diff --git a/.gitignore b/.gitignore index 259148f..26c9709 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,18 @@ -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app +*.bat +*.log +*.lnk +**/msvc/Debug* +**/msvc/Release* +**/msvc/Tests +**/msvc/*.sdf +**/msvc/*.opensdf +**/msvc/*.user +**/msvc/*.suo +**/msvc/*.db +**/msvc/*.opendb +**/msvc/*.txt +**/msvc/*.amplxeproj +**/msvc/.vs +**/msvc/ipch +**/msvc/PublishPath*.ini +publish diff --git a/README.md b/README.md index 3f0b415..7cb4dd4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,52 @@ -# hitboxtracker -Demonstrate position hitboxes calculated by server on client-side +# Description +Dev-tool that demonstrates on client-side true position of the hitboxes calculated by server + +# Installation +* Install `hitboxtracker_mm.dll` on your HLDS as metamod plugin and put `delta.lst` to gamedir directory `cstrike/delta.lst` +* Put `hitboxtracker.dll` and `cs.exe` to working directory of the game CS 1.6 client +* Run `cs.exe` + +# Requirements +* For `Client`: build 4554 and later +* For `HLDS`: Metamod 1.20 and later + +# Configuring + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
r_drawentitiesDescription
0No entities
1Default and draws entities normally
2Entities draws as skeletons
3Entities draws hitboxes
4Entities draws with translucent hitboxes and the model beneath the hitboxes
5Individual box for player and weapon
6Same as 4 but draws true position of the hitboxes calculated by server :new:
+ +# Preview +![r_drawentities-preview](https://user-images.githubusercontent.com/5860435/34445881-52d2096a-ed09-11e7-90ad-78cfb38f3f40.gif) diff --git a/dep/ISysModule.h b/dep/ISysModule.h new file mode 100644 index 0000000..f2ad44a --- /dev/null +++ b/dep/ISysModule.h @@ -0,0 +1,37 @@ +#pragma once + +#define PSAPI_VERSION 1 +#include + +using module_handle_t = HINSTANCE; +using byteptr_t = uint8_t *; + +enum OpCodes : int8_t +{ + OP_ANY = '\x2A', + OP_PUSH = '\x68', + OP_JUMP = '\xE9', + OP_CALL = '\xE8', +}; + +class ISysModule +{ +public: + virtual ~ISysModule() {} + virtual bool Init(const char *szModuleName, const char *pszFile = nullptr) = 0; + + virtual module_handle_t load(void *addr) = 0; + virtual module_handle_t load(const char *filename) = 0; + + virtual void Printf(const char *fmt, ...) = 0; + virtual void TraceLog(const char *fmt, ...) = 0; + + virtual byteptr_t getsym(const char *name) const = 0; + virtual module_handle_t gethandle() const = 0; + virtual byteptr_t getbase() const = 0; + virtual size_t getsize() const = 0; + virtual bool is_opened() const = 0; + + virtual byteptr_t find_string(const char *string, int8_t opcode = OP_ANY) const = 0; + virtual byteptr_t find_pattern(byteptr_t pStart, size_t range, const char *pattern) const = 0; +}; diff --git a/dep/hlsdk/common/BaseSystemModule.cpp b/dep/hlsdk/common/BaseSystemModule.cpp new file mode 100644 index 0000000..3233b54 --- /dev/null +++ b/dep/hlsdk/common/BaseSystemModule.cpp @@ -0,0 +1,164 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +BaseSystemModule::BaseSystemModule() +{ + m_System = nullptr; + m_Serial = 0; + m_SystemTime = 0; + m_State = MODULE_UNDEFINED; + + Q_memset(m_Name, 0, sizeof(m_Name)); +} + +char *BaseSystemModule::GetName() +{ + return m_Name; +} + +char *BaseSystemModule::GetType() +{ + return "GenericModule"; +} + +char *BaseSystemModule::GetStatusLine() +{ + return "No status available.\n"; +} + +void BaseSystemModule::ExecuteCommand(int commandID, char *commandLine) +{ + m_System->DPrintf("WARNING! Undeclared ExecuteCommand().\n"); +} + +extern int COM_BuildNumber(); + +int BaseSystemModule::GetVersion() +{ + return COM_BuildNumber(); +} + +int BaseSystemModule::GetSerial() +{ + return m_Serial; +} + +IBaseSystem *BaseSystemModule::GetSystem() +{ + return m_System; +} + +bool BaseSystemModule::Init(IBaseSystem *system, int serial, char *name) +{ + if (!system) + return false; + + m_State = MODULE_INITIALIZING; + m_System = system; + m_Serial = serial; + m_SystemTime = 0; + + if (name) { + Q_strlcpy(m_Name, name); + } + + return true; +} + +void BaseSystemModule::RunFrame(double time) +{ + m_SystemTime = time; +} + +void BaseSystemModule::ShutDown() +{ + if (m_State == MODULE_DISCONNECTED) + return; + + m_Listener.Clear(); + m_State = MODULE_DISCONNECTED; + + if (!m_System->RemoveModule(this)) + { + m_System->DPrintf("ERROR! BaseSystemModule::ShutDown: faild to remove module %s.\n", m_Name); + } +} + +void BaseSystemModule::RegisterListener(ISystemModule *module) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + if (listener->GetSerial() == module->GetSerial()) + { + m_System->DPrintf("WARNING! BaseSystemModule::RegisterListener: module %s already added.\n", module->GetName()); + return; + } + + listener = (ISystemModule *)m_Listener.GetNext(); + } + + m_Listener.Add(module); +} + +void BaseSystemModule::RemoveListener(ISystemModule *module) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + if (listener->GetSerial() == module->GetSerial()) + { + m_Listener.Remove(module); + return; + } + + listener = (ISystemModule *)m_Listener.GetNext(); + } +} + +void BaseSystemModule::FireSignal(unsigned int signal, void *data) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + listener->ReceiveSignal(this, signal, data); + listener = (ISystemModule *)m_Listener.GetNext(); + } +} + +void BaseSystemModule::ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) +{ + m_System->DPrintf("WARNING! Unhandled signal (%i) from module %s.\n", signal, module->GetName()); +} + +int BaseSystemModule::GetState() +{ + return m_State; +} diff --git a/dep/hlsdk/common/BaseSystemModule.h b/dep/hlsdk/common/BaseSystemModule.h new file mode 100644 index 0000000..f4998b4 --- /dev/null +++ b/dep/hlsdk/common/BaseSystemModule.h @@ -0,0 +1,75 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ObjectList.h" +#include "IBaseSystem.h" + +// C4250 - 'class1' : inherits 'BaseSystemModule::member' via dominance +#pragma warning(disable:4250) + +class BaseSystemModule: virtual public ISystemModule { +public: + BaseSystemModule(); + virtual ~BaseSystemModule() {} + + EXT_FUNC virtual bool Init(IBaseSystem *system, int serial, char *name); + EXT_FUNC virtual void RunFrame(double time); + EXT_FUNC virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data); + EXT_FUNC virtual void ExecuteCommand(int commandID, char *commandLine); + EXT_FUNC virtual void RegisterListener(ISystemModule *module); + EXT_FUNC virtual void RemoveListener(ISystemModule *module); + EXT_FUNC virtual IBaseSystem *GetSystem(); + EXT_FUNC virtual int GetSerial(); + EXT_FUNC virtual char *GetStatusLine(); + EXT_FUNC virtual char *GetType(); + EXT_FUNC virtual char *GetName(); + + enum ModuleState { + MODULE_UNDEFINED = 0, + MODULE_INITIALIZING, + MODULE_CONNECTING, + MODULE_RUNNING, + MODULE_DISCONNECTED + }; + + EXT_FUNC virtual int GetState(); + EXT_FUNC virtual int GetVersion(); + EXT_FUNC virtual void ShutDown(); + EXT_FUNC virtual char *GetBaseDir() { return ""; } + void FireSignal(unsigned int signal, void *data = nullptr); + +protected: + IBaseSystem *m_System; + ObjectList m_Listener; + char m_Name[255]; + unsigned int m_State; + unsigned int m_Serial; + double m_SystemTime; +}; diff --git a/dep/hlsdk/common/IAdminServer.h b/dep/hlsdk/common/IAdminServer.h new file mode 100644 index 0000000..ab367ce --- /dev/null +++ b/dep/hlsdk/common/IAdminServer.h @@ -0,0 +1,54 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +// handle to a game window +typedef unsigned int ManageServerUIHandle_t; +class IManageServer; + +// Purpose: Interface to server administration functions +class IAdminServer: public IBaseInterface +{ +public: + // opens a manage server dialog for a local server + virtual ManageServerUIHandle_t OpenManageServerDialog(const char *serverName, const char *gameDir) = 0; + + // opens a manage server dialog to a remote server + virtual ManageServerUIHandle_t OpenManageServerDialog(unsigned int gameIP, unsigned int gamePort, const char *password) = 0; + + // forces the game info dialog closed + virtual void CloseManageServerDialog(ManageServerUIHandle_t gameDialog) = 0; + + // Gets a handle to the interface + virtual IManageServer *GetManageServerInterface(ManageServerUIHandle_t handle) = 0; +}; + +#define ADMINSERVER_INTERFACE_VERSION "AdminServer002" diff --git a/dep/hlsdk/common/IBaseSystem.h b/dep/hlsdk/common/IBaseSystem.h new file mode 100644 index 0000000..9f50fe3 --- /dev/null +++ b/dep/hlsdk/common/IBaseSystem.h @@ -0,0 +1,91 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#if defined(_WIN32) + #define LIBRARY_PREFIX "dll" +#elif defined(OSX) + #define LIBRARY_PREFIX "dylib" +#else + #define LIBRARY_PREFIX "so" +#endif + +#include "ISystemModule.h" +#include "IVGuiModule.h" + +class Panel; +class ObjectList; +class IFileSystem; + +class IBaseSystem: virtual public ISystemModule { +public: + virtual ~IBaseSystem() {} + + virtual double GetTime() = 0; + virtual unsigned int GetTick() = 0; + virtual void SetFPS(float fps) = 0; + + virtual void Printf(char *fmt, ...) = 0; + virtual void DPrintf(char *fmt, ...) = 0; + + virtual void RedirectOutput(char *buffer = nullptr, int maxSize = 0) = 0; + + virtual IFileSystem *GetFileSystem() = 0; + virtual unsigned char *LoadFile(const char *name, int *length = nullptr) = 0; + virtual void FreeFile(unsigned char *fileHandle) = 0; + + virtual void SetTitle(char *text) = 0; + virtual void SetStatusLine(char *text) = 0; + + virtual void ShowConsole(bool visible) = 0; + virtual void LogConsole(char *filename) = 0; + + virtual bool InitVGUI(IVGuiModule *module) = 0; + +#ifdef _WIN32 + virtual Panel *GetPanel() = 0; +#endif // _WIN32 + + virtual bool RegisterCommand(char *name, ISystemModule *module, int commandID) = 0; + virtual void GetCommandMatches(char *string, ObjectList *pMatchList) = 0; + virtual void ExecuteString(char *commands) = 0; + virtual void ExecuteFile(char *filename) = 0; + virtual void Errorf(char *fmt, ...) = 0; + + virtual char *CheckParam(char *param) = 0; + + virtual bool AddModule(ISystemModule *module, char *name) = 0; + virtual ISystemModule *GetModule(char *interfacename, char *library, char *instancename = nullptr) = 0; + virtual bool RemoveModule(ISystemModule *module) = 0; + + virtual void Stop() = 0; + virtual char *GetBaseDir() = 0; +}; + +#define BASESYSTEM_INTERFACE_VERSION "basesystem002" diff --git a/dep/hlsdk/common/IDemoPlayer.h b/dep/hlsdk/common/IDemoPlayer.h new file mode 100644 index 0000000..2431b54 --- /dev/null +++ b/dep/hlsdk/common/IDemoPlayer.h @@ -0,0 +1,93 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ref_params.h" + +class IWorld; +class IProxy; +class DirectorCmd; +class IBaseSystem; +class ISystemModule; +class IObjectContainer; + +class IDemoPlayer { +public: + virtual ~IDemoPlayer() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual void NewGame(IWorld *world, IProxy *proxy = nullptr) = 0; + virtual char *GetModName() = 0; + virtual void WriteCommands(BitBuffer *stream, float startTime, float endTime) = 0; + virtual int AddCommand(DirectorCmd *cmd) = 0; + virtual bool RemoveCommand(int index) = 0; + virtual DirectorCmd *GetLastCommand() = 0; + virtual IObjectContainer *GetCommands() = 0; + virtual void SetWorldTime(double time, bool relative) = 0; + virtual void SetTimeScale(float scale) = 0; + virtual void SetPaused(bool state) = 0; + virtual void SetEditMode(bool state) = 0; + virtual void SetMasterMode(bool state) = 0; + virtual bool IsPaused() = 0; + virtual bool IsLoading() = 0; + virtual bool IsActive() = 0; + virtual bool IsEditMode() = 0; + virtual bool IsMasterMode() = 0; + virtual void RemoveFrames(double starttime, double endtime) = 0; + virtual void ExecuteDirectorCmd(DirectorCmd *cmd) = 0; + virtual double GetWorldTime() = 0; + virtual double GetStartTime() = 0; + virtual double GetEndTime() = 0; + virtual float GetTimeScale() = 0; + virtual IWorld *GetWorld() = 0; + virtual char *GetFileName() = 0; + virtual bool SaveGame(char *filename) = 0; + virtual bool LoadGame(char *filename) = 0; + virtual void Stop() = 0; + virtual void ForceHLTV(bool state) = 0; + virtual void GetDemoViewInfo(ref_params_t *rp, float *view, int *viewmodel) = 0; + virtual int ReadDemoMessage(unsigned char *buffer, int size) = 0; + virtual void ReadNetchanState(int *incoming_sequence, int *incoming_acknowledged, int *incoming_reliable_acknowledged, int *incoming_reliable_sequence, int *outgoing_sequence, int *reliable_sequence, int *last_reliable_sequence) = 0; +}; + +#define DEMOPLAYER_INTERFACE_VERSION "demoplayer001" diff --git a/dep/hlsdk/common/IEngineWrapper.h b/dep/hlsdk/common/IEngineWrapper.h new file mode 100644 index 0000000..0a58d4c --- /dev/null +++ b/dep/hlsdk/common/IEngineWrapper.h @@ -0,0 +1,56 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "event_args.h" +#include "vmodes.h" +#include "cdll_int.h" + +class IBaseSystem; +class ISystemModule; + +class IEngineWrapper: virtual public ISystemModule { +public: + virtual ~IEngineWrapper() {} + + virtual bool GetViewOrigin(float *origin) = 0; + virtual bool GetViewAngles(float *angles) = 0; + virtual int GetTraceEntity() = 0; + virtual float GetCvarFloat(char *szName) = 0; + virtual char *GetCvarString(char *szName) = 0; + virtual void SetCvar(char *szName, char *szValue) = 0; + virtual void Cbuf_AddText(char *text) = 0; + virtual void DemoUpdateClientData(client_data_t *cdat) = 0; + virtual void CL_QueueEvent(int flags, int index, float delay, event_args_t *pargs) = 0; + virtual void HudWeaponAnim(int iAnim, int body) = 0; + virtual void CL_DemoPlaySound(int channel, char *sample, float attenuation, float volume, int flags, int pitch) = 0; + virtual void ClientDLL_ReadDemoBuffer(int size, unsigned char *buffer) = 0; +}; + +#define ENGINEWRAPPER_INTERFACE_VERSION "enginewrapper001" diff --git a/dep/hlsdk/common/IGameServerData.h b/dep/hlsdk/common/IGameServerData.h new file mode 100644 index 0000000..d431f00 --- /dev/null +++ b/dep/hlsdk/common/IGameServerData.h @@ -0,0 +1,15 @@ +#pragma once + +#include "maintypes.h" +#include "interface.h" + +class IGameServerData : public IBaseInterface { +public: + virtual ~IGameServerData() { }; + + virtual void WriteDataRequest(const void *buffer, int bufferSize) = 0; + + virtual int ReadDataResponse(void *data, int len) = 0; +}; + +#define GAMESERVERDATA_INTERFACE_VERSION "GameServerData001" diff --git a/dep/hlsdk/common/IObjectContainer.h b/dep/hlsdk/common/IObjectContainer.h new file mode 100644 index 0000000..333e9d0 --- /dev/null +++ b/dep/hlsdk/common/IObjectContainer.h @@ -0,0 +1,47 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IObjectContainer { +public: + virtual ~IObjectContainer() {} + + virtual void Init() = 0; + + virtual bool Add(void *newObject) = 0; + virtual bool Remove(void *object) = 0; + virtual void Clear(bool freeElementsMemory) = 0; + + virtual void *GetFirst() = 0; + virtual void *GetNext() = 0; + + virtual int CountElements() = 0; + virtual bool Contains(void *object) = 0; + virtual bool IsEmpty() = 0; +}; diff --git a/dep/hlsdk/common/ISystemModule.h b/dep/hlsdk/common/ISystemModule.h new file mode 100644 index 0000000..9004a95 --- /dev/null +++ b/dep/hlsdk/common/ISystemModule.h @@ -0,0 +1,57 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +class IBaseSystem; +class ISystemModule; + +class ISystemModule: public IBaseInterface { +public: + virtual ~ISystemModule() {} + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data = nullptr) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + + virtual IBaseSystem *GetSystem() = 0; + + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; +}; diff --git a/dep/hlsdk/common/IVGuiModule.h b/dep/hlsdk/common/IVGuiModule.h new file mode 100644 index 0000000..e6864c8 --- /dev/null +++ b/dep/hlsdk/common/IVGuiModule.h @@ -0,0 +1,76 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include +#include "interface.h" + +// Purpose: Standard interface to loading vgui modules +class IVGuiModule: public IBaseInterface +{ +public: + // called first to setup the module with the vgui + // returns true on success, false on failure + virtual bool Initialize(CreateInterfaceFn *vguiFactories, int factoryCount) = 0; + + // called after all the modules have been initialized + // modules should use this time to link to all the other module interfaces + virtual bool PostInitialize(CreateInterfaceFn *modules = nullptr, int factoryCount = 0) = 0; + + // called when the module is selected from the menu or otherwise activated + virtual bool Activate() = 0; + + // returns true if the module is successfully initialized and available + virtual bool IsValid() = 0; + + // requests that the UI is temporarily disabled and all data files saved + virtual void Deactivate() = 0; + + // restart from a Deactivate() + virtual void Reactivate() = 0; + + // called when the module is about to be shutdown + virtual void Shutdown() = 0; + + // returns a handle to the main module panel + virtual vgui2::VPANEL GetPanel() = 0; + + // sets the parent of the main module panel + virtual void SetParent(vgui2::VPANEL parent) = 0; + + // messages sent through through the panel returned by GetPanel(): + // + // "ConnectedToGame" "ip" "port" "gamedir" + // "DisconnectedFromGame" + // "ActiveGameName" "name" + // "LoadingStarted" "type" "name" + // "LoadingFinished" "type" "name" +}; + +#define VGUIMODULE_INTERFACE_VERSION "VGuiModuleAdminServer001" diff --git a/dep/hlsdk/common/ObjectDictionary.cpp b/dep/hlsdk/common/ObjectDictionary.cpp new file mode 100644 index 0000000..84a0f88 --- /dev/null +++ b/dep/hlsdk/common/ObjectDictionary.cpp @@ -0,0 +1,515 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +ObjectDictionary::ObjectDictionary() +{ + m_currentEntry = 0; + m_findKey = 0; + m_entries = nullptr; + + Q_memset(m_cache, 0, sizeof(m_cache)); + + m_cacheIndex = 0; + m_size = 0; + m_maxSize = 0; +} + +ObjectDictionary::~ObjectDictionary() +{ + if (m_entries) { + Mem_Free(m_entries); + } +} + +void ObjectDictionary::Clear(bool freeObjectssMemory) +{ + if (freeObjectssMemory) + { + for (int i = 0; i < m_size; i++) + { + void *obj = m_entries[i].object; + if (obj) { + Mem_Free(obj); + } + } + } + + m_size = 0; + CheckSize(); + ClearCache(); +} + +bool ObjectDictionary::Add(void *object, float key) +{ + if (m_size == m_maxSize && !CheckSize()) + return false; + + entry_t *p; + if (m_size && key < m_entries[m_size - 1].key) + { + p = &m_entries[FindClosestAsIndex(key)]; + + entry_t *e1 = &m_entries[m_size]; + entry_t *e2 = &m_entries[m_size - 1]; + + while (p->key <= key) { p++; } + while (p != e1) + { + e1->object = e2->object; + e1->key = e2->key; + + e1--; + e2--; + } + } + else + p = &m_entries[m_size]; + + p->key = key; + p->object = object; + m_size++; + + ClearCache(); + AddToCache(p); + + return true; +} + +int ObjectDictionary::FindClosestAsIndex(float key) +{ + if (m_size <= 0) + return -1; + + if (key <= m_entries->key) + return 0; + + int index = FindKeyInCache(key); + if (index >= 0) { + return index; + } + + int middle; + int first = 0; + int last = m_size - 1; + float keyMiddle, keyNext; + + if (key < m_entries[last].key) + { + while (true) + { + middle = (last + first) >> 1; + keyMiddle = m_entries[middle].key; + + if (keyMiddle == key) + break; + + if (keyMiddle < key) + { + if (m_entries[middle + 1].key >= key) + { + if (m_entries[middle + 1].key - key < key - keyMiddle) + ++middle; + break; + } + + first = (last + first) >> 1; + } + else + { + last = (last + first) >> 1; + } + } + } + else + { + middle = last; + } + + keyNext = m_entries[middle - 1].key; + while (keyNext == key) { + keyNext = m_entries[middle--].key; + } + + AddToCache(&m_entries[middle], key); + return middle; +} + +void ObjectDictionary::ClearCache() +{ + Q_memset(m_cache, 0, sizeof(m_cache)); + m_cacheIndex = 0; +} + +bool ObjectDictionary::RemoveIndex(int index, bool freeObjectMemory) +{ + if (index < 0 || index >= m_size) + return false; + + entry_t *p = &m_entries[m_size - 1]; + entry_t *e1 = &m_entries[index]; + entry_t *e2 = &m_entries[index + 1]; + + if (freeObjectMemory && e1->object) + Mem_Free(e1->object); + + while (p != e1) + { + e1->object = e2->object; + e1->key = e2->key; + + e1++; + e2++; + } + + p->object = nullptr; + p->key = 0; + m_size--; + + CheckSize(); + ClearCache(); + + return false; +} + +bool ObjectDictionary::RemoveIndexRange(int minIndex, int maxIndex) +{ + if (minIndex > maxIndex) + { + if (maxIndex < 0) + maxIndex = 0; + + if (minIndex >= m_size) + minIndex = m_size - 1; + } + else + { + if (minIndex < 0) + minIndex = 0; + + if (maxIndex >= m_size) + maxIndex = m_size - 1; + } + + int offset = minIndex + maxIndex - 1; + m_size -= offset; + CheckSize(); + return true; +} + +bool ObjectDictionary::Remove(void *object) +{ + bool found = false; + for (int i = 0; i < m_size; i++) + { + if (m_entries[i].object == object) { + RemoveIndex(i); + found = true; + } + } + + return found ? true : false; +} + +bool ObjectDictionary::RemoveSingle(void *object) +{ + for (int i = 0; i < m_size; i++) + { + if (m_entries[i].object == object) { + RemoveIndex(i); + return true; + } + } + + return false; +} + +bool ObjectDictionary::RemoveKey(float key) +{ + int i = FindClosestAsIndex(key); + if (m_entries[i].key == key) + { + int j = i; + do { + ++j; + } + while (key == m_entries[j + 1].key); + + return RemoveIndexRange(i, j); + } + + return false; +} + +bool ObjectDictionary::CheckSize() +{ + int newSize = m_maxSize; + if (m_size == m_maxSize) + { + newSize = 1 - (int)(m_maxSize * -1.25f); + } + else if (m_maxSize * 0.5f > m_size) + { + newSize = (int)(m_maxSize * 0.75f); + } + + if (newSize != m_maxSize) + { + entry_t *newEntries = (entry_t *)Mem_Malloc(sizeof(entry_t) * newSize); + if (!newEntries) + return false; + + Q_memset(&newEntries[m_size], 0, sizeof(entry_t) * (newSize - m_size)); + + if (m_entries && m_size) + { + Q_memcpy(newEntries, m_entries, sizeof(entry_t) * m_size); + Mem_Free(m_entries); + } + + m_entries = newEntries; + m_maxSize = newSize; + } + + return true; +} + +void ObjectDictionary::Init() +{ + m_size = 0; + m_maxSize = 0; + m_entries = nullptr; + + CheckSize(); + ClearCache(); +} + +void ObjectDictionary::Init(int baseSize) +{ + m_size = 0; + m_maxSize = 0; + m_entries = (entry_t *)Mem_ZeroMalloc(sizeof(entry_t) * baseSize); + + if (m_entries) { + m_maxSize = baseSize; + } +} + +bool ObjectDictionary::Add(void *object) +{ + return Add(object, 0); +} + +int ObjectDictionary::CountElements() +{ + return m_size; +} + +bool ObjectDictionary::IsEmpty() +{ + return (m_size == 0) ? true : false; +} + +bool ObjectDictionary::Contains(void *object) +{ + if (FindObjectInCache(object) >= 0) + return true; + + for (int i = 0; i < m_size; i++) + { + entry_t *e = &m_entries[i]; + if (e->object == object) { + AddToCache(e); + return true; + } + } + + return false; +} + +void *ObjectDictionary::GetFirst() +{ + m_currentEntry = 0; + return GetNext(); +} + +void *ObjectDictionary::GetLast() +{ + return (m_size > 0) ? m_entries[m_size - 1].object : nullptr; +} + +bool ObjectDictionary::ChangeKey(void *object, float newKey) +{ + int pos = FindObjectInCache(object); + if (pos < 0) + { + for (pos = 0; pos < m_size; pos++) + { + if (m_entries[pos].object == object) { + AddToCache(&m_entries[pos]); + break; + } + } + + if (pos == m_size) { + return false; + } + } + + entry_t *p, *e; + + p = &m_entries[pos]; + if (p->key == newKey) + return false; + + int newpos = FindClosestAsIndex(newKey); + e = &m_entries[newpos]; + if (pos < newpos) + { + if (e->key > newKey) + e--; + + entry_t *e2 = &m_entries[pos + 1]; + while (p < e) + { + p->object = e2->object; + p->key = e2->key; + + p++; + e2++; + } + } + else if (pos > newpos) + { + if (e->key > newKey) + e++; + + entry_t *e2 = &m_entries[pos - 1]; + while (p > e) + { + p->object = e2->object; + p->key = e2->key; + + p--; + e2--; + } + } + + p->object = object; + p->key = newKey; + ClearCache(); + + return true; +} + +bool ObjectDictionary::UnsafeChangeKey(void *object, float newKey) +{ + int pos = FindObjectInCache(object); + if (pos < 0) + { + for (pos = 0; pos < m_size; pos++) + { + if (m_entries[pos].object == object) { + break; + } + } + + if (pos == m_size) { + return false; + } + } + + m_entries[pos].key = newKey; + ClearCache(); + return true; +} + +void ObjectDictionary::AddToCache(entry_t *entry) +{ + int i = (m_cacheIndex % MAX_OBJECT_CACHE); + + m_cache[i].object = entry; + m_cache[i].key = entry->key; + m_cacheIndex++; +} + +void ObjectDictionary::AddToCache(entry_t *entry, float key) +{ + int i = (m_cacheIndex % MAX_OBJECT_CACHE); + + m_cache[i].object = entry; + m_cache[i].key = key; + m_cacheIndex++; +} + +int ObjectDictionary::FindKeyInCache(float key) +{ + for (auto& ch : m_cache) + { + if (ch.object && ch.key == key) { + return (entry_t *)ch.object - m_entries; + } + } + + return -1; +} + +int ObjectDictionary::FindObjectInCache(void *object) +{ + for (auto& ch : m_cache) + { + if (ch.object && ch.object == object) { + return (entry_t *)ch.object - m_entries; + } + } + + return -1; +} + +void *ObjectDictionary::FindClosestKey(float key) +{ + m_currentEntry = FindClosestAsIndex(key); + return GetNext(); +} + +void *ObjectDictionary::GetNext() +{ + if (m_currentEntry < 0 || m_currentEntry >= m_size) + return nullptr; + + return m_entries[m_currentEntry++].object; +} + +void *ObjectDictionary::FindExactKey(float key) +{ + if ((m_currentEntry = FindClosestAsIndex(key)) < 0) + return nullptr; + + return (m_entries[m_currentEntry].key == key) ? GetNext() : nullptr; +} diff --git a/dep/hlsdk/common/ObjectDictionary.h b/dep/hlsdk/common/ObjectDictionary.h new file mode 100644 index 0000000..bf1b77f --- /dev/null +++ b/dep/hlsdk/common/ObjectDictionary.h @@ -0,0 +1,94 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IObjectContainer.h" + +class ObjectDictionary: public IObjectContainer { +public: + ObjectDictionary(); + virtual ~ObjectDictionary(); + + void Init(); + void Init(int baseSize); + + bool Add(void *object); + bool Contains(void *object); + bool IsEmpty(); + int CountElements(); + + void Clear(bool freeObjectssMemory = false); + + bool Add(void *object, float key); + bool ChangeKey(void *object, float newKey); + bool UnsafeChangeKey(void *object, float newKey); + + bool Remove(void *object); + bool RemoveSingle(void *object); + bool RemoveKey(float key); + bool RemoveRange(float startKey, float endKey); + + void *FindClosestKey(float key); + void *FindExactKey(float key); + + void *GetFirst(); + void *GetLast(); + void *GetNext(); + + int FindKeyInCache(float key); + int FindObjectInCache(void *object); + + void ClearCache(); + bool CheckSize(); + + typedef struct entry_s { + void *object; + float key; + } entry_t; + + void AddToCache(entry_t *entry); + void AddToCache(entry_t *entry, float key); + + bool RemoveIndex(int index, bool freeObjectMemory = false); + bool RemoveIndexRange(int minIndex, int maxIndex); + int FindClosestAsIndex(float key); + +protected: + int m_currentEntry; + float m_findKey; + + enum { MAX_OBJECT_CACHE = 32 }; + + entry_t *m_entries; + entry_t m_cache[MAX_OBJECT_CACHE]; + + int m_cacheIndex; + int m_size; + int m_maxSize; +}; diff --git a/dep/hlsdk/common/ObjectList.cpp b/dep/hlsdk/common/ObjectList.cpp new file mode 100644 index 0000000..4518090 --- /dev/null +++ b/dep/hlsdk/common/ObjectList.cpp @@ -0,0 +1,259 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +ObjectList::ObjectList() +{ + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +ObjectList::~ObjectList() +{ + Clear(false); +} + +bool ObjectList::AddHead(void *newObject) +{ + // create new element + element_t *newElement = (element_t *)Mem_ZeroMalloc(sizeof(element_t)); + + // out of memory + if (!newElement) + return false; + + // insert element + newElement->object = newObject; + + if (m_head) + { + newElement->next = m_head; + m_head->prev = newElement; + } + + m_head = newElement; + + // if list was empty set new m_tail + if (!m_tail) + m_tail = m_head; + + m_number++; + return true; +} + +void *ObjectList::RemoveHead() +{ + void *retObj; + + // check m_head is present + if (m_head) + { + retObj = m_head->object; + element_t *newHead = m_head->next; + if (newHead) + newHead->prev = nullptr; + + // if only one element is in list also update m_tail + // if we remove this prev element + if (m_tail == m_head) + m_tail = nullptr; + + Mem_Free(m_head); + m_head = newHead; + + m_number--; + } + else + retObj = nullptr; + + return retObj; +} + +bool ObjectList::AddTail(void *newObject) +{ + // create new element + element_t *newElement = (element_t *)Mem_ZeroMalloc(sizeof(element_t)); + + // out of memory + if (!newElement) + return false; + + // insert element + newElement->object = newObject; + + if (m_tail) + { + newElement->prev = m_tail; + m_tail->next = newElement; + } + + m_tail = newElement; + + // if list was empty set new m_tail + if (!m_head) + m_head = m_tail; + + m_number++; + return true; +} + +void *ObjectList::RemoveTail() +{ + void *retObj; + + // check m_tail is present + if (m_tail) + { + retObj = m_tail->object; + element_t *newTail = m_tail->prev; + if (newTail) + newTail->next = nullptr; + + // if only one element is in list also update m_tail + // if we remove this prev element + if (m_head == m_tail) + m_head = nullptr; + + Mem_Free(m_tail); + m_tail = newTail; + + m_number--; + + } + else + retObj = nullptr; + + return retObj; +} + +bool ObjectList::IsEmpty() +{ + return (m_head == nullptr); +} + +int ObjectList::CountElements() +{ + return m_number; +} + +bool ObjectList::Contains(void *object) +{ + element_t *e = m_head; + + while (e && e->object != object) { e = e->next; } + + if (e) + { + m_current = e; + return true; + } + else + { + return false; + } +} + +void ObjectList::Clear(bool freeElementsMemory) +{ + element_t *ne; + element_t *e = m_head; + + while (e) + { + ne = e->next; + + if (freeElementsMemory && e->object) + Mem_Free(e->object); + + Mem_Free(e); + e = ne; + } + + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +bool ObjectList::Remove(void *object) +{ + element_t *e = m_head; + + while (e && e->object != object) { e = e->next; } + + if (e) + { + if (e->prev) e->prev->next = e->next; + if (e->next) e->next->prev = e->prev; + + if (m_head == e) m_head = e->next; + if (m_tail == e) m_tail = e->prev; + if (m_current == e) m_current= e->next; + + Mem_Free(e); + m_number--; + } + + return (e != nullptr); +} + +void ObjectList::Init() +{ + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +void *ObjectList::GetFirst() +{ + if (m_head) + { + m_current = m_head->next; + return m_head->object; + } + else + { + m_current = nullptr; + return nullptr; + } +} + +void *ObjectList::GetNext() +{ + void *retObj = nullptr; + if (m_current) + { + retObj = m_current->object; + m_current = m_current->next; + } + + return retObj; +} + +bool ObjectList::Add(void *newObject) +{ + return AddTail(newObject); +} diff --git a/dep/hlsdk/common/ObjectList.h b/dep/hlsdk/common/ObjectList.h new file mode 100644 index 0000000..aa023f8 --- /dev/null +++ b/dep/hlsdk/common/ObjectList.h @@ -0,0 +1,65 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IObjectContainer.h" + +class ObjectList: public IObjectContainer { +public: + EXT_FUNC void Init(); + EXT_FUNC bool Add(void *newObject); + EXT_FUNC void *GetFirst(); + EXT_FUNC void *GetNext(); + + ObjectList(); + virtual ~ObjectList(); + + EXT_FUNC void Clear(bool freeElementsMemory = false); + EXT_FUNC int CountElements(); + void *RemoveTail(); + void *RemoveHead(); + + bool AddTail(void *newObject); + bool AddHead(void *newObject); + EXT_FUNC bool Remove(void *object); + EXT_FUNC bool Contains(void *object); + EXT_FUNC bool IsEmpty(); + + typedef struct element_s { + struct element_s *prev; // pointer to the last element or NULL + struct element_s *next; // pointer to the next elemnet or NULL + void *object; // the element's object + } element_t; + +protected: + element_t *m_head; // first element in list + element_t *m_tail; // last element in list + element_t *m_current; // current element in list + int m_number; +}; diff --git a/dep/hlsdk/common/Sequence.h b/dep/hlsdk/common/Sequence.h new file mode 100644 index 0000000..8df553d --- /dev/null +++ b/dep/hlsdk/common/Sequence.h @@ -0,0 +1,201 @@ +//--------------------------------------------------------------------------- +// +// S c r i p t e d S e q u e n c e s +// +//--------------------------------------------------------------------------- +#ifndef _INCLUDE_SEQUENCE_H_ +#define _INCLUDE_SEQUENCE_H_ + + +#ifndef _DEF_BYTE_ +typedef unsigned char byte; +#endif + +//--------------------------------------------------------------------------- +// client_textmessage_t +//--------------------------------------------------------------------------- +typedef struct client_textmessage_s +{ + int effect; + byte r1, g1, b1, a1; // 2 colors for effects + byte r2, g2, b2, a2; + float x; + float y; + float fadein; + float fadeout; + float holdtime; + float fxtime; + const char *pName; + const char *pMessage; +} client_textmessage_t; + + +//-------------------------------------------------------------------------- +// sequenceDefaultBits_e +// +// Enumerated list of possible modifiers for a command. This enumeration +// is used in a bitarray controlling what modifiers are specified for a command. +//--------------------------------------------------------------------------- +enum sequenceModifierBits +{ + SEQUENCE_MODIFIER_EFFECT_BIT = (1 << 1), + SEQUENCE_MODIFIER_POSITION_BIT = (1 << 2), + SEQUENCE_MODIFIER_COLOR_BIT = (1 << 3), + SEQUENCE_MODIFIER_COLOR2_BIT = (1 << 4), + SEQUENCE_MODIFIER_FADEIN_BIT = (1 << 5), + SEQUENCE_MODIFIER_FADEOUT_BIT = (1 << 6), + SEQUENCE_MODIFIER_HOLDTIME_BIT = (1 << 7), + SEQUENCE_MODIFIER_FXTIME_BIT = (1 << 8), + SEQUENCE_MODIFIER_SPEAKER_BIT = (1 << 9), + SEQUENCE_MODIFIER_LISTENER_BIT = (1 << 10), + SEQUENCE_MODIFIER_TEXTCHANNEL_BIT = (1 << 11), +}; +typedef enum sequenceModifierBits sequenceModifierBits_e ; + + +//--------------------------------------------------------------------------- +// sequenceCommandEnum_e +// +// Enumerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandEnum_ +{ + SEQUENCE_COMMAND_ERROR = -1, + SEQUENCE_COMMAND_PAUSE = 0, + SEQUENCE_COMMAND_FIRETARGETS, + SEQUENCE_COMMAND_KILLTARGETS, + SEQUENCE_COMMAND_TEXT, + SEQUENCE_COMMAND_SOUND, + SEQUENCE_COMMAND_GOSUB, + SEQUENCE_COMMAND_SENTENCE, + SEQUENCE_COMMAND_REPEAT, + SEQUENCE_COMMAND_SETDEFAULTS, + SEQUENCE_COMMAND_MODIFIER, + SEQUENCE_COMMAND_POSTMODIFIER, + SEQUENCE_COMMAND_NOOP, + + SEQUENCE_MODIFIER_EFFECT, + SEQUENCE_MODIFIER_POSITION, + SEQUENCE_MODIFIER_COLOR, + SEQUENCE_MODIFIER_COLOR2, + SEQUENCE_MODIFIER_FADEIN, + SEQUENCE_MODIFIER_FADEOUT, + SEQUENCE_MODIFIER_HOLDTIME, + SEQUENCE_MODIFIER_FXTIME, + SEQUENCE_MODIFIER_SPEAKER, + SEQUENCE_MODIFIER_LISTENER, + SEQUENCE_MODIFIER_TEXTCHANNEL, +}; +typedef enum sequenceCommandEnum_ sequenceCommandEnum_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandType_e +// +// Typeerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandType_ +{ + SEQUENCE_TYPE_COMMAND, + SEQUENCE_TYPE_MODIFIER, +}; +typedef enum sequenceCommandType_ sequenceCommandType_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandMapping_s +// +// A mapping of a command enumerated-value to its name. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandMapping_ sequenceCommandMapping_s; +struct sequenceCommandMapping_ +{ + sequenceCommandEnum_e commandEnum; + const char* commandName; + sequenceCommandType_e commandType; +}; + + +//--------------------------------------------------------------------------- +// sequenceCommandLine_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandLine_ sequenceCommandLine_s; +struct sequenceCommandLine_ +{ + int commandType; // Specifies the type of command + client_textmessage_t clientMessage; // Text HUD message struct + char* speakerName; // Targetname of speaking entity + char* listenerName; // Targetname of entity being spoken to + char* soundFileName; // Name of sound file to play + char* sentenceName; // Name of sentences.txt to play + char* fireTargetNames; // List of targetnames to fire + char* killTargetNames; // List of targetnames to remove + float delay; // Seconds 'till next command + int repeatCount; // If nonzero, reset execution pointer to top of block (N times, -1 = infinite) + int textChannel; // Display channel on which text message is sent + int modifierBitField; // Bit field to specify what clientmessage fields are valid + sequenceCommandLine_s* nextCommandLine; // Next command (linked list) +}; + + +//--------------------------------------------------------------------------- +// sequenceEntry_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceEntry_ sequenceEntry_s; +struct sequenceEntry_ +{ + char* fileName; // Name of sequence file without .SEQ extension + char* entryName; // Name of entry label in file + sequenceCommandLine_s* firstCommand; // Linked list of commands in entry + sequenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? +}; + + + +//--------------------------------------------------------------------------- +// sentenceEntry_s +// Structure representing a single sentence of a group from a .SEQ +// file entry. Sentences are identical to entries in sentences.txt, but +// can be unique per level and are loaded/unloaded with the level. +//--------------------------------------------------------------------------- +typedef struct sentenceEntry_ sentenceEntry_s; +struct sentenceEntry_ +{ + char* data; // sentence data (ie "We have hostiles" ) + sentenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? + unsigned int index; // this entry's position in the file. +}; + +//-------------------------------------------------------------------------- +// sentenceGroupEntry_s +// Structure representing a group of sentences found in a .SEQ file. +// A sentence group is defined by all sentences with the same name, ignoring +// the number at the end of the sentence name. Groups enable a sentence +// to be picked at random across a group. +//-------------------------------------------------------------------------- +typedef struct sentenceGroupEntry_ sentenceGroupEntry_s; +struct sentenceGroupEntry_ +{ + char* groupName; // name of the group (ie CT_ALERT ) + unsigned int numSentences; // number of sentences in group + sentenceEntry_s* firstSentence; // head of linked list of sentences in group + sentenceGroupEntry_s* nextEntry; // next loaded group +}; + +//--------------------------------------------------------------------------- +// Function declarations +//--------------------------------------------------------------------------- +sequenceEntry_s* SequenceGet( const char* fileName, const char* entryName ); +void Sequence_ParseFile( const char* fileName, qboolean isGlobal ); +void Sequence_OnLevelLoad( const char* mapName ); +sentenceEntry_s* SequencePickSentence( const char *groupName, int pickMethod, int *picked ); + +#endif // _INCLUDE_SEQUENCE_H_ diff --git a/dep/hlsdk/common/SteamAppStartUp.cpp b/dep/hlsdk/common/SteamAppStartUp.cpp new file mode 100644 index 0000000..7f13f4b --- /dev/null +++ b/dep/hlsdk/common/SteamAppStartUp.cpp @@ -0,0 +1,211 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#ifdef _WIN32 +#include "SteamAppStartup.h" + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include + +#define STEAM_PARM "-steam" + +bool FileExists(const char *fileName) +{ + struct _stat statbuf; + return (_stat(fileName, &statbuf) == 0); +} + +// Handles launching the game indirectly via steam +void LaunchSelfViaSteam(const char *params) +{ + // calculate the details of our launch + char appPath[MAX_PATH]; + ::GetModuleFileName((HINSTANCE)GetModuleHandle(NULL), appPath, sizeof(appPath)); + + // strip out the exe name + char *slash = Q_strrchr(appPath, '\\'); + if (slash) + { + *slash = '\0'; + } + + // save out our details to the registry + HKEY hKey; + if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey)) + { + DWORD dwType = REG_SZ; + DWORD dwSize = static_cast(Q_strlen(appPath) + 1); + RegSetValueEx(hKey, "TempAppPath", NULL, dwType, (LPBYTE)appPath, dwSize); + dwSize = static_cast(Q_strlen(params) + 1); + RegSetValueEx(hKey, "TempAppCmdLine", NULL, dwType, (LPBYTE)params, dwSize); + // clear out the appID (since we don't know it yet) + dwType = REG_DWORD; + int appID = -1; + RegSetValueEx(hKey, "TempAppID", NULL, dwType, (LPBYTE)&appID, sizeof(appID)); + RegCloseKey(hKey); + } + + // search for an active steam instance + HWND hwnd = ::FindWindow("Valve_SteamIPC_Class", "Hidden Window"); + if (hwnd) + { + ::PostMessage(hwnd, WM_USER + 3, 0, 0); + } + else + { + // couldn't find steam, find and launch it + + // first, search backwards through our current set of directories + char steamExe[MAX_PATH] = ""; + char dir[MAX_PATH]; + + if (::GetCurrentDirectoryA(sizeof(dir), dir)) + { + char *slash = Q_strrchr(dir, '\\'); + while (slash) + { + // see if steam_dev.exe is in the directory first + slash[1] = '\0'; + Q_strcat(slash, "steam_dev.exe"); + FILE *f = fopen(dir, "rb"); + if (f) + { + // found it + fclose(f); + Q_strcpy(steamExe, dir); + break; + } + + // see if steam.exe is in the directory + slash[1] = '\0'; + Q_strcat(slash, "steam.exe"); + f = fopen(dir, "rb"); + if (f) + { + // found it + fclose(f); + Q_strcpy(steamExe, dir); + break; + } + + // kill the string at the slash + slash[0] = '\0'; + + // move to the previous slash + slash = Q_strrchr(dir, '\\'); + } + } + + if (!steamExe[0]) + { + // still not found, use the one in the registry + HKEY hKey; + if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey)) + { + DWORD dwType; + DWORD dwSize = sizeof(steamExe); + RegQueryValueEx(hKey, "SteamExe", NULL, &dwType, (LPBYTE)steamExe, &dwSize); + RegCloseKey(hKey); + } + } + + if (!steamExe[0]) + { + // still no path, error + ::MessageBox(NULL, "Error running game: could not find steam.exe to launch", "Fatal Error", MB_OK | MB_ICONERROR); + return; + } + + // fix any slashes + for (char *slash = steamExe; *slash; slash++) + { + if (*slash == '/') + { + *slash = '\\'; + } + } + + // change to the steam directory + Q_strcpy(dir, steamExe); + char *delimiter = Q_strrchr(dir, '\\'); + if (delimiter) + { + *delimiter = '\0'; + _chdir(dir); + } + + // exec steam.exe, in silent mode, with the launch app param + char *args[4] = { steamExe, "-silent", "-applaunch", '\0' }; + _spawnv(_P_NOWAIT, steamExe, args); + } +} + +// Launches steam if necessary +bool ShouldLaunchAppViaSteam(const char *lpCmdLine, const char *steamFilesystemDllName, const char *stdioFilesystemDllName) +{ + // see if steam is on the command line + const char *steamStr = Q_strstr(lpCmdLine, STEAM_PARM); + + // check the character following it is a whitespace or null + if (steamStr) + { + const char *postChar = steamStr + Q_strlen(STEAM_PARM); + if (*postChar == 0 || isspace(*postChar)) + { + // we're running under steam already, let the app continue + return false; + } + } + + // we're not running under steam, see which filesystems are available + if (FileExists(stdioFilesystemDllName)) + { + // we're being run with a stdio filesystem, so we can continue without steam + return false; + } + + // make sure we have a steam filesystem available + if (!FileExists(steamFilesystemDllName)) + { + return false; + } + + // we have the steam filesystem, and no stdio filesystem, so we must need to be run under steam + // launch steam + LaunchSelfViaSteam(lpCmdLine); + return true; +} + +#endif // _WIN32 diff --git a/dep/hlsdk/common/SteamAppStartUp.h b/dep/hlsdk/common/SteamAppStartUp.h new file mode 100644 index 0000000..2b9fbe7 --- /dev/null +++ b/dep/hlsdk/common/SteamAppStartUp.h @@ -0,0 +1,37 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Call this first thing at startup +// Works out if the app is a steam app that is being ran outside of steam, +// and if so, launches steam and tells it to run us as a steam app +// +// if it returns true, then exit +// if it ruturns false, then continue with normal startup +bool ShouldLaunchAppViaSteam(const char *cmdLine, const char *steamFilesystemDllName, const char *stdioFilesystemDllName); diff --git a/dep/hlsdk/common/SteamCommon.h b/dep/hlsdk/common/SteamCommon.h new file mode 100644 index 0000000..c3fb1b0 --- /dev/null +++ b/dep/hlsdk/common/SteamCommon.h @@ -0,0 +1,707 @@ + +//========= Copyright Valve Corporation, All rights reserved. ============// +/* +** The copyright to the contents herein is the property of Valve Corporation. +** The contents may be used and/or copied only with the written permission of +** Valve, or in accordance with the terms and conditions stipulated in +** the agreement/contract under which the contents have been supplied. +** +******************************************************************************* +** +** Contents: +** +** Common types used in the Steam DLL interface. +** +** This file is distributed to Steam application developers. +** +** +** +*******************************************************************************/ + +#ifndef INCLUDED_STEAM_COMMON_STEAMCOMMON_H +#define INCLUDED_STEAM_COMMON_STEAMCOMMON_H + +#if defined(_MSC_VER) && (_MSC_VER > 1000) +#pragma once +#endif + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Applications should not define STEAM_EXPORTS. */ + +#if defined ( _WIN32 ) + +#ifdef STEAM_EXPORTS +#define STEAM_API __declspec(dllexport) EXT_FUNC +#else +#define STEAM_API __declspec(dllimport) +#endif + +#define STEAM_CALL __cdecl + +#else + +#ifdef STEAM_EXPORTS +#define STEAM_API EXT_FUNC +#else +#define STEAM_API /* */ +#endif +#define STEAM_CALL /* */ + +#endif + +typedef void (STEAM_CALL *KeyValueIteratorCallback_t )(const char *Key, const char *Val, void *pvParam); + + +/****************************************************************************** +** +** Exported macros and constants +** +******************************************************************************/ + +/* DEPRECATED -- these are ignored now, all API access is granted on SteamStartup */ +#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) +/* END DEPRECATED */ + +#define STEAM_MAX_PATH (255) +#define STEAM_QUESTION_MAXLEN (255) +#define STEAM_SALT_SIZE (8) +#define STEAM_PROGRESS_PERCENT_SCALE (0x00001000) + +/* These are maximum significant string lengths, excluding nul-terminator. */ +#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) // mm/dd/yy +#define STEAM_BILLING_TRANS_TIME_SIZE (9) // hh:mm:ss + +/****************************************************************************** +** +** Scalar type and enumerated type definitions. +** +******************************************************************************/ + + +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 /* Filter elements returned by SteamFind{First,Next} */ +{ + eSteamFindLocalOnly, /* limit search to local filesystem */ + eSteamFindRemoteOnly, /* limit search to remote repository */ + eSteamFindAll /* do not limit search (duplicates allowed) */ +} ESteamFindFilter; + + +/****************************************************************************** +** +** Exported structure and complex type definitions. +** +******************************************************************************/ + + +typedef struct +{ + ESteamError eSteamError; + EDetailedPlatformErrorType eDetailedErrorType; + int nDetailedErrorCode; + char szDesc[STEAM_MAX_PATH]; +} TSteamError; + + + +typedef struct +{ + int bIsDir; /* If non-zero, element is a directory; if zero, element is a file */ + unsigned int uSizeOrCount; /* If element is a file, this contains size of file in bytes */ + int bIsLocal; /* If non-zero, reported item is a standalone element on local filesystem */ + char cszName[STEAM_MAX_PATH]; /* Base element name (no path) */ + long lLastAccessTime; /* Seconds since 1/1/1970 (like time_t) when element was last accessed */ + long lLastModificationTime; /* Seconds since 1/1/1970 (like time_t) when element was last modified */ + long lCreationTime; /* Seconds since 1/1/1970 (like time_t) when element was created */ +} 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; /* non-zero if call provides progress info */ + unsigned int uPercentDone; /* 0 to 100 * STEAM_PROGRESS_PERCENT_SCALE if bValid */ + char szProgress[STEAM_MAX_PATH]; /* additional progress info */ +} 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; + /* If the TSteamSubscription says that shipping info is required, */ + /* then the following fields must be filled out. */ + /* If szShippingName is empty, then assumes so are the rest. */ + 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 ]; + + /* A ProofOfPurchase token is not necessarily a nul-terminated string; it may be binary data + (perhaps encrypted). Hence we need a length and an array of bytes. */ + 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, /* indirect billing via ISP etc (not supported yet) */ + ePaymentCardReceipt = 5, + ePrepurchaseReceipt = 6, + eEmptyReceipt = 7 +} ESteamSubscriptionBillingInfoType; + +typedef struct +{ + ESteamSubscriptionBillingInfoType eBillingInfoType; + union { + TSteamPaymentCardInfo PaymentCardInfo; + TSteamPrepurchaseInfo PrepurchaseInfo; + TSteamExternalBillingInfo ExternalBillingInfo; + char bUseAccountBillingInfo; + }; + +} TSteamSubscriptionBillingInfo; + +typedef enum +{ + /* Subscribed */ + eSteamSubscriptionOK = 0, /* Subscribed */ + eSteamSubscriptionPending = 1, /* Awaiting transaction completion */ + eSteamSubscriptionPreorder = 2, /* Is currently a pre-order */ + eSteamSubscriptionPrepurchaseTransferred = 3, /* hop to this account */ + /* Unusbscribed */ + eSteamSubscriptionPrepurchaseInvalid = 4, /* Invalid cd-key */ + eSteamSubscriptionPrepurchaseRejected = 5, /* hopped out / banned / etc */ + eSteamSubscriptionPrepurchaseRevoked = 6, /* hop away from this account */ + eSteamSubscriptionPaymentCardDeclined = 7, /* CC txn declined */ + eSteamSubscriptionCancelledByUser = 8, /* Cancelled by client */ + eSteamSubscriptionCancelledByVendor = 9, /* Cancelled by us */ + eSteamSubscriptionPaymentCardUseLimit = 10, /* Card used too many times, potential fraud */ + eSteamSubscriptionPaymentCardAlert = 11, /* Got a "pick up card" or the like from bank */ + eSteamSubscriptionFailed = 12, /* Other Error in subscription data or transaction failed/lost */ + eSteamSubscriptionPaymentCardAVSFailure = 13, /* Card failed Address Verification check */ + eSteamSubscriptionPaymentCardInsufficientFunds = 14, /* Card failed due to insufficient funds */ + eSteamSubscriptionRestrictedCountry = 15 /* The subscription is not available in the user's country */ + +} 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 ]; + + // The following are only available after the subscription leaves "pending" status + char szCardApprovalCode[ STEAM_BILLING_CARD_APPROVAL_CODE_SIZE + 1]; + char szTransDate[ STEAM_BILLING_TRANS_DATE_SIZE + 1]; /* mm/dd/yy */ + char szTransTime[ STEAM_BILLING_TRANS_TIME_SIZE + 1]; /* hh:mm:ss */ + 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, /* May subscribe, unsubscribe, etc */ + eSteamUserDeveloper = 0x00000002, /* Steam or App developer */ + eSteamUserCyberCafe = 0x00000004 /* CyberCafe, school, etc -- UI should ask for password */ + /* before allowing logout, unsubscribe, etc */ +} ESteamUserTypeFlags; + +typedef enum +{ + eSteamAccountStatusDefault = 0x00000000, + eSteamAccountStatusEmailVerified = 0x00000001, + /* Note: Mask value 0x2 is reserved for future use. (Some, but not all, public accounts already have this set.) */ + 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; + +/****************************************************************************** +** +** More exported constants +** +******************************************************************************/ + + +#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 + + +/****************************************************************************** +** Each Steam instance (licensed Steam Service Provider) has a unique SteamInstanceID_t. +** +** Each Steam instance as its own DB of users. +** Each user in the DB has a unique SteamLocalUserID_t (a serial number, with possible +** rare gaps in the sequence). +** +******************************************************************************/ + +typedef unsigned short SteamInstanceID_t; // MUST be 16 bits + + +#if defined ( _WIN32 ) +typedef unsigned __int64 SteamLocalUserID_t; // MUST be 64 bits +#else +typedef unsigned long long SteamLocalUserID_t; // MUST be 64 bits +#endif + +/****************************************************************************** +** +** Applications need to be able to authenticate Steam users from ANY instance. +** So a SteamIDTicket contains SteamGlobalUserID, which is a unique combination of +** instance and user id. +** +** SteamLocalUserID is an unsigned 64-bit integer. +** For platforms without 64-bit int support, we provide access via a union that splits it into +** high and low unsigned 32-bit ints. Such platforms will only need to compare LocalUserIDs +** for equivalence anyway - not perform arithmetic with them. +** +********************************************************************************/ +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 diff --git a/dep/hlsdk/common/TextConsoleUnix.cpp b/dep/hlsdk/common/TextConsoleUnix.cpp new file mode 100644 index 0000000..32671ae --- /dev/null +++ b/dep/hlsdk/common/TextConsoleUnix.cpp @@ -0,0 +1,324 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if !defined(_WIN32) + +#include "TextConsoleUnix.h" +#include "icommandline.h" + +#include +#include +#include +#include +#include +#include +#include + +CTextConsoleUnix console; + +CTextConsoleUnix::~CTextConsoleUnix() +{ + CTextConsoleUnix::ShutDown(); +} + +bool CTextConsoleUnix::Init(IBaseSystem *system) +{ + static struct termios termNew; + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + + tty = stdout; + + // this code is for echo-ing key presses to the connected tty + // (which is != STDOUT) + if (isatty(STDIN_FILENO)) + { + tty = fopen(ctermid(NULL), "w+"); + if (!tty) + { + printf("Unable to open tty(%s) for output\n", ctermid(NULL)); + tty = stdout; + } + else + { + // turn buffering off + setbuf(tty, NULL); + } + } + else + { + tty = fopen("/dev/null", "w+"); + if (!tty) + { + tty = stdout; + } + } + + tcgetattr(STDIN_FILENO, &termStored); + + Q_memcpy(&termNew, &termStored, sizeof(struct termios)); + + // Disable canonical mode, and set buffer size to 1 byte + termNew.c_lflag &= (~ICANON); + termNew.c_cc[ VMIN ] = 1; + termNew.c_cc[ VTIME ] = 0; + + // disable echo + termNew.c_lflag &= (~ECHO); + + tcsetattr(STDIN_FILENO, TCSANOW, &termNew); + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + + return CTextConsole::Init(system); +} + +void CTextConsoleUnix::ShutDown() +{ + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + tcsetattr(STDIN_FILENO, TCSANOW, &termStored); + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + + CTextConsole::ShutDown(); +} + +// return 0 if the kb isn't hit +int CTextConsoleUnix::kbhit() +{ + fd_set rfds; + struct timeval tv; + + // Watch stdin (fd 0) to see when it has input. + FD_ZERO(&rfds); + FD_SET(STDIN_FILENO, &rfds); + + // Return immediately. + tv.tv_sec = 0; + tv.tv_usec = 0; + + // Must be in raw or cbreak mode for this to work correctly. + return select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv) != -1 && FD_ISSET(STDIN_FILENO, &rfds); +} + +char *CTextConsoleUnix::GetLine() +{ + // early return for 99.999% case :) + if (!kbhit()) + return NULL; + + escape_sequence_t es; + + es = ESCAPE_CLEAR; + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigaddset(&block_ttou, SIGTTIN); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + + while (true) + { + if (!kbhit()) + break; + + int nLen; + char ch = 0; + int numRead = read(STDIN_FILENO, &ch, 1); + if (!numRead) + break; + + switch (ch) + { + case '\n': // Enter + es = ESCAPE_CLEAR; + + nLen = ReceiveNewline(); + if (nLen) + { + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + return m_szConsoleText; + } + break; + + case 127: // Backspace + case '\b': // Backspace + es = ESCAPE_CLEAR; + ReceiveBackspace(); + break; + + case '\t': // TAB + es = ESCAPE_CLEAR; + ReceiveTab(); + break; + + case 27: // Escape character + es = ESCAPE_RECEIVED; + break; + + case '[': // 2nd part of escape sequence + case 'O': + case 'o': + switch (es) + { + case ESCAPE_CLEAR: + case ESCAPE_BRACKET_RECEIVED: + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + break; + + case ESCAPE_RECEIVED: + es = ESCAPE_BRACKET_RECEIVED; + break; + } + break; + case 'A': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveUpArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'B': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveDownArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'C': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveRightArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'D': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveLeftArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + default: + // Just eat this char if it's an unsupported escape + if (es != ESCAPE_BRACKET_RECEIVED) + { + // dont' accept nonprintable chars + if ((ch >= ' ') && (ch <= '~')) + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + } + break; + } + + fflush(stdout); + } + + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + return NULL; +} + +void CTextConsoleUnix::PrintRaw(char *pszMsg, int nChars) +{ + if (nChars == 0) + { + printf("%s", pszMsg); + } + else + { + for (int nCount = 0; nCount < nChars; nCount++) + { + putchar(pszMsg[ nCount ]); + } + } +} + +void CTextConsoleUnix::Echo(char *pszMsg, int nChars) +{ + if (nChars == 0) + { + fputs(pszMsg, tty); + } + else + { + for (int nCount = 0; nCount < nChars; nCount++) + { + fputc(pszMsg[ nCount ], tty); + } + } +} + +int CTextConsoleUnix::GetWidth() +{ + struct winsize ws; + int nWidth = 0; + + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) + { + nWidth = (int)ws.ws_col; + } + + if (nWidth <= 1) + { + nWidth = 80; + } + + return nWidth; +} + +#endif // !defined(_WIN32) diff --git a/dep/hlsdk/common/TextConsoleUnix.h b/dep/hlsdk/common/TextConsoleUnix.h new file mode 100644 index 0000000..b40cbc4 --- /dev/null +++ b/dep/hlsdk/common/TextConsoleUnix.h @@ -0,0 +1,59 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include +#include "textconsole.h" + +enum escape_sequence_t +{ + ESCAPE_CLEAR, + ESCAPE_RECEIVED, + ESCAPE_BRACKET_RECEIVED +}; + +class CTextConsoleUnix: public CTextConsole { +public: + virtual ~CTextConsoleUnix(); + + bool Init(IBaseSystem *system = nullptr); + void ShutDown(); + void PrintRaw(char *pszMsg, int nChars = 0); + void Echo(char *pszMsg, int nChars = 0); + char *GetLine(); + int GetWidth(); + +private: + int kbhit(); + + struct termios termStored; + FILE *tty; +}; + +extern CTextConsoleUnix console; diff --git a/dep/hlsdk/common/TextConsoleWin32.cpp b/dep/hlsdk/common/TextConsoleWin32.cpp new file mode 100644 index 0000000..aeaefb3 --- /dev/null +++ b/dep/hlsdk/common/TextConsoleWin32.cpp @@ -0,0 +1,282 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if defined(_WIN32) + +CTextConsoleWin32 console; +#pragma comment(lib, "user32.lib") + +BOOL WINAPI ConsoleHandlerRoutine(DWORD CtrlType) +{ + // TODO ? + /*if (CtrlType != CTRL_C_EVENT && CtrlType != CTRL_BREAK_EVENT) + { + // don't quit on break or ctrl+c + m_System->Stop(); + }*/ + + return TRUE; +} + +// GetConsoleHwnd() helper function from MSDN Knowledge Base Article Q124103 +// needed, because HWND GetConsoleWindow(VOID) is not avaliable under Win95/98/ME +HWND GetConsoleHwnd() +{ + HWND hwndFound; // This is what is returned to the caller. + char pszNewWindowTitle[1024]; // Contains fabricated WindowTitle + char pszOldWindowTitle[1024]; // Contains original WindowTitle + + // Fetch current window title. + GetConsoleTitle(pszOldWindowTitle, sizeof(pszOldWindowTitle)); + + // Format a "unique" NewWindowTitle. + wsprintf(pszNewWindowTitle, "%d/%d", GetTickCount(), GetCurrentProcessId()); + + // Change current window title. + SetConsoleTitle(pszNewWindowTitle); + + // Ensure window title has been updated. + Sleep(40); + + // Look for NewWindowTitle. + hwndFound = FindWindow(nullptr, pszNewWindowTitle); + + // Restore original window title. + SetConsoleTitle(pszOldWindowTitle); + + return hwndFound; +} + +CTextConsoleWin32::~CTextConsoleWin32() +{ + CTextConsoleWin32::ShutDown(); +} + +bool CTextConsoleWin32::Init(IBaseSystem *system) +{ + if (!AllocConsole()) + m_System = system; + + SetTitle(m_System ? m_System->GetName() : "Console"); + + hinput = GetStdHandle(STD_INPUT_HANDLE); + houtput = GetStdHandle(STD_OUTPUT_HANDLE); + + if (!SetConsoleCtrlHandler(&ConsoleHandlerRoutine, TRUE)) { + Print("WARNING! TextConsole::Init: Could not attach console hook.\n"); + } + + Attrib = FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; + SetWindowPos(GetConsoleHwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOREPOSITION | SWP_SHOWWINDOW); + + return CTextConsole::Init(system); +} + +void CTextConsoleWin32::ShutDown() +{ + FreeConsole(); + CTextConsole::ShutDown(); +} + +void CTextConsoleWin32::SetVisible(bool visible) +{ + ShowWindow(GetConsoleHwnd(), visible ? SW_SHOW : SW_HIDE); + m_ConsoleVisible = visible; +} + +char *CTextConsoleWin32::GetLine() +{ + while (true) + { + INPUT_RECORD recs[1024]; + unsigned long numread; + unsigned long numevents; + + if (!GetNumberOfConsoleInputEvents(hinput, &numevents)) + { + if (m_System) { + m_System->Errorf("CTextConsoleWin32::GetLine: !GetNumberOfConsoleInputEvents\n"); + } + + return nullptr; + } + + if (numevents <= 0) + break; + + if (!ReadConsoleInput(hinput, recs, ARRAYSIZE(recs), &numread)) + { + if (m_System) { + m_System->Errorf("CTextConsoleWin32::GetLine: !ReadConsoleInput\n"); + } + + return nullptr; + } + + if (numread == 0) + return nullptr; + + for (int i = 0; i < (int)numread; i++) + { + INPUT_RECORD *pRec = &recs[i]; + if (pRec->EventType != KEY_EVENT) + continue; + + if (pRec->Event.KeyEvent.bKeyDown) + { + // check for cursor keys + if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_UP) + { + ReceiveUpArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_DOWN) + { + ReceiveDownArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_LEFT) + { + ReceiveLeftArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_RIGHT) + { + ReceiveRightArrow(); + } + else + { + int nLen; + char ch = pRec->Event.KeyEvent.uChar.AsciiChar; + switch (ch) + { + case '\r': // Enter + nLen = ReceiveNewline(); + if (nLen) + { + return m_szConsoleText; + } + break; + case '\b': // Backspace + ReceiveBackspace(); + break; + case '\t': // TAB + ReceiveTab(); + break; + default: + // dont' accept nonprintable chars + if ((ch >= ' ') && (ch <= '~')) + { + ReceiveStandardChar(ch); + } + break; + } + } + } + } + } + + return nullptr; +} + +void CTextConsoleWin32::PrintRaw(char *pszMsg, int nChars) +{ +#ifdef LAUNCHER_FIXES + char outputStr[2048]; + WCHAR unicodeStr[1024]; + + DWORD nSize = MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, NULL, 0); + if (nSize > sizeof(unicodeStr)) + return; + + MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, unicodeStr, nSize); + DWORD nLength = WideCharToMultiByte(CP_OEMCP, 0, unicodeStr, -1, 0, 0, NULL, NULL); + if (nLength > sizeof(outputStr)) + return; + + WideCharToMultiByte(CP_OEMCP, 0, unicodeStr, -1, outputStr, nLength, NULL, NULL); + WriteFile(houtput, outputStr, nChars ? nChars : Q_strlen(outputStr), NULL, NULL); +#else + WriteFile(houtput, pszMsg, nChars ? nChars : Q_strlen(pszMsg), NULL, NULL); +#endif +} + +void CTextConsoleWin32::Echo(char *pszMsg, int nChars) +{ + PrintRaw(pszMsg, nChars); +} + +int CTextConsoleWin32::GetWidth() +{ + CONSOLE_SCREEN_BUFFER_INFO csbi; + int nWidth = 0; + + if (GetConsoleScreenBufferInfo(houtput, &csbi)) { + nWidth = csbi.dwSize.X; + } + + if (nWidth <= 1) + nWidth = 80; + + return nWidth; +} + +void CTextConsoleWin32::SetStatusLine(char *pszStatus) +{ + Q_strncpy(statusline, pszStatus, sizeof(statusline) - 1); + statusline[sizeof(statusline) - 2] = '\0'; + UpdateStatus(); +} + +void CTextConsoleWin32::UpdateStatus() +{ + COORD coord; + DWORD dwWritten = 0; + WORD wAttrib[ 80 ]; + + for (int i = 0; i < 80; i++) + { + wAttrib[i] = Attrib; // FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; + } + + coord.X = coord.Y = 0; + + WriteConsoleOutputAttribute(houtput, wAttrib, 80, coord, &dwWritten); + WriteConsoleOutputCharacter(houtput, statusline, 80, coord, &dwWritten); +} + +void CTextConsoleWin32::SetTitle(char *pszTitle) +{ + SetConsoleTitle(pszTitle); +} + +void CTextConsoleWin32::SetColor(WORD attrib) +{ + Attrib = attrib; +} + +#endif // defined(_WIN32) diff --git a/dep/hlsdk/common/TextConsoleWin32.h b/dep/hlsdk/common/TextConsoleWin32.h new file mode 100644 index 0000000..656110e --- /dev/null +++ b/dep/hlsdk/common/TextConsoleWin32.h @@ -0,0 +1,62 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#include +#include "TextConsole.h" + +class CTextConsoleWin32: public CTextConsole { +public: + virtual ~CTextConsoleWin32(); + + bool Init(IBaseSystem *system = nullptr); + void ShutDown(); + + void SetTitle(char *pszTitle); + void SetStatusLine(char *pszStatus); + void UpdateStatus(); + + void PrintRaw(char * pszMsz, int nChars = 0); + void Echo(char * pszMsz, int nChars = 0); + char *GetLine(); + int GetWidth(); + + void SetVisible(bool visible); + void SetColor(WORD); + +private: + HANDLE hinput; // standard input handle + HANDLE houtput; // standard output handle + WORD Attrib; // attrib colours for status bar + + char statusline[81]; // first line in console is status line +}; + +extern CTextConsoleWin32 console; diff --git a/dep/hlsdk/common/TokenLine.cpp b/dep/hlsdk/common/TokenLine.cpp new file mode 100644 index 0000000..7f88555 --- /dev/null +++ b/dep/hlsdk/common/TokenLine.cpp @@ -0,0 +1,132 @@ +#include "precompiled.h" + +TokenLine::TokenLine() +{ + Q_memset(m_token, 0, sizeof(m_token)); + Q_memset(m_fullLine, 0, sizeof(m_fullLine)); + Q_memset(m_tokenBuffer, 0, sizeof(m_tokenBuffer)); + + m_tokenNumber = 0; +} + +TokenLine::TokenLine(char *string) +{ + SetLine(string); +} + +TokenLine::~TokenLine() +{ + +} + +bool TokenLine::SetLine(const char *newLine) +{ + m_tokenNumber = 0; + + if (!newLine || (Q_strlen(newLine) >= (MAX_LINE_CHARS - 1))) + { + Q_memset(m_fullLine, 0, sizeof(m_fullLine)); + Q_memset(m_tokenBuffer, 0, sizeof(m_tokenBuffer)); + return false; + } + + Q_strlcpy(m_fullLine, newLine); + Q_strlcpy(m_tokenBuffer, newLine); + + // parse tokens + char *charPointer = m_tokenBuffer; + while (*charPointer && (m_tokenNumber < MAX_LINE_TOKENS)) + { + // skip nonprintable chars + while (*charPointer && ((*charPointer <= ' ') || (*charPointer > '~'))) + charPointer++; + + if (*charPointer) + { + m_token[m_tokenNumber] = charPointer; + + // special treatment for quotes + if (*charPointer == '\"') + { + charPointer++; + m_token[m_tokenNumber] = charPointer; + while (*charPointer && (*charPointer != '\"')) + charPointer++; + } + else + { + m_token[m_tokenNumber] = charPointer; + while (*charPointer && ((*charPointer > 32) && (*charPointer <= 126))) + charPointer++; + } + + m_tokenNumber++; + + if (*charPointer) + { + *charPointer = '\0'; + charPointer++; + } + } + } + + return (m_tokenNumber != MAX_LINE_TOKENS); +} + +char *TokenLine::GetLine() +{ + return m_fullLine; +} + +char *TokenLine::GetToken(int i) +{ + if (i >= m_tokenNumber) + return NULL; + + return m_token[i]; +} + +// if the given parm is not present return NULL +// otherwise return the address of the following token, or an empty string +char *TokenLine::CheckToken(char *parm) +{ + for (int i = 0; i < m_tokenNumber; i++) + { + if (!m_token[i]) + continue; + + if (!Q_strcmp(parm, m_token[i])) + { + char *ret = m_token[i + 1]; + + // if this token doesn't exist, since index i was the last + // return an empty string + if (m_tokenNumber == (i + 1)) + ret = ""; + + return ret; + } + } + + return NULL; +} + +int TokenLine::CountToken() +{ + int c = 0; + for (int i = 0; i < m_tokenNumber; i++) + { + if (m_token[i]) + c++; + } + + return c; +} + +char *TokenLine::GetRestOfLine(int i) +{ + if (i >= m_tokenNumber) + return NULL; + + return m_fullLine + (m_token[i] - m_tokenBuffer); +} diff --git a/dep/hlsdk/common/TokenLine.h b/dep/hlsdk/common/TokenLine.h new file mode 100644 index 0000000..0d16fb6 --- /dev/null +++ b/dep/hlsdk/common/TokenLine.h @@ -0,0 +1,51 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class TokenLine { +public: + TokenLine(); + TokenLine(char *string); + virtual ~TokenLine(); + + char *GetRestOfLine(int i); // returns all chars after token i + int CountToken(); // returns number of token + char *CheckToken(char *parm); // returns token after token parm or "" + char *GetToken(int i); // returns token i + char *GetLine(); // returns full line + bool SetLine(const char *newLine); // set new token line and parses it + +private: + enum { MAX_LINE_CHARS = 2048, MAX_LINE_TOKENS = 128 }; + + char m_tokenBuffer[MAX_LINE_CHARS]; + char m_fullLine[MAX_LINE_CHARS]; + char *m_token[MAX_LINE_TOKENS]; + int m_tokenNumber; +}; diff --git a/dep/hlsdk/common/beamdef.h b/dep/hlsdk/common/beamdef.h new file mode 100644 index 0000000..fd77a76 --- /dev/null +++ b/dep/hlsdk/common/beamdef.h @@ -0,0 +1,62 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( BEAMDEFH ) +#define BEAMDEFH +#ifdef _WIN32 +#pragma once +#endif + +#define FBEAM_STARTENTITY 0x00000001 +#define FBEAM_ENDENTITY 0x00000002 +#define FBEAM_FADEIN 0x00000004 +#define FBEAM_FADEOUT 0x00000008 +#define FBEAM_SINENOISE 0x00000010 +#define FBEAM_SOLID 0x00000020 +#define FBEAM_SHADEIN 0x00000040 +#define FBEAM_SHADEOUT 0x00000080 +#define FBEAM_STARTVISIBLE 0x10000000 // Has this client actually seen this beam's start entity yet? +#define FBEAM_ENDVISIBLE 0x20000000 // Has this client actually seen this beam's end entity yet? +#define FBEAM_ISACTIVE 0x40000000 +#define FBEAM_FOREVER 0x80000000 + +typedef struct beam_s BEAM; +struct beam_s +{ + BEAM *next; + int type; + int flags; + vec3_t source; + vec3_t target; + vec3_t delta; + float t; // 0 .. 1 over lifetime of beam + float freq; + float die; + float width; + float amplitude; + float r, g, b; + float brightness; + float speed; + float frameRate; + float frame; + int segments; + int startEntity; + int endEntity; + int modelIndex; + int frameCount; + struct model_s *pFollowModel; + struct particle_s *particles; +}; + +#endif diff --git a/dep/hlsdk/common/cl_entity.h b/dep/hlsdk/common/cl_entity.h new file mode 100644 index 0000000..a7cd472 --- /dev/null +++ b/dep/hlsdk/common/cl_entity.h @@ -0,0 +1,115 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// cl_entity.h +#if !defined( CL_ENTITYH ) +#define CL_ENTITYH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct efrag_s +{ + struct mleaf_s *leaf; + struct efrag_s *leafnext; + struct cl_entity_s *entity; + struct efrag_s *entnext; +} efrag_t; + +typedef struct +{ + byte mouthopen; // 0 = mouth closed, 255 = mouth agape + byte sndcount; // counter for running average + int sndavg; // running average +} mouth_t; + +typedef struct +{ + float prevanimtime; + float sequencetime; + byte prevseqblending[2]; + vec3_t prevorigin; + vec3_t prevangles; + + int prevsequence; + float prevframe; + + byte prevcontroller[4]; + byte prevblending[2]; +} latchedvars_t; + +typedef struct +{ + // Time stamp for this movement + float animtime; + + vec3_t origin; + vec3_t angles; +} position_history_t; + +typedef struct cl_entity_s cl_entity_t; + +#define HISTORY_MAX 64 // Must be power of 2 +#define HISTORY_MASK ( HISTORY_MAX - 1 ) + + +#if !defined( ENTITY_STATEH ) +#include "entity_state.h" +#endif + +#if !defined( PROGS_H ) +#include "progs.h" +#endif + +struct cl_entity_s +{ + int index; // Index into cl_entities ( should match actual slot, but not necessarily ) + + qboolean player; // True if this entity is a "player" + + entity_state_t baseline; // The original state from which to delta during an uncompressed message + entity_state_t prevstate; // The state information from the penultimate message received from the server + entity_state_t curstate; // The state information from the last message received from server + + int current_position; // Last received history update index + position_history_t ph[ HISTORY_MAX ]; // History of position and angle updates for this player + + mouth_t mouth; // For synchronizing mouth movements. + + latchedvars_t latched; // Variables used by studio model rendering routines + + // Information based on interplocation, extrapolation, prediction, or just copied from last msg received. + // + float lastmove; + + // Actual render position and angles + vec3_t origin; + vec3_t angles; + + // Attachment points + vec3_t attachment[4]; + + // Other entity local information + int trivial_accept; + + struct model_s *model; // cl.model_precache[ curstate.modelindes ]; all visible entities have a model + struct efrag_s *efrag; // linked list of efrags + struct mnode_s *topnode; // for bmodels, first world node that splits bmodel, or NULL if not split + + float syncbase; // for client-side animations -- used by obsolete alias animation system, remove? + int visframe; // last frame this entity was found in an active leaf + colorVec cvFloorColor; +}; + +#endif // !CL_ENTITYH diff --git a/dep/hlsdk/common/com_model.h b/dep/hlsdk/common/com_model.h new file mode 100644 index 0000000..4e85d22 --- /dev/null +++ b/dep/hlsdk/common/com_model.h @@ -0,0 +1,340 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// com_model.h +#pragma once + +#define STUDIO_RENDER 1 +#define STUDIO_EVENTS 2 + +//#define MAX_MODEL_NAME 64 +//#define MAX_MAP_HULLS 4 +//#define MIPLEVELS 4 +//#define NUM_AMBIENTS 4 // automatic ambient sounds +//#define MAXLIGHTMAPS 4 +#define PLANE_ANYZ 5 + +#define ALIAS_Z_CLIP_PLANE 5 + +// flags in finalvert_t.flags +#define ALIAS_LEFT_CLIP 0x0001 +#define ALIAS_TOP_CLIP 0x0002 +#define ALIAS_RIGHT_CLIP 0x0004 +#define ALIAS_BOTTOM_CLIP 0x0008 +#define ALIAS_Z_CLIP 0x0010 +#define ALIAS_ONSEAM 0x0020 +#define ALIAS_XY_CLIP_MASK 0x000F + +#define ZISCALE ((float)0x8000) + +#define CACHE_SIZE 32 // used to align key data structures + +//typedef enum +//{ +// mod_brush, +// mod_sprite, +// mod_alias, +// mod_studio +//} modtype_t; + +// must match definition in modelgen.h +//#ifndef SYNCTYPE_T +//#define SYNCTYPE_T +// +//typedef enum +//{ +// ST_SYNC=0, +// ST_RAND +//} synctype_t; +// +//#endif + +//typedef struct +//{ +// float mins[3], maxs[3]; +// float origin[3]; +// int headnode[MAX_MAP_HULLS]; +// int visleafs; // not including the solid leaf 0 +// int firstface, numfaces; +//} dmodel_t; + +// plane_t structure +//typedef struct mplane_s +//{ +// vec3_t normal; // surface normal +// float dist; // closest appoach to origin +// byte type; // for texture axis selection and fast side tests +// byte signbits; // signx + signy<<1 + signz<<1 +// byte pad[2]; +//} mplane_t; + +//typedef struct +//{ +// vec3_t position; +//} mvertex_t; + +//typedef struct +//{ +// unsigned short v[2]; +// unsigned int cachededgeoffset; +//} medge_t; + +//typedef struct texture_s +//{ +// char name[16]; +// unsigned width, height; +// int anim_total; // total tenths in sequence ( 0 = no) +// int anim_min, anim_max; // time for this frame min <=time< max +// struct texture_s *anim_next; // in the animation sequence +// struct texture_s *alternate_anims; // bmodels in frame 1 use these +// unsigned offsets[MIPLEVELS]; // four mip maps stored +// unsigned paloffset; +//} texture_t; + +//typedef struct +//{ +// float vecs[2][4]; // [s/t] unit vectors in world space. +// // [i][3] is the s/t offset relative to the origin. +// // s or t = dot(3Dpoint,vecs[i])+vecs[i][3] +// float mipadjust; // ?? mipmap limits for very small surfaces +// texture_t *texture; +// int flags; // sky or slime, no lightmap or 256 subdivision +//} mtexinfo_t; + +//typedef struct mnode_s +//{ +// // common with leaf +// int contents; // 0, to differentiate from leafs +// int visframe; // node needs to be traversed if current +// +// short minmaxs[6]; // for bounding box culling +// +// struct mnode_s *parent; +// +// // node specific +// mplane_t *plane; +// struct mnode_s *children[2]; +// +// unsigned short firstsurface; +// unsigned short numsurfaces; +//} mnode_t; + +//typedef struct msurface_s msurface_t; +//typedef struct decal_s decal_t; + +// JAY: Compress this as much as possible +//struct decal_s +//{ +// decal_t *pnext; // linked list for each surface +// msurface_t *psurface; // Surface id for persistence / unlinking +// short dx; // Offsets into surface texture (in texture coordinates, so we don't need floats) +// short dy; +// short texture; // Decal texture +// byte scale; // Pixel scale +// byte flags; // Decal flags +// +// short entityIndex; // Entity this is attached to +//}; + +//typedef struct mleaf_s +//{ +// // common with node +// int contents; // wil be a negative contents number +// int visframe; // node needs to be traversed if current +// +// short minmaxs[6]; // for bounding box culling +// +// struct mnode_s *parent; +// +// // leaf specific +// byte *compressed_vis; +// struct efrag_s *efrags; +// +// msurface_t **firstmarksurface; +// int nummarksurfaces; +// int key; // BSP sequence number for leaf's contents +// byte ambient_sound_level[NUM_AMBIENTS]; +//} mleaf_t; + +//struct msurface_s +//{ +// int visframe; // should be drawn when node is crossed +// +// int dlightframe; // last frame the surface was checked by an animated light +// int dlightbits; // dynamically generated. Indicates if the surface illumination +// // is modified by an animated light. +// +// mplane_t *plane; // pointer to shared plane +// int flags; // see SURF_ #defines +// +// int firstedge; // look up in model->surfedges[], negative numbers +// int numedges; // are backwards edges +// +// // surface generation data +// struct surfcache_s *cachespots[MIPLEVELS]; +// +// short texturemins[2]; // smallest s/t position on the surface. +// short extents[2]; // ?? s/t texture size, 1..256 for all non-sky surfaces +// +// mtexinfo_t *texinfo; +// +// // lighting info +// byte styles[MAXLIGHTMAPS]; // index into d_lightstylevalue[] for animated lights +// // no one surface can be effected by more than 4 +// // animated lights. +// color24 *samples; +// +// decal_t *pdecals; +//}; + +//typedef struct +//{ +// int planenum; +// short children[2]; // negative numbers are contents +//} dclipnode_t; + +//typedef struct hull_s +//{ +// dclipnode_t *clipnodes; +// mplane_t *planes; +// int firstclipnode; +// int lastclipnode; +// vec3_t clip_mins; +// vec3_t clip_maxs; +//} hull_t; + +typedef struct cache_user_s +{ + void *data; +} cache_user_t; + +//typedef struct model_s +//{ +// char name[ MAX_MODEL_NAME ]; +// qboolean needload; // bmodels and sprites don't cache normally +// +// modtype_t type; +// int numframes; +// synctype_t synctype; +// +// int flags; +// +// // +// // volume occupied by the model +// // +// vec3_t mins, maxs; +// float radius; +// +// // +// // brush model +// // +// int firstmodelsurface, nummodelsurfaces; +// +// int numsubmodels; +// dmodel_t *submodels; +// +// int numplanes; +// mplane_t *planes; +// +// int numleafs; // number of visible leafs, not counting 0 +// struct mleaf_s *leafs; +// +// int numvertexes; +// mvertex_t *vertexes; +// +// int numedges; +// medge_t *edges; +// +// int numnodes; +// mnode_t *nodes; +// +// int numtexinfo; +// mtexinfo_t *texinfo; +// +// int numsurfaces; +// msurface_t *surfaces; +// +// int numsurfedges; +// int *surfedges; +// +// int numclipnodes; +// dclipnode_t *clipnodes; +// +// int nummarksurfaces; +// msurface_t **marksurfaces; +// +// hull_t hulls[MAX_MAP_HULLS]; +// +// int numtextures; +// texture_t **textures; +// +// byte *visdata; +// +// color24 *lightdata; +// +// char *entities; +// +// // +// // additional model data +// // +// cache_user_t cache; // only access through Mod_Extradata +// +//} model_t; + +//typedef vec_t vec4_t[4]; + +typedef struct alight_s +{ + int ambientlight; // clip at 128 + int shadelight; // clip at 192 - ambientlight + vec3_t color; + float *plightvec; +} alight_t; + +typedef struct auxvert_s +{ + float fv[3]; // viewspace x, y +} auxvert_t; + +#include "custom.h" + +//#define MAX_SCOREBOARDNAME 32 + +// Defined in client.h differently +//typedef struct player_info_s +//{ +// // User id on server +// int userid; +// +// // User info string +// char userinfo[ MAX_INFO_STRING ]; +// +// // Name +// char name[ MAX_SCOREBOARDNAME ]; +// +// // Spectator or not, unused +// int spectator; +// +// int ping; +// int packet_loss; +// +// // skin information +// char model[MAX_QPATH]; +// int topcolor; +// int bottomcolor; +// +// // last frame rendered +// int renderframe; +// +// // Gait frame estimation +// int gaitsequence; +// float gaitframe; +// float gaityaw; +// vec3_t prevgaitorigin; +// +// customization_t customdata; +//} player_info_t; diff --git a/dep/hlsdk/common/commandline.cpp b/dep/hlsdk/common/commandline.cpp new file mode 100644 index 0000000..5efa7d8 --- /dev/null +++ b/dep/hlsdk/common/commandline.cpp @@ -0,0 +1,384 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +class CCommandLine: public ICommandLine { +public: + CCommandLine(); + virtual ~CCommandLine(); + + void CreateCmdLine(const char *commandline); + void CreateCmdLine(int argc, const char *argv[]); + const char *GetCmdLine() const; + + // Check whether a particular parameter exists + const char *CheckParm(const char *psz, char **ppszValue = nullptr) const; + void RemoveParm(const char *pszParm); + void AppendParm(const char *pszParm, const char *pszValues); + + void SetParm(const char *pszParm, const char *pszValues); + void SetParm(const char *pszParm, int iValue); + + // When the commandline contains @name, it reads the parameters from that file + void LoadParametersFromFile(const char *&pSrc, char *&pDst, int maxDestLen); + +private: + // Copy of actual command line + char *m_pszCmdLine; +}; + +CCommandLine g_CmdLine; +ICommandLine *cmdline = &g_CmdLine; + +ICommandLine *CommandLine() +{ + return &g_CmdLine; +} + +CCommandLine::CCommandLine() +{ + m_pszCmdLine = nullptr; +} + +CCommandLine::~CCommandLine() +{ + if (m_pszCmdLine) + { + delete [] m_pszCmdLine; + m_pszCmdLine = nullptr; + } +} + +char *CopyString(const char *src) +{ + if (!src) + return nullptr; + + char *out = (char *)new char[Q_strlen(src) + 1]; + Q_strcpy(out, src); + return out; +} + +// Creates a command line from the arguments passed in +void CCommandLine::CreateCmdLine(int argc, const char *argv[]) +{ + char cmdline[4096] = ""; + const int MAX_CHARS = sizeof(cmdline) - 1; + + for (int i = 0; i < argc; ++i) + { + if (Q_strchr(argv[i], ' ')) + { + Q_strlcat(cmdline, "\""); + Q_strlcat(cmdline, argv[i]); + Q_strlcat(cmdline, "\""); + } + else + { + Q_strlcat(cmdline, argv[i]); + } + + Q_strlcat(cmdline, " "); + } + + cmdline[Q_strlen(cmdline)] = '\0'; + CreateCmdLine(cmdline); +} + +void CCommandLine::LoadParametersFromFile(const char *&pSrc, char *&pDst, int maxDestLen) +{ + // Suck out the file name + char szFileName[ MAX_PATH ]; + char *pOut; + char *pDestStart = pDst; + + // Skip the @ sign + pSrc++; + pOut = szFileName; + + while (*pSrc && *pSrc != ' ') + { + *pOut++ = *pSrc++; +#if 0 + if ((pOut - szFileName) >= (MAX_PATH - 1)) + break; +#endif + } + + *pOut = '\0'; + + // Skip the space after the file name + if (*pSrc) + pSrc++; + + // Now read in parameters from file + FILE *fp = fopen(szFileName, "r"); + if (fp) + { + char c; + c = (char)fgetc(fp); + while (c != EOF) + { + // Turn return characters into spaces + if (c == '\n') + c = ' '; + + *pDst++ = c; + +#if 0 + // Don't go past the end, and allow for our terminating space character AND a terminating null character. + if ((pDst - pDestStart) >= (maxDestLen - 2)) + break; +#endif + + // Get the next character, if there are more + c = (char)fgetc(fp); + } + + // Add a terminating space character + *pDst++ = ' '; + + fclose(fp); + } + else + { + printf("Parameter file '%s' not found, skipping...", szFileName); + } +} + +// Purpose: Create a command line from the passed in string +// Note that if you pass in a @filename, then the routine will read settings from a file instead of the command line +void CCommandLine::CreateCmdLine(const char *commandline) +{ + if (m_pszCmdLine) + { + delete[] m_pszCmdLine; + m_pszCmdLine = nullptr; + } + + char szFull[4096]; + + char *pDst = szFull; + const char *pSrc = commandline; + + bool allowAtSign = true; + + while (*pSrc) + { + if (*pSrc == '@') + { + if (allowAtSign) + { + LoadParametersFromFile(pSrc, pDst, sizeof(szFull) - (pDst - szFull)); + continue; + } + } + + allowAtSign = isspace(*pSrc) != 0; + +#if 0 + // Don't go past the end. + if ((pDst - szFull) >= (sizeof(szFull) - 1)) + break; +#endif + *pDst++ = *pSrc++; + } + + *pDst = '\0'; + + int len = Q_strlen(szFull) + 1; + m_pszCmdLine = new char[len]; + Q_memcpy(m_pszCmdLine, szFull, len); +} + +// Purpose: Remove specified string ( and any args attached to it ) from command line +void CCommandLine::RemoveParm(const char *pszParm) +{ + if (!m_pszCmdLine) + return; + + if (!pszParm || *pszParm == '\0') + return; + + // Search for first occurrence of pszParm + char *p, *found; + char *pnextparam; + int n; + int curlen; + + p = m_pszCmdLine; + while (*p) + { + curlen = Q_strlen(p); + found = Q_strstr(p, pszParm); + + if (!found) + break; + + pnextparam = found + 1; + while (pnextparam && *pnextparam && (*pnextparam != '-') && (*pnextparam != '+')) + pnextparam++; + + if (pnextparam && *pnextparam) + { + // We are either at the end of the string, or at the next param. Just chop out the current param. + // # of characters after this param. + n = curlen - (pnextparam - p); + + Q_memcpy(found, pnextparam, n); + found[n] = '\0'; + } + else + { + // Clear out rest of string. + n = pnextparam - found; + Q_memset(found, 0, n); + } + } + + // Strip and trailing ' ' characters left over. + while (1) + { + int curpos = Q_strlen(m_pszCmdLine); + if (curpos == 0 || m_pszCmdLine[ curpos - 1 ] != ' ') + break; + + m_pszCmdLine[curpos - 1] = '\0'; + } +} + +// Purpose: Append parameter and argument values to command line +void CCommandLine::AppendParm(const char *pszParm, const char *pszValues) +{ + int nNewLength = 0; + char *pCmdString; + + // Parameter. + nNewLength = Q_strlen(pszParm); + + // Values + leading space character. + if (pszValues) + nNewLength += Q_strlen(pszValues) + 1; + + // Terminal 0; + nNewLength++; + + if (!m_pszCmdLine) + { + m_pszCmdLine = new char[ nNewLength ]; + Q_strcpy(m_pszCmdLine, pszParm); + if (pszValues) + { + Q_strcat(m_pszCmdLine, " "); + Q_strcat(m_pszCmdLine, pszValues); + } + + return; + } + + // Remove any remnants from the current Cmd Line. + RemoveParm(pszParm); + + nNewLength += Q_strlen(m_pszCmdLine) + 1 + 1; + + pCmdString = new char[ nNewLength ]; + Q_memset(pCmdString, 0, nNewLength); + + Q_strcpy(pCmdString, m_pszCmdLine); // Copy old command line. + Q_strcat(pCmdString, " "); // Put in a space + Q_strcat(pCmdString, pszParm); + + if (pszValues) + { + Q_strcat(pCmdString, " "); + Q_strcat(pCmdString, pszValues); + } + + // Kill off the old one + delete[] m_pszCmdLine; + + // Point at the new command line. + m_pszCmdLine = pCmdString; +} + +void CCommandLine::SetParm(const char *pszParm, const char *pszValues) +{ + RemoveParm(pszParm); + AppendParm(pszParm, pszValues); +} + +void CCommandLine::SetParm(const char *pszParm, int iValue) +{ + char buf[64]; + Q_snprintf(buf, sizeof(buf), "%d", iValue); + SetParm(pszParm, buf); +} + +// Purpose: Search for the parameter in the current commandline +const char *CCommandLine::CheckParm(const char *psz, char **ppszValue) const +{ + static char sz[128] = ""; + + if (!m_pszCmdLine) + return nullptr; + + if (ppszValue) + *ppszValue = nullptr; + + char *pret = Q_strstr(m_pszCmdLine, psz); + if (!pret || !ppszValue) + return pret; + + // find the next whitespace + char *p1 = pret; + do { + ++p1; + } while (*p1 != ' ' && *p1); + + int i = 0; + char *p2 = p1 + 1; + + do { + if (p2[i] == '\0' || p2[i] == ' ') + break; + + sz[i] = p2[i]; + i++; + } while (i < sizeof(sz)); + + sz[i] = '\0'; + *ppszValue = sz; + + return pret; +} + +const char *CCommandLine::GetCmdLine() const +{ + return m_pszCmdLine; +} diff --git a/dep/hlsdk/common/con_nprint.h b/dep/hlsdk/common/con_nprint.h new file mode 100644 index 0000000..b2a1888 --- /dev/null +++ b/dep/hlsdk/common/con_nprint.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( CON_NPRINTH ) +#define CON_NPRINTH +#ifdef _WIN32 +#pragma once +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct con_nprint_s +{ + int index; // Row # + float time_to_live; // # of seconds before it dissappears + float color[ 3 ]; // RGB colors ( 0.0 -> 1.0 scale ) +} con_nprint_t; + +void Con_NPrintf( int idx, const char *fmt, ... ); +void Con_NXPrintf( struct con_nprint_s *info, const char *fmt, ... ); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/hlsdk/common/const.h b/dep/hlsdk/common/const.h new file mode 100644 index 0000000..5d71a78 --- /dev/null +++ b/dep/hlsdk/common/const.h @@ -0,0 +1,805 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef CONST_H +#define CONST_H +#ifdef _WIN32 +#pragma once +#endif + +// Max # of clients allowed in a server. +#define MAX_CLIENTS 32 + +// How many bits to use to encode an edict. +#define MAX_EDICT_BITS 11 // # of bits needed to represent max edicts +// Max # of edicts in a level (2048) +#define MAX_EDICTS (1<flags +#define FL_FLY (1<<0) // Changes the SV_Movestep() behavior to not need to be on ground +#define FL_SWIM (1<<1) // Changes the SV_Movestep() behavior to not need to be on ground (but stay in water) +#define FL_CONVEYOR (1<<2) +#define FL_CLIENT (1<<3) +#define FL_INWATER (1<<4) +#define FL_MONSTER (1<<5) +#define FL_GODMODE (1<<6) +#define FL_NOTARGET (1<<7) +#define FL_SKIPLOCALHOST (1<<8) // Don't send entity to local host, it's predicting this entity itself +#define FL_ONGROUND (1<<9) // At rest / on the ground +#define FL_PARTIALGROUND (1<<10) // not all corners are valid +#define FL_WATERJUMP (1<<11) // player jumping out of water +#define FL_FROZEN (1<<12) // Player is frozen for 3rd person camera +#define FL_FAKECLIENT (1<<13) // JAC: fake client, simulated server side; don't send network messages to them +#define FL_DUCKING (1<<14) // Player flag -- Player is fully crouched +#define FL_FLOAT (1<<15) // Apply floating force to this entity when in water +#define FL_GRAPHED (1<<16) // worldgraph has this ent listed as something that blocks a connection + +// UNDONE: Do we need these? +#define FL_IMMUNE_WATER (1<<17) +#define FL_IMMUNE_SLIME (1<<18) +#define FL_IMMUNE_LAVA (1<<19) + +#define FL_PROXY (1<<20) // This is a spectator proxy +#define FL_ALWAYSTHINK (1<<21) // Brush model flag -- call think every frame regardless of nextthink - ltime (for constantly changing velocity/path) +#define FL_BASEVELOCITY (1<<22) // Base velocity has been applied this frame (used to convert base velocity into momentum) +#define FL_MONSTERCLIP (1<<23) // Only collide in with monsters who have FL_MONSTERCLIP set +#define FL_ONTRAIN (1<<24) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction. +#define FL_WORLDBRUSH (1<<25) // Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something) +#define FL_SPECTATOR (1<<26) // This client is a spectator, don't run touch functions, etc. +#define FL_CUSTOMENTITY (1<<29) // This is a custom entity +#define FL_KILLME (1<<30) // This entity is marked for death -- This allows the engine to kill ents at the appropriate time +#define FL_DORMANT (1<<31) // Entity is dormant, no updates to client + +// SV_EmitSound2 flags +#define SND_EMIT2_NOPAS (1<<0) // never to do check PAS +#define SND_EMIT2_INVOKER (1<<1) // do not send to the client invoker + +// Engine edict->spawnflags +#define SF_NOTINDEATHMATCH 0x0800 // Do not spawn when deathmatch and loading entities from a file + + +// Goes into globalvars_t.trace_flags +#define FTRACE_SIMPLEBOX (1<<0) // Traceline with a simple box + + +// walkmove modes +#define WALKMOVE_NORMAL 0 // normal walkmove +#define WALKMOVE_WORLDONLY 1 // doesn't hit ANY entities, no matter what the solid type +#define WALKMOVE_CHECKONLY 2 // move, but don't touch triggers + +// edict->movetype values +#define MOVETYPE_NONE 0 // never moves +//#define MOVETYPE_ANGLENOCLIP 1 +//#define MOVETYPE_ANGLECLIP 2 +#define MOVETYPE_WALK 3 // Player only - moving on the ground +#define MOVETYPE_STEP 4 // gravity, special edge handling -- monsters use this +#define MOVETYPE_FLY 5 // No gravity, but still collides with stuff +#define MOVETYPE_TOSS 6 // gravity/collisions +#define MOVETYPE_PUSH 7 // no clip to world, push and crush +#define MOVETYPE_NOCLIP 8 // No gravity, no collisions, still do velocity/avelocity +#define MOVETYPE_FLYMISSILE 9 // extra size to monsters +#define MOVETYPE_BOUNCE 10 // Just like Toss, but reflect velocity when contacting surfaces +#define MOVETYPE_BOUNCEMISSILE 11 // bounce w/o gravity +#define MOVETYPE_FOLLOW 12 // track movement of aiment +#define MOVETYPE_PUSHSTEP 13 // BSP model that needs physics/world collisions (uses nearest hull for world collision) + +// edict->solid values +// NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves +// SOLID only effects OTHER entities colliding with this one when they move - UGH! +#define SOLID_NOT 0 // no interaction with other objects +#define SOLID_TRIGGER 1 // touch on edge, but not blocking +#define SOLID_BBOX 2 // touch on edge, block +#define SOLID_SLIDEBOX 3 // touch on edge, but not an onground +#define SOLID_BSP 4 // bsp clip, touch on edge, block + +// edict->deadflag values +#define DEAD_NO 0 // alive +#define DEAD_DYING 1 // playing death animation or still falling off of a ledge waiting to hit ground +#define DEAD_DEAD 2 // dead. lying still. +#define DEAD_RESPAWNABLE 3 +#define DEAD_DISCARDBODY 4 + +#define DAMAGE_NO 0 +#define DAMAGE_YES 1 +#define DAMAGE_AIM 2 + +// entity effects +#define EF_BRIGHTFIELD 1 // swirling cloud of particles +#define EF_MUZZLEFLASH 2 // single frame ELIGHT on entity attachment 0 +#define EF_BRIGHTLIGHT 4 // DLIGHT centered at entity origin +#define EF_DIMLIGHT 8 // player flashlight +#define EF_INVLIGHT 16 // get lighting from ceiling +#define EF_NOINTERP 32 // don't interpolate the next frame +#define EF_LIGHT 64 // rocket flare glow sprite +#define EF_NODRAW 128 // don't draw entity +#define EF_NIGHTVISION 256 // player nightvision +#define EF_SNIPERLASER 512 // sniper laser effect +#define EF_FIBERCAMERA 1024// fiber camera + + +// entity flags +#define EFLAG_SLERP 1 // do studio interpolation of this entity + +// +// temp entity events +// +#define TE_BEAMPOINTS 0 // beam effect between two points +// coord coord coord (start position) +// coord coord coord (end position) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMENTPOINT 1 // beam effect between point and entity +// short (start entity) +// coord coord coord (end position) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_GUNSHOT 2 // particle effect plus ricochet sound +// coord coord coord (position) + +#define TE_EXPLOSION 3 // additive sprite, 2 dynamic lights, flickering particles, explosion sound, move vertically 8 pps +// coord coord coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (framerate) +// byte (flags) +// +// The Explosion effect has some flags to control performance/aesthetic features: +#define TE_EXPLFLAG_NONE 0 // all flags clear makes default Half-Life explosion +#define TE_EXPLFLAG_NOADDITIVE 1 // sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite) +#define TE_EXPLFLAG_NODLIGHTS 2 // do not render dynamic lights +#define TE_EXPLFLAG_NOSOUND 4 // do not play client explosion sound +#define TE_EXPLFLAG_NOPARTICLES 8 // do not draw particles + + +#define TE_TAREXPLOSION 4 // Quake1 "tarbaby" explosion with sound +// coord coord coord (position) + +#define TE_SMOKE 5 // alphablend sprite, move vertically 30 pps +// coord coord coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (framerate) + +#define TE_TRACER 6 // tracer effect from point to point +// coord, coord, coord (start) +// coord, coord, coord (end) + +#define TE_LIGHTNING 7 // TE_BEAMPOINTS with simplified parameters +// coord, coord, coord (start) +// coord, coord, coord (end) +// byte (life in 0.1's) +// byte (width in 0.1's) +// byte (amplitude in 0.01's) +// short (sprite model index) + +#define TE_BEAMENTS 8 +// short (start entity) +// short (end entity) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_SPARKS 9 // 8 random tracers with gravity, ricochet sprite +// coord coord coord (position) + +#define TE_LAVASPLASH 10 // Quake1 lava splash +// coord coord coord (position) + +#define TE_TELEPORT 11 // Quake1 teleport splash +// coord coord coord (position) + +#define TE_EXPLOSION2 12 // Quake1 colormaped (base palette) particle explosion with sound +// coord coord coord (position) +// byte (starting color) +// byte (num colors) + +#define TE_BSPDECAL 13 // Decal from the .BSP file +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// short (texture index of precached decal texture name) +// short (entity index) +// [optional - only included if previous short is non-zero (not the world)] short (index of model of above entity) + +#define TE_IMPLOSION 14 // tracers moving toward a point +// coord, coord, coord (position) +// byte (radius) +// byte (count) +// byte (life in 0.1's) + +#define TE_SPRITETRAIL 15 // line of moving glow sprites with gravity, fadeout, and collisions +// coord, coord, coord (start) +// coord, coord, coord (end) +// short (sprite index) +// byte (count) +// byte (life in 0.1's) +// byte (scale in 0.1's) +// byte (velocity along vector in 10's) +// byte (randomness of velocity in 10's) + +#define TE_BEAM 16 // obsolete + +#define TE_SPRITE 17 // additive sprite, plays 1 cycle +// coord, coord, coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (brightness) + +#define TE_BEAMSPRITE 18 // A beam with a sprite at the end +// coord, coord, coord (start position) +// coord, coord, coord (end position) +// short (beam sprite index) +// short (end sprite index) + +#define TE_BEAMTORUS 19 // screen aligned beam ring, expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMDISK 20 // disk that expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMCYLINDER 21 // cylinder that expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMFOLLOW 22 // create a line of decaying beam segments until entity stops moving +// short (entity:attachment to follow) +// short (sprite index) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte,byte,byte (color) +// byte (brightness) + +#define TE_GLOWSPRITE 23 +// coord, coord, coord (pos) short (model index) byte (scale / 10) + +#define TE_BEAMRING 24 // connect a beam ring to two entities +// short (start entity) +// short (end entity) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_STREAK_SPLASH 25 // oriented shower of tracers +// coord coord coord (start position) +// coord coord coord (direction vector) +// byte (color) +// short (count) +// short (base speed) +// short (ramdon velocity) + +#define TE_BEAMHOSE 26 // obsolete + +#define TE_DLIGHT 27 // dynamic light, effect world, minor entity effect +// coord, coord, coord (pos) +// byte (radius in 10's) +// byte byte byte (color) +// byte (brightness) +// byte (life in 10's) +// byte (decay rate in 10's) + +#define TE_ELIGHT 28 // point entity light, no world effect +// short (entity:attachment to follow) +// coord coord coord (initial position) +// coord (radius) +// byte byte byte (color) +// byte (life in 0.1's) +// coord (decay rate) + +#define TE_TEXTMESSAGE 29 +// short 1.2.13 x (-1 = center) +// short 1.2.13 y (-1 = center) +// byte Effect 0 = fade in/fade out + // 1 is flickery credits + // 2 is write out (training room) + +// 4 bytes r,g,b,a color1 (text color) +// 4 bytes r,g,b,a color2 (effect color) +// ushort 8.8 fadein time +// ushort 8.8 fadeout time +// ushort 8.8 hold time +// optional ushort 8.8 fxtime (time the highlight lags behing the leading text in effect 2) +// string text message (512 chars max sz string) +#define TE_LINE 30 +// coord, coord, coord startpos +// coord, coord, coord endpos +// short life in 0.1 s +// 3 bytes r, g, b + +#define TE_BOX 31 +// coord, coord, coord boxmins +// coord, coord, coord boxmaxs +// short life in 0.1 s +// 3 bytes r, g, b + +#define TE_KILLBEAM 99 // kill all beams attached to entity +// short (entity) + +#define TE_LARGEFUNNEL 100 +// coord coord coord (funnel position) +// short (sprite index) +// short (flags) + +#define TE_BLOODSTREAM 101 // particle spray +// coord coord coord (start position) +// coord coord coord (spray vector) +// byte (color) +// byte (speed) + +#define TE_SHOWLINE 102 // line of particles every 5 units, dies in 30 seconds +// coord coord coord (start position) +// coord coord coord (end position) + +#define TE_BLOOD 103 // particle spray +// coord coord coord (start position) +// coord coord coord (spray vector) +// byte (color) +// byte (speed) + +#define TE_DECAL 104 // Decal applied to a brush entity (not the world) +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name) +// short (entity index) + +#define TE_FIZZ 105 // create alpha sprites inside of entity, float upwards +// short (entity) +// short (sprite index) +// byte (density) + +#define TE_MODEL 106 // create a moving model that bounces and makes a sound when it hits +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// angle (initial yaw) +// short (model index) +// byte (bounce sound type) +// byte (life in 0.1's) + +#define TE_EXPLODEMODEL 107 // spherical shower of models, picks from set +// coord, coord, coord (origin) +// coord (velocity) +// short (model index) +// short (count) +// byte (life in 0.1's) + +#define TE_BREAKMODEL 108 // box of models or sprites +// coord, coord, coord (position) +// coord, coord, coord (size) +// coord, coord, coord (velocity) +// byte (random velocity in 10's) +// short (sprite or model index) +// byte (count) +// byte (life in 0.1 secs) +// byte (flags) + +#define TE_GUNSHOTDECAL 109 // decal and ricochet sound +// coord, coord, coord (position) +// short (entity index???) +// byte (decal???) + +#define TE_SPRITE_SPRAY 110 // spay of alpha sprites +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// short (sprite index) +// byte (count) +// byte (speed) +// byte (noise) + +#define TE_ARMOR_RICOCHET 111 // quick spark sprite, client ricochet sound. +// coord, coord, coord (position) +// byte (scale in 0.1's) + +#define TE_PLAYERDECAL 112 // ??? +// byte (playerindex) +// coord, coord, coord (position) +// short (entity???) +// byte (decal number???) +// [optional] short (model index???) + +#define TE_BUBBLES 113 // create alpha sprites inside of box, float upwards +// coord, coord, coord (min start position) +// coord, coord, coord (max start position) +// coord (float height) +// short (model index) +// byte (count) +// coord (speed) + +#define TE_BUBBLETRAIL 114 // create alpha sprites along a line, float upwards +// coord, coord, coord (min start position) +// coord, coord, coord (max start position) +// coord (float height) +// short (model index) +// byte (count) +// coord (speed) + +#define TE_BLOODSPRITE 115 // spray of opaque sprite1's that fall, single sprite2 for 1..2 secs (this is a high-priority tent) +// coord, coord, coord (position) +// short (sprite1 index) +// short (sprite2 index) +// byte (color) +// byte (scale) + +#define TE_WORLDDECAL 116 // Decal applied to the world brush +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name) + +#define TE_WORLDDECALHIGH 117 // Decal (with texture index > 256) applied to world brush +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name - 256) + +#define TE_DECALHIGH 118 // Same as TE_DECAL, but the texture index was greater than 256 +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name - 256) +// short (entity index) + +#define TE_PROJECTILE 119 // Makes a projectile (like a nail) (this is a high-priority tent) +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// short (modelindex) +// byte (life) +// byte (owner) projectile won't collide with owner (if owner == 0, projectile will hit any client). + +#define TE_SPRAY 120 // Throws a shower of sprites or models +// coord, coord, coord (position) +// coord, coord, coord (direction) +// short (modelindex) +// byte (count) +// byte (speed) +// byte (noise) +// byte (rendermode) + +#define TE_PLAYERSPRITES 121 // sprites emit from a player's bounding box (ONLY use for players!) +// byte (playernum) +// short (sprite modelindex) +// byte (count) +// byte (variance) (0 = no variance in size) (10 = 10% variance in size) + +#define TE_PARTICLEBURST 122 // very similar to lavasplash. +// coord (origin) +// short (radius) +// byte (particle color) +// byte (duration * 10) (will be randomized a bit) + +#define TE_FIREFIELD 123 // makes a field of fire. +// coord (origin) +// short (radius) (fire is made in a square around origin. -radius, -radius to radius, radius) +// short (modelindex) +// byte (count) +// byte (flags) +// byte (duration (in seconds) * 10) (will be randomized a bit) +// +// to keep network traffic low, this message has associated flags that fit into a byte: +#define TEFIRE_FLAG_ALLFLOAT 1 // all sprites will drift upwards as they animate +#define TEFIRE_FLAG_SOMEFLOAT 2 // some of the sprites will drift upwards. (50% chance) +#define TEFIRE_FLAG_LOOP 4 // if set, sprite plays at 15 fps, otherwise plays at whatever rate stretches the animation over the sprite's duration. +#define TEFIRE_FLAG_ALPHA 8 // if set, sprite is rendered alpha blended at 50% else, opaque +#define TEFIRE_FLAG_PLANAR 16 // if set, all fire sprites have same initial Z instead of randomly filling a cube. +#define TEFIRE_FLAG_ADDITIVE 32 // if set, sprite is rendered non-opaque with additive + +#define TE_PLAYERATTACHMENT 124 // attaches a TENT to a player (this is a high-priority tent) +// byte (entity index of player) +// coord (vertical offset) ( attachment origin.z = player origin.z + vertical offset ) +// short (model index) +// short (life * 10 ); + +#define TE_KILLPLAYERATTACHMENTS 125 // will expire all TENTS attached to a player. +// byte (entity index of player) + +#define TE_MULTIGUNSHOT 126 // much more compact shotgun message +// This message is used to make a client approximate a 'spray' of gunfire. +// Any weapon that fires more than one bullet per frame and fires in a bit of a spread is +// a good candidate for MULTIGUNSHOT use. (shotguns) +// +// NOTE: This effect makes the client do traces for each bullet, these client traces ignore +// entities that have studio models.Traces are 4096 long. +// +// coord (origin) +// coord (origin) +// coord (origin) +// coord (direction) +// coord (direction) +// coord (direction) +// coord (x noise * 100) +// coord (y noise * 100) +// byte (count) +// byte (bullethole decal texture index) + +#define TE_USERTRACER 127 // larger message than the standard tracer, but allows some customization. +// coord (origin) +// coord (origin) +// coord (origin) +// coord (velocity) +// coord (velocity) +// coord (velocity) +// byte ( life * 10 ) +// byte ( color ) this is an index into an array of color vectors in the engine. (0 - ) +// byte ( length * 10 ) + + + +#define MSG_BROADCAST 0 // unreliable to all +#define MSG_ONE 1 // reliable to one (msg_entity) +#define MSG_ALL 2 // reliable to all +#define MSG_INIT 3 // write to the init string +#define MSG_PVS 4 // Ents in PVS of org +#define MSG_PAS 5 // Ents in PAS of org +#define MSG_PVS_R 6 // Reliable to PVS +#define MSG_PAS_R 7 // Reliable to PAS +#define MSG_ONE_UNRELIABLE 8 // Send to one client, but don't put in reliable stream, put in unreliable datagram ( could be dropped ) +#define MSG_SPEC 9 // Sends to all spectator proxies + +// contents of a spot in the world +#define CONTENTS_EMPTY -1 +#define CONTENTS_SOLID -2 +#define CONTENTS_WATER -3 +#define CONTENTS_SLIME -4 +#define CONTENTS_LAVA -5 +#define CONTENTS_SKY -6 +/* These additional contents constants are defined in bspfile.h +#define CONTENTS_ORIGIN -7 // removed at csg time +#define CONTENTS_CLIP -8 // changed to contents_solid +#define CONTENTS_CURRENT_0 -9 +#define CONTENTS_CURRENT_90 -10 +#define CONTENTS_CURRENT_180 -11 +#define CONTENTS_CURRENT_270 -12 +#define CONTENTS_CURRENT_UP -13 +#define CONTENTS_CURRENT_DOWN -14 + +#define CONTENTS_TRANSLUCENT -15 +*/ +#define CONTENTS_LADDER -16 + +#define CONTENT_FLYFIELD -17 +#define CONTENT_GRAVITY_FLYFIELD -18 +#define CONTENT_FOG -19 + +#define CONTENT_EMPTY -1 +#define CONTENT_SOLID -2 +#define CONTENT_WATER -3 +#define CONTENT_SLIME -4 +#define CONTENT_LAVA -5 +#define CONTENT_SKY -6 + +// channels +#define CHAN_AUTO 0 +#define CHAN_WEAPON 1 +#define CHAN_VOICE 2 +#define CHAN_ITEM 3 +#define CHAN_BODY 4 +#define CHAN_STREAM 5 // allocate stream channel from the static or dynamic area +#define CHAN_STATIC 6 // allocate channel from the static area +#define CHAN_NETWORKVOICE_BASE 7 // voice data coming across the network +#define CHAN_NETWORKVOICE_END 500 // network voice data reserves slots (CHAN_NETWORKVOICE_BASE through CHAN_NETWORKVOICE_END). +#define CHAN_BOT 501 // channel used for bot chatter. + +// attenuation values +#define ATTN_NONE 0 +#define ATTN_NORM (float)0.8 +#define ATTN_IDLE (float)2 +#define ATTN_STATIC (float)1.25 + +// 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 + +// volume values +#define VOL_NORM 1.0 + +// plats +#define PLAT_LOW_TRIGGER 1 + +// Trains +#define SF_TRAIN_WAIT_RETRIGGER 1 +#define SF_TRAIN_START_ON 4 // Train is initially moving +#define SF_TRAIN_PASSABLE 8 // Train is not solid -- used to make water trains + +// buttons +#ifndef IN_BUTTONS_H +#include "in_buttons.h" +#endif + +// Break Model Defines + +#define BREAK_TYPEMASK 0x4F +#define BREAK_GLASS 0x01 +#define BREAK_METAL 0x02 +#define BREAK_FLESH 0x04 +#define BREAK_WOOD 0x08 + +#define BREAK_SMOKE 0x10 +#define BREAK_TRANS 0x20 +#define BREAK_CONCRETE 0x40 +#define BREAK_2 0x80 + +// Colliding temp entity sounds + +#define BOUNCE_GLASS BREAK_GLASS +#define BOUNCE_METAL BREAK_METAL +#define BOUNCE_FLESH BREAK_FLESH +#define BOUNCE_WOOD BREAK_WOOD +#define BOUNCE_SHRAP 0x10 +#define BOUNCE_SHELL 0x20 +#define BOUNCE_CONCRETE BREAK_CONCRETE +#define BOUNCE_SHOTSHELL 0x80 + +// Temp entity bounce sound types +#define TE_BOUNCE_NULL 0 +#define TE_BOUNCE_SHELL 1 +#define TE_BOUNCE_SHOTSHELL 2 + +// Rendering constants +enum +{ + kRenderNormal, // src + kRenderTransColor, // c*a+dest*(1-a) + kRenderTransTexture, // src*a+dest*(1-a) + kRenderGlow, // src*a+dest -- No Z buffer checks + kRenderTransAlpha, // src*srca+dest*(1-srca) + kRenderTransAdd, // src*a+dest +}; + +enum +{ + kRenderFxNone = 0, + kRenderFxPulseSlow, + kRenderFxPulseFast, + kRenderFxPulseSlowWide, + kRenderFxPulseFastWide, + kRenderFxFadeSlow, + kRenderFxFadeFast, + kRenderFxSolidSlow, + kRenderFxSolidFast, + kRenderFxStrobeSlow, + kRenderFxStrobeFast, + kRenderFxStrobeFaster, + kRenderFxFlickerSlow, + kRenderFxFlickerFast, + kRenderFxNoDissipation, + kRenderFxDistort, // Distort/scale/translate flicker + kRenderFxHologram, // kRenderFxDistort + distance fade + kRenderFxDeadPlayer, // kRenderAmt is the player index + kRenderFxExplode, // Scale up really big! + kRenderFxGlowShell, // Glowing Shell + kRenderFxClampMinScale, // Keep this sprite from getting very small (SPRITES only!) + kRenderFxLightMultiplier, //CTM !!!CZERO added to tell the studiorender that the value in iuser2 is a lightmultiplier +}; + + +typedef unsigned int func_t; + +typedef unsigned char byte; +typedef unsigned short word; +#define _DEF_BYTE_ + +#undef true +#undef false + +#ifndef __cplusplus +typedef enum {false, true} qboolean; +#else +typedef int qboolean; +#endif + +typedef struct +{ + byte r, g, b; +} color24; + +typedef struct +{ + unsigned r, g, b, a; +} colorVec; + +#ifdef _WIN32 +#pragma pack(push,2) +#endif + +typedef struct +{ + unsigned short r, g, b, a; +} PackedColorVec; + +#ifdef _WIN32 +#pragma pack(pop) +#endif +typedef struct link_s +{ + struct link_s *prev, *next; +} link_t; + +typedef struct edict_s edict_t; + +typedef struct +{ + vec3_t normal; + float dist; +} plane_t; + +typedef struct +{ + qboolean allsolid; // if true, plane is not valid + qboolean startsolid; // if true, the initial point was in a solid area + qboolean inopen, inwater; + float fraction; // time completed, 1.0 = didn't hit anything + vec3_t endpos; // final position + plane_t plane; // surface normal at impact + edict_t * ent; // entity the surface is on + int hitgroup; // 0 == generic, non zero is specific body part +} trace_t; + +#endif // CONST_H diff --git a/dep/hlsdk/common/crc.h b/dep/hlsdk/common/crc.h new file mode 100644 index 0000000..f7c6bb2 --- /dev/null +++ b/dep/hlsdk/common/crc.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +/* crc.h */ +#pragma once + +#include "quakedef.h" + +typedef unsigned int CRC32_t; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void CRC32_Init(CRC32_t *pulCRC); +CRC32_t CRC32_Final(CRC32_t pulCRC); +void CRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch); +void CRC32_ProcessBuffer(CRC32_t *pulCRC, void *pBuffer, int nBuffer); +BOOL CRC_File(CRC32_t *crcvalue, char *pszFileName); + +#ifdef __cplusplus +} +#endif + +byte COM_BlockSequenceCRCByte(byte *base, int length, int sequence); +int CRC_MapFile(CRC32_t *crcvalue, char *pszFileName); diff --git a/dep/hlsdk/common/cvardef.h b/dep/hlsdk/common/cvardef.h new file mode 100644 index 0000000..7bba22b --- /dev/null +++ b/dep/hlsdk/common/cvardef.h @@ -0,0 +1,50 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef CVARDEF_H +#define CVARDEF_H + +#define FCVAR_ARCHIVE (1<<0) // set to cause it to be saved to vars.rc +#define FCVAR_USERINFO (1<<1) // changes the client's info string +#define FCVAR_SERVER (1<<2) // notifies players when changed +#define FCVAR_EXTDLL (1<<3) // defined by external DLL +#define FCVAR_CLIENTDLL (1<<4) // defined by the client dll +#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as value +#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server. +#define FCVAR_PRINTABLEONLY (1<<7) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ). +#define FCVAR_UNLOGGED (1<<8) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log +#define FCVAR_NOEXTRAWHITEPACE (1<<9) // strip trailing/leading white space from this cvar + +typedef struct cvar_s +{ + const char *name; + char *string; + int flags; + float value; + struct cvar_s *next; +} cvar_t; + +using cvar_callback_t = void (*)(const char *pszNewValue); + +struct cvar_listener_t +{ + cvar_listener_t(const char *var_name, cvar_callback_t handler) : + func(handler), name(var_name) {} + + cvar_callback_t func; + const char *name; +}; + +#endif // CVARDEF_H diff --git a/dep/hlsdk/common/demo_api.h b/dep/hlsdk/common/demo_api.h new file mode 100644 index 0000000..8284a81 --- /dev/null +++ b/dep/hlsdk/common/demo_api.h @@ -0,0 +1,31 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( DEMO_APIH ) +#define DEMO_APIH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct demo_api_s +{ + int ( *IsRecording ) ( void ); + int ( *IsPlayingback ) ( void ); + int ( *IsTimeDemo ) ( void ); + void ( *WriteBuffer ) ( int size, unsigned char *buffer ); +} demo_api_t; + +extern demo_api_t demoapi; + +#endif diff --git a/dep/hlsdk/common/director_cmds.h b/dep/hlsdk/common/director_cmds.h new file mode 100644 index 0000000..4c8fdd5 --- /dev/null +++ b/dep/hlsdk/common/director_cmds.h @@ -0,0 +1,38 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// director_cmds.h +// sub commands for svc_director + +#define DRC_ACTIVE 0 // tells client that he's an spectator and will get director command +#define DRC_STATUS 1 // send status infos about proxy +#define DRC_CAMERA 2 // set the actual director camera position +#define DRC_EVENT 3 // informs the dircetor about ann important game event + + +#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important) +#define DRC_FLAG_SIDE (1<<4) +#define DRC_FLAG_DRAMATIC (1<<5) + + + +// commands of the director API function CallDirectorProc(...) + +#define DRCAPI_NOP 0 // no operation +#define DRCAPI_ACTIVE 1 // de/acivates director mode in engine +#define DRCAPI_STATUS 2 // request proxy information +#define DRCAPI_SETCAM 3 // set camera n to given position and angle +#define DRCAPI_GETCAM 4 // request camera n position and angle +#define DRCAPI_DIRPLAY 5 // set director time and play with normal speed +#define DRCAPI_DIRFREEZE 6 // freeze directo at this time +#define DRCAPI_SETVIEWMODE 7 // overview or 4 cameras +#define DRCAPI_SETOVERVIEWPARAMS 8 // sets parameter for overview mode +#define DRCAPI_SETFOCUS 9 // set the camera which has the input focus +#define DRCAPI_GETTARGETS 10 // queries engine for player list +#define DRCAPI_SETVIEWPOINTS 11 // gives engine all waypoints + + diff --git a/dep/hlsdk/common/dlight.h b/dep/hlsdk/common/dlight.h new file mode 100644 index 0000000..f869c98 --- /dev/null +++ b/dep/hlsdk/common/dlight.h @@ -0,0 +1,33 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( DLIGHTH ) +#define DLIGHTH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct dlight_s +{ + vec3_t origin; + float radius; + color24 color; + float die; // stop lighting after this time + float decay; // drop this each second + float minlight; // don't add when contributing less + int key; + qboolean dark; // subtracts light instead of adding +} dlight_t; + +#endif diff --git a/dep/hlsdk/common/dll_state.h b/dep/hlsdk/common/dll_state.h new file mode 100644 index 0000000..ad16296 --- /dev/null +++ b/dep/hlsdk/common/dll_state.h @@ -0,0 +1,23 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +//DLL State Flags + +#define DLL_INACTIVE 0 // no dll +#define DLL_ACTIVE 1 // dll is running +#define DLL_PAUSED 2 // dll is paused +#define DLL_CLOSE 3 // closing down dll +#define DLL_TRANS 4 // Level Transition + +// DLL Pause reasons + +#define DLL_NORMAL 0 // User hit Esc or something. +#define DLL_QUIT 4 // Quit now +#define DLL_RESTART 5 // Switch to launcher for linux, does a quit but returns 1 + +// DLL Substate info ( not relevant ) +#define ENG_NORMAL (1<<0) diff --git a/dep/hlsdk/common/entity_state.h b/dep/hlsdk/common/entity_state.h new file mode 100644 index 0000000..bdfd19e --- /dev/null +++ b/dep/hlsdk/common/entity_state.h @@ -0,0 +1,198 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef ENTITY_STATE_H +#define ENTITY_STATE_H +#ifdef _WIN32 +#pragma once +#endif + +#include "const.h" + + +// For entityType below +#define ENTITY_NORMAL (1<<0) +#define ENTITY_BEAM (1<<1) +#define ENTITY_UNINITIALIZED (1<<30) + +// Entity state is used for the baseline and for delta compression of a packet of +// entities that is sent to a client. +typedef struct entity_state_s entity_state_t; + +struct entity_state_s +{ +// Fields which are filled in by routines outside of delta compression + int entityType; + // Index into cl_entities array for this entity. + int number; + float msg_time; + + // Message number last time the player/entity state was updated. + int messagenum; + + // Fields which can be transitted and reconstructed over the network stream + vec3_t origin; + vec3_t angles; + + int modelindex; + int sequence; + float frame; + int colormap; + short skin; + short solid; + int effects; + float scale; + + byte eflags; + + // Render information + int rendermode; + int renderamt; + color24 rendercolor; + int renderfx; + + int movetype; + float animtime; + float framerate; + int body; + byte controller[4]; + byte blending[4]; + vec3_t velocity; + + // Send bbox down to client for use during prediction. + vec3_t mins; + vec3_t maxs; + + int aiment; + // If owned by a player, the index of that player ( for projectiles ). + int owner; + + // Friction, for prediction. + float friction; + // Gravity multiplier + float gravity; + +// PLAYER SPECIFIC + int team; + int playerclass; + int health; + qboolean spectator; + int weaponmodel; + int gaitsequence; + // If standing on conveyor, e.g. + vec3_t basevelocity; + // Use the crouched hull, or the regular player hull. + int usehull; + // Latched buttons last time state updated. + int oldbuttons; + // -1 = in air, else pmove entity number + int onground; + int iStepLeft; + // How fast we are falling + float flFallVelocity; + + float fov; + int weaponanim; + + // Parametric movement overrides + vec3_t startpos; + vec3_t endpos; + float impacttime; + float starttime; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; +}; + +#include "pm_info.h" + +typedef struct clientdata_s +{ + vec3_t origin; + vec3_t velocity; + + int viewmodel; + vec3_t punchangle; + int flags; + int waterlevel; + int watertype; + vec3_t view_ofs; + float health; + + int bInDuck; + + int weapons; // remove? + + int flTimeStepSound; + int flDuckTime; + int flSwimTime; + int waterjumptime; + + float maxspeed; + + float fov; + int weaponanim; + + int m_iId; + int ammo_shells; + int ammo_nails; + int ammo_cells; + int ammo_rockets; + float m_flNextAttack; + + int tfstate; + + int pushmsec; + + int deadflag; + + char physinfo[ MAX_PHYSINFO_STRING ]; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; +} clientdata_t; + +#include "weaponinfo.h" + +typedef struct local_state_s +{ + entity_state_t playerstate; + clientdata_t client; + weapon_data_t weapondata[ 64 ]; +} local_state_t; + +#endif // ENTITY_STATE_H diff --git a/dep/hlsdk/common/entity_types.h b/dep/hlsdk/common/entity_types.h new file mode 100644 index 0000000..ff783df --- /dev/null +++ b/dep/hlsdk/common/entity_types.h @@ -0,0 +1,26 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// entity_types.h +#if !defined( ENTITY_TYPESH ) +#define ENTITY_TYPESH + +#define ET_NORMAL 0 +#define ET_PLAYER 1 +#define ET_TEMPENTITY 2 +#define ET_BEAM 3 +// BMODEL or SPRITE that was split across BSP nodes +#define ET_FRAGMENTED 4 + +#endif // !ENTITY_TYPESH diff --git a/dep/hlsdk/common/enums.h b/dep/hlsdk/common/enums.h new file mode 100644 index 0000000..ad8bfe0 --- /dev/null +++ b/dep/hlsdk/common/enums.h @@ -0,0 +1,28 @@ +/*** + * + * Copyright (c) 2009, Valve LLC. All rights reserved. + * + * This product contains software technology licensed from Id + * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. + * All Rights Reserved. + * + * Use, distribution, and modification of this source code and/or resulting + * object code is restricted to non-commercial enhancements to products from + * Valve LLC. All other use, distribution, or modification is prohibited + * without written permission from Valve LLC. + * + ****/ + +#ifndef ENUMS_H +#define ENUMS_H + +// Used as array indexer +typedef enum netsrc_s +{ + NS_CLIENT = 0, + NS_SERVER, + NS_MULTICAST, // xxxMO + NS_MAX +} netsrc_t; + +#endif diff --git a/dep/hlsdk/common/event_api.h b/dep/hlsdk/common/event_api.h new file mode 100644 index 0000000..722dfe2 --- /dev/null +++ b/dep/hlsdk/common/event_api.h @@ -0,0 +1,51 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( EVENT_APIH ) +#define EVENT_APIH +#ifdef _WIN32 +#pragma once +#endif + +#define EVENT_API_VERSION 1 + +typedef struct event_api_s +{ + int version; + void ( *EV_PlaySound ) ( int ent, float *origin, int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch ); + void ( *EV_StopSound ) ( int ent, int channel, const char *sample ); + int ( *EV_FindModelIndex )( const char *pmodel ); + int ( *EV_IsLocal ) ( int playernum ); + int ( *EV_LocalPlayerDucking ) ( void ); + void ( *EV_LocalPlayerViewheight ) ( float * ); + void ( *EV_LocalPlayerBounds ) ( int hull, float *mins, float *maxs ); + int ( *EV_IndexFromTrace) ( struct pmtrace_s *pTrace ); + struct physent_s *( *EV_GetPhysent ) ( int idx ); + void ( *EV_SetUpPlayerPrediction ) ( int dopred, int bIncludeLocalClient ); + void ( *EV_PushPMStates ) ( void ); + void ( *EV_PopPMStates ) ( void ); + void ( *EV_SetSolidPlayers ) (int playernum); + void ( *EV_SetTraceHull ) ( int hull ); + void ( *EV_PlayerTrace ) ( float *start, float *end, int traceFlags, int ignore_pe, struct pmtrace_s *tr ); + void ( *EV_WeaponAnimation ) ( int sequence, int body ); + unsigned short ( *EV_PrecacheEvent ) ( int type, const char* psz ); + void ( *EV_PlaybackEvent ) ( int flags, const struct edict_s *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); + const char *( *EV_TraceTexture ) ( int ground, float *vstart, float *vend ); + void ( *EV_StopAllSounds ) ( int entnum, int entchannel ); + void ( *EV_KillEvents ) ( int entnum, const char *eventname ); +} event_api_t; + +extern event_api_t eventapi; + +#endif diff --git a/dep/hlsdk/common/event_args.h b/dep/hlsdk/common/event_args.h new file mode 100644 index 0000000..99dd49a --- /dev/null +++ b/dep/hlsdk/common/event_args.h @@ -0,0 +1,50 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( EVENT_ARGSH ) +#define EVENT_ARGSH +#ifdef _WIN32 +#pragma once +#endif + +// Event was invoked with stated origin +#define FEVENT_ORIGIN ( 1<<0 ) + +// Event was invoked with stated angles +#define FEVENT_ANGLES ( 1<<1 ) + +typedef struct event_args_s +{ + int flags; + + // Transmitted + int entindex; + + float origin[3]; + float angles[3]; + float velocity[3]; + + int ducking; + + float fparam1; + float fparam2; + + int iparam1; + int iparam2; + + int bparam1; + int bparam2; +} event_args_t; + +#endif diff --git a/dep/hlsdk/common/event_flags.h b/dep/hlsdk/common/event_flags.h new file mode 100644 index 0000000..43f804f --- /dev/null +++ b/dep/hlsdk/common/event_flags.h @@ -0,0 +1,47 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( EVENT_FLAGSH ) +#define EVENT_FLAGSH +#ifdef _WIN32 +#pragma once +#endif + +// Skip local host for event send. +#define FEV_NOTHOST (1<<0) + +// Send the event reliably. You must specify the origin and angles and use +// PLAYBACK_EVENT_FULL for this to work correctly on the server for anything +// that depends on the event origin/angles. I.e., the origin/angles are not +// taken from the invoking edict for reliable events. +#define FEV_RELIABLE (1<<1) + +// Don't restrict to PAS/PVS, send this event to _everybody_ on the server ( useful for stopping CHAN_STATIC +// sounds started by client event when client is not in PVS anymore ( hwguy in TFC e.g. ). +#define FEV_GLOBAL (1<<2) + +// If this client already has one of these events in its queue, just update the event instead of sending it as a duplicate +// +#define FEV_UPDATE (1<<3) + +// Only send to entity specified as the invoker +#define FEV_HOSTONLY (1<<4) + +// Only send if the event was created on the server. +#define FEV_SERVER (1<<5) + +// Only issue event client side ( from shared code ) +#define FEV_CLIENT (1<<6) + +#endif diff --git a/dep/hlsdk/common/hltv.h b/dep/hlsdk/common/hltv.h new file mode 100644 index 0000000..ea420a3 --- /dev/null +++ b/dep/hlsdk/common/hltv.h @@ -0,0 +1,60 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// hltv.h +// all shared consts between server, clients and proxy + +#ifndef HLTV_H +#define HLTV_H + +#define TYPE_CLIENT 0 // client is a normal HL client (default) +#define TYPE_PROXY 1 // client is another proxy +#define TYPE_DIRECTOR 2 +#define TYPE_COMMENTATOR 3 // client is a commentator +#define TYPE_DEMO 4 // client is a demo file + +// sub commands of svc_hltv: +#define HLTV_ACTIVE 0 // tells client that he's an spectator and will get director commands +#define HLTV_STATUS 1 // send status infos about proxy +#define HLTV_LISTEN 2 // tell client to listen to a multicast stream + +// director command types: +#define DRC_CMD_NONE 0 // NULL director command +#define DRC_CMD_START 1 // start director mode +#define DRC_CMD_EVENT 2 // informs about director command +#define DRC_CMD_MODE 3 // switches camera modes +#define DRC_CMD_CAMERA 4 // set fixed camera +#define DRC_CMD_TIMESCALE 5 // sets time scale +#define DRC_CMD_MESSAGE 6 // send HUD centerprint +#define DRC_CMD_SOUND 7 // plays a particular sound +#define DRC_CMD_STATUS 8 // HLTV broadcast status +#define DRC_CMD_BANNER 9 // set GUI banner +#define DRC_CMD_STUFFTEXT 10 // like the normal svc_stufftext but as director command +#define DRC_CMD_CHASE 11 // chase a certain player +#define DRC_CMD_INEYE 12 // view player through own eyes +#define DRC_CMD_MAP 13 // show overview map +#define DRC_CMD_CAMPATH 14 // define camera waypoint +#define DRC_CMD_WAYPOINTS 15 // start moving camera, inetranl message + +#define DRC_CMD_LAST 15 + +// DRC_CMD_EVENT event flags +#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important) +#define DRC_FLAG_SIDE (1<<4) // +#define DRC_FLAG_DRAMATIC (1<<5) // is a dramatic scene +#define DRC_FLAG_SLOWMOTION (1<<6) // would look good in SloMo +#define DRC_FLAG_FACEPLAYER (1<<7) // player is doning something (reload/defuse bomb etc) +#define DRC_FLAG_INTRO (1<<8) // is a introduction scene +#define DRC_FLAG_FINAL (1<<9) // is a final scene +#define DRC_FLAG_NO_RANDOM (1<<10) // don't randomize event data + +// DRC_CMD_WAYPOINT flags +#define DRC_FLAG_STARTPATH 1 // end with speed 0.0 +#define DRC_FLAG_SLOWSTART 2 // start with speed 0.0 +#define DRC_FLAG_SLOWEND 4 // end with speed 0.0 + +#endif // HLTV_H diff --git a/dep/hlsdk/common/in_buttons.h b/dep/hlsdk/common/in_buttons.h new file mode 100644 index 0000000..4196a2d --- /dev/null +++ b/dep/hlsdk/common/in_buttons.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef IN_BUTTONS_H +#define IN_BUTTONS_H +#ifdef _WIN32 +#pragma once +#endif + +#define IN_ATTACK (1 << 0) +#define IN_JUMP (1 << 1) +#define IN_DUCK (1 << 2) +#define IN_FORWARD (1 << 3) +#define IN_BACK (1 << 4) +#define IN_USE (1 << 5) +#define IN_CANCEL (1 << 6) +#define IN_LEFT (1 << 7) +#define IN_RIGHT (1 << 8) +#define IN_MOVELEFT (1 << 9) +#define IN_MOVERIGHT (1 << 10) +#define IN_ATTACK2 (1 << 11) +#define IN_RUN (1 << 12) +#define IN_RELOAD (1 << 13) +#define IN_ALT1 (1 << 14) +#define IN_SCORE (1 << 15) // Used by client.dll for when scoreboard is held down + +#endif // IN_BUTTONS_H diff --git a/dep/hlsdk/common/ivoicetweak.h b/dep/hlsdk/common/ivoicetweak.h new file mode 100644 index 0000000..da568c5 --- /dev/null +++ b/dep/hlsdk/common/ivoicetweak.h @@ -0,0 +1,38 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef IVOICETWEAK_H +#define IVOICETWEAK_H +#ifdef _WIN32 +#pragma once +#endif + +// These provide access to the voice controls. +typedef enum +{ + MicrophoneVolume=0, // values 0-1. + OtherSpeakerScale, // values 0-1. Scales how loud other players are. + MicBoost, // 20 db gain to voice input +} VoiceTweakControl; + + +typedef struct IVoiceTweak_s +{ + // These turn voice tweak mode on and off. While in voice tweak mode, the user's voice is echoed back + // without sending to the server. + int (*StartVoiceTweakMode)(); // Returns 0 on error. + void (*EndVoiceTweakMode)(); + + // Get/set control values. + void (*SetControlFloat)(VoiceTweakControl iControl, float value); + float (*GetControlFloat)(VoiceTweakControl iControl); + + int (*GetSpeakingVolume)(); +} IVoiceTweak; + + +#endif // IVOICETWEAK_H diff --git a/dep/hlsdk/common/kbutton.h b/dep/hlsdk/common/kbutton.h new file mode 100644 index 0000000..5607568 --- /dev/null +++ b/dep/hlsdk/common/kbutton.h @@ -0,0 +1,41 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef KBUTTON_H +#define KBUTTON_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct kbutton_s +{ + int down[2]; + int state; +} kbutton_t; + +#endif // KBUTTON_H diff --git a/dep/hlsdk/common/mathlib.h b/dep/hlsdk/common/mathlib.h new file mode 100644 index 0000000..757a7f4 --- /dev/null +++ b/dep/hlsdk/common/mathlib.h @@ -0,0 +1,176 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MATHLIB_H +#define MATHLIB_H +#ifdef _WIN32 +#pragma once +#endif + +typedef float vec_t; + +#if !defined DID_VEC3_T_DEFINE && !defined vec3_t +#define DID_VEC3_T_DEFINE +typedef vec_t vec3_t[3]; +#endif + +typedef vec_t vec4_t[4]; +typedef int fixed16_t; + +typedef union DLONG_u +{ + int i[2]; + double d; + float f; +} DLONG; + +#define M_PI 3.14159265358979323846 + +#ifdef __cplusplus +#ifdef min +#undef min +#endif + +#ifdef max +#undef max +#endif + +#ifdef clamp +#undef clamp +#endif + +template +inline T min(T a, T b) +{ + return (a < b) ? a : b; +} + +template +inline T max(T a, T b) +{ + return (a < b) ? b : a; +} + +template +inline T clamp(T a, T min, T max) +{ + return (a > max) ? max : (a < min) ? min : a; +} + +template +inline T bswap(T s) +{ + switch (sizeof(T)) + { + case 2: {auto res = __builtin_bswap16(*(uint16 *)&s); return *(T *)&res; } + case 4: {auto res = __builtin_bswap32(*(uint32 *)&s); return *(T *)&res; } + case 8: {auto res = __builtin_bswap64(*(uint64 *)&s); return *(T *)&res; } + default: return s; + } +} +#else // __cplusplus +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif + +#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) +#endif // __cplusplus + +inline void VectorAdd(const vec_t *veca, const vec_t *vecb, vec_t *out) +{ + out[0] = veca[0] + vecb[0]; + out[1] = veca[1] + vecb[1]; + out[2] = veca[2] + vecb[2]; +} + +inline void VectorSubtract(const vec_t *veca, const vec_t *vecb, vec_t *out) +{ + out[0] = veca[0] - vecb[0]; + out[1] = veca[1] - vecb[1]; + out[2] = veca[2] - vecb[2]; +} + +inline void VectorMA(const vec_t *veca, float scale, const vec_t *vecm, vec_t *out) +{ + out[0] = scale * vecm[0] + veca[0]; + out[1] = scale * vecm[1] + veca[1]; + out[2] = scale * vecm[2] + veca[2]; +} + +inline void VectorScale(const vec_t *in, float scale, vec_t *out) +{ + out[0] = scale * in[0]; + out[1] = scale * in[1]; + out[2] = scale * in[2]; +} + +inline void VectorClear(vec_t *in) +{ + in[0] = 0.0f; + in[1] = 0.0f; + in[2] = 0.0f; +} + +inline void VectorCopy(const vec_t *in, vec_t *out) +{ + out[0] = in[0]; + out[1] = in[1]; + out[2] = in[2]; +} + +inline void VectorNegate(const vec_t *in, vec_t *out) +{ + out[0] = -in[0]; + out[1] = -in[1]; + out[2] = -in[2]; +} + +inline void VectorInverse(vec_t *in) +{ + in[0] = -in[0]; + in[1] = -in[1]; + in[2] = -in[2]; +} + +inline void VectorAverage(const vec_t *veca, const vec_t *vecb, vec_t *out) +{ + out[0] = (veca[0] + vecb[0]) * 0.5f; + out[1] = (veca[1] + vecb[1]) * 0.5f; + out[2] = (veca[2] + vecb[2]) * 0.5f; +} + +inline bool VectorIsZero(const vec_t *in) +{ + return (in[0] == 0.0f && in[1] == 0.0f && in[2] == 0.0f); +} + +#endif // MATHLIB_H diff --git a/dep/hlsdk/common/md5.h b/dep/hlsdk/common/md5.h new file mode 100644 index 0000000..637ba0f --- /dev/null +++ b/dep/hlsdk/common/md5.h @@ -0,0 +1,34 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#pragma once + +#include + +// MD5 Hash +typedef struct +{ + unsigned int buf[4]; + unsigned int bits[2]; + unsigned char in[64]; +} MD5Context_t; + +void MD5Init(MD5Context_t *ctx); +void MD5Update(MD5Context_t *ctx, const unsigned char *buf, unsigned int len); +void MD5Final(unsigned char digest[16], MD5Context_t *ctx); +void MD5Transform(unsigned int buf[4], const unsigned int in[16]); + +BOOL MD5_Hash_File(unsigned char digest[16], char *pszFileName, BOOL bUsefopen, BOOL bSeed, unsigned int seed[4]); +char *MD5_Print(unsigned char hash[16]); diff --git a/dep/hlsdk/common/net_api.h b/dep/hlsdk/common/net_api.h new file mode 100644 index 0000000..9551d18 --- /dev/null +++ b/dep/hlsdk/common/net_api.h @@ -0,0 +1,99 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#if !defined( NET_APIH ) +#define NET_APIH +#ifdef _WIN32 +#pragma once +#endif + +#if !defined ( NETADRH ) +#include "netadr.h" +#endif + +#define NETAPI_REQUEST_SERVERLIST ( 0 ) // Doesn't need a remote address +#define NETAPI_REQUEST_PING ( 1 ) +#define NETAPI_REQUEST_RULES ( 2 ) +#define NETAPI_REQUEST_PLAYERS ( 3 ) +#define NETAPI_REQUEST_DETAILS ( 4 ) + +// Set this flag for things like broadcast requests, etc. where the engine should not +// kill the request hook after receiving the first response +#define FNETAPI_MULTIPLE_RESPONSE ( 1<<0 ) + +typedef void ( *net_api_response_func_t ) ( struct net_response_s *response ); + +#define NET_SUCCESS ( 0 ) +#define NET_ERROR_TIMEOUT ( 1<<0 ) +#define NET_ERROR_PROTO_UNSUPPORTED ( 1<<1 ) +#define NET_ERROR_UNDEFINED ( 1<<2 ) + +typedef struct net_adrlist_s +{ + struct net_adrlist_s *next; + netadr_t remote_address; +} net_adrlist_t; + +typedef struct net_response_s +{ + // NET_SUCCESS or an error code + int error; + + // Context ID + int context; + // Type + int type; + + // Server that is responding to the request + netadr_t remote_address; + + // Response RTT ping time + double ping; + // Key/Value pair string ( separated by backlash \ characters ) + // WARNING: You must copy this buffer in the callback function, because it is freed + // by the engine right after the call!!!! + // ALSO: For NETAPI_REQUEST_SERVERLIST requests, this will be a pointer to a linked list of net_adrlist_t's + void *response; +} net_response_t; + +typedef struct net_status_s +{ + // Connected to remote server? 1 == yes, 0 otherwise + int connected; + // Client's IP address + netadr_t local_address; + // Address of remote server + netadr_t remote_address; + // Packet Loss ( as a percentage ) + int packet_loss; + // Latency, in seconds ( multiply by 1000.0 to get milliseconds ) + double latency; + // Connection time, in seconds + double connection_time; + // Rate setting ( for incoming data ) + double rate; +} net_status_t; + +typedef struct net_api_s +{ + // APIs + void ( *InitNetworking )( void ); + void ( *Status ) ( struct net_status_s *status ); + void ( *SendRequest) ( int context, int request, int flags, double timeout, struct netadr_s *remote_address, net_api_response_func_t response ); + void ( *CancelRequest ) ( int context ); + void ( *CancelAllRequests ) ( void ); + char *( *AdrToString ) ( struct netadr_s *a ); + int ( *CompareAdr ) ( struct netadr_s *a, struct netadr_s *b ); + int ( *StringToAdr ) ( char *s, struct netadr_s *a ); + const char *( *ValueForKey ) ( const char *s, const char *key ); + void ( *RemoveKey ) ( char *s, const char *key ); + void ( *SetValueForKey ) (char *s, const char *key, const char *value, int maxsize ); +} net_api_t; + +extern net_api_t netapi; + +#endif // NET_APIH diff --git a/dep/hlsdk/common/netadr.h b/dep/hlsdk/common/netadr.h new file mode 100644 index 0000000..0a468d2 --- /dev/null +++ b/dep/hlsdk/common/netadr.h @@ -0,0 +1,40 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef NETADR_H +#define NETADR_H +#ifdef _WIN32 +#pragma once +#endif + +typedef enum +{ + NA_UNUSED, + NA_LOOPBACK, + NA_BROADCAST, + NA_IP, + NA_IPX, + NA_BROADCAST_IPX, +} netadrtype_t; + +typedef struct netadr_s +{ + netadrtype_t type; + unsigned char ip[4]; + unsigned char ipx[10]; + unsigned short port; +} netadr_t; + +#endif // NETADR_H diff --git a/dep/hlsdk/common/netapi.cpp b/dep/hlsdk/common/netapi.cpp new file mode 100644 index 0000000..7c69449 --- /dev/null +++ b/dep/hlsdk/common/netapi.cpp @@ -0,0 +1,208 @@ +#include +#include + +#ifdef _WIN32 + #include "winsock.h" +#else + #include + #include + #include + #include + #include + #include +#endif // _WIN32 + +#include "netapi.h" + +class CNetAPI: public INetAPI { +public: + virtual void NetAdrToSockAddr(netadr_t *a, struct sockaddr *s); + virtual void SockAddrToNetAdr(struct sockaddr *s, netadr_t *a); + + virtual char *AdrToString(netadr_t *a); + virtual bool StringToAdr(const char *s, netadr_t *a); + + virtual void GetSocketAddress(int socket, netadr_t *a); + virtual bool CompareAdr(netadr_t *a, netadr_t *b); + virtual void GetLocalIP(netadr_t *a); +}; + +// Expose interface +CNetAPI g_NetAPI; +INetAPI *net = (INetAPI *)&g_NetAPI; + +void CNetAPI::NetAdrToSockAddr(netadr_t *a, struct sockaddr *s) +{ + memset(s, 0, sizeof(*s)); + + if (a->type == NA_BROADCAST) + { + ((struct sockaddr_in *)s)->sin_family = AF_INET; + ((struct sockaddr_in *)s)->sin_port = a->port; + ((struct sockaddr_in *)s)->sin_addr.s_addr = INADDR_BROADCAST; + } + else if (a->type == NA_IP) + { + ((struct sockaddr_in *)s)->sin_family = AF_INET; + ((struct sockaddr_in *)s)->sin_addr.s_addr = *(int *)&a->ip; + ((struct sockaddr_in *)s)->sin_port = a->port; + } +} + +void CNetAPI::SockAddrToNetAdr(struct sockaddr *s, netadr_t *a) +{ + if (s->sa_family == AF_INET) + { + a->type = NA_IP; + *(int *)&a->ip = ((struct sockaddr_in *)s)->sin_addr.s_addr; + a->port = ((struct sockaddr_in *)s)->sin_port; + } +} + +char *CNetAPI::AdrToString(netadr_t *a) +{ + static char s[64]; + memset(s, 0, sizeof(s)); + + if (a) + { + if (a->type == NA_LOOPBACK) + { + sprintf(s, "loopback"); + } + else if (a->type == NA_IP) + { + sprintf(s, "%i.%i.%i.%i:%i", a->ip[0], a->ip[1], a->ip[2], a->ip[3], ntohs(a->port)); + } + } + + return s; +} + +bool StringToSockaddr(const char *s, struct sockaddr *sadr) +{ + struct hostent *h; + char *colon; + char copy[128]; + struct sockaddr_in *p; + + memset(sadr, 0, sizeof(*sadr)); + + p = (struct sockaddr_in *)sadr; + p->sin_family = AF_INET; + p->sin_port = 0; + + strcpy(copy, s); + + // strip off a trailing :port if present + for (colon = copy ; *colon ; colon++) + { + if (*colon == ':') + { + // terminate + *colon = '\0'; + + // Start at next character + p->sin_port = htons((short)atoi(colon + 1)); + } + } + + // Numeric IP, no DNS + if (copy[0] >= '0' && copy[0] <= '9' && strstr(copy, ".")) + { + *(int *)&p->sin_addr = inet_addr(copy); + } + else + { + // DNS it + if (!(h = gethostbyname(copy))) + { + return false; + } + + // Use first result + *(int *)&p->sin_addr = *(int *)h->h_addr_list[0]; + } + + return true; +} + +bool CNetAPI::StringToAdr(const char *s, netadr_t *a) +{ + struct sockaddr sadr; + if (!strcmp(s, "localhost")) + { + memset(a, 0, sizeof(*a)); + a->type = NA_LOOPBACK; + return true; + } + + if (!StringToSockaddr(s, &sadr)) + { + return false; + } + + SockAddrToNetAdr(&sadr, a); + return true; +} + +// Lookup the IP address for the specified IP socket +void CNetAPI::GetSocketAddress(int socket, netadr_t *a) +{ + char buff[512]; + struct sockaddr_in address; + int namelen; + + memset(a, 0, sizeof(*a)); + gethostname(buff, sizeof(buff)); + + // Ensure that it doesn't overrun the buffer + buff[sizeof buff - 1] = '\0'; + StringToAdr(buff, a); + + namelen = sizeof(address); + if (getsockname(socket, (struct sockaddr *)&address, (int *)&namelen) == 0) + { + a->port = address.sin_port; + } +} + +bool CNetAPI::CompareAdr(netadr_t *a, netadr_t *b) +{ + if (a->type != b->type) + { + return false; + } + + if (a->type == NA_LOOPBACK) + { + return true; + } + + if (a->type == NA_IP && + a->ip[0] == b->ip[0] && + a->ip[1] == b->ip[1] && + a->ip[2] == b->ip[2] && + a->ip[3] == b->ip[3] && + a->port == b->port) + { + return true; + } + + return false; +} + +void CNetAPI::GetLocalIP(netadr_t *a) +{ + char s[64]; + if(!::gethostname(s, 64)) + { + struct hostent *localip = ::gethostbyname(s); + if(localip) + { + a->type = NA_IP; + a->port = 0; + memcpy(a->ip, localip->h_addr_list[0], 4); + } + } +} diff --git a/dep/hlsdk/common/netapi.h b/dep/hlsdk/common/netapi.h new file mode 100644 index 0000000..8401c92 --- /dev/null +++ b/dep/hlsdk/common/netapi.h @@ -0,0 +1,25 @@ +#ifndef NETAPI_H +#define NETAPI_H +#ifdef _WIN32 +#pragma once +#endif + +#include "netadr.h" + +class INetAPI { +public: + virtual void NetAdrToSockAddr(netadr_t *a, struct sockaddr *s) = 0; // Convert a netadr_t to sockaddr + virtual void SockAddrToNetAdr(struct sockaddr *s, netadr_t *a) = 0; // Convert a sockaddr to netadr_t + + virtual char *AdrToString(netadr_t *a) = 0; // Convert a netadr_t to a string + virtual bool StringToAdr(const char *s, netadr_t *a) = 0; // Convert a string address to a netadr_t, doing DNS if needed + virtual void GetSocketAddress(int socket, netadr_t *a) = 0; // Look up IP address for socket + virtual bool CompareAdr(netadr_t *a, netadr_t *b) = 0; + + // return the IP of the local host + virtual void GetLocalIP(netadr_t *a) = 0; +}; + +extern INetAPI *net; + +#endif // NETAPI_H diff --git a/dep/hlsdk/common/nowin.h b/dep/hlsdk/common/nowin.h new file mode 100644 index 0000000..0b1f577 --- /dev/null +++ b/dep/hlsdk/common/nowin.h @@ -0,0 +1,16 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef INC_NOWIN_H +#define INC_NOWIN_H +#ifndef _WIN32 + +#include +#include + +#endif //!_WIN32 +#endif //INC_NOWIN_H diff --git a/dep/hlsdk/common/parsemsg.cpp b/dep/hlsdk/common/parsemsg.cpp new file mode 100644 index 0000000..3d121d6 --- /dev/null +++ b/dep/hlsdk/common/parsemsg.cpp @@ -0,0 +1,258 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// parsemsg.cpp +// +//-------------------------------------------------------------------------------------------------------------- +#include "precompiled.h" + +typedef unsigned char byte; +#define true 1 + +static byte *gpBuf; +static int giSize; +static int giRead; +static int giBadRead; + +int READ_OK( void ) +{ + return !giBadRead; +} + +void BEGIN_READ( void *buf, int size ) +{ + giRead = 0; + giBadRead = 0; + giSize = size; + gpBuf = (byte*)buf; +} + + +int READ_CHAR( void ) +{ + int c; + + if (giRead + 1 > giSize) + { + giBadRead = true; + return -1; + } + + c = (signed char)gpBuf[giRead]; + giRead++; + + return c; +} + +int READ_BYTE( void ) +{ + int c; + + if (giRead+1 > giSize) + { + giBadRead = true; + return -1; + } + + c = (unsigned char)gpBuf[giRead]; + giRead++; + + return c; +} + +int READ_SHORT( void ) +{ + int c; + + if (giRead+2 > giSize) + { + giBadRead = true; + return -1; + } + + c = (short)( gpBuf[giRead] + ( gpBuf[giRead+1] << 8 ) ); + + giRead += 2; + + return c; +} + +int READ_WORD( void ) +{ + return READ_SHORT(); +} + + +int READ_LONG( void ) +{ + int c; + + if (giRead+4 > giSize) + { + giBadRead = true; + return -1; + } + + c = gpBuf[giRead] + (gpBuf[giRead + 1] << 8) + (gpBuf[giRead + 2] << 16) + (gpBuf[giRead + 3] << 24); + + giRead += 4; + + return c; +} + +float READ_FLOAT( void ) +{ + union + { + byte b[4]; + float f; + int l; + } dat; + + dat.b[0] = gpBuf[giRead]; + dat.b[1] = gpBuf[giRead+1]; + dat.b[2] = gpBuf[giRead+2]; + dat.b[3] = gpBuf[giRead+3]; + giRead += 4; + +// dat.l = LittleLong (dat.l); + + return dat.f; +} + +char* READ_STRING( void ) +{ + static char string[2048]; + int l,c; + + string[0] = 0; + + l = 0; + do + { + if ( giRead+1 > giSize ) + break; // no more characters + + c = READ_CHAR(); + if (c == -1 || c == 0) + break; + string[l] = c; + l++; + } while (l < sizeof(string)-1); + + string[l] = 0; + + return string; +} + +float READ_COORD( void ) +{ + return (float)(READ_SHORT() * (1.0/8)); +} + +float READ_ANGLE( void ) +{ + return (float)(READ_CHAR() * (360.0/256)); +} + +float READ_HIRESANGLE( void ) +{ + return (float)(READ_SHORT() * (360.0/65536)); +} + +//-------------------------------------------------------------------------------------------------------------- +BufferWriter::BufferWriter() +{ + Init( NULL, 0 ); +} + +//-------------------------------------------------------------------------------------------------------------- +BufferWriter::BufferWriter( unsigned char *buffer, int bufferLen ) +{ + Init( buffer, bufferLen ); +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::Init( unsigned char *buffer, int bufferLen ) +{ + m_overflow = false; + m_buffer = buffer; + m_remaining = bufferLen; + m_overallLength = bufferLen; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteByte( unsigned char data ) +{ + if (!m_buffer || !m_remaining) + { + m_overflow = true; + return; + } + + *m_buffer = data; + ++m_buffer; + --m_remaining; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteLong( int data ) +{ + if (!m_buffer || m_remaining < 4) + { + m_overflow = true; + return; + } + + m_buffer[0] = data&0xff; + m_buffer[1] = (data>>8)&0xff; + m_buffer[2] = (data>>16)&0xff; + m_buffer[3] = data>>24; + m_buffer += 4; + m_remaining -= 4; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteString( const char *str ) +{ + if (!m_buffer || !m_remaining) + { + m_overflow = true; + return; + } + + if (!str) + str = ""; + + int len = strlen(str)+1; + if ( len > m_remaining ) + { + m_overflow = true; + str = ""; + len = 1; + } + + strcpy((char *)m_buffer, str); + m_remaining -= len; + m_buffer += len; +} + +//-------------------------------------------------------------------------------------------------------------- +int BufferWriter::GetSpaceUsed() +{ + return m_overallLength - m_remaining; +} + +//-------------------------------------------------------------------------------------------------------------- diff --git a/dep/hlsdk/common/parsemsg.h b/dep/hlsdk/common/parsemsg.h new file mode 100644 index 0000000..be7affc --- /dev/null +++ b/dep/hlsdk/common/parsemsg.h @@ -0,0 +1,66 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// parsemsg.h +// MDC - copying from cstrike\cl_dll so career-mode stuff can catch messages +// in this dll. (and C++ifying it) +// + +#ifndef PARSEMSG_H +#define PARSEMSG_H + +#define ASSERT( x ) +//-------------------------------------------------------------------------------------------------------------- +void BEGIN_READ( void *buf, int size ); +int READ_CHAR( void ); +int READ_BYTE( void ); +int READ_SHORT( void ); +int READ_WORD( void ); +int READ_LONG( void ); +float READ_FLOAT( void ); +char* READ_STRING( void ); +float READ_COORD( void ); +float READ_ANGLE( void ); +float READ_HIRESANGLE( void ); +int READ_OK( void ); + +//-------------------------------------------------------------------------------------------------------------- +class BufferWriter +{ +public: + BufferWriter(); + BufferWriter( unsigned char *buffer, int bufferLen ); + void Init( unsigned char *buffer, int bufferLen ); + + void WriteByte( unsigned char data ); + void WriteLong( int data ); + void WriteString( const char *str ); + + bool HasOverflowed(); + int GetSpaceUsed(); + +protected: + unsigned char *m_buffer; + int m_remaining; + bool m_overflow; + int m_overallLength; +}; + +//-------------------------------------------------------------------------------------------------------------- + +#endif // PARSEMSG_H + + + diff --git a/dep/hlsdk/common/particledef.h b/dep/hlsdk/common/particledef.h new file mode 100644 index 0000000..7e4043a --- /dev/null +++ b/dep/hlsdk/common/particledef.h @@ -0,0 +1,57 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( PARTICLEDEFH ) +#define PARTICLEDEFH +#ifdef _WIN32 +#pragma once +#endif + +typedef enum { + pt_static, + pt_grav, + pt_slowgrav, + pt_fire, + pt_explode, + pt_explode2, + pt_blob, + pt_blob2, + pt_vox_slowgrav, + pt_vox_grav, + pt_clientcustom // Must have callback function specified +} ptype_t; + +// !!! if this is changed, it must be changed in d_ifacea.h too !!! +typedef struct particle_s +{ +// driver-usable fields + vec3_t org; + short color; + short packedColor; +// drivers never touch the following fields + struct particle_s *next; + vec3_t vel; + float ramp; + float die; + ptype_t type; + void (*deathfunc)( struct particle_s *particle ); + + // for pt_clientcusttom, we'll call this function each frame + void (*callback)( struct particle_s *particle, float frametime ); + + // For deathfunc, etc. + unsigned char context; +} particle_t; + +#endif diff --git a/dep/hlsdk/common/pmtrace.h b/dep/hlsdk/common/pmtrace.h new file mode 100644 index 0000000..1784e9c --- /dev/null +++ b/dep/hlsdk/common/pmtrace.h @@ -0,0 +1,43 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( PMTRACEH ) +#define PMTRACEH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct +{ + vec3_t normal; + float dist; +} pmplane_t; + +typedef struct pmtrace_s pmtrace_t; + +struct pmtrace_s +{ + qboolean allsolid; // if true, plane is not valid + qboolean startsolid; // if true, the initial point was in a solid area + qboolean inopen, inwater; // End point is in empty space or in water + float fraction; // time completed, 1.0 = didn't hit anything + vec3_t endpos; // final position + pmplane_t plane; // surface normal at impact + int ent; // entity at impact + vec3_t deltavelocity; // Change in player's velocity caused by impact. + // Only run on server. + int hitgroup; +}; + +#endif diff --git a/dep/hlsdk/common/port.h b/dep/hlsdk/common/port.h new file mode 100644 index 0000000..a0838a7 --- /dev/null +++ b/dep/hlsdk/common/port.h @@ -0,0 +1,119 @@ +// port.h: portability helper +// +////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "archtypes.h" // DAL + +#ifdef _WIN32 + + // Insert your headers here + #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + #define WIN32_EXTRA_LEAN + + #include "winsani_in.h" + #include + #include "winsani_out.h" + + #include + #include + #include + +#else // _WIN32 + + #include + #include + #include // exit() + #include // strncpy() + #include // tolower() + #include + #include + #include + #include + + typedef unsigned char BYTE; + + typedef int32 LONG; + //typedef uint32 ULONG; + + #ifndef ARCHTYPES_H + typedef uint32 ULONG; + #endif + + typedef void *HANDLE; + + #ifndef HMODULE + typedef void *HMODULE; + #endif + + typedef char * LPSTR; + + #define __cdecl + + + #ifdef __linux__ + typedef struct POINT_s + { + int x; + int y; + } POINT; + typedef void *HINSTANCE; + typedef void *HWND; + typedef void *HDC; + typedef void *HGLRC; + + typedef struct RECT_s + { + int left; + int right; + int top; + int bottom; + } RECT; + #endif + + + #ifdef __cplusplus + + //#undef FALSE + //#undef TRUE + + #ifdef OSX + //#else + //const bool FALSE = false; + //const bool TRUE = true; + #endif + #endif + + #ifndef NULL + #ifdef __cplusplus + #define NULL 0 + #else + #define NULL ((void *)0) + #endif + #endif + + #ifdef __cplusplus + inline int ioctlsocket( int d, int cmd, uint32 *argp ) { return ioctl( d, cmd, argp ); } + inline int closesocket( int fd ) { return close( fd ); } + inline char * GetCurrentDirectory( size_t size, char * buf ) { return getcwd( buf, size ); } + inline int WSAGetLastError() { return errno; } + + inline void DebugBreak( void ) { exit( 1 ); } + #endif + + extern char g_szEXEName[ 4096 ]; + + #define _snprintf snprintf + + #if defined(OSX) + #define SO_ARCH_SUFFIX ".dylib" + #else + #if defined ( __x86_64__ ) + #define SO_ARCH_SUFFIX "_amd64.so" + #else + #define SO_ARCH_SUFFIX ".so" + #endif + #endif +#endif + diff --git a/dep/hlsdk/common/qfont.h b/dep/hlsdk/common/qfont.h new file mode 100644 index 0000000..2fc8129 --- /dev/null +++ b/dep/hlsdk/common/qfont.h @@ -0,0 +1,41 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( QFONTH ) +#define QFONTH +#ifdef _WIN32 +#pragma once +#endif + +// Font stuff + +#define NUM_GLYPHS 256 +// does not exist: // #include "basetypes.h" + +typedef struct +{ + short startoffset; + short charwidth; +} charinfo; + +typedef struct qfont_s +{ + int width, height; + int rowcount; + int rowheight; + charinfo fontinfo[ NUM_GLYPHS ]; + unsigned char data[4]; +} qfont_t; + +#endif // qfont.h diff --git a/dep/hlsdk/common/qlimits.h b/dep/hlsdk/common/qlimits.h new file mode 100644 index 0000000..1a67bd5 --- /dev/null +++ b/dep/hlsdk/common/qlimits.h @@ -0,0 +1,44 @@ +//========= Copyright (c) 1996-2002, Valve LLC, All rights reserved. ========== +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef QLIMITS_H +#define QLIMITS_H + +#if defined( _WIN32 ) +#pragma once +#endif + +// DATA STRUCTURE INFO + +#define MAX_NUM_ARGVS 50 + +// SYSTEM INFO +#define MAX_QPATH 64 // max length of a game pathname +#define MAX_OSPATH 260 // max length of a filesystem pathname + +#define ON_EPSILON 0.1 // point on plane side epsilon + +#define MAX_LIGHTSTYLE_INDEX_BITS 6 +#define MAX_LIGHTSTYLES (1< + +#if !defined(_WIN32) +void NORETURN Sys_Error(const char *error, ...); + +// This file adds the necessary compatibility tricks to avoid symbols with +// version GLIBCXX_3.4.16 and bigger, keeping binary compatibility with libstdc++ 4.6.1. +namespace std +{ + // We shouldn't be throwing exceptions at all, but it sadly turns out we call STL (inline) functions that do. + void __throw_out_of_range_fmt(const char *fmt, ...) + { + va_list ap; + char buf[1024]; // That should be big enough. + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + buf[sizeof(buf) - 1] = '\0'; + va_end(ap); + + Sys_Error(buf); + } +}; // namespace std + +// Technically, this symbol is not in GLIBCXX_3.4.20, but in CXXABI_1.3.8, +// but that's equivalent, version-wise. Those calls are added by the compiler +// itself on `new Class[n]` calls. +extern "C" +void __cxa_throw_bad_array_new_length() +{ + Sys_Error("Bad array new length."); +} +#endif // !defined(_WIN32) diff --git a/dep/hlsdk/common/studio_event.h b/dep/hlsdk/common/studio_event.h new file mode 100644 index 0000000..c79c210 --- /dev/null +++ b/dep/hlsdk/common/studio_event.h @@ -0,0 +1,29 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( STUDIO_EVENTH ) +#define STUDIO_EVENTH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct mstudioevent_s +{ + int frame; + int event; + int type; + char options[64]; +} mstudioevent_t; + +#endif // STUDIO_EVENTH diff --git a/dep/hlsdk/common/textconsole.cpp b/dep/hlsdk/common/textconsole.cpp new file mode 100644 index 0000000..45d13d7 --- /dev/null +++ b/dep/hlsdk/common/textconsole.cpp @@ -0,0 +1,392 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +bool CTextConsole::Init(IBaseSystem *system) +{ + // NULL or a valid base system interface + m_System = system; + + Q_memset(m_szConsoleText, 0, sizeof(m_szConsoleText)); + m_nConsoleTextLen = 0; + m_nCursorPosition = 0; + + Q_memset(m_szSavedConsoleText, 0, sizeof(m_szSavedConsoleText)); + m_nSavedConsoleTextLen = 0; + + Q_memset(m_aszLineBuffer, 0, sizeof(m_aszLineBuffer)); + m_nTotalLines = 0; + m_nInputLine = 0; + m_nBrowseLine = 0; + + // these are log messages, not related to console + Sys_Printf("\n"); + Sys_Printf("Console initialized.\n"); + + m_ConsoleVisible = true; + + return true; +} + +void CTextConsole::InitSystem(IBaseSystem *system) +{ + m_System = system; +} + +void CTextConsole::SetVisible(bool visible) +{ + m_ConsoleVisible = visible; +} + +bool CTextConsole::IsVisible() +{ + return m_ConsoleVisible; +} + +void CTextConsole::ShutDown() +{ + ; +} + +void CTextConsole::Print(char *pszMsg) +{ + if (m_nConsoleTextLen) + { + int nLen = m_nConsoleTextLen; + while (nLen--) + { + PrintRaw("\b \b"); + } + } + + PrintRaw(pszMsg); + + if (m_nConsoleTextLen) + { + PrintRaw(m_szConsoleText, m_nConsoleTextLen); + } + + UpdateStatus(); +} + +int CTextConsole::ReceiveNewline() +{ + int nLen = 0; + + Echo("\n"); + + if (m_nConsoleTextLen) + { + nLen = m_nConsoleTextLen; + + m_szConsoleText[ m_nConsoleTextLen ] = '\0'; + m_nConsoleTextLen = 0; + m_nCursorPosition = 0; + + // cache line in buffer, but only if it's not a duplicate of the previous line + if ((m_nInputLine == 0) || (Q_strcmp(m_aszLineBuffer[ m_nInputLine - 1 ], m_szConsoleText))) + { + Q_strncpy(m_aszLineBuffer[ m_nInputLine ], m_szConsoleText, MAX_CONSOLE_TEXTLEN); + m_nInputLine++; + + if (m_nInputLine > m_nTotalLines) + m_nTotalLines = m_nInputLine; + + if (m_nInputLine >= MAX_BUFFER_LINES) + m_nInputLine = 0; + + } + + m_nBrowseLine = m_nInputLine; + } + + return nLen; +} + +void CTextConsole::ReceiveBackspace() +{ + int nCount; + + if (m_nCursorPosition == 0) + { + return; + } + + m_nConsoleTextLen--; + m_nCursorPosition--; + + Echo("\b"); + + for (nCount = m_nCursorPosition; nCount < m_nConsoleTextLen; ++nCount) + { + m_szConsoleText[ nCount ] = m_szConsoleText[ nCount + 1 ]; + Echo(m_szConsoleText + nCount, 1); + } + + Echo(" "); + + nCount = m_nConsoleTextLen; + while (nCount >= m_nCursorPosition) + { + Echo("\b"); + nCount--; + } + + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveTab() +{ + if (!m_System) + return; + + ObjectList matches; + m_szConsoleText[ m_nConsoleTextLen ] = '\0'; + m_System->GetCommandMatches(m_szConsoleText, &matches); + + if (matches.IsEmpty()) + return; + + if (matches.CountElements() == 1) + { + char *pszCmdName = (char *)matches.GetFirst(); + char *pszRest = pszCmdName + Q_strlen(m_szConsoleText); + + if (pszRest) + { + Echo(pszRest); + Q_strlcat(m_szConsoleText, pszRest); + m_nConsoleTextLen += Q_strlen(pszRest); + + Echo(" "); + Q_strlcat(m_szConsoleText, " "); + m_nConsoleTextLen++; + } + } + else + { + int nLongestCmd = 0; + int nSmallestCmd = 0; + int nCurrentColumn; + int nTotalColumns; + char szCommonCmd[256]; // Should be enough. + char szFormatCmd[256]; + char *pszSmallestCmd; + char *pszCurrentCmd = (char *)matches.GetFirst(); + nSmallestCmd = Q_strlen(pszCurrentCmd); + pszSmallestCmd = pszCurrentCmd; + while (pszCurrentCmd) + { + if ((int)Q_strlen(pszCurrentCmd) > nLongestCmd) + { + nLongestCmd = Q_strlen(pszCurrentCmd); + } + if ((int)Q_strlen(pszCurrentCmd) < nSmallestCmd) + { + nSmallestCmd = Q_strlen(pszCurrentCmd); + pszSmallestCmd = pszCurrentCmd; + } + pszCurrentCmd = (char *)matches.GetNext(); + } + + nTotalColumns = (GetWidth() - 1) / (nLongestCmd + 1); + nCurrentColumn = 0; + + Echo("\n"); + Q_strcpy(szCommonCmd, pszSmallestCmd); + + // Would be nice if these were sorted, but not that big a deal + pszCurrentCmd = (char *)matches.GetFirst(); + while (pszCurrentCmd) + { + if (++nCurrentColumn > nTotalColumns) + { + Echo("\n"); + nCurrentColumn = 1; + } + + Q_snprintf(szFormatCmd, sizeof(szFormatCmd), "%-*s ", nLongestCmd, pszCurrentCmd); + Echo(szFormatCmd); + for (char *pCur = pszCurrentCmd, *pCommon = szCommonCmd; (*pCur && *pCommon); pCur++, pCommon++) + { + if (*pCur != *pCommon) + { + *pCommon = 0; + break; + } + } + + pszCurrentCmd = (char *)matches.GetNext(); + } + + Echo("\n"); + if (Q_strcmp(szCommonCmd, m_szConsoleText)) + { + Q_strcpy(m_szConsoleText, szCommonCmd); + m_nConsoleTextLen = Q_strlen(szCommonCmd); + } + + Echo(m_szConsoleText); + } + + m_nCursorPosition = m_nConsoleTextLen; + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveStandardChar(const char ch) +{ + int nCount; + + // If the line buffer is maxed out, ignore this char + if (m_nConsoleTextLen >= (sizeof(m_szConsoleText) - 2)) + { + return; + } + + nCount = m_nConsoleTextLen; + while (nCount > m_nCursorPosition) + { + m_szConsoleText[ nCount ] = m_szConsoleText[ nCount - 1 ]; + nCount--; + } + + m_szConsoleText[ m_nCursorPosition ] = ch; + + Echo(m_szConsoleText + m_nCursorPosition, m_nConsoleTextLen - m_nCursorPosition + 1); + + m_nConsoleTextLen++; + m_nCursorPosition++; + + nCount = m_nConsoleTextLen; + while (nCount > m_nCursorPosition) + { + Echo("\b"); + nCount--; + } + + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveUpArrow() +{ + int nLastCommandInHistory = m_nInputLine + 1; + if (nLastCommandInHistory > m_nTotalLines) + nLastCommandInHistory = 0; + + if (m_nBrowseLine == nLastCommandInHistory) + return; + + if (m_nBrowseLine == m_nInputLine) + { + if (m_nConsoleTextLen > 0) + { + // Save off current text + Q_strncpy(m_szSavedConsoleText, m_szConsoleText, m_nConsoleTextLen); + // No terminator, it's a raw buffer we always know the length of + } + + m_nSavedConsoleTextLen = m_nConsoleTextLen; + } + + m_nBrowseLine--; + if (m_nBrowseLine < 0) + { + m_nBrowseLine = m_nTotalLines - 1; + } + + // delete old line + while (m_nConsoleTextLen--) + { + Echo("\b \b"); + } + + // copy buffered line + Echo(m_aszLineBuffer[ m_nBrowseLine ]); + + Q_strncpy(m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN); + + m_nConsoleTextLen = Q_strlen(m_aszLineBuffer[ m_nBrowseLine ]); + m_nCursorPosition = m_nConsoleTextLen; +} + +void CTextConsole::ReceiveDownArrow() +{ + if (m_nBrowseLine == m_nInputLine) + return; + + if (++m_nBrowseLine > m_nTotalLines) + m_nBrowseLine = 0; + + // delete old line + while (m_nConsoleTextLen--) + { + Echo("\b \b"); + } + + if (m_nBrowseLine == m_nInputLine) + { + if (m_nSavedConsoleTextLen > 0) + { + // Restore current text + Q_strncpy(m_szConsoleText, m_szSavedConsoleText, m_nSavedConsoleTextLen); + // No terminator, it's a raw buffer we always know the length of + + Echo(m_szConsoleText, m_nSavedConsoleTextLen); + } + + m_nConsoleTextLen = m_nSavedConsoleTextLen; + } + else + { + // copy buffered line + Echo(m_aszLineBuffer[ m_nBrowseLine ]); + Q_strncpy(m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN); + m_nConsoleTextLen = Q_strlen(m_aszLineBuffer[ m_nBrowseLine ]); + } + + m_nCursorPosition = m_nConsoleTextLen; +} + +void CTextConsole::ReceiveLeftArrow() +{ + if (m_nCursorPosition == 0) + return; + + Echo("\b"); + m_nCursorPosition--; +} + +void CTextConsole::ReceiveRightArrow() +{ + if (m_nCursorPosition == m_nConsoleTextLen) + return; + + Echo(m_szConsoleText + m_nCursorPosition, 1); + m_nCursorPosition++; +} diff --git a/dep/hlsdk/common/textconsole.h b/dep/hlsdk/common/textconsole.h new file mode 100644 index 0000000..9d1b67e --- /dev/null +++ b/dep/hlsdk/common/textconsole.h @@ -0,0 +1,95 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IBaseSystem.h" + +#define MAX_CONSOLE_TEXTLEN 256 +#define MAX_BUFFER_LINES 30 + +class CTextConsole { +public: + virtual ~CTextConsole() {} + + virtual bool Init(IBaseSystem *system = nullptr); + virtual void ShutDown(); + virtual void Print(char *pszMsg); + + virtual void SetTitle(char *pszTitle) {} + virtual void SetStatusLine(char *pszStatus) {} + virtual void UpdateStatus() {} + + // Must be provided by children + virtual void PrintRaw(char *pszMsg, int nChars = 0) = 0; + virtual void Echo(char *pszMsg, int nChars = 0) = 0; + virtual char *GetLine() = 0; + virtual int GetWidth() = 0; + + virtual void SetVisible(bool visible); + virtual bool IsVisible(); + + void InitSystem(IBaseSystem *system); + +protected: + char m_szConsoleText[MAX_CONSOLE_TEXTLEN]; // console text buffer + int m_nConsoleTextLen; // console textbuffer length + int m_nCursorPosition; // position in the current input line + + // Saved input data when scrolling back through command history + char m_szSavedConsoleText[MAX_CONSOLE_TEXTLEN]; // console text buffer + int m_nSavedConsoleTextLen; // console textbuffer length + + char m_aszLineBuffer[MAX_BUFFER_LINES][MAX_CONSOLE_TEXTLEN]; // command buffer last MAX_BUFFER_LINES commands + int m_nInputLine; // Current line being entered + int m_nBrowseLine; // current buffer line for up/down arrow + int m_nTotalLines; // # of nonempty lines in the buffer + + bool m_ConsoleVisible; + + IBaseSystem *m_System; + + int ReceiveNewline(); + void ReceiveBackspace(); + void ReceiveTab(); + void ReceiveStandardChar(const char ch); + void ReceiveUpArrow(); + void ReceiveDownArrow(); + void ReceiveLeftArrow(); + void ReceiveRightArrow(); +}; + +#include "SteamAppStartUp.h" + +#if defined(_WIN32) + #include "TextConsoleWin32.h" +#else + #include "TextConsoleUnix.h" +#endif // defined(_WIN32) + +void Sys_Printf(char *fmt, ...); diff --git a/dep/hlsdk/common/triangleapi.h b/dep/hlsdk/common/triangleapi.h new file mode 100644 index 0000000..c1d6bd0 --- /dev/null +++ b/dep/hlsdk/common/triangleapi.h @@ -0,0 +1,64 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( TRIANGLEAPIH ) +#define TRIANGLEAPIH +#ifdef _WIN32 +#pragma once +#endif + +typedef enum +{ + TRI_FRONT = 0, + TRI_NONE = 1, +} TRICULLSTYLE; + +#define TRI_API_VERSION 1 + +#define TRI_TRIANGLES 0 +#define TRI_TRIANGLE_FAN 1 +#define TRI_QUADS 2 +#define TRI_POLYGON 3 +#define TRI_LINES 4 +#define TRI_TRIANGLE_STRIP 5 +#define TRI_QUAD_STRIP 6 + +typedef struct triangleapi_s +{ + int version; + + void ( *RenderMode )( int mode ); + void ( *Begin )( int primitiveCode ); + void ( *End ) ( void ); + + void ( *Color4f ) ( float r, float g, float b, float a ); + void ( *Color4ub ) ( unsigned char r, unsigned char g, unsigned char b, unsigned char a ); + void ( *TexCoord2f ) ( float u, float v ); + void ( *Vertex3fv ) ( float *worldPnt ); + void ( *Vertex3f ) ( float x, float y, float z ); + void ( *Brightness ) ( float brightness ); + void ( *CullFace ) ( TRICULLSTYLE style ); + int ( *SpriteTexture ) ( struct model_s *pSpriteModel, int frame ); + int ( *WorldToScreen ) ( float *world, float *screen ); // Returns 1 if it's z clipped + void ( *Fog ) ( float flFogColor[3], float flStart, float flEnd, int bOn ); // Works just like GL_FOG, flFogColor is r/g/b. + void ( *ScreenToWorld ) ( float *screen, float *world ); + void ( *GetMatrix ) ( const int pname, float *matrix ); + int ( *BoxInPVS ) ( float *mins, float *maxs ); + void ( *LightAtPoint ) ( float *pos, float *value ); + void ( *Color4fRendermode ) ( float r, float g, float b, float a, int rendermode ); + void ( *FogParams ) ( float flDensity, int iFogSkybox ); // Used with Fog()...sets fog density and whether the fog should be applied to the skybox + +} triangleapi_t; + +#endif // !TRIANGLEAPIH diff --git a/dep/hlsdk/common/usercmd.h b/dep/hlsdk/common/usercmd.h new file mode 100644 index 0000000..3411769 --- /dev/null +++ b/dep/hlsdk/common/usercmd.h @@ -0,0 +1,41 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef USERCMD_H +#define USERCMD_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct usercmd_s +{ + short lerp_msec; // Interpolation time on client + byte msec; // Duration in ms of command + vec3_t viewangles; // Command view angles. + +// intended velocities + float forwardmove; // Forward velocity. + float sidemove; // Sideways velocity. + float upmove; // Upward velocity. + byte lightlevel; // Light level at spot where we are standing. + unsigned short buttons; // Attack buttons + byte impulse; // Impulse command issued. + byte weaponselect; // Current weapon id + +// Experimental player impact stuff. + int impact_index; + vec3_t impact_position; +} usercmd_t; + +#endif // USERCMD_H diff --git a/dep/hlsdk/common/vmodes.h b/dep/hlsdk/common/vmodes.h new file mode 100644 index 0000000..9765bca --- /dev/null +++ b/dep/hlsdk/common/vmodes.h @@ -0,0 +1,33 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +typedef struct rect_s +{ + int left, right, top, bottom; +} wrect_t; diff --git a/dep/hlsdk/common/weaponinfo.h b/dep/hlsdk/common/weaponinfo.h new file mode 100644 index 0000000..5abd38b --- /dev/null +++ b/dep/hlsdk/common/weaponinfo.h @@ -0,0 +1,53 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef WEAPONINFO_H +#define WEAPONINFO_H +#ifdef _WIN32 +#pragma once +#endif + +// Info about weapons player might have in his/her possession +typedef struct weapon_data_s +{ + int m_iId; + int m_iClip; + + float m_flNextPrimaryAttack; + float m_flNextSecondaryAttack; + float m_flTimeWeaponIdle; + + int m_fInReload; + int m_fInSpecialReload; + float m_flNextReload; + float m_flPumpTime; + float m_fReloadTime; + + float m_fAimedDamage; + float m_fNextAimBonus; + int m_fInZoom; + int m_iWeaponState; + + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; +} weapon_data_t; + +#endif // WEAPONINFO_H diff --git a/dep/hlsdk/common/winsani_in.h b/dep/hlsdk/common/winsani_in.h new file mode 100644 index 0000000..d8c8527 --- /dev/null +++ b/dep/hlsdk/common/winsani_in.h @@ -0,0 +1,7 @@ +#if _MSC_VER >= 1500 // MSVC++ 9.0 (Visual Studio 2008) +#pragma push_macro("ARRAYSIZE") +#ifdef ARRAYSIZE +#undef ARRAYSIZE +#endif +#define HSPRITE WINDOWS_HSPRITE +#endif diff --git a/dep/hlsdk/common/winsani_out.h b/dep/hlsdk/common/winsani_out.h new file mode 100644 index 0000000..2726950 --- /dev/null +++ b/dep/hlsdk/common/winsani_out.h @@ -0,0 +1,4 @@ +#if _MSC_VER >= 1500 // MSVC++ 9.0 (Visual Studio 2008) +#undef HSPRITE +#pragma pop_macro("ARRAYSIZE") +#endif diff --git a/dep/hlsdk/dlls/activity.h b/dep/hlsdk/dlls/activity.h new file mode 100644 index 0000000..d854e9a --- /dev/null +++ b/dep/hlsdk/dlls/activity.h @@ -0,0 +1,146 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef enum Activity_s +{ + ACT_INVALID = -1, + + ACT_RESET = 0, // Set m_Activity to this invalid value to force a reset to m_IdealActivity + ACT_IDLE, + ACT_GUARD, + ACT_WALK, + ACT_RUN, + ACT_FLY, // Fly (and flap if appropriate) + ACT_SWIM, + ACT_HOP, // vertical jump + ACT_LEAP, // long forward jump + ACT_FALL, + ACT_LAND, + ACT_STRAFE_LEFT, + ACT_STRAFE_RIGHT, + ACT_ROLL_LEFT, // tuck and roll, left + ACT_ROLL_RIGHT, // tuck and roll, right + ACT_TURN_LEFT, // turn quickly left (stationary) + ACT_TURN_RIGHT, // turn quickly right (stationary) + ACT_CROUCH, // the act of crouching down from a standing position + ACT_CROUCHIDLE, // holding body in crouched position (loops) + ACT_STAND, // the act of standing from a crouched position + ACT_USE, + ACT_SIGNAL1, + ACT_SIGNAL2, + ACT_SIGNAL3, + ACT_TWITCH, + ACT_COWER, + ACT_SMALL_FLINCH, + ACT_BIG_FLINCH, + ACT_RANGE_ATTACK1, + ACT_RANGE_ATTACK2, + ACT_MELEE_ATTACK1, + ACT_MELEE_ATTACK2, + ACT_RELOAD, + ACT_ARM, // pull out gun, for instance + ACT_DISARM, // reholster gun + ACT_EAT, // monster chowing on a large food item (loop) + ACT_DIESIMPLE, + ACT_DIEBACKWARD, + ACT_DIEFORWARD, + ACT_DIEVIOLENT, + ACT_BARNACLE_HIT, // barnacle tongue hits a monster + ACT_BARNACLE_PULL, // barnacle is lifting the monster ( loop ) + ACT_BARNACLE_CHOMP, // barnacle latches on to the monster + ACT_BARNACLE_CHEW, // barnacle is holding the monster in its mouth ( loop ) + ACT_SLEEP, + ACT_INSPECT_FLOOR, // for active idles, look at something on or near the floor + ACT_INSPECT_WALL, // for active idles, look at something directly ahead of you ( doesn't HAVE to be a wall or on a wall ) + ACT_IDLE_ANGRY, // alternate idle animation in which the monster is clearly agitated. (loop) + ACT_WALK_HURT, // limp (loop) + ACT_RUN_HURT, // limp (loop) + ACT_HOVER, // Idle while in flight + ACT_GLIDE, // Fly (don't flap) + ACT_FLY_LEFT, // Turn left in flight + ACT_FLY_RIGHT, // Turn right in flight + ACT_DETECT_SCENT, // this means the monster smells a scent carried by the air + ACT_SNIFF, // this is the act of actually sniffing an item in front of the monster + ACT_BITE, // some large monsters can eat small things in one bite. This plays one time, EAT loops. + ACT_THREAT_DISPLAY, // without attacking, monster demonstrates that it is angry. (Yell, stick out chest, etc ) + ACT_FEAR_DISPLAY, // monster just saw something that it is afraid of + ACT_EXCITED, // for some reason, monster is excited. Sees something he really likes to eat, or whatever. + ACT_SPECIAL_ATTACK1, // very monster specific special attacks. + ACT_SPECIAL_ATTACK2, + ACT_COMBAT_IDLE, // agitated idle. + ACT_WALK_SCARED, + ACT_RUN_SCARED, + ACT_VICTORY_DANCE, // killed a player, do a victory dance. + ACT_DIE_HEADSHOT, // die, hit in head. + ACT_DIE_CHESTSHOT, // die, hit in chest + ACT_DIE_GUTSHOT, // die, hit in gut + ACT_DIE_BACKSHOT, // die, hit in back + ACT_FLINCH_HEAD, + ACT_FLINCH_CHEST, + ACT_FLINCH_STOMACH, + ACT_FLINCH_LEFTARM, + ACT_FLINCH_RIGHTARM, + ACT_FLINCH_LEFTLEG, + ACT_FLINCH_RIGHTLEG, + ACT_FLINCH, + ACT_LARGE_FLINCH, + ACT_HOLDBOMB, + ACT_IDLE_FIDGET, + ACT_IDLE_SCARED, + ACT_IDLE_SCARED_FIDGET, + ACT_FOLLOW_IDLE, + ACT_FOLLOW_IDLE_FIDGET, + ACT_FOLLOW_IDLE_SCARED, + ACT_FOLLOW_IDLE_SCARED_FIDGET, + ACT_CROUCH_IDLE, + ACT_CROUCH_IDLE_FIDGET, + ACT_CROUCH_IDLE_SCARED, + ACT_CROUCH_IDLE_SCARED_FIDGET, + ACT_CROUCH_WALK, + ACT_CROUCH_WALK_SCARED, + ACT_CROUCH_DIE, + ACT_WALK_BACK, + ACT_IDLE_SNEAKY, + ACT_IDLE_SNEAKY_FIDGET, + ACT_WALK_SNEAKY, + ACT_WAVE, + ACT_YES, + ACT_NO, + +} Activity; + +typedef struct +{ + int type; + char *name; + +} activity_map_t; + +extern activity_map_t activity_map[]; diff --git a/dep/hlsdk/dlls/activitymap.h b/dep/hlsdk/dlls/activitymap.h new file mode 100644 index 0000000..17e5be2 --- /dev/null +++ b/dep/hlsdk/dlls/activitymap.h @@ -0,0 +1,111 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#define _A(a)\ + { a, #a } + +activity_map_t activity_map[] = +{ + _A(ACT_IDLE), + _A(ACT_GUARD), + _A(ACT_WALK), + _A(ACT_RUN), + _A(ACT_FLY), + _A(ACT_SWIM), + _A(ACT_HOP), + _A(ACT_LEAP), + _A(ACT_FALL), + _A(ACT_LAND), + _A(ACT_STRAFE_LEFT), + _A(ACT_STRAFE_RIGHT), + _A(ACT_ROLL_LEFT), + _A(ACT_ROLL_RIGHT), + _A(ACT_TURN_LEFT), + _A(ACT_TURN_RIGHT), + _A(ACT_CROUCH), + _A(ACT_CROUCHIDLE), + _A(ACT_STAND), + _A(ACT_USE), + _A(ACT_SIGNAL1), + _A(ACT_SIGNAL2), + _A(ACT_SIGNAL3), + _A(ACT_TWITCH), + _A(ACT_COWER), + _A(ACT_SMALL_FLINCH), + _A(ACT_BIG_FLINCH), + _A(ACT_RANGE_ATTACK1), + _A(ACT_RANGE_ATTACK2), + _A(ACT_MELEE_ATTACK1), + _A(ACT_MELEE_ATTACK2), + _A(ACT_RELOAD), + _A(ACT_ARM), + _A(ACT_DISARM), + _A(ACT_EAT), + _A(ACT_DIESIMPLE), + _A(ACT_DIEBACKWARD), + _A(ACT_DIEFORWARD), + _A(ACT_DIEVIOLENT), + _A(ACT_BARNACLE_HIT), + _A(ACT_BARNACLE_PULL), + _A(ACT_BARNACLE_CHOMP), + _A(ACT_BARNACLE_CHEW), + _A(ACT_SLEEP), + _A(ACT_INSPECT_FLOOR), + _A(ACT_INSPECT_WALL), + _A(ACT_IDLE_ANGRY), + _A(ACT_WALK_HURT), + _A(ACT_RUN_HURT), + _A(ACT_HOVER), + _A(ACT_GLIDE), + _A(ACT_FLY_LEFT), + _A(ACT_FLY_RIGHT), + _A(ACT_DETECT_SCENT), + _A(ACT_SNIFF), + _A(ACT_BITE), + _A(ACT_THREAT_DISPLAY), + _A(ACT_FEAR_DISPLAY), + _A(ACT_EXCITED), + _A(ACT_SPECIAL_ATTACK1), + _A(ACT_SPECIAL_ATTACK2), + _A(ACT_COMBAT_IDLE), + _A(ACT_WALK_SCARED), + _A(ACT_RUN_SCARED), + _A(ACT_VICTORY_DANCE), + _A(ACT_DIE_HEADSHOT), + _A(ACT_DIE_CHESTSHOT), + _A(ACT_DIE_GUTSHOT), + _A(ACT_DIE_BACKSHOT), + _A(ACT_FLINCH_HEAD), + _A(ACT_FLINCH_CHEST), + _A(ACT_FLINCH_STOMACH), + _A(ACT_FLINCH_LEFTARM), + _A(ACT_FLINCH_RIGHTARM), + _A(ACT_FLINCH_LEFTLEG), + _A(ACT_FLINCH_RIGHTLEG), + 0, nullptr +}; diff --git a/dep/hlsdk/dlls/airtank.h b/dep/hlsdk/dlls/airtank.h new file mode 100644 index 0000000..90de064 --- /dev/null +++ b/dep/hlsdk/dlls/airtank.h @@ -0,0 +1,43 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CAirtank: public CGrenade { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual int BloodColor() = 0; + + int GetState() const { return m_state; } +private: + int m_state; +}; diff --git a/dep/hlsdk/dlls/ammo.h b/dep/hlsdk/dlls/ammo.h new file mode 100644 index 0000000..8c41ff6 --- /dev/null +++ b/dep/hlsdk/dlls/ammo.h @@ -0,0 +1,99 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class C9MMAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class CBuckShotAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C556NatoAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C556NatoBoxAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C762NatoAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C45ACPAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C50AEAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C338MagnumAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C57MMAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; + +class C357SIGAmmo: public CBasePlayerAmmo { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; +}; diff --git a/dep/hlsdk/dlls/basemonster.h b/dep/hlsdk/dlls/basemonster.h new file mode 100644 index 0000000..c26746e --- /dev/null +++ b/dep/hlsdk/dlls/basemonster.h @@ -0,0 +1,118 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "gib.h" +#include "activity.h" + +enum +{ + ITBD_PARALLYZE = 0, + ITBD_NERVE_GAS, + ITBD_POISON, + ITBD_RADIATION, + ITBD_DROWN_RECOVER, + ITBD_ACID, + ITBD_SLOW_BURN, + ITBD_SLOW_FREEZE, + ITBD_END +}; + +enum MONSTERSTATE +{ + MONSTERSTATE_NONE = 0, + MONSTERSTATE_IDLE, + MONSTERSTATE_COMBAT, + MONSTERSTATE_ALERT, + MONSTERSTATE_HUNT, + MONSTERSTATE_PRONE, + MONSTERSTATE_SCRIPT, + MONSTERSTATE_PLAYDEAD, + MONSTERSTATE_DEAD +}; + +class CBaseToggle; +class CBaseMonster: public CBaseToggle { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual BOOL TakeHealth(float flHealth, int bitsDamageType) = 0; + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual int BloodColor() = 0; + virtual BOOL IsAlive() = 0; + virtual float ChangeYaw(int speed) = 0; + virtual BOOL HasHumanGibs() = 0; + virtual BOOL HasAlienGibs() = 0; + virtual void FadeMonster() = 0; + virtual void GibMonster() = 0; + virtual Activity GetDeathActivity() = 0; + virtual void BecomeDead() = 0; + virtual BOOL ShouldFadeOnDeath() = 0; + virtual int IRelationship(CBaseEntity *pTarget) = 0; + virtual void PainSound() = 0; + virtual void ResetMaxSpeed() = 0; + virtual void ReportAIState() = 0; + virtual void MonsterInitDead() = 0; + virtual void Look(int iDistance) = 0; + virtual CBaseEntity *BestVisibleEnemy() = 0; + virtual BOOL FInViewCone(CBaseEntity *pEntity) = 0; + virtual BOOL FInViewCone(const Vector *pOrigin) = 0; +public: + void SetConditions(int iConditions) { m_afConditions |= iConditions; } + void ClearConditions(int iConditions) { m_afConditions &= ~iConditions; } + BOOL HasConditions(int iConditions) { return (m_afConditions & iConditions) ? TRUE : FALSE; } + BOOL HasAllConditions(int iConditions) { return ((m_afConditions & iConditions) == iConditions) ? TRUE : FALSE; } + + void Remember(int iMemory) { m_afMemory |= iMemory; } + void Forget(int iMemory) { m_afMemory &= ~iMemory; } + BOOL HasMemory(int iMemory) { return (m_afMemory & iMemory) ? TRUE : FALSE; } + BOOL HasAllMemories(int iMemory) { return ((m_afMemory & iMemory) == iMemory) ? TRUE : FALSE; } + + void StopAnimation() { pev->framerate = 0.0f; } +public: + Activity m_Activity; // what the monster is doing (animation) + Activity m_IdealActivity; // monster should switch to this activity + int m_LastHitGroup; // the last body region that took damage + int m_bitsDamageType; // what types of damage has monster (player) taken + byte m_rgbTimeBasedDamage[ITBD_END]; + + MONSTERSTATE m_MonsterState; // monster's current state + MONSTERSTATE m_IdealMonsterState; // monster should change to this state + int m_afConditions; + int m_afMemory; + + float m_flNextAttack; // cannot attack again until this time + EHANDLE m_hEnemy; // the entity that the monster is fighting. + EHANDLE m_hTargetEnt; // the entity that the monster is trying to reach + float m_flFieldOfView; // width of monster's field of view (dot product) + int m_bloodColor; // color of blood particless + Vector m_HackedGunPos; // HACK until we can query end of gun + Vector m_vecEnemyLKP; // last known position of enemy. (enemy's origin) +}; diff --git a/dep/hlsdk/dlls/bmodels.h b/dep/hlsdk/dlls/bmodels.h new file mode 100644 index 0000000..cc24fa6 --- /dev/null +++ b/dep/hlsdk/dlls/bmodels.h @@ -0,0 +1,149 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// covering cheesy noise1, noise2, & noise3 fields so they make more sense (for rotating fans) +#define noiseStart noise1 +#define noiseStop noise2 +#define noiseRunning noise3 + +// This is just a solid wall if not inhibited +class CFuncWall: public CBaseEntity { +public: + virtual void Spawn() = 0; + + // Bmodels don't go across transitions + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +#define SF_WALL_TOOGLE_START_OFF BIT(0) +#define SF_WALL_TOOGLE_NOTSOLID BIT(3) + +class CFuncWallToggle: public CFuncWall { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +#define SF_CONVEYOR_VISUAL BIT(0) +#define SF_CONVEYOR_NOTSOLID BIT(1) + +class CFuncConveyor: public CFuncWall { +public: + virtual void Spawn() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +// A simple entity that looks solid but lets you walk through it. +class CFuncIllusionary: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int ObjectCaps() = 0; +}; + +// Monster only clip brush +// +// This brush will be solid for any entity who has the FL_MONSTERCLIP flag set +// in pev->flags +// +// otherwise it will be invisible and not solid. This can be used to keep +// specific monsters out of certain areas +class CFuncMonsterClip: public CFuncWall { +public: + virtual void Spawn() = 0; + + // Clear out func_wall's use function + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +#define SF_BRUSH_ROTATE_START_ON BIT(0) +#define SF_BRUSH_ROTATE_BACKWARDS BIT(1) +#define SF_BRUSH_ROTATE_Z_AXIS BIT(2) +#define SF_BRUSH_ROTATE_X_AXIS BIT(3) +#define SF_BRUSH_ACCDCC BIT(4) // Brush should accelerate and decelerate when toggled +#define SF_BRUSH_HURT BIT(5) // Rotating brush that inflicts pain based on rotation speed +#define SF_BRUSH_ROTATE_NOT_SOLID BIT(6) // Some special rotating objects are not solid. +#define SF_BRUSH_ROTATE_SMALLRADIUS BIT(7) +#define SF_BRUSH_ROTATE_MEDIUMRADIUS BIT(8) +#define SF_BRUSH_ROTATE_LARGERADIUS BIT(9) + +const int MAX_FANPITCH = 100; +const int MIN_FANPITCH = 30; + +class CFuncRotating: public CBaseEntity { +public: + // basic functions + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; +public: + + float m_flFanFriction; + float m_flAttenuation; + float m_flVolume; + float m_pitch; + int m_sounds; + + Vector m_angles; +}; + +#define SF_PENDULUM_START_ON BIT(0) +#define SF_PENDULUM_SWING BIT(1) // Spawnflag that makes a pendulum a rope swing +#define SF_PENDULUM_PASSABLE BIT(3) +#define SF_PENDULUM_AUTO_RETURN BIT(4) + +class CPendulum: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; +public: + float m_accel; // Acceleration + float m_distance; + float m_time; + float m_damp; + float m_maxSpeed; + float m_dampSpeed; + + Vector m_center; + Vector m_start; +}; diff --git a/dep/hlsdk/dlls/bot/cs_bot.h b/dep/hlsdk/dlls/bot/cs_bot.h new file mode 100644 index 0000000..28c4d86 --- /dev/null +++ b/dep/hlsdk/dlls/bot/cs_bot.h @@ -0,0 +1,639 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "bot/cs_gamestate.h" +#include "bot/cs_bot_manager.h" +#include "bot/cs_bot_chatter.h" + +const int MAX_BUY_WEAPON_PRIMARY = 13; +const int MAX_BUY_WEAPON_SECONDARY = 3; + +enum +{ + BOT_PROGGRESS_DRAW = 0, // draw status bar progress + BOT_PROGGRESS_START, // init status bar progress + BOT_PROGGRESS_HIDE, // hide status bar progress +}; + +extern int _navAreaCount; +extern int _currentIndex; + +extern struct BuyInfo primaryWeaponBuyInfoCT[MAX_BUY_WEAPON_PRIMARY]; +extern struct BuyInfo secondaryWeaponBuyInfoCT[MAX_BUY_WEAPON_SECONDARY]; + +extern struct BuyInfo primaryWeaponBuyInfoT[MAX_BUY_WEAPON_PRIMARY]; +extern struct BuyInfo secondaryWeaponBuyInfoT[MAX_BUY_WEAPON_SECONDARY]; + +class CCSBot; +class BotChatterInterface; + +class BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const = 0; +}; + +class IdleState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual const char *GetName() const { return "Idle"; } +}; + +class HuntState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "Hunt"; } +public: + CNavArea *m_huntArea; +}; + +class AttackState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "Attack"; } +public: + enum DodgeStateType + { + STEADY_ON, + SLIDE_LEFT, + SLIDE_RIGHT, + JUMP, + NUM_ATTACK_STATES + } m_dodgeState; + + float m_nextDodgeStateTimestamp; + CountdownTimer m_repathTimer; + float m_scopeTimestamp; + bool m_haveSeenEnemy; + bool m_isEnemyHidden; + float m_reacquireTimestamp; + float m_shieldToggleTimestamp; + bool m_shieldForceOpen; + float m_pinnedDownTimestamp; + bool m_crouchAndHold; + bool m_didAmbushCheck; + bool m_dodge; + bool m_firstDodge; + bool m_isCoward; + CountdownTimer m_retreatTimer; +}; + +class InvestigateNoiseState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "InvestigateNoise"; } +private: + void AttendCurrentNoise(CCSBot *me); + Vector m_checkNoisePosition; +}; + +class BuyState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "Buy"; } +public: + bool m_isInitialDelay; + int m_prefRetries; + int m_prefIndex; + int m_retries; + bool m_doneBuying; + bool m_buyDefuseKit; + bool m_buyGrenade; + bool m_buyShield; + bool m_buyPistol; +}; + +class MoveToState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "MoveTo"; } + + void SetGoalPosition(const Vector &pos) { m_goalPosition = pos; } + void SetRouteType(RouteType route) { m_routeType = route; } + +private: + Vector m_goalPosition; + RouteType m_routeType; + bool m_radioedPlan; + bool m_askedForCover; +}; + +class FetchBombState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual const char *GetName() const { return "FetchBomb"; } +}; + +class PlantBombState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "PlantBomb"; } +}; + +class DefuseBombState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "DefuseBomb"; } +}; + +class HideState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "Hide"; } + +public: + void SetHidingSpot(const Vector &pos) { m_hidingSpot = pos; } + const Vector &GetHidingSpot() const { return m_hidingSpot; } + + void SetSearchArea(CNavArea *area) { m_searchFromArea = area; } + void SetSearchRange(float range) { m_range = range; } + + void SetDuration(float time) { m_duration = time; } + void SetHoldPosition(bool hold) { m_isHoldingPosition = hold; } + + bool IsAtSpot() const { return m_isAtSpot; } + +public: + CNavArea *m_searchFromArea; + float m_range; + + Vector m_hidingSpot; + bool m_isAtSpot; + float m_duration; + bool m_isHoldingPosition; + float m_holdPositionTime; + bool m_heardEnemy; + + float m_firstHeardEnemyTime; + int m_retry; + Vector m_leaderAnchorPos; +}; + +class EscapeFromBombState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "EscapeFromBomb"; } +}; + +class FollowState: public BotState +{ +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "Follow"; } + + void SetLeader(CBasePlayer *leader) { m_leader = leader; } + +public: + EntityHandle m_leader; + Vector m_lastLeaderPos; + bool m_isStopped; + float m_stoppedTimestamp; + + enum LeaderMotionStateType + { + INVALID, + STOPPED, + WALKING, + RUNNING + + } m_leaderMotionState; + + IntervalTimer m_leaderMotionStateTime; + + bool m_isSneaking; + float m_lastSawLeaderTime; + CountdownTimer m_repathInterval; + + IntervalTimer m_walkTime; + bool m_isAtWalkSpeed; + + float m_waitTime; + CountdownTimer m_idleTimer; +}; + +class UseEntityState: public BotState { +public: + virtual void OnEnter(CCSBot *me) {} + virtual void OnUpdate(CCSBot *me) {} + virtual void OnExit(CCSBot *me) {} + virtual const char *GetName() const { return "UseEntity"; } + + void SetEntity(CBaseEntity *entity) { m_entity = entity; } + +private: + EntityHandle m_entity; +}; + +// The Counter-strike Bot +class CCSBot: public CBot { +public: + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; // invoked when injured by something (EXTEND) - returns the amount of damage inflicted + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; // invoked when killed (EXTEND) + virtual void RoundRespawn() = 0; + virtual void Blind(float duration, float holdTime, float fadeTime, int alpha = 255) = 0; // player blinded by a flashbang + virtual void OnTouchingWeapon(CWeaponBox *box) = 0; // invoked when in contact with a CWeaponBox + + virtual bool Initialize(const BotProfile *profile) = 0; // (EXTEND) prepare bot for action + virtual void SpawnBot() = 0; // (EXTEND) spawn the bot into the game + + virtual void Upkeep() = 0; // lightweight maintenance, invoked frequently + virtual void Update() = 0; // heavyweight algorithms, invoked less often + + virtual void Walk() = 0; + virtual bool Jump(bool mustJump = false) = 0; // returns true if jump was started + + virtual void OnEvent(GameEventType event, CBaseEntity *entity = NULL, CBaseEntity *other = NULL) = 0; // invoked when event occurs in the game (some events have NULL entity) + + #define CHECK_FOV true + virtual bool IsVisible(const Vector *pos, bool testFOV = false) const = 0; // return true if we can see the point + virtual bool IsVisible(CBasePlayer *player, bool testFOV = false, unsigned char *visParts = NULL) const = 0; // return true if we can see any part of the player + + virtual bool IsEnemyPartVisible(VisiblePartType part) const = 0; // if enemy is visible, return the part we see for our current enemy + + +public: + const Vector &GetEyePosition() const + { + m_eyePos = pev->origin + pev->view_ofs; + return m_eyePos; + } +public: + friend class CCSBotManager; + + // TODO: Get rid of these + friend class AttackState; + friend class BuyState; + + char m_name[64]; // copied from STRING(pev->netname) for debugging + + // behavior properties + float m_combatRange; // desired distance between us and them during gunplay + mutable bool m_isRogue; // if true, the bot is a "rogue" and listens to no-one + mutable CountdownTimer m_rogueTimer; + + enum MoraleType + { + TERRIBLE = -3, + BAD = -2, + NEGATIVE = -1, + NEUTRAL = 0, + POSITIVE = 1, + GOOD = 2, + EXCELLENT = 3, + }; + + MoraleType m_morale; // our current morale, based on our win/loss history + bool m_diedLastRound; // true if we died last round + float m_safeTime; // duration at the beginning of the round where we feel "safe" + bool m_wasSafe; // true if we were in the safe time last update + NavRelativeDirType m_blindMoveDir; // which way to move when we're blind + bool m_blindFire; // if true, fire weapon while blinded + + // TODO: implement through CountdownTimer + float m_surpriseDelay; // when we were surprised + float m_surpriseTimestamp; + + bool m_isFollowing; // true if we are following someone + EHANDLE m_leader; // the ID of who we are following + float m_followTimestamp; // when we started following + float m_allowAutoFollowTime; // time when we can auto follow + + CountdownTimer m_hurryTimer; // if valid, bot is in a hurry + + // instances of each possible behavior state, to avoid dynamic memory allocation during runtime + IdleState m_idleState; + HuntState m_huntState; + AttackState m_attackState; + InvestigateNoiseState m_investigateNoiseState; + BuyState m_buyState; + MoveToState m_moveToState; + FetchBombState m_fetchBombState; + PlantBombState m_plantBombState; + DefuseBombState m_defuseBombState; + HideState m_hideState; + EscapeFromBombState m_escapeFromBombState; + FollowState m_followState; + UseEntityState m_useEntityState; + + // TODO: Allow multiple simultaneous state machines (look around, etc) + BotState *m_state; // current behavior state + float m_stateTimestamp; // time state was entered + bool m_isAttacking; // if true, special Attack state is overriding the state machine + + // high-level tasks + enum TaskType + { + SEEK_AND_DESTROY, + PLANT_BOMB, + FIND_TICKING_BOMB, + DEFUSE_BOMB, + GUARD_TICKING_BOMB, + GUARD_BOMB_DEFUSER, + GUARD_LOOSE_BOMB, + GUARD_BOMB_ZONE, + ESCAPE_FROM_BOMB, + HOLD_POSITION, + FOLLOW, + VIP_ESCAPE, + GUARD_VIP_ESCAPE_ZONE, + COLLECT_HOSTAGES, + RESCUE_HOSTAGES, + GUARD_HOSTAGES, + GUARD_HOSTAGE_RESCUE_ZONE, + MOVE_TO_LAST_KNOWN_ENEMY_POSITION, + MOVE_TO_SNIPER_SPOT, + SNIPING, + + NUM_TASKS + }; + TaskType m_task; // our current task + EntityHandle m_taskEntity; // an entity used for our task + + // navigation + Vector m_goalPosition; + EHandle m_goalEntity; + + CNavArea *m_currentArea; // the nav area we are standing on + CNavArea *m_lastKnownArea; // the last area we were in + EntityHandle m_avoid; // higher priority player we need to make way for + float m_avoidTimestamp; + bool m_isJumpCrouching; + bool m_isJumpCrouched; + float m_jumpCrouchTimestamp; + + // path navigation data + enum { _MAX_PATH_LENGTH = 256 }; + struct ConnectInfo + { + CNavArea *area; // the area along the path + NavTraverseType how; // how to enter this area from the previous one + Vector pos; // our movement goal position at this point in the path + const CNavLadder *ladder; // if "how" refers to a ladder, this is it + } + m_path[_MAX_PATH_LENGTH]; + int m_pathLength; + int m_pathIndex; + float m_areaEnteredTimestamp; + + CountdownTimer m_repathTimer; // must have elapsed before bot can pathfind again + + mutable CountdownTimer m_avoidFriendTimer; // used to throttle how often we check for friends in our path + mutable bool m_isFriendInTheWay; // true if a friend is blocking our path + CountdownTimer m_politeTimer; // we'll wait for friend to move until this runs out + bool m_isWaitingBehindFriend; // true if we are waiting for a friend to move + + enum LadderNavState + { + APPROACH_ASCENDING_LADDER, // prepare to scale a ladder + APPROACH_DESCENDING_LADDER, // prepare to go down ladder + FACE_ASCENDING_LADDER, + FACE_DESCENDING_LADDER, + MOUNT_ASCENDING_LADDER, // move toward ladder until "on" it + MOUNT_DESCENDING_LADDER, // move toward ladder until "on" it + ASCEND_LADDER, // go up the ladder + DESCEND_LADDER, // go down the ladder + DISMOUNT_ASCENDING_LADDER, // get off of the ladder + DISMOUNT_DESCENDING_LADDER, // get off of the ladder + MOVE_TO_DESTINATION, // dismount ladder and move to destination area + } + m_pathLadderState; + bool m_pathLadderFaceIn; // if true, face towards ladder, otherwise face away + const CNavLadder *m_pathLadder; // the ladder we need to use to reach the next area + NavRelativeDirType m_pathLadderDismountDir; // which way to dismount + float m_pathLadderDismountTimestamp; // time when dismount started + float m_pathLadderEnd; // if ascending, z of top, if descending z of bottom + float m_pathLadderTimestamp; // time when we started using ladder - for timeout check + + CountdownTimer m_mustRunTimer; // if nonzero, bot cannot walk + + // game scenario mechanisms + CSGameState m_gameState; + + // hostages mechanism + byte m_hostageEscortCount; + float m_hostageEscortCountTimestamp; + bool m_isWaitingForHostage; + CountdownTimer m_inhibitWaitingForHostageTimer; + CountdownTimer m_waitForHostageTimer; + + // listening mechanism + Vector m_noisePosition; // position we last heard non-friendly noise + float m_noiseTimestamp; // when we heard it (can get zeroed) + CNavArea *m_noiseArea; // the nav area containing the noise + float m_noiseCheckTimestamp; + PriorityType m_noisePriority; // priority of currently heard noise + bool m_isNoiseTravelRangeChecked; + + // "looking around" mechanism + float m_lookAroundStateTimestamp; // time of next state change + float m_lookAheadAngle; // our desired forward look angle + float m_forwardAngle; // our current forward facing direction + float m_inhibitLookAroundTimestamp; // time when we can look around again + + enum LookAtSpotState + { + NOT_LOOKING_AT_SPOT, // not currently looking at a point in space + LOOK_TOWARDS_SPOT, // in the process of aiming at m_lookAtSpot + LOOK_AT_SPOT, // looking at m_lookAtSpot + NUM_LOOK_AT_SPOT_STATES + } + m_lookAtSpotState; + Vector m_lookAtSpot; // the spot we're currently looking at + PriorityType m_lookAtSpotPriority; + float m_lookAtSpotDuration; // how long we need to look at the spot + float m_lookAtSpotTimestamp; // when we actually began looking at the spot + float m_lookAtSpotAngleTolerance; // how exactly we must look at the spot + bool m_lookAtSpotClearIfClose; // if true, the look at spot is cleared if it gets close to us + const char *m_lookAtDesc; // for debugging + float m_peripheralTimestamp; + + enum { MAX_APPROACH_POINTS = 16 }; + Vector m_approachPoint[MAX_APPROACH_POINTS]; + unsigned char m_approachPointCount; + Vector m_approachPointViewPosition; // the position used when computing current approachPoint set + bool m_isWaitingToTossGrenade; // lining up throw + CountdownTimer m_tossGrenadeTimer; // timeout timer for grenade tossing + + SpotEncounter *m_spotEncounter; // the spots we will encounter as we move thru our current area + float m_spotCheckTimestamp; // when to check next encounter spot + + // TODO: Add timestamp for each possible client to hiding spots + enum { MAX_CHECKED_SPOTS = 64 }; + struct HidingSpotCheckInfo + { + HidingSpot *spot; + float timestamp; + } + m_checkedHidingSpot[MAX_CHECKED_SPOTS]; + int m_checkedHidingSpotCount; + + // view angle mechanism + float m_lookPitch; // our desired look pitch angle + float m_lookPitchVel; + float m_lookYaw; // our desired look yaw angle + float m_lookYawVel; + + // aim angle mechanism + mutable Vector m_eyePos; + Vector m_aimOffset; // current error added to victim's position to get actual aim spot + Vector m_aimOffsetGoal; // desired aim offset + float m_aimOffsetTimestamp; // time of next offset adjustment + float m_aimSpreadTimestamp; // time used to determine max spread as it begins to tighten up + Vector m_aimSpot; // the spot we are currently aiming to fire at + + // attack state data + // behavior modifiers + enum DispositionType + { + ENGAGE_AND_INVESTIGATE, // engage enemies on sight and investigate enemy noises + OPPORTUNITY_FIRE, // engage enemies on sight, but only look towards enemy noises, dont investigate + SELF_DEFENSE, // only engage if fired on, or very close to enemy + IGNORE_ENEMIES, // ignore all enemies - useful for ducking around corners, running away, etc + + NUM_DISPOSITIONS + }; + DispositionType m_disposition; // how we will react to enemies + CountdownTimer m_ignoreEnemiesTimer; // how long will we ignore enemies + mutable EntityHandle m_enemy; // our current enemy + bool m_isEnemyVisible; // result of last visibility test on enemy + unsigned char m_visibleEnemyParts; // which parts of the visible enemy do we see + Vector m_lastEnemyPosition; // last place we saw the enemy + float m_lastSawEnemyTimestamp; + float m_firstSawEnemyTimestamp; + float m_currentEnemyAcquireTimestamp; + float m_enemyDeathTimestamp; // if m_enemy is dead, this is when he died + bool m_isLastEnemyDead; // true if we killed or saw our last enemy die + int m_nearbyEnemyCount; // max number of enemies we've seen recently + unsigned int m_enemyPlace; // the location where we saw most of our enemies + + struct WatchInfo + { + float timestamp; + bool isEnemy; + } + m_watchInfo[MAX_CLIENTS]; + mutable EntityHandle m_bomber; // points to bomber if we can see him + + int m_nearbyFriendCount; // number of nearby teammates + mutable EntityHandle m_closestVisibleFriend; // the closest friend we can see + mutable EntityHandle m_closestVisibleHumanFriend; // the closest human friend we can see + + CBasePlayer *m_attacker; // last enemy that hurt us (may not be same as m_enemy) + float m_attackedTimestamp; // when we were hurt by the m_attacker + + int m_lastVictimID; // the entindex of the last victim we killed, or zero + bool m_isAimingAtEnemy; // if true, we are trying to aim at our enemy + bool m_isRapidFiring; // if true, RunUpkeep() will toggle our primary attack as fast as it can + IntervalTimer m_equipTimer; // how long have we had our current weapon equipped + float m_fireWeaponTimestamp; + + // reaction time system + enum { MAX_ENEMY_QUEUE = 20 }; + struct ReactionState + { + // NOTE: player position & orientation is not currently stored separately + EntityHandle player; + bool isReloading; + bool isProtectedByShield; + } + m_enemyQueue[MAX_ENEMY_QUEUE]; // round-robin queue for simulating reaction times + + byte m_enemyQueueIndex; + byte m_enemyQueueCount; + byte m_enemyQueueAttendIndex; // index of the timeframe we are "conscious" of + + // stuck detection + bool m_isStuck; + float m_stuckTimestamp; // time when we got stuck + Vector m_stuckSpot; // the location where we became stuck + NavRelativeDirType m_wiggleDirection; + float m_wiggleTimestamp; + float m_stuckJumpTimestamp; // time for next jump when stuck + + enum { MAX_VEL_SAMPLES = 5 }; + float m_avgVel[MAX_VEL_SAMPLES]; + int m_avgVelIndex; + int m_avgVelCount; + Vector m_lastOrigin; + + // chatter mechanism + GameEventType m_lastRadioCommand; // last radio command we recieved + + float m_lastRadioRecievedTimestamp; // time we recieved a radio message + float m_lastRadioSentTimestamp; // time when we send a radio message + EntityHandle m_radioSubject; // who issued the radio message + Vector m_radioPosition; // position referred to in radio message + float m_voiceFeedbackStartTimestamp; + float m_voiceFeedbackEndTimestamp; // new-style "voice" chatter gets voice feedback + BotChatterInterface m_chatter; + + // learn map mechanism + const CNavNode *m_navNodeList; + CNavNode *m_currentNode; + NavDirType m_generationDir; + NavAreaList::iterator m_analyzeIter; + + enum ProcessType + { + PROCESS_NORMAL, + PROCESS_LEARN, + PROCESS_ANALYZE_ALPHA, + PROCESS_ANALYZE_BETA, + PROCESS_SAVE, + } + m_processMode; + CountdownTimer m_mumbleTimer; + CountdownTimer m_booTimer; + CountdownTimer m_relocateTimer; +}; diff --git a/dep/hlsdk/dlls/bot/cs_bot_chatter.h b/dep/hlsdk/dlls/bot/cs_bot_chatter.h new file mode 100644 index 0000000..2e62a33 --- /dev/null +++ b/dep/hlsdk/dlls/bot/cs_bot_chatter.h @@ -0,0 +1,339 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define UNDEFINED_COUNT 0xFFFF +#define MAX_PLACES_PER_MAP 64 +#define UNDEFINED_SUBJECT (-1) +#define COUNT_MANY 4 // equal to or greater than this is "many" + +class CCSBot; +class BotChatterInterface; + +typedef unsigned int PlaceCriteria; +typedef unsigned int CountCriteria; + +// A meme is a unit information that bots use to +// transmit information to each other via the radio +class BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const = 0; // cause the given bot to act on this meme +}; + +class BotAllHostagesGoneMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme +}; + +class BotHostageBeingTakenMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme +}; + +class BotHelpMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme + +public: + Place m_place; +}; + +class BotBombsiteStatusMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme + +public: + enum StatusType { CLEAR, PLANTED }; + int m_zoneIndex; // the bombsite + StatusType m_status; // whether it is cleared or the bomb is there (planted) +}; + +class BotBombStatusMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme + +public: + CSGameState::BombState m_state; + Vector m_pos; +}; + +class BotFollowMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme +}; + +class BotDefendHereMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme + +public: + Vector m_pos; +}; + +class BotWhereBombMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme +}; + +class BotRequestReportMeme: public BotMeme { +public: + virtual void Interpret(CCSBot *sender, CCSBot *receiver) const; // cause the given bot to act on this meme +}; + +enum BotStatementType +{ + REPORT_VISIBLE_ENEMIES, + REPORT_ENEMY_ACTION, + REPORT_MY_CURRENT_TASK, + REPORT_MY_INTENTION, + REPORT_CRITICAL_EVENT, + REPORT_REQUEST_HELP, + REPORT_REQUEST_INFORMATION, + REPORT_ROUND_END, + REPORT_MY_PLAN, + REPORT_INFORMATION, + REPORT_EMOTE, + REPORT_ACKNOWLEDGE, // affirmative or negative + REPORT_ENEMIES_REMAINING, + REPORT_FRIENDLY_FIRE, + REPORT_KILLED_FRIEND, + //REPORT_ENEMY_LOST + + NUM_BOT_STATEMENT_TYPES, +}; + +// BotSpeakables are the smallest unit of bot chatter. +// They represent a specific wav file of a phrase, and the criteria for which it is useful +class BotSpeakable { +public: + char *m_phrase; + float m_duration; + PlaceCriteria m_place; + CountCriteria m_count; +}; + +typedef std::vector BotSpeakableVector; +typedef std::vector BotVoiceBankVector; + +// The BotPhrase class is a collection of Speakables associated with a name, ID, and criteria +class BotPhrase { +public: + const char *GetName() const { return m_name; } + Place GetID() const { return m_id; } + GameEventType GetRadioEquivalent() const { return m_radioEvent; } + bool IsImportant() const { return m_isImportant; } // return true if this phrase is part of an important statement + bool IsPlace() const { return m_isPlace; } + +public: + friend class BotPhraseManager; + char *m_name; + Place m_id; + bool m_isPlace; // true if this is a Place phrase + GameEventType m_radioEvent; + bool m_isImportant; // mission-critical statement + + mutable BotVoiceBankVector m_voiceBank; // array of voice banks (arrays of speakables) + std::vector m_count; // number of speakables + mutable std::vector< int > m_index; // index of next speakable to return + int m_numVoiceBanks; // number of voice banks that have been initialized + + mutable PlaceCriteria m_placeCriteria; + mutable CountCriteria m_countCriteria; +}; + +typedef std::list BotPhraseList; + +// The BotPhraseManager is a singleton that provides an interface to all BotPhrase collections +class BotPhraseManager { +public: + const BotPhraseList *GetPlaceList() const { return &m_placeList; } + + // return time last statement of given type was emitted by a teammate for the given place + float GetPlaceStatementInterval(Place place) const; + + // set time of last statement of given type was emitted by a teammate for the given place + void ResetPlaceStatementInterval(Place place) const; + +public: + int FindPlaceIndex(Place where) const; + + // master list of all phrase collections + BotPhraseList m_list; + + // master list of all Place phrases + BotPhraseList m_placeList; + + struct PlaceTimeInfo + { + Place placeID; + IntervalTimer timer; + }; + + mutable PlaceTimeInfo m_placeStatementHistory[MAX_PLACES_PER_MAP]; + mutable int m_placeCount; +}; + +inline int BotPhraseManager::FindPlaceIndex(Place where) const +{ + for (int i = 0; i < m_placeCount; ++i) + { + if (m_placeStatementHistory[i].placeID == where) + return i; + } + + if (m_placeCount < MAX_PLACES_PER_MAP) + { + m_placeStatementHistory[++m_placeCount].placeID = where; + m_placeStatementHistory[++m_placeCount].timer.Invalidate(); + return m_placeCount - 1; + } + + return -1; +} + +inline float BotPhraseManager::GetPlaceStatementInterval(Place place) const +{ + int index = FindPlaceIndex(place); + + if (index < 0) + return 999999.9f; + + if (index >= m_placeCount) + return 999999.9f; + + return m_placeStatementHistory[index].timer.GetElapsedTime(); +} + +inline void BotPhraseManager::ResetPlaceStatementInterval(Place place) const +{ + int index = FindPlaceIndex(place); + + if (index < 0) + return; + + if (index >= m_placeCount) + return; + + m_placeStatementHistory[index].timer.Reset(); +} + +// Statements are meaningful collections of phrases +class BotStatement { +public: + BotChatterInterface *GetChatter() const { return m_chatter; } + BotStatementType GetType() const { return m_type; } // return the type of statement this is + bool HasSubject() const { return (m_subject != UNDEFINED_SUBJECT); } + void SetSubject(int playerID) { m_subject = playerID; } // who this statement is about + int GetSubject() const { return m_subject; } // who this statement is about + void SetPlace(Place where) { m_place = where; } // explicitly set place + + void SetStartTime(float timestamp) { m_startTime = timestamp; } // define the earliest time this statement can be spoken + float GetStartTime() const { return m_startTime; } + bool IsSpeaking() const { return m_isSpeaking; } // return true if this statement is currently being spoken + float GetTimestamp() const { return m_timestamp; } // get time statement was created (but not necessarily started talking) + +public: + friend class BotChatterInterface; + + BotChatterInterface *m_chatter; // the chatter system this statement is part of + BotStatement *m_next, *m_prev; // linked list hooks + BotStatementType m_type; // what kind of statement this is + int m_subject; // who this subject is about + Place m_place; // explicit place - note some phrases have implicit places as well + BotMeme *m_meme; // a statement can only have a single meme for now + + float m_timestamp; // time when message was created + float m_startTime; // the earliest time this statement can be spoken + float m_expireTime; // time when this statement is no longer valid + float m_speakTimestamp; // time when message began being spoken + bool m_isSpeaking; // true if this statement is current being spoken + + float m_nextTime; // time for next phrase to begin + + enum { MAX_BOT_PHRASES = 4 }; + enum ContextType + { + CURRENT_ENEMY_COUNT, + REMAINING_ENEMY_COUNT, + SHORT_DELAY, + LONG_DELAY, + ACCUMULATE_ENEMIES_DELAY, + }; + struct + { + bool isPhrase; + union + { + const BotPhrase *phrase; + ContextType context; + }; + + } + m_statement[MAX_BOT_PHRASES]; + + enum { MAX_BOT_CONDITIONS = 4 }; + enum ConditionType + { + IS_IN_COMBAT, + RADIO_SILENCE, + ENEMIES_REMAINING, + NUM_CONDITIONS, + }; + + ConditionType m_condition[MAX_BOT_CONDITIONS]; // conditions that must be true for the statement to be said + int m_conditionCount; + + int m_index; // m_index refers to the phrase currently being spoken, or -1 if we havent started yet + int m_count; +}; + +// This class defines the interface to the bot radio chatter system +class BotChatterInterface { +public: + CCSBot *GetOwner() const { return m_me; } + int GetPitch() const { return m_pitch; } + bool SeesAtLeastOneEnemy() const { return m_seeAtLeastOneEnemy; } + +public: + BotStatement *m_statementList; // list of all active/pending messages for this bot + CCSBot *m_me; // the bot this chatter is for + bool m_seeAtLeastOneEnemy; + float m_timeWhenSawFirstEnemy; + bool m_reportedEnemies; + bool m_requestedBombLocation; // true if we already asked where the bomb has been planted + int m_pitch; + IntervalTimer m_needBackupInterval; + IntervalTimer m_spottedBomberInterval; + IntervalTimer m_scaredInterval; + IntervalTimer m_planInterval; + CountdownTimer m_spottedLooseBombTimer; + CountdownTimer m_heardNoiseTimer; + CountdownTimer m_escortingHostageTimer; +}; + +extern BotPhraseManager *TheBotPhrases; diff --git a/dep/hlsdk/dlls/bot/cs_bot_manager.h b/dep/hlsdk/dlls/bot/cs_bot_manager.h new file mode 100644 index 0000000..38f3d60 --- /dev/null +++ b/dep/hlsdk/dlls/bot/cs_bot_manager.h @@ -0,0 +1,145 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +extern CBotManager *TheBots; + +// The manager for Counter-Strike specific bots +class CCSBotManager: public CBotManager { +public: + virtual void ClientDisconnect(CBasePlayer *pPlayer) = 0; + virtual BOOL ClientCommand(CBasePlayer *pPlayer, const char *pcmd) = 0; + + virtual void ServerActivate() = 0; + virtual void ServerDeactivate() = 0; + + virtual void ServerCommand(const char *pcmd) = 0; + virtual void AddServerCommand(const char *cmd) = 0; + virtual void AddServerCommands() = 0; + + virtual void RestartRound() = 0; // (EXTEND) invoked when a new round begins + virtual void StartFrame() = 0; // (EXTEND) called each frame + + virtual void OnEvent(GameEventType event, CBaseEntity *entity = NULL, CBaseEntity *other = NULL) = 0; + virtual unsigned int GetPlayerPriority(CBasePlayer *player) const = 0; // return priority of player (0 = max pri) + virtual bool IsImportantPlayer(CBasePlayer *player) const = 0; // return true if player is important to scenario (VIP, bomb carrier, etc) + +public: + // the supported game scenarios + enum GameScenarioType + { + SCENARIO_DEATHMATCH, + SCENARIO_DEFUSE_BOMB, + SCENARIO_RESCUE_HOSTAGES, + SCENARIO_ESCORT_VIP + }; + GameScenarioType GetScenario() const { return m_gameScenario; } + + // "zones" + // depending on the game mode, these are bomb zones, rescue zones, etc. + enum { MAX_ZONES = 4 }; // max # of zones in a map + enum { MAX_ZONE_NAV_AREAS = 16 }; // max # of nav areas in a zone + struct Zone + { + CBaseEntity *m_entity; // the map entity + CNavArea *m_area[MAX_ZONE_NAV_AREAS]; // nav areas that overlap this zone + int m_areaCount; + Vector m_center; + bool m_isLegacy; // if true, use pev->origin and 256 unit radius as zone + int m_index; + Extent m_extent; + }; + + const Zone *GetZone(int i) const { return &m_zone[i]; } + int GetZoneCount() const { return m_zoneCount; } + + // pick a zone at random and return it + const Zone *GetRandomZone() const + { + if (!m_zoneCount) + return NULL; + + return &m_zone[RANDOM_LONG(0, m_zoneCount - 1)]; + } + + bool IsBombPlanted() const { return m_isBombPlanted; } // returns true if bomb has been planted + float GetBombPlantTimestamp() const { return m_bombPlantTimestamp; } // return time bomb was planted + bool IsTimeToPlantBomb() const { return (gpGlobals->time >= m_earliestBombPlantTimestamp); } // return true if it's ok to try to plant bomb + CBasePlayer *GetBombDefuser() const { return m_bombDefuser; } // return the player currently defusing the bomb, or NULL + CBaseEntity *GetLooseBomb() { return m_looseBomb; } // return the bomb if it is loose on the ground + CNavArea *GetLooseBombArea() const { return m_looseBombArea; } // return area that bomb is in/near + + float GetLastSeenEnemyTimestamp() const { return m_lastSeenEnemyTimestamp; } // return the last time anyone has seen an enemy + void SetLastSeenEnemyTimestamp() { m_lastSeenEnemyTimestamp = gpGlobals->time; } + + float GetRoundStartTime() const { return m_roundStartTimestamp; } + float GetElapsedRoundTime() const { return gpGlobals->time - m_roundStartTimestamp; } // return the elapsed time since the current round began + + bool IsDefenseRushing() const { return m_isDefenseRushing; } // returns true if defense team has "decided" to rush this round + bool IsRoundOver() const { return m_isRoundOver; } // return true if the round has ended + + unsigned int GetNavPlace() const { return m_navPlace; } + void SetNavPlace(unsigned int place) { m_navPlace = place; } + +public: + GameScenarioType m_gameScenario; // what kind of game are we playing + + Zone m_zone[MAX_ZONES]; + int m_zoneCount; + + bool m_isBombPlanted; // true if bomb has been planted + float m_bombPlantTimestamp; // time bomb was planted + float m_earliestBombPlantTimestamp; // don't allow planting until after this time has elapsed + CBasePlayer *m_bombDefuser; // the player currently defusing a bomb + EHANDLE m_looseBomb; // will be non-NULL if bomb is loose on the ground + CNavArea *m_looseBombArea; // area that bomb is is/near + + bool m_isRoundOver; // true if the round has ended + float m_radioMsgTimestamp[24][2]; + + float m_lastSeenEnemyTimestamp; + float m_roundStartTimestamp; // the time when the current round began + + bool m_isDefenseRushing; // whether defensive team is rushing this round or not + + unsigned int m_navPlace; + CountdownTimer m_respawnTimer; + bool m_isRespawnStarted; + bool m_canRespawn; + bool m_bServerActive; +}; + +inline int OtherTeam(int team) +{ + return (team == TERRORIST) ? CT : TERRORIST; +} + +inline CCSBotManager *TheCSBots() +{ + return reinterpret_cast(TheBots); +} diff --git a/dep/hlsdk/dlls/bot/cs_gamestate.h b/dep/hlsdk/dlls/bot/cs_gamestate.h new file mode 100644 index 0000000..769575f --- /dev/null +++ b/dep/hlsdk/dlls/bot/cs_gamestate.h @@ -0,0 +1,90 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class CCSBot; + +// This class represents the game state as known by a particular bot +class CSGameState { +public: + // bomb defuse scenario + enum BombState + { + MOVING, // being carried by a Terrorist + LOOSE, // loose on the ground somewhere + PLANTED, // planted and ticking + DEFUSED, // the bomb has been defused + EXPLODED, // the bomb has exploded + }; + + bool IsBombMoving() const { return (m_bombState == MOVING); } + bool IsBombLoose() const { return (m_bombState == LOOSE); } + bool IsBombPlanted() const { return (m_bombState == PLANTED); } + bool IsBombDefused() const { return (m_bombState == DEFUSED); } + bool IsBombExploded() const { return (m_bombState == EXPLODED); } + +public: + CCSBot *m_owner; // who owns this gamestate + bool m_isRoundOver; // true if round is over, but no yet reset + + // bomb defuse scenario + BombState GetBombState() { return m_bombState; } + BombState m_bombState; // what we think the bomb is doing + + IntervalTimer m_lastSawBomber; + Vector m_bomberPos; + + IntervalTimer m_lastSawLooseBomb; + Vector m_looseBombPos; + + bool m_isBombsiteClear[4]; // corresponds to zone indices in CCSBotManager + int m_bombsiteSearchOrder[4]; // randomized order of bombsites to search + int m_bombsiteCount; + int m_bombsiteSearchIndex; // the next step in the search + + int m_plantedBombsite; // zone index of the bombsite where the planted bomb is + + bool m_isPlantedBombPosKnown; // if true, we know the exact location of the bomb + Vector m_plantedBombPos; + + // hostage rescue scenario + struct HostageInfo + { + CHostage *hostage; + Vector knownPos; + bool isValid; + bool isAlive; + bool isFree; // not being escorted by a CT + } + m_hostage[MAX_HOSTAGES]; + int m_hostageCount; // number of hostages left in map + CountdownTimer m_validateInterval; + + bool m_allHostagesRescued; // if true, so every hostages been is rescued + bool m_haveSomeHostagesBeenTaken; // true if a hostage has been moved by a CT (and we've seen it) +}; diff --git a/dep/hlsdk/dlls/buttons.h b/dep/hlsdk/dlls/buttons.h new file mode 100644 index 0000000..65a72b8 --- /dev/null +++ b/dep/hlsdk/dlls/buttons.h @@ -0,0 +1,105 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_GLOBAL_SET BIT(0) // Set global state to initial state on spawn + +class CEnvGlobal: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + string_t m_globalstate; + int m_triggermode; + int m_initialstate; +}; + +#define SF_ROTBUTTON_NOTSOLID BIT(0) +#define SF_ROTBUTTON_BACKWARDS BIT(1) + +class CRotButton: public CBaseButton { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; +public: + Vector m_vecSpawn; +}; + +// Make this button behave like a door (HACKHACK) +// This will disable use and make the button solid +// rotating buttons were made SOLID_NOT by default since their were some +// collision problems with them... +#define SF_MOMENTARY_DOOR BIT(0) + +class CMomentaryRotButton: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_lastUsed; + int m_direction; + float m_returnSpeed; + Vector m_start; + Vector m_end; + int m_sounds; +}; + +#define SF_SPARK_TOOGLE BIT(5) +#define SF_SPARK_IF_OFF BIT(6) + +class CEnvSpark: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; +public: + float m_flDelay; +}; + +#define SF_BTARGET_USE BIT(0) +#define SF_BTARGET_ON BIT(1) + +class CButtonTarget: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int ObjectCaps() = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; diff --git a/dep/hlsdk/dlls/cbase.h b/dep/hlsdk/dlls/cbase.h new file mode 100644 index 0000000..a156a34 --- /dev/null +++ b/dep/hlsdk/dlls/cbase.h @@ -0,0 +1,485 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "util.h" +#include "schedule.h" +#include "saverestore.h" +#include "scriptevent.h" +#include "monsterevent.h" + +class CSave; +class CRestore; +class CBasePlayer; +class CBaseEntity; +class CBaseMonster; +class CBasePlayerItem; +class CSquadMonster; +class CCSEntity; + +class CBaseEntity { +public: + // Constructor. Set engine to use C/C++ callback functions + // pointers to engine data + entvars_t *pev; // Don't need to save/restore this pointer, the engine resets it + + // path corners + CBaseEntity *m_pGoalEnt; // path corner we are heading towards + CBaseEntity *m_pLink; // used for temporary link-list operations. + + // initialization functions + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Activate() = 0; + + // Setup the object->object collision box (pev->mins / pev->maxs is the object->world collision box) + virtual void SetObjectCollisionBox() = 0; + + // Classify - returns the type of group (i.e, "houndeye", or "human military" so that monsters with different classnames + // still realize that they are teammates. (overridden for monsters that form groups) + virtual int Classify() = 0; + virtual void DeathNotice(entvars_t *pevChild) = 0; + + virtual void TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual BOOL TakeHealth(float flHealth, int bitsDamageType) = 0; + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual int BloodColor() = 0; + virtual void TraceBleed(float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + virtual BOOL IsTriggered(CBaseEntity *pActivator) = 0; + virtual CBaseMonster *MyMonsterPointer() = 0; + virtual CSquadMonster *MySquadMonsterPointer() = 0; + virtual int GetToggleState() = 0; + virtual void AddPoints(int score, BOOL bAllowNegativeScore) = 0; + virtual void AddPointsToTeam(int score, BOOL bAllowNegativeScore) = 0; + virtual BOOL AddPlayerItem(CBasePlayerItem *pItem) = 0; + virtual BOOL RemovePlayerItem(CBasePlayerItem *pItem) = 0; + virtual int GiveAmmo(int iAmount, const char *szName, int iMax = -1) = 0; + virtual float GetDelay() = 0; + virtual int IsMoving() = 0; + virtual void OverrideReset() = 0; + virtual int DamageDecal(int bitsDamageType) = 0; + + // This is ONLY used by the node graph to test movement through a door + virtual void SetToggleState(int state) = 0; + virtual void StartSneaking() = 0; + virtual void UpdateOnRemove() = 0; + virtual BOOL OnControls(entvars_t *onpev) = 0; + virtual BOOL IsSneaking() = 0; + virtual BOOL IsAlive() = 0; + virtual BOOL IsBSPModel() = 0; + virtual BOOL ReflectGauss() = 0; + virtual BOOL HasTarget(string_t targetname) = 0; + virtual BOOL IsInWorld() = 0; + virtual BOOL IsPlayer() = 0; + virtual BOOL IsNetClient() = 0; + virtual const char *TeamID() = 0; + + virtual CBaseEntity *GetNextTarget() = 0; + + // fundamental callbacks + void (CBaseEntity::*m_pfnThink)(); + void (CBaseEntity::*m_pfnTouch)(CBaseEntity *pOther); + void (CBaseEntity::*m_pfnUse)(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value); + void (CBaseEntity::*m_pfnBlocked)(CBaseEntity *pOther); + + void EXT_FUNC DLLEXPORT SUB_Think(); + void EXT_FUNC DLLEXPORT SUB_Touch(CBaseEntity *pOther); + void EXT_FUNC DLLEXPORT SUB_Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value); + void EXT_FUNC DLLEXPORT SUB_Blocked(CBaseEntity *pOther); + + using thinkfn_t = decltype(m_pfnThink); + template + void SetThink(void (T::*pfn)()); + void SetThink(std::nullptr_t); + + using touchfn_t = decltype(m_pfnTouch); + template + void SetTouch(void (T::*pfn)(CBaseEntity *pOther)); + void SetTouch(std::nullptr_t); + + using usefn_t = decltype(m_pfnUse); + template + void SetUse(void (T::*pfn)(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)); + void SetUse(std::nullptr_t); + + using blockedfn_t = decltype(m_pfnBlocked); + template + void SetBlocked(void (T::*pfn)(CBaseEntity *pOther)); + void SetBlocked(std::nullptr_t); + + virtual void Think() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType = USE_OFF, float value = 0.0f) = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; + + virtual CBaseEntity *Respawn() = 0; + virtual void UpdateOwner() = 0; + virtual BOOL FBecomeProne() = 0; + + virtual Vector Center() = 0; // center point of entity + virtual Vector EyePosition() = 0; // position of eyes + virtual Vector EarPosition() = 0; // position of ears + virtual Vector BodyTarget(const Vector &posSrc) = 0; // position to shoot at + + virtual int Illumination() = 0; + virtual BOOL FVisible(CBaseEntity *pEntity) = 0; + virtual BOOL FVisible(const Vector &vecOrigin) = 0; +public: + static CBaseEntity *Instance(edict_t *pent) { return (CBaseEntity *)GET_PRIVATE(pent ? pent : ENT(0)); } + static CBaseEntity *Instance(entvars_t *pev) { return Instance(ENT(pev)); } + static CBaseEntity *Instance(int offset) { return Instance(ENT(offset)); } + + edict_t *edict(); + EOFFSET eoffset(); + int entindex(); + int IsDormant(); + + bool Intersects(CBaseEntity *pOther); + bool Intersects(const Vector &mins, const Vector &maxs); + + // Exports func's, useful method's for SetThink + void EXPORT SUB_CallUseToggle() + { + Use(this, this, USE_TOGGLE, 0); + } + + void EXPORT SUB_Remove() + { + if (pev->health > 0) + { + // this situation can screw up monsters who can't tell their entity pointers are invalid. + pev->health = 0; + ALERT(at_aiconsole, "SUB_Remove called on entity with health > 0\n"); + } + + REMOVE_ENTITY(ENT(pev)); + } + +public: + // NOTE: it was replaced on member "int *current_ammo" because it is useless. + CCSEntity *m_pEntity; + + // We use this variables to store each ammo count. + float currentammo; + int maxammo_buckshot; + int ammo_buckshot; + int maxammo_9mm; + int ammo_9mm; + int maxammo_556nato; + int ammo_556nato; + int maxammo_556natobox; + int ammo_556natobox; + int maxammo_762nato; + int ammo_762nato; + int maxammo_45acp; + int ammo_45acp; + int maxammo_50ae; + int ammo_50ae; + int maxammo_338mag; + int ammo_338mag; + int maxammo_57mm; + int ammo_57mm; + int maxammo_357sig; + int ammo_357sig; + + // Special stuff for grenades and knife. + float m_flStartThrow; + float m_flReleaseThrow; + int m_iSwing; + + // client has left the game + bool has_disconnected; +}; + +#include "ehandle.h" + +// Inlines +inline BOOL FNullEnt(CBaseEntity *ent) { return (ent == NULL || FNullEnt(ent->edict())); } + +template +inline void CBaseEntity::SetThink(void (T::*pfn)()) +{ + m_pfnThink = static_cast(pfn); +} + +inline void CBaseEntity::SetThink(std::nullptr_t) +{ + m_pfnThink = nullptr; +} + +template +inline void CBaseEntity::SetTouch(void (T::*pfn)(CBaseEntity *pOther)) +{ + m_pfnTouch = static_cast(pfn); +} + +inline void CBaseEntity::SetTouch(std::nullptr_t) +{ + m_pfnTouch = nullptr; +} + +template +inline void CBaseEntity::SetUse(void (T::*pfn)(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)) +{ + m_pfnUse = static_cast(pfn); +} + +inline void CBaseEntity::SetUse(std::nullptr_t) +{ + m_pfnUse = nullptr; +} + +template +inline void CBaseEntity::SetBlocked(void (T::*pfn)(CBaseEntity *pOther)) +{ + m_pfnBlocked = static_cast(pfn); +} + +inline void CBaseEntity::SetBlocked(std::nullptr_t) +{ + m_pfnBlocked = nullptr; +} + +class CPointEntity: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int ObjectCaps() = 0; +}; + +// generic Delay entity +class CBaseDelay: public CBaseEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; +public: + float m_flDelay; + string_t m_iszKillTarget; +}; + +class CBaseAnimating: public CBaseDelay { +public: + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void HandleAnimEvent(MonsterEvent_t *pEvent) = 0; +public: + // animation needs + float m_flFrameRate; // computed FPS for current sequence + float m_flGroundSpeed; // computed linear movement rate for current sequence + float m_flLastEventCheck; // last time the event list was checked + BOOL m_fSequenceFinished; // flag set when StudioAdvanceFrame moves across a frame boundry + BOOL m_fSequenceLoops; // true if the sequence loops +}; + +// generic Toggle entity. +class CBaseToggle: public CBaseAnimating { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int GetToggleState() = 0; + virtual float GetDelay() = 0; + + void EXT_FUNC DLLEXPORT SUB_MoveDone(); +public: + TOGGLE_STATE m_toggle_state; + float m_flActivateFinished; // like attack_finished, but for doors + float m_flMoveDistance; // how far a door should slide or rotate + float m_flWait; + float m_flLip; + float m_flTWidth; // for plats + float m_flTLength; // for plats + + Vector m_vecPosition1; + Vector m_vecPosition2; + Vector m_vecAngle1; + Vector m_vecAngle2; + + int m_cTriggersLeft; // trigger_counter only, # of activations remaining + float m_flHeight; + EHANDLE m_hActivator; + void (CBaseToggle::*m_pfnCallWhenMoveDone)(); + + using movedonefn_t = decltype(m_pfnCallWhenMoveDone); + template + void SetMoveDone(void (T::*pfn)()); + void SetMoveDone(std::nullptr_t); + + Vector m_vecFinalDest; + Vector m_vecFinalAngle; + + int m_bitsDamageInflict; // DMG_ damage type that the door or tigger does + + string_t m_sMaster; // If this button has a master switch, this is the targetname. + // A master switch must be of the multisource type. If all + // of the switches in the multisource have been triggered, then + // the button will be allowed to operate. Otherwise, it will be + // deactivated. +}; + +template +inline void CBaseToggle::SetMoveDone(void (T::*pfn)()) +{ + m_pfnCallWhenMoveDone = static_cast(pfn); +} + +inline void CBaseToggle::SetMoveDone(std::nullptr_t) +{ + m_pfnCallWhenMoveDone = nullptr; +} + +#include "world.h" +#include "basemonster.h" +#include "player.h" + +#define SF_BUTTON_DONTMOVE BIT(0) +#define SF_BUTTON_TOGGLE BIT(5) // button stays pushed until reactivated +#define SF_BUTTON_SPARK_IF_OFF BIT(6) // button sparks in OFF state +#define SF_BUTTON_TOUCH_ONLY BIT(8) // button only fires as a result of USE key. + +// Generic Button +class CBaseButton: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; // Buttons that don't take damage can be IMPULSE used +public: + BOOL m_fStayPushed; // button stays pushed in until touched again? + BOOL m_fRotating; // a rotating button? default is a sliding button. + + string_t m_strChangeTarget; // if this field is not null, this is an index into the engine string array. + // when this button is touched, it's target entity's TARGET field will be set + // to the button's ChangeTarget. This allows you to make a func_train switch paths, etc. + + locksound_t m_ls; // door lock sounds + + byte m_bLockedSound; // ordinals from entity selection + byte m_bLockedSentence; + byte m_bUnlockedSound; + byte m_bUnlockedSentence; + int m_sounds; +}; + +// MultiSouce +#define MAX_MS_TARGETS 32 // maximum number of targets a single multisource entity may be assigned. +#define SF_MULTI_INIT BIT(0) + +class CMultiSource: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL IsTriggered(CBaseEntity *pActivator) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + EHANDLE m_rgEntities[MAX_MS_TARGETS]; + int m_rgTriggered[MAX_MS_TARGETS]; + + int m_iTotal; + string_t m_globalstate; +}; + +// Converts a entvars_t * to a class pointer +// It will allocate the class and entity if necessary +template +T *GetClassPtr(T *a) +{ + entvars_t *pev = (entvars_t *)a; + + // allocate entity if necessary + if (pev == nullptr) + pev = VARS(CREATE_ENTITY()); + + // get the private data + a = (T *)GET_PRIVATE(ENT(pev)); + + if (a == nullptr) + { + // allocate private data + a = new(pev) T; + a->pev = pev; + } + + return a; +} + +// Inlines +inline edict_t *CBaseEntity::edict() +{ + return ENT(pev); +} + +inline EOFFSET CBaseEntity::eoffset() +{ + return OFFSET(pev); +} + +inline int CBaseEntity::entindex() +{ + return ENTINDEX(edict()); +} + +inline int CBaseEntity::IsDormant() +{ + return (pev->flags & FL_DORMANT) == FL_DORMANT; +} + +inline bool CBaseEntity::Intersects(CBaseEntity *pOther) +{ + return Intersects(pOther->pev->absmin, pOther->pev->absmax); +} + +inline bool CBaseEntity::Intersects(const Vector &mins, const Vector &maxs) +{ + if (mins.x > pev->absmax.x + || mins.y > pev->absmax.y + || mins.z > pev->absmax.z + || maxs.x < pev->absmin.x + || maxs.y < pev->absmin.y + || maxs.z < pev->absmin.z) + { + return false; + } + + return true; +} diff --git a/dep/hlsdk/dlls/cdll_dll.h b/dep/hlsdk/dlls/cdll_dll.h new file mode 100644 index 0000000..91fc662 --- /dev/null +++ b/dep/hlsdk/dlls/cdll_dll.h @@ -0,0 +1,195 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +const int MAX_WEAPON_SLOTS = 5; // hud item selection slots +const int MAX_ITEM_TYPES = 6; // hud item selection slots +const int MAX_AMMO_SLOTS = 32; // not really slots +const int MAX_ITEMS = 4; // hard coded item types + +const int DEFAULT_FOV = 90; // the default field of view + +#define HIDEHUD_WEAPONS BIT(0) +#define HIDEHUD_FLASHLIGHT BIT(1) +#define HIDEHUD_ALL BIT(2) +#define HIDEHUD_HEALTH BIT(3) +#define HIDEHUD_TIMER BIT(4) +#define HIDEHUD_MONEY BIT(5) +#define HIDEHUD_CROSSHAIR BIT(6) +#define HIDEHUD_OBSERVER_CROSSHAIR BIT(7) + +#define STATUSICON_HIDE 0 +#define STATUSICON_SHOW 1 +#define STATUSICON_FLASH 2 + +#define HUD_PRINTNOTIFY 1 +#define HUD_PRINTCONSOLE 2 +#define HUD_PRINTTALK 3 +#define HUD_PRINTCENTER 4 +#define HUD_PRINTRADIO 5 + +#define TEAM_UNASSIGNED 0 +#define TEAM_TERRORIST 1 +#define TEAM_CT 2 +#define TEAM_SPECTATOR 3 + +#define STATUS_NIGHTVISION_ON 1 +#define STATUS_NIGHTVISION_OFF 0 + +#define ITEM_STATUS_NIGHTVISION BIT(0) +#define ITEM_STATUS_DEFUSER BIT(1) + +#define SCORE_STATUS_DEAD BIT(0) +#define SCORE_STATUS_BOMB BIT(1) +#define SCORE_STATUS_VIP BIT(2) + +// player data iuser3 +#define PLAYER_CAN_SHOOT BIT(0) +#define PLAYER_FREEZE_TIME_OVER BIT(1) +#define PLAYER_IN_BOMB_ZONE BIT(2) +#define PLAYER_HOLDING_SHIELD BIT(3) + +#define MENU_KEY_1 BIT(0) +#define MENU_KEY_2 BIT(1) +#define MENU_KEY_3 BIT(2) +#define MENU_KEY_4 BIT(3) +#define MENU_KEY_5 BIT(4) +#define MENU_KEY_6 BIT(5) +#define MENU_KEY_7 BIT(6) +#define MENU_KEY_8 BIT(7) +#define MENU_KEY_9 BIT(8) +#define MENU_KEY_0 BIT(9) + +#define CS_NUM_SKIN 4 +#define CZ_NUM_SKIN 5 + +#define FIELD_ORIGIN0 0 +#define FIELD_ORIGIN1 1 +#define FIELD_ORIGIN2 2 + +#define FIELD_ANGLES0 3 +#define FIELD_ANGLES1 4 +#define FIELD_ANGLES2 5 + +#define CUSTOMFIELD_ORIGIN0 0 +#define CUSTOMFIELD_ORIGIN1 1 +#define CUSTOMFIELD_ORIGIN2 2 + +#define CUSTOMFIELD_ANGLES0 3 +#define CUSTOMFIELD_ANGLES1 4 +#define CUSTOMFIELD_ANGLES2 5 + +#define CUSTOMFIELD_SKIN 6 +#define CUSTOMFIELD_SEQUENCE 7 +#define CUSTOMFIELD_ANIMTIME 8 + +#define HUD_PRINTNOTIFY 1 +#define HUD_PRINTCONSOLE 2 +#define HUD_PRINTTALK 3 +#define HUD_PRINTCENTER 4 + +#define WEAPON_SUIT 31 +#define WEAPON_ALLWEAPONS (~(1<skin = ENTINDEX(pEntity); + pev->body = attachment; + pev->aiment = pEntity; + pev->movetype = MOVETYPE_FOLLOW; + } + } + + float Frames() const { return m_maxFrame; } + void SetTransparency(int rendermode, int r, int g, int b, int a, int fx) + { + pev->rendermode = rendermode; + pev->rendercolor.x = r; + pev->rendercolor.y = g; + pev->rendercolor.z = b; + pev->renderamt = a; + pev->renderfx = fx; + } + + void SetTexture(int spriteIndex) { pev->modelindex = spriteIndex; } + void SetScale(float scale) { pev->scale = scale; } + void SetColor(int r, int g, int b) { pev->rendercolor.x = r; pev->rendercolor.y = g; pev->rendercolor.z = b; } + void SetBrightness(int brightness) { pev->renderamt = brightness; } + void AnimateAndDie(float framerate) + { + SetThink(&CSprite::AnimateUntilDead); + pev->framerate = framerate; + pev->dmgtime = gpGlobals->time + (m_maxFrame / framerate); + pev->nextthink = gpGlobals->time; + } +private: + float m_lastTime; + float m_maxFrame; +}; + +#define SF_BEAM_STARTON BIT(0) +#define SF_BEAM_TOGGLE BIT(1) +#define SF_BEAM_RANDOM BIT(2) +#define SF_BEAM_RING BIT(3) +#define SF_BEAM_SPARKSTART BIT(4) +#define SF_BEAM_SPARKEND BIT(5) +#define SF_BEAM_DECALS BIT(6) +#define SF_BEAM_SHADEIN BIT(7) +#define SF_BEAM_SHADEOUT BIT(8) +#define SF_BEAM_TEMPORARY BIT(15) + +class CBeam: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int ObjectCaps() = 0; + virtual Vector Center() = 0; +public: + void SetType(int type) { pev->rendermode = (pev->rendermode & 0xF0) | (type & 0x0F); } + void SetFlags(int flags) { pev->rendermode = (pev->rendermode & 0x0F) | (flags & 0xF0); } + void SetStartPos(const Vector &pos) { pev->origin = pos; } + void SetEndPos(const Vector &pos) { pev->angles = pos; } + + void SetStartEntity(int entityIndex); + void SetEndEntity(int entityIndex); + + void SetStartAttachment(int attachment) { pev->sequence = (pev->sequence & 0x0FFF) | ((attachment & 0xF) << 12); } + void SetEndAttachment(int attachment) { pev->skin = (pev->skin & 0x0FFF) | ((attachment & 0xF) << 12); } + void SetTexture(int spriteIndex) { pev->modelindex = spriteIndex; } + void SetWidth(int width) { pev->scale = width; } + void SetNoise(int amplitude) { pev->body = amplitude; } + void SetColor(int r, int g, int b) { pev->rendercolor.x = r; pev->rendercolor.y = g; pev->rendercolor.z = b; } + void SetBrightness(int brightness) { pev->renderamt = brightness; } + void SetFrame(float frame) { pev->frame = frame; } + void SetScrollRate(int speed) { pev->animtime = speed; } + int GetType() const { return pev->rendermode & 0x0F; } + int GetFlags() const { return pev->rendermode & 0xF0; } + int GetStartEntity() const { return pev->sequence & 0xFFF; } + int GetEndEntity() const { return pev->skin & 0xFFF; } + + const Vector &GetStartPos(); + const Vector &GetEndPos(); + + int GetTexture() const { return pev->modelindex; } + int GetWidth() const { return pev->scale; } + int GetNoise() const { return pev->body; } + int GetBrightness() const { return pev->renderamt; } + int GetFrame() const { return pev->frame; } + int GetScrollRate() const { return pev->animtime; } + + void LiveForTime(float time) + { + SetThink(&CBeam::SUB_Remove); + pev->nextthink = gpGlobals->time + time; + } + void BeamDamageInstant(TraceResult *ptr, float damage) + { + pev->dmg = damage; + pev->dmgtime = gpGlobals->time - 1; + BeamDamage(ptr); + } +}; + +class CLaser: public CBeam { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + CSprite *m_pSprite; + int m_iszSpriteName; + Vector m_firePosition; +}; + +#define SF_BUBBLES_STARTOFF BIT(0) + +class CBubbling: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_density; + int m_frequency; + int m_bubbleModel; + int m_state; +}; + +class CLightning: public CBeam { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Activate() = 0; +public: + inline BOOL ServerSide() const + { + if (!m_life && !(pev->spawnflags & SF_BEAM_RING)) + return TRUE; + + return FALSE; + } +public: + int m_active; + int m_iszStartEntity; + int m_iszEndEntity; + float m_life; + int m_boltWidth; + int m_noiseAmplitude; + int m_brightness; + int m_speed; + float m_restrike; + int m_spriteTexture; + int m_iszSpriteName; + int m_frameStart; + float m_radius; +}; + +class CGlow: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Think() = 0; +public: + float m_lastTime; + float m_maxFrame; +}; + +class CBombGlow: public CSprite { +public: + virtual void Spawn() = 0; + virtual void Think() = 0; +public: + float m_lastTime; + float m_tmBeepPeriod; + bool m_bSetModel; +}; + +#define SF_GIBSHOOTER_REPEATABLE BIT(0) // Allows a gibshooter to be refired + +class CGibShooter: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual CGib *CreateGib() = 0; +public: + int m_iGibs; + int m_iGibCapacity; + int m_iGibMaterial; + int m_iGibModelIndex; + + float m_flGibVelocity; + float m_flVariance; + float m_flGibLife; +}; + +class CEnvShooter: public CGibShooter { +public: + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual CGib *CreateGib() = 0; +}; + +const int MAX_BEAM = 24; + +class CTestEffect: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_iLoop; + int m_iBeam; + + CBeam *m_pBeam[MAX_BEAM]; + + float m_flBeamTime[MAX_BEAM]; + float m_flStartTime; +}; + +#define SF_BLOOD_RANDOM BIT(0) +#define SF_BLOOD_STREAM BIT(1) +#define SF_BLOOD_PLAYER BIT(2) +#define SF_BLOOD_DECAL BIT(3) + +class CBlood: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + +public: + int Color() const { return pev->impulse; } + float BloodAmount() const { return pev->dmg; } + + void SetColor(int color) { pev->impulse = color; } + void SetBloodAmount(float amount) { pev->dmg = amount; } +}; + +#define SF_SHAKE_EVERYONE BIT(0) // Don't check radius +#define SF_SHAKE_DISRUPT BIT(1) // Disrupt controls +#define SF_SHAKE_INAIR BIT(2) // Shake players in air + +class CShake: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float Amplitude() const { return pev->scale; } + float Frequency() const { return pev->dmg_save; } + float Duration() const { return pev->dmg_take; } + float Radius() const { return pev->dmg; } + + void SetAmplitude(float amplitude) { pev->scale = amplitude; } + void SetFrequency(float frequency) { pev->dmg_save = frequency; } + void SetDuration(float duration) { pev->dmg_take = duration; } + void SetRadius(float radius) { pev->dmg = radius; } +}; + +#define SF_FADE_IN BIT(0) // Fade in, not out +#define SF_FADE_MODULATE BIT(1) // Modulate, don't blend +#define SF_FADE_ONLYONE BIT(2) + +class CFade: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float Duration() const { return pev->dmg_take; } + float HoldTime() const { return pev->dmg_save; } + + void SetDuration(float duration) { pev->dmg_take = duration; } + void SetHoldTime(float hold) { pev->dmg_save = hold; } +}; + +#define SF_MESSAGE_ONCE BIT(0) // Fade in, not out +#define SF_MESSAGE_ALL BIT(1) // Send to all clients + +class CMessage: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +#define SF_FUNNEL_REVERSE BIT(0) // Funnel effect repels particles instead of attracting them + +class CEnvFunnel: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_iSprite; +}; + +class CEnvBeverage: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +class CItemSoda: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; +}; + +// Inlines +inline void CBeam::SetStartEntity(int entityIndex) +{ + pev->sequence = (entityIndex & 0x0FFF) | ((pev->sequence & 0xF000) << 12); + pev->owner = INDEXENT(entityIndex); +} + +inline void CBeam::SetEndEntity(int entityIndex) +{ + pev->skin = (entityIndex & 0x0FFF) | ((pev->skin & 0xF000) << 12); + pev->aiment = INDEXENT(entityIndex); +} + +inline const Vector &CBeam::GetStartPos() +{ + if (GetType() == BEAM_ENTS) + { + edict_t *pent = INDEXENT(GetStartEntity()); + return pent->v.origin; + } + + return pev->origin; +} + +inline const Vector &CBeam::GetEndPos() +{ + int type = GetType(); + if (type == BEAM_POINTS || type == BEAM_HOSE) + { + return pev->angles; + } + + edict_t *pent = INDEXENT(GetEndEntity()); + if (pent) + { + return pent->v.origin; + } + + return pev->angles; +} diff --git a/dep/hlsdk/dlls/ehandle.h b/dep/hlsdk/dlls/ehandle.h new file mode 100644 index 0000000..66897fb --- /dev/null +++ b/dep/hlsdk/dlls/ehandle.h @@ -0,0 +1,239 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Safe way to point to CBaseEntities who may die between frames. +template +class EntityHandle +{ +public: + EntityHandle() : m_edict(nullptr), m_serialnumber(0) {} + EntityHandle(const EntityHandle &other); + EntityHandle(const T *pEntity); + EntityHandle(const edict_t *pEdict); + + // cast to base class + // NOTE: this is a unsafe method + template + R *Get() const; + + edict_t *Get() const; + edict_t *Set(edict_t *pEdict); + + void Remove(); + bool IsValid() const; + int GetSerialNumber() const; + + bool operator==(T *pEntity) const; + operator bool() const; + operator T *() const; + + T *operator=(T *pEntity); + T *operator->(); + + // Copy the ehandle. + EntityHandle& operator=(const EntityHandle &other); + +private: + edict_t *m_edict; + int m_serialnumber; +}; + +// Short alias +using EHandle = EntityHandle<>; +using EHANDLE = EHandle; + +// Inlines +template +inline bool FNullEnt(EntityHandle &hent) +{ + return (!hent || FNullEnt(OFFSET(hent.Get()))); +} + +// Copy constructor +template +EntityHandle::EntityHandle(const EntityHandle &other) +{ + m_edict = other.m_edict; + m_serialnumber = other.m_serialnumber; +} + +template +EntityHandle::EntityHandle(const T *pEntity) +{ + if (pEntity) + { + Set(ENT(pEntity->pev)); + } + else + { + m_edict = nullptr; + m_serialnumber = 0; + } +} + +template +EntityHandle::EntityHandle(const edict_t *pEdict) +{ + Set(const_cast(pEdict)); +} + +template +template +inline R *EntityHandle::Get() const +{ + return GET_PRIVATE(Get()); +} + +template +inline edict_t *EntityHandle::Get() const +{ + if (!m_edict || m_edict->serialnumber != m_serialnumber || m_edict->free) + { + return nullptr; + } + + return m_edict; +} + +template +inline edict_t *EntityHandle::Set(edict_t *pEdict) +{ + m_edict = pEdict; + if (pEdict) + { + m_serialnumber = pEdict->serialnumber; + } + + return pEdict; +} + +template +void EntityHandle::Remove() +{ + if (IsValid()) + { + UTIL_Remove(*this); + } + + m_edict = nullptr; + m_serialnumber = 0; +} + +// Returns whether this handle is valid. +template +inline bool EntityHandle::IsValid() const +{ + edict_t *pEdict = Get(); + if (!pEdict) + { + return false; + } + + CBaseEntity *pEntity = GET_PRIVATE(pEdict); + if (!pEntity) + { + return false; + } + + return true; +} + +// CBaseEntity serial number. +// Used to determine if the entity is still valid. +template +inline int EntityHandle::GetSerialNumber() const +{ + return m_serialnumber; +} + +template +inline bool EntityHandle::operator==(T *pEntity) const +{ + assert(("EntityHandle::operator==: got a nullptr pointer!", pEntity != nullptr)); + + if (m_serialnumber != pEntity->edict()->serialnumber) + { + return false; + } + + return m_edict == pEntity->edict(); +} + +template +inline EntityHandle::operator bool() const +{ + return IsValid(); +} + +// Gets the Entity this handle refers to. +// Returns null if invalid. +template +inline EntityHandle::operator T *() const +{ + return GET_PRIVATE(Get()); +} + +// Assigns the given entity to this handle. +template +inline T *EntityHandle::operator=(T *pEntity) +{ + if (pEntity) + { + Set(ENT(pEntity->pev)); + } + else + { + m_edict = nullptr; + m_serialnumber = 0; + } + + return static_cast(pEntity); +} + +template +inline T *EntityHandle::operator->() +{ + edict_t *pEdict = Get(); + assert(("EntityHandle::operator->: pointer is nullptr!", pEdict != nullptr)); + + T *pEntity = GET_PRIVATE(pEdict); + assert(("EntityHandle::operator->: pvPrivateData is nullptr!", pEntity != nullptr)); + return pEntity; +} + +// Makes this handle refer to the same entity as the given handle. +template +inline EntityHandle& EntityHandle::operator=(const EntityHandle &other) +{ + m_edict = other.m_edict; + m_serialnumber = other.m_serialnumber; + + return (*this); +} diff --git a/dep/hlsdk/dlls/enginecallback.h b/dep/hlsdk/dlls/enginecallback.h new file mode 100644 index 0000000..93150ac --- /dev/null +++ b/dep/hlsdk/dlls/enginecallback.h @@ -0,0 +1,186 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "event_flags.h" + +// Must be provided by user of this code +extern enginefuncs_t g_engfuncs; + +// The actual engine callbacks +#define GETPLAYERUSERID (*g_engfuncs.pfnGetPlayerUserId) +#define PRECACHE_MODEL (*g_engfuncs.pfnPrecacheModel) +#define PRECACHE_SOUND (*g_engfuncs.pfnPrecacheSound) +#define PRECACHE_GENERIC (*g_engfuncs.pfnPrecacheGeneric) +#define SET_MODEL (*g_engfuncs.pfnSetModel) +#define MODEL_INDEX (*g_engfuncs.pfnModelIndex) +#define MODEL_FRAMES (*g_engfuncs.pfnModelFrames) +#define SET_SIZE (*g_engfuncs.pfnSetSize) +#define CHANGE_LEVEL (*g_engfuncs.pfnChangeLevel) +#define GET_SPAWN_PARMS (*g_engfuncs.pfnGetSpawnParms) +#define SAVE_SPAWN_PARMS (*g_engfuncs.pfnSaveSpawnParms) +#define VEC_TO_YAW (*g_engfuncs.pfnVecToYaw) +#define VEC_TO_ANGLES (*g_engfuncs.pfnVecToAngles) +#define MOVE_TO_ORIGIN (*g_engfuncs.pfnMoveToOrigin) +#define oldCHANGE_YAW (*g_engfuncs.pfnChangeYaw) +#define CHANGE_PITCH (*g_engfuncs.pfnChangePitch) +#define MAKE_VECTORS (*g_engfuncs.pfnMakeVectors) +#define CREATE_ENTITY (*g_engfuncs.pfnCreateEntity) +#define REMOVE_ENTITY (*g_engfuncs.pfnRemoveEntity) +#define CREATE_NAMED_ENTITY (*g_engfuncs.pfnCreateNamedEntity) +#define MAKE_STATIC (*g_engfuncs.pfnMakeStatic) +#define ENT_IS_ON_FLOOR (*g_engfuncs.pfnEntIsOnFloor) +#define DROP_TO_FLOOR (*g_engfuncs.pfnDropToFloor) +#define WALK_MOVE (*g_engfuncs.pfnWalkMove) +#define SET_ORIGIN (*g_engfuncs.pfnSetOrigin) +#define EMIT_SOUND_DYN2 (*g_engfuncs.pfnEmitSound) +#define BUILD_SOUND_MSG (*g_engfuncs.pfnBuildSoundMsg) +#define TRACE_LINE (*g_engfuncs.pfnTraceLine) +#define TRACE_TOSS (*g_engfuncs.pfnTraceToss) +#define TRACE_MONSTER_HULL (*g_engfuncs.pfnTraceMonsterHull) +#define TRACE_HULL (*g_engfuncs.pfnTraceHull) +#define TRACE_MODEL (*g_engfuncs.pfnTraceModel) +#define GET_AIM_VECTOR (*g_engfuncs.pfnGetAimVector) +#define SERVER_COMMAND (*g_engfuncs.pfnServerCommand) +#define SERVER_EXECUTE (*g_engfuncs.pfnServerExecute) +#define CLIENT_COMMAND (*g_engfuncs.pfnClientCommand) +#define PARTICLE_EFFECT (*g_engfuncs.pfnParticleEffect) +#define LIGHT_STYLE (*g_engfuncs.pfnLightStyle) +#define DECAL_INDEX (*g_engfuncs.pfnDecalIndex) +#define POINT_CONTENTS (*g_engfuncs.pfnPointContents) +#define CRC32_INIT (*g_engfuncs.pfnCRC32_Init) +#define CRC32_PROCESS_BUFFER (*g_engfuncs.pfnCRC32_ProcessBuffer) +#define CRC32_PROCESS_BYTE (*g_engfuncs.pfnCRC32_ProcessByte) +#define CRC32_FINAL (*g_engfuncs.pfnCRC32_Final) +#define RANDOM_LONG (*g_engfuncs.pfnRandomLong) +#define RANDOM_FLOAT (*g_engfuncs.pfnRandomFloat) +#define ADD_SERVER_COMMAND (*g_engfuncs.pfnAddServerCommand) +#define SET_CLIENT_LISTENING (*g_engfuncs.pfnVoice_SetClientListening) +#define GETPLAYERAUTHID (*g_engfuncs.pfnGetPlayerAuthId) +#define GET_FILE_SIZE (*g_engfuncs.pfnGetFileSize) +#define GET_APPROX_WAVE_PLAY_LEN (*g_engfuncs.pfnGetApproxWavePlayLen) +#define IS_CAREER_MATCH (*g_engfuncs.pfnIsCareerMatch) +#define GET_LOCALIZED_STRING_LENGTH (*g_engfuncs.pfnGetLocalizedStringLength) +#define REGISTER_TUTOR_MESSAGE_SHOWN (*g_engfuncs.pfnRegisterTutorMessageShown) +#define GET_TIMES_TUTOR_MESSAGE_SHOWN (*g_engfuncs.pfnGetTimesTutorMessageShown) +#define ENG_CHECK_PARM (*g_engfuncs.pfnEngCheckParm) + +inline void MESSAGE_BEGIN(int msg_dest, int msg_type, const float *pOrigin = nullptr, edict_t *ed = nullptr) +{ + (*g_engfuncs.pfnMessageBegin)(msg_dest, msg_type, pOrigin, ed); +} + +template +inline T *GET_PRIVATE(edict_t *pEdict) +{ + if (pEdict) + { + return static_cast(pEdict->pvPrivateData); + } + + return nullptr; +} + +#define MESSAGE_END (*g_engfuncs.pfnMessageEnd) +#define WRITE_BYTE (*g_engfuncs.pfnWriteByte) +#define WRITE_CHAR (*g_engfuncs.pfnWriteChar) +#define WRITE_SHORT (*g_engfuncs.pfnWriteShort) +#define WRITE_LONG (*g_engfuncs.pfnWriteLong) +#define WRITE_ANGLE (*g_engfuncs.pfnWriteAngle) +#define WRITE_COORD (*g_engfuncs.pfnWriteCoord) +#define WRITE_STRING (*g_engfuncs.pfnWriteString) +#define WRITE_ENTITY (*g_engfuncs.pfnWriteEntity) +#define CVAR_REGISTER (*g_engfuncs.pfnCVarRegister) +#define CVAR_GET_FLOAT (*g_engfuncs.pfnCVarGetFloat) +#define CVAR_GET_STRING (*g_engfuncs.pfnCVarGetString) +#define CVAR_SET_FLOAT (*g_engfuncs.pfnCVarSetFloat) +#define CVAR_SET_STRING (*g_engfuncs.pfnCVarSetString) +#define CVAR_GET_POINTER (*g_engfuncs.pfnCVarGetPointer) +#define ALERT (*g_engfuncs.pfnAlertMessage) +#define ENGINE_FPRINTF (*g_engfuncs.pfnEngineFprintf) +#define ALLOC_PRIVATE (*g_engfuncs.pfnPvAllocEntPrivateData) +#define FREE_PRIVATE (*g_engfuncs.pfnFreeEntPrivateData) +//#define STRING (*g_engfuncs.pfnSzFromIndex) +#define ALLOC_STRING (*g_engfuncs.pfnAllocString) +#define FIND_ENTITY_BY_STRING (*g_engfuncs.pfnFindEntityByString) +#define GETENTITYILLUM (*g_engfuncs.pfnGetEntityIllum) +#define FIND_ENTITY_IN_SPHERE (*g_engfuncs.pfnFindEntityInSphere) +#define FIND_CLIENT_IN_PVS (*g_engfuncs.pfnFindClientInPVS) +#define FIND_ENTITY_IN_PVS (*g_engfuncs.pfnEntitiesInPVS) +#define EMIT_AMBIENT_SOUND (*g_engfuncs.pfnEmitAmbientSound) +#define GET_MODEL_PTR (*g_engfuncs.pfnGetModelPtr) +#define REG_USER_MSG (*g_engfuncs.pfnRegUserMsg) +#define GET_BONE_POSITION (*g_engfuncs.pfnGetBonePosition) +#define FUNCTION_FROM_NAME (*g_engfuncs.pfnFunctionFromName) +#define NAME_FOR_FUNCTION (*g_engfuncs.pfnNameForFunction) +#define TRACE_TEXTURE (*g_engfuncs.pfnTraceTexture) +#define CLIENT_PRINTF (*g_engfuncs.pfnClientPrintf) +#define SERVER_PRINT (*g_engfuncs.pfnServerPrint) +#define CMD_ARGS (*g_engfuncs.pfnCmd_Args) +#define CMD_ARGC (*g_engfuncs.pfnCmd_Argc) +#define CMD_ARGV (*g_engfuncs.pfnCmd_Argv) +#define GET_ATTACHMENT (*g_engfuncs.pfnGetAttachment) +#define SET_VIEW (*g_engfuncs.pfnSetView) +#define SET_CROSSHAIRANGLE (*g_engfuncs.pfnCrosshairAngle) +#define LOAD_FILE_FOR_ME (*g_engfuncs.pfnLoadFileForMe) +#define FREE_FILE (*g_engfuncs.pfnFreeFile) +#define END_SECTION (*g_engfuncs.pfnEndSection) +#define COMPARE_FILE_TIME (*g_engfuncs.pfnCompareFileTime) +#define GET_GAME_DIR (*g_engfuncs.pfnGetGameDir) +#define SET_CLIENT_MAXSPEED (*g_engfuncs.pfnSetClientMaxspeed) +#define CREATE_FAKE_CLIENT (*g_engfuncs.pfnCreateFakeClient) +#define PLAYER_RUN_MOVE (*g_engfuncs.pfnRunPlayerMove) +#define NUMBER_OF_ENTITIES (*g_engfuncs.pfnNumberOfEntities) +#define GET_INFO_BUFFER (*g_engfuncs.pfnGetInfoKeyBuffer) +#define GET_KEY_VALUE (*g_engfuncs.pfnInfoKeyValue) +#define SET_KEY_VALUE (*g_engfuncs.pfnSetKeyValue) +#define SET_CLIENT_KEY_VALUE (*g_engfuncs.pfnSetClientKeyValue) +#define IS_MAP_VALID (*g_engfuncs.pfnIsMapValid) +#define STATIC_DECAL (*g_engfuncs.pfnStaticDecal) +#define IS_DEDICATED_SERVER (*g_engfuncs.pfnIsDedicatedServer) +#define PRECACHE_EVENT (*g_engfuncs.pfnPrecacheEvent) +#define PLAYBACK_EVENT_FULL (*g_engfuncs.pfnPlaybackEvent) +#define ENGINE_SET_PVS (*g_engfuncs.pfnSetFatPVS) +#define ENGINE_SET_PAS (*g_engfuncs.pfnSetFatPAS) +#define ENGINE_CHECK_VISIBILITY (*g_engfuncs.pfnCheckVisibility) +#define DELTA_SET (*g_engfuncs.pfnDeltaSetField) +#define DELTA_UNSET (*g_engfuncs.pfnDeltaUnsetField) +#define DELTA_ADDENCODER (*g_engfuncs.pfnDeltaAddEncoder) +#define ENGINE_CURRENT_PLAYER (*g_engfuncs.pfnGetCurrentPlayer) +#define ENGINE_CANSKIP (*g_engfuncs.pfnCanSkipPlayer) +#define DELTA_FINDFIELD (*g_engfuncs.pfnDeltaFindField) +#define DELTA_SETBYINDEX (*g_engfuncs.pfnDeltaSetFieldByIndex) +#define DELTA_UNSETBYINDEX (*g_engfuncs.pfnDeltaUnsetFieldByIndex) +#define REMOVE_KEY_VALUE (*g_engfuncs.pfnInfo_RemoveKey) +#define SET_PHYSICS_KEY_VALUE (*g_engfuncs.pfnSetPhysicsKeyValue) +#define ENGINE_GETPHYSINFO (*g_engfuncs.pfnGetPhysicsInfoString) +#define ENGINE_SETGROUPMASK (*g_engfuncs.pfnSetGroupMask) +#define ENGINE_INSTANCE_BASELINE (*g_engfuncs.pfnCreateInstancedBaseline) +#define ENGINE_FORCE_UNMODIFIED (*g_engfuncs.pfnForceUnmodified) +#define PLAYER_CNX_STATS (*g_engfuncs.pfnGetPlayerStats) diff --git a/dep/hlsdk/dlls/explode.h b/dep/hlsdk/dlls/explode.h new file mode 100644 index 0000000..67a73f7 --- /dev/null +++ b/dep/hlsdk/dlls/explode.h @@ -0,0 +1,56 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CShower: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int ObjectCaps() = 0; + virtual void Think() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +}; + +#define SF_ENVEXPLOSION_NODAMAGE BIT(0) // when set, ENV_EXPLOSION will not actually inflict damage +#define SF_ENVEXPLOSION_REPEATABLE BIT(1) // can this entity be refired? +#define SF_ENVEXPLOSION_NOFIREBALL BIT(2) // don't draw the fireball +#define SF_ENVEXPLOSION_NOSMOKE BIT(3) // don't draw the smoke +#define SF_ENVEXPLOSION_NODECAL BIT(4) // don't make a scorch mark +#define SF_ENVEXPLOSION_NOSPARKS BIT(5) // don't make a scorch mark + +class CEnvExplosion: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_iMagnitude; + int m_spriteScale; +}; diff --git a/dep/hlsdk/dlls/extdef.h b/dep/hlsdk/dlls/extdef.h new file mode 100644 index 0000000..ed204fe --- /dev/null +++ b/dep/hlsdk/dlls/extdef.h @@ -0,0 +1,115 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "regamedll_const.h" + +#undef DLLEXPORT +#ifdef _WIN32 + // Attributes to specify an "exported" function, visible from outside the + // DLL. + #define DLLEXPORT __declspec(dllexport) + // WINAPI should be provided in the windows compiler headers. + // It's usually defined to something like "__stdcall". + + #define NOINLINE __declspec(noinline) +#else + #define DLLEXPORT __attribute__((visibility("default"))) + #define WINAPI /* */ + #define NOINLINE __attribute__((noinline)) +#endif // _WIN32 + +// Manual branch optimization for GCC 3.0.0 and newer +#if !defined(__GNUC__) || __GNUC__ < 3 + #define likely(x) (x) + #define unlikely(x) (x) +#else + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#endif + +const int MAX_MAPNAME_LENGHT = 32; + +// Simplified macro for declaring/defining exported DLL functions. They +// need to be 'extern "C"' so that the C++ compiler enforces parameter +// type-matching, rather than considering routines with mis-matched +// arguments/types to be overloaded functions... +// +// AFAIK, this is os-independent, but it's included here in osdep.h where +// DLLEXPORT is defined, for convenience. +#define C_DLLEXPORT extern "C" DLLEXPORT + +enum hash_types_e { CLASSNAME }; + +// Things that toggle (buttons/triggers/doors) need this +enum TOGGLE_STATE { TS_AT_TOP, TS_AT_BOTTOM, TS_GOING_UP, TS_GOING_DOWN }; + +typedef struct hash_item_s +{ + entvars_t *pev; + struct hash_item_s *next; + struct hash_item_s *lastHash; + int pevIndex; + +} hash_item_t; + +typedef struct locksounds +{ + string_t sLockedSound; + string_t sLockedSentence; + string_t sUnlockedSound; + string_t sUnlockedSentence; + int iLockedSentence; + int iUnlockedSentence; + float flwaitSound; + float flwaitSentence; + byte bEOFLocked; + byte bEOFUnlocked; + +} locksound_t; + +typedef struct hudtextparms_s +{ + float x; + float y; + int effect; + byte r1,g1,b1,a1; + byte r2,g2,b2,a2; + float fadeinTime; + float fadeoutTime; + float holdTime; + float fxTime; + int channel; + +} hudtextparms_t; + +enum USE_TYPE { USE_OFF, USE_ON, USE_SET, USE_TOGGLE }; +enum IGNORE_MONSTERS { ignore_monsters = 1, dont_ignore_monsters = 0, missile = 2 }; +enum IGNORE_GLASS { ignore_glass = 1, dont_ignore_glass = 0 }; +enum { point_hull = 0, human_hull = 1, large_hull = 2, head_hull = 3 }; diff --git a/dep/hlsdk/dlls/extdll.h b/dep/hlsdk/dlls/extdll.h new file mode 100644 index 0000000..1c242c3 --- /dev/null +++ b/dep/hlsdk/dlls/extdll.h @@ -0,0 +1,82 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#pragma warning(disable:4244) // int or float down-conversion +#pragma warning(disable:4305) // int or float data truncation +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4514) // unreferenced inline function removed +#pragma warning(disable:4100) // unreferenced formal parameter + +#include "basetypes.h" +#include "maintypes.h" +#include "strtools.h" + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN + #define NOWINRES + #define NOSERVICE + #define NOMCX + #define NOIME + #include "winsani_in.h" + #include "windows.h" + #include "winsani_out.h" + #undef PlaySound +#else + #include + #include + #include +#endif // _WIN32 + +// Misc C-runtime library headers +#include "stdio.h" +#include "stdlib.h" +#include "math.h" + +// Header file containing definition of globalvars_t and entvars_t +typedef int EOFFSET; // More explicit than "int" +typedef unsigned int func_t; +typedef unsigned int string_t; // from engine's pr_comp.h; +typedef float vec_t; // needed before including progdefs.h + +// Vector class +#include "vector.h" +//#include "vector.h" +// Defining it as a (bogus) struct helps enforce type-checking +#define vec3_t Vector +// Shared engine/DLL constants + +#include "const.h" +#include "edict.h" + +// Shared header describing protocol between engine and DLLs +#include "eiface.h" +// Shared header between the client DLL and the game DLLs +#include "cdll_dll.h" +#include "extdef.h" diff --git a/dep/hlsdk/dlls/func_break.h b/dep/hlsdk/dlls/func_break.h new file mode 100644 index 0000000..c618a31 --- /dev/null +++ b/dep/hlsdk/dlls/func_break.h @@ -0,0 +1,118 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +enum Explosions +{ + expRandom = 0, + expDirected, +}; + +enum Materials +{ + matGlass = 0, + matWood, + matMetal, + matFlesh, + matCinderBlock, + matCeilingTile, + matComputer, + matUnbreakableGlass, + matRocks, + matNone, + matLastMaterial, +}; + +// this many shards spawned when breakable objects break +#define NUM_SHARDS 6 // this many shards spawned when breakable objects break + +// func breakable +#define SF_BREAK_TRIGGER_ONLY BIT(0) // may only be broken by trigger +#define SF_BREAK_TOUCH BIT(1) // can be 'crashed through' by running player (plate glass) +#define SF_BREAK_PRESSURE BIT(2) // can be broken by a player standing on it +#define SF_BREAK_CROWBAR BIT(8) // instant break if hit with crowbar + +class CBreakable: public CBaseDelay { +public: + // basic functions + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + + // To spark when hit + virtual void TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + + // breakables use an overridden takedamage + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + + virtual int DamageDecal(int bitsDamageType) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + +public: + BOOL Explodable() const { return ExplosionMagnitude() > 0; } + int ExplosionMagnitude() const { return pev->impulse; } + void ExplosionSetMagnitude(int magnitude) { pev->impulse = magnitude; } + +public: + Materials m_Material; + Explosions m_Explosion; + int m_idShard; + float m_angle; + int m_iszGibModel; + int m_iszSpawnObject; + float m_flHealth; +}; + +#define SF_PUSH_BREAKABLE BIT(7) // func_pushable (it's also func_breakable, so don't collide with those flags) + +class CPushable: public CBreakable { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + +public: + float MaxSpeed() const { return m_maxSpeed; } + +public: + int m_lastSound; + float m_maxSpeed; + float m_soundTime; +}; diff --git a/dep/hlsdk/dlls/func_tank.h b/dep/hlsdk/dlls/func_tank.h new file mode 100644 index 0000000..63c3ff8 --- /dev/null +++ b/dep/hlsdk/dlls/func_tank.h @@ -0,0 +1,161 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +enum TANKBULLET +{ + TANK_BULLET_NONE = 0, // Custom damage + TANK_BULLET_9MM, // env_laser (duration is 0.5 rate of fire) + TANK_BULLET_MP5, // rockets + TANK_BULLET_12MM, // explosion? +}; + +#define SF_TANK_ACTIVE BIT(0) +#define SF_TANK_PLAYER BIT(1) +#define SF_TANK_HUMANS BIT(2) +#define SF_TANK_ALIENS BIT(3) +#define SF_TANK_LINEOFSIGHT BIT(4) +#define SF_TANK_CANCONTROL BIT(5) + +#define SF_TANK_SOUNDON BIT(15) + +class CFuncTank: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + + // Bmodels don't go across transitions + virtual int ObjectCaps() = 0; + virtual BOOL OnControls(entvars_t *pevTest) = 0; + virtual void Think() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void Fire(const Vector &barrelEnd, const Vector &forward, entvars_t *pevAttacker) = 0; + virtual Vector UpdateTargetPosition(CBaseEntity *pTarget) = 0; +public: + BOOL IsActive() const { return (pev->spawnflags & SF_TANK_ACTIVE) == SF_TANK_ACTIVE; } + void TankActivate() + { + pev->spawnflags |= SF_TANK_ACTIVE; + pev->nextthink = pev->ltime + 0.1f; + m_fireLast = 0.0f; + } + void TankDeactivate() + { + pev->spawnflags &= ~SF_TANK_ACTIVE; + m_fireLast = 0.0f; + StopRotSound(); + } + + BOOL CanFire() const { return (gpGlobals->time - m_lastSightTime) < m_persist; } + Vector BarrelPosition() + { + Vector forward, right, up; + UTIL_MakeVectorsPrivate(pev->angles, forward, right, up); + return pev->origin + (forward * m_barrelPos.x) + (right * m_barrelPos.y) + (up * m_barrelPos.z); + } +protected: + CBasePlayer *m_pController; + float m_flNextAttack; + Vector m_vecControllerUsePos; + + float m_yawCenter; // "Center" yaw + float m_yawRate; // Max turn rate to track targets + float m_yawRange; // Range of turning motion (one-sided: 30 is +/- 30 degress from center) + // Zero is full rotation + + float m_yawTolerance; // Tolerance angle + + float m_pitchCenter; // "Center" pitch + float m_pitchRate; // Max turn rate on pitch + float m_pitchRange; // Range of pitch motion as above + float m_pitchTolerance; // Tolerance angle + + float m_fireLast; // Last time I fired + float m_fireRate; // How many rounds/second + float m_lastSightTime; // Last time I saw target + float m_persist; // Persistence of firing (how long do I shoot when I can't see) + float m_minRange; // Minimum range to aim/track + float m_maxRange; // Max range to aim/track + + Vector m_barrelPos; // Length of the freakin barrel + float m_spriteScale; // Scale of any sprites we shoot + int m_iszSpriteSmoke; + int m_iszSpriteFlash; + TANKBULLET m_bulletType;// Bullet type + int m_iBulletDamage; // 0 means use Bullet type's default damage + + Vector m_sightOrigin; // Last sight of target + int m_spread; // firing spread + int m_iszMaster; // Master entity (game_team_master or multisource) +}; + +class CFuncTankGun: public CFuncTank { +public: + virtual void Fire(const Vector &barrelEnd, const Vector &forward, entvars_t *pevAttacker) = 0; +}; + +class CFuncTankLaser: public CFuncTank { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Activate() = 0; + virtual void Think() = 0; + virtual void Fire(const Vector &barrelEnd, const Vector &forward, entvars_t *pevAttacker) = 0; +public: + CLaser *m_pLaser; + float m_laserTime; +}; + +class CFuncTankRocket: public CFuncTank { +public: + virtual void Precache() = 0; + virtual void Fire(const Vector &barrelEnd, const Vector &forward, entvars_t *pevAttacker) = 0; +}; + +class CFuncTankMortar: public CFuncTank { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Fire(const Vector &barrelEnd, const Vector &forward, entvars_t *pevAttacker) = 0; +}; + +class CFuncTankControls: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Think() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + CFuncTank *m_pTank; +}; diff --git a/dep/hlsdk/dlls/gamerules.h b/dep/hlsdk/dlls/gamerules.h new file mode 100644 index 0000000..aa9ee6e --- /dev/null +++ b/dep/hlsdk/dlls/gamerules.h @@ -0,0 +1,690 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "voice_gamemgr.h" + +const int MAX_RULE_BUFFER = 1024; +const int MAX_VOTE_MAPS = 100; +const int MAX_VIP_QUEUES = 5; + +const int MAX_MOTD_CHUNK = 60; +const int MAX_MOTD_LENGTH = 1536; // (MAX_MOTD_CHUNK * 4) + +const float ITEM_RESPAWN_TIME = 30; +const float WEAPON_RESPAWN_TIME = 20; +const float AMMO_RESPAWN_TIME = 20; +const float ROUND_RESPAWN_TIME = 20; +const float ROUND_BEGIN_DELAY = 5; // delay before beginning new round + +// longest the intermission can last, in seconds +const int MAX_INTERMISSION_TIME = 120; + +// when we are within this close to running out of entities, items +// marked with the ITEM_FLAG_LIMITINWORLD will delay their respawn +const int ENTITY_INTOLERANCE = 100; + +// custom enum +#define WINNER_NONE 0 +#define WINNER_DRAW 1 + +enum +{ + WINSTATUS_NONE = 0, + WINSTATUS_CTS, + WINSTATUS_TERRORISTS, + WINSTATUS_DRAW, +}; + +// Custom enum +// Used for EndRoundMessage() logged messages +enum ScenarioEventEndRound +{ + ROUND_NONE, + ROUND_TARGET_BOMB, + ROUND_VIP_ESCAPED, + ROUND_VIP_ASSASSINATED, + ROUND_TERRORISTS_ESCAPED, + ROUND_CTS_PREVENT_ESCAPE, + ROUND_ESCAPING_TERRORISTS_NEUTRALIZED, + ROUND_BOMB_DEFUSED, + ROUND_CTS_WIN, + ROUND_TERRORISTS_WIN, + ROUND_END_DRAW, + ROUND_ALL_HOSTAGES_RESCUED, + ROUND_TARGET_SAVED, + ROUND_HOSTAGE_NOT_RESCUED, + ROUND_TERRORISTS_NOT_ESCAPED, + ROUND_VIP_NOT_ESCAPED, + ROUND_GAME_COMMENCE, + ROUND_GAME_RESTART, + ROUND_GAME_OVER +}; + +enum RewardRules +{ + RR_CTS_WIN, + RR_TERRORISTS_WIN, + RR_TARGET_BOMB, + RR_VIP_ESCAPED, + RR_VIP_ASSASSINATED, + RR_TERRORISTS_ESCAPED, + RR_CTS_PREVENT_ESCAPE, + RR_ESCAPING_TERRORISTS_NEUTRALIZED, + RR_BOMB_DEFUSED, + RR_BOMB_PLANTED, + RR_BOMB_EXPLODED, + RR_ALL_HOSTAGES_RESCUED, + RR_TARGET_BOMB_SAVED, + RR_HOSTAGE_NOT_RESCUED, + RR_VIP_NOT_ESCAPED, + RR_LOSER_BONUS_DEFAULT, + RR_LOSER_BONUS_MIN, + RR_LOSER_BONUS_MAX, + RR_LOSER_BONUS_ADD, + RR_RESCUED_HOSTAGE, + RR_TOOK_HOSTAGE_ACC, + RR_TOOK_HOSTAGE, + RR_END +}; + +// custom enum +enum RewardAccount +{ + REWARD_TARGET_BOMB = 3500, + REWARD_VIP_ESCAPED = 3500, + REWARD_VIP_ASSASSINATED = 3250, + REWARD_TERRORISTS_ESCAPED = 3150, + REWARD_CTS_PREVENT_ESCAPE = 3500, + REWARD_ESCAPING_TERRORISTS_NEUTRALIZED = 3250, + REWARD_BOMB_DEFUSED = 3250, + REWARD_BOMB_PLANTED = 800, + REWARD_BOMB_EXPLODED = 3250, + REWARD_CTS_WIN = 3000, + REWARD_TERRORISTS_WIN = 3000, + REWARD_ALL_HOSTAGES_RESCUED = 2500, + + // the end round was by the expiration time + REWARD_TARGET_BOMB_SAVED = 3250, + REWARD_HOSTAGE_NOT_RESCUED = 3250, + REWARD_VIP_NOT_ESCAPED = 3250, + + // loser bonus + REWARD_LOSER_BONUS_DEFAULT = 1400, + REWARD_LOSER_BONUS_MIN = 1500, + REWARD_LOSER_BONUS_MAX = 3000, + REWARD_LOSER_BONUS_ADD = 500, + + REWARD_RESCUED_HOSTAGE = 750, + REWARD_KILLED_ENEMY = 300, + REWARD_KILLED_VIP = 2500, + REWARD_VIP_HAVE_SELF_RESCUED = 2500, + + REWARD_TAKEN_HOSTAGE = 1000, + REWARD_TOOK_HOSTAGE_ACC = 100, + REWARD_TOOK_HOSTAGE = 150, +}; + +// custom enum +enum PaybackForBadThing +{ + PAYBACK_FOR_KILLED_TEAMMATES = -3300, +}; + +// custom enum +enum InfoMapBuyParam +{ + BUYING_EVERYONE = 0, + BUYING_ONLY_CTS, + BUYING_ONLY_TERRORISTS, + BUYING_NO_ONE, +}; + +// weapon respawning return codes +enum +{ + GR_NONE = 0, + + GR_WEAPON_RESPAWN_YES, + GR_WEAPON_RESPAWN_NO, + + GR_AMMO_RESPAWN_YES, + GR_AMMO_RESPAWN_NO, + + GR_ITEM_RESPAWN_YES, + GR_ITEM_RESPAWN_NO, + + GR_PLR_DROP_GUN_ALL, + GR_PLR_DROP_GUN_ACTIVE, + GR_PLR_DROP_GUN_NO, + + GR_PLR_DROP_AMMO_ALL, + GR_PLR_DROP_AMMO_ACTIVE, + GR_PLR_DROP_AMMO_NO, +}; + +// custom enum +enum +{ + SCENARIO_BLOCK_TIME_EXPRIRED = BIT(0), // flag "a" + SCENARIO_BLOCK_NEED_PLAYERS = BIT(1), // flag "b" + SCENARIO_BLOCK_VIP_ESCAPE = BIT(2), // flag "c" + SCENARIO_BLOCK_PRISON_ESCAPE = BIT(3), // flag "d" + SCENARIO_BLOCK_BOMB = BIT(4), // flag "e" + SCENARIO_BLOCK_TEAM_EXTERMINATION = BIT(5), // flag "f" + SCENARIO_BLOCK_HOSTAGE_RESCUE = BIT(6), // flag "g" +}; + +// Player relationship return codes +enum +{ + GR_NOTTEAMMATE = 0, + GR_TEAMMATE, + GR_ENEMY, + GR_ALLY, + GR_NEUTRAL, +}; + +class CItem; + +class CGameRules { +protected: + virtual ~CGameRules() {}; +public: + virtual void RefreshSkillData() = 0; // fill skill data struct with proper values + virtual void Think() = 0; // runs every server frame, should handle any timer tasks, periodic events, etc. + virtual BOOL IsAllowedToSpawn(CBaseEntity *pEntity) = 0; // Can this item spawn (eg monsters don't spawn in deathmatch). + + virtual BOOL FAllowFlashlight() = 0; // Are players allowed to switch on their flashlight? + virtual BOOL FShouldSwitchWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; // should the player switch to this weapon? + virtual BOOL GetNextBestWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon) = 0; // I can't use this weapon anymore, get me the next best one. + + // Functions to verify the single/multiplayer status of a game + virtual BOOL IsMultiplayer() = 0; // is this a multiplayer game? (either coop or deathmatch) + virtual BOOL IsDeathmatch() = 0; // is this a deathmatch game? + virtual BOOL IsTeamplay() = 0; // is this deathmatch game being played with team rules? + virtual BOOL IsCoOp() = 0; // is this a coop game? + virtual const char *GetGameDescription() = 0; // this is the game name that gets seen in the server browser + + // Client connection/disconnection + virtual BOOL ClientConnected(edict_t *pEntity, const char *pszName, const char *pszAddress, char *szRejectReason) = 0; // a client just connected to the server (player hasn't spawned yet) + virtual void InitHUD(CBasePlayer *pl) = 0; // the client dll is ready for updating + virtual void ClientDisconnected(edict_t *pClient) = 0; // a client just disconnected from the server + virtual void UpdateGameMode(CBasePlayer *pPlayer) = 0; // the client needs to be informed of the current game mode + + // Client damage rules + virtual float FlPlayerFallDamage(CBasePlayer *pPlayer) = 0; + virtual BOOL FPlayerCanTakeDamage(CBasePlayer *pPlayer, CBaseEntity *pAttacker) = 0; // can this player take damage from this attacker? + virtual BOOL ShouldAutoAim(CBasePlayer *pPlayer, edict_t *target) = 0; + + // Client spawn/respawn control + virtual void PlayerSpawn(CBasePlayer *pPlayer) = 0; // called by CBasePlayer::Spawn just before releasing player into the game + virtual void PlayerThink(CBasePlayer *pPlayer) = 0; // called by CBasePlayer::PreThink every frame, before physics are run and after keys are accepted + virtual BOOL FPlayerCanRespawn(CBasePlayer *pPlayer) = 0; // is this player allowed to respawn now? + virtual float FlPlayerSpawnTime(CBasePlayer *pPlayer) = 0; // When in the future will this player be able to spawn? + virtual edict_t *GetPlayerSpawnSpot(CBasePlayer *pPlayer) = 0; // Place this player on their spawnspot and face them the proper direction. + + virtual BOOL AllowAutoTargetCrosshair() = 0; + virtual BOOL ClientCommand_DeadOrAlive(CBasePlayer *pPlayer, const char *pcmd) = 0; + virtual BOOL ClientCommand(CBasePlayer *pPlayer, const char *pcmd) = 0; // handles the user commands; returns TRUE if command handled properly + virtual void ClientUserInfoChanged(CBasePlayer *pPlayer, char *infobuffer) = 0; // the player has changed userinfo; can change it now + + // Client kills/scoring + virtual int IPointsForKill(CBasePlayer *pAttacker, CBasePlayer *pKilled) = 0; // how many points do I award whoever kills this player? + virtual void PlayerKilled(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; // Called each time a player dies + virtual void DeathNotice(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pevInflictor) = 0; // Call this from within a GameRules class to report an obituary. + + // Weapon retrieval + virtual BOOL CanHavePlayerItem(CBasePlayer *pPlayer, CBasePlayerItem *pItem) = 0; // The player is touching an CBasePlayerItem, do I give it to him? + virtual void PlayerGotWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; // Called each time a player picks up a weapon from the ground + + // Weapon spawn/respawn control + virtual int WeaponShouldRespawn(CBasePlayerItem *pWeapon) = 0; // should this weapon respawn? + virtual float FlWeaponRespawnTime(CBasePlayerItem *pWeapon) = 0; // when may this weapon respawn? + virtual float FlWeaponTryRespawn(CBasePlayerItem *pWeapon) = 0; // can i respawn now, and if not, when should i try again? + virtual Vector VecWeaponRespawnSpot(CBasePlayerItem *pWeapon) = 0; // where in the world should this weapon respawn? + + // Item retrieval + virtual BOOL CanHaveItem(CBasePlayer *pPlayer, CItem *pItem) = 0; // is this player allowed to take this item? + virtual void PlayerGotItem(CBasePlayer *pPlayer, CItem *pItem) = 0; // call each time a player picks up an item (battery, healthkit, longjump) + + // Item spawn/respawn control + virtual int ItemShouldRespawn(CItem *pItem) = 0; // Should this item respawn? + virtual float FlItemRespawnTime(CItem *pItem) = 0; // when may this item respawn? + virtual Vector VecItemRespawnSpot(CItem *pItem) = 0; // where in the world should this item respawn? + + // Ammo retrieval + virtual BOOL CanHaveAmmo(CBasePlayer *pPlayer, const char *pszAmmoName, int iMaxCarry) = 0; // can this player take more of this ammo? + virtual void PlayerGotAmmo(CBasePlayer *pPlayer, char *szName, int iCount) = 0; // called each time a player picks up some ammo in the world + + // Ammo spawn/respawn control + virtual int AmmoShouldRespawn(CBasePlayerAmmo *pAmmo) = 0; // should this ammo item respawn? + virtual float FlAmmoRespawnTime(CBasePlayerAmmo *pAmmo) = 0; // when should this ammo item respawn? + virtual Vector VecAmmoRespawnSpot(CBasePlayerAmmo *pAmmo) = 0; // where in the world should this ammo item respawn? + + // Healthcharger respawn control + virtual float FlHealthChargerRechargeTime() = 0; // how long until a depleted HealthCharger recharges itself? + virtual float FlHEVChargerRechargeTime() = 0; // how long until a depleted HealthCharger recharges itself? + + // What happens to a dead player's weapons + virtual int DeadPlayerWeapons(CBasePlayer *pPlayer) = 0; // what do I do with a player's weapons when he's killed? + + // What happens to a dead player's ammo + virtual int DeadPlayerAmmo(CBasePlayer *pPlayer) = 0; // Do I drop ammo when the player dies? How much? + + // Teamplay stuff + virtual const char *GetTeamID(CBaseEntity *pEntity) = 0; // what team is this entity on? + virtual int PlayerRelationship(CBasePlayer *pPlayer, CBaseEntity *pTarget) = 0; // What is the player's relationship with this entity? + virtual int GetTeamIndex(const char *pTeamName) = 0; + virtual const char *GetIndexedTeamName(int teamIndex) = 0; + virtual BOOL IsValidTeam(const char *pTeamName) = 0; + virtual void ChangePlayerTeam(CBasePlayer *pPlayer, const char *pTeamName, BOOL bKill, BOOL bGib) = 0; + virtual const char *SetDefaultPlayerTeam(CBasePlayer *pPlayer) = 0; + + // Sounds + virtual BOOL PlayTextureSounds() = 0; + + // Monsters + virtual BOOL FAllowMonsters() = 0; // are monsters allowed + + // Immediately end a multiplayer game + virtual void EndMultiplayerGame() = 0; + + // Stuff that is shared between client and server. + virtual BOOL IsFreezePeriod() = 0; + virtual void ServerDeactivate() = 0; + virtual void CheckMapConditions() = 0; + + // inline function's + inline bool IsGameOver() const { return m_bGameOver; } + inline void SetGameOver() { m_bGameOver = true; } + +public: + BOOL m_bFreezePeriod; // TRUE at beginning of round, set to FALSE when the period expires + BOOL m_bBombDropped; + + // custom + char *m_GameDesc; + bool m_bGameOver; // intermission or finale (deprecated name g_fGameOver) +}; + +// CHalfLifeRules - rules for the single player Half-Life game. +class CHalfLifeRules: public CGameRules { +protected: + virtual ~CHalfLifeRules() {}; +public: + virtual void Think() = 0; + virtual BOOL IsAllowedToSpawn(CBaseEntity *pEntity) = 0; + virtual BOOL FAllowFlashlight() = 0; + + virtual BOOL FShouldSwitchWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; + virtual BOOL GetNextBestWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon) = 0; + + // Functions to verify the single/multiplayer status of a game + virtual BOOL IsMultiplayer() = 0; + virtual BOOL IsDeathmatch() = 0; + virtual BOOL IsCoOp() = 0; + + // Client connection/disconnection + virtual BOOL ClientConnected(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[128]) = 0; + virtual void InitHUD(CBasePlayer *pl) = 0; // the client dll is ready for updating + virtual void ClientDisconnected(edict_t *pClient) = 0; + + // Client damage rules + virtual float FlPlayerFallDamage(CBasePlayer *pPlayer) = 0; + + // Client spawn/respawn control + virtual void PlayerSpawn(CBasePlayer *pPlayer) = 0; + virtual void PlayerThink(CBasePlayer *pPlayer) = 0; + virtual BOOL FPlayerCanRespawn(CBasePlayer *pPlayer) = 0; + virtual float FlPlayerSpawnTime(CBasePlayer *pPlayer) = 0; + virtual edict_t *GetPlayerSpawnSpot(CBasePlayer *pPlayer) = 0; + + virtual BOOL AllowAutoTargetCrosshair() = 0; + + // Client kills/scoring + virtual int IPointsForKill(CBasePlayer *pAttacker, CBasePlayer *pKilled) = 0; + virtual void PlayerKilled(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; + virtual void DeathNotice(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; + + // Weapon retrieval + virtual void PlayerGotWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; + + // Weapon spawn/respawn control + virtual int WeaponShouldRespawn(CBasePlayerItem *pWeapon) = 0; + virtual float FlWeaponRespawnTime(CBasePlayerItem *pWeapon) = 0; + virtual float FlWeaponTryRespawn(CBasePlayerItem *pWeapon) = 0; + virtual Vector VecWeaponRespawnSpot(CBasePlayerItem *pWeapon) = 0; + + // Item retrieval + virtual BOOL CanHaveItem(CBasePlayer *pPlayer, CItem *pItem) = 0; + virtual void PlayerGotItem(CBasePlayer *pPlayer, CItem *pItem) = 0; + + // Item spawn/respawn control + virtual int ItemShouldRespawn(CItem *pItem) = 0; + virtual float FlItemRespawnTime(CItem *pItem) = 0; + virtual Vector VecItemRespawnSpot(CItem *pItem) = 0; + + // Ammo retrieval + virtual void PlayerGotAmmo(CBasePlayer *pPlayer, char *szName, int iCount) = 0; + + // Ammo spawn/respawn control + virtual int AmmoShouldRespawn(CBasePlayerAmmo *pAmmo) = 0; + virtual float FlAmmoRespawnTime(CBasePlayerAmmo *pAmmo) = 0; + virtual Vector VecAmmoRespawnSpot(CBasePlayerAmmo *pAmmo) = 0; + + // Healthcharger respawn control + virtual float FlHealthChargerRechargeTime() = 0; + + // What happens to a dead player's weapons + virtual int DeadPlayerWeapons(CBasePlayer *pPlayer) = 0; + + // What happens to a dead player's ammo + virtual int DeadPlayerAmmo(CBasePlayer *pPlayer) = 0; + + // Teamplay stuff + virtual const char *GetTeamID(CBaseEntity *pEntity) = 0; + virtual int PlayerRelationship(CBasePlayer *pPlayer, CBaseEntity *pTarget) = 0; + + // Monsters + virtual BOOL FAllowMonsters() = 0; +}; + +// CHalfLifeMultiplay - rules for the basic half life multiplayer competition +class CHalfLifeMultiplay: public CGameRules { +protected: + virtual ~CHalfLifeMultiplay() {}; +public: + virtual void RefreshSkillData() = 0; + virtual void Think() = 0; + virtual BOOL IsAllowedToSpawn(CBaseEntity *pEntity) = 0; + virtual BOOL FAllowFlashlight() = 0; + + virtual BOOL FShouldSwitchWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; + virtual BOOL GetNextBestWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon) = 0; + + virtual BOOL IsMultiplayer() = 0; + virtual BOOL IsDeathmatch() = 0; + virtual BOOL IsCoOp() = 0; + + // Client connection/disconnection + // If ClientConnected returns FALSE, the connection is rejected and the user is provided the reason specified in szRejectReason + // Only the client's name and remote address are provided to the dll for verification. + virtual BOOL ClientConnected(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[128]) = 0; + virtual void InitHUD(CBasePlayer *pl) = 0; + virtual void ClientDisconnected(edict_t *pClient) = 0; + virtual void UpdateGameMode(CBasePlayer *pPlayer) = 0; + + // Client damage rules + virtual float FlPlayerFallDamage(CBasePlayer *pPlayer) = 0; + virtual BOOL FPlayerCanTakeDamage(CBasePlayer *pPlayer, CBaseEntity *pAttacker) = 0; + + // Client spawn/respawn control + virtual void PlayerSpawn(CBasePlayer *pPlayer) = 0; + virtual void PlayerThink(CBasePlayer *pPlayer) = 0; + virtual BOOL FPlayerCanRespawn(CBasePlayer *pPlayer) = 0; + virtual float FlPlayerSpawnTime(CBasePlayer *pPlayer) = 0; + virtual edict_t *GetPlayerSpawnSpot(CBasePlayer *pPlayer) = 0; + + virtual BOOL AllowAutoTargetCrosshair() = 0; + + virtual BOOL ClientCommand_DeadOrAlive(CBasePlayer *pPlayer, const char *pcmd) = 0; + virtual BOOL ClientCommand(CBasePlayer *pPlayer, const char *pcmd) = 0; + virtual void ClientUserInfoChanged(CBasePlayer *pPlayer, char *infobuffer) = 0; + + // Client kills/scoring + virtual int IPointsForKill(CBasePlayer *pAttacker, CBasePlayer *pKilled) = 0; + virtual void PlayerKilled(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; + virtual void DeathNotice(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; + + // Weapon retrieval + virtual BOOL CanHavePlayerItem(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; + virtual void PlayerGotWeapon(CBasePlayer *pPlayer, CBasePlayerItem *pWeapon) = 0; + + // Weapon spawn/respawn control + virtual int WeaponShouldRespawn(CBasePlayerItem *pWeapon) = 0; + virtual float FlWeaponRespawnTime(CBasePlayerItem *pWeapon) = 0; + virtual float FlWeaponTryRespawn(CBasePlayerItem *pWeapon) = 0; + virtual Vector VecWeaponRespawnSpot(CBasePlayerItem *pWeapon) = 0; + + // Item retrieval + virtual BOOL CanHaveItem(CBasePlayer *pPlayer, CItem *pItem) = 0; + virtual void PlayerGotItem(CBasePlayer *pPlayer, CItem *pItem) = 0; + + // Item spawn/respawn control + virtual int ItemShouldRespawn(CItem *pItem) = 0; + virtual float FlItemRespawnTime(CItem *pItem) = 0; + virtual Vector VecItemRespawnSpot(CItem *pItem) = 0; + + // Ammo retrieval + virtual void PlayerGotAmmo(CBasePlayer *pPlayer, char *szName, int iCount) = 0; + + // Ammo spawn/respawn control + virtual int AmmoShouldRespawn(CBasePlayerAmmo *pAmmo) = 0; + virtual float FlAmmoRespawnTime(CBasePlayerAmmo *pAmmo) = 0; + virtual Vector VecAmmoRespawnSpot(CBasePlayerAmmo *pAmmo) = 0; + + // Healthcharger respawn control + virtual float FlHealthChargerRechargeTime() = 0; + virtual float FlHEVChargerRechargeTime() = 0; + + // What happens to a dead player's weapons + virtual int DeadPlayerWeapons(CBasePlayer *pPlayer) = 0; + + // What happens to a dead player's ammo + virtual int DeadPlayerAmmo(CBasePlayer *pPlayer) = 0; + + // Teamplay stuff + virtual const char *GetTeamID(CBaseEntity *pEntity) = 0; + virtual int PlayerRelationship(CBasePlayer *pPlayer, CBaseEntity *pTarget) = 0; + virtual void ChangePlayerTeam(CBasePlayer *pPlayer, const char *pTeamName, BOOL bKill, BOOL bGib) = 0; + + virtual BOOL PlayTextureSounds() = 0; + + // Monsters + virtual BOOL FAllowMonsters() = 0; + + // Immediately end a multiplayer game + virtual void EndMultiplayerGame() = 0; + virtual void ServerDeactivate() = 0; + virtual void CheckMapConditions() = 0; + + // Recreate all the map entities from the map data (preserving their indices), + // then remove everything else except the players. + // Also get rid of all world decals. + virtual void CleanUpMap() = 0; + + virtual void RestartRound() = 0; + + // check if the scenario has been won/lost + virtual void CheckWinConditions() = 0; + virtual void RemoveGuns() = 0; + virtual void GiveC4() = 0; + virtual void ChangeLevel() = 0; + virtual void GoToIntermission() = 0; + + // Setup counts for m_iNumTerrorist, m_iNumCT, m_iNumSpawnableTerrorist, m_iNumSpawnableCT, etc. + virtual void InitializePlayerCounts(int &NumAliveTerrorist, int &NumAliveCT, int &NumDeadTerrorist, int &NumDeadCT) = 0; + + virtual void BalanceTeams() = 0; + virtual void SwapAllPlayers() = 0; + virtual void UpdateTeamScores() = 0; + virtual void EndRoundMessage(const char *sentence, int event) = 0; + virtual void SetAccountRules(RewardRules rules, int amount) = 0; + virtual RewardAccount GetAccountRules(RewardRules rules) const = 0; + + // BOMB MAP FUNCTIONS + virtual BOOL IsThereABomber() = 0; + virtual BOOL IsThereABomb() = 0; + virtual TeamName SelectDefaultTeam() = 0; + + virtual bool HasRoundTimeExpired() = 0; + virtual bool IsBombPlanted() = 0; + +public: + bool ShouldSkipShowMenu() const { return m_bSkipShowMenu; } + void MarkShowMenuSkipped() { m_bSkipShowMenu = false; } + + bool ShouldSkipSpawn() const { return m_bSkipSpawn; } + void MarkSpawnSkipped() { m_bSkipSpawn = false; } + + float GetRoundRemainingTime() const { return m_iRoundTimeSecs - gpGlobals->time + m_fRoundStartTime; } + float GetRoundRemainingTimeReal() const { return m_iRoundTimeSecs - gpGlobals->time + m_fRoundStartTimeReal; } + float GetTimeLeft() const { return m_flTimeLimit - gpGlobals->time; } + bool IsMatchStarted() { return (m_flRestartRoundTime != 0.0f || m_fCareerRoundMenuTime != 0.0f || m_fCareerMatchMenuTime != 0.0f); } + + void TerminateRound(float tmDelay, int iWinStatus); + +public: + CVoiceGameMgr m_VoiceGameMgr; + float m_flRestartRoundTime; // The global time when the round is supposed to end, if this is not 0 (deprecated name m_fTeamCount) + float m_flCheckWinConditions; + float m_fRoundStartTime; // Time round has started (deprecated name m_fRoundCount) + int m_iRoundTime; // (From mp_roundtime) - How many seconds long this round is. + int m_iRoundTimeSecs; + int m_iIntroRoundTime; // (From mp_freezetime) - How many seconds long the intro round (when players are frozen) is. + float m_fRoundStartTimeReal; // The global time when the intro round ends and the real one starts + // wrote the original "m_flRoundTime" comment for this variable). + int m_iAccountTerrorist; + int m_iAccountCT; + int m_iNumTerrorist; // The number of terrorists on the team (this is generated at the end of a round) + int m_iNumCT; // The number of CTs on the team (this is generated at the end of a round) + int m_iNumSpawnableTerrorist; + int m_iNumSpawnableCT; + int m_iSpawnPointCount_Terrorist; // Number of Terrorist spawn points + int m_iSpawnPointCount_CT; // Number of CT spawn points + int m_iHostagesRescued; + int m_iHostagesTouched; + int m_iRoundWinStatus; // 1 == CT's won last round, 2 == Terrorists did, 3 == Draw, no winner + + short m_iNumCTWins; + short m_iNumTerroristWins; + + bool m_bTargetBombed; // whether or not the bomb has been bombed + bool m_bBombDefused; // whether or not the bomb has been defused + + bool m_bMapHasBombTarget; + bool m_bMapHasBombZone; + bool m_bMapHasBuyZone; + bool m_bMapHasRescueZone; + bool m_bMapHasEscapeZone; + + BOOL m_bMapHasVIPSafetyZone; // TRUE = has VIP safety zone, FALSE = does not have VIP safetyzone + BOOL m_bMapHasCameras; + int m_iC4Timer; + int m_iC4Guy; // The current Terrorist who has the C4. + int m_iLoserBonus; // the amount of money the losing team gets. This scales up as they lose more rounds in a row + int m_iNumConsecutiveCTLoses; // the number of rounds the CTs have lost in a row. + int m_iNumConsecutiveTerroristLoses; // the number of rounds the Terrorists have lost in a row. + + float m_fMaxIdlePeriod; // For the idle kick functionality. This is tha max amount of time that the player has to be idle before being kicked + + int m_iLimitTeams; + bool m_bLevelInitialized; + bool m_bRoundTerminating; + bool m_bCompleteReset; // Set to TRUE to have the scores reset next time round restarts + float m_flRequiredEscapeRatio; + int m_iNumEscapers; + int m_iHaveEscaped; + bool m_bCTCantBuy; + bool m_bTCantBuy; // Who can and can't buy. + float m_flBombRadius; + int m_iConsecutiveVIP; + int m_iTotalGunCount; + int m_iTotalGrenadeCount; + int m_iTotalArmourCount; + int m_iUnBalancedRounds; // keeps track of the # of consecutive rounds that have gone by where one team outnumbers the other team by more than 2 + int m_iNumEscapeRounds; // keeps track of the # of consecutive rounds of escape played.. Teams will be swapped after 8 rounds + int m_iMapVotes[MAX_VOTE_MAPS]; + int m_iLastPick; + int m_iMaxMapTime; + int m_iMaxRounds; + int m_iTotalRoundsPlayed; + int m_iMaxRoundsWon; + int m_iStoredSpectValue; + float m_flForceCameraValue; + float m_flForceChaseCamValue; + float m_flFadeToBlackValue; + CBasePlayer *m_pVIP; + CBasePlayer *m_pVIPQueue[MAX_VIP_QUEUES]; + float m_flIntermissionEndTime; + float m_flIntermissionStartTime; + BOOL m_iEndIntermissionButtonHit; + float m_tmNextPeriodicThink; + bool m_bGameStarted; // TRUE = the game commencing when there is at least one CT and T, FALSE = scoring will not start until both teams have players (deprecated name m_bFirstConnected) + bool m_bInCareerGame; + float m_fCareerRoundMenuTime; + int m_iCareerMatchWins; + int m_iRoundWinDifference; + float m_fCareerMatchMenuTime; + bool m_bSkipSpawn; + + // custom + bool m_bSkipShowMenu; + bool m_bNeededPlayers; + float m_flEscapeRatio; + float m_flTimeLimit; + float m_flGameStartTime; +}; + +typedef struct mapcycle_item_s +{ + struct mapcycle_item_s *next; + char mapname[32]; + int minplayers; + int maxplayers; + char rulebuffer[MAX_RULE_BUFFER]; + +} mapcycle_item_t; + +typedef struct mapcycle_s +{ + struct mapcycle_item_s *items; + struct mapcycle_item_s *next_item; + +} mapcycle_t; + +class CCStrikeGameMgrHelper: public IVoiceGameMgrHelper { +public: + virtual bool CanPlayerHearPlayer(CBasePlayer *pListener, CBasePlayer *pSender) = 0; +}; + +extern CGameRules *g_pGameRules; + +// Gets us at the CS game rules +inline CHalfLifeMultiplay *CSGameRules() +{ + return static_cast(g_pGameRules); +} + +inline void CHalfLifeMultiplay::TerminateRound(float tmDelay, int iWinStatus) +{ + m_iRoundWinStatus = iWinStatus; + m_flRestartRoundTime = gpGlobals->time + tmDelay; + m_bRoundTerminating = true; +} diff --git a/dep/hlsdk/dlls/gib.h b/dep/hlsdk/dlls/gib.h new file mode 100644 index 0000000..dc5be9a --- /dev/null +++ b/dep/hlsdk/dlls/gib.h @@ -0,0 +1,39 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CGib: public CBaseEntity { +public: + virtual int ObjectCaps() = 0; +public: + int m_bloodColor; + int m_cBloodDecals; + int m_material; + float m_lifeTime; +}; diff --git a/dep/hlsdk/dlls/h_battery.h b/dep/hlsdk/dlls/h_battery.h new file mode 100644 index 0000000..987ffcb --- /dev/null +++ b/dep/hlsdk/dlls/h_battery.h @@ -0,0 +1,46 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CRecharge: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float m_flNextCharge; + int m_iReactivate; + int m_iJuice; + int m_iOn; + float m_flSoundTime; +}; diff --git a/dep/hlsdk/dlls/h_cycler.h b/dep/hlsdk/dlls/h_cycler.h new file mode 100644 index 0000000..dc917f0 --- /dev/null +++ b/dep/hlsdk/dlls/h_cycler.h @@ -0,0 +1,105 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CCycler: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + + // Don't treat as a live target + virtual BOOL IsAlive() = 0; + virtual void Think() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int m_animate; +}; + +// We should get rid of all the other cyclers and replace them with this. +class CGenericCycler: public CCycler { +public: + virtual void Spawn() = 0; +}; + +// Probe droid imported for tech demo compatibility +class CCyclerProbe: public CCycler { +public: + virtual void Spawn() = 0; +}; + +class CCyclerSprite: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual void Think() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + inline int ShouldAnimate() { return (m_animate && m_maxFrame > 1.0f); } +public: + int m_animate; + float m_lastTime; + float m_maxFrame; + int m_renderfx; + int m_rendermode; + float m_renderamt; + vec3_t m_rendercolor; +}; + +class CWeaponCycler: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal = 0) = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; +public: + int m_iszModel; + int m_iModel; +}; + +// Flaming Wreakage +class CWreckage: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Think() = 0; +public: + int m_flStartTime; +}; diff --git a/dep/hlsdk/dlls/healthkit.h b/dep/hlsdk/dlls/healthkit.h new file mode 100644 index 0000000..643ec6f --- /dev/null +++ b/dep/hlsdk/dlls/healthkit.h @@ -0,0 +1,53 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CHealthKit: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CWallHealth: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float m_flNextCharge; + int m_iReactivate; + int m_iJuice; + int m_iOn; + float m_flSoundTime; +}; diff --git a/dep/hlsdk/dlls/hintmessage.h b/dep/hlsdk/dlls/hintmessage.h new file mode 100644 index 0000000..c166517 --- /dev/null +++ b/dep/hlsdk/dlls/hintmessage.h @@ -0,0 +1,82 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "utlvector.h" + +#define DHF_ROUND_STARTED BIT(1) +#define DHF_HOSTAGE_SEEN_FAR BIT(2) +#define DHF_HOSTAGE_SEEN_NEAR BIT(3) +#define DHF_HOSTAGE_USED BIT(4) +#define DHF_HOSTAGE_INJURED BIT(5) +#define DHF_HOSTAGE_KILLED BIT(6) +#define DHF_FRIEND_SEEN BIT(7) +#define DHF_ENEMY_SEEN BIT(8) +#define DHF_FRIEND_INJURED BIT(9) +#define DHF_FRIEND_KILLED BIT(10) +#define DHF_ENEMY_KILLED BIT(11) +#define DHF_BOMB_RETRIEVED BIT(12) +#define DHF_AMMO_EXHAUSTED BIT(15) +#define DHF_IN_TARGET_ZONE BIT(16) +#define DHF_IN_RESCUE_ZONE BIT(17) +#define DHF_IN_ESCAPE_ZONE BIT(18) +#define DHF_IN_VIPSAFETY_ZONE BIT(19) +#define DHF_NIGHTVISION BIT(20) +#define DHF_HOSTAGE_CTMOVE BIT(21) +#define DHF_SPEC_DUCK BIT(22) + +#define DHM_ROUND_CLEAR (DHF_ROUND_STARTED | DHF_HOSTAGE_KILLED | DHF_FRIEND_KILLED | DHF_BOMB_RETRIEVED) +#define DHM_CONNECT_CLEAR (DHF_HOSTAGE_SEEN_FAR | DHF_HOSTAGE_SEEN_NEAR | DHF_HOSTAGE_USED | DHF_HOSTAGE_INJURED | DHF_FRIEND_SEEN | DHF_ENEMY_SEEN | DHF_FRIEND_INJURED | DHF_ENEMY_KILLED | DHF_AMMO_EXHAUSTED | DHF_IN_TARGET_ZONE | DHF_IN_RESCUE_ZONE | DHF_IN_ESCAPE_ZONE | DHF_IN_VIPSAFETY_ZONE | DHF_HOSTAGE_CTMOVE | DHF_SPEC_DUCK) + +class CHintMessage { +public: + CHintMessage(const char *hintString, bool isHint, CUtlVector *args, float duration); + ~CHintMessage(); +public: + float GetDuration() const { return m_duration; } + void Send(CBaseEntity *client); + +private: + const char *m_hintString; + bool m_isHint; + CUtlVector m_args; + float m_duration; +}; + +class CHintMessageQueue { +public: + void Reset(); + void Update(CBaseEntity *client); + bool AddMessage(const char *message, float duration, bool isHint, CUtlVector *args); + bool IsEmpty() const { return m_messages.Count() == 0; } + +private: + float m_tmMessageEnd; + CUtlVector m_messages; +}; diff --git a/dep/hlsdk/dlls/hookchains.h b/dep/hlsdk/dlls/hookchains.h new file mode 100644 index 0000000..7ea472a --- /dev/null +++ b/dep/hlsdk/dlls/hookchains.h @@ -0,0 +1,121 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +template +class IHookChain { +protected: + virtual ~IHookChain() {} + +public: + virtual t_ret callNext(t_args... args) = 0; + virtual t_ret callOriginal(t_args... args) = 0; +}; + +template +class IHookChainClass { +protected: + virtual ~IHookChainClass() {} + +public: + virtual t_ret callNext(t_class *, t_args... args) = 0; + virtual t_ret callOriginal(t_class *, t_args... args) = 0; +}; + +template +class IVoidHookChain +{ +protected: + virtual ~IVoidHookChain() {} + +public: + virtual void callNext(t_args... args) = 0; + virtual void callOriginal(t_args... args) = 0; +}; + +template +class IVoidHookChainClass +{ +protected: + virtual ~IVoidHookChainClass() {} + +public: + virtual void callNext(t_class *, t_args... args) = 0; + virtual void callOriginal(t_class *, t_args... args) = 0; +}; + +// Specifies priorities for hooks call order in the chain. +// For equal priorities first registered hook will be called first. +enum HookChainPriority +{ + HC_PRIORITY_UNINTERRUPTABLE = 255, // Hook will be called before other hooks. + HC_PRIORITY_HIGH = 192, // Hook will be called before hooks with default priority. + HC_PRIORITY_DEFAULT = 128, // Default hook call priority. + HC_PRIORITY_MEDIUM = 64, // Hook will be called after hooks with default priority. + HC_PRIORITY_LOW = 0, // Hook will be called after all other hooks. +}; + +// Hook chain registry(for hooks [un]registration) +template +class IHookChainRegistry { +public: + typedef t_ret(*hookfunc_t)(IHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; + +// Hook chain registry(for hooks [un]registration) +template +class IHookChainRegistryClass { +public: + typedef t_ret(*hookfunc_t)(IHookChainClass*, t_class *, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; + +// Hook chain registry(for hooks [un]registration) +template +class IVoidHookChainRegistry { +public: + typedef void(*hookfunc_t)(IVoidHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; + +// Hook chain registry(for hooks [un]registration) +template +class IVoidHookChainRegistryClass { +public: + typedef void(*hookfunc_t)(IVoidHookChainClass*, t_class *, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; diff --git a/dep/hlsdk/dlls/hostage/hostage.h b/dep/hlsdk/dlls/hostage/hostage.h new file mode 100644 index 0000000..a0be24c --- /dev/null +++ b/dep/hlsdk/dlls/hostage/hostage.h @@ -0,0 +1,233 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define MAX_NODES 100 +#define MAX_HOSTAGES 12 +#define MAX_HOSTAGES_NAV 20 + +#define HOSTAGE_STEPSIZE 26.0f +#define HOSTAGE_STEPSIZE_DEFAULT 18.0f + +#define VEC_HOSTAGE_VIEW Vector(0, 0, 12) +#define VEC_HOSTAGE_HULL_MIN Vector(-10, -10, 0) +#define VEC_HOSTAGE_HULL_MAX Vector(10, 10, 62) + +#define VEC_HOSTAGE_CROUCH Vector(10, 10, 30) +#define RESCUE_HOSTAGES_RADIUS 256.0f // rescue zones from legacy info_* + +class CHostage; +class CLocalNav; +class CHostageImprov; +class CHostageManager; + +enum HostageChatterType +{ + HOSTAGE_CHATTER_START_FOLLOW = 0, + HOSTAGE_CHATTER_STOP_FOLLOW, + HOSTAGE_CHATTER_INTIMIDATED, + HOSTAGE_CHATTER_PAIN, + HOSTAGE_CHATTER_SCARED_OF_GUNFIRE, + HOSTAGE_CHATTER_SCARED_OF_MURDER, + HOSTAGE_CHATTER_LOOK_OUT, + HOSTAGE_CHATTER_PLEASE_RESCUE_ME, + HOSTAGE_CHATTER_SEE_RESCUE_ZONE, + HOSTAGE_CHATTER_IMPATIENT_FOR_RESCUE, + HOSTAGE_CHATTER_CTS_WIN , + HOSTAGE_CHATTER_TERRORISTS_WIN, + HOSTAGE_CHATTER_RESCUED, + HOSTAGE_CHATTER_WARN_NEARBY, + HOSTAGE_CHATTER_WARN_SPOTTED, + HOSTAGE_CHATTER_CALL_TO_RESCUER, + HOSTAGE_CHATTER_RETREAT, + HOSTAGE_CHATTER_COUGH, + HOSTAGE_CHATTER_BLINDED, + HOSTAGE_CHATTER_SAW_HE_GRENADE, + HOSTAGE_CHATTER_DEATH_CRY, + NUM_HOSTAGE_CHATTER_TYPES, +}; + +// Improved the hostages from CZero +#include "hostage/hostage_improv.h" + +extern CHostageManager *g_pHostages; +extern int g_iHostageNumber; + +// A Counter-Strike Hostage Simple +class CHostage: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int ObjectCaps() = 0; // make hostage "useable" + virtual int Classify() = 0; + virtual void TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual int BloodColor() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int GetActivity() { return m_Activity; } + + // queries + bool IsFollowingSomeone() { return IsFollowing(); } + CBaseEntity *GetLeader() // return our leader, or NULL + { + if (m_improv != NULL) + { + return m_improv->GetFollowLeader(); + } + + return m_hTargetEnt; + } + bool IsFollowing(const CBaseEntity *entity = NULL) + { + if (m_improv != NULL) + { + return m_improv->IsFollowing(); + } + + if (entity == NULL && m_hTargetEnt == NULL || (entity != NULL && m_hTargetEnt != entity)) + return false; + + if (m_State != FOLLOW) + return false; + + return true; + } + bool IsValid() const { return (pev->takedamage == DAMAGE_YES); } + bool IsDead() const { return (pev->deadflag == DEAD_DEAD); } + bool IsAtHome() const { return (pev->origin - m_vStart).IsLengthGreaterThan(20) != true; } + const Vector *GetHomePosition() const { return &m_vStart; } +public: + int m_Activity; + BOOL m_bTouched; + BOOL m_bRescueMe; + float m_flFlinchTime; + float m_flNextChange; + float m_flMarkPosition; + int m_iModel; + int m_iSkin; + float m_flNextRadarTime; + enum state { FOLLOW, STAND, DUCK, SCARED, IDLE, FOLLOWPATH } + m_State; + Vector m_vStart; + Vector m_vStartAngles; + Vector m_vPathToFollow[20]; + int m_iWaypoint; + CBasePlayer *m_target; + CLocalNav *m_LocalNav; + int nTargetNode; + Vector vecNodes[MAX_NODES]; + EHANDLE m_hStoppedTargetEnt; + float m_flNextFullThink; + float m_flPathCheckInterval; + float m_flLastPathCheck; + int m_nPathNodes; + BOOL m_fHasPath; + float m_flPathAcquired; + Vector m_vOldPos; + int m_iHostageIndex; + BOOL m_bStuck; + float m_flStuckTime; + CHostageImprov *m_improv; + + enum ModelType { REGULAR_GUY, OLD_GUY, BLACK_GUY, GOOFY_GUY } + m_whichModel; +}; + +class SimpleChatter { +public: + struct SoundFile + { + char *filename; + float duration; + }; + + struct ChatterSet + { + SoundFile file[32]; + int count; + int index; + bool needsShuffle; + }; +private: + ChatterSet m_chatter[21]; +}; + +class CHostageManager { +public: + SimpleChatter *GetChatter() + { + return &m_chatter; + } + // Iterate over all active hostages in the game, invoking functor on each. + // If functor returns false, stop iteration and return false. + template + inline bool ForEachHostage(Functor &func) const + { + for (int i = 0; i < m_hostageCount; i++) + { + CHostage *hostage = m_hostage[i]; + + if (hostage == NULL || hostage->pev->deadflag == DEAD_DEAD) + continue; + + if (func(hostage) == false) + return false; + } + + return true; + } + inline CHostage *GetClosestHostage(const Vector &pos, float *resultRange = NULL) + { + float range; + float closeRange = 1e8f; + CHostage *close = NULL; + + for (int i = 0; i < m_hostageCount; i++) + { + range = (m_hostage[i]->pev->origin - pos).Length(); + + if (range < closeRange) + { + closeRange = range; + close = m_hostage[i]; + } + } + + if (resultRange) + *resultRange = closeRange; + + return close; + } + +private: + CHostage *m_hostage[MAX_HOSTAGES]; + int m_hostageCount; + SimpleChatter m_chatter; +}; diff --git a/dep/hlsdk/dlls/hostage/hostage_improv.h b/dep/hlsdk/dlls/hostage/hostage_improv.h new file mode 100644 index 0000000..9c1784d --- /dev/null +++ b/dep/hlsdk/dlls/hostage/hostage_improv.h @@ -0,0 +1,334 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "hostage/hostage.h" +#include "hostage/hostage_states.h" + +class CHostage; +enum HostageChatterType; + +// A Counter-Strike Hostage improved +class CHostageImprov: public CImprov { +public: + virtual ~CHostageImprov() {}; + + // invoked when an improv reaches its MoveTo goal + virtual void OnMoveToSuccess(const Vector &goal) = 0; + + // invoked when an improv fails to reach a MoveTo goal + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) = 0; + virtual void OnInjury(float amount) = 0; + virtual bool IsAlive() const = 0; + virtual void MoveTo(const Vector &goal) = 0; + virtual void LookAt(const Vector &target) = 0; + virtual void ClearLookAt() = 0; + virtual void FaceTo(const Vector &goal) = 0; + virtual void ClearFaceTo() = 0; + virtual bool IsAtMoveGoal(float error = 20.0f) const = 0; + virtual bool HasLookAt() const = 0; + virtual bool HasFaceTo() const = 0; + virtual bool IsAtFaceGoal() const = 0; + virtual bool IsFriendInTheWay(const Vector &goalPos) const = 0; + virtual bool IsFriendInTheWay(CBaseEntity *myFriend, const Vector &goalPos) const = 0; + virtual void MoveForward() = 0; + virtual void MoveBackward() = 0; + virtual void StrafeLeft() = 0; + virtual void StrafeRight() = 0; + + #define HOSTAGE_MUST_JUMP true + virtual bool Jump() = 0; + + virtual void Crouch() = 0; + virtual void StandUp() = 0; + virtual void TrackPath(const Vector &pathGoal, float deltaT) = 0; // move along path by following "pathGoal" + virtual void StartLadder(const CNavLadder *ladder, NavTraverseType how, const Vector *approachPos, const Vector *departPos) = 0; + virtual bool TraverseLadder(const CNavLadder *ladder, NavTraverseType how, const Vector *approachPos, const Vector *departPos, float deltaT) = 0; + virtual bool GetSimpleGroundHeightWithFloor(const Vector *pos, float *height, Vector *normal = NULL) = 0; + virtual void Run() = 0; + virtual void Walk() = 0; + virtual void Stop() = 0; + virtual float GetMoveAngle() const = 0; + virtual float GetFaceAngle() const = 0; + virtual const Vector &GetFeet() const = 0; + virtual const Vector &GetCentroid() const = 0; + virtual const Vector &GetEyes() const = 0; + virtual bool IsRunning() const = 0; + virtual bool IsWalking() const = 0; + virtual bool IsStopped() const = 0; + virtual bool IsCrouching() const = 0; + virtual bool IsJumping() const = 0; + virtual bool IsUsingLadder() const = 0; + virtual bool IsOnGround() const = 0; + virtual bool IsMoving() const = 0; + virtual bool CanRun() const = 0; + virtual bool CanCrouch() const = 0; + virtual bool CanJump() const = 0; + virtual bool IsVisible(const Vector &pos, bool testFOV = false) const = 0; // return true if hostage can see position + virtual bool IsPlayerLookingAtMe(CBasePlayer *other, float cosTolerance = 0.95f) const = 0; + virtual CBasePlayer *IsAnyPlayerLookingAtMe(int team = 0, float cosTolerance = 0.95f) const = 0; + virtual CBasePlayer *GetClosestPlayerByTravelDistance(int team = 0, float *range = NULL) const = 0; + virtual CNavArea *GetLastKnownArea() const = 0; + virtual void OnUpdate(float deltaT) = 0; + virtual void OnUpkeep(float deltaT) = 0; + virtual void OnReset() = 0; + virtual void OnGameEvent(GameEventType event, CBaseEntity *entity = NULL, CBaseEntity *other = NULL) = 0; + virtual void OnTouch(CBaseEntity *other) = 0; // in contact with "other" +public: + enum MoveType { Stopped, Walking, Running }; + enum ScareType { NERVOUS, SCARED, TERRIFIED }; + + const Vector &GetKnownGoodPosition() const { return m_knownGoodPos; } + void ApplyForce(Vector force) { m_vel.x += force.x; m_vel.y += force.y; } // apply a force to the hostage + const Vector GetActualVelocity() const { return m_actualVel; } + void SetMoveLimit(MoveType limit) { m_moveLimit = limit; } + MoveType GetMoveLimit() const { return m_moveLimit; } + CNavPath *GetPath() { return &m_path; } + + // hostage states + // stand idle + void Idle() { m_behavior.SetState(&m_idleState); } + bool IsIdle() const { return m_behavior.IsState(&m_idleState); } + + // begin following "leader" + void Follow(CBasePlayer *leader) { m_followState.SetLeader(leader); m_behavior.SetState(&m_followState); } + bool IsFollowing(const CBaseEntity *leader = NULL) const { return m_behavior.IsState(&m_followState); } + + // Escape + void Escape() { m_behavior.SetState(&m_escapeState); } + bool IsEscaping() const { return m_behavior.IsState(&m_escapeState); } + + // Retreat + void Retreat() { m_behavior.SetState(&m_retreatState); } + bool IsRetreating() const { return m_behavior.IsState(&m_retreatState); } + + CBaseEntity *GetFollowLeader() const { return m_followState.GetLeader(); } + ScareType GetScareIntensity() const { return m_scareIntensity; } + bool IsIgnoringTerrorists() const { return m_ignoreTerroristTimer.IsElapsed(); } + float GetAggression() const { return m_aggression; } + bool IsTalking() const { return m_talkingTimer.IsElapsed(); } + CHostage *GetEntity() const { return m_hostage; } + void SetMoveAngle(float angle) { m_moveAngle = angle; } +public: + CountdownTimer m_coughTimer; + CountdownTimer m_grenadeTimer; +private: + CHostage *m_hostage; + CNavArea *m_lastKnownArea; // last area we were in + mutable Vector m_centroid; + mutable Vector m_eye; + HostageStateMachine m_behavior; + HostageIdleState m_idleState; + HostageEscapeState m_escapeState; + HostageRetreatState m_retreatState; + HostageFollowState m_followState; + HostageAnimateState m_animateState; + bool m_didFidget; + float m_aggression; + IntervalTimer m_lastSawCT; + IntervalTimer m_lastSawT; + CountdownTimer m_checkNearbyTerroristTimer; + bool m_isTerroristNearby; + CountdownTimer m_nearbyTerroristTimer; + CountdownTimer m_scaredTimer; + ScareType m_scareIntensity; + CountdownTimer m_ignoreTerroristTimer; + CountdownTimer m_blinkTimer; + char m_blinkCounter; + IntervalTimer m_lastInjuryTimer; + IntervalTimer m_lastNoiseTimer; + mutable CountdownTimer m_avoidFriendTimer; + mutable bool m_isFriendInTheWay; + CountdownTimer m_chatterTimer; + bool m_isDelayedChatterPending; + CountdownTimer m_delayedChatterTimer; + HostageChatterType m_delayedChatterType; + bool m_delayedChatterMustSpeak; + CountdownTimer m_talkingTimer; + unsigned int m_moveFlags; + Vector2D m_vel; + Vector m_actualVel; + Vector m_moveGoal; + Vector m_knownGoodPos; + bool m_hasKnownGoodPos; + Vector m_priorKnownGoodPos; + bool m_hasPriorKnownGoodPos; + CountdownTimer m_priorKnownGoodPosTimer; + IntervalTimer m_collisionTimer; + Vector m_viewGoal; + bool m_isLookingAt; + Vector m_faceGoal; + bool m_isFacingTo; + CNavPath m_path; // current path to follow + CNavPathFollower m_follower; + Vector m_lastPosition; + MoveType m_moveType; + MoveType m_moveLimit; + bool m_isCrouching; // true if hostage is crouching + CountdownTimer m_minCrouchTimer; + float m_moveAngle; + NavRelativeDirType m_wiggleDirection; + + CountdownTimer m_wiggleTimer; // for wiggling + CountdownTimer m_wiggleJumpTimer; + CountdownTimer m_inhibitObstacleAvoidance; + CountdownTimer m_jumpTimer; // if zero, we can jump + + bool m_hasJumped; + bool m_hasJumpedIntoAir; + Vector m_jumpTarget; + CountdownTimer m_clearPathTimer; + bool m_traversingLadder; + EntityHandle m_visiblePlayer[MAX_CLIENTS]; + int m_visiblePlayerCount; + CountdownTimer m_visionTimer; +}; + +class CheckWayFunctor { +public: + CheckWayFunctor(const CHostageImprov *me, const Vector &goalPos) + { + m_me = me; + m_goalPos = goalPos; + m_blocker = NULL; + } + bool operator()(CHostage *them) + { + if (((CBaseMonster *)them)->IsAlive() && m_me->IsFriendInTheWay((CBaseEntity *)them, m_goalPos)) + { + m_blocker = them; + return false; + } + + return true; + } + + const CHostageImprov *m_me; + Vector m_goalPos; + CHostage *m_blocker; +}; + +// Functor used with NavAreaBuildPath() for building Hostage paths. +// Once we hook up crouching and ladders, this can be removed and ShortestPathCost() can be used instead. +class HostagePathCost { +public: + float operator()(CNavArea *area, CNavArea *fromArea, const CNavLadder *ladder) + { + if (fromArea == NULL) + { + // first area in path, no cost + return 0.0f; + } + else + { + // compute distance travelled along path so far + float dist; + + if (ladder != NULL) + { + const float ladderCost = 10.0f; + return ladder->m_length * ladderCost + fromArea->GetCostSoFar(); + } + else + { + dist = (*area->GetCenter() - *fromArea->GetCenter()).Length(); + } + + float cost = dist + fromArea->GetCostSoFar(); + + // if this is a "crouch" area, add penalty + if (area->GetAttributes() & NAV_CROUCH) + { + const float crouchPenalty = 10.0f; + cost += crouchPenalty * dist; + } + + // if this is a "jump" area, add penalty + if (area->GetAttributes() & NAV_JUMP) + { + const float jumpPenalty = 10.0f; + cost += jumpPenalty * dist; + } + + return cost; + } + } +}; + +class KeepPersonalSpace { +public: + KeepPersonalSpace(CHostageImprov *improv) + { + m_improv = improv; + m_velDir = improv->GetActualVelocity(); + m_speed = m_velDir.NormalizeInPlace(); + } + bool operator()(CBaseEntity *entity) + { + const float space = 1.0f; + Vector to; + float range; + + if (entity == reinterpret_cast(m_improv->GetEntity())) + return true; + + if (entity->IsPlayer() && !entity->IsAlive()) + return true; + + to = entity->pev->origin - m_improv->GetCentroid(); + range = to.NormalizeInPlace(); + + CBasePlayer *player = static_cast(entity); + + const float spring = 50.0f; + const float damper = 1.0f; + + if (range >= spring) + return true; + + const float cosTolerance = 0.8f; + if (entity->IsPlayer() && player->m_iTeam == CT && !m_improv->IsFollowing() && m_improv->IsPlayerLookingAtMe(player, cosTolerance)) + return true; + + const float minSpace = (spring - range); + float ds = -minSpace; + + m_improv->ApplyForce(to * ds); + + const float force = 0.1f; + m_improv->ApplyForce(m_speed * -force * m_velDir); + + return true; + } + +private: + CHostageImprov *m_improv; + Vector m_velDir; + float m_speed; +}; diff --git a/dep/hlsdk/dlls/hostage/hostage_localnav.h b/dep/hlsdk/dlls/hostage/hostage_localnav.h new file mode 100644 index 0000000..5a40e6f --- /dev/null +++ b/dep/hlsdk/dlls/hostage/hostage_localnav.h @@ -0,0 +1,58 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define NODE_INVALID_EMPTY -1 + +#define PATH_TRAVERSABLE_EMPTY 0 +#define PATH_TRAVERSABLE_SLOPE 1 +#define PATH_TRAVERSABLE_STEP 2 +#define PATH_TRAVERSABLE_STEPJUMPABLE 3 + +typedef int node_index_t; + +typedef struct localnode_s +{ + Vector vecLoc; + int offsetX; + int offsetY; + byte bDepth; + BOOL fSearched; + node_index_t nindexParent; + +} localnode_t; + +class CLocalNav { +private: + CHostage *m_pOwner; + edict_t *m_pTargetEnt; + BOOL m_fTargetEntHit; + localnode_t *m_nodeArr; + node_index_t m_nindexAvailableNode; + Vector m_vecStartingLoc; +}; diff --git a/dep/hlsdk/dlls/hostage/hostage_states.h b/dep/hlsdk/dlls/hostage/hostage_states.h new file mode 100644 index 0000000..95c5854 --- /dev/null +++ b/dep/hlsdk/dlls/hostage/hostage_states.h @@ -0,0 +1,204 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CHostageImprov; + +class HostageState: public SimpleState, public IImprovEvent { +public: + virtual ~HostageState() {} + virtual void UpdateStationaryAnimation(CHostageImprov *improv) {} +}; + +class HostageStateMachine: public SimpleStateMachine, public IImprovEvent { +public: + virtual void OnMoveToSuccess(const Vector &goal) {} + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {} + virtual void OnInjury(float amount) {} +}; + +class HostageIdleState: public HostageState { +public: + virtual ~HostageIdleState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Idle"; } + virtual void UpdateStationaryAnimation(CHostageImprov *improv) {} + virtual void OnMoveToSuccess(const Vector &goal) {} + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {} + virtual void OnInjury(float amount = -1.0f) {} +private: + CountdownTimer m_waveTimer; + CountdownTimer m_fleeTimer; + CountdownTimer m_disagreeTimer; + CountdownTimer m_escapeTimer; + CountdownTimer m_askTimer; + IntervalTimer m_intimidatedTimer; + CountdownTimer m_pleadTimer; + + enum + { + NotMoving = 0, + Moving, + MoveDone, + MoveFailed, + } m_moveState; + + bool m_mustFlee; +}; + +class HostageEscapeToCoverState: public HostageState { +public: + virtual ~HostageEscapeToCoverState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Escape:ToCover"; } + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {} +public: + void SetRescueGoal(const Vector &rescueGoal) { m_rescueGoal = rescueGoal; } + +private: + Vector m_rescueGoal; + Vector m_spot; + bool m_canEscape; +}; + +class HostageEscapeLookAroundState: public HostageState { +public: + virtual ~HostageEscapeLookAroundState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Escape:LookAround"; } + +private: + CountdownTimer m_timer; +}; + +class HostageEscapeState: public HostageState { +public: + virtual ~HostageEscapeState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Escape"; } + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {} +public: + void ToCover() { m_behavior.SetState(&m_toCoverState); } + void LookAround() { m_behavior.SetState(&m_lookAroundState); } +private: + HostageEscapeToCoverState m_toCoverState; + HostageEscapeLookAroundState m_lookAroundState; + HostageStateMachine m_behavior; + bool m_canEscape; + CountdownTimer m_runTimer; +}; + +class HostageRetreatState: public HostageState { +public: + virtual ~HostageRetreatState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Retreat"; } +}; + +class HostageFollowState: public HostageState { +public: + virtual ~HostageFollowState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Follow"; } + virtual void UpdateStationaryAnimation(CHostageImprov *improv) {} +public: + void SetLeader(CBasePlayer *leader) { m_leader = leader; } + CBasePlayer *GetLeader() const { return m_leader; } +private: + mutable EntityHandle m_leader; + Vector m_lastLeaderPos; + bool m_isWaiting; + float m_stopRange; + CountdownTimer m_makeWayTimer; + CountdownTimer m_impatientTimer; + CountdownTimer m_repathTimer; + bool m_isWaitingForFriend; + CountdownTimer m_waitForFriendTimer; +}; + +class HostageAnimateState: public HostageState { +public: + virtual ~HostageAnimateState() {} + virtual void OnEnter(CHostageImprov *improv) {} + virtual void OnUpdate(CHostageImprov *improv) {} + virtual void OnExit(CHostageImprov *improv) {} + virtual const char *GetName() const { return "Animate"; } +public: + struct SeqInfo + { + int seqID; + float holdTime; + float rate; + }; + + enum PerformanceType + { + None = 0, + Walk, + Run, + Jump, + Fall, + Crouch, + CrouchWalk, + Calm, + Anxious, + Afraid, + Sitting, + GettingUp, + Waving, + LookingAround, + Disagreeing, + Flinching, + }; + + bool IsBusy() const { return (m_sequenceCount > 0); } + int GetCurrentSequenceID() { return m_currentSequence; } + PerformanceType GetPerformance() const { return m_performance; } + void SetPerformance(PerformanceType performance) { m_performance = performance; } +private: + enum { MAX_SEQUENCES = 8 }; + struct SeqInfo m_sequence[MAX_SEQUENCES]; + int m_sequenceCount; + int m_currentSequence; + enum PerformanceType m_performance; + bool m_isHolding; + CountdownTimer m_holdTimer; +}; diff --git a/dep/hlsdk/dlls/items.h b/dep/hlsdk/dlls/items.h new file mode 100644 index 0000000..614ce05 --- /dev/null +++ b/dep/hlsdk/dlls/items.h @@ -0,0 +1,156 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +enum ItemRestType +{ + ITEM_TYPE_BUYING, // When a player is buying items + ITEM_TYPE_TOUCHED, // When the player touches with a weaponbox or armoury_entity + ITEM_TYPE_EQUIPPED // When an entity game_player_equip gives item to player or default items on player spawn +}; + +// Constant items +#define ITEM_ID_ANTIDOTE 2 +#define ITEM_ID_SECURITY 3 + +enum ItemID +{ + ITEM_NONE = -1, + ITEM_SHIELDGUN, + ITEM_P228, + ITEM_GLOCK, + ITEM_SCOUT, + ITEM_HEGRENADE, + ITEM_XM1014, + ITEM_C4, + ITEM_MAC10, + ITEM_AUG, + ITEM_SMOKEGRENADE, + ITEM_ELITE, + ITEM_FIVESEVEN, + ITEM_UMP45, + ITEM_SG550, + ITEM_GALIL, + ITEM_FAMAS, + ITEM_USP, + ITEM_GLOCK18, + ITEM_AWP, + ITEM_MP5N, + ITEM_M249, + ITEM_M3, + ITEM_M4A1, + ITEM_TMP, + ITEM_G3SG1, + ITEM_FLASHBANG, + ITEM_DEAGLE, + ITEM_SG552, + ITEM_AK47, + ITEM_KNIFE, + ITEM_P90, + ITEM_NVG, + ITEM_DEFUSEKIT, + ITEM_KEVLAR, + ITEM_ASSAULT, + ITEM_LONGJUMP, + ITEM_SODACAN, + ITEM_HEALTHKIT, + ITEM_ANTIDOTE, + ITEM_BATTERY +}; + +class CItem: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual CBaseEntity *Respawn() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CWorldItem: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +public: + int m_iType; +}; + +class CItemSuit: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemBattery: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemAntidote: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemSecurity: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemLongJump: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemKevlar: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemAssaultSuit: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; + +class CItemThighPack: public CItem { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual BOOL MyTouch(CBasePlayer *pPlayer) = 0; +}; diff --git a/dep/hlsdk/dlls/lights.h b/dep/hlsdk/dlls/lights.h new file mode 100644 index 0000000..b35eed1 --- /dev/null +++ b/dep/hlsdk/dlls/lights.h @@ -0,0 +1,51 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_LIGHT_START_OFF BIT(0) + +class CLight: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +private: + int m_iStyle; + int m_iszPattern; + BOOL m_iStartedOff; +}; + +class CEnvLight: public CLight { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +}; diff --git a/dep/hlsdk/dlls/mapinfo.h b/dep/hlsdk/dlls/mapinfo.h new file mode 100644 index 0000000..acefce0 --- /dev/null +++ b/dep/hlsdk/dlls/mapinfo.h @@ -0,0 +1,43 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +const float MAX_BOMB_RADIUS = 2048.0f; + +class CMapInfo: public CPointEntity +{ +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void UpdateOnRemove() = 0; + +public: + InfoMapBuyParam m_iBuyingStatus; + float m_flBombRadius; +}; diff --git a/dep/hlsdk/dlls/maprules.h b/dep/hlsdk/dlls/maprules.h new file mode 100644 index 0000000..fd663fe --- /dev/null +++ b/dep/hlsdk/dlls/maprules.h @@ -0,0 +1,224 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CRuleEntity: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; +public: + void SetMaster(int iszMaster) { m_iszMaster = iszMaster; } + +private: + string_t m_iszMaster; +}; + +// Base class for all rule "point" entities (not brushes) +class CRulePointEntity: public CRuleEntity { +public: + virtual void Spawn() = 0; +}; + +// Base class for all rule "brush" entities (not brushes) +// Default behavior is to set up like a trigger, invisible, but keep the model for volume testing +class CRuleBrushEntity: public CRuleEntity { +public: + virtual void Spawn() = 0; +}; + +#define SF_SCORE_NEGATIVE BIT(0) // Allow negative scores +#define SF_SCORE_TEAM BIT(1) // Award points to team in teamplay + +// Award points to player / team +// Points +/- total +class CGameScore: public CRulePointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + int Points() const { return int(pev->frags); } + bool AllowNegativeScore() { return (pev->spawnflags & SF_SCORE_NEGATIVE) == SF_SCORE_NEGATIVE; } + bool AwardToTeam() const { return (pev->spawnflags & SF_SCORE_TEAM) == SF_SCORE_TEAM; } + void SetPoints(int points) { pev->frags = points; } +}; + +// Ends the game in Multiplayer +class CGameEnd: public CRulePointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +#define SF_ENVTEXT_ALLPLAYERS BIT(0) // Message will be displayed to all players instead of just the activator. + +// NON-Localized HUD Message (use env_message to display a titles.txt message) +class CGameText: public CRulePointEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + +public: + bool MessageToAll() const { return (pev->spawnflags & SF_ENVTEXT_ALLPLAYERS) == SF_ENVTEXT_ALLPLAYERS; } + void MessageSet(const char *pMessage) { pev->message = ALLOC_STRING(pMessage); } + const char *MessageGet() const { return STRING(pev->message); } + +private: + hudtextparms_t m_textParms; +}; + +#define SF_TEAMMASTER_FIREONCE BIT(0) // Remove on Fire +#define SF_TEAMMASTER_ANYTEAM BIT(1) // Any team until set? -- Any team can use this until the team is set (otherwise no teams can use it) + +// "Masters" like multisource, but based on the team of the activator +// Only allows mastered entity to fire if the team matches my team +// +// team index (pulled from server team list "mp_teamlist" +class CGameTeamMaster: public CRulePointEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL IsTriggered(CBaseEntity *pActivator) = 0; + virtual const char *TeamID() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool RemoveOnFire() const { return (pev->spawnflags & SF_TEAMMASTER_FIREONCE) == SF_TEAMMASTER_FIREONCE; } + bool AnyTeam() const { return (pev->spawnflags & SF_TEAMMASTER_ANYTEAM) == SF_TEAMMASTER_ANYTEAM; } + +public: + int m_teamIndex; + USE_TYPE m_triggerType; +}; + +#define SF_TEAMSET_FIREONCE BIT(0) // Remove entity after firing. +#define SF_TEAMSET_CLEARTEAM BIT(1) // Clear team -- Sets the team to "NONE" instead of activator + +// Changes the team of the entity it targets to the activator's team +class CGameTeamSet: public CRulePointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool RemoveOnFire() const { return (pev->spawnflags & SF_TEAMSET_FIREONCE) == SF_TEAMSET_FIREONCE; } + bool ShouldClearTeam() const { return (pev->spawnflags & SF_TEAMSET_CLEARTEAM) == SF_TEAMSET_CLEARTEAM; } +}; + +// Players in the zone fire my target when I'm fired +// Needs master? +class CGamePlayerZone: public CRuleBrushEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +private: + string_t m_iszInTarget; + string_t m_iszOutTarget; + string_t m_iszInCount; + string_t m_iszOutCount; +}; + +#define SF_PKILL_FIREONCE BIT(0) // Remove entity after firing. + +// Damages the player who fires it +class CGamePlayerHurt: public CRulePointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool RemoveOnFire() const { return (pev->spawnflags & SF_PKILL_FIREONCE) == SF_PKILL_FIREONCE; } +}; + +#define SF_GAMECOUNT_FIREONCE BIT(0) // Remove entity after firing. +#define SF_GAMECOUNT_RESET BIT(1) // Reset entity Initial value after fired. +#define SF_GAMECOUNT_OVER_LIMIT BIT(2) // Fire a target when initial value is higher than limit value. + +// Counts events and fires target +class CGameCounter: public CRulePointEntity { +public: + virtual void Spawn() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool RemoveOnFire() const { return (pev->spawnflags & SF_GAMECOUNT_FIREONCE) == SF_GAMECOUNT_FIREONCE; } + bool ResetOnFire() const { return (pev->spawnflags & SF_GAMECOUNT_RESET) == SF_GAMECOUNT_RESET; } + + void CountUp() { pev->frags++; } + void CountDown() { pev->frags--; } + void ResetCount() { pev->frags = pev->dmg; } + + int CountValue() const { return int(pev->frags); } + int LimitValue() const { return int(pev->health); } + bool HitLimit() const { return ((pev->spawnflags & SF_GAMECOUNT_OVER_LIMIT) == SF_GAMECOUNT_OVER_LIMIT) ? (CountValue() >= LimitValue()) : (CountValue() == LimitValue()); } + +private: + void SetCountValue(int value) { pev->frags = value; } + void SetInitialValue(int value) { pev->dmg = value; } +}; + +#define SF_GAMECOUNTSET_FIREONCE BIT(0) // Remove entity after firing. + +// Sets the counter's value +class CGameCounterSet: public CRulePointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool RemoveOnFire() const { return (pev->spawnflags & SF_GAMECOUNTSET_FIREONCE) == SF_GAMECOUNTSET_FIREONCE; } +}; + +#define MAX_EQUIP 32 +#define SF_PLAYEREQUIP_USEONLY BIT(0) // If set, the game_player_equip entity will not equip respawning players, + // but only react to direct triggering, equipping its activator. This makes its master obsolete. + +// Sets the default player equipment +class CGamePlayerEquip: public CRulePointEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + bool UseOnly() const { return (pev->spawnflags & SF_PLAYEREQUIP_USEONLY) == SF_PLAYEREQUIP_USEONLY; } +public: + string_t m_weaponNames[MAX_EQUIP]; + int m_weaponCount[MAX_EQUIP]; +}; + +#define SF_PTEAM_FIREONCE BIT(0) // Remove entity after firing. +#define SF_PTEAM_KILL BIT(1) // Kill Player. +#define SF_PTEAM_GIB BIT(2) // Gib Player. + +// Changes the team of the player who fired it +class CGamePlayerTeam: public CRulePointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +private: + bool RemoveOnFire() const { return (pev->spawnflags & SF_PTEAM_FIREONCE) == SF_PTEAM_FIREONCE; } + bool ShouldKillPlayer() const { return (pev->spawnflags & SF_PTEAM_KILL) == SF_PTEAM_KILL; } + bool ShouldGibPlayer() const { return (pev->spawnflags & SF_PTEAM_GIB) == SF_PTEAM_GIB; } +}; diff --git a/dep/hlsdk/dlls/monsterevent.h b/dep/hlsdk/dlls/monsterevent.h new file mode 100644 index 0000000..2c7b1b0 --- /dev/null +++ b/dep/hlsdk/dlls/monsterevent.h @@ -0,0 +1,45 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef struct MonsterEvent_s +{ + int event; + char *options; + +} MonsterEvent_t; + +#define EVENT_SPECIFIC 0 +#define EVENT_SCRIPTED 1000 +#define EVENT_SHARED 2000 +#define EVENT_CLIENT 5000 + +#define MONSTER_EVENT_BODYDROP_LIGHT 2001 +#define MONSTER_EVENT_BODYDROP_HEAVY 2002 +#define MONSTER_EVENT_SWISHSOUND 2010 diff --git a/dep/hlsdk/dlls/monsters.h b/dep/hlsdk/dlls/monsters.h new file mode 100644 index 0000000..b4495e2 --- /dev/null +++ b/dep/hlsdk/dlls/monsters.h @@ -0,0 +1,84 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "skill.h" + +#define R_AL -2 // (ALLY) pals. Good alternative to R_NO when applicable. +#define R_FR -1 // (FEAR) will run +#define R_NO 0 // (NO RELATIONSHIP) disregard +#define R_DL 1 // (DISLIKE) will attack +#define R_HT 2 // (HATE) will attack this character instead of any visible DISLIKEd characters +#define R_NM 3 // (NEMESIS) A monster Will ALWAYS attack its nemsis, no matter what + +#define SF_MONSTER_WAIT_TILL_SEEN BIT(0) // spawnflag that makes monsters wait until player can see them before attacking. +#define SF_MONSTER_GAG BIT(1) // no idle noises from this monster +#define SF_MONSTER_HITMONSTERCLIP BIT(2) +#define SF_MONSTER_PRISONER BIT(4) // monster won't attack anyone, no one will attacks him. + +#define SF_MONSTER_WAIT_FOR_SCRIPT BIT(7) //spawnflag that makes monsters wait to check for attacking until the script is done or they've been attacked +#define SF_MONSTER_PREDISASTER BIT(8) //this is a predisaster scientist or barney. Influences how they speak. +#define SF_MONSTER_FADECORPSE BIT(9) // Fade out corpse after death +#define SF_MONSTER_FALL_TO_GROUND BIT(31) + +// These bits represent the monster's memory +#define MEMORY_CLEAR 0 +#define bits_MEMORY_PROVOKED BIT(0) // right now only used for houndeyes. +#define bits_MEMORY_INCOVER BIT(1) // monster knows it is in a covered position. +#define bits_MEMORY_SUSPICIOUS BIT(2) // Ally is suspicious of the player, and will move to provoked more easily +#define bits_MEMORY_PATH_FINISHED BIT(3) // Finished monster path (just used by big momma for now) +#define bits_MEMORY_ON_PATH BIT(4) // Moving on a path +#define bits_MEMORY_MOVE_FAILED BIT(5) // Movement has already failed +#define bits_MEMORY_FLINCHED BIT(6) // Has already flinched +#define bits_MEMORY_KILLED BIT(7) // HACKHACK -- remember that I've already called my Killed() +#define bits_MEMORY_CUSTOM4 BIT(28) // Monster-specific memory +#define bits_MEMORY_CUSTOM3 BIT(29) // Monster-specific memory +#define bits_MEMORY_CUSTOM2 BIT(30) // Monster-specific memory +#define bits_MEMORY_CUSTOM1 BIT(31) // Monster-specific memory + +// MoveToOrigin stuff +#define MOVE_START_TURN_DIST 64 // when this far away from moveGoal, start turning to face next goal +#define MOVE_STUCK_DIST 32 // if a monster can't step this far, it is stuck. + +#define MOVE_NORMAL 0 // normal move in the direction monster is facing +#define MOVE_STRAFE 1 // moves in direction specified, no matter which way monster is facing + +enum HitBoxGroup +{ + HITGROUP_GENERIC = 0, + HITGROUP_HEAD, + HITGROUP_CHEST, + HITGROUP_STOMACH, + HITGROUP_LEFTARM, + HITGROUP_RIGHTARM, + HITGROUP_LEFTLEG, + HITGROUP_RIGHTLEG, + HITGROUP_SHIELD, + NUM_HITGROUPS, +}; diff --git a/dep/hlsdk/dlls/mortar.h b/dep/hlsdk/dlls/mortar.h new file mode 100644 index 0000000..85e4d60 --- /dev/null +++ b/dep/hlsdk/dlls/mortar.h @@ -0,0 +1,56 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CFuncMortarField: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + + // Bmodels don't go across transitions + virtual int ObjectCaps() = 0; +public: + int m_iszXController; + int m_iszYController; + float m_flSpread; + float m_flDelay; + int m_iCount; + int m_fControl; +}; + +class CMortar: public CGrenade { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; +public: + int m_spriteTexture; +}; diff --git a/dep/hlsdk/dlls/observer.h b/dep/hlsdk/dlls/observer.h new file mode 100644 index 0000000..937c86d --- /dev/null +++ b/dep/hlsdk/dlls/observer.h @@ -0,0 +1,32 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define CAMERA_MODE_SPEC_ANYONE 0 +#define CAMERA_MODE_SPEC_ONLY_TEAM 1 +#define CAMERA_MODE_SPEC_ONLY_FRIST_PERSON 2 diff --git a/dep/hlsdk/dlls/pathcorner.h b/dep/hlsdk/dlls/pathcorner.h new file mode 100644 index 0000000..4499bfd --- /dev/null +++ b/dep/hlsdk/dlls/pathcorner.h @@ -0,0 +1,44 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_CORNER_WAITFORTRIG BIT(0) +#define SF_CORNER_TELEPORT BIT(1) +#define SF_CORNER_FIREONCE BIT(2) + +class CPathCorner: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual float GetDelay() = 0; +private: + float m_flWait; +}; diff --git a/dep/hlsdk/dlls/plats.h b/dep/hlsdk/dlls/plats.h new file mode 100644 index 0000000..3d318b7 --- /dev/null +++ b/dep/hlsdk/dlls/plats.h @@ -0,0 +1,190 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_PLAT_TOGGLE BIT(0) // The lift is no more automatically called from top and activated by stepping on it. + // It required trigger to do so. + +class CBasePlatTrain: public CBaseToggle { +public: + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + + // This is done to fix spawn flag collisions between this class and a derived class + virtual BOOL IsTogglePlat() = 0; +public: + byte m_bMoveSnd; + byte m_bStopSnd; + float m_volume; +}; + +class CFuncPlat: public CBasePlatTrain { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; + virtual void GoUp() = 0; + virtual void GoDown() = 0; + virtual void HitTop() = 0; + virtual void HitBottom() = 0; +}; + +class CPlatTrigger: public CBaseEntity { +public: + virtual int ObjectCaps() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +public: + CFuncPlat *m_pPlatform; +}; + +class CFuncPlatRot: public CFuncPlat { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void GoUp() = 0; + virtual void GoDown() = 0; + virtual void HitTop() = 0; + virtual void HitBottom() = 0; +public: + Vector m_end; + Vector m_start; +}; + +#define SF_TRAIN_WAIT_RETRIGGER BIT(0) +#define SF_TRAIN_START_ON BIT(2) // Train is initially moving +#define SF_TRAIN_PASSABLE BIT(3) // Train is not solid -- used to make water trains + +class CFuncTrain: public CBasePlatTrain { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Activate() = 0; + virtual void OverrideReset() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; +public: + Vector m_vStartPosition; + entvars_t *m_pevFirstTarget; + entvars_t *m_pevCurrentTarget; + int m_sounds; + BOOL m_activated; +}; + +// This class defines the volume of space that the player must stand in to control the train +class CFuncTrainControls: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int ObjectCaps() = 0; +}; + +#define SF_TRACK_ACTIVATETRAIN BIT(0) +#define SF_TRACK_RELINK BIT(1) +#define SF_TRACK_ROTMOVE BIT(2) +#define SF_TRACK_STARTBOTTOM BIT(3) +#define SF_TRACK_DONT_MOVE BIT(4) + +enum TRAIN_CODE { TRAIN_SAFE, TRAIN_BLOCKING, TRAIN_FOLLOWING }; + +// This entity is a rotating/moving platform that will carry a train to a new track. +// It must be larger in X-Y planar area than the train, since it must contain the +// train within these dimensions in order to operate when the train is near it. +class CFuncTrackChange: public CFuncPlatRot { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void OverrideReset() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual BOOL IsTogglePlat() = 0; + virtual void GoUp() = 0; + virtual void GoDown() = 0; + virtual void HitTop() = 0; + virtual void HitBottom() = 0; + virtual void UpdateAutoTargets(int toggleState) = 0; + +public: + void DisableUse() { m_use = 0; } + void EnableUse() { m_use = 1; } + + int UseEnabled() const { return m_use; } + +public: + static TYPEDESCRIPTION IMPL(m_SaveData)[9]; + + CPathTrack *m_trackTop; + CPathTrack *m_trackBottom; + CFuncTrackTrain *m_train; + + int m_trackTopName; + int m_trackBottomName; + int m_trainName; + + TRAIN_CODE m_code; + int m_targetState; + int m_use; +}; + +class CFuncTrackAuto: public CFuncTrackChange { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void UpdateAutoTargets(int toggleState) = 0; +}; + +// pev->speed is the travel speed +// pev->health is current health +// pev->max_health is the amount to reset to each time it starts + +#define SF_GUNTARGET_START_ON BIT(0) + +class CGunTarget: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Activate() = 0; + virtual int Classify() = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual int BloodColor() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual Vector BodyTarget(const Vector &posSrc) = 0; +private: + BOOL m_on; +}; diff --git a/dep/hlsdk/dlls/player.h b/dep/hlsdk/dlls/player.h new file mode 100644 index 0000000..042a191 --- /dev/null +++ b/dep/hlsdk/dlls/player.h @@ -0,0 +1,668 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "weapons.h" +#include "pm_materials.h" +#include "hintmessage.h" +#include "unisignals.h" + +#define SOUND_FLASHLIGHT_ON "items/flashlight1.wav" +#define SOUND_FLASHLIGHT_OFF "items/flashlight1.wav" + +const int MAX_PLAYER_NAME_LENGTH = 32; +const int MAX_AUTOBUY_LENGTH = 256; +const int MAX_REBUY_LENGTH = 256; + +const int MAX_RECENT_PATH = 20; +const int MAX_HOSTAGE_ICON = 4; // the maximum number of icons of the hostages in the HUD + +const int MAX_SUIT_NOREPEAT = 32; +const int MAX_SUIT_PLAYLIST = 4; // max of 4 suit sentences queued up at any time + +const int MAX_BUFFER_MENU = 175; +const int MAX_BUFFER_MENU_BRIEFING = 50; + +const float SUIT_UPDATE_TIME = 3.5f; +const float SUIT_FIRST_UPDATE_TIME = 0.1f; + +const float MAX_PLAYER_FATAL_FALL_SPEED = 1100.0f; +const float MAX_PLAYER_SAFE_FALL_SPEED = 500.0f; +const float MAX_PLAYER_USE_RADIUS = 64.0f; + +const float ARMOR_RATIO = 0.5f; // Armor Takes 50% of the damage +const float ARMOR_BONUS = 0.5f; // Each Point of Armor is work 1/x points of health + +const float FLASH_DRAIN_TIME = 1.2f; // 100 units/3 minutes +const float FLASH_CHARGE_TIME = 0.2f; // 100 units/20 seconds (seconds per unit) + +// damage per unit per second. +const float DAMAGE_FOR_FALL_SPEED = 100.0f / (MAX_PLAYER_FATAL_FALL_SPEED - MAX_PLAYER_SAFE_FALL_SPEED); +const float PLAYER_MIN_BOUNCE_SPEED = 350.0f; + +// won't punch player's screen/make scrape noise unless player falling at least this fast. +const float PLAYER_FALL_PUNCH_THRESHHOLD = 250.0f; + +// Money blinks few of times on the freeze period +// NOTE: It works for CZ +const int MONEY_BLINK_AMOUNT = 30; + +// Player time based damage +#define AIRTIME 12 // lung full of air lasts this many seconds +#define PARALYZE_DURATION 2 // number of 2 second intervals to take damage +#define PARALYZE_DAMAGE 1.0f // damage to take each 2 second interval + +#define NERVEGAS_DURATION 2 +#define NERVEGAS_DAMAGE 5.0f + +#define POISON_DURATION 5 +#define POISON_DAMAGE 2.0f + +#define RADIATION_DURATION 2 +#define RADIATION_DAMAGE 1.0f + +#define ACID_DURATION 2 +#define ACID_DAMAGE 5.0f + +#define SLOWBURN_DURATION 2 +#define SLOWBURN_DAMAGE 1.0f + +#define SLOWFREEZE_DURATION 2 +#define SLOWFREEZE_DAMAGE 1.0f + +// Player physics flags bits +// CBasePlayer::m_afPhysicsFlags +#define PFLAG_ONLADDER BIT(0) +#define PFLAG_ONSWING BIT(0) +#define PFLAG_ONTRAIN BIT(1) +#define PFLAG_ONBARNACLE BIT(2) +#define PFLAG_DUCKING BIT(3) // In the process of ducking, but not totally squatted yet +#define PFLAG_USING BIT(4) // Using a continuous entity +#define PFLAG_OBSERVER BIT(5) // Player is locked in stationary cam mode. Spectators can move, observers can't. + +#define TRAIN_OFF 0x00 +#define TRAIN_NEUTRAL 0x01 +#define TRAIN_SLOW 0x02 +#define TRAIN_MEDIUM 0x03 +#define TRAIN_FAST 0x04 +#define TRAIN_BACK 0x05 + +#define TRAIN_ACTIVE 0x80 +#define TRAIN_NEW 0xc0 + +const bool SUIT_GROUP = true; +const bool SUIT_SENTENCE = false; + +const int SUIT_REPEAT_OK = 0; +const int SUIT_NEXT_IN_30SEC = 30; +const int SUIT_NEXT_IN_1MIN = 60; +const int SUIT_NEXT_IN_5MIN = 300; +const int SUIT_NEXT_IN_10MIN = 600; +const int SUIT_NEXT_IN_30MIN = 1800; +const int SUIT_NEXT_IN_1HOUR = 3600; + +const int MAX_TEAM_NAME_LENGTH = 16; + +const auto AUTOAIM_2DEGREES = 0.0348994967025; +const auto AUTOAIM_5DEGREES = 0.08715574274766; +const auto AUTOAIM_8DEGREES = 0.1391731009601; +const auto AUTOAIM_10DEGREES = 0.1736481776669; + +// custom enum +enum RewardType +{ + RT_NONE, + RT_ROUND_BONUS, + RT_PLAYER_RESET, + RT_PLAYER_JOIN, + RT_PLAYER_SPEC_JOIN, + RT_PLAYER_BOUGHT_SOMETHING, + RT_HOSTAGE_TOOK, + RT_HOSTAGE_RESCUED, + RT_HOSTAGE_DAMAGED, + RT_HOSTAGE_KILLED, + RT_TEAMMATES_KILLED, + RT_ENEMY_KILLED, + RT_INTO_GAME, + RT_VIP_KILLED, + RT_VIP_RESCUED_MYSELF +}; + +enum PLAYER_ANIM +{ + PLAYER_IDLE, + PLAYER_WALK, + PLAYER_JUMP, + PLAYER_SUPERJUMP, + PLAYER_DIE, + PLAYER_ATTACK1, + PLAYER_ATTACK2, + PLAYER_FLINCH, + PLAYER_LARGE_FLINCH, + PLAYER_RELOAD, + PLAYER_HOLDBOMB +}; + +enum _Menu +{ + Menu_OFF, + Menu_ChooseTeam, + Menu_IGChooseTeam, + Menu_ChooseAppearance, + Menu_Buy, + Menu_BuyPistol, + Menu_BuyRifle, + Menu_BuyMachineGun, + Menu_BuyShotgun, + Menu_BuySubMachineGun, + Menu_BuyItem, + Menu_Radio1, + Menu_Radio2, + Menu_Radio3, + Menu_ClientBuy +}; + +enum TeamName +{ + UNASSIGNED, + TERRORIST, + CT, + SPECTATOR, +}; + +enum ModelName +{ + MODEL_UNASSIGNED, + MODEL_URBAN, + MODEL_TERROR, + MODEL_LEET, + MODEL_ARCTIC, + MODEL_GSG9, + MODEL_GIGN, + MODEL_SAS, + MODEL_GUERILLA, + MODEL_VIP, + MODEL_MILITIA, + MODEL_SPETSNAZ, + MODEL_AUTO +}; + +enum JoinState +{ + JOINED, + SHOWLTEXT, + READINGLTEXT, + SHOWTEAMSELECT, + PICKINGTEAM, + GETINTOGAME +}; + +enum TrackCommands +{ + CMD_SAY = 0, + CMD_SAYTEAM, + CMD_FULLUPDATE, + CMD_VOTE, + CMD_VOTEMAP, + CMD_LISTMAPS, + CMD_LISTPLAYERS, + CMD_NIGHTVISION, + COMMANDS_TO_TRACK, +}; + +enum IgnoreChatMsg : int +{ + IGNOREMSG_NONE, // Nothing to do + IGNOREMSG_ENEMY, // To ignore any chat messages from the enemy + IGNOREMSG_TEAM // Same as IGNOREMSG_ENEMY but ignore teammates +}; + +struct RebuyStruct +{ + int m_primaryWeapon; + int m_primaryAmmo; + int m_secondaryWeapon; + int m_secondaryAmmo; + int m_heGrenade; + int m_flashbang; + int m_smokeGrenade; + int m_defuser; + int m_nightVision; + ArmorType m_armor; +}; + +enum ThrowDirection +{ + THROW_NONE, + THROW_FORWARD, + THROW_BACKWARD, + THROW_HITVEL, + THROW_BOMB, + THROW_GRENADE, + THROW_HITVEL_MINUS_AIRVEL +}; + +const float MAX_ID_RANGE = 2048.0f; +const float MAX_SPEC_ID_RANGE = 8192.0f; +const int MAX_SBAR_STRING = 128; + +const int SBAR_TARGETTYPE_TEAMMATE = 1; +const int SBAR_TARGETTYPE_ENEMY = 2; +const int SBAR_TARGETTYPE_HOSTAGE = 3; + +enum sbar_data +{ + SBAR_ID_TARGETTYPE = 1, + SBAR_ID_TARGETNAME, + SBAR_ID_TARGETHEALTH, + SBAR_END +}; + +enum MusicState { SILENT, CALM, INTENSE }; + +class CCSPlayer; + +class CStripWeapons: public CPointEntity { +public: + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +// Multiplayer intermission spots. +class CInfoIntermission: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void Think() = 0; +}; + +// Dead HEV suit prop +class CDeadHEV: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Classify() = 0; +public: + int m_iPose; // which sequence to display -- temporary, don't need to save + static char *m_szPoses[4]; +}; + +class CSprayCan: public CBaseEntity { +public: + virtual void Think() = 0; + virtual int ObjectCaps() = 0; +}; + +class CBloodSplat: public CBaseEntity { +public: +}; + +class CBasePlayer: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual int Classify() = 0; + virtual void TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) = 0; + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + virtual BOOL TakeHealth(float flHealth, int bitsDamageType) = 0; + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual void AddPoints(int score, BOOL bAllowNegativeScore) = 0; + virtual void AddPointsToTeam(int score, BOOL bAllowNegativeScore) = 0; + virtual BOOL AddPlayerItem(CBasePlayerItem *pItem) = 0; + virtual BOOL RemovePlayerItem(CBasePlayerItem *pItem) = 0; + virtual int GiveAmmo(int iAmount, const char *szName, int iMax = -1) = 0; + virtual void StartSneaking() = 0; + virtual void UpdateOnRemove() = 0; + virtual BOOL IsSneaking() = 0; + virtual BOOL IsAlive() = 0; + virtual BOOL IsPlayer() = 0; + virtual BOOL IsNetClient() = 0; + virtual const char *TeamID() = 0; + virtual BOOL FBecomeProne() = 0; + virtual Vector BodyTarget(const Vector &posSrc) = 0; + virtual int Illumination() = 0; + virtual BOOL ShouldFadeOnDeath() = 0; + virtual void ResetMaxSpeed() = 0; + virtual void Jump() = 0; + virtual void Duck() = 0; + virtual void PreThink() = 0; + virtual void PostThink() = 0; + virtual Vector GetGunPosition() = 0; + virtual BOOL IsBot() = 0; + virtual void UpdateClientData() = 0; + virtual void ImpulseCommands() = 0; + virtual void RoundRespawn() = 0; + virtual Vector GetAutoaimVector(float flDelta) = 0; + virtual void Blind(float flUntilTime, float flHoldTime, float flFadeTime, int iAlpha) = 0; + virtual void OnTouchingWeapon(CWeaponBox *pWeapon) = 0; +public: + static CBasePlayer *Instance(edict_t *pent) { return (CBasePlayer *)GET_PRIVATE(pent ? pent : ENT(0)); } + static CBasePlayer *Instance(entvars_t *pev) { return Instance(ENT(pev)); } + static CBasePlayer *Instance(int offset) { return Instance(ENT(offset)); } + + int IsObserver() { return pev->iuser1; } + void SetWeaponAnimType(const char *szExtention) { strcpy(m_szAnimExtention, szExtention); } + bool IsProtectedByShield() { return m_bOwnsShield && m_bShieldDrawn; } + bool IsReloading() const; + bool IsBlind() const { return (m_blindUntilTime > gpGlobals->time); } + bool IsAutoFollowAllowed() const { return (gpGlobals->time > m_allowAutoFollowTime); } + void InhibitAutoFollow(float duration) { m_allowAutoFollowTime = gpGlobals->time + duration; } + void AllowAutoFollow() { m_allowAutoFollowTime = 0; } + void SetObserverAutoDirector(bool val) { m_bObserverAutoDirector = val; } + bool CanSwitchObserverModes() const { return m_canSwitchObserverModes; } + CCSPlayer *CSPlayer() const; + + // templates + template + T *ForEachItem(int slot, const Functor &func) + { + auto item = m_rgpPlayerItems[ slot ]; + while (item) + { + if (func(static_cast(item))) + return static_cast(item); + + item = item->m_pNext; + } + + return nullptr; + } + + template + T *ForEachItem(const Functor &func) + { + for (auto item : m_rgpPlayerItems) + { + while (item) + { + if (func(static_cast(item))) + return static_cast(item); + + item = item->m_pNext; + } + } + + return nullptr; + } + + template + T *ForEachItem(const char *pszItemName, const Functor &func) + { + if (!pszItemName) { + return nullptr; + } + + for (auto item : m_rgpPlayerItems) + { + while (item) + { + if (FClassnameIs(pszItemName, STRING(item->pev->classname)) && func(static_cast(item))) { + return static_cast(item); + } + + item = item->m_pNext; + } + } + + return nullptr; + } + +public: + enum { MaxLocationLen = 32 }; + + int random_seed; + unsigned short m_usPlayerBleed; + EHANDLE m_hObserverTarget; + float m_flNextObserverInput; + int m_iObserverWeapon; + int m_iObserverC4State; + bool m_bObserverHasDefuser; + int m_iObserverLastMode; + float m_flFlinchTime; + float m_flAnimTime; + bool m_bHighDamage; + float m_flVelocityModifier; + int m_iLastZoom; + bool m_bResumeZoom; + float m_flEjectBrass; + ArmorType m_iKevlar; + bool m_bNotKilled; + TeamName m_iTeam; + int m_iAccount; + bool m_bHasPrimary; + float m_flDeathThrowTime; + int m_iThrowDirection; + float m_flLastTalk; + bool m_bJustConnected; + bool m_bContextHelp; + JoinState m_iJoiningState; + CBaseEntity *m_pIntroCamera; + float m_fIntroCamTime; + float m_fLastMovement; + bool m_bMissionBriefing; + bool m_bTeamChanged; + ModelName m_iModelName; + int m_iTeamKills; + IgnoreChatMsg m_iIgnoreGlobalChat; + bool m_bHasNightVision; + bool m_bNightVisionOn; + Vector m_vRecentPath[MAX_RECENT_PATH]; + float m_flIdleCheckTime; + float m_flRadioTime; + int m_iRadioMessages; + bool m_bIgnoreRadio; + bool m_bHasC4; + bool m_bHasDefuser; + bool m_bKilledByBomb; + Vector m_vBlastVector; + bool m_bKilledByGrenade; + CHintMessageQueue m_hintMessageQueue; + int m_flDisplayHistory; + _Menu m_iMenu; + int m_iChaseTarget; + CBaseEntity *m_pChaseTarget; + float m_fCamSwitch; + bool m_bEscaped; + bool m_bIsVIP; + float m_tmNextRadarUpdate; + Vector m_vLastOrigin; + int m_iCurrentKickVote; + float m_flNextVoteTime; + bool m_bJustKilledTeammate; + int m_iHostagesKilled; + int m_iMapVote; + bool m_bCanShoot; + float m_flLastFired; + float m_flLastAttackedTeammate; + bool m_bHeadshotKilled; + bool m_bPunishedForTK; + bool m_bReceivesNoMoneyNextRound; + int m_iTimeCheckAllowed; + bool m_bHasChangedName; + char m_szNewName[MAX_PLAYER_NAME_LENGTH]; + bool m_bIsDefusing; + float m_tmHandleSignals; + CUnifiedSignals m_signals; + edict_t *m_pentCurBombTarget; + int m_iPlayerSound; + int m_iTargetVolume; + int m_iWeaponVolume; + int m_iExtraSoundTypes; + int m_iWeaponFlash; + float m_flStopExtraSoundTime; + float m_flFlashLightTime; + int m_iFlashBattery; + int m_afButtonLast; + int m_afButtonPressed; + int m_afButtonReleased; + edict_t *m_pentSndLast; + float m_flSndRoomtype; + float m_flSndRange; + float m_flFallVelocity; + int m_rgItems[MAX_ITEMS]; + int m_fNewAmmo; + unsigned int m_afPhysicsFlags; + float m_fNextSuicideTime; + float m_flTimeStepSound; + float m_flTimeWeaponIdle; + float m_flSwimTime; + float m_flDuckTime; + float m_flWallJumpTime; + float m_flSuitUpdate; + int m_rgSuitPlayList[MAX_SUIT_PLAYLIST]; + int m_iSuitPlayNext; + int m_rgiSuitNoRepeat[MAX_SUIT_NOREPEAT]; + float m_rgflSuitNoRepeatTime[MAX_SUIT_NOREPEAT]; + int m_lastDamageAmount; + float m_tbdPrev; + float m_flgeigerRange; + float m_flgeigerDelay; + int m_igeigerRangePrev; + int m_iStepLeft; + char m_szTextureName[CBTEXTURENAMEMAX]; + char m_chTextureType; + int m_idrowndmg; + int m_idrownrestored; + int m_bitsHUDDamage; + BOOL m_fInitHUD; + BOOL m_fGameHUDInitialized; + int m_iTrain; + BOOL m_fWeapon; + EHANDLE m_pTank; + float m_fDeadTime; + BOOL m_fNoPlayerSound; + BOOL m_fLongJump; + float m_tSneaking; + int m_iUpdateTime; + int m_iClientHealth; + int m_iClientBattery; + int m_iHideHUD; + int m_iClientHideHUD; + int m_iFOV; + int m_iClientFOV; + int m_iNumSpawns; + CBaseEntity *m_pObserver; + CBasePlayerItem *m_rgpPlayerItems[MAX_ITEM_TYPES]; + CBasePlayerItem *m_pActiveItem; + CBasePlayerItem *m_pClientActiveItem; + CBasePlayerItem *m_pLastItem; + int m_rgAmmo[MAX_AMMO_SLOTS]; + int m_rgAmmoLast[MAX_AMMO_SLOTS]; + Vector m_vecAutoAim; + BOOL m_fOnTarget; + int m_iDeaths; + int m_izSBarState[SBAR_END]; + float m_flNextSBarUpdateTime; + float m_flStatusBarDisappearDelay; + char m_SbarString0[MAX_SBAR_STRING]; + int m_lastx; + int m_lasty; + int m_nCustomSprayFrames; + float m_flNextDecalTime; + char m_szTeamName[MAX_TEAM_NAME_LENGTH]; + int m_modelIndexPlayer; + char m_szAnimExtention[32]; + int m_iGaitsequence; + float m_flGaitframe; + float m_flGaityaw; + Vector m_prevgaitorigin; + float m_flPitch; + float m_flYaw; + float m_flGaitMovement; + int m_iAutoWepSwitch; + bool m_bVGUIMenus; + bool m_bShowHints; + bool m_bShieldDrawn; + bool m_bOwnsShield; + bool m_bWasFollowing; + float m_flNextFollowTime; + float m_flYawModifier; + float m_blindUntilTime; + float m_blindStartTime; + float m_blindHoldTime; + float m_blindFadeTime; + int m_blindAlpha; + float m_allowAutoFollowTime; + char m_autoBuyString[MAX_AUTOBUY_LENGTH]; + char *m_rebuyString; + RebuyStruct m_rebuyStruct; + bool m_bIsInRebuy; + float m_flLastUpdateTime; + char m_lastLocation[MaxLocationLen]; + float m_progressStart; + float m_progressEnd; + bool m_bObserverAutoDirector; + bool m_canSwitchObserverModes; + float m_heartBeatTime; + float m_intenseTimestamp; + float m_silentTimestamp; + MusicState m_musicState; + float m_flLastCommandTime[COMMANDS_TO_TRACK]; +}; + +class CWShield: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +public: + void SetCantBePickedUpByUser(CBasePlayer *pPlayer, float time) { m_hEntToIgnoreTouchesFrom = pPlayer; m_flTimeToIgnoreTouches = gpGlobals->time + time; } +public: + EntityHandle m_hEntToIgnoreTouchesFrom; + float m_flTimeToIgnoreTouches; +}; + +inline bool CBasePlayer::IsReloading() const +{ + CBasePlayerWeapon *weapon = static_cast(m_pActiveItem); + if (weapon && weapon->m_fInReload) + return true; + + return false; +} + +inline CCSPlayer *CBasePlayer::CSPlayer() const { + return reinterpret_cast(this->m_pEntity); +} + +// returns a CBaseEntity pointer to a player by index. Only returns if the player is spawned and connected otherwise returns NULL +// Index is 1 based +inline CBasePlayer *UTIL_PlayerByIndex(int playerIndex) +{ + return (CBasePlayer *)GET_PRIVATE(INDEXENT(playerIndex)); +} + +inline CBasePlayer *UTIL_PlayerByIndexSafe(int playerIndex) +{ + CBasePlayer *player = nullptr; + if (likely(playerIndex > 0 && playerIndex <= gpGlobals->maxClients)) + player = UTIL_PlayerByIndex(playerIndex); + + return player; +} diff --git a/dep/hlsdk/dlls/qstring.h b/dep/hlsdk/dlls/qstring.h new file mode 100644 index 0000000..d6e1799 --- /dev/null +++ b/dep/hlsdk/dlls/qstring.h @@ -0,0 +1,121 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define QSTRING_DEFINE + +constexpr unsigned int iStringNull = {0}; + +// Quake string (helper class) +class QString final +{ +public: + using qstring_t = unsigned int; + + QString(): m_string(iStringNull) {}; + QString(qstring_t string): m_string(string) {}; + + bool IsNull() const; + bool IsNullOrEmpty() const; + + // Copy the array + QString &operator=(const QString &other); + + bool operator==(qstring_t string) const; + bool operator==(const QString &s) const; + bool operator==(const char *pszString) const; + + operator const char *() const; + operator unsigned int() const; + const char *str() const; + +private: + qstring_t m_string; +}; + +#ifdef USE_QSTRING +#define string_t QString +#endif + +#include "const.h" +#include "edict.h" +#include "eiface.h" +#include "enginecallback.h" + +extern globalvars_t *gpGlobals; + +#define STRING(offset) ((const char *)(gpGlobals->pStringBase + (unsigned int)(offset))) +#define MAKE_STRING(str) ((unsigned int)(str) - (unsigned int)(STRING(0))) + +// Inlines +inline bool QString::IsNull() const +{ + return m_string == iStringNull; +} + +inline bool QString::IsNullOrEmpty() const +{ + return IsNull() || (&gpGlobals->pStringBase[m_string])[0] == '\0'; +} + +inline QString &QString::operator=(const QString &other) +{ + m_string = other.m_string; + return (*this); +} + +inline bool QString::operator==(qstring_t string) const +{ + return m_string == string; +} + +inline bool QString::operator==(const QString &s) const +{ + return m_string == s.m_string; +} + +inline bool QString::operator==(const char *pszString) const +{ + return strcmp(&gpGlobals->pStringBase[m_string], pszString) == 0; +} + +inline const char *QString::str() const +{ + return &gpGlobals->pStringBase[m_string]; +} + +inline QString::operator const char *() const +{ + return str(); +} + +inline QString::operator unsigned int() const +{ + return m_string; +} diff --git a/dep/hlsdk/dlls/regamedll_api.h b/dep/hlsdk/dlls/regamedll_api.h new file mode 100644 index 0000000..47bdb10 --- /dev/null +++ b/dep/hlsdk/dlls/regamedll_api.h @@ -0,0 +1,490 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once +#include "archtypes.h" +#include "regamedll_interfaces.h" +#include "hookchains.h" +#include "interface.h" +#include "player.h" +#include "gamerules.h" +#include "cdll_dll.h" +#include "items.h" + +#define REGAMEDLL_API_VERSION_MAJOR 5 +#define REGAMEDLL_API_VERSION_MINOR 3 + +// CBasePlayer::Spawn hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Spawn; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Spawn; + +// CBasePlayer::Precache hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Precache; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Precache; + +// CBasePlayer::ObjectCaps hook +typedef IHookChainClass IReGameHook_CBasePlayer_ObjectCaps; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_ObjectCaps; + +// CBasePlayer::Classify hook +typedef IHookChainClass IReGameHook_CBasePlayer_Classify; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Classify; + +// CBasePlayer::TraceAttack hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_TraceAttack; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_TraceAttack; + +// CBasePlayer::TakeDamage hook +typedef IHookChainClass IReGameHook_CBasePlayer_TakeDamage; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_TakeDamage; + +// CBasePlayer::TakeHealth hook +typedef IHookChainClass IReGameHook_CBasePlayer_TakeHealth; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_TakeHealth; + +// CBasePlayer::Killed hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Killed; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Killed; + +// CBasePlayer::AddPoints hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_AddPoints; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_AddPoints; + +// CBasePlayer::AddPointsToTeam hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_AddPointsToTeam; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_AddPointsToTeam; + +// CBasePlayer::AddPlayerItem hook +typedef IHookChainClass IReGameHook_CBasePlayer_AddPlayerItem; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_AddPlayerItem; + +// CBasePlayer::RemovePlayerItem hook +typedef IHookChainClass IReGameHook_CBasePlayer_RemovePlayerItem; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_RemovePlayerItem; + +// CBasePlayer::GiveAmmo hook +typedef IHookChainClass IReGameHook_CBasePlayer_GiveAmmo; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_GiveAmmo; + +// CBasePlayer::ResetMaxSpeed hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_ResetMaxSpeed; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_ResetMaxSpeed; + +// CBasePlayer::Jump hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Jump; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Jump; + +// CBasePlayer::Duck hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Duck; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Duck; + +// CBasePlayer::PreThink hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_PreThink; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_PreThink; + +// CBasePlayer::PostThink hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_PostThink; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_PostThink; + +// CBasePlayer::UpdateClientData hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_UpdateClientData; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_UpdateClientData; + +// CBasePlayer::ImpulseCommands hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_ImpulseCommands; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_ImpulseCommands; + +// CBasePlayer::RoundRespawn hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_RoundRespawn; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_RoundRespawn; + +// CBasePlayer::Blind hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Blind; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Blind; + +// CBasePlayer::Observer_IsValidTarget hook +typedef IHookChainClass IReGameHook_CBasePlayer_Observer_IsValidTarget; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Observer_IsValidTarget; + +// CBasePlayer::SetAnimation hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_SetAnimation; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_SetAnimation; + +// CBasePlayer::GiveDefaultItems hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_GiveDefaultItems; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_GiveDefaultItems; + +// CBasePlayer::GiveNamedItem hook +typedef IHookChainClass IReGameHook_CBasePlayer_GiveNamedItem; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_GiveNamedItem; + +// CBasePlayer::AddAccount hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_AddAccount; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_AddAccount; + +// CBasePlayer::GiveShield hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_GiveShield; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_GiveShield; + +// CBasePlayer:SetClientUserInfoModel hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_SetClientUserInfoModel; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_SetClientUserInfoModel; + +// CBasePlayer:SetClientUserInfoName hook +typedef IHookChainClass IReGameHook_CBasePlayer_SetClientUserInfoName; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_SetClientUserInfoName; + +// CBasePlayer::HasRestrictItem hook +typedef IHookChainClass IReGameHook_CBasePlayer_HasRestrictItem; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_HasRestrictItem; + +// CBasePlayer::DropPlayerItem hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_DropPlayerItem; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_DropPlayerItem; + +// CBasePlayer::DropShield hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_DropShield; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_DropShield; + +// CBasePlayer::OnSpawnEquip hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_OnSpawnEquip; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_OnSpawnEquip; + +// CBasePlayer::Radio hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Radio; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Radio; + +// CBasePlayer::Disappear hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_Disappear; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_Disappear; + +// CBasePlayer::MakeVIP hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_MakeVIP; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_MakeVIP; + +// CBasePlayer::MakeBomber hook +typedef IHookChainClass IReGameHook_CBasePlayer_MakeBomber; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_MakeBomber; + +// CBasePlayer::StartObserver hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_StartObserver; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_StartObserver; + +// CBasePlayer::GetIntoGame hook +typedef IHookChainClass IReGameHook_CBasePlayer_GetIntoGame; +typedef IHookChainRegistryClass IReGameHookRegistry_CBasePlayer_GetIntoGame; + +// CBaseAnimating::ResetSequenceInfo hook +typedef IVoidHookChainClass IReGameHook_CBaseAnimating_ResetSequenceInfo; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBaseAnimating_ResetSequenceInfo; + +// GetForceCamera hook +typedef IHookChain IReGameHook_GetForceCamera; +typedef IHookChainRegistry IReGameHookRegistry_GetForceCamera; + +// PlayerBlind hook +typedef IVoidHookChain IReGameHook_PlayerBlind; +typedef IVoidHookChainRegistry IReGameHookRegistry_PlayerBlind; + +// RadiusFlash_TraceLine hook +typedef IVoidHookChain IReGameHook_RadiusFlash_TraceLine; +typedef IVoidHookChainRegistry IReGameHookRegistry_RadiusFlash_TraceLine; + +// RoundEnd hook +typedef IHookChain IReGameHook_RoundEnd; +typedef IHookChainRegistry IReGameHookRegistry_RoundEnd; + +// InstallGameRules hook +typedef IHookChain IReGameHook_InstallGameRules; +typedef IHookChainRegistry IReGameHookRegistry_InstallGameRules; + +// PM_Init hook +typedef IVoidHookChain IReGameHook_PM_Init; +typedef IVoidHookChainRegistry IReGameHookRegistry_PM_Init; + +// PM_Move hook +typedef IVoidHookChain IReGameHook_PM_Move; +typedef IVoidHookChainRegistry IReGameHookRegistry_PM_Move; + +// PM_AirMove hook +typedef IVoidHookChain IReGameHook_PM_AirMove; +typedef IVoidHookChainRegistry IReGameHookRegistry_PM_AirMove; + +// HandleMenu_ChooseAppearance hook +typedef IVoidHookChain IReGameHook_HandleMenu_ChooseAppearance; +typedef IVoidHookChainRegistry IReGameHookRegistry_HandleMenu_ChooseAppearance; + +// HandleMenu_ChooseTeam hook +typedef IHookChain IReGameHook_HandleMenu_ChooseTeam; +typedef IHookChainRegistry IReGameHookRegistry_HandleMenu_ChooseTeam; + +// ShowMenu hook +typedef IVoidHookChain IReGameHook_ShowMenu; +typedef IVoidHookChainRegistry IReGameHookRegistry_ShowMenu; + +// ShowVGUIMenu hook +typedef IVoidHookChain IReGameHook_ShowVGUIMenu; +typedef IVoidHookChainRegistry IReGameHookRegistry_ShowVGUIMenu; + +// BuyGunAmmo hook +typedef IHookChain IReGameHook_BuyGunAmmo; +typedef IHookChainRegistry IReGameHookRegistry_BuyGunAmmo; + +// BuyWeaponByWeaponID hook +typedef IHookChain IReGameHook_BuyWeaponByWeaponID; +typedef IHookChainRegistry IReGameHookRegistry_BuyWeaponByWeaponID; + +// InternalCommand hook +typedef IHookChain IReGameHook_InternalCommand; +typedef IHookChainRegistry IReGameHookRegistry_InternalCommand; + +// CHalfLifeMultiplay::FShouldSwitchWeapon hook +typedef IHookChain IReGameHook_CSGameRules_FShouldSwitchWeapon; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_FShouldSwitchWeapon; + +// CHalfLifeMultiplay::GetNextBestWeapon hook +typedef IHookChain IReGameHook_CSGameRules_GetNextBestWeapon; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_GetNextBestWeapon; + +// CHalfLifeMultiplay::FlPlayerFallDamage hook +typedef IHookChain IReGameHook_CSGameRules_FlPlayerFallDamage; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_FlPlayerFallDamage; + +// CHalfLifeMultiplay::FPlayerCanTakeDamage hook +typedef IHookChain IReGameHook_CSGameRules_FPlayerCanTakeDamage; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_FPlayerCanTakeDamage; + +// CHalfLifeMultiplay::PlayerSpawn hook +typedef IVoidHookChain IReGameHook_CSGameRules_PlayerSpawn; +typedef IVoidHookChainRegistry IReGameHookRegistry_CSGameRules_PlayerSpawn; + +// CHalfLifeMultiplay::FPlayerCanRespawn hook +typedef IHookChain IReGameHook_CSGameRules_FPlayerCanRespawn; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_FPlayerCanRespawn; + +// CHalfLifeMultiplay::GetPlayerSpawnSpot hook +typedef IHookChain IReGameHook_CSGameRules_GetPlayerSpawnSpot; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_GetPlayerSpawnSpot; + +// CHalfLifeMultiplay::ClientUserInfoChanged hook +typedef IVoidHookChain IReGameHook_CSGameRules_ClientUserInfoChanged; +typedef IVoidHookChainRegistry IReGameHookRegistry_CSGameRules_ClientUserInfoChanged; + +// CHalfLifeMultiplay::PlayerKilled hook +typedef IVoidHookChain IReGameHook_CSGameRules_PlayerKilled; +typedef IVoidHookChainRegistry IReGameHookRegistry_CSGameRules_PlayerKilled; + +// CHalfLifeMultiplay::DeathNotice hook +typedef IVoidHookChain IReGameHook_CSGameRules_DeathNotice; +typedef IVoidHookChainRegistry IReGameHookRegistry_CSGameRules_DeathNotice; + +// CHalfLifeMultiplay::CanHavePlayerItem hook +typedef IHookChain IReGameHook_CSGameRules_CanHavePlayerItem; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_CanHavePlayerItem; + +// CHalfLifeMultiplay::DeadPlayerWeapons hook +typedef IHookChain IReGameHook_CSGameRules_DeadPlayerWeapons; +typedef IHookChainRegistry IReGameHookRegistry_CSGameRules_DeadPlayerWeapons; + +// CHalfLifeMultiplay::ServerDeactivate hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_ServerDeactivate; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_ServerDeactivate; + +// CHalfLifeMultiplay::CheckMapConditions hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_CheckMapConditions; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_CheckMapConditions; + +// CHalfLifeMultiplay::CleanUpMap hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_CleanUpMap; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_CleanUpMap; + +// CHalfLifeMultiplay::RestartRound hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_RestartRound; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_RestartRound; + +// CHalfLifeMultiplay::CheckWinConditions hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_CheckWinConditions; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_CheckWinConditions; + +// CHalfLifeMultiplay::RemoveGuns hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_RemoveGuns; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_RemoveGuns; + +// CHalfLifeMultiplay::GiveC4 hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_GiveC4; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_GiveC4; + +// CHalfLifeMultiplay::ChangeLevel hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_ChangeLevel; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_ChangeLevel; + +// CHalfLifeMultiplay::GoToIntermission hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_GoToIntermission; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_GoToIntermission; + +// CHalfLifeMultiplay::BalanceTeams hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_BalanceTeams; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_BalanceTeams; + +// CHalfLifeMultiplay::OnRoundFreezeEnd hook +typedef IVoidHookChain<> IReGameHook_CSGameRules_OnRoundFreezeEnd; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_CSGameRules_OnRoundFreezeEnd; + +// PM_UpdateStepSound hook +typedef IVoidHookChain<> IReGameHook_PM_UpdateStepSound; +typedef IVoidHookChainRegistry<> IReGameHookRegistry_PM_UpdateStepSound; + +// CBasePlayer::StartDeathCam hook +typedef IVoidHookChainClass IReGameHook_CBasePlayer_StartDeathCam; +typedef IVoidHookChainRegistryClass IReGameHookRegistry_CBasePlayer_StartDeathCam; + +class IReGameHookchains { +public: + virtual ~IReGameHookchains() {} + + // CBasePlayer virtual + virtual IReGameHookRegistry_CBasePlayer_Spawn* CBasePlayer_Spawn() = 0; + virtual IReGameHookRegistry_CBasePlayer_Precache* CBasePlayer_Precache() = 0; + virtual IReGameHookRegistry_CBasePlayer_ObjectCaps* CBasePlayer_ObjectCaps() = 0; + virtual IReGameHookRegistry_CBasePlayer_Classify* CBasePlayer_Classify() = 0; + virtual IReGameHookRegistry_CBasePlayer_TraceAttack* CBasePlayer_TraceAttack() = 0; + virtual IReGameHookRegistry_CBasePlayer_TakeDamage* CBasePlayer_TakeDamage() = 0; + virtual IReGameHookRegistry_CBasePlayer_TakeHealth* CBasePlayer_TakeHealth() = 0; + virtual IReGameHookRegistry_CBasePlayer_Killed* CBasePlayer_Killed() = 0; + virtual IReGameHookRegistry_CBasePlayer_AddPoints* CBasePlayer_AddPoints() = 0; + virtual IReGameHookRegistry_CBasePlayer_AddPointsToTeam* CBasePlayer_AddPointsToTeam() = 0; + virtual IReGameHookRegistry_CBasePlayer_AddPlayerItem* CBasePlayer_AddPlayerItem() = 0; + virtual IReGameHookRegistry_CBasePlayer_RemovePlayerItem* CBasePlayer_RemovePlayerItem() = 0; + virtual IReGameHookRegistry_CBasePlayer_GiveAmmo* CBasePlayer_GiveAmmo() = 0; + virtual IReGameHookRegistry_CBasePlayer_ResetMaxSpeed* CBasePlayer_ResetMaxSpeed() = 0; + virtual IReGameHookRegistry_CBasePlayer_Jump* CBasePlayer_Jump() = 0; + virtual IReGameHookRegistry_CBasePlayer_Duck* CBasePlayer_Duck() = 0; + virtual IReGameHookRegistry_CBasePlayer_PreThink* CBasePlayer_PreThink() = 0; + virtual IReGameHookRegistry_CBasePlayer_PostThink* CBasePlayer_PostThink() = 0; + virtual IReGameHookRegistry_CBasePlayer_UpdateClientData* CBasePlayer_UpdateClientData() = 0; + virtual IReGameHookRegistry_CBasePlayer_ImpulseCommands* CBasePlayer_ImpulseCommands() = 0; + virtual IReGameHookRegistry_CBasePlayer_RoundRespawn* CBasePlayer_RoundRespawn() = 0; + virtual IReGameHookRegistry_CBasePlayer_Blind* CBasePlayer_Blind() = 0; + + virtual IReGameHookRegistry_CBasePlayer_Observer_IsValidTarget* CBasePlayer_Observer_IsValidTarget() = 0; + virtual IReGameHookRegistry_CBasePlayer_SetAnimation* CBasePlayer_SetAnimation() = 0; + virtual IReGameHookRegistry_CBasePlayer_GiveDefaultItems* CBasePlayer_GiveDefaultItems() = 0; + virtual IReGameHookRegistry_CBasePlayer_GiveNamedItem* CBasePlayer_GiveNamedItem() = 0; + virtual IReGameHookRegistry_CBasePlayer_AddAccount* CBasePlayer_AddAccount() = 0; + virtual IReGameHookRegistry_CBasePlayer_GiveShield* CBasePlayer_GiveShield() = 0; + virtual IReGameHookRegistry_CBasePlayer_SetClientUserInfoModel* CBasePlayer_SetClientUserInfoModel() = 0; + virtual IReGameHookRegistry_CBasePlayer_SetClientUserInfoName* CBasePlayer_SetClientUserInfoName() = 0; + virtual IReGameHookRegistry_CBasePlayer_HasRestrictItem* CBasePlayer_HasRestrictItem() = 0; + virtual IReGameHookRegistry_CBasePlayer_DropPlayerItem* CBasePlayer_DropPlayerItem() = 0; + virtual IReGameHookRegistry_CBasePlayer_DropShield* CBasePlayer_DropShield() = 0; + virtual IReGameHookRegistry_CBasePlayer_OnSpawnEquip* CBasePlayer_OnSpawnEquip() = 0; + virtual IReGameHookRegistry_CBasePlayer_Radio* CBasePlayer_Radio() = 0; + virtual IReGameHookRegistry_CBasePlayer_Disappear* CBasePlayer_Disappear() = 0; + virtual IReGameHookRegistry_CBasePlayer_MakeVIP* CBasePlayer_MakeVIP() = 0; + virtual IReGameHookRegistry_CBasePlayer_MakeBomber* CBasePlayer_MakeBomber() = 0; + virtual IReGameHookRegistry_CBasePlayer_StartObserver* CBasePlayer_StartObserver() = 0; + virtual IReGameHookRegistry_CBasePlayer_GetIntoGame* CBasePlayer_GetIntoGame() = 0; + + virtual IReGameHookRegistry_CBaseAnimating_ResetSequenceInfo* CBaseAnimating_ResetSequenceInfo() = 0; + + virtual IReGameHookRegistry_GetForceCamera* GetForceCamera() = 0; + virtual IReGameHookRegistry_PlayerBlind* PlayerBlind() = 0; + virtual IReGameHookRegistry_RadiusFlash_TraceLine* RadiusFlash_TraceLine() = 0; + virtual IReGameHookRegistry_RoundEnd* RoundEnd() = 0; + virtual IReGameHookRegistry_InstallGameRules* InstallGameRules() = 0; + virtual IReGameHookRegistry_PM_Init* PM_Init() = 0; + virtual IReGameHookRegistry_PM_Move* PM_Move() = 0; + virtual IReGameHookRegistry_PM_AirMove* PM_AirMove() = 0; + virtual IReGameHookRegistry_HandleMenu_ChooseAppearance* HandleMenu_ChooseAppearance() = 0; + virtual IReGameHookRegistry_HandleMenu_ChooseTeam* HandleMenu_ChooseTeam() = 0; + virtual IReGameHookRegistry_ShowMenu* ShowMenu() = 0; + virtual IReGameHookRegistry_ShowVGUIMenu* ShowVGUIMenu() = 0; + virtual IReGameHookRegistry_BuyGunAmmo* BuyGunAmmo() = 0; + virtual IReGameHookRegistry_BuyWeaponByWeaponID* BuyWeaponByWeaponID() = 0; + virtual IReGameHookRegistry_InternalCommand* InternalCommand() = 0; + + virtual IReGameHookRegistry_CSGameRules_FShouldSwitchWeapon* CSGameRules_FShouldSwitchWeapon() = 0; + virtual IReGameHookRegistry_CSGameRules_GetNextBestWeapon* CSGameRules_GetNextBestWeapon() = 0; + virtual IReGameHookRegistry_CSGameRules_FlPlayerFallDamage* CSGameRules_FlPlayerFallDamage() = 0; + virtual IReGameHookRegistry_CSGameRules_FPlayerCanTakeDamage* CSGameRules_FPlayerCanTakeDamage() = 0; + virtual IReGameHookRegistry_CSGameRules_PlayerSpawn* CSGameRules_PlayerSpawn() = 0; + virtual IReGameHookRegistry_CSGameRules_FPlayerCanRespawn* CSGameRules_FPlayerCanRespawn() = 0; + virtual IReGameHookRegistry_CSGameRules_GetPlayerSpawnSpot* CSGameRules_GetPlayerSpawnSpot() = 0; + virtual IReGameHookRegistry_CSGameRules_ClientUserInfoChanged* CSGameRules_ClientUserInfoChanged() = 0; + virtual IReGameHookRegistry_CSGameRules_PlayerKilled* CSGameRules_PlayerKilled() = 0; + virtual IReGameHookRegistry_CSGameRules_DeathNotice* CSGameRules_DeathNotice() = 0; + virtual IReGameHookRegistry_CSGameRules_CanHavePlayerItem* CSGameRules_CanHavePlayerItem() = 0; + virtual IReGameHookRegistry_CSGameRules_DeadPlayerWeapons* CSGameRules_DeadPlayerWeapons() = 0; + virtual IReGameHookRegistry_CSGameRules_ServerDeactivate* CSGameRules_ServerDeactivate() = 0; + virtual IReGameHookRegistry_CSGameRules_CheckMapConditions* CSGameRules_CheckMapConditions() = 0; + virtual IReGameHookRegistry_CSGameRules_CleanUpMap* CSGameRules_CleanUpMap() = 0; + virtual IReGameHookRegistry_CSGameRules_RestartRound* CSGameRules_RestartRound() = 0; + virtual IReGameHookRegistry_CSGameRules_CheckWinConditions* CSGameRules_CheckWinConditions() = 0; + virtual IReGameHookRegistry_CSGameRules_RemoveGuns* CSGameRules_RemoveGuns() = 0; + virtual IReGameHookRegistry_CSGameRules_GiveC4* CSGameRules_GiveC4() = 0; + virtual IReGameHookRegistry_CSGameRules_ChangeLevel* CSGameRules_ChangeLevel() = 0; + virtual IReGameHookRegistry_CSGameRules_GoToIntermission* CSGameRules_GoToIntermission() = 0; + virtual IReGameHookRegistry_CSGameRules_BalanceTeams* CSGameRules_BalanceTeams() = 0; + virtual IReGameHookRegistry_CSGameRules_OnRoundFreezeEnd* CSGameRules_OnRoundFreezeEnd() = 0; + virtual IReGameHookRegistry_PM_UpdateStepSound* PM_UpdateStepSound() = 0; + virtual IReGameHookRegistry_CBasePlayer_StartDeathCam* CBasePlayer_StartDeathCam() = 0; +}; + +struct ReGameFuncs_t { + struct edict_s *(*CREATE_NAMED_ENTITY2)(string_t iClass); + void (*ChangeString)(char *&dest, const char *source); + void (*RadiusDamage)(Vector vecSrc, entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, float flRadius, int iClassIgnore, int bitsDamageType); + void (*ClearMultiDamage)(); + void (*ApplyMultiDamage)(entvars_t *pevInflictor, entvars_t *pevAttacker); + void (*AddMultiDamage)(entvars_t *pevInflictor, CBaseEntity *pEntity, float flDamage, int bitsDamageType); + class CBaseEntity *(*UTIL_FindEntityByString)(class CBaseEntity *pStartEntity, const char *szKeyword, const char *szValue); + void (*AddEntityHashValue)(entvars_t *pev, const char *value, hash_types_e fieldType); + void (*RemoveEntityHashValue)(entvars_t *pev, const char *value, hash_types_e fieldType); + int (*Cmd_Argc)(); + const char *(*Cmd_Argv)(int i); +}; + +class IReGameApi { +public: + virtual ~IReGameApi() {} + + virtual int GetMajorVersion() = 0; + virtual int GetMinorVersion() = 0; + virtual const ReGameFuncs_t* GetFuncs() = 0; + virtual IReGameHookchains* GetHookchains() = 0; + + virtual class CGameRules* GetGameRules() = 0; + virtual struct WeaponInfoStruct* GetWeaponInfo(int weaponID) = 0; + virtual struct WeaponInfoStruct* GetWeaponInfo(const char* weaponName) = 0; + virtual struct playermove_s* GetPlayerMove() = 0; + virtual struct WeaponSlotInfo* GetWeaponSlot(WeaponIdType weaponID) = 0; + virtual struct WeaponSlotInfo* GetWeaponSlot(const char* weaponName) = 0; + virtual struct ItemInfo* GetItemInfo(WeaponIdType weaponID) = 0; + virtual struct AmmoInfo* GetAmmoInfo(AmmoType ammoID) = 0; +}; + +#define VRE_GAMEDLL_API_VERSION "VRE_GAMEDLL_API_VERSION001" diff --git a/dep/hlsdk/dlls/regamedll_const.h b/dep/hlsdk/dlls/regamedll_const.h new file mode 100644 index 0000000..ddbe62a --- /dev/null +++ b/dep/hlsdk/dlls/regamedll_const.h @@ -0,0 +1,108 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// These are caps bits to indicate what an object's capabilities (currently used for save/restore and level transitions) +#define FCAP_CUSTOMSAVE 0x00000001 +#define FCAP_ACROSS_TRANSITION 0x00000002 // Should transfer between transitions +#define FCAP_MUST_SPAWN 0x00000004 // Spawn after restore +#define FCAP_DONT_SAVE 0x80000000 // Don't save this +#define FCAP_IMPULSE_USE 0x00000008 // Can be used by the player +#define FCAP_CONTINUOUS_USE 0x00000010 // Can be used by the player +#define FCAP_ONOFF_USE 0x00000020 // Can be used by the player +#define FCAP_DIRECTIONAL_USE 0x00000040 // Player sends +/- 1 when using (currently only tracktrains) +#define FCAP_MASTER 0x00000080 // Can be used to "master" other entities (like multisource) +#define FCAP_MUST_RESET 0x00000100 // Should reset on the new round +#define FCAP_MUST_RELEASE 0x00000200 // Should release on the new round + +// UNDONE: This will ignore transition volumes (trigger_transition), but not the PVS!!! +#define FCAP_FORCE_TRANSITION 0x00000080 // ALWAYS goes across transitions + +// for Classify +#define CLASS_NONE 0 +#define CLASS_MACHINE 1 +#define CLASS_PLAYER 2 +#define CLASS_HUMAN_PASSIVE 3 +#define CLASS_HUMAN_MILITARY 4 +#define CLASS_ALIEN_MILITARY 5 +#define CLASS_ALIEN_PASSIVE 6 +#define CLASS_ALIEN_MONSTER 7 +#define CLASS_ALIEN_PREY 8 +#define CLASS_ALIEN_PREDATOR 9 +#define CLASS_INSECT 10 +#define CLASS_PLAYER_ALLY 11 +#define CLASS_PLAYER_BIOWEAPON 12 // hornets and snarks.launched by players +#define CLASS_ALIEN_BIOWEAPON 13 // hornets and snarks.launched by the alien menace +#define CLASS_VEHICLE 14 +#define CLASS_BARNACLE 99 // special because no one pays attention to it, and it eats a wide cross-section of creatures. + +#define SF_NORESPAWN (1<<30) // set this bit on guns and stuff that should never respawn. + +#define DMG_GENERIC 0 // generic damage was done +#define DMG_CRUSH (1<<0) // crushed by falling or moving object +#define DMG_BULLET (1<<1) // shot +#define DMG_SLASH (1<<2) // cut, clawed, stabbed +#define DMG_BURN (1<<3) // heat burned +#define DMG_FREEZE (1<<4) // frozen +#define DMG_FALL (1<<5) // fell too far +#define DMG_BLAST (1<<6) // explosive blast damage +#define DMG_CLUB (1<<7) // crowbar, punch, headbutt +#define DMG_SHOCK (1<<8) // electric shock +#define DMG_SONIC (1<<9) // sound pulse shockwave +#define DMG_ENERGYBEAM (1<<10) // laser or other high energy beam +#define DMG_NEVERGIB (1<<12) // with this bit OR'd in, no damage type will be able to gib victims upon death +#define DMG_ALWAYSGIB (1<<13) // with this bit OR'd in, any damage type can be made to gib victims upon death +#define DMG_DROWN (1<<14) // Drowning + +// time-based damage +#define DMG_TIMEBASED (~(0x3FFF)) // mask for time-based damage + +#define DMG_PARALYZE (1<<15) // slows affected creature down +#define DMG_NERVEGAS (1<<16) // nerve toxins, very bad +#define DMG_POISON (1<<17) // blood poisioning +#define DMG_RADIATION (1<<18) // radiation exposure +#define DMG_DROWNRECOVER (1<<19) // drowning recovery +#define DMG_ACID (1<<20) // toxic chemicals or acid burns +#define DMG_SLOWBURN (1<<21) // in an oven +#define DMG_SLOWFREEZE (1<<22) // in a subzero freezer +#define DMG_MORTAR (1<<23) // Hit by air raid (done to distinguish grenade from mortar) +#define DMG_EXPLOSION (1<<24) + +// These are the damage types that are allowed to gib corpses +#define DMG_GIB_CORPSE (DMG_CRUSH | DMG_FALL | DMG_BLAST | DMG_SONIC | DMG_CLUB) + +// These are the damage types that have client hud art +#define DMG_SHOWNHUD (DMG_POISON | DMG_ACID | DMG_FREEZE | DMG_SLOWFREEZE | DMG_DROWN | DMG_BURN | DMG_SLOWBURN | DMG_NERVEGAS | DMG_RADIATION | DMG_SHOCK) + +// When calling KILLED(), a value that governs gib behavior is expected to be +// one of these three values +#define GIB_NORMAL 0 // Gib if entity was overkilled +#define GIB_NEVER 1 // Never gib, no matter how much death damage is done ( freezing, etc ) +#define GIB_ALWAYS 2 // Always gib ( Houndeye Shock, Barnacle Bite ) +#define GIB_HEALTH_VALUE -30 diff --git a/dep/hlsdk/dlls/regamedll_interfaces.h b/dep/hlsdk/dlls/regamedll_interfaces.h new file mode 100644 index 0000000..39877a5 --- /dev/null +++ b/dep/hlsdk/dlls/regamedll_interfaces.h @@ -0,0 +1,303 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CBaseEntity; +class CBasePlayer; + +// Implementation wrapper +class CCSEntity { +public: + virtual ~CCSEntity() {} + virtual void FireBullets(int iShots, Vector &vecSrc, Vector &vecDirShooting, Vector &vecSpread, float flDistance, int iBulletType, int iTracerFreq, int iDamage, entvars_t *pevAttacker); + virtual Vector FireBullets3(Vector &vecSrc, Vector &vecDirShooting, float vecSpread, float flDistance, int iPenetration, int iBulletType, int iDamage, float flRangeModifier, entvars_t *pevAttacker, bool bPistol, int shared_rand); +public: + CBaseEntity *m_pContainingEntity; +}; + +class CCSDelay: public CCSEntity {}; +class CCSAnimating: public CCSDelay {}; +class CCSPlayerItem: public CCSAnimating {}; +class CCSToggle: public CCSAnimating {}; +class CCSMonster: public CCSToggle {}; +class CCSWeaponBox: public CCSEntity {}; +class CCSArmoury: public CCSEntity {}; + +class CCSPlayer: public CCSMonster { +public: + CCSPlayer() : m_bForceShowMenu(false) + { + m_szModel[0] = '\0'; + } + + virtual bool IsConnected() const; + virtual void SetAnimation(PLAYER_ANIM playerAnim); + virtual void AddAccount(int amount, RewardType type = RT_NONE, bool bTrackChange = true); + virtual CBaseEntity *GiveNamedItem(const char *pszName); + virtual CBaseEntity *GiveNamedItemEx(const char *pszName); + virtual void GiveDefaultItems(); + virtual void GiveShield(bool bDeploy = true); + virtual void DropShield(bool bDeploy = true); + virtual void DropPlayerItem(const char *pszItemName); + virtual void RemoveShield(); + virtual void RemoveAllItems(bool bRemoveSuit); + virtual bool RemovePlayerItem(const char* pszItemName); + virtual void SetPlayerModel(bool bHasC4); + virtual void SetPlayerModelEx(const char *modelName); + virtual void SetNewPlayerModel(const char *modelName); + virtual void ClientCommand(const char *cmd, const char *arg1 = nullptr, const char *arg2 = nullptr, const char *arg3 = nullptr); + virtual void SetProgressBarTime(int time); + virtual void SetProgressBarTime2(int time, float timeElapsed); + virtual struct edict_s *EntSelectSpawnPoint(); + virtual void SetBombIcon(bool bFlash = false); + virtual void SetScoreAttrib(CBasePlayer *dest); + virtual void SendItemStatus(); + virtual void ReloadWeapons(CBasePlayerItem *pWeapon = nullptr, bool bForceReload = false, bool bForceRefill = false); + virtual void Observer_SetMode(int iMode); + virtual bool SelectSpawnSpot(const char *pEntClassName, CBaseEntity* &pSpot); + virtual bool SwitchWeapon(CBasePlayerItem *pWeapon); + virtual void SwitchTeam(); + virtual bool JoinTeam(TeamName team); + virtual void StartObserver(Vector& vecPosition, Vector& vecViewAngle); + virtual void TeamChangeUpdate(); + virtual void DropSecondary(); + virtual void DropPrimary(); + virtual bool HasPlayerItem(CBasePlayerItem *pCheckItem); + virtual bool HasNamedPlayerItem(const char *pszItemName); + virtual CBasePlayerItem *GetItemById(WeaponIdType weaponID); + virtual CBasePlayerItem *GetItemByName(const char *itemName); + virtual void Disappear(); + virtual void MakeVIP(); + virtual bool MakeBomber(); + virtual void StartDeathCam(); + + CBasePlayer *BasePlayer() const; +public: + char m_szModel[32]; + bool m_bForceShowMenu; +}; + +class CAPI_Bot: public CCSPlayer {}; +class CAPI_CSBot: public CAPI_Bot {}; +class CCSShield: public CCSEntity {}; +class CCSDeadHEV: public CCSMonster {}; +class CCSSprayCan: public CCSEntity {}; +class CCSBloodSplat: public CCSEntity {}; +class CCSPlayerWeapon: public CCSPlayerItem {}; +class CCSWorld: public CCSEntity {}; +class CCSDecal: public CCSEntity {}; +class CCSCorpse: public CCSEntity {}; +class CCSGrenade: public CCSMonster {}; +class CCSAirtank: public CCSGrenade {}; +class CCSPlayerAmmo: public CCSEntity {}; +class CCS9MMAmmo: public CCSPlayerAmmo {}; +class CCSBuckShotAmmo: public CCSPlayerAmmo {}; +class CCS556NatoAmmo: public CCSPlayerAmmo {}; +class CCS556NatoBoxAmmo: public CCSPlayerAmmo {}; +class CCS762NatoAmmo: public CCSPlayerAmmo {}; +class CCS45ACPAmmo: public CCSPlayerAmmo {}; +class CCS50AEAmmo: public CCSPlayerAmmo {}; +class CCS338MagnumAmmo: public CCSPlayerAmmo {}; +class CCS57MMAmmo: public CCSPlayerAmmo {}; +class CCS357SIGAmmo: public CCSPlayerAmmo {}; +class CCSFuncWall: public CCSEntity {}; +class CCSFuncWallToggle: public CCSFuncWall {}; +class CCSFuncConveyor: public CCSFuncWall {}; +class CCSFuncIllusionary: public CCSToggle {}; +class CCSFuncMonsterClip: public CCSFuncWall {}; +class CCSFuncRotating: public CCSEntity {}; +class CCSPendulum: public CCSEntity {}; +class CCSPointEntity: public CCSEntity {}; +class CCSStripWeapons: public CCSPointEntity {}; +class CCSInfoIntermission: public CCSPointEntity {}; +class CCSRevertSaved: public CCSPointEntity {}; +class CCSEnvGlobal: public CCSPointEntity {}; +class CCSMultiSource: public CCSPointEntity {}; +class CCSButton: public CCSToggle {}; +class CCSRotButton: public CCSButton {}; +class CCSMomentaryRotButton: public CCSToggle {}; +class CCSEnvSpark: public CCSEntity {}; +class CCSButtonTarget: public CCSEntity {}; +class CCSDoor: public CCSToggle {}; +class CCSRotDoor: public CCSDoor {}; +class CCSMomentaryDoor: public CCSToggle {}; +class CCSGib: public CCSEntity {}; +class CCSBubbling: public CCSEntity {}; +class CCSBeam: public CCSEntity {}; +class CCSLightning: public CCSBeam {}; +class CCSLaser: public CCSBeam {}; +class CCSGlow: public CCSPointEntity {}; +class CCSSprite: public CCSPointEntity {}; +class CCSBombGlow: public CCSSprite {}; +class CCSGibShooter: public CCSDelay {}; +class CCSEnvShooter: public CCSGibShooter {}; +class CCSTestEffect: public CCSDelay {}; +class CCSBlood: public CCSPointEntity {}; +class CCSShake: public CCSPointEntity {}; +class CCSFade: public CCSPointEntity {}; +class CCSMessage: public CCSPointEntity {}; +class CCSEnvFunnel: public CCSDelay {}; +class CCSEnvBeverage: public CCSDelay {}; +class CCSItemSoda: public CCSEntity {}; +class CCSShower: public CCSEntity {}; +class CCSEnvExplosion: public CCSMonster {}; +class CCSBreakable: public CCSDelay {}; +class CCSPushable: public CCSBreakable {}; +class CCSFuncTank: public CCSEntity {}; +class CCSFuncTankGun: public CCSFuncTank {}; +class CCSFuncTankLaser: public CCSFuncTank {}; +class CCSFuncTankRocket: public CCSFuncTank {}; +class CCSFuncTankMortar: public CCSFuncTank {}; +class CCSFuncTankControls: public CCSEntity {}; +class CCSRecharge: public CCSToggle {}; +class CCSCycler: public CCSMonster {}; +class CCSGenericCycler: public CCSCycler {}; +class CCSCyclerProbe: public CCSCycler {}; +class CCSCyclerSprite: public CCSEntity {}; +class CCSWeaponCycler: public CCSPlayerWeapon {}; +class CCSWreckage: public CCSMonster {}; +class CCSWorldItem: public CCSEntity {}; +class CCSItem: public CCSEntity {}; +class CCSHealthKit: public CCSItem {}; +class CCSWallHealth: public CCSToggle {}; +class CCSItemSuit: public CCSItem {}; +class CCSItemBattery: public CCSItem {}; +class CCSItemAntidote: public CCSItem {}; +class CCSItemSecurity: public CCSItem {}; +class CCSItemLongJump: public CCSItem {}; +class CCSItemKevlar: public CCSItem {}; +class CCSItemAssaultSuit: public CCSItem {}; +class CCSItemThighPack: public CCSItem {}; +class CCSGrenCatch: public CCSEntity {}; +class CCSFuncWeaponCheck: public CCSEntity {}; +class CCSHostage: public CCSMonster {}; +class CCSLight: public CCSPointEntity {}; +class CCSEnvLight: public CCSLight {}; +class CCSRuleEntity: public CCSEntity {}; +class CCSRulePointEntity: public CCSRuleEntity {}; +class CCSRuleBrushEntity: public CCSRuleEntity {}; +class CCSGameScore: public CCSRulePointEntity {}; +class CCSGameEnd: public CCSRulePointEntity {}; +class CCSGameText: public CCSRulePointEntity {}; +class CCSGameTeamMaster: public CCSRulePointEntity {}; +class CCSGameTeamSet: public CCSRulePointEntity {}; +class CCSGamePlayerZone: public CCSRuleBrushEntity {}; +class CCSGamePlayerHurt: public CCSRulePointEntity {}; +class CCSGameCounter: public CCSRulePointEntity {}; +class CCSGameCounterSet: public CCSRulePointEntity {}; +class CCSGamePlayerEquip: public CCSRulePointEntity {}; +class CCSGamePlayerTeam: public CCSRulePointEntity {}; +class CCSFuncMortarField: public CCSToggle {}; +class CCSMortar: public CCSGrenade {}; +class CCSMapInfo: public CCSPointEntity {}; +class CCSPathCorner: public CCSPointEntity {}; +class CCSPathTrack: public CCSPointEntity {}; +class CCSFuncTrackTrain: public CCSEntity {}; +class CCSFuncVehicleControls: public CCSEntity {}; +class CCSFuncVehicle: public CCSEntity {}; +class CCSPlatTrain: public CCSToggle {}; +class CCSFuncPlat: public CCSPlatTrain {}; +class CCSPlatTrigger: public CCSEntity {}; +class CCSFuncPlatRot: public CCSFuncPlat {}; +class CCSFuncTrain: public CCSPlatTrain {}; +class CCSFuncTrainControls: public CCSEntity {}; +class CCSFuncTrackChange: public CCSFuncPlatRot {}; +class CCSFuncTrackAuto: public CCSFuncTrackChange {}; +class CCSGunTarget: public CCSMonster {}; +class CCSAmbientGeneric: public CCSEntity {}; +class CCSEnvSound: public CCSPointEntity {}; +class CCSSpeaker: public CCSEntity {}; +class CCSSoundEnt: public CCSEntity {}; +class CCSUSP: public CCSPlayerWeapon {}; +class CCSMP5N: public CCSPlayerWeapon {}; +class CCSSG552: public CCSPlayerWeapon {}; +class CCSAK47: public CCSPlayerWeapon {}; +class CCSAUG: public CCSPlayerWeapon {}; +class CCSAWP: public CCSPlayerWeapon {}; +class CCSC4: public CCSPlayerWeapon {}; +class CCSDEAGLE: public CCSPlayerWeapon {}; +class CCSFlashbang: public CCSPlayerWeapon {}; +class CCSG3SG1: public CCSPlayerWeapon {}; +class CCSGLOCK18: public CCSPlayerWeapon {}; +class CCSHEGrenade: public CCSPlayerWeapon {}; +class CCSKnife: public CCSPlayerWeapon {}; +class CCSM249: public CCSPlayerWeapon {}; +class CCSM3: public CCSPlayerWeapon {}; +class CCSM4A1: public CCSPlayerWeapon {}; +class CCSMAC10: public CCSPlayerWeapon {}; +class CCSP228: public CCSPlayerWeapon {}; +class CCSP90: public CCSPlayerWeapon {}; +class CCSSCOUT: public CCSPlayerWeapon {}; +class CCSSmokeGrenade: public CCSPlayerWeapon {}; +class CCSTMP: public CCSPlayerWeapon {}; +class CCSXM1014: public CCSPlayerWeapon {}; +class CCSELITE: public CCSPlayerWeapon {}; +class CCSFiveSeven: public CCSPlayerWeapon {}; +class CCSUMP45: public CCSPlayerWeapon {}; +class CCSSG550: public CCSPlayerWeapon {}; +class CCSGalil: public CCSPlayerWeapon {}; +class CCSFamas: public CCSPlayerWeapon {}; +class CCSNullEntity: public CCSEntity {}; +class CCSDMStart: public CCSPointEntity {}; +class CCSFrictionModifier: public CCSEntity {}; +class CCSAutoTrigger: public CCSDelay {}; +class CCSTriggerRelay: public CCSDelay {}; +class CCSMultiManager: public CCSToggle {}; +class CCSRenderFxManager: public CCSEntity {}; +class CCSTrigger: public CCSToggle {}; +class CCSTriggerHurt: public CCSTrigger {}; +class CCSTriggerMonsterJump: public CCSTrigger {}; +class CCSTriggerCDAudio: public CCSTrigger {}; +class CCSTargetCDAudio: public CCSPointEntity {}; +class CCSTriggerMultiple: public CCSTrigger {}; +class CCSTriggerOnce: public CCSTriggerMultiple {}; +class CCSTriggerCounter: public CCSTrigger {}; +class CCSTriggerVolume: public CCSPointEntity {}; +class CCSFireAndDie: public CCSDelay {}; +class CCSChangeLevel: public CCSTrigger {}; +class CCSLadder: public CCSTrigger {}; +class CCSTriggerPush: public CCSTrigger {}; +class CCSTriggerTeleport: public CCSTrigger {}; +class CCSBuyZone: public CCSTrigger {}; +class CCSBombTarget: public CCSTrigger {}; +class CCSHostageRescue: public CCSTrigger {}; +class CCSEscapeZone: public CCSTrigger {}; +class CCSVIP_SafetyZone: public CCSTrigger {}; +class CCSTriggerSave: public CCSTrigger {}; +class CCSTriggerEndSection: public CCSTrigger {}; +class CCSTriggerGravity: public CCSTrigger {}; +class CCSTriggerChangeTarget: public CCSDelay {}; +class CCSTriggerCamera: public CCSDelay {}; +class CCSWeather: public CCSTrigger {}; +class CCSClientFog: public CCSEntity {}; +class CCSTriggerSetOrigin: public CCSDelay {}; + +inline CBasePlayer *CCSPlayer::BasePlayer() const { + return reinterpret_cast(this->m_pContainingEntity); +} diff --git a/dep/hlsdk/dlls/revert_saved.h b/dep/hlsdk/dlls/revert_saved.h new file mode 100644 index 0000000..f8bb4ee --- /dev/null +++ b/dep/hlsdk/dlls/revert_saved.h @@ -0,0 +1,49 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class CRevertSaved: public CPointEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float Duration() const { return pev->dmg_take; } + float HoldTime() const { return pev->dmg_save; } + float MessageTime() const { return m_messageTime; } + float LoadTime() const { return m_loadTime; } + + void SetDuration(float duration) { pev->dmg_take = duration; } + void SetHoldTime(float hold) { pev->dmg_save = hold; } + void SetMessageTime(float time) { m_messageTime = time; } + void SetLoadTime(float time) { m_loadTime = time; } +public: + float m_messageTime; + float m_loadTime; +}; diff --git a/dep/hlsdk/dlls/saverestore.h b/dep/hlsdk/dlls/saverestore.h new file mode 100644 index 0000000..c579ebc --- /dev/null +++ b/dep/hlsdk/dlls/saverestore.h @@ -0,0 +1,207 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define IMPLEMENT_SAVERESTORE(derivedClass, baseClass)\ + int derivedClass::Save(CSave &save)\ + {\ + if (!baseClass::Save(save))\ + return 0;\ + return save.WriteFields(#derivedClass, this, m_SaveData, ARRAYSIZE(m_SaveData));\ + }\ + int derivedClass::Restore(CRestore &restore)\ + {\ + if (!baseClass::Restore(restore))\ + return 0;\ + return restore.ReadFields(#derivedClass, this, m_SaveData, ARRAYSIZE(m_SaveData));\ + } + +enum GLOBALESTATE +{ + GLOBAL_OFF, + GLOBAL_ON, + GLOBAL_DEAD +}; + +typedef struct globalentity_s +{ + char name[64]; + char levelName[MAX_MAPNAME_LENGHT]; + GLOBALESTATE state; + struct globalentity_s *pNext; + +} globalentity_t; + +struct HEADER +{ + unsigned short size; + unsigned short token; + char *pData; +}; + +const int MAX_ENTITY_ARRAY = 64; + +class CBaseEntity; +class CSaveRestoreBuffer +{ +public: + CSaveRestoreBuffer(); + CSaveRestoreBuffer(SAVERESTOREDATA *pdata); + ~CSaveRestoreBuffer(); + + int EntityIndex(entvars_t *pevLookup); + int EntityIndex(edict_t *pentLookup); + int EntityIndex(EOFFSET eoLookup); + int EntityIndex(CBaseEntity *pEntity); + int EntityFlags(int entityIndex, int flags); + int EntityFlagsSet(int entityIndex, int flags); + edict_t *EntityFromIndex(int entityIndex); + unsigned short TokenHash(const char *pszToken); + +protected: + static constexpr int m_Sizes[] = { + sizeof(float), // FIELD_FLOAT + sizeof(int), // FIELD_STRING + sizeof(int), // FIELD_ENTITY + sizeof(int), // FIELD_CLASSPTR + sizeof(int), // FIELD_EHANDLE + sizeof(int), // FIELD_entvars_t + sizeof(int), // FIELD_EDICT + sizeof(float) * 3, // FIELD_VECTOR + sizeof(float) * 3, // FIELD_POSITION_VECTOR + sizeof(int *), // FIELD_POINTER + sizeof(int), // FIELD_INTEGER + sizeof(int *), // FIELD_FUNCTION + sizeof(int), // FIELD_BOOLEAN + sizeof(short), // FIELD_SHORT + sizeof(char), // FIELD_CHARACTER + sizeof(float), // FIELD_TIME + sizeof(int), // FIELD_MODELNAME + sizeof(int), // FIELD_SOUNDNAME + }; + + SAVERESTOREDATA *m_pData; + void BufferRewind(int size); + unsigned int HashString(const char *pszToken); +}; + +class CSave: public CSaveRestoreBuffer +{ +public: + CSave(SAVERESTOREDATA *pdata) : CSaveRestoreBuffer(pdata) {}; + + void WriteShort(const char *pname, const short *value, int count); + void WriteInt(const char *pname, const int *value, int count); + void WriteFloat(const char *pname, const float *value, int count); + void WriteTime(const char *pname, const float *value, int count); + void WriteData(const char *pname, int size, const char *pdata); + void WriteString(const char *pname, const char *pstring); + void WriteString(const char *pname, const int *stringId, int count); + void WriteVector(const char *pname, const Vector &value); + void WriteVector(const char *pname, const float *value, int count); + void WritePositionVector(const char *pname, const Vector &value); + void WritePositionVector(const char *pname, const float *value, int count); + void WriteFunction(const char *pname, void **data, int count); + int WriteEntVars(const char *pname, entvars_t *pev); + int WriteFields(const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount); + +private: + int DataEmpty(const char *pdata, int size); + void BufferField(const char *pname, int size, const char *pdata); + void BufferString(char *pdata, int len); + void BufferData(const char *pdata, int size); + void BufferHeader(const char *pname, int size); +}; + +class CRestore: public CSaveRestoreBuffer +{ +public: + CRestore(SAVERESTOREDATA *pdata) : CSaveRestoreBuffer(pdata) + { + m_global = FALSE; + m_precache = TRUE; + } + int ReadEntVars(const char *pname, entvars_t *pev); + int ReadFields(const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount); + int ReadField(void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount, int startField, int size, char *pName, void *pData); + int ReadInt(); + short ReadShort(); + int ReadNamedInt(const char *pName); + char *ReadNamedString(const char *pName); + + bool Empty() const { return (!m_pData || ((m_pData->pCurrentData - m_pData->pBaseData) >= m_pData->bufferSize)); } + void SetGlobalMode(BOOL global) { m_global = global; } + void PrecacheMode(BOOL mode) { m_precache = mode; } + +private: + char *BufferPointer(); + void BufferReadBytes(char *pOutput, int size); + void BufferSkipBytes(int bytes); + int BufferSkipZString(); + int BufferCheckZString(const char *string); + void BufferReadHeader(HEADER *pheader); + +private: + BOOL m_global; + BOOL m_precache; +}; + +class CGlobalState +{ +public: + CGlobalState(); + + void Reset(); + void ClearStates(); + void EntityAdd(string_t globalname, string_t mapName, GLOBALESTATE state); + void EntitySetState(string_t globalname, GLOBALESTATE state); + void EntityUpdate(string_t globalname, string_t mapname); + const globalentity_t *EntityFromTable(string_t globalname); + GLOBALESTATE EntityGetState(string_t globalname); + + BOOL EntityInTable(string_t globalname) { return Find(globalname) ? TRUE : FALSE; } + int Save(CSave &save); + int Restore(CRestore &restore); + void DumpGlobals(); + + static TYPEDESCRIPTION m_SaveData[]; + static TYPEDESCRIPTION m_GlobalEntitySaveData[]; + +private: + globalentity_t *Find(string_t globalname); + + globalentity_t *m_pList; + int m_listCount; +}; + +void SaveGlobalState(SAVERESTOREDATA *pSaveData); +void RestoreGlobalState(SAVERESTOREDATA *pSaveData); +void ResetGlobalState(); + +extern CGlobalState gGlobalState; diff --git a/dep/hlsdk/dlls/schedule.h b/dep/hlsdk/dlls/schedule.h new file mode 100644 index 0000000..67cb43c --- /dev/null +++ b/dep/hlsdk/dlls/schedule.h @@ -0,0 +1,289 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// these MoveFlag values are assigned to a WayPoint's TYPE in order to demonstrate the +// type of movement the monster should use to get there. +#define bits_MF_TO_TARGETENT BIT(0) // local move to targetent. +#define bits_MF_TO_ENEMY BIT(1) // local move to enemy +#define bits_MF_TO_COVER BIT(2) // local move to a hiding place +#define bits_MF_TO_DETOUR BIT(3) // local move to detour point. +#define bits_MF_TO_PATHCORNER BIT(4) // local move to a path corner +#define bits_MF_TO_NODE BIT(5) // local move to a node +#define bits_MF_TO_LOCATION BIT(6) // local move to an arbitrary point +#define bits_MF_IS_GOAL BIT(7) // this waypoint is the goal of the whole move. +#define bits_MF_DONT_SIMPLIFY BIT(8) // Don't let the route code simplify this waypoint + +// If you define any flags that aren't _TO_ flags, add them here so we can mask +// them off when doing compares. +#define bits_MF_NOT_TO_MASK (bits_MF_IS_GOAL | bits_MF_DONT_SIMPLIFY) + +#define MOVEGOAL_NONE (0) +#define MOVEGOAL_TARGETENT (bits_MF_TO_TARGETENT) +#define MOVEGOAL_ENEMY (bits_MF_TO_ENEMY) +#define MOVEGOAL_PATHCORNER (bits_MF_TO_PATHCORNER) +#define MOVEGOAL_LOCATION (bits_MF_TO_LOCATION) +#define MOVEGOAL_NODE (bits_MF_TO_NODE) + +// these bits represent conditions that may befall the monster, of which some are allowed +// to interrupt certain schedules. +#define bits_COND_NO_AMMO_LOADED BIT(0) // weapon needs to be reloaded! +#define bits_COND_SEE_HATE BIT(1) // see something that you hate +#define bits_COND_SEE_FEAR BIT(2) // see something that you are afraid of +#define bits_COND_SEE_DISLIKE BIT(3) // see something that you dislike +#define bits_COND_SEE_ENEMY BIT(4) // target entity is in full view. +#define bits_COND_ENEMY_OCCLUDED BIT(5) // target entity occluded by the world +#define bits_COND_SMELL_FOOD BIT(6) +#define bits_COND_ENEMY_TOOFAR BIT(7) +#define bits_COND_LIGHT_DAMAGE BIT(8) // hurt a little +#define bits_COND_HEAVY_DAMAGE BIT(9) // hurt a lot +#define bits_COND_CAN_RANGE_ATTACK1 BIT(10) +#define bits_COND_CAN_MELEE_ATTACK1 BIT(11) +#define bits_COND_CAN_RANGE_ATTACK2 BIT(12) +#define bits_COND_CAN_MELEE_ATTACK2 BIT(13) +//#define bits_COND_CAN_RANGE_ATTACK3 BIT(14) + +#define bits_COND_PROVOKED BIT(15) +#define bits_COND_NEW_ENEMY BIT(16) +#define bits_COND_HEAR_SOUND BIT(17) // there is an interesting sound +#define bits_COND_SMELL BIT(18) // there is an interesting scent +#define bits_COND_ENEMY_FACING_ME BIT(19) // enemy is facing me +#define bits_COND_ENEMY_DEAD BIT(20) // enemy was killed. If you get this in combat, try to find another enemy. If you get it in alert, victory dance. +#define bits_COND_SEE_CLIENT BIT(21) // see a client +#define bits_COND_SEE_NEMESIS BIT(22) // see my nemesis + +#define bits_COND_SPECIAL1 BIT(28) // Defined by individual monster +#define bits_COND_SPECIAL2 BIT(29) // Defined by individual monster + +#define bits_COND_TASK_FAILED BIT(30) +#define bits_COND_SCHEDULE_DONE BIT(31) + +#define bits_COND_ALL_SPECIAL (bits_COND_SPECIAL1 | bits_COND_SPECIAL2) +#define bits_COND_CAN_ATTACK (bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1 | bits_COND_CAN_RANGE_ATTACK2 | bits_COND_CAN_MELEE_ATTACK2) + +#define TASKSTATUS_NEW 0 // Just started +#define TASKSTATUS_RUNNING 1 // Running task & movement +#define TASKSTATUS_RUNNING_MOVEMENT 2 // Just running movement +#define TASKSTATUS_RUNNING_TASK 3 // Just running task +#define TASKSTATUS_COMPLETE 4 // Completed, get next task + +// These are the schedule types +typedef enum +{ + SCHED_NONE = 0, + SCHED_IDLE_STAND, + SCHED_IDLE_WALK, + SCHED_WAKE_ANGRY, + SCHED_WAKE_CALLED, + SCHED_ALERT_FACE, + SCHED_ALERT_SMALL_FLINCH, + SCHED_ALERT_BIG_FLINCH, + SCHED_ALERT_STAND, + SCHED_INVESTIGATE_SOUND, + SCHED_COMBAT_FACE, + SCHED_COMBAT_STAND, + SCHED_CHASE_ENEMY, + SCHED_CHASE_ENEMY_FAILED, + SCHED_VICTORY_DANCE, + SCHED_TARGET_FACE, + SCHED_TARGET_CHASE, + SCHED_SMALL_FLINCH, + SCHED_TAKE_COVER_FROM_ENEMY, + SCHED_TAKE_COVER_FROM_BEST_SOUND, + SCHED_TAKE_COVER_FROM_ORIGIN, + SCHED_COWER, // usually a last resort! + SCHED_MELEE_ATTACK1, + SCHED_MELEE_ATTACK2, + SCHED_RANGE_ATTACK1, + SCHED_RANGE_ATTACK2, + SCHED_SPECIAL_ATTACK1, + SCHED_SPECIAL_ATTACK2, + SCHED_STANDOFF, + SCHED_ARM_WEAPON, + SCHED_RELOAD, + SCHED_GUARD, + SCHED_AMBUSH, + SCHED_DIE, + SCHED_WAIT_TRIGGER, + SCHED_FOLLOW, + SCHED_SLEEP, + SCHED_WAKE, + SCHED_BARNACLE_VICTIM_GRAB, + SCHED_BARNACLE_VICTIM_CHOMP, + SCHED_AISCRIPT, + SCHED_FAIL, + + LAST_COMMON_SCHEDULE // Leave this at the bottom + +} SCHEDULE_TYPE; + +// These are the shared tasks +typedef enum +{ + TASK_INVALID = 0, + TASK_WAIT, + TASK_WAIT_FACE_ENEMY, + TASK_WAIT_PVS, + TASK_SUGGEST_STATE, + TASK_WALK_TO_TARGET, + TASK_RUN_TO_TARGET, + TASK_MOVE_TO_TARGET_RANGE, + TASK_GET_PATH_TO_ENEMY, + TASK_GET_PATH_TO_ENEMY_LKP, + TASK_GET_PATH_TO_ENEMY_CORPSE, + TASK_GET_PATH_TO_LEADER, + TASK_GET_PATH_TO_SPOT, + TASK_GET_PATH_TO_TARGET, + TASK_GET_PATH_TO_HINTNODE, + TASK_GET_PATH_TO_LASTPOSITION, + TASK_GET_PATH_TO_BESTSOUND, + TASK_GET_PATH_TO_BESTSCENT, + TASK_RUN_PATH, + TASK_WALK_PATH, + TASK_STRAFE_PATH, + TASK_CLEAR_MOVE_WAIT, + TASK_STORE_LASTPOSITION, + TASK_CLEAR_LASTPOSITION, + TASK_PLAY_ACTIVE_IDLE, + TASK_FIND_HINTNODE, + TASK_CLEAR_HINTNODE, + TASK_SMALL_FLINCH, + TASK_FACE_IDEAL, + TASK_FACE_ROUTE, + TASK_FACE_ENEMY, + TASK_FACE_HINTNODE, + TASK_FACE_TARGET, + TASK_FACE_LASTPOSITION, + TASK_RANGE_ATTACK1, + TASK_RANGE_ATTACK2, + TASK_MELEE_ATTACK1, + TASK_MELEE_ATTACK2, + TASK_RELOAD, + TASK_RANGE_ATTACK1_NOTURN, + TASK_RANGE_ATTACK2_NOTURN, + TASK_MELEE_ATTACK1_NOTURN, + TASK_MELEE_ATTACK2_NOTURN, + TASK_RELOAD_NOTURN, + TASK_SPECIAL_ATTACK1, + TASK_SPECIAL_ATTACK2, + TASK_CROUCH, + TASK_STAND, + TASK_GUARD, + TASK_STEP_LEFT, + TASK_STEP_RIGHT, + TASK_STEP_FORWARD, + TASK_STEP_BACK, + TASK_DODGE_LEFT, + TASK_DODGE_RIGHT, + TASK_SOUND_ANGRY, + TASK_SOUND_DEATH, + TASK_SET_ACTIVITY, + TASK_SET_SCHEDULE, + TASK_SET_FAIL_SCHEDULE, + TASK_CLEAR_FAIL_SCHEDULE, + TASK_PLAY_SEQUENCE, + TASK_PLAY_SEQUENCE_FACE_ENEMY, + TASK_PLAY_SEQUENCE_FACE_TARGET, + TASK_SOUND_IDLE, + TASK_SOUND_WAKE, + TASK_SOUND_PAIN, + TASK_SOUND_DIE, + TASK_FIND_COVER_FROM_BEST_SOUND, // tries lateral cover first, then node cover + TASK_FIND_COVER_FROM_ENEMY, // tries lateral cover first, then node cover + TASK_FIND_LATERAL_COVER_FROM_ENEMY, + TASK_FIND_NODE_COVER_FROM_ENEMY, + TASK_FIND_NEAR_NODE_COVER_FROM_ENEMY, // data for this one is the MAXIMUM acceptable distance to the cover. + TASK_FIND_FAR_NODE_COVER_FROM_ENEMY, // data for this one is there MINIMUM aceptable distance to the cover. + TASK_FIND_COVER_FROM_ORIGIN, + TASK_EAT, + TASK_DIE, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_PLANT_ON_SCRIPT, + TASK_FACE_SCRIPT, + TASK_WAIT_RANDOM, + TASK_WAIT_INDEFINITE, + TASK_STOP_MOVING, + TASK_TURN_LEFT, + TASK_TURN_RIGHT, + TASK_REMEMBER, + TASK_FORGET, + TASK_WAIT_FOR_MOVEMENT, // wait until MovementIsComplete() + LAST_COMMON_TASK, // LEAVE THIS AT THE BOTTOM (sjb) + +} SHARED_TASKS; + +// These go in the flData member of the TASK_WALK_TO_TARGET, TASK_RUN_TO_TARGET +enum +{ + TARGET_MOVE_NORMAL = 0, + TARGET_MOVE_SCRIPTED = 1, +}; + +// A goal should be used for a task that requires several schedules to complete. +// The goal index should indicate which schedule (ordinally) the monster is running. +// That way, when tasks fail, the AI can make decisions based on the context of the +// current goal and sequence rather than just the current schedule. +enum +{ + GOAL_ATTACK_ENEMY, + GOAL_MOVE, + GOAL_TAKE_COVER, + GOAL_MOVE_TARGET, + GOAL_EAT, +}; + +// an array of tasks is a task list +// an array of schedules is a schedule list +struct Task_t +{ + int iTask; + float flData; +}; + +struct Schedule_t +{ + Task_t *pTasklist; + int cTasks; + int iInterruptMask; // a bit mask of conditions that can interrupt this schedule + + // a more specific mask that indicates which TYPES of sounds will interrupt the schedule in the + // event that the schedule is broken by COND_HEAR_SOUND + int iSoundMask; + const char *pName; +}; + +// an array of waypoints makes up the monster's route. +// LATER - this declaration doesn't belong in this file. +struct WayPoint_t +{ + Vector vecLocation; + int iType; +}; diff --git a/dep/hlsdk/dlls/scriptevent.h b/dep/hlsdk/dlls/scriptevent.h new file mode 100644 index 0000000..2e9aeb5 --- /dev/null +++ b/dep/hlsdk/dlls/scriptevent.h @@ -0,0 +1,41 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SCRIPT_EVENT_DEAD 1000 // character is now dead +#define SCRIPT_EVENT_NOINTERRUPT 1001 // does not allow interrupt +#define SCRIPT_EVENT_CANINTERRUPT 1002 // will allow interrupt +#define SCRIPT_EVENT_FIREEVENT 1003 // event now fires +#define SCRIPT_EVENT_SOUND 1004 // Play named wave file (on CHAN_BODY) +#define SCRIPT_EVENT_SENTENCE 1005 // Play named sentence +#define SCRIPT_EVENT_INAIR 1006 // Leave the character in air at the end of the sequence (don't find the floor) +#define SCRIPT_EVENT_ENDANIMATION 1007 // Set the animation by name after the sequence completes +#define SCRIPT_EVENT_SOUND_VOICE 1008 // Play named wave file (on CHAN_VOICE) +#define SCRIPT_EVENT_SENTENCE_RND1 1009 // Play sentence group 25% of the time +#define SCRIPT_EVENT_NOT_DEAD 1010 // Bring back to life (for life/death sequences) diff --git a/dep/hlsdk/dlls/skill.h b/dep/hlsdk/dlls/skill.h new file mode 100644 index 0000000..822b007 --- /dev/null +++ b/dep/hlsdk/dlls/skill.h @@ -0,0 +1,54 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SKILL_EASY 1 +#define SKILL_MEDIUM 2 +#define SKILL_HARD 3 + +struct skilldata_t +{ + int iSkillLevel; + float plrDmg9MM; + float plrDmg357; + float plrDmgMP5; + float plrDmgM203Grenade; + float plrDmgBuckshot; + float plrDmgCrossbowClient; + float plrDmgRPG; + float monDmg9MM; + float monDmgMP5; + float monDmg12MM; + float suitchargerCapacity; + float batteryCapacity; + float healthchargerCapacity; + float healthkitCapacity; +}; + +extern skilldata_t gSkillData; diff --git a/dep/hlsdk/dlls/sound.h b/dep/hlsdk/dlls/sound.h new file mode 100644 index 0000000..6717668 --- /dev/null +++ b/dep/hlsdk/dlls/sound.h @@ -0,0 +1,148 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +const int MAX_SENTENCE_NAME = 16; +const int MAX_SENTENCE_VOXFILE = 1536; // Max number of sentences in game. NOTE: this must match CVOXFILESENTENCEMAX in engine\sound.h + +const int MAX_SENTENCE_GROUPS = 200; // Max number of sentence groups +const int MAX_SENTENCE_LRU = 32; // Max number of elements per sentence group +const int MAX_SENTENCE_DPV_RESET = 27; // Max number of dynamic pitch volumes + +const float MAX_ANNOUNCE_MINS = 2.25f; +const float MIN_ANNOUNCE_MINS = 0.25f; + +enum LowFreqOsc : int +{ + LFO_OFF = 0, + LFO_SQUARE, // Square + LFO_TRIANGLE, // Triangle + LFO_RANDOM, // Random +}; + +// Group of related sentences +struct sentenceg +{ + char szgroupname[16]; + int count; + unsigned char rgblru[MAX_SENTENCE_LRU]; +}; + +// Runtime pitch shift and volume fadein/out structure + +// NOTE: IF YOU CHANGE THIS STRUCT YOU MUST CHANGE THE SAVE/RESTORE VERSION NUMBER +// SEE BELOW (in the typedescription for the class) +typedef struct dynpitchvol +{ + // NOTE: do not change the order of these parameters + // NOTE: unless you also change order of rgdpvpreset array elements! + int preset; + + int pitchrun; // Pitch shift % when sound is running 0 - 255 + int pitchstart; // Pitch shift % when sound stops or starts 0 - 255 + int spinup; // Spinup time 0 - 100 + int spindown; // Spindown time 0 - 100 + + int volrun; // Volume change % when sound is running 0 - 10 + int volstart; // Volume change % when sound stops or starts 0 - 10 + int fadein; // Volume fade in time 0 - 100 + int fadeout; // Volume fade out time 0 - 100 + + // Low Frequency Oscillator + LowFreqOsc lfotype; // 0) off 1) square 2) triangle 3) random + int lforate; // 0 - 1000, how fast lfo osciallates + + int lfomodpitch; // 0-100 mod of current pitch. 0 is off. + int lfomodvol; // 0-100 mod of current volume. 0 is off. + + int cspinup; // Each trigger hit increments counter and spinup pitch + + int cspincount; + int pitch; + int spinupsav; + int spindownsav; + int pitchfrac; + int vol; + int fadeinsav; + int fadeoutsav; + int volfrac; + int lfofrac; + int lfomult; + +} dynpitchvol_t; + +#define SF_AMBIENT_SOUND_STATIC 0 // Medium radius attenuation +#define SF_AMBIENT_SOUND_EVERYWHERE BIT(0) +#define SF_AMBIENT_SOUND_SMALLRADIUS BIT(1) +#define SF_AMBIENT_SOUND_MEDIUMRADIUS BIT(2) +#define SF_AMBIENT_SOUND_LARGERADIUS BIT(3) +#define SF_AMBIENT_SOUND_START_SILENT BIT(4) +#define SF_AMBIENT_SOUND_NOT_LOOPING BIT(5) + +class CAmbientGeneric: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; +public: + float m_flAttenuation; // Attenuation value + dynpitchvol_t m_dpv; + BOOL m_fActive; // Only TRUE when the entity is playing a looping sound + BOOL m_fLooping; // TRUE when the sound played will loop +}; + +class CEnvSound: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Think() = 0; +public: + float m_flRadius; + float m_flRoomtype; +}; + +#define SF_SPEAKER_START_SILENT BIT(0) // Wait for trigger 'on' to start announcements + +class CSpeaker: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; +public: + int m_preset; // Preset number +}; diff --git a/dep/hlsdk/dlls/spectator.h b/dep/hlsdk/dlls/spectator.h new file mode 100644 index 0000000..9d0a07b --- /dev/null +++ b/dep/hlsdk/dlls/spectator.h @@ -0,0 +1,34 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CBaseSpectator: public CBaseEntity { +public: + virtual void Spawn(); +}; diff --git a/dep/hlsdk/dlls/subs.h b/dep/hlsdk/dlls/subs.h new file mode 100644 index 0000000..8cae347 --- /dev/null +++ b/dep/hlsdk/dlls/subs.h @@ -0,0 +1,40 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CNullEntity: public CBaseEntity { +public: + virtual void Spawn() = 0; +}; + +class CBaseDMStart: public CPointEntity { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual BOOL IsTriggered(CBaseEntity *pEntity) = 0; +}; diff --git a/dep/hlsdk/dlls/training_gamerules.h b/dep/hlsdk/dlls/training_gamerules.h new file mode 100644 index 0000000..d820e18 --- /dev/null +++ b/dep/hlsdk/dlls/training_gamerules.h @@ -0,0 +1,94 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CHalfLifeTraining: public CHalfLifeMultiplay { +protected: + virtual ~CHalfLifeTraining() {}; +public: + virtual BOOL IsMultiplayer() = 0; + virtual BOOL IsDeathmatch() = 0; + virtual void InitHUD(CBasePlayer *pl) = 0; + virtual void PlayerSpawn(CBasePlayer *pPlayer) = 0; + virtual void PlayerThink(CBasePlayer *pPlayer) = 0; + virtual BOOL FPlayerCanRespawn(CBasePlayer *pPlayer) = 0; + virtual edict_t *GetPlayerSpawnSpot(CBasePlayer *pPlayer) = 0; + virtual void PlayerKilled(CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor) = 0; + virtual int ItemShouldRespawn(CItem *pItem) = 0; + virtual void CheckMapConditions() = 0; + virtual void CheckWinConditions() = 0; +public: + float FillAccountTime; + float ServerRestartTime; + BOOL fInBuyArea; + BOOL fVisitedBuyArea; + bool fVGUIMenus; +}; + +enum GrenCatchType : int +{ + GRENADETYPE_NONE = 0, + GRENADETYPE_SMOKE, + GRENADETYPE_FLASH, +}; + +class CBaseGrenCatch: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Think() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +public: + GrenCatchType m_NeedGrenadeType; + string_t sTriggerOnGrenade; + string_t sDisableOnGrenade; + bool m_fSmokeTouching; + bool m_fFlashTouched; +}; + +const int MAX_ITEM_COUNTS = 32; + +class CFuncWeaponCheck: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +private: + string_t sTriggerWithItems; + string_t sTriggerNoItems; + string_t sMaster; + string_t sItemName[MAX_ITEM_COUNTS]; + int iItemCount; + int iAnyWeapon; +}; diff --git a/dep/hlsdk/dlls/trains.h b/dep/hlsdk/dlls/trains.h new file mode 100644 index 0000000..18f57ba --- /dev/null +++ b/dep/hlsdk/dlls/trains.h @@ -0,0 +1,145 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_PATH_DISABLED BIT(0) +#define SF_PATH_FIREONCE BIT(1) +#define SF_PATH_ALTREVERSE BIT(2) +#define SF_PATH_DISABLE_TRAIN BIT(3) +#define SF_PATH_ALTERNATE BIT(15) + +class CPathTrack: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData* pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void Activate() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + float m_length; + string_t m_altName; + CPathTrack *m_pnext; + CPathTrack *m_pprevious; + CPathTrack *m_paltpath; +}; + +const float TRAIN_STARTPITCH = 60.0f; +const float TRAIN_MAXPITCH = 200.0f; +const float TRAIN_MAXSPEED = 1000.0f; + +#define SF_TRACKTRAIN_NOPITCH BIT(0) +#define SF_TRACKTRAIN_NOCONTROL BIT(1) +#define SF_TRACKTRAIN_FORWARDONLY BIT(2) +#define SF_TRACKTRAIN_PASSABLE BIT(3) + +class CFuncTrackTrain: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData* pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void OverrideReset() = 0; + virtual BOOL OnControls(entvars_t *pev) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; +public: + CPathTrack *m_ppath; + float m_length; + float m_height; + float m_speed; + float m_dir; + float m_startSpeed; + Vector m_controlMins; + Vector m_controlMaxs; + int m_soundPlaying; + int m_sounds; + float m_flVolume; + float m_flBank; + float m_oldSpeed; + float m_fTurnAngle; + float m_flSteeringWheelDecay; + float m_flAcceleratorDecay; +private: + unsigned short m_usAdjustPitch; +}; + +class CFuncVehicle: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual int Classify() = 0; + virtual void OverrideReset() = 0; + virtual BOOL OnControls(entvars_t *pev) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void Blocked(CBaseEntity *pOther) = 0; +public: + CPathTrack *m_ppath; + float m_length; + float m_width; + float m_height; + float m_speed; + float m_dir; + float m_startSpeed; + Vector m_controlMins; + Vector m_controlMaxs; + int m_soundPlaying; + int m_sounds; + int m_acceleration; + float m_flVolume; + float m_flBank; + float m_oldSpeed; + int m_iTurnAngle; + float m_flSteeringWheelDecay; + float m_flAcceleratorDecay; + float m_flTurnStartTime; + float m_flLaunchTime; + float m_flLastNormalZ; + float m_flCanTurnNow; + float m_flUpdateSound; + Vector m_vFrontLeft; + Vector m_vFront; + Vector m_vFrontRight; + Vector m_vBackLeft; + Vector m_vBack; + Vector m_vBackRight; + Vector m_vSurfaceNormal; + Vector m_vVehicleDirection; + CBaseEntity *m_pDriver; +private: + unsigned short m_usAdjustPitch; +}; diff --git a/dep/hlsdk/dlls/triggers.h b/dep/hlsdk/dlls/triggers.h new file mode 100644 index 0000000..9a1556d --- /dev/null +++ b/dep/hlsdk/dlls/triggers.h @@ -0,0 +1,374 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "utlmap.h" + +class CFrictionModifier: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; +public: + float m_frictionFraction; +}; + +#define SF_AUTO_FIREONCE BIT(0) +#define SF_AUTO_NORESET BIT(1) + +// This trigger will fire when the level spawns (or respawns if not fire once) +// It will check a global state before firing. It supports delay and killtargets +class CAutoTrigger: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Think() = 0; +public: + int m_globalstate; + USE_TYPE m_triggerType; +}; + +#define SF_RELAY_FIREONCE BIT(0) + +class CTriggerRelay: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + USE_TYPE m_triggerType; +}; + +const int MAX_MM_TARGETS = 16; // maximum number of targets a single multi_manager entity may be assigned. + +#define SF_MULTIMAN_THREAD BIT(0) +#define SF_MULTIMAN_CLONE BIT(31) + +// This entity when fire, will fire up to 16 targets at specified times. +// FLAG: THREAD (create clones when triggered) +// FLAG: CLONE (this is a clone for a threaded execution) +class CMultiManager: public CBaseToggle { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual BOOL HasTarget(string_t targetname) = 0; +public: + int m_cTargets; + int m_index; + float m_startTime; + int m_iTargetName[MAX_MM_TARGETS]; + float m_flTargetDelay[MAX_MM_TARGETS]; +}; + +// Flags to indicate masking off various render parameters that are normally copied to the targets +#define SF_RENDER_MASKFX BIT(0) +#define SF_RENDER_MASKAMT BIT(1) +#define SF_RENDER_MASKMODE BIT(2) +#define SF_RENDER_MASKCOLOR BIT(3) + +// Render parameters trigger +// This entity will copy its render parameters (renderfx, rendermode, rendercolor, renderamt) +// to its targets when triggered. +class CRenderFxManager: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual void UpdateOnRemove() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + struct RenderGroup_t + { + int rendermode; + float renderamt; + Vector rendercolor; + int renderfx; + }; + CUtlMap m_RenderGroups; +}; + +#define SF_TRIGGER_ALLOWMONSTERS BIT(0) // monsters allowed to fire this trigger +#define SF_TRIGGER_NOCLIENTS BIT(1) // players not allowed to fire this trigger +#define SF_TRIGGER_PUSHABLES BIT(2) // only pushables can fire this trigger +#define SF_TRIGGER_NORESET BIT(6) // it is not allowed to be resetting on a new round + +class CBaseTrigger: public CBaseToggle { +public: + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int ObjectCaps() = 0; +}; + +#define SF_TRIGGER_HURT_TARGETONCE BIT(0) // Only fire hurt target once +#define SF_TRIGGER_HURT_START_OFF BIT(1) // spawnflag that makes trigger_push spawn turned OFF +#define SF_TRIGGER_HURT_NO_CLIENTS BIT(3) // spawnflag that makes trigger_push spawn turned OFF +#define SF_TRIGGER_HURT_CLIENTONLYFIRE BIT(4) // trigger hurt will only fire its target if it is hurting a client +#define SF_TRIGGER_HURT_CLIENTONLYTOUCH BIT(5) // only clients may touch this trigger. + +// Hurts anything that touches it. +// If the trigger has a targetname, firing it will toggle state +class CTriggerHurt: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual int ObjectCaps() = 0; +}; + +class CTriggerMonsterJump: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void Think() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +}; + +// Starts/stops cd audio tracks +class CTriggerCDAudio: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +// This plays a CD track when fired or when the player enters it's radius +class CTargetCDAudio: public CPointEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Think() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +}; + +// Variable sized repeatable trigger. Must be targeted at one or more entities. +// If "health" is set, the trigger must be killed to activate each time. +// If "delay" is set, the trigger waits some time after activating before firing. +// "wait" : Seconds between triggerings. (.2 default) +// If notouch is set, the trigger is only fired by other entities, not by touching. +// NOTOUCH has been obsoleted by trigger_relay! +// sounds +// 1) secret +// 2) beep beep +// 3) large switch +// 4) +// NEW +// if a trigger has a NETNAME, that NETNAME will become the TARGET of the triggered object. +class CTriggerMultiple: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +// Variable sized trigger. Triggers once, then removes itself. You must set the key "target" to the name of another object in the level that has a matching +// "targetname". If "health" is set, the trigger must be killed to activate. +// If notouch is set, the trigger is only fired by other entities, not by touching. +// if "killtarget" is set, any objects that have a matching "target" will be removed when the trigger is fired. +// if "angle" is set, the trigger will only fire when someone is facing the direction of the angle. Use "360" for an angle of 0. +// sounds +// 1) secret +// 2) beep beep +// 3) large switch +// 4) +class CTriggerOnce: public CTriggerMultiple { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; +}; + +// Acts as an intermediary for an action that takes multiple inputs. +// If nomessage is not set, it will print "1 more.. " etc when triggered and +// "sequence complete" when finished. After the counter has been triggered "cTriggersLeft" +// times (default 2), it will fire all of it's targets and remove itself. +class CTriggerCounter: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +// Derive from point entity so this doesn't move across levels +class CTriggerVolume: public CPointEntity { +public: + virtual void Spawn() = 0; +}; + +// Fires a target after level transition and then dies +class CFireAndDie: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int ObjectCaps() = 0; // Always go across transitions + virtual void Think() = 0; +}; + +#define SF_CHANGELEVEL_USEONLY BIT(1) + +// When the player touches this, he gets sent to the map listed in the "map" variable. +// Unless the NO_INTERMISSION flag is set, the view will go to the info_intermission spot and display stats. +class CChangeLevel: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; +public: + char m_szMapName[MAX_MAPNAME_LENGHT]; // next map + char m_szLandmarkName[MAX_MAPNAME_LENGHT]; // landmark on next map + int m_changeTarget; + float m_changeTargetDelay; +}; + +class CLadder: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +}; + +#define SF_TRIGGER_PUSH_ONCE BIT(0) +#define SF_TRIGGER_PUSH_START_OFF BIT(1) // spawnflag that makes trigger_push spawn turned OFF + +class CTriggerPush: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +}; + +class CTriggerTeleport: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CBuyZone: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CBombTarget: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CHostageRescue: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CEscapeZone: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CVIP_SafetyZone: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CTriggerSave: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +#define SF_ENDSECTION_USEONLY BIT(0) + +class CTriggerEndSection: public CBaseTrigger { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +}; + +class CTriggerGravity: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +// this is a really bad idea. +class CTriggerChangeTarget: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +private: + int m_iszNewTarget; +}; + +#define SF_CAMERA_PLAYER_POSITION BIT(0) +#define SF_CAMERA_PLAYER_TARGET BIT(1) +#define SF_CAMERA_PLAYER_TAKECONTROL BIT(2) + +class CTriggerCamera: public CBaseDelay { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; +public: + EHANDLE m_hPlayer; + EHANDLE m_hTarget; + CBaseEntity *m_pentPath; + int m_sPath; + float m_flWait; + float m_flReturnTime; + float m_flStopTime; + float m_moveDistance; + float m_targetSpeed; + float m_initialSpeed; + float m_acceleration; + float m_deceleration; + int m_state; +}; + +class CWeather: public CBaseTrigger { +public: + virtual void Spawn() = 0; +}; + +class CClientFog: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +public: + int m_iStartDist; + int m_iEndDist; + float m_fDensity; +}; diff --git a/dep/hlsdk/dlls/unisignals.h b/dep/hlsdk/dlls/unisignals.h new file mode 100644 index 0000000..f96be69 --- /dev/null +++ b/dep/hlsdk/dlls/unisignals.h @@ -0,0 +1,58 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SIGNAL_BUY BIT(0) +#define SIGNAL_BOMB BIT(1) +#define SIGNAL_RESCUE BIT(2) +#define SIGNAL_ESCAPE BIT(3) +#define SIGNAL_VIPSAFETY BIT(4) + +class CUnifiedSignals +{ +public: + CUnifiedSignals() + { + m_flSignal = 0; + m_flState = 0; + } +public: + void Update() + { + m_flState = m_flSignal; + m_flSignal = 0; + } + void Signal(int flags) { m_flSignal |= flags; } + int GetSignal() const { return m_flSignal; } + int GetState() const { return m_flState; } + +private: + int m_flSignal; + int m_flState; +}; diff --git a/dep/hlsdk/dlls/util.h b/dep/hlsdk/dlls/util.h new file mode 100644 index 0000000..eb9efc2 --- /dev/null +++ b/dep/hlsdk/dlls/util.h @@ -0,0 +1,180 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "shake.h" +#include "activity.h" +#include "enginecallback.h" +#include "utlvector.h" + +extern globalvars_t *gpGlobals; + +#define STRING(offset) ((const char *)(gpGlobals->pStringBase + (unsigned int)(offset))) +#define MAKE_STRING(str) ((uint64)(str) - (uint64)(STRING(0))) + +#define GROUP_OP_AND 0 +#define GROUP_OP_NAND 1 + +// Dot products for view cone checking +#define VIEW_FIELD_FULL -1.0 // +-180 degrees +#define VIEW_FIELD_WIDE -0.7 // +-135 degrees 0.1 // +-85 degrees, used for full FOV checks +#define VIEW_FIELD_NARROW 0.7 // +-45 degrees, more narrow check used to set up ranged attacks +#define VIEW_FIELD_ULTRA_NARROW 0.9 // +-25 degrees, more narrow check used to set up ranged attacks + +#define SND_STOP BIT(5) // duplicated in protocol.h stop sound +#define SND_CHANGE_VOL BIT(6) // duplicated in protocol.h change sound vol +#define SND_CHANGE_PITCH BIT(7) // duplicated in protocol.h change sound pitch +#define SND_SPAWNING BIT(8) // duplicated in protocol.h we're spawing, used in some cases for ambients + +// All monsters need this data +#define DONT_BLEED -1 +#define BLOOD_COLOR_DARKRED (byte)223 +#define BLOOD_COLOR_RED (byte)247 +#define BLOOD_COLOR_YELLOW (byte)195 +#define BLOOD_COLOR_GREEN BLOOD_COLOR_YELLOW + +#define GERMAN_GIB_COUNT 4 +#define HUMAN_GIB_COUNT 6 +#define ALIEN_GIB_COUNT 4 + +#define LANGUAGE_ENGLISH 0 +#define LANGUAGE_GERMAN 1 +#define LANGUAGE_FRENCH 2 +#define LANGUAGE_BRITISH 3 + +#define SVC_NOP 1 +#define SVC_SOUND 6 +#define SVC_TEMPENTITY 23 +#define SVC_INTERMISSION 30 +#define SVC_CDTRACK 32 +#define SVC_WEAPONANIM 35 +#define SVC_ROOMTYPE 37 +#define SVC_DIRECTOR 51 + +#define VEC_HULL_MIN_Z Vector(0, 0, -36) +#define VEC_DUCK_HULL_MIN_Z Vector(0, 0, -18) + +#define VEC_HULL_MIN Vector(-16, -16, -36) +#define VEC_HULL_MAX Vector(16, 16, 36) + +#define VEC_VIEW Vector(0, 0, 17) + +#define VEC_DUCK_HULL_MIN Vector(-16, -16, -18) +#define VEC_DUCK_HULL_MAX Vector(16, 16, 32) +#define VEC_DUCK_VIEW Vector(0, 0, 12) + +#define PRECACHE_SOUND_ARRAY(a) \ + { for (int i = 0; i < ARRAYSIZE(a); ++i) PRECACHE_SOUND((char *)a[i]); } + +#define PLAYBACK_EVENT(flags, who, index)\ + PLAYBACK_EVENT_FULL(flags, who, index, 0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0) + +#define PLAYBACK_EVENT_DELAY(flags, who, index, delay)\ + PLAYBACK_EVENT_FULL(flags, who, index, delay, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0) + +#define LINK_ENTITY_TO_CLASS(mapClassName, DLLClassName)\ + C_DLLEXPORT void EXT_FUNC mapClassName(entvars_t *pev);\ + void mapClassName(entvars_t *pev)\ + {\ + GetClassPtr((DLLClassName *)pev);\ + } + +const EOFFSET eoNullEntity = (EOFFSET)0; // Testing the three types of "entity" for nullity +const string_t iStringNull = (string_t)0; // Testing strings for nullity + +// Inlines +inline edict_t *FIND_ENTITY_BY_CLASSNAME(edict_t *entStart, const char *pszName) { return FIND_ENTITY_BY_STRING(entStart, "classname", pszName); } +inline edict_t *FIND_ENTITY_BY_TARGETNAME(edict_t *entStart, const char *pszName) { return FIND_ENTITY_BY_STRING(entStart, "targetname", pszName); } + +inline edict_t *ENT(const entvars_t *pev) { return pev->pContainingEntity; } +inline edict_t *ENT(EOFFSET eoffset) { return (*g_engfuncs.pfnPEntityOfEntOffset)(eoffset); } +inline EOFFSET OFFSET(const edict_t *pent) { return (*g_engfuncs.pfnEntOffsetOfPEntity)(pent); } +inline EOFFSET OFFSET(const entvars_t *pev) { return OFFSET(ENT(pev)); } + +inline entvars_t *VARS(edict_t *pent) +{ + if (!pent) + return nullptr; + + return &pent->v; +} + +inline entvars_t *VARS(EOFFSET eoffset) +{ + return VARS(ENT(eoffset)); +} + +#ifndef ENTINDEX +inline int ENTINDEX(const edict_t *pEdict) { return (*g_engfuncs.pfnIndexOfEdict)(pEdict); } +inline int ENTINDEX(const entvars_t *pev) { return (*g_engfuncs.pfnIndexOfEdict)(ENT(pev)); } +#endif // ENTINDEX + +#ifndef INDEXENT +inline edict_t *INDEXENT(int iEdictNum) { return (*g_engfuncs.pfnPEntityOfEntIndex)(iEdictNum); } +#endif // INDEXENT + +inline void MESSAGE_BEGIN(int msg_dest, int msg_type, const float *pOrigin, entvars_t *ent) { MESSAGE_BEGIN(msg_dest, msg_type, pOrigin, ENT(ent)); } +inline bool FNullEnt(EOFFSET eoffset) { return (eoffset == 0); } +inline bool FNullEnt(entvars_t *pev) { return (pev == nullptr || FNullEnt(OFFSET(pev))); } +inline bool FNullEnt(const edict_t *pent) { return (pent == nullptr || pent->free || FNullEnt(OFFSET(pent))); } +inline bool FStringNull(string_t iString) { return (iString == iStringNull); } +inline bool FStrEq(const char *sz1, const char *sz2) { return (Q_strcmp(sz1, sz2) == 0); } +inline bool FClassnameIs(entvars_t *pev, const char *szClassname) { return FStrEq(STRING(pev->classname), szClassname); } +inline bool FClassnameIs(edict_t *pent, const char *szClassname) { return FStrEq(STRING(VARS(pent)->classname), szClassname); } +inline void UTIL_MakeVectorsPrivate(Vector vecAngles, float *p_vForward, float *p_vRight, float *p_vUp) { g_engfuncs.pfnAngleVectors(vecAngles, p_vForward, p_vRight, p_vUp); } + +extern void EMIT_SOUND_DYN(edict_t *entity, int channel, const char *sample, float volume, float attenuation, int flags, int pitch); + +// NOTE: use EMIT_SOUND_DYN to set the pitch of a sound. Pitch of 100 +// is no pitch shift. Pitch > 100 up to 255 is a higher pitch, pitch < 100 +// down to 1 is a lower pitch. 150 to 70 is the realistic range. +// EMIT_SOUND_DYN with pitch != 100 should be used sparingly, as it's not quite as +// fast as EMIT_SOUND (the pitchshift mixer is not native coded). +inline void EMIT_SOUND(edict_t *entity, int channel, const char *sample, float volume, float attenuation) +{ + EMIT_SOUND_DYN(entity, channel, sample, volume, attenuation, 0, PITCH_NORM); +} + +inline void STOP_SOUND(edict_t *entity, int channel, const char *sample) +{ + EMIT_SOUND_DYN(entity, channel, sample, 0, 0, SND_STOP, PITCH_NORM); +} + +inline void EMIT_SOUND_MSG(edict_t *entity, int msg_type, int channel, const char *sample, float volume, float attenuation, int flags, int pitch = PITCH_NORM, Vector vecOrigin = Vector(0, 0, 0), edict_t *player = nullptr) +{ + BUILD_SOUND_MSG(entity, channel, sample, (volume * 255.0f), attenuation, flags, pitch, msg_type, SVC_NOP, vecOrigin, player); +} + +inline void STOP_SOUND_MSG(edict_t *entity, int msg_type, int channel, const char *sample, edict_t *player) +{ + BUILD_SOUND_MSG(entity, channel, sample, 0, 0, SND_STOP, PITCH_NORM, msg_type, SVC_NOP, Vector(0, 0, 0), player); +} + +extern char *UTIL_VarArgs(char *format, ...); +extern void UTIL_LogPrintf(const char *fmt, ...); diff --git a/dep/hlsdk/dlls/vector.h b/dep/hlsdk/dlls/vector.h new file mode 100644 index 0000000..a117071 --- /dev/null +++ b/dep/hlsdk/dlls/vector.h @@ -0,0 +1,208 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Used for many pathfinding and many other operations that are treated as planar rather than 3D. +class Vector2D { +public: + // Construction/destruction + inline Vector2D() : x(), y() {} + inline Vector2D(float X, float Y) : x(X), y(Y) {} + inline Vector2D(const Vector2D &v) { *(int *)&x = *(int *)&v.x; *(int *)&y = *(int *)&v.y; } + + // Operators + inline decltype(auto) operator-() const { return Vector2D(-x, -y); } + inline bool operator==(const Vector2D &v) const { return x == v.x && y == v.y; } + inline bool operator!=(const Vector2D &v) const { return !(*this == v); } + + inline decltype(auto) operator+(const Vector2D &v) const { return Vector2D(x + v.x, y + v.y); } + inline decltype(auto) operator-(const Vector2D &v) const { return Vector2D(x - v.x, y - v.y); } + inline decltype(auto) operator*(const Vector2D &v) const { return Vector2D(x * v.x, y * v.y); } + inline decltype(auto) operator/(const Vector2D &v) const { return Vector2D(x / v.x, y / v.y); } + + inline decltype(auto) operator+=(const Vector2D &v) { return (*this = *this + v); } + inline decltype(auto) operator-=(const Vector2D &v) { return (*this = *this - v); } + inline decltype(auto) operator*=(const Vector2D &v) { return (*this = *this * v); } + inline decltype(auto) operator/=(const Vector2D &v) { return (*this = *this / v); } + + inline decltype(auto) operator+(float fl) const { return Vector2D(x + fl, y + fl); } + inline decltype(auto) operator-(float fl) const { return Vector2D(x - fl, y - fl); } + inline decltype(auto) operator*(float fl) const { return Vector2D(x * fl, y * fl); } + inline decltype(auto) operator/(float fl) const { return Vector2D(x / fl, y / fl); } + + inline decltype(auto) operator+=(float fl) { return (*this = *this + fl); } + inline decltype(auto) operator-=(float fl) { return (*this = *this - fl); } + inline decltype(auto) operator*=(float fl) { return (*this = *this * fl); } + inline decltype(auto) operator/=(float fl) { return (*this = *this / fl); } + + // Methods + inline void CopyToArray(float *rgfl) const { *(int *)&rgfl[0] = *(int *)&x; *(int *)&rgfl[1] = *(int *)&y; } + inline float Length() const { return sqrt(x * x + y * y); } // Get the vector's magnitude + inline float LengthSquared() const { return (x * x + y * y); } // Get the vector's magnitude squared + + operator float*() { return &x; } + operator const float*() const { return &x; } + + inline Vector2D Normalize() const + { + float flLen = Length(); + if (flLen == 0) + return Vector2D(0, 0); + + flLen = 1 / flLen; + return Vector2D(x * flLen, y * flLen); + } + + inline bool IsLengthLessThan (float length) const { return (LengthSquared() < length * length); } + inline bool IsLengthGreaterThan(float length) const { return (LengthSquared() > length * length); } + inline float NormalizeInPlace() + { + float flLen = Length(); + if (flLen == 0) + { + x = 1; y = 0; + } + else + { + flLen = 1 / flLen; + x *= flLen; y *= flLen; + } + + return flLen; + } + inline bool IsZero(float tolerance = 0.01f) const + { + return (x > -tolerance && x < tolerance && + y > -tolerance && y < tolerance); + } + + // Members + vec_t x, y; +}; + +inline float DotProduct(const Vector2D &a, const Vector2D &b) { return (a.x * b.x + a.y * b.y); } +inline Vector2D operator*(float fl, const Vector2D &v) { return v * fl; } + +// 3D Vector +// Same data-layout as engine's vec3_t, which is a vec_t[3] +class Vector { +public: + // Construction/destruction + inline Vector() : x(), y(), z() {} + inline Vector(float X, float Y, float Z) : x(X), y(Y), z(Z) {} + inline Vector(const Vector &v) { *(int *)&x = *(int *)&v.x; *(int *)&y = *(int *)&v.y; *(int *)&z = *(int *)&v.z; } + inline Vector(const float rgfl[3]) { *(int *)&x = *(int *)&rgfl[0]; *(int *)&y = *(int *)&rgfl[1]; *(int *)&z = *(int *)&rgfl[2]; } + + // Operators + inline decltype(auto) operator-() const { return Vector(-x, -y, -z); } + inline bool operator==(const Vector &v) const { return x == v.x && y == v.y && z == v.z; } + inline bool operator!=(const Vector &v) const { return !(*this == v); } + + inline decltype(auto) operator+(const Vector &v) const { return Vector(x + v.x, y + v.y, z + v.z); } + inline decltype(auto) operator-(const Vector &v) const { return Vector(x - v.x, y - v.y, z - v.z); } + inline decltype(auto) operator*(const Vector &v) const { return Vector(x * v.x, y * v.y, z * v.z); } + inline decltype(auto) operator/(const Vector &v) const { return Vector(x / v.x, y / v.y, z / v.z); } + + inline decltype(auto) operator+=(const Vector &v) { return (*this = *this + v); } + inline decltype(auto) operator-=(const Vector &v) { return (*this = *this - v); } + inline decltype(auto) operator*=(const Vector &v) { return (*this = *this * v); } + inline decltype(auto) operator/=(const Vector &v) { return (*this = *this / v); } + + inline decltype(auto) operator+(float fl) const { return Vector(x + fl, y + fl, z + fl); } + inline decltype(auto) operator-(float fl) const { return Vector(x - fl, y - fl, z - fl); } + inline decltype(auto) operator*(float fl) const { return Vector(x * fl, y * fl, z * fl); } + inline decltype(auto) operator/(float fl) const { return Vector(x / fl, y / fl, z / fl); } + + inline decltype(auto) operator+=(float fl) { return (*this = *this + fl); } + inline decltype(auto) operator-=(float fl) { return (*this = *this - fl); } + inline decltype(auto) operator*=(float fl) { return (*this = *this * fl); } + inline decltype(auto) operator/=(float fl) { return (*this = *this / fl); } + + // Methods + inline void CopyToArray(float *rgfl) const { *(int *)&rgfl[0] = *(int *)&x; *(int *)&rgfl[1] = *(int *)&y; *(int *)&rgfl[2] = *(int *)&z; } + inline float Length() const { return sqrt(x * x + y * y + z * z); } // Get the vector's magnitude + inline float LengthSquared() const { return (x * x + y * y + z * z); } // Get the vector's magnitude squared + + operator float*() { return &x; } // Vectors will now automatically convert to float * when needed + operator const float*() const { return &x; } // Vectors will now automatically convert to float * when needed + + inline Vector Normalize() + { + float flLen = Length(); + if (flLen == 0) + return Vector(0, 0, 1); + + flLen = 1 / flLen; + return Vector(x * flLen, y * flLen, z * flLen); + } + inline Vector2D Make2D() const + { + Vector2D Vec2; + *(int *)&Vec2.x = *(int *)&x; + *(int *)&Vec2.y = *(int *)&y; + return Vec2; + } + + inline float Length2D() const { return sqrt(x * x + y * y); } + + inline bool IsLengthLessThan (float length) const { return (LengthSquared() < length * length); } + inline bool IsLengthGreaterThan(float length) const { return (LengthSquared() > length * length); } + + inline float NormalizeInPlace() + { + float flLen = Length(); + if (flLen == 0) + { + x = 0; y = 0; z = 1; + } + else + { + flLen = 1 / flLen; + x *= flLen; y *= flLen; z *= flLen; + } + + return flLen; + } + inline bool IsZero(float tolerance = 0.01f) const + { + return (x > -tolerance && x < tolerance && + y > -tolerance && y < tolerance && + z > -tolerance && z < tolerance); + } + + // Members + vec_t x, y, z; +}; + +inline Vector operator*(float fl, const Vector &v) { return v * fl; } +inline float DotProduct(const Vector &a, const Vector &b) { return (a.x * b.x + a.y * b.y + a.z * b.z); } +inline float DotProduct2D(const Vector &a, const Vector &b) { return (a.x * b.x + a.y * b.y); } +inline Vector CrossProduct(const Vector &a, const Vector &b) { return Vector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); } + +#define vec3_t Vector diff --git a/dep/hlsdk/dlls/vehicle.h b/dep/hlsdk/dlls/vehicle.h new file mode 100644 index 0000000..1e8e3b4 --- /dev/null +++ b/dep/hlsdk/dlls/vehicle.h @@ -0,0 +1,54 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define VEHICLE_SPEED0_ACCELERATION 0.005000000000000000 +#define VEHICLE_SPEED1_ACCELERATION 0.002142857142857143 +#define VEHICLE_SPEED2_ACCELERATION 0.003333333333333334 +#define VEHICLE_SPEED3_ACCELERATION 0.004166666666666667 +#define VEHICLE_SPEED4_ACCELERATION 0.004000000000000000 +#define VEHICLE_SPEED5_ACCELERATION 0.003800000000000000 +#define VEHICLE_SPEED6_ACCELERATION 0.004500000000000000 +#define VEHICLE_SPEED7_ACCELERATION 0.004250000000000000 +#define VEHICLE_SPEED8_ACCELERATION 0.002666666666666667 +#define VEHICLE_SPEED9_ACCELERATION 0.002285714285714286 +#define VEHICLE_SPEED10_ACCELERATION 0.001875000000000000 +#define VEHICLE_SPEED11_ACCELERATION 0.001444444444444444 +#define VEHICLE_SPEED12_ACCELERATION 0.001200000000000000 +#define VEHICLE_SPEED13_ACCELERATION 0.000916666666666666 + +#define VEHICLE_STARTPITCH 60 +#define VEHICLE_MAXPITCH 200 +#define VEHICLE_MAXSPEED 1500 + +class CFuncVehicleControls: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual int ObjectCaps() = 0; +}; diff --git a/dep/hlsdk/dlls/weapons.h b/dep/hlsdk/dlls/weapons.h new file mode 100644 index 0000000..c6bf810 --- /dev/null +++ b/dep/hlsdk/dlls/weapons.h @@ -0,0 +1,1404 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CBasePlayer; + +const float MAX_NORMAL_BATTERY = 100.0f; +const float MAX_DIST_RELOAD_SOUND = 512.0f; + +#define MAX_WEAPONS 32 + +#define ITEM_FLAG_SELECTONEMPTY 1 +#define ITEM_FLAG_NOAUTORELOAD 2 +#define ITEM_FLAG_NOAUTOSWITCHEMPTY 4 +#define ITEM_FLAG_LIMITINWORLD 8 +#define ITEM_FLAG_EXHAUSTIBLE 16 // A player can totally exhaust their ammo supply and lose this weapon + +#define WEAPON_IS_ONTARGET 0x40 + +// the maximum amount of ammo each weapon's clip can hold +#define WEAPON_NOCLIP -1 + +#define LOUD_GUN_VOLUME 1000 +#define NORMAL_GUN_VOLUME 600 +#define QUIET_GUN_VOLUME 200 + +#define BRIGHT_GUN_FLASH 512 +#define NORMAL_GUN_FLASH 256 +#define DIM_GUN_FLASH 128 + +#define BIG_EXPLOSION_VOLUME 2048 +#define NORMAL_EXPLOSION_VOLUME 1024 +#define SMALL_EXPLOSION_VOLUME 512 + +#define WEAPON_ACTIVITY_VOLUME 64 + +// spawn flags +#define SF_DETONATE BIT(0) // Grenades flagged with this will be triggered when the owner calls detonateSatchelCharges + +// custom enum +enum ArmorType +{ + ARMOR_NONE, // No armor + ARMOR_KEVLAR, // Body vest only + ARMOR_VESTHELM, // Vest and helmet +}; + +enum ArmouryItemPack +{ + ARMOURY_MP5NAVY, + ARMOURY_TMP, + ARMOURY_P90, + ARMOURY_MAC10, + ARMOURY_AK47, + ARMOURY_SG552, + ARMOURY_M4A1, + ARMOURY_AUG, + ARMOURY_SCOUT, + ARMOURY_G3SG1, + ARMOURY_AWP, + ARMOURY_M3, + ARMOURY_XM1014, + ARMOURY_M249, + ARMOURY_FLASHBANG, + ARMOURY_HEGRENADE, + ARMOURY_KEVLAR, + ARMOURY_ASSAULT, + ARMOURY_SMOKEGRENADE, + ARMOURY_SHIELD, + ARMOURY_FAMAS, + ARMOURY_SG550, + ARMOURY_GALIL, + ARMOURY_UMP45, + ARMOURY_GLOCK18, + ARMOURY_USP, + ARMOURY_ELITE, + ARMOURY_FIVESEVEN, + ARMOURY_P228, + ARMOURY_DEAGLE, +}; + +struct ItemInfo +{ + int iSlot; + int iPosition; + const char *pszAmmo1; + int iMaxAmmo1; + const char *pszAmmo2; + int iMaxAmmo2; + const char *pszName; + int iMaxClip; + int iId; + int iFlags; + int iWeight; +}; + +struct AmmoInfo +{ + const char *pszName; + int iId; +}; + +struct MULTIDAMAGE +{ + CBaseEntity *pEntity; + float amount; + int type; +}; + +#include "weapontype.h" +#include "items.h" + +class CArmoury: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void Restart() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +public: + ArmouryItemPack m_iItem; + int m_iCount; + int m_iInitialCount; + bool m_bAlreadyCounted; +}; + +// Smoke Grenade / HE grenade / Flashbang grenade / C4 +class CGrenade: public CBaseMonster { +public: + virtual void Spawn() = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual int ObjectCaps() = 0; + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual int BloodColor() = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual void BounceSound() = 0; +public: + bool m_bStartDefuse; + bool m_bIsC4; + EntityHandle m_pBombDefuser; + float m_flDefuseCountDown; + float m_flC4Blow; + float m_flNextFreqInterval; + float m_flNextBeep; + float m_flNextFreq; + char *m_sBeepName; + float m_fAttenu; + float m_flNextBlink; + float m_fNextDefuse; + bool m_bJustBlew; + int m_iTeam; + int m_iCurWave; + edict_t *m_pentCurBombTarget; + int m_SGSmoke; + int m_angle; + unsigned short m_usEvent; + bool m_bLightSmoke; + bool m_bDetonated; + Vector m_vSmokeDetonate; + int m_iBounceCount; + BOOL m_fRegisteredSound; // whether or not this grenade has issued its DANGER sound to the world sound list yet. +}; + +// Items that the player has in their inventory that they can use +class CBasePlayerItem: public CBaseAnimating { +public: + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void SetObjectCollisionBox() = 0; + virtual CBaseEntity *Respawn() = 0; + virtual int AddToPlayer(CBasePlayer *pPlayer) = 0; // return TRUE if the item you want the item added to the player inventory + virtual int AddDuplicate(CBasePlayerItem *pItem) = 0; // return TRUE if you want your duplicate removed from world + virtual int GetItemInfo(ItemInfo *p) = 0; // returns 0 if struct not filled out + virtual BOOL CanDeploy() = 0; + virtual BOOL CanDrop() = 0; // returns is deploy was successful + virtual BOOL Deploy() = 0; + virtual BOOL IsWeapon() = 0; + virtual BOOL CanHolster() = 0; // can this weapon be put away right now? + virtual void Holster(int skiplocal = 0) = 0; + virtual void UpdateItemInfo() = 0; + virtual void ItemPreFrame() = 0; // called each frame by the player PreThink + virtual void ItemPostFrame() = 0; // called each frame by the player PostThink + virtual void Drop() = 0; + virtual void Kill() = 0; + virtual void AttachToPlayer(CBasePlayer *pPlayer) = 0; + virtual int PrimaryAmmoIndex() = 0; + virtual int SecondaryAmmoIndex() = 0; + virtual int UpdateClientData(CBasePlayer *pPlayer) = 0; + virtual CBasePlayerItem *GetWeaponPtr() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; // return 0 to MAX_ITEMS_SLOTS, used in hud +public: + CBasePlayer *m_pPlayer; + CBasePlayerItem *m_pNext; + int m_iId; // WEAPON_??? +}; + +// inventory items that +class CBasePlayerWeapon: public CBasePlayerItem { +public: + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + + // generic weapon versions of CBasePlayerItem calls + virtual int AddToPlayer(CBasePlayer *pPlayer) = 0; + virtual int AddDuplicate(CBasePlayerItem *pItem) = 0; + virtual BOOL CanDeploy() = 0; + virtual BOOL IsWeapon() = 0; + virtual void Holster(int skiplocal = 0) = 0; + virtual void UpdateItemInfo() = 0; + virtual void ItemPostFrame() = 0; + virtual int PrimaryAmmoIndex() = 0; + virtual int SecondaryAmmoIndex() = 0; + virtual int UpdateClientData(CBasePlayer *pPlayer) = 0; + virtual CBasePlayerItem *GetWeaponPtr() = 0; + virtual int ExtractAmmo(CBasePlayerWeapon *pWeapon) = 0; + virtual int ExtractClipAmmo(CBasePlayerWeapon *pWeapon) = 0; + virtual int AddWeapon() = 0; + virtual BOOL PlayEmptySound() = 0; + virtual void ResetEmptySound() = 0; + virtual void SendWeaponAnim(int iAnim, int skiplocal = 0) = 0; + virtual BOOL IsUseable() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual void RetireWeapon() = 0; + virtual BOOL ShouldWeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + BOOL IsPistol() { return (m_iId == WEAPON_USP || m_iId == WEAPON_GLOCK18 || m_iId == WEAPON_P228 || m_iId == WEAPON_DEAGLE || m_iId == WEAPON_ELITE || m_iId == WEAPON_FIVESEVEN); } + + int m_iPlayEmptySound; + int m_fFireOnEmpty; + float m_flNextPrimaryAttack; // soonest time ItemPostFrame will call PrimaryAttack + float m_flNextSecondaryAttack; // soonest time ItemPostFrame will call SecondaryAttack + float m_flTimeWeaponIdle; // soonest time ItemPostFrame will call WeaponIdle + int m_iPrimaryAmmoType; // "primary" ammo index into players m_rgAmmo[] + int m_iSecondaryAmmoType; // "secondary" ammo index into players m_rgAmmo[] + int m_iClip; // number of shots left in the primary weapon clip, -1 it not used + int m_iClientClip; // the last version of m_iClip sent to hud dll + int m_iClientWeaponState; // the last version of the weapon state sent to hud dll (is current weapon, is on target) + int m_fInReload; // Are we in the middle of a reload; + int m_fInSpecialReload; // Are we in the middle of a reload for the shotguns + int m_iDefaultAmmo; // how much ammo you get when you pick up this weapon as placed by a level designer. + int m_iShellId; + float m_fMaxSpeed; + bool m_bDelayFire; + int m_iDirection; + bool m_bSecondarySilencerOn; + float m_flAccuracy; + float m_flLastFire; + int m_iShotsFired; + Vector m_vVecAiming; + string_t model_name; + float m_flGlock18Shoot; // time to shoot the remaining bullets of the glock18 burst fire + int m_iGlock18ShotsFired; // used to keep track of the shots fired during the Glock18 burst fire mode. + float m_flFamasShoot; + int m_iFamasShotsFired; + float m_fBurstSpread; + int m_iWeaponState; + float m_flNextReload; + float m_flDecreaseShotsFired; + unsigned short m_usFireGlock18; + unsigned short m_usFireFamas; + + // hle time creep vars + float m_flPrevPrimaryAttack; + float m_flLastFireTime; +}; + +class CBasePlayerAmmo: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual BOOL AddAmmo(CBaseEntity *pOther) = 0; + virtual CBaseEntity *Respawn() = 0; +}; + +class CWeaponBox: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual int Save(CSave &save) = 0; + virtual int Restore(CRestore &restore) = 0; + virtual void SetObjectCollisionBox() = 0; + virtual void Touch(CBaseEntity *pOther) = 0; +public: + CBasePlayerItem *m_rgpPlayerItems[MAX_ITEM_TYPES]; + string_t m_rgiszAmmo[MAX_AMMO_SLOTS]; + int m_rgAmmo[MAX_AMMO_SLOTS]; + int m_cAmmoTypes; + bool m_bIsBomb; +}; + + +const float USP_MAX_SPEED = 250.0f; +const float USP_DAMAGE = 34.0f; +const float USP_DAMAGE_SIL = 30.0f; +const float USP_RANGE_MODIFER = 0.79f; +const float USP_RELOAD_TIME = 2.7f; + +enum usp_e +{ + USP_IDLE, + USP_SHOOT1, + USP_SHOOT2, + USP_SHOOT3, + USP_SHOOT_EMPTY, + USP_RELOAD, + USP_DRAW, + USP_ATTACH_SILENCER, + USP_UNSIL_IDLE, + USP_UNSIL_SHOOT1, + USP_UNSIL_SHOOT2, + USP_UNSIL_SHOOT3, + USP_UNSIL_SHOOT_EMPTY, + USP_UNSIL_RELOAD, + USP_UNSIL_DRAW, + USP_DETACH_SILENCER, +}; + +enum usp_shield_e +{ + USP_SHIELD_IDLE, + USP_SHIELD_SHOOT1, + USP_SHIELD_SHOOT2, + USP_SHIELD_SHOOT_EMPTY, + USP_SHIELD_RELOAD, + USP_SHIELD_DRAW, + USP_SHIELD_UP_IDLE, + USP_SHIELD_UP, + USP_SHIELD_DOWN, +}; + +class CUSP: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float MP5N_MAX_SPEED = 250.0f; +const float MP5N_DAMAGE = 26.0f; +const float MP5N_RANGE_MODIFER = 0.84f; +const float MP5N_RELOAD_TIME = 2.63f; + +enum mp5n_e +{ + MP5N_IDLE1, + MP5N_RELOAD, + MP5N_DRAW, + MP5N_SHOOT1, + MP5N_SHOOT2, + MP5N_SHOOT3, +}; + +class CMP5N: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float SG552_MAX_SPEED = 235.0f; +const float SG552_MAX_SPEED_ZOOM = 200.0f; +const float SG552_DAMAGE = 33.0f; +const float SG552_RANGE_MODIFER = 0.955f; +const float SG552_RELOAD_TIME = 3.0f; + +enum sg552_e +{ + SG552_IDLE1, + SG552_RELOAD, + SG552_DRAW, + SG552_SHOOT1, + SG552_SHOOT2, + SG552_SHOOT3, +}; + +class CSG552: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float AK47_MAX_SPEED = 221.0f; +const float AK47_DAMAGE = 36.0f; +const float AK47_RANGE_MODIFER = 0.98f; +const float AK47_RELOAD_TIME = 2.45f; + +enum ak47_e +{ + AK47_IDLE1, + AK47_RELOAD, + AK47_DRAW, + AK47_SHOOT1, + AK47_SHOOT2, + AK47_SHOOT3, +}; + +class CAK47: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float AUG_MAX_SPEED = 240.0f; +const float AUG_DAMAGE = 32.0f; +const float AUG_RANGE_MODIFER = 0.96f; +const float AUG_RELOAD_TIME = 3.3f; + +enum aug_e +{ + AUG_IDLE1, + AUG_RELOAD, + AUG_DRAW, + AUG_SHOOT1, + AUG_SHOOT2, + AUG_SHOOT3, +}; + +class CAUG: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float AWP_MAX_SPEED = 210.0f; +const float AWP_MAX_SPEED_ZOOM = 150.0f; +const float AWP_DAMAGE = 115.0f; +const float AWP_RANGE_MODIFER = 0.99f; +const float AWP_RELOAD_TIME = 2.5f; + +enum awp_e +{ + AWP_IDLE, + AWP_SHOOT, + AWP_SHOOT2, + AWP_SHOOT3, + AWP_RELOAD, + AWP_DRAW, +}; + +class CAWP: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +// for usermsg BombDrop +#define BOMB_FLAG_DROPPED 0 // if the bomb was dropped due to voluntary dropping or death/disconnect +#define BOMB_FLAG_PLANTED 1 // if the bomb has been planted will also trigger the round timer to hide will also show where the dropped bomb on the Terrorist team's radar. + +const float C4_MAX_AMMO = 1.0f; +const float C4_MAX_SPEED = 250.0f; +const float C4_ARMING_ON_TIME = 3.0f; + +enum c4_e +{ + C4_IDLE1, + C4_DRAW, + C4_DROP, + C4_ARM, +}; + +class CC4: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; + virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal) = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + bool m_bStartedArming; + bool m_bBombPlacedAnimation; + float m_fArmedTime; + bool m_bHasShield; +}; + + +const float DEAGLE_MAX_SPEED = 250.0f; +const float DEAGLE_DAMAGE = 54.0f; +const float DEAGLE_RANGE_MODIFER = 0.81f; +const float DEAGLE_RELOAD_TIME = 2.2f; + +enum deagle_e +{ + DEAGLE_IDLE1, + DEAGLE_SHOOT1, + DEAGLE_SHOOT2, + DEAGLE_SHOOT_EMPTY, + DEAGLE_RELOAD, + DEAGLE_DRAW, +}; + +class CDEAGLE: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float FLASHBANG_MAX_SPEED = 250.0f; +const float FLASHBANG_MAX_SPEED_SHIELD = 180.0f; + +enum flashbang_e +{ + FLASHBANG_IDLE, + FLASHBANG_PULLPIN, + FLASHBANG_THROW, + FLASHBANG_DRAW, +}; + +class CFlashbang: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL CanDeploy() = 0; + virtual BOOL CanDrop() = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal) = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +}; + + +const float G3SG1_MAX_SPEED = 210.0f; +const float G3SG1_MAX_SPEED_ZOOM = 150.0f; +const float G3SG1_DAMAGE = 80.0f; +const float G3SG1_RANGE_MODIFER = 0.98f; +const float G3SG1_RELOAD_TIME = 3.5f; + +enum g3sg1_e +{ + G3SG1_IDLE, + G3SG1_SHOOT, + G3SG1_SHOOT2, + G3SG1_RELOAD, + G3SG1_DRAW, +}; + +class CG3SG1: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float GLOCK18_MAX_SPEED = 250.0f; +const float GLOCK18_DAMAGE = 25.0f; +const float GLOCK18_RANGE_MODIFER = 0.75f; +const float GLOCK18_RELOAD_TIME = 2.2f; + +enum glock18_e +{ + GLOCK18_IDLE1, + GLOCK18_IDLE2, + GLOCK18_IDLE3, + GLOCK18_SHOOT, + GLOCK18_SHOOT2, + GLOCK18_SHOOT3, + GLOCK18_SHOOT_EMPTY, + GLOCK18_RELOAD, + GLOCK18_DRAW, + GLOCK18_HOLSTER, + GLOCK18_ADD_SILENCER, + GLOCK18_DRAW2, + GLOCK18_RELOAD2, +}; + +enum glock18_shield_e +{ + GLOCK18_SHIELD_IDLE1, + GLOCK18_SHIELD_SHOOT, + GLOCK18_SHIELD_SHOOT2, + GLOCK18_SHIELD_SHOOT_EMPTY, + GLOCK18_SHIELD_RELOAD, + GLOCK18_SHIELD_DRAW, + GLOCK18_SHIELD_IDLE, + GLOCK18_SHIELD_UP, + GLOCK18_SHIELD_DOWN, +}; + +class CGLOCK18: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + bool m_bBurstFire; +}; + + +const float HEGRENADE_MAX_SPEED = 250.0f; +const float HEGRENADE_MAX_SPEED_SHIELD = 180.0f; + +enum hegrenade_e +{ + HEGRENADE_IDLE, + HEGRENADE_PULLPIN, + HEGRENADE_THROW, + HEGRENADE_DRAW, +}; + +class CHEGrenade: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL CanDeploy() = 0; + virtual BOOL CanDrop() = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal) = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + unsigned short m_usCreate; +}; + + +const float KNIFE_BODYHIT_VOLUME = 128.0f; +const float KNIFE_WALLHIT_VOLUME = 512.0f; +const float KNIFE_MAX_SPEED = 250.0f; +const float KNIFE_MAX_SPEED_SHIELD = 180.0f; + +enum knife_e +{ + KNIFE_IDLE, + KNIFE_ATTACK1HIT, + KNIFE_ATTACK2HIT, + KNIFE_DRAW, + KNIFE_STABHIT, + KNIFE_STABMISS, + KNIFE_MIDATTACK1HIT, + KNIFE_MIDATTACK2HIT, +}; + +enum knife_shield_e +{ + KNIFE_SHIELD_IDLE, + KNIFE_SHIELD_SLASH, + KNIFE_SHIELD_ATTACKHIT, + KNIFE_SHIELD_DRAW, + KNIFE_SHIELD_UPIDLE, + KNIFE_SHIELD_UP, + KNIFE_SHIELD_DOWN, +}; + +class CKnife: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL CanDrop() = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal) = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual BOOL UseDecrement() = 0; + virtual void WeaponIdle() = 0; +public: + TraceResult m_trHit; + unsigned short m_usKnife; +}; + + +const float M249_MAX_SPEED = 220.0f; +const float M249_DAMAGE = 32.0f; +const float M249_RANGE_MODIFER = 0.97f; +const float M249_RELOAD_TIME = 4.7f; + +enum m249_e +{ + M249_IDLE1, + M249_SHOOT1, + M249_SHOOT2, + M249_RELOAD, + M249_DRAW, +}; + +class CM249: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float M3_MAX_SPEED = 230.0f; +const Vector M3_CONE_VECTOR = Vector(0.0675, 0.0675, 0.0); // special shotgun spreads + +enum m3_e +{ + M3_IDLE, + M3_FIRE1, + M3_FIRE2, + M3_RELOAD, + M3_PUMP, + M3_START_RELOAD, + M3_DRAW, + M3_HOLSTER, +}; + +class CM3: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + float m_flPumpTime; + unsigned short m_usFire; +}; + + +const float M4A1_MAX_SPEED = 230.0f; +const float M4A1_DAMAGE = 32.0f; +const float M4A1_DAMAGE_SIL = 33.0f; +const float M4A1_RANGE_MODIFER = 0.97f; +const float M4A1_RANGE_MODIFER_SIL = 0.95f; +const float M4A1_RELOAD_TIME = 3.05f; + +enum m4a1_e +{ + M4A1_IDLE, + M4A1_SHOOT1, + M4A1_SHOOT2, + M4A1_SHOOT3, + M4A1_RELOAD, + M4A1_DRAW, + M4A1_ATTACH_SILENCER, + M4A1_UNSIL_IDLE, + M4A1_UNSIL_SHOOT1, + M4A1_UNSIL_SHOOT2, + M4A1_UNSIL_SHOOT3, + M4A1_UNSIL_RELOAD, + M4A1_UNSIL_DRAW, + M4A1_DETACH_SILENCER, +}; + +class CM4A1: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float MAC10_MAX_SPEED = 250.0f; +const float MAC10_DAMAGE = 29.0f; +const float MAC10_RANGE_MODIFER = 0.82f; +const float MAC10_RELOAD_TIME = 3.15f; + +enum mac10_e +{ + MAC10_IDLE1, + MAC10_RELOAD, + MAC10_DRAW, + MAC10_SHOOT1, + MAC10_SHOOT2, + MAC10_SHOOT3, +}; + +class CMAC10: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float P228_MAX_SPEED = 250.0f; +const float P228_DAMAGE = 32.0f; +const float P228_RANGE_MODIFER = 0.8f; +const float P228_RELOAD_TIME = 2.7f; + +enum p228_e +{ + P228_IDLE, + P228_SHOOT1, + P228_SHOOT2, + P228_SHOOT3, + P228_SHOOT_EMPTY, + P228_RELOAD, + P228_DRAW, +}; + +enum p228_shield_e +{ + P228_SHIELD_IDLE, + P228_SHIELD_SHOOT1, + P228_SHIELD_SHOOT2, + P228_SHIELD_SHOOT_EMPTY, + P228_SHIELD_RELOAD, + P228_SHIELD_DRAW, + P228_SHIELD_IDLE_UP, + P228_SHIELD_UP, + P228_SHIELD_DOWN, +}; + +class CP228: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float P90_MAX_SPEED = 245.0f; +const float P90_DAMAGE = 21.0f; +const float P90_RANGE_MODIFER = 0.885f; +const float P90_RELOAD_TIME = 3.4f; + +enum p90_e +{ + P90_IDLE1, + P90_RELOAD, + P90_DRAW, + P90_SHOOT1, + P90_SHOOT2, + P90_SHOOT3, +}; + +class CP90: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float SCOUT_MAX_SPEED = 260.0f; +const float SCOUT_MAX_SPEED_ZOOM = 220.0f; +const float SCOUT_DAMAGE = 75.0f; +const float SCOUT_RANGE_MODIFER = 0.98f; +const float SCOUT_RELOAD_TIME = 2.0f; + +enum scout_e +{ + SCOUT_IDLE, + SCOUT_SHOOT, + SCOUT_SHOOT2, + SCOUT_RELOAD, + SCOUT_DRAW, +}; + +class CSCOUT: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float SMOKEGRENADE_MAX_SPEED = 250.0f; +const float SMOKEGRENADE_MAX_SPEED_SHIELD = 180.0f; + +enum smokegrenade_e +{ + SMOKEGRENADE_IDLE, + SMOKEGRENADE_PINPULL, + SMOKEGRENADE_THROW, + SMOKEGRENADE_DRAW, +}; + +class CSmokeGrenade: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL CanDeploy() = 0; + virtual BOOL CanDrop() = 0; + virtual BOOL Deploy() = 0; + virtual void Holster(int skiplocal) = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + unsigned short m_usCreate; +}; + + +const float TMP_MAX_SPEED = 250.0f; +const float TMP_DAMAGE = 20.0f; +const float TMP_RANGE_MODIFER = 0.85f; +const float TMP_RELOAD_TIME = 2.12f; + +enum tmp_e +{ + TMP_IDLE1, + TMP_RELOAD, + TMP_DRAW, + TMP_SHOOT1, + TMP_SHOOT2, + TMP_SHOOT3, +}; + +class CTMP: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float XM1014_MAX_SPEED = 240.0f; +const Vector XM1014_CONE_VECTOR = Vector(0.0725, 0.0725, 0.0); // special shotgun spreads + +enum xm1014_e +{ + XM1014_IDLE, + XM1014_FIRE1, + XM1014_FIRE2, + XM1014_RELOAD, + XM1014_PUMP, + XM1014_START_RELOAD, + XM1014_DRAW, +}; + +class CXM1014: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + float m_flPumpTime; + unsigned short m_usFire; +}; + + +const float ELITE_MAX_SPEED = 250.0f; +const float ELITE_RELOAD_TIME = 4.5f; +const float ELITE_DAMAGE = 36.0f; +const float ELITE_RANGE_MODIFER = 0.75f; + +enum elite_e +{ + ELITE_IDLE, + ELITE_IDLE_LEFTEMPTY, + ELITE_SHOOTLEFT1, + ELITE_SHOOTLEFT2, + ELITE_SHOOTLEFT3, + ELITE_SHOOTLEFT4, + ELITE_SHOOTLEFT5, + ELITE_SHOOTLEFTLAST, + ELITE_SHOOTRIGHT1, + ELITE_SHOOTRIGHT2, + ELITE_SHOOTRIGHT3, + ELITE_SHOOTRIGHT4, + ELITE_SHOOTRIGHT5, + ELITE_SHOOTRIGHTLAST, + ELITE_RELOAD, + ELITE_DRAW, +}; + +class CELITE: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + unsigned short m_usFire_LEFT; + unsigned short m_usFire_RIGHT; +}; + + +const float FIVESEVEN_MAX_SPEED = 250.0f; +const float FIVESEVEN_DAMAGE = 20.0f; +const float FIVESEVEN_RANGE_MODIFER = 0.885f; +const float FIVESEVEN_RELOAD_TIME = 2.7f; + +enum fiveseven_e +{ + FIVESEVEN_IDLE, + FIVESEVEN_SHOOT1, + FIVESEVEN_SHOOT2, + FIVESEVEN_SHOOT_EMPTY, + FIVESEVEN_RELOAD, + FIVESEVEN_DRAW, +}; + +class CFiveSeven: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; + virtual BOOL IsPistol() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float UMP45_MAX_SPEED = 250.0f; +const float UMP45_DAMAGE = 30.0f; +const float UMP45_RANGE_MODIFER = 0.82f; +const float UMP45_RELOAD_TIME = 3.5f; + +enum ump45_e +{ + UMP45_IDLE1, + UMP45_RELOAD, + UMP45_DRAW, + UMP45_SHOOT1, + UMP45_SHOOT2, + UMP45_SHOOT3, +}; + +class CUMP45: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float SG550_MAX_SPEED = 210.0f; +const float SG550_MAX_SPEED_ZOOM = 150.0f; +const float SG550_DAMAGE = 70.0f; +const float SG550_RANGE_MODIFER = 0.98f; +const float SG550_RELOAD_TIME = 3.35f; + +enum sg550_e +{ + SG550_IDLE, + SG550_SHOOT, + SG550_SHOOT2, + SG550_RELOAD, + SG550_DRAW, +}; + +class CSG550: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + unsigned short m_usFire; +}; + + +const float GALIL_MAX_SPEED = 240.0f; +const float GALIL_DAMAGE = 30.0f; +const float GALIL_RANGE_MODIFER = 0.98f; +const float GALIL_RELOAD_TIME = 2.45f; + +enum galil_e +{ + GALIL_IDLE1, + GALIL_RELOAD, + GALIL_DRAW, + GALIL_SHOOT1, + GALIL_SHOOT2, + GALIL_SHOOT3, +}; + +class CGalil: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; + unsigned short m_usFire; +}; + + +const float FAMAS_MAX_SPEED = 240.0f; +const float FAMAS_RELOAD_TIME = 3.3f; +const float FAMAS_DAMAGE = 30.0f; +const float FAMAS_DAMAGE_BURST = 34.0f; +const float FAMAS_RANGE_MODIFER = 0.96f; + +enum famas_e +{ + FAMAS_IDLE1, + FAMAS_RELOAD, + FAMAS_DRAW, + FAMAS_SHOOT1, + FAMAS_SHOOT2, + FAMAS_SHOOT3, +}; + +class CFamas: public CBasePlayerWeapon { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual int GetItemInfo(ItemInfo *p) = 0; + virtual BOOL Deploy() = 0; + virtual float GetMaxSpeed() = 0; + virtual int iItemSlot() = 0; + virtual void PrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + virtual void WeaponIdle() = 0; + virtual BOOL UseDecrement() = 0; +public: + int m_iShell; + int m_iShellOn; +}; diff --git a/dep/hlsdk/dlls/weapontype.h b/dep/hlsdk/dlls/weapontype.h new file mode 100644 index 0000000..a791cac --- /dev/null +++ b/dep/hlsdk/dlls/weapontype.h @@ -0,0 +1,418 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +enum WeaponIdType +{ + WEAPON_NONE, + WEAPON_P228, + WEAPON_GLOCK, + WEAPON_SCOUT, + WEAPON_HEGRENADE, + WEAPON_XM1014, + WEAPON_C4, + WEAPON_MAC10, + WEAPON_AUG, + WEAPON_SMOKEGRENADE, + WEAPON_ELITE, + WEAPON_FIVESEVEN, + WEAPON_UMP45, + WEAPON_SG550, + WEAPON_GALIL, + WEAPON_FAMAS, + WEAPON_USP, + WEAPON_GLOCK18, + WEAPON_AWP, + WEAPON_MP5N, + WEAPON_M249, + WEAPON_M3, + WEAPON_M4A1, + WEAPON_TMP, + WEAPON_G3SG1, + WEAPON_FLASHBANG, + WEAPON_DEAGLE, + WEAPON_SG552, + WEAPON_AK47, + WEAPON_KNIFE, + WEAPON_P90, + WEAPON_SHIELDGUN = 99 +}; + +enum AutoBuyClassType +{ + AUTOBUYCLASS_NONE = 0, + AUTOBUYCLASS_PRIMARY = BIT(0), + AUTOBUYCLASS_SECONDARY = BIT(1), + AUTOBUYCLASS_AMMO = BIT(2), + AUTOBUYCLASS_ARMOR = BIT(3), + AUTOBUYCLASS_DEFUSER = BIT(4), + AUTOBUYCLASS_PISTOL = BIT(5), + AUTOBUYCLASS_SMG = BIT(6), + AUTOBUYCLASS_RIFLE = BIT(7), + AUTOBUYCLASS_SNIPERRIFLE = BIT(8), + AUTOBUYCLASS_SHOTGUN = BIT(9), + AUTOBUYCLASS_MACHINEGUN = BIT(10), + AUTOBUYCLASS_GRENADE = BIT(11), + AUTOBUYCLASS_NIGHTVISION = BIT(12), + AUTOBUYCLASS_SHIELD = BIT(13), +}; + +enum AmmoCostType +{ + AMMO_338MAG_PRICE = 125, + AMMO_357SIG_PRICE = 50, + AMMO_45ACP_PRICE = 25, + AMMO_50AE_PRICE = 40, + AMMO_556MM_PRICE = 60, + AMMO_57MM_PRICE = 50, + AMMO_762MM_PRICE = 80, + AMMO_9MM_PRICE = 20, + AMMO_BUCKSHOT_PRICE = 65, +}; + +enum WeaponCostType +{ + AK47_PRICE = 2500, + AWP_PRICE = 4750, + DEAGLE_PRICE = 650, + G3SG1_PRICE = 5000, + SG550_PRICE = 4200, + GLOCK18_PRICE = 400, + M249_PRICE = 5750, + M3_PRICE = 1700, + M4A1_PRICE = 3100, + AUG_PRICE = 3500, + MP5NAVY_PRICE = 1500, + P228_PRICE = 600, + P90_PRICE = 2350, + UMP45_PRICE = 1700, + MAC10_PRICE = 1400, + SCOUT_PRICE = 2750, + SG552_PRICE = 3500, + TMP_PRICE = 1250, + USP_PRICE = 500, + ELITE_PRICE = 800, + FIVESEVEN_PRICE = 750, + XM1014_PRICE = 3000, + GALIL_PRICE = 2000, + FAMAS_PRICE = 2250, + SHIELDGUN_PRICE = 2200, +}; + +enum WeaponState +{ + WPNSTATE_USP_SILENCED = BIT(0), + WPNSTATE_GLOCK18_BURST_MODE = BIT(1), + WPNSTATE_M4A1_SILENCED = BIT(2), + WPNSTATE_ELITE_LEFT = BIT(3), + WPNSTATE_FAMAS_BURST_MODE = BIT(4), + WPNSTATE_SHIELD_DRAWN = BIT(5), +}; + +// custom enum +// the default amount of ammo that comes with each gun when it spawns +enum ClipGiveDefault +{ + P228_DEFAULT_GIVE = 13, + GLOCK18_DEFAULT_GIVE = 20, + SCOUT_DEFAULT_GIVE = 10, + HEGRENADE_DEFAULT_GIVE = 1, + XM1014_DEFAULT_GIVE = 7, + C4_DEFAULT_GIVE = 1, + MAC10_DEFAULT_GIVE = 30, + AUG_DEFAULT_GIVE = 30, + SMOKEGRENADE_DEFAULT_GIVE = 1, + ELITE_DEFAULT_GIVE = 30, + FIVESEVEN_DEFAULT_GIVE = 20, + UMP45_DEFAULT_GIVE = 25, + SG550_DEFAULT_GIVE = 30, + GALIL_DEFAULT_GIVE = 35, + FAMAS_DEFAULT_GIVE = 25, + USP_DEFAULT_GIVE = 12, + AWP_DEFAULT_GIVE = 10, + MP5NAVY_DEFAULT_GIVE = 30, + M249_DEFAULT_GIVE = 100, + M3_DEFAULT_GIVE = 8, + M4A1_DEFAULT_GIVE = 30, + TMP_DEFAULT_GIVE = 30, + G3SG1_DEFAULT_GIVE = 20, + FLASHBANG_DEFAULT_GIVE = 1, + DEAGLE_DEFAULT_GIVE = 7, + SG552_DEFAULT_GIVE = 30, + AK47_DEFAULT_GIVE = 30, + //KNIFE_DEFAULT_GIVE = 1, + P90_DEFAULT_GIVE = 50, +}; + +enum ClipSizeType +{ + P228_MAX_CLIP = 13, + GLOCK18_MAX_CLIP = 20, + SCOUT_MAX_CLIP = 10, + XM1014_MAX_CLIP = 7, + MAC10_MAX_CLIP = 30, + AUG_MAX_CLIP = 30, + ELITE_MAX_CLIP = 30, + FIVESEVEN_MAX_CLIP = 20, + UMP45_MAX_CLIP = 25, + SG550_MAX_CLIP = 30, + GALIL_MAX_CLIP = 35, + FAMAS_MAX_CLIP = 25, + USP_MAX_CLIP = 12, + AWP_MAX_CLIP = 10, + MP5N_MAX_CLIP = 30, + M249_MAX_CLIP = 100, + M3_MAX_CLIP = 8, + M4A1_MAX_CLIP = 30, + TMP_MAX_CLIP = 30, + G3SG1_MAX_CLIP = 20, + DEAGLE_MAX_CLIP = 7, + SG552_MAX_CLIP = 30, + AK47_MAX_CLIP = 30, + P90_MAX_CLIP = 50, +}; + +enum WeightWeapon +{ + P228_WEIGHT = 5, + GLOCK18_WEIGHT = 5, + SCOUT_WEIGHT = 30, + HEGRENADE_WEIGHT = 2, + XM1014_WEIGHT = 20, + C4_WEIGHT = 3, + MAC10_WEIGHT = 25, + AUG_WEIGHT = 25, + SMOKEGRENADE_WEIGHT = 1, + ELITE_WEIGHT = 5, + FIVESEVEN_WEIGHT = 5, + UMP45_WEIGHT = 25, + SG550_WEIGHT = 20, + GALIL_WEIGHT = 25, + FAMAS_WEIGHT = 75, + USP_WEIGHT = 5, + AWP_WEIGHT = 30, + MP5NAVY_WEIGHT = 25, + M249_WEIGHT = 25, + M3_WEIGHT = 20, + M4A1_WEIGHT = 25, + TMP_WEIGHT = 25, + G3SG1_WEIGHT = 20, + FLASHBANG_WEIGHT = 1, + DEAGLE_WEIGHT = 7, + SG552_WEIGHT = 25, + AK47_WEIGHT = 25, + P90_WEIGHT = 26, + KNIFE_WEIGHT = 0, +}; + +enum MaxAmmoType +{ + MAX_AMMO_BUCKSHOT = 32, + MAX_AMMO_9MM = 120, + MAX_AMMO_556NATO = 90, + MAX_AMMO_556NATOBOX = 200, + MAX_AMMO_762NATO = 90, + MAX_AMMO_45ACP = 100, + MAX_AMMO_50AE = 35, + MAX_AMMO_338MAGNUM = 30, + MAX_AMMO_57MM = 100, + MAX_AMMO_357SIG = 52, + + // custom + MAX_AMMO_SMOKEGRENADE = 1, + MAX_AMMO_HEGRENADE = 1, + MAX_AMMO_FLASHBANG = 2, +}; + +enum AmmoType +{ + AMMO_NONE, + AMMO_338MAGNUM, + AMMO_762NATO, + AMMO_556NATOBOX, + AMMO_556NATO, + AMMO_BUCKSHOT, + AMMO_45ACP, + AMMO_57MM, + AMMO_50AE, + AMMO_357SIG, + AMMO_9MM, + AMMO_FLASHBANG, + AMMO_HEGRENADE, + AMMO_SMOKEGRENADE, + AMMO_C4, + + AMMO_MAX_TYPES +}; + +enum WeaponClassType +{ + WEAPONCLASS_NONE, + WEAPONCLASS_KNIFE, + WEAPONCLASS_PISTOL, + WEAPONCLASS_GRENADE, + WEAPONCLASS_SUBMACHINEGUN, + WEAPONCLASS_SHOTGUN, + WEAPONCLASS_MACHINEGUN, + WEAPONCLASS_RIFLE, + WEAPONCLASS_SNIPERRIFLE, + WEAPONCLASS_MAX, +}; + +enum AmmoBuyAmount +{ + AMMO_338MAG_BUY = 10, + AMMO_357SIG_BUY = 13, + AMMO_45ACP_BUY = 12, + AMMO_50AE_BUY = 7, + AMMO_556NATO_BUY = 30, + AMMO_556NATOBOX_BUY = 30, + AMMO_57MM_BUY = 50, + AMMO_762NATO_BUY = 30, + AMMO_9MM_BUY = 30, + AMMO_BUCKSHOT_BUY = 8, +}; + +enum ItemCostType +{ + ASSAULTSUIT_PRICE = 1000, + FLASHBANG_PRICE = 200, + HEGRENADE_PRICE = 300, + SMOKEGRENADE_PRICE = 300, + KEVLAR_PRICE = 650, + HELMET_PRICE = 350, + NVG_PRICE = 1250, + DEFUSEKIT_PRICE = 200, +}; + +enum shieldgun_e +{ + SHIELDGUN_IDLE, + SHIELDGUN_SHOOT1, + SHIELDGUN_SHOOT2, + SHIELDGUN_SHOOT_EMPTY, + SHIELDGUN_RELOAD, + SHIELDGUN_DRAW, + SHIELDGUN_DRAWN_IDLE, + SHIELDGUN_UP, + SHIELDGUN_DOWN, +}; + +// custom +enum shieldgren_e +{ + SHIELDREN_IDLE = 4, + SHIELDREN_UP, + SHIELDREN_DOWN +}; + +enum InventorySlotType +{ + NONE_SLOT, + PRIMARY_WEAPON_SLOT, + PISTOL_SLOT, + KNIFE_SLOT, + GRENADE_SLOT, + C4_SLOT, +}; + +enum Bullet +{ + BULLET_NONE, + BULLET_PLAYER_9MM, + BULLET_PLAYER_MP5, + BULLET_PLAYER_357, + BULLET_PLAYER_BUCKSHOT, + BULLET_PLAYER_CROWBAR, + BULLET_MONSTER_9MM, + BULLET_MONSTER_MP5, + BULLET_MONSTER_12MM, + BULLET_PLAYER_45ACP, + BULLET_PLAYER_338MAG, + BULLET_PLAYER_762MM, + BULLET_PLAYER_556MM, + BULLET_PLAYER_50AE, + BULLET_PLAYER_57MM, + BULLET_PLAYER_357SIG, +}; + +struct WeaponStruct +{ + int m_type; + int m_price; + int m_side; + int m_slot; + int m_ammoPrice; +}; + +struct AutoBuyInfoStruct +{ + int m_class; + char *m_command; + char *m_classname; +}; + +struct WeaponAliasInfo +{ + char *alias; + WeaponIdType id; +}; + +struct WeaponBuyAliasInfo +{ + char *alias; + WeaponIdType id; + char *failName; +}; + +struct WeaponClassAliasInfo +{ + char *alias; + WeaponClassType id; +}; + +struct WeaponInfoStruct +{ + int id; + int cost; + int clipCost; + int buyClipSize; + int gunClipSize; + int maxRounds; + int ammoType; + char *entityName; + const char *ammoName; +}; + +struct WeaponSlotInfo +{ + WeaponIdType id; + InventorySlotType slot; + const char *weaponName; +}; diff --git a/dep/hlsdk/dlls/world.h b/dep/hlsdk/dlls/world.h new file mode 100644 index 0000000..d1fb34d --- /dev/null +++ b/dep/hlsdk/dlls/world.h @@ -0,0 +1,50 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define SF_WORLD_DARK BIT(0) // Fade from black at startup +#define SF_WORLD_TITLE BIT(1) // Display game title at startup +#define SF_WORLD_FORCETEAM BIT(2) // Force teams + +// This spawns first when each level begins. +class CWorld: public CBaseEntity { +public: + virtual void Spawn() = 0; + virtual void Precache() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +}; + +#define SF_DECAL_NOTINDEATHMATCH BIT(11) + +class CDecal: public CBaseEntity +{ +public: + virtual void Spawn() = 0; + virtual void KeyValue(KeyValueData *pkvd) = 0; +}; diff --git a/dep/hlsdk/engine/APIProxy.h b/dep/hlsdk/engine/APIProxy.h new file mode 100644 index 0000000..88333db --- /dev/null +++ b/dep/hlsdk/engine/APIProxy.h @@ -0,0 +1,942 @@ +#pragma once + +#include "netadr.h" +#include "Sequence.h" + + +#ifndef _WIN32 +#include "enums.h" +#endif + +const int MAX_ALIAS_NAME = 32; + +typedef struct cmdalias_s +{ + struct cmdalias_s *next; + char name[MAX_ALIAS_NAME]; + char *value; +} cmdalias_t; + + +// ******************************************************** +// Functions exported by the client .dll +// ******************************************************** + +// Function type declarations for client exports +typedef int (*INITIALIZE_FUNC) (struct cl_enginefuncs_s*, int); +typedef void (*HUD_INIT_FUNC) (void); +typedef int (*HUD_VIDINIT_FUNC) (void); +typedef int (*HUD_REDRAW_FUNC) (float, int); +typedef int (*HUD_UPDATECLIENTDATA_FUNC) (struct client_data_s*, float); +typedef void (*HUD_RESET_FUNC) (void); +typedef void (*HUD_CLIENTMOVE_FUNC) (struct playermove_s *ppmove, qboolean server); +typedef void (*HUD_CLIENTMOVEINIT_FUNC) (struct playermove_s *ppmove); +typedef char (*HUD_TEXTURETYPE_FUNC) (char *name); +typedef void (*HUD_IN_ACTIVATEMOUSE_FUNC) (void); +typedef void (*HUD_IN_DEACTIVATEMOUSE_FUNC) (void); +typedef void (*HUD_IN_MOUSEEVENT_FUNC) (int mstate); +typedef void (*HUD_IN_CLEARSTATES_FUNC) (void); +typedef void (*HUD_IN_ACCUMULATE_FUNC) (void); +typedef void (*HUD_CL_CREATEMOVE_FUNC) (float frametime, struct usercmd_s *cmd, int active); +typedef int (*HUD_CL_ISTHIRDPERSON_FUNC) (void); +typedef void (*HUD_CL_GETCAMERAOFFSETS_FUNC) (float *ofs); +typedef struct kbutton_s * (*HUD_KB_FIND_FUNC) (const char *name); +typedef void (*HUD_CAMTHINK_FUNC) (void); +typedef void (*HUD_CALCREF_FUNC) (struct ref_params_s *pparams); +typedef int (*HUD_ADDENTITY_FUNC) (int type, struct cl_entity_s *ent, const char *modelname); +typedef void (*HUD_CREATEENTITIES_FUNC) (void); +typedef void (*HUD_DRAWNORMALTRIS_FUNC) (void); +typedef void (*HUD_DRAWTRANSTRIS_FUNC) (void); +typedef void (*HUD_STUDIOEVENT_FUNC) (const struct mstudioevent_s *event, const struct cl_entity_s *entity); +typedef void (*HUD_POSTRUNCMD_FUNC) (struct local_state_s *from, struct local_state_s *to, struct usercmd_s *cmd, int runfuncs, double time, unsigned int random_seed); +typedef void (*HUD_SHUTDOWN_FUNC) (void); +typedef void (*HUD_TXFERLOCALOVERRIDES_FUNC) (struct entity_state_s *state, const struct clientdata_s *client); +typedef void (*HUD_PROCESSPLAYERSTATE_FUNC) (struct entity_state_s *dst, struct entity_state_s *src); +typedef void (*HUD_TXFERPREDICTIONDATA_FUNC) (struct entity_state_s *ps, const struct entity_state_s *pps, struct clientdata_s *pcd, const struct clientdata_s *ppcd, struct weapon_data_s *wd, const struct weapon_data_s *pwd); +typedef void (*HUD_DEMOREAD_FUNC) (int size, unsigned char *buffer); +typedef int (*HUD_CONNECTIONLESS_FUNC) (const struct netadr_s *net_from_, const char *args, char *response_buffer, int *response_buffer_size); +typedef int (*HUD_GETHULLBOUNDS_FUNC) (int hullnumber, float *mins, float *maxs); +typedef void (*HUD_FRAME_FUNC) (double); +typedef int (*HUD_KEY_EVENT_FUNC) (int eventcode, int keynum, const char *pszCurrentBinding); +typedef void (*HUD_TEMPENTUPDATE_FUNC) (double frametime, double client_time, double cl_gravity, struct tempent_s **ppTempEntFree, struct tempent_s **ppTempEntActive, int(*Callback_AddVisibleEntity)(struct cl_entity_s *pEntity), void(*Callback_TempEntPlaySound)(struct tempent_s *pTemp, float damp)); +typedef struct cl_entity_s *(*HUD_GETUSERENTITY_FUNC) (int index); +typedef void (*HUD_VOICESTATUS_FUNC) (int entindex, qboolean bTalking); +typedef void (*HUD_DIRECTORMESSAGE_FUNC) (int iSize, void *pbuf); +typedef int (*HUD_STUDIO_INTERFACE_FUNC) (int version, struct r_studio_interface_s **ppinterface, struct engine_studio_api_s *pstudio); +typedef void (*HUD_CHATINPUTPOSITION_FUNC) (int *x, int *y); +typedef int (*HUD_GETPLAYERTEAM) (int iplayer); +typedef void * (*CLIENTFACTORY) (); // this should be CreateInterfaceFn but that means including interface.h + // which is a C++ file and some of the client files a C only... + // so we return a void * which we then do a typecast on later. + + +// Pointers to the exported client functions themselves +typedef struct +{ + INITIALIZE_FUNC pInitFunc; + HUD_INIT_FUNC pHudInitFunc; + HUD_VIDINIT_FUNC pHudVidInitFunc; + HUD_REDRAW_FUNC pHudRedrawFunc; + HUD_UPDATECLIENTDATA_FUNC pHudUpdateClientDataFunc; + HUD_RESET_FUNC pHudResetFunc; + HUD_CLIENTMOVE_FUNC pClientMove; + HUD_CLIENTMOVEINIT_FUNC pClientMoveInit; + HUD_TEXTURETYPE_FUNC pClientTextureType; + HUD_IN_ACTIVATEMOUSE_FUNC pIN_ActivateMouse; + HUD_IN_DEACTIVATEMOUSE_FUNC pIN_DeactivateMouse; + HUD_IN_MOUSEEVENT_FUNC pIN_MouseEvent; + HUD_IN_CLEARSTATES_FUNC pIN_ClearStates; + HUD_IN_ACCUMULATE_FUNC pIN_Accumulate; + HUD_CL_CREATEMOVE_FUNC pCL_CreateMove; + HUD_CL_ISTHIRDPERSON_FUNC pCL_IsThirdPerson; + HUD_CL_GETCAMERAOFFSETS_FUNC pCL_GetCameraOffsets; + HUD_KB_FIND_FUNC pFindKey; + HUD_CAMTHINK_FUNC pCamThink; + HUD_CALCREF_FUNC pCalcRefdef; + HUD_ADDENTITY_FUNC pAddEntity; + HUD_CREATEENTITIES_FUNC pCreateEntities; + HUD_DRAWNORMALTRIS_FUNC pDrawNormalTriangles; + HUD_DRAWTRANSTRIS_FUNC pDrawTransparentTriangles; + HUD_STUDIOEVENT_FUNC pStudioEvent; + HUD_POSTRUNCMD_FUNC pPostRunCmd; + HUD_SHUTDOWN_FUNC pShutdown; + HUD_TXFERLOCALOVERRIDES_FUNC pTxferLocalOverrides; + HUD_PROCESSPLAYERSTATE_FUNC pProcessPlayerState; + HUD_TXFERPREDICTIONDATA_FUNC pTxferPredictionData; + HUD_DEMOREAD_FUNC pReadDemoBuffer; + HUD_CONNECTIONLESS_FUNC pConnectionlessPacket; + HUD_GETHULLBOUNDS_FUNC pGetHullBounds; + HUD_FRAME_FUNC pHudFrame; + HUD_KEY_EVENT_FUNC pKeyEvent; + HUD_TEMPENTUPDATE_FUNC pTempEntUpdate; + HUD_GETUSERENTITY_FUNC pGetUserEntity; + HUD_VOICESTATUS_FUNC pVoiceStatus; // Possibly null on old client dlls. + HUD_DIRECTORMESSAGE_FUNC pDirectorMessage; // Possibly null on old client dlls. + HUD_STUDIO_INTERFACE_FUNC pStudioInterface; // Not used by all clients + HUD_CHATINPUTPOSITION_FUNC pChatInputPosition; // Not used by all clients + HUD_GETPLAYERTEAM pGetPlayerTeam; // Not used by all clients + CLIENTFACTORY pClientFactory; +} cldll_func_t; + +// Function type declarations for client destination functions +typedef void(*DST_INITIALIZE_FUNC) (struct cl_enginefuncs_s**, int *); +typedef void(*DST_HUD_INIT_FUNC) (void); +typedef void(*DST_HUD_VIDINIT_FUNC) (void); +typedef void(*DST_HUD_REDRAW_FUNC) (float*, int*); +typedef void(*DST_HUD_UPDATECLIENTDATA_FUNC) (struct client_data_s**, float*); +typedef void(*DST_HUD_RESET_FUNC) (void); +typedef void(*DST_HUD_CLIENTMOVE_FUNC) (struct playermove_s **, qboolean *); +typedef void(*DST_HUD_CLIENTMOVEINIT_FUNC) (struct playermove_s **); +typedef void(*DST_HUD_TEXTURETYPE_FUNC) (char **); +typedef void(*DST_HUD_IN_ACTIVATEMOUSE_FUNC) (void); +typedef void(*DST_HUD_IN_DEACTIVATEMOUSE_FUNC) (void); +typedef void(*DST_HUD_IN_MOUSEEVENT_FUNC) (int *); +typedef void(*DST_HUD_IN_CLEARSTATES_FUNC) (void); +typedef void(*DST_HUD_IN_ACCUMULATE_FUNC) (void); +typedef void(*DST_HUD_CL_CREATEMOVE_FUNC) (float *, struct usercmd_s **, int *); +typedef void(*DST_HUD_CL_ISTHIRDPERSON_FUNC) (void); +typedef void(*DST_HUD_CL_GETCAMERAOFFSETS_FUNC) (float **); +typedef void(*DST_HUD_KB_FIND_FUNC) (const char **); +typedef void(*DST_HUD_CAMTHINK_FUNC) (void); +typedef void(*DST_HUD_CALCREF_FUNC) (struct ref_params_s **); +typedef void(*DST_HUD_ADDENTITY_FUNC) (int *, struct cl_entity_s **, const char **); +typedef void(*DST_HUD_CREATEENTITIES_FUNC) (void); +typedef void(*DST_HUD_DRAWNORMALTRIS_FUNC) (void); +typedef void(*DST_HUD_DRAWTRANSTRIS_FUNC) (void); +typedef void(*DST_HUD_STUDIOEVENT_FUNC) (const struct mstudioevent_s **, const struct cl_entity_s **); +typedef void(*DST_HUD_POSTRUNCMD_FUNC) (struct local_state_s **, struct local_state_s **, struct usercmd_s **, int *, double *, unsigned int *); +typedef void(*DST_HUD_SHUTDOWN_FUNC) (void); +typedef void(*DST_HUD_TXFERLOCALOVERRIDES_FUNC) (struct entity_state_s **, const struct clientdata_s **); +typedef void(*DST_HUD_PROCESSPLAYERSTATE_FUNC) (struct entity_state_s **, const struct entity_state_s **); +typedef void(*DST_HUD_TXFERPREDICTIONDATA_FUNC) (struct entity_state_s **, const struct entity_state_s **, struct clientdata_s **, const struct clientdata_s **, struct weapon_data_s **, const struct weapon_data_s **); +typedef void(*DST_HUD_DEMOREAD_FUNC) (int *, unsigned char **); +typedef void(*DST_HUD_CONNECTIONLESS_FUNC) (const struct netadr_s **, const char **, char **, int **); +typedef void(*DST_HUD_GETHULLBOUNDS_FUNC) (int *, float **, float **); +typedef void(*DST_HUD_FRAME_FUNC) (double *); +typedef void(*DST_HUD_KEY_EVENT_FUNC) (int *, int *, const char **); +typedef void(*DST_HUD_TEMPENTUPDATE_FUNC) (double *, double *, double *, struct tempent_s ***, struct tempent_s ***, int(**Callback_AddVisibleEntity)(struct cl_entity_s *pEntity), void(**Callback_TempEntPlaySound)(struct tempent_s *pTemp, float damp)); +typedef void(*DST_HUD_GETUSERENTITY_FUNC) (int *); +typedef void(*DST_HUD_VOICESTATUS_FUNC) (int *, qboolean *); +typedef void(*DST_HUD_DIRECTORMESSAGE_FUNC) (int *, void **); +typedef void(*DST_HUD_STUDIO_INTERFACE_FUNC) (int *, struct r_studio_interface_s ***, struct engine_studio_api_s **); +typedef void(*DST_HUD_CHATINPUTPOSITION_FUNC) (int **, int **); +typedef void(*DST_HUD_GETPLAYERTEAM) (int); + +// Pointers to the client destination functions +typedef struct +{ + DST_INITIALIZE_FUNC pInitFunc; + DST_HUD_INIT_FUNC pHudInitFunc; + DST_HUD_VIDINIT_FUNC pHudVidInitFunc; + DST_HUD_REDRAW_FUNC pHudRedrawFunc; + DST_HUD_UPDATECLIENTDATA_FUNC pHudUpdateClientDataFunc; + DST_HUD_RESET_FUNC pHudResetFunc; + DST_HUD_CLIENTMOVE_FUNC pClientMove; + DST_HUD_CLIENTMOVEINIT_FUNC pClientMoveInit; + DST_HUD_TEXTURETYPE_FUNC pClientTextureType; + DST_HUD_IN_ACTIVATEMOUSE_FUNC pIN_ActivateMouse; + DST_HUD_IN_DEACTIVATEMOUSE_FUNC pIN_DeactivateMouse; + DST_HUD_IN_MOUSEEVENT_FUNC pIN_MouseEvent; + DST_HUD_IN_CLEARSTATES_FUNC pIN_ClearStates; + DST_HUD_IN_ACCUMULATE_FUNC pIN_Accumulate; + DST_HUD_CL_CREATEMOVE_FUNC pCL_CreateMove; + DST_HUD_CL_ISTHIRDPERSON_FUNC pCL_IsThirdPerson; + DST_HUD_CL_GETCAMERAOFFSETS_FUNC pCL_GetCameraOffsets; + DST_HUD_KB_FIND_FUNC pFindKey; + DST_HUD_CAMTHINK_FUNC pCamThink; + DST_HUD_CALCREF_FUNC pCalcRefdef; + DST_HUD_ADDENTITY_FUNC pAddEntity; + DST_HUD_CREATEENTITIES_FUNC pCreateEntities; + DST_HUD_DRAWNORMALTRIS_FUNC pDrawNormalTriangles; + DST_HUD_DRAWTRANSTRIS_FUNC pDrawTransparentTriangles; + DST_HUD_STUDIOEVENT_FUNC pStudioEvent; + DST_HUD_POSTRUNCMD_FUNC pPostRunCmd; + DST_HUD_SHUTDOWN_FUNC pShutdown; + DST_HUD_TXFERLOCALOVERRIDES_FUNC pTxferLocalOverrides; + DST_HUD_PROCESSPLAYERSTATE_FUNC pProcessPlayerState; + DST_HUD_TXFERPREDICTIONDATA_FUNC pTxferPredictionData; + DST_HUD_DEMOREAD_FUNC pReadDemoBuffer; + DST_HUD_CONNECTIONLESS_FUNC pConnectionlessPacket; + DST_HUD_GETHULLBOUNDS_FUNC pGetHullBounds; + DST_HUD_FRAME_FUNC pHudFrame; + DST_HUD_KEY_EVENT_FUNC pKeyEvent; + DST_HUD_TEMPENTUPDATE_FUNC pTempEntUpdate; + DST_HUD_GETUSERENTITY_FUNC pGetUserEntity; + DST_HUD_VOICESTATUS_FUNC pVoiceStatus; // Possibly null on old client dlls. + DST_HUD_DIRECTORMESSAGE_FUNC pDirectorMessage; // Possibly null on old client dlls. + DST_HUD_STUDIO_INTERFACE_FUNC pStudioInterface; // Not used by all clients + DST_HUD_CHATINPUTPOSITION_FUNC pChatInputPosition; // Not used by all clients + DST_HUD_GETPLAYERTEAM pGetPlayerTeam; // Not used by all clients +} cldll_func_dst_t; + + + + +// ******************************************************** +// Functions exported by the engine +// ******************************************************** + +#ifdef _WIN32 +typedef HSPRITE HSPRITE_t; +#else +typedef int HSPRITE_t; +#endif + +// Function type declarations for engine exports +typedef HSPRITE_t (*pfnEngSrc_pfnSPR_Load_t ) ( const char *szPicName ); +typedef int (*pfnEngSrc_pfnSPR_Frames_t ) ( HSPRITE_t hPic ); +typedef int (*pfnEngSrc_pfnSPR_Height_t ) ( HSPRITE_t hPic, int frame ); +typedef int (*pfnEngSrc_pfnSPR_Width_t ) ( HSPRITE_t hPic, int frame ); +typedef void (*pfnEngSrc_pfnSPR_Set_t ) ( HSPRITE_t hPic, int r, int g, int b ); +typedef void (*pfnEngSrc_pfnSPR_Draw_t ) ( int frame, int x, int y, const struct rect_s *prc ); +typedef void (*pfnEngSrc_pfnSPR_DrawHoles_t ) ( int frame, int x, int y, const struct rect_s *prc ); +typedef void (*pfnEngSrc_pfnSPR_DrawAdditive_t ) ( int frame, int x, int y, const struct rect_s *prc ); +typedef void (*pfnEngSrc_pfnSPR_EnableScissor_t ) ( int x, int y, int width, int height ); +typedef void (*pfnEngSrc_pfnSPR_DisableScissor_t ) ( void ); +typedef struct client_sprite_s * (*pfnEngSrc_pfnSPR_GetList_t ) ( char *psz, int *piCount ); +typedef void (*pfnEngSrc_pfnFillRGBA_t ) ( int x, int y, int width, int height, int r, int g, int b, int a ); +typedef int (*pfnEngSrc_pfnGetScreenInfo_t ) ( struct SCREENINFO_s *pscrinfo ); +typedef void (*pfnEngSrc_pfnSetCrosshair_t ) ( HSPRITE_t hspr, wrect_t rc, int r, int g, int b ); +typedef struct cvar_s * (*pfnEngSrc_pfnRegisterVariable_t ) ( char *szName, char *szValue, int flags ); +typedef float (*pfnEngSrc_pfnGetCvarFloat_t ) ( char *szName ); +typedef char* (*pfnEngSrc_pfnGetCvarString_t ) ( char *szName ); +typedef int (*pfnEngSrc_pfnAddCommand_t ) ( char *cmd_name, void (*pfnEngSrc_function)(void) ); +typedef int (*pfnEngSrc_pfnHookUserMsg_t ) ( char *szMsgName, pfnUserMsgHook pfn ); +typedef int (*pfnEngSrc_pfnServerCmd_t ) ( char *szCmdString ); +typedef int (*pfnEngSrc_pfnClientCmd_t ) ( char *szCmdString ); +typedef void (*pfnEngSrc_pfnPrimeMusicStream_t ) ( char *szFilename, int looping ); +typedef void (*pfnEngSrc_pfnGetPlayerInfo_t ) ( int ent_num, struct hud_player_info_s *pinfo ); +typedef void (*pfnEngSrc_pfnPlaySoundByName_t ) ( char *szSound, float volume ); +typedef void (*pfnEngSrc_pfnPlaySoundByNameAtPitch_t )( char *szSound, float volume, int pitch ); +typedef void (*pfnEngSrc_pfnPlaySoundVoiceByName_t ) ( char *szSound, float volume, int pitch ); +typedef void (*pfnEngSrc_pfnPlaySoundByIndex_t ) ( int iSound, float volume ); +typedef void (*pfnEngSrc_pfnAngleVectors_t ) ( const float * vecAngles, float * forward, float * right, float * up ); +typedef struct client_textmessage_s*(*pfnEngSrc_pfnTextMessageGet_t ) ( const char *pName ); +typedef int (*pfnEngSrc_pfnDrawCharacter_t ) ( int x, int y, int number, int r, int g, int b ); +typedef int (*pfnEngSrc_pfnDrawConsoleString_t ) ( int x, int y, char *string ); +typedef void (*pfnEngSrc_pfnDrawSetTextColor_t ) ( float r, float g, float b ); +typedef void (*pfnEngSrc_pfnDrawConsoleStringLen_t ) ( const char *string, int *length, int *height ); +typedef void (*pfnEngSrc_pfnConsolePrint_t ) ( const char *string ); +typedef void (*pfnEngSrc_pfnCenterPrint_t ) ( const char *string ); +typedef int (*pfnEngSrc_GetWindowCenterX_t ) ( void ); +typedef int (*pfnEngSrc_GetWindowCenterY_t ) ( void ); +typedef void (*pfnEngSrc_GetViewAngles_t ) ( float * ); +typedef void (*pfnEngSrc_SetViewAngles_t ) ( float * ); +typedef int (*pfnEngSrc_GetMaxClients_t ) ( void ); +typedef void (*pfnEngSrc_Cvar_SetValue_t ) ( char *cvar, float value ); +typedef int (*pfnEngSrc_Cmd_Argc_t) (void); +typedef char * (*pfnEngSrc_Cmd_Argv_t ) ( int arg ); +typedef void (*pfnEngSrc_Con_Printf_t ) ( char *fmt, ... ); +typedef void (*pfnEngSrc_Con_DPrintf_t ) ( char *fmt, ... ); +typedef void (*pfnEngSrc_Con_NPrintf_t ) ( int pos, char *fmt, ... ); +typedef void (*pfnEngSrc_Con_NXPrintf_t ) ( struct con_nprint_s *info, char *fmt, ... ); +typedef const char * (*pfnEngSrc_PhysInfo_ValueForKey_t ) ( const char *key ); +typedef const char * (*pfnEngSrc_ServerInfo_ValueForKey_t ) ( const char *key ); +typedef float (*pfnEngSrc_GetClientMaxspeed_t ) ( void ); +typedef int (*pfnEngSrc_CheckParm_t ) ( char *parm, char **ppnext ); +typedef void (*pfnEngSrc_Key_Event_t ) ( int key, int down ); +typedef void (*pfnEngSrc_GetMousePosition_t ) ( int *mx, int *my ); +typedef int (*pfnEngSrc_IsNoClipping_t ) ( void ); +typedef struct cl_entity_s * (*pfnEngSrc_GetLocalPlayer_t ) ( void ); +typedef struct cl_entity_s * (*pfnEngSrc_GetViewModel_t ) ( void ); +typedef struct cl_entity_s * (*pfnEngSrc_GetEntityByIndex_t ) ( int idx ); +typedef float (*pfnEngSrc_GetClientTime_t ) ( void ); +typedef void (*pfnEngSrc_V_CalcShake_t ) ( void ); +typedef void (*pfnEngSrc_V_ApplyShake_t ) ( float *origin, float *angles, float factor ); +typedef int (*pfnEngSrc_PM_PointContents_t ) ( float *point, int *truecontents ); +typedef int (*pfnEngSrc_PM_WaterEntity_t ) ( float *p ); +typedef struct pmtrace_s * (*pfnEngSrc_PM_TraceLine_t ) ( float *start, float *end, int flags, int usehull, int ignore_pe ); +typedef struct model_s * (*pfnEngSrc_CL_LoadModel_t ) ( const char *modelname, int *index ); +typedef int (*pfnEngSrc_CL_CreateVisibleEntity_t ) ( int type, struct cl_entity_s *ent ); +typedef const struct model_s * (*pfnEngSrc_GetSpritePointer_t ) ( HSPRITE_t hSprite ); +typedef void (*pfnEngSrc_pfnPlaySoundByNameAtLocation_t )( char *szSound, float volume, float *origin ); +typedef unsigned short (*pfnEngSrc_pfnPrecacheEvent_t ) ( int type, const char* psz ); +typedef void (*pfnEngSrc_pfnPlaybackEvent_t ) ( int flags, const struct edict_s *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); +typedef void (*pfnEngSrc_pfnWeaponAnim_t ) ( int iAnim, int body ); +typedef float (*pfnEngSrc_pfnRandomFloat_t ) ( float flLow, float flHigh ); +typedef int32 (*pfnEngSrc_pfnRandomLong_t ) ( int32 lLow, int32 lHigh ); +typedef void (*pfnEngSrc_pfnHookEvent_t ) ( char *name, void ( *pfnEvent )( struct event_args_s *args ) ); +typedef int (*pfnEngSrc_Con_IsVisible_t) (); +typedef const char * (*pfnEngSrc_pfnGetGameDirectory_t ) ( void ); +typedef struct cvar_s * (*pfnEngSrc_pfnGetCvarPointer_t ) ( const char *szName ); +typedef const char * (*pfnEngSrc_Key_LookupBinding_t ) ( const char *pBinding ); +typedef const char * (*pfnEngSrc_pfnGetLevelName_t ) ( void ); +typedef void (*pfnEngSrc_pfnGetScreenFade_t ) ( struct screenfade_s *fade ); +typedef void (*pfnEngSrc_pfnSetScreenFade_t ) ( struct screenfade_s *fade ); +typedef void * (*pfnEngSrc_VGui_GetPanel_t ) ( ); +typedef void (*pfnEngSrc_VGui_ViewportPaintBackground_t )(int extents[4]); +typedef byte* (*pfnEngSrc_COM_LoadFile_t ) ( char *path, int usehunk, int *pLength ); +typedef char* (*pfnEngSrc_COM_ParseFile_t ) ( char *data, char *token ); +typedef void (*pfnEngSrc_COM_FreeFile_t) ( void *buffer ); +typedef struct triangleapi_s * pTriAPI; +typedef struct efx_api_s * pEfxAPI; +typedef struct event_api_s * pEventAPI; +typedef struct demo_api_s * pDemoAPI; +typedef struct net_api_s * pNetAPI; +typedef struct IVoiceTweak_s * pVoiceTweak; +typedef int (*pfnEngSrc_IsSpectateOnly_t ) ( void ); +typedef struct model_s * (*pfnEngSrc_LoadMapSprite_t ) ( const char *filename ); +typedef void (*pfnEngSrc_COM_AddAppDirectoryToSearchPath_t ) ( const char *pszBaseDir, const char *appName ); +typedef int (*pfnEngSrc_COM_ExpandFilename_t) ( const char *fileName, char *nameOutBuffer, int nameOutBufferSize ); +typedef const char * (*pfnEngSrc_PlayerInfo_ValueForKey_t ) ( int playerNum, const char *key ); +typedef void (*pfnEngSrc_PlayerInfo_SetValueForKey_t )( const char *key, const char *value ); +typedef qboolean (*pfnEngSrc_GetPlayerUniqueID_t) (int iPlayer, char playerID[16]); +typedef int (*pfnEngSrc_GetTrackerIDForPlayer_t) (int playerSlot); +typedef int (*pfnEngSrc_GetPlayerForTrackerID_t) (int trackerID); +typedef int (*pfnEngSrc_pfnServerCmdUnreliable_t ) ( char *szCmdString ); +typedef void (*pfnEngSrc_GetMousePos_t ) (struct tagPOINT *ppt); +typedef void (*pfnEngSrc_SetMousePos_t ) (int x, int y); +typedef void (*pfnEngSrc_SetMouseEnable_t) (qboolean fEnable); +typedef struct cvar_s * (*pfnEngSrc_GetFirstCVarPtr_t) (); +typedef unsigned int (*pfnEngSrc_GetFirstCmdFunctionHandle_t)(); +typedef unsigned int (*pfnEngSrc_GetNextCmdFunctionHandle_t) (unsigned int cmdhandle); +typedef const char * (*pfnEngSrc_GetCmdFunctionName_t) (unsigned int cmdhandle); +typedef float (*pfnEngSrc_GetClientOldTime_t) (); +typedef float (*pfnEngSrc_GetServerGravityValue_t) (); +typedef struct model_s * (*pfnEngSrc_GetModelByIndex_t) ( int index ); +typedef void (*pfnEngSrc_pfnSetFilterMode_t ) ( int mode ); +typedef void (*pfnEngSrc_pfnSetFilterColor_t ) ( float r, float g, float b ); +typedef void (*pfnEngSrc_pfnSetFilterBrightness_t ) ( float brightness ); +typedef sequenceEntry_s* (*pfnEngSrc_pfnSequenceGet_t ) ( const char *fileName, const char* entryName ); +typedef void (*pfnEngSrc_pfnSPR_DrawGeneric_t ) ( int frame, int x, int y, const struct rect_s *prc, int src, int dest, int w, int h ); +typedef sentenceEntry_s* (*pfnEngSrc_pfnSequencePickSentence_t ) ( const char *sentenceName, int pickMethod, int* entryPicked ); +// draw a complete string +typedef int (*pfnEngSrc_pfnDrawString_t ) ( int x, int y, const char *str, int r, int g, int b ); +typedef int (*pfnEngSrc_pfnDrawStringReverse_t ) ( int x, int y, const char *str, int r, int g, int b ); +typedef const char * (*pfnEngSrc_LocalPlayerInfo_ValueForKey_t )( const char *key ); +typedef int (*pfnEngSrc_pfnVGUI2DrawCharacter_t ) ( int x, int y, int ch, unsigned int font ); +typedef int (*pfnEngSrc_pfnVGUI2DrawCharacterAdd_t )( int x, int y, int ch, int r, int g, int b, unsigned int font); +typedef unsigned int (*pfnEngSrc_COM_GetApproxWavePlayLength )( const char * filename); +typedef void * (*pfnEngSrc_pfnGetCareerUI_t) (); +typedef void (*pfnEngSrc_Cvar_Set_t ) ( char *cvar, char *value ); +typedef int (*pfnEngSrc_pfnIsPlayingCareerMatch_t) (); +typedef double (*pfnEngSrc_GetAbsoluteTime_t) ( void ); +typedef void (*pfnEngSrc_pfnProcessTutorMessageDecayBuffer_t)(int *buffer, int bufferLength); +typedef void (*pfnEngSrc_pfnConstructTutorMessageDecayBuffer_t)(int *buffer, int bufferLength); +typedef void (*pfnEngSrc_pfnResetTutorMessageDecayData_t)(); +typedef void (*pfnEngSrc_pfnFillRGBABlend_t ) ( int x, int y, int width, int height, int r, int g, int b, int a ); +typedef int (*pfnEngSrc_pfnGetAppID_t) ( void ); +typedef cmdalias_t* (*pfnEngSrc_pfnGetAliases_t) ( void ); +typedef void (*pfnEngSrc_pfnVguiWrap2_GetMouseDelta_t)( int *x, int *y ); + +// Pointers to the exported engine functions themselves +typedef struct cl_enginefuncs_s +{ + pfnEngSrc_pfnSPR_Load_t pfnSPR_Load; + pfnEngSrc_pfnSPR_Frames_t pfnSPR_Frames; + pfnEngSrc_pfnSPR_Height_t pfnSPR_Height; + pfnEngSrc_pfnSPR_Width_t pfnSPR_Width; + pfnEngSrc_pfnSPR_Set_t pfnSPR_Set; + pfnEngSrc_pfnSPR_Draw_t pfnSPR_Draw; + pfnEngSrc_pfnSPR_DrawHoles_t pfnSPR_DrawHoles; + pfnEngSrc_pfnSPR_DrawAdditive_t pfnSPR_DrawAdditive; + pfnEngSrc_pfnSPR_EnableScissor_t pfnSPR_EnableScissor; + pfnEngSrc_pfnSPR_DisableScissor_t pfnSPR_DisableScissor; + pfnEngSrc_pfnSPR_GetList_t pfnSPR_GetList; + pfnEngSrc_pfnFillRGBA_t pfnFillRGBA; + pfnEngSrc_pfnGetScreenInfo_t pfnGetScreenInfo; + pfnEngSrc_pfnSetCrosshair_t pfnSetCrosshair; + pfnEngSrc_pfnRegisterVariable_t pfnRegisterVariable; + pfnEngSrc_pfnGetCvarFloat_t pfnGetCvarFloat; + pfnEngSrc_pfnGetCvarString_t pfnGetCvarString; + pfnEngSrc_pfnAddCommand_t pfnAddCommand; + pfnEngSrc_pfnHookUserMsg_t pfnHookUserMsg; + pfnEngSrc_pfnServerCmd_t pfnServerCmd; + pfnEngSrc_pfnClientCmd_t pfnClientCmd; + pfnEngSrc_pfnGetPlayerInfo_t pfnGetPlayerInfo; + pfnEngSrc_pfnPlaySoundByName_t pfnPlaySoundByName; + pfnEngSrc_pfnPlaySoundByIndex_t pfnPlaySoundByIndex; + pfnEngSrc_pfnAngleVectors_t pfnAngleVectors; + pfnEngSrc_pfnTextMessageGet_t pfnTextMessageGet; + pfnEngSrc_pfnDrawCharacter_t pfnDrawCharacter; + pfnEngSrc_pfnDrawConsoleString_t pfnDrawConsoleString; + pfnEngSrc_pfnDrawSetTextColor_t pfnDrawSetTextColor; + pfnEngSrc_pfnDrawConsoleStringLen_t pfnDrawConsoleStringLen; + pfnEngSrc_pfnConsolePrint_t pfnConsolePrint; + pfnEngSrc_pfnCenterPrint_t pfnCenterPrint; + pfnEngSrc_GetWindowCenterX_t GetWindowCenterX; + pfnEngSrc_GetWindowCenterY_t GetWindowCenterY; + pfnEngSrc_GetViewAngles_t GetViewAngles; + pfnEngSrc_SetViewAngles_t SetViewAngles; + pfnEngSrc_GetMaxClients_t GetMaxClients; + pfnEngSrc_Cvar_SetValue_t Cvar_SetValue; + pfnEngSrc_Cmd_Argc_t Cmd_Argc; + pfnEngSrc_Cmd_Argv_t Cmd_Argv; + pfnEngSrc_Con_Printf_t Con_Printf; + pfnEngSrc_Con_DPrintf_t Con_DPrintf; + pfnEngSrc_Con_NPrintf_t Con_NPrintf; + pfnEngSrc_Con_NXPrintf_t Con_NXPrintf; + pfnEngSrc_PhysInfo_ValueForKey_t PhysInfo_ValueForKey; + pfnEngSrc_ServerInfo_ValueForKey_t ServerInfo_ValueForKey; + pfnEngSrc_GetClientMaxspeed_t GetClientMaxspeed; + pfnEngSrc_CheckParm_t CheckParm; + pfnEngSrc_Key_Event_t Key_Event; + pfnEngSrc_GetMousePosition_t GetMousePosition; + pfnEngSrc_IsNoClipping_t IsNoClipping; + pfnEngSrc_GetLocalPlayer_t GetLocalPlayer; + pfnEngSrc_GetViewModel_t GetViewModel; + pfnEngSrc_GetEntityByIndex_t GetEntityByIndex; + pfnEngSrc_GetClientTime_t GetClientTime; + pfnEngSrc_V_CalcShake_t V_CalcShake; + pfnEngSrc_V_ApplyShake_t V_ApplyShake; + pfnEngSrc_PM_PointContents_t PM_PointContents; + pfnEngSrc_PM_WaterEntity_t PM_WaterEntity; + pfnEngSrc_PM_TraceLine_t PM_TraceLine; + pfnEngSrc_CL_LoadModel_t CL_LoadModel; + pfnEngSrc_CL_CreateVisibleEntity_t CL_CreateVisibleEntity; + pfnEngSrc_GetSpritePointer_t GetSpritePointer; + pfnEngSrc_pfnPlaySoundByNameAtLocation_t pfnPlaySoundByNameAtLocation; + pfnEngSrc_pfnPrecacheEvent_t pfnPrecacheEvent; + pfnEngSrc_pfnPlaybackEvent_t pfnPlaybackEvent; + pfnEngSrc_pfnWeaponAnim_t pfnWeaponAnim; + pfnEngSrc_pfnRandomFloat_t pfnRandomFloat; + pfnEngSrc_pfnRandomLong_t pfnRandomLong; + pfnEngSrc_pfnHookEvent_t pfnHookEvent; + pfnEngSrc_Con_IsVisible_t Con_IsVisible; + pfnEngSrc_pfnGetGameDirectory_t pfnGetGameDirectory; + pfnEngSrc_pfnGetCvarPointer_t pfnGetCvarPointer; + pfnEngSrc_Key_LookupBinding_t Key_LookupBinding; + pfnEngSrc_pfnGetLevelName_t pfnGetLevelName; + pfnEngSrc_pfnGetScreenFade_t pfnGetScreenFade; + pfnEngSrc_pfnSetScreenFade_t pfnSetScreenFade; + pfnEngSrc_VGui_GetPanel_t VGui_GetPanel; + pfnEngSrc_VGui_ViewportPaintBackground_t VGui_ViewportPaintBackground; + pfnEngSrc_COM_LoadFile_t COM_LoadFile; + pfnEngSrc_COM_ParseFile_t COM_ParseFile; + pfnEngSrc_COM_FreeFile_t COM_FreeFile; + struct triangleapi_s *pTriAPI; + struct efx_api_s *pEfxAPI; + struct event_api_s *pEventAPI; + struct demo_api_s *pDemoAPI; + struct net_api_s *pNetAPI; + struct IVoiceTweak_s *pVoiceTweak; + pfnEngSrc_IsSpectateOnly_t IsSpectateOnly; + pfnEngSrc_LoadMapSprite_t LoadMapSprite; + pfnEngSrc_COM_AddAppDirectoryToSearchPath_t COM_AddAppDirectoryToSearchPath; + pfnEngSrc_COM_ExpandFilename_t COM_ExpandFilename; + pfnEngSrc_PlayerInfo_ValueForKey_t PlayerInfo_ValueForKey; + pfnEngSrc_PlayerInfo_SetValueForKey_t PlayerInfo_SetValueForKey; + pfnEngSrc_GetPlayerUniqueID_t GetPlayerUniqueID; + pfnEngSrc_GetTrackerIDForPlayer_t GetTrackerIDForPlayer; + pfnEngSrc_GetPlayerForTrackerID_t GetPlayerForTrackerID; + pfnEngSrc_pfnServerCmdUnreliable_t pfnServerCmdUnreliable; + pfnEngSrc_GetMousePos_t pfnGetMousePos; + pfnEngSrc_SetMousePos_t pfnSetMousePos; + pfnEngSrc_SetMouseEnable_t pfnSetMouseEnable; + pfnEngSrc_GetFirstCVarPtr_t GetFirstCvarPtr; + pfnEngSrc_GetFirstCmdFunctionHandle_t GetFirstCmdFunctionHandle; + pfnEngSrc_GetNextCmdFunctionHandle_t GetNextCmdFunctionHandle; + pfnEngSrc_GetCmdFunctionName_t GetCmdFunctionName; + pfnEngSrc_GetClientOldTime_t hudGetClientOldTime; + pfnEngSrc_GetServerGravityValue_t hudGetServerGravityValue; + pfnEngSrc_GetModelByIndex_t hudGetModelByIndex; + pfnEngSrc_pfnSetFilterMode_t pfnSetFilterMode; + pfnEngSrc_pfnSetFilterColor_t pfnSetFilterColor; + pfnEngSrc_pfnSetFilterBrightness_t pfnSetFilterBrightness; + pfnEngSrc_pfnSequenceGet_t pfnSequenceGet; + pfnEngSrc_pfnSPR_DrawGeneric_t pfnSPR_DrawGeneric; + pfnEngSrc_pfnSequencePickSentence_t pfnSequencePickSentence; + pfnEngSrc_pfnDrawString_t pfnDrawString; + pfnEngSrc_pfnDrawStringReverse_t pfnDrawStringReverse; + pfnEngSrc_LocalPlayerInfo_ValueForKey_t LocalPlayerInfo_ValueForKey; + pfnEngSrc_pfnVGUI2DrawCharacter_t pfnVGUI2DrawCharacter; + pfnEngSrc_pfnVGUI2DrawCharacterAdd_t pfnVGUI2DrawCharacterAdd; + pfnEngSrc_COM_GetApproxWavePlayLength COM_GetApproxWavePlayLength; + pfnEngSrc_pfnGetCareerUI_t pfnGetCareerUI; + pfnEngSrc_Cvar_Set_t Cvar_Set; + pfnEngSrc_pfnIsPlayingCareerMatch_t pfnIsCareerMatch; + pfnEngSrc_pfnPlaySoundVoiceByName_t pfnPlaySoundVoiceByName; + pfnEngSrc_pfnPrimeMusicStream_t pfnPrimeMusicStream; + pfnEngSrc_GetAbsoluteTime_t GetAbsoluteTime; + pfnEngSrc_pfnProcessTutorMessageDecayBuffer_t pfnProcessTutorMessageDecayBuffer; + pfnEngSrc_pfnConstructTutorMessageDecayBuffer_t pfnConstructTutorMessageDecayBuffer; + pfnEngSrc_pfnResetTutorMessageDecayData_t pfnResetTutorMessageDecayData; + pfnEngSrc_pfnPlaySoundByNameAtPitch_t pfnPlaySoundByNameAtPitch; + pfnEngSrc_pfnFillRGBABlend_t pfnFillRGBABlend; + pfnEngSrc_pfnGetAppID_t pfnGetAppID; + pfnEngSrc_pfnGetAliases_t pfnGetAliasList; + pfnEngSrc_pfnVguiWrap2_GetMouseDelta_t pfnVguiWrap2_GetMouseDelta; +} cl_enginefunc_t; + +// Function type declarations for engine destination functions +typedef void(*pfnEngDst_pfnSPR_Load_t) (const char **); +typedef void(*pfnEngDst_pfnSPR_Frames_t) (HSPRITE_t *); +typedef void(*pfnEngDst_pfnSPR_Height_t) (HSPRITE_t *, int *); +typedef void(*pfnEngDst_pfnSPR_Width_t) (HSPRITE_t *, int *); +typedef void(*pfnEngDst_pfnSPR_Set_t) (HSPRITE_t *, int *, int *, int *); +typedef void(*pfnEngDst_pfnSPR_Draw_t) (int *, int *, int *, const struct rect_s **); +typedef void(*pfnEngDst_pfnSPR_DrawHoles_t) (int *, int *, int *, const struct rect_s **); +typedef void(*pfnEngDst_pfnSPR_DrawAdditive_t) (int *, int *, int *, const struct rect_s **); +typedef void(*pfnEngDst_pfnSPR_EnableScissor_t) (int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnSPR_DisableScissor_t) (void); +typedef void(*pfnEngDst_pfnSPR_GetList_t) (char **, int **); +typedef void(*pfnEngDst_pfnFillRGBA_t) (int *, int *, int *, int *, int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnGetScreenInfo_t) (struct SCREENINFO_s **); +typedef void(*pfnEngDst_pfnSetCrosshair_t) (HSPRITE_t *, struct rect_s *, int *, int *, int *); +typedef void(*pfnEngDst_pfnRegisterVariable_t) (char **, char **, int *); +typedef void(*pfnEngDst_pfnGetCvarFloat_t) (char **); +typedef void(*pfnEngDst_pfnGetCvarString_t) (char **); +typedef void(*pfnEngDst_pfnAddCommand_t) (char **, void(**pfnEngDst_function)(void)); +typedef void(*pfnEngDst_pfnHookUserMsg_t) (char **, pfnUserMsgHook *); +typedef void(*pfnEngDst_pfnServerCmd_t) (char **); +typedef void(*pfnEngDst_pfnClientCmd_t) (char **); +typedef void(*pfnEngDst_pfnPrimeMusicStream_t) (char **, int *); +typedef void(*pfnEngDst_pfnGetPlayerInfo_t) (int *, struct hud_player_info_s **); +typedef void(*pfnEngDst_pfnPlaySoundByName_t) (char **, float *); +typedef void(*pfnEngDst_pfnPlaySoundByNameAtPitch_t) (char **, float *, int *); +typedef void(*pfnEngDst_pfnPlaySoundVoiceByName_t) (char **, float *); +typedef void(*pfnEngDst_pfnPlaySoundByIndex_t) (int *, float *); +typedef void(*pfnEngDst_pfnAngleVectors_t) (const float * *, float * *, float * *, float * *); +typedef void(*pfnEngDst_pfnTextMessageGet_t) (const char **); +typedef void(*pfnEngDst_pfnDrawCharacter_t) (int *, int *, int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnDrawConsoleString_t) (int *, int *, char **); +typedef void(*pfnEngDst_pfnDrawSetTextColor_t) (float *, float *, float *); +typedef void(*pfnEngDst_pfnDrawConsoleStringLen_t) (const char **, int **, int **); +typedef void(*pfnEngDst_pfnConsolePrint_t) (const char **); +typedef void(*pfnEngDst_pfnCenterPrint_t) (const char **); +typedef void(*pfnEngDst_GetWindowCenterX_t) (void); +typedef void(*pfnEngDst_GetWindowCenterY_t) (void); +typedef void(*pfnEngDst_GetViewAngles_t) (float **); +typedef void(*pfnEngDst_SetViewAngles_t) (float **); +typedef void(*pfnEngDst_GetMaxClients_t) (void); +typedef void(*pfnEngDst_Cvar_SetValue_t) (char **, float *); +typedef void(*pfnEngDst_Cmd_Argc_t) (void); +typedef void(*pfnEngDst_Cmd_Argv_t) (int *); +typedef void(*pfnEngDst_Con_Printf_t) (char **); +typedef void(*pfnEngDst_Con_DPrintf_t) (char **); +typedef void(*pfnEngDst_Con_NPrintf_t) (int *, char **); +typedef void(*pfnEngDst_Con_NXPrintf_t) (struct con_nprint_s **, char **); +typedef void(*pfnEngDst_PhysInfo_ValueForKey_t) (const char **); +typedef void(*pfnEngDst_ServerInfo_ValueForKey_t) (const char **); +typedef void(*pfnEngDst_GetClientMaxspeed_t) (void); +typedef void(*pfnEngDst_CheckParm_t) (char **, char ***); +typedef void(*pfnEngDst_Key_Event_t) (int *, int *); +typedef void(*pfnEngDst_GetMousePosition_t) (int **, int **); +typedef void(*pfnEngDst_IsNoClipping_t) (void); +typedef void(*pfnEngDst_GetLocalPlayer_t) (void); +typedef void(*pfnEngDst_GetViewModel_t) (void); +typedef void(*pfnEngDst_GetEntityByIndex_t) (int *); +typedef void(*pfnEngDst_GetClientTime_t) (void); +typedef void(*pfnEngDst_V_CalcShake_t) (void); +typedef void(*pfnEngDst_V_ApplyShake_t) (float **, float **, float *); +typedef void(*pfnEngDst_PM_PointContents_t) (float **, int **); +typedef void(*pfnEngDst_PM_WaterEntity_t) (float **); +typedef void(*pfnEngDst_PM_TraceLine_t) (float **, float **, int *, int *, int *); +typedef void(*pfnEngDst_CL_LoadModel_t) (const char **, int **); +typedef void(*pfnEngDst_CL_CreateVisibleEntity_t) (int *, struct cl_entity_s **); +typedef void(*pfnEngDst_GetSpritePointer_t) (HSPRITE_t *); +typedef void(*pfnEngDst_pfnPlaySoundByNameAtLocation_t) (char **, float *, float **); +typedef void(*pfnEngDst_pfnPrecacheEvent_t) (int *, const char* *); +typedef void(*pfnEngDst_pfnPlaybackEvent_t) (int *, const struct edict_s **, unsigned short *, float *, float **, float **, float *, float *, int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnWeaponAnim_t) (int *, int *); +typedef void(*pfnEngDst_pfnRandomFloat_t) (float *, float *); +typedef void(*pfnEngDst_pfnRandomLong_t) (int32 *, int32 *); +typedef void(*pfnEngDst_pfnHookEvent_t) (char **, void(**pfnEvent)(struct event_args_s *args)); +typedef void(*pfnEngDst_Con_IsVisible_t) (); +typedef void(*pfnEngDst_pfnGetGameDirectory_t) (void); +typedef void(*pfnEngDst_pfnGetCvarPointer_t) (const char **); +typedef void(*pfnEngDst_Key_LookupBinding_t) (const char **); +typedef void(*pfnEngDst_pfnGetLevelName_t) (void); +typedef void(*pfnEngDst_pfnGetScreenFade_t) (struct screenfade_s **); +typedef void(*pfnEngDst_pfnSetScreenFade_t) (struct screenfade_s **); +typedef void(*pfnEngDst_VGui_GetPanel_t) (); +typedef void(*pfnEngDst_VGui_ViewportPaintBackground_t) (int **); +typedef void(*pfnEngDst_COM_LoadFile_t) (const char **, int *, int **); +typedef void(*pfnEngDst_COM_ParseFile_t) (char **, char **); +typedef void(*pfnEngDst_COM_FreeFile_t) (void **); +typedef void(*pfnEngDst_IsSpectateOnly_t) (void); +typedef void(*pfnEngDst_LoadMapSprite_t) (const char **); +typedef void(*pfnEngDst_COM_AddAppDirectoryToSearchPath_t) (const char **, const char **); +typedef void(*pfnEngDst_COM_ExpandFilename_t) (const char **, char **, int *); +typedef void(*pfnEngDst_PlayerInfo_ValueForKey_t) (int *, const char **); +typedef void(*pfnEngDst_PlayerInfo_SetValueForKey_t) (const char **, const char **); +typedef void(*pfnEngDst_GetPlayerUniqueID_t) (int *, char **); +typedef void(*pfnEngDst_GetTrackerIDForPlayer_t) (int *); +typedef void(*pfnEngDst_GetPlayerForTrackerID_t) (int *); +typedef void(*pfnEngDst_pfnServerCmdUnreliable_t) (char **); +typedef void(*pfnEngDst_GetMousePos_t) (struct tagPOINT **); +typedef void(*pfnEngDst_SetMousePos_t) (int *, int *); +typedef void(*pfnEngDst_SetMouseEnable_t) (qboolean *); +typedef void(*pfnEngDst_pfnSetFilterMode_t) (int *); +typedef void(*pfnEngDst_pfnSetFilterColor_t) (float *, float *, float *); +typedef void(*pfnEngDst_pfnSetFilterBrightness_t) (float *); +typedef void(*pfnEngDst_pfnSequenceGet_t) (const char**, const char**); +typedef void(*pfnEngDst_pfnSPR_DrawGeneric_t) (int *, int *, int *, const struct rect_s **, int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnSequencePickSentence_t) (const char**, int *, int **); +typedef void(*pfnEngDst_pfnDrawString_t) (int *, int *, const char *, int *, int *, int *); +typedef void(*pfnEngDst_pfnDrawStringReverse_t) (int *, int *, const char *, int *, int *, int *); +typedef void(*pfnEngDst_LocalPlayerInfo_ValueForKey_t) (const char **); +typedef void(*pfnEngDst_pfnVGUI2DrawCharacter_t) (int *, int *, int *, unsigned int *); +typedef void(*pfnEngDst_pfnVGUI2DrawCharacterAdd_t) (int *, int *, int *, int *, int *, int *, unsigned int *); +typedef void(*pfnEngDst_pfnProcessTutorMessageDecayBuffer_t) (int **, int *); +typedef void(*pfnEngDst_pfnConstructTutorMessageDecayBuffer_t) (int **, int *); +typedef void(*pfnEngDst_pfnResetTutorMessageDecayData_t) (); +typedef void(*pfnEngDst_pfnFillRGBABlend_t) (int *, int *, int *, int *, int *, int *, int *, int *); +typedef void(*pfnEngDst_pfnGetAppID_t) (void); +typedef void(*pfnEngDst_pfnGetAliases_t) (void); +typedef void(*pfnEngDst_pfnVguiWrap2_GetMouseDelta_t) (int *x, int *y); + + +// Pointers to the engine destination functions +typedef struct +{ + pfnEngDst_pfnSPR_Load_t pfnSPR_Load; + pfnEngDst_pfnSPR_Frames_t pfnSPR_Frames; + pfnEngDst_pfnSPR_Height_t pfnSPR_Height; + pfnEngDst_pfnSPR_Width_t pfnSPR_Width; + pfnEngDst_pfnSPR_Set_t pfnSPR_Set; + pfnEngDst_pfnSPR_Draw_t pfnSPR_Draw; + pfnEngDst_pfnSPR_DrawHoles_t pfnSPR_DrawHoles; + pfnEngDst_pfnSPR_DrawAdditive_t pfnSPR_DrawAdditive; + pfnEngDst_pfnSPR_EnableScissor_t pfnSPR_EnableScissor; + pfnEngDst_pfnSPR_DisableScissor_t pfnSPR_DisableScissor; + pfnEngDst_pfnSPR_GetList_t pfnSPR_GetList; + pfnEngDst_pfnFillRGBA_t pfnFillRGBA; + pfnEngDst_pfnGetScreenInfo_t pfnGetScreenInfo; + pfnEngDst_pfnSetCrosshair_t pfnSetCrosshair; + pfnEngDst_pfnRegisterVariable_t pfnRegisterVariable; + pfnEngDst_pfnGetCvarFloat_t pfnGetCvarFloat; + pfnEngDst_pfnGetCvarString_t pfnGetCvarString; + pfnEngDst_pfnAddCommand_t pfnAddCommand; + pfnEngDst_pfnHookUserMsg_t pfnHookUserMsg; + pfnEngDst_pfnServerCmd_t pfnServerCmd; + pfnEngDst_pfnClientCmd_t pfnClientCmd; + pfnEngDst_pfnGetPlayerInfo_t pfnGetPlayerInfo; + pfnEngDst_pfnPlaySoundByName_t pfnPlaySoundByName; + pfnEngDst_pfnPlaySoundByIndex_t pfnPlaySoundByIndex; + pfnEngDst_pfnAngleVectors_t pfnAngleVectors; + pfnEngDst_pfnTextMessageGet_t pfnTextMessageGet; + pfnEngDst_pfnDrawCharacter_t pfnDrawCharacter; + pfnEngDst_pfnDrawConsoleString_t pfnDrawConsoleString; + pfnEngDst_pfnDrawSetTextColor_t pfnDrawSetTextColor; + pfnEngDst_pfnDrawConsoleStringLen_t pfnDrawConsoleStringLen; + pfnEngDst_pfnConsolePrint_t pfnConsolePrint; + pfnEngDst_pfnCenterPrint_t pfnCenterPrint; + pfnEngDst_GetWindowCenterX_t GetWindowCenterX; + pfnEngDst_GetWindowCenterY_t GetWindowCenterY; + pfnEngDst_GetViewAngles_t GetViewAngles; + pfnEngDst_SetViewAngles_t SetViewAngles; + pfnEngDst_GetMaxClients_t GetMaxClients; + pfnEngDst_Cvar_SetValue_t Cvar_SetValue; + pfnEngDst_Cmd_Argc_t Cmd_Argc; + pfnEngDst_Cmd_Argv_t Cmd_Argv; + pfnEngDst_Con_Printf_t Con_Printf; + pfnEngDst_Con_DPrintf_t Con_DPrintf; + pfnEngDst_Con_NPrintf_t Con_NPrintf; + pfnEngDst_Con_NXPrintf_t Con_NXPrintf; + pfnEngDst_PhysInfo_ValueForKey_t PhysInfo_ValueForKey; + pfnEngDst_ServerInfo_ValueForKey_t ServerInfo_ValueForKey; + pfnEngDst_GetClientMaxspeed_t GetClientMaxspeed; + pfnEngDst_CheckParm_t CheckParm; + pfnEngDst_Key_Event_t Key_Event; + pfnEngDst_GetMousePosition_t GetMousePosition; + pfnEngDst_IsNoClipping_t IsNoClipping; + pfnEngDst_GetLocalPlayer_t GetLocalPlayer; + pfnEngDst_GetViewModel_t GetViewModel; + pfnEngDst_GetEntityByIndex_t GetEntityByIndex; + pfnEngDst_GetClientTime_t GetClientTime; + pfnEngDst_V_CalcShake_t V_CalcShake; + pfnEngDst_V_ApplyShake_t V_ApplyShake; + pfnEngDst_PM_PointContents_t PM_PointContents; + pfnEngDst_PM_WaterEntity_t PM_WaterEntity; + pfnEngDst_PM_TraceLine_t PM_TraceLine; + pfnEngDst_CL_LoadModel_t CL_LoadModel; + pfnEngDst_CL_CreateVisibleEntity_t CL_CreateVisibleEntity; + pfnEngDst_GetSpritePointer_t GetSpritePointer; + pfnEngDst_pfnPlaySoundByNameAtLocation_t pfnPlaySoundByNameAtLocation; + pfnEngDst_pfnPrecacheEvent_t pfnPrecacheEvent; + pfnEngDst_pfnPlaybackEvent_t pfnPlaybackEvent; + pfnEngDst_pfnWeaponAnim_t pfnWeaponAnim; + pfnEngDst_pfnRandomFloat_t pfnRandomFloat; + pfnEngDst_pfnRandomLong_t pfnRandomLong; + pfnEngDst_pfnHookEvent_t pfnHookEvent; + pfnEngDst_Con_IsVisible_t Con_IsVisible; + pfnEngDst_pfnGetGameDirectory_t pfnGetGameDirectory; + pfnEngDst_pfnGetCvarPointer_t pfnGetCvarPointer; + pfnEngDst_Key_LookupBinding_t Key_LookupBinding; + pfnEngDst_pfnGetLevelName_t pfnGetLevelName; + pfnEngDst_pfnGetScreenFade_t pfnGetScreenFade; + pfnEngDst_pfnSetScreenFade_t pfnSetScreenFade; + pfnEngDst_VGui_GetPanel_t VGui_GetPanel; + pfnEngDst_VGui_ViewportPaintBackground_t VGui_ViewportPaintBackground; + pfnEngDst_COM_LoadFile_t COM_LoadFile; + pfnEngDst_COM_ParseFile_t COM_ParseFile; + pfnEngDst_COM_FreeFile_t COM_FreeFile; + struct triangleapi_s *pTriAPI; + struct efx_api_s *pEfxAPI; + struct event_api_s *pEventAPI; + struct demo_api_s *pDemoAPI; + struct net_api_s *pNetAPI; + struct IVoiceTweak_s *pVoiceTweak; + pfnEngDst_IsSpectateOnly_t IsSpectateOnly; + pfnEngDst_LoadMapSprite_t LoadMapSprite; + pfnEngDst_COM_AddAppDirectoryToSearchPath_t COM_AddAppDirectoryToSearchPath; + pfnEngDst_COM_ExpandFilename_t COM_ExpandFilename; + pfnEngDst_PlayerInfo_ValueForKey_t PlayerInfo_ValueForKey; + pfnEngDst_PlayerInfo_SetValueForKey_t PlayerInfo_SetValueForKey; + pfnEngDst_GetPlayerUniqueID_t GetPlayerUniqueID; + pfnEngDst_GetTrackerIDForPlayer_t GetTrackerIDForPlayer; + pfnEngDst_GetPlayerForTrackerID_t GetPlayerForTrackerID; + pfnEngDst_pfnServerCmdUnreliable_t pfnServerCmdUnreliable; + pfnEngDst_GetMousePos_t pfnGetMousePos; + pfnEngDst_SetMousePos_t pfnSetMousePos; + pfnEngDst_SetMouseEnable_t pfnSetMouseEnable; + pfnEngDst_pfnSetFilterMode_t pfnSetFilterMode ; + pfnEngDst_pfnSetFilterColor_t pfnSetFilterColor ; + pfnEngDst_pfnSetFilterBrightness_t pfnSetFilterBrightness ; + pfnEngDst_pfnSequenceGet_t pfnSequenceGet; + pfnEngDst_pfnSPR_DrawGeneric_t pfnSPR_DrawGeneric; + pfnEngDst_pfnSequencePickSentence_t pfnSequencePickSentence; + pfnEngDst_pfnDrawString_t pfnDrawString; + pfnEngDst_pfnDrawString_t pfnDrawStringReverse; + pfnEngDst_LocalPlayerInfo_ValueForKey_t LocalPlayerInfo_ValueForKey; + pfnEngDst_pfnVGUI2DrawCharacter_t pfnVGUI2DrawCharacter; + pfnEngDst_pfnVGUI2DrawCharacterAdd_t pfnVGUI2DrawCharacterAdd; + pfnEngDst_pfnPlaySoundVoiceByName_t pfnPlaySoundVoiceByName; + pfnEngDst_pfnPrimeMusicStream_t pfnPrimeMusicStream; + pfnEngDst_pfnProcessTutorMessageDecayBuffer_t pfnProcessTutorMessageDecayBuffer; + pfnEngDst_pfnConstructTutorMessageDecayBuffer_t pfnConstructTutorMessageDecayBuffer; + pfnEngDst_pfnResetTutorMessageDecayData_t pfnResetTutorMessageDecayData; + pfnEngDst_pfnPlaySoundByNameAtPitch_t pfnPlaySoundByNameAtPitch; + pfnEngDst_pfnFillRGBABlend_t pfnFillRGBABlend; + pfnEngDst_pfnGetAppID_t pfnGetAppID; + pfnEngDst_pfnGetAliases_t pfnGetAliasList; + pfnEngDst_pfnVguiWrap2_GetMouseDelta_t pfnVguiWrap2_GetMouseDelta; +} cl_enginefunc_dst_t; + + +// ******************************************************** +// Functions exposed by the engine to the module +// ******************************************************** + +// Functions for ModuleS +typedef void (*PFN_KICKPLAYER)(int nPlayerSlot, int nReason); + +typedef struct modshelpers_s +{ + PFN_KICKPLAYER m_pfnKickPlayer; + + // reserved for future expansion + int m_nVoid1; + int m_nVoid2; + int m_nVoid3; + int m_nVoid4; + int m_nVoid5; + int m_nVoid6; + int m_nVoid7; + int m_nVoid8; + int m_nVoid9; +} modshelpers_t; + +// Functions for moduleC +typedef struct modchelpers_s +{ + // reserved for future expansion + int m_nVoid0; + int m_nVoid1; + int m_nVoid2; + int m_nVoid3; + int m_nVoid4; + int m_nVoid5; + int m_nVoid6; + int m_nVoid7; + int m_nVoid8; + int m_nVoid9; +} modchelpers_t; + + +// ******************************************************** +// Information about the engine +// ******************************************************** +typedef struct engdata_s +{ + cl_enginefunc_t *pcl_enginefuncs; // functions exported by the engine + cl_enginefunc_dst_t *pg_engdstAddrs; // destination handlers for engine exports + cldll_func_t *pcl_funcs; // client exports + cldll_func_dst_t *pg_cldstAddrs; // client export destination handlers + struct modfuncs_s *pg_modfuncs; // engine's pointer to module functions + struct cmd_function_s **pcmd_functions; // list of all registered commands + void *pkeybindings; // all key bindings (not really a void *, but easier this way) + void (*pfnConPrintf)(char *, ...); // dump to console + struct cvar_s **pcvar_vars; // pointer to head of cvar list + struct glwstate_t *pglwstate; // OpenGl information + void *(*pfnSZ_GetSpace)(struct sizebuf_s *, int); // pointer to SZ_GetSpace + struct modfuncs_s *pmodfuncs; // &g_modfuncs + void *pfnGetProcAddress; // &GetProcAddress + void *pfnGetModuleHandle; // &GetModuleHandle + struct server_static_s *psvs; // &svs + struct client_static_s *pcls; // &cls + void (*pfnSV_DropClient)(struct client_s *, qboolean, char *, ...); // pointer to SV_DropClient + void (*pfnNetchan_Transmit)(struct netchan_s *, int, byte *); // pointer to Netchan_Transmit + void (*pfnNET_SendPacket)(enum netsrc_s sock, int length, void *data, netadr_t to); // &NET_SendPacket + struct cvar_s *(*pfnCvarFindVar)(const char *pchName); // pointer to Cvar_FindVar + int *phinstOpenGlEarly; // &g_hinstOpenGlEarly + + // Reserved for future expansion + void *pVoid0; // reserved for future expan + void *pVoid1; // reserved for future expan + void *pVoid2; // reserved for future expan + void *pVoid3; // reserved for future expan + void *pVoid4; // reserved for future expan + void *pVoid5; // reserved for future expan + void *pVoid6; // reserved for future expan + void *pVoid7; // reserved for future expan + void *pVoid8; // reserved for future expan + void *pVoid9; // reserved for future expan +} engdata_t; + + +// ******************************************************** +// Functions exposed by the security module +// ******************************************************** +typedef void (*PFN_LOADMOD)(char *pchModule); +typedef void (*PFN_CLOSEMOD)(void); +typedef int (*PFN_NCALL)(int ijump, int cnArg, ...); + +typedef void (*PFN_GETCLDSTADDRS)(cldll_func_dst_t *pcldstAddrs); +typedef void (*PFN_GETENGDSTADDRS)(cl_enginefunc_dst_t *pengdstAddrs); +typedef void (*PFN_MODULELOADED)(void); + +typedef void (*PFN_PROCESSOUTGOINGNET)(struct netchan_s *pchan, struct sizebuf_s *psizebuf); +typedef qboolean (*PFN_PROCESSINCOMINGNET)(struct netchan_s *pchan, struct sizebuf_s *psizebuf); + +typedef void (*PFN_TEXTURELOAD)(char *pszName, int dxWidth, int dyHeight, char *pbData); +typedef void (*PFN_MODELLOAD)(struct model_s *pmodel, void *pvBuf); + +typedef void (*PFN_FRAMEBEGIN)(void); +typedef void (*PFN_FRAMERENDER1)(void); +typedef void (*PFN_FRAMERENDER2)(void); + +typedef void (*PFN_SETMODSHELPERS)(modshelpers_t *pmodshelpers); +typedef void (*PFN_SETMODCHELPERS)(modchelpers_t *pmodchelpers); +typedef void (*PFN_SETENGDATA)(engdata_t *pengdata); + +typedef void (*PFN_CONNECTCLIENT)(int iPlayer); +typedef void (*PFN_RECORDIP)(unsigned int pnIP); +typedef void (*PFN_PLAYERSTATUS)(unsigned char *pbData, int cbData); + +typedef void (*PFN_SETENGINEVERSION)(int nVersion); + +// typedef class CMachine *(*PFN_PCMACHINE)(void); +typedef int (*PFN_PCMACHINE)(void); +typedef void (*PFN_SETIP)(int ijump); +typedef void (*PFN_EXECUTE)(void); + +typedef struct modfuncs_s +{ + // Functions for the pcode interpreter + PFN_LOADMOD m_pfnLoadMod; + PFN_CLOSEMOD m_pfnCloseMod; + PFN_NCALL m_pfnNCall; + + // API destination functions + PFN_GETCLDSTADDRS m_pfnGetClDstAddrs; + PFN_GETENGDSTADDRS m_pfnGetEngDstAddrs; + + // Miscellaneous functions + PFN_MODULELOADED m_pfnModuleLoaded; // Called right after the module is loaded + + // Functions for processing network traffic + PFN_PROCESSOUTGOINGNET m_pfnProcessOutgoingNet; // Every outgoing packet gets run through this + PFN_PROCESSINCOMINGNET m_pfnProcessIncomingNet; // Every incoming packet gets run through this + + // Resource functions + PFN_TEXTURELOAD m_pfnTextureLoad; // Called as each texture is loaded + PFN_MODELLOAD m_pfnModelLoad; // Called as each model is loaded + + // Functions called every frame + PFN_FRAMEBEGIN m_pfnFrameBegin; // Called at the beginning of each frame cycle + PFN_FRAMERENDER1 m_pfnFrameRender1; // Called at the beginning of the render loop + PFN_FRAMERENDER2 m_pfnFrameRender2; // Called at the end of the render loop + + // Module helper transfer + PFN_SETMODSHELPERS m_pfnSetModSHelpers; + PFN_SETMODCHELPERS m_pfnSetModCHelpers; + PFN_SETENGDATA m_pfnSetEngData; + + // Which version of the module is this? + int m_nVersion; + + // Miscellaneous game stuff + PFN_CONNECTCLIENT m_pfnConnectClient; // Called whenever a new client connects + PFN_RECORDIP m_pfnRecordIP; // Secure master has reported a new IP for us + PFN_PLAYERSTATUS m_pfnPlayerStatus; // Called whenever we receive a PlayerStatus packet + + // Recent additions + PFN_SETENGINEVERSION m_pfnSetEngineVersion; // 1 = patched engine + + // reserved for future expansion + int m_nVoid2; + int m_nVoid3; + int m_nVoid4; + int m_nVoid5; + int m_nVoid6; + int m_nVoid7; + int m_nVoid8; + int m_nVoid9; +} modfuncs_t; + +enum +{ + k_nEngineVersion15Base = 0, + k_nEngineVersion15Patch, + k_nEngineVersion16Base, + k_nEngineVersion16Validated // 1.6 engine with built-in validation +}; + +typedef struct validator_s +{ + int m_nRandomizer; // Random number to be XOR'd into all subsequent fields + int m_nSignature1; // First signature that identifies this structure + int m_nSignature2; // Second signature + int m_pbCode; // Beginning of the code block + int m_cbCode; // Size of the code block + int m_nChecksum; // Checksum of the code block + int m_nSpecial; // For engine, 1 if hw.dll, 0 if sw.dll. For client, pclfuncs checksum + int m_nCompensator; // Keeps the checksum correct +} validator_t; + + +#define k_nChecksumCompensator 0x36a8f09c // Don't change this value: it's hardcorded in cdll_int.cpp, + +#define k_nModuleVersionCur 0x43210004 diff --git a/dep/hlsdk/engine/FlightRecorder.h b/dep/hlsdk/engine/FlightRecorder.h new file mode 100644 index 0000000..66a6477 --- /dev/null +++ b/dep/hlsdk/engine/FlightRecorder.h @@ -0,0 +1,61 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "archtypes.h" + +class IRehldsFlightRecorder +{ +public: + virtual ~IRehldsFlightRecorder() { } + + virtual uint16 RegisterMessage(const char* module, const char *message, unsigned int version, bool inOut) = 0; + + virtual void StartMessage(uint16 msg, bool entrance) = 0; + virtual void EndMessage(uint16 msg, bool entrance) = 0; + + virtual void WriteInt8(int8 v) = 0; + virtual void WriteUInt8(uint8 v) = 0; + + virtual void WriteInt16(int16 v) = 0; + virtual void WriteUInt16(uint16 v) = 0; + + virtual void WriteInt32(int32 v) = 0; + virtual void WriteUInt32(uint32 v) = 0; + + virtual void WriteInt64(int64 v) = 0; + virtual void WriteUInt64(uint64 v) = 0; + + virtual void WriteFloat(float v) = 0; + virtual void WriteDouble(double v) = 0; + + virtual void WriteString(const char* s) = 0; + + virtual void WriteBuffer(const void* data ,unsigned int len) = 0; + +}; diff --git a/dep/hlsdk/engine/Sequence.h b/dep/hlsdk/engine/Sequence.h new file mode 100644 index 0000000..53d31b7 --- /dev/null +++ b/dep/hlsdk/engine/Sequence.h @@ -0,0 +1,201 @@ +//--------------------------------------------------------------------------- +// +// S c r i p t e d S e q u e n c e s +// +//--------------------------------------------------------------------------- +#ifndef _INCLUDE_SEQUENCE_H_ +#define _INCLUDE_SEQUENCE_H_ + + +#ifndef _DEF_BYTE_ +typedef unsigned char byte; +#endif + +//--------------------------------------------------------------------------- +// client_textmessage_t +//--------------------------------------------------------------------------- +typedef struct client_textmessage_s +{ + int effect; + byte r1, g1, b1, a1; // 2 colors for effects + byte r2, g2, b2, a2; + float x; + float y; + float fadein; + float fadeout; + float holdtime; + float fxtime; + const char *pName; + const char *pMessage; +} client_textmessage_t; + + +//-------------------------------------------------------------------------- +// sequenceDefaultBits_e +// +// Enumerated list of possible modifiers for a command. This enumeration +// is used in a bitarray controlling what modifiers are specified for a command. +//--------------------------------------------------------------------------- +enum sequenceModifierBits +{ + SEQUENCE_MODIFIER_EFFECT_BIT = (1 << 1), + SEQUENCE_MODIFIER_POSITION_BIT = (1 << 2), + SEQUENCE_MODIFIER_COLOR_BIT = (1 << 3), + SEQUENCE_MODIFIER_COLOR2_BIT = (1 << 4), + SEQUENCE_MODIFIER_FADEIN_BIT = (1 << 5), + SEQUENCE_MODIFIER_FADEOUT_BIT = (1 << 6), + SEQUENCE_MODIFIER_HOLDTIME_BIT = (1 << 7), + SEQUENCE_MODIFIER_FXTIME_BIT = (1 << 8), + SEQUENCE_MODIFIER_SPEAKER_BIT = (1 << 9), + SEQUENCE_MODIFIER_LISTENER_BIT = (1 << 10), + SEQUENCE_MODIFIER_TEXTCHANNEL_BIT = (1 << 11), +}; +typedef enum sequenceModifierBits sequenceModifierBits_e ; + + +//--------------------------------------------------------------------------- +// sequenceCommandEnum_e +// +// Enumerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandEnum_ +{ + SEQUENCE_COMMAND_ERROR = -1, + SEQUENCE_COMMAND_PAUSE = 0, + SEQUENCE_COMMAND_FIRETARGETS, + SEQUENCE_COMMAND_KILLTARGETS, + SEQUENCE_COMMAND_TEXT, + SEQUENCE_COMMAND_SOUND, + SEQUENCE_COMMAND_GOSUB, + SEQUENCE_COMMAND_SENTENCE, + SEQUENCE_COMMAND_REPEAT, + SEQUENCE_COMMAND_SETDEFAULTS, + SEQUENCE_COMMAND_MODIFIER, + SEQUENCE_COMMAND_POSTMODIFIER, + SEQUENCE_COMMAND_NOOP, + + SEQUENCE_MODIFIER_EFFECT, + SEQUENCE_MODIFIER_POSITION, + SEQUENCE_MODIFIER_COLOR, + SEQUENCE_MODIFIER_COLOR2, + SEQUENCE_MODIFIER_FADEIN, + SEQUENCE_MODIFIER_FADEOUT, + SEQUENCE_MODIFIER_HOLDTIME, + SEQUENCE_MODIFIER_FXTIME, + SEQUENCE_MODIFIER_SPEAKER, + SEQUENCE_MODIFIER_LISTENER, + SEQUENCE_MODIFIER_TEXTCHANNEL, +}; +typedef enum sequenceCommandEnum_ sequenceCommandEnum_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandType_e +// +// Typeerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandType_ +{ + SEQUENCE_TYPE_COMMAND, + SEQUENCE_TYPE_MODIFIER, +}; +typedef enum sequenceCommandType_ sequenceCommandType_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandMapping_s +// +// A mapping of a command enumerated-value to its name. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandMapping_ sequenceCommandMapping_s; +struct sequenceCommandMapping_ +{ + sequenceCommandEnum_e commandEnum; + const char* commandName; + sequenceCommandType_e commandType; +}; + + +//--------------------------------------------------------------------------- +// sequenceCommandLine_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandLine_ sequenceCommandLine_s; +struct sequenceCommandLine_ +{ + int commandType; // Specifies the type of command + client_textmessage_t clientMessage; // Text HUD message struct + char* speakerName; // Targetname of speaking entity + char* listenerName; // Targetname of entity being spoken to + char* soundFileName; // Name of sound file to play + char* sentenceName; // Name of sentences.txt to play + char* fireTargetNames; // List of targetnames to fire + char* killTargetNames; // List of targetnames to remove + float delay; // Seconds 'till next command + int repeatCount; // If nonzero, reset execution pointer to top of block (N times, -1 = infinite) + int textChannel; // Display channel on which text message is sent + int modifierBitField; // Bit field to specify what clientmessage fields are valid + sequenceCommandLine_s* nextCommandLine; // Next command (linked list) +}; + + +//--------------------------------------------------------------------------- +// sequenceEntry_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceEntry_ sequenceEntry_s; +struct sequenceEntry_ +{ + char* fileName; // Name of sequence file without .SEQ extension + char* entryName; // Name of entry label in file + sequenceCommandLine_s* firstCommand; // Linked list of commands in entry + sequenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? +}; + + + +//--------------------------------------------------------------------------- +// sentenceEntry_s +// Structure representing a single sentence of a group from a .SEQ +// file entry. Sentences are identical to entries in sentences.txt, but +// can be unique per level and are loaded/unloaded with the level. +//--------------------------------------------------------------------------- +typedef struct sentenceEntry_ sentenceEntry_s; +struct sentenceEntry_ +{ + char* data; // sentence data (ie "We have hostiles" ) + sentenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? + unsigned int index; // this entry's position in the file. +}; + +//-------------------------------------------------------------------------- +// sentenceGroupEntry_s +// Structure representing a group of sentences found in a .SEQ file. +// A sentence group is defined by all sentences with the same name, ignoring +// the number at the end of the sentence name. Groups enable a sentence +// to be picked at random across a group. +//-------------------------------------------------------------------------- +typedef struct sentenceGroupEntry_ sentenceGroupEntry_s; +struct sentenceGroupEntry_ +{ + char* groupName; // name of the group (ie CT_ALERT ) + unsigned int numSentences; // number of sentences in group + sentenceEntry_s* firstSentence; // head of linked list of sentences in group + sentenceGroupEntry_s* nextEntry; // next loaded group +}; + +//--------------------------------------------------------------------------- +// Function declarations +//--------------------------------------------------------------------------- +sequenceEntry_s* SequenceGet( const char* fileName, const char* entryName ); +void Sequence_ParseFile( const char* fileName, qboolean isGlobal ); +void Sequence_OnLevelLoad( const char* mapName ); +sentenceEntry_s* SequencePickSentence( const char *groupName, int pickMethod, int *picked ); + +#endif /* _INCLUDE_SEQUENCE_H_ */ diff --git a/dep/hlsdk/engine/archtypes.h b/dep/hlsdk/engine/archtypes.h new file mode 100644 index 0000000..e528a6d --- /dev/null +++ b/dep/hlsdk/engine/archtypes.h @@ -0,0 +1,66 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/#ifndef ARCHTYPES_H +#define ARCHTYPES_H + +#ifdef __x86_64__ +#define X64BITS +#endif + +#if defined( _WIN32 ) && (! defined( __MINGW32__ )) + +typedef __int8 int8; +typedef unsigned __int8 uint8; +typedef __int16 int16; +typedef unsigned __int16 uint16; +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; +typedef __int32 intp; // intp is an integer that can accomodate a pointer +typedef unsigned __int32 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) + +#else /* _WIN32 */ +typedef char int8; +typedef unsigned char uint8; +typedef short int16; +typedef unsigned short uint16; +typedef int int32; +typedef unsigned int uint32; +typedef long long int64; +typedef unsigned long long uint64; +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif /* else _WIN32 */ + +#endif /* ARCHTYPES_H */ diff --git a/dep/hlsdk/engine/bspfile.h b/dep/hlsdk/engine/bspfile.h new file mode 100644 index 0000000..b6d498c --- /dev/null +++ b/dep/hlsdk/engine/bspfile.h @@ -0,0 +1,160 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// header +#define Q1BSP_VERSION 29 // quake1 regular version (beta is 28) +#define HLBSP_VERSION 30 // half-life regular version + +#define MAX_MAP_HULLS 4 + +#define CONTENTS_ORIGIN -7 // removed at csg time +#define CONTENTS_CLIP -8 // changed to contents_solid +#define CONTENTS_CURRENT_0 -9 +#define CONTENTS_CURRENT_90 -10 +#define CONTENTS_CURRENT_180 -11 +#define CONTENTS_CURRENT_270 -12 +#define CONTENTS_CURRENT_UP -13 +#define CONTENTS_CURRENT_DOWN -14 + +#define CONTENTS_TRANSLUCENT -15 + +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_TEXTURES 2 +#define LUMP_VERTEXES 3 +#define LUMP_VISIBILITY 4 +#define LUMP_NODES 5 +#define LUMP_TEXINFO 6 +#define LUMP_FACES 7 +#define LUMP_LIGHTING 8 +#define LUMP_CLIPNODES 9 +#define LUMP_LEAFS 10 +#define LUMP_MARKSURFACES 11 +#define LUMP_EDGES 12 +#define LUMP_SURFEDGES 13 +#define LUMP_MODELS 14 + +#define HEADER_LUMPS 15 + +typedef struct lump_s +{ + int fileofs; + int filelen; +} lump_t; + +typedef struct dmodel_s +{ + float mins[3], maxs[3]; + float origin[3]; + int headnode[MAX_MAP_HULLS]; + int visleafs; // not including the solid leaf 0 + int firstface, numfaces; +} dmodel_t; + +typedef struct dheader_s +{ + int version; + lump_t lumps[15]; +} dheader_t; + +typedef struct dmiptexlump_s +{ + int _nummiptex; + int dataofs[4]; +} dmiptexlump_t; + +typedef struct miptex_s +{ + char name[16]; + unsigned width; + unsigned height; + unsigned offsets[4]; +} miptex_t; + +typedef struct dvertex_s +{ + float point[3]; +} dvertex_t; + +typedef struct dplane_s +{ + float normal[3]; + float dist; + int type; +} dplane_t; + +typedef struct dnode_s +{ + int planenum; + short children[2]; + short mins[3]; + short maxs[3]; + unsigned short firstface; + unsigned short numfaces; +} dnode_t; + +typedef struct dclipnode_s +{ + int planenum; + short children[2]; // negative numbers are contents +} dclipnode_t; + +typedef struct texinfo_s +{ + float vecs[2][4]; + int _miptex; + int flags; +} texinfo_t; + +typedef struct dedge_s +{ + unsigned short v[2]; +} dedge_t; + +typedef struct dface_s +{ + short planenum; + short side; + int firstedge; + short numedges; + short texinfo; + byte styles[4]; + int lightofs; +} dface_t; + +typedef struct dleaf_s +{ + int contents; + int visofs; + short mins[3]; + short maxs[3]; + unsigned short firstmarksurface; + unsigned short nummarksurfaces; + byte ambient_level[4]; +} dleaf_t; diff --git a/dep/hlsdk/engine/cdll_int.h b/dep/hlsdk/engine/cdll_int.h new file mode 100644 index 0000000..231aa87 --- /dev/null +++ b/dep/hlsdk/engine/cdll_int.h @@ -0,0 +1,326 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// cdll_int.h +// +// 4-23-98 +// JOHN: client dll interface declarations +// +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "const.h" + +// this file is included by both the engine and the client-dll, +// so make sure engine declarations aren't done twice + +enum +{ + SCRINFO_SCREENFLASH = 1, + SCRINFO_STRETCHED +}; + +typedef struct SCREENINFO_s +{ + int iSize; + int iWidth; + int iHeight; + int iFlags; + int iCharHeight; + short charWidths[256]; +} SCREENINFO; + +typedef struct client_data_s +{ + // fields that cannot be modified (ie. have no effect if changed) + vec3_t origin; + + // fields that can be changed by the cldll + vec3_t viewangles; + int iWeaponBits; +// int iAccessoryBits; + float fov; // field of view +} client_data_t; + +typedef struct client_sprite_s +{ + char szName[64]; + char szSprite[64]; + int hspr; + int iRes; + wrect_t rc; +} client_sprite_t; + +typedef struct hud_player_info_s +{ + char *name; + short ping; + byte thisplayer; // TRUE if this is the calling player + + byte spectator; + byte packetloss; + + char *model; + short topcolor; + short bottomcolor; + + uint64 m_nSteamID; +} hud_player_info_t; + +typedef struct module_s +{ + unsigned char ucMD5Hash[16]; // hash over code + qboolean fLoaded; // true if successfully loaded +} module_t; + +#ifndef IN_BUTTONS_H +#include "in_buttons.h" +#endif + +const int CLDLL_INTERFACE_VERSION = 7; + +extern void LoadSecurityModuleFromDisk(char * pszDllName); +extern void LoadSecurityModuleFromMemory( unsigned char * pCode, int nSize ); +extern void CloseSecurityModule(); + +extern void ClientDLL_Init( void ); // from cdll_int.c +extern void ClientDLL_Shutdown( void ); +extern void ClientDLL_HudInit( void ); +extern void ClientDLL_HudVidInit( void ); +extern void ClientDLL_UpdateClientData( void ); +extern void ClientDLL_Frame( double time ); +extern void ClientDLL_HudRedraw( int intermission ); +extern void ClientDLL_MoveClient( struct playermove_s *ppmove ); +extern void ClientDLL_ClientMoveInit( struct playermove_s *ppmove ); +extern char ClientDLL_ClientTextureType( char *name ); + +extern void ClientDLL_CreateMove( float frametime, struct usercmd_s *cmd, int active ); +extern void ClientDLL_ActivateMouse( void ); +extern void ClientDLL_DeactivateMouse( void ); +extern void ClientDLL_MouseEvent( int mstate ); +extern void ClientDLL_ClearStates( void ); +extern int ClientDLL_IsThirdPerson( void ); +extern void ClientDLL_GetCameraOffsets( float *ofs ); +extern int ClientDLL_GraphKeyDown( void ); +extern struct kbutton_s *ClientDLL_FindKey( const char *name ); +extern void ClientDLL_CAM_Think( void ); +extern void ClientDLL_IN_Accumulate( void ); +extern void ClientDLL_CalcRefdef( struct ref_params_s *pparams ); +extern int ClientDLL_AddEntity( int type, struct cl_entity_s *ent ); +extern void ClientDLL_CreateEntities( void ); + +extern void ClientDLL_DrawNormalTriangles( void ); +extern void ClientDLL_DrawTransparentTriangles( void ); +extern void ClientDLL_StudioEvent( const struct mstudioevent_s *event, const struct cl_entity_s *entity ); +extern void ClientDLL_PostRunCmd( struct local_state_s *from, struct local_state_s *to, struct usercmd_s *cmd, int runfuncs, double time, unsigned int random_seed ); +extern void ClientDLL_TxferLocalOverrides( struct entity_state_s *state, const struct clientdata_s *client ); +extern void ClientDLL_ProcessPlayerState( struct entity_state_s *dst, const struct entity_state_s *src ); +extern void ClientDLL_TxferPredictionData ( struct entity_state_s *ps, const struct entity_state_s *pps, struct clientdata_s *pcd, const struct clientdata_s *ppcd, struct weapon_data_s *wd, const struct weapon_data_s *pwd ); +extern void ClientDLL_ReadDemoBuffer( int size, unsigned char *buffer ); +extern int ClientDLL_ConnectionlessPacket( const struct netadr_s *net_from_, const char *args, char *response_buffer, int *response_buffer_size ); +extern int ClientDLL_GetHullBounds( int hullnumber, float *mins, float *maxs ); + +extern void ClientDLL_VGui_ConsolePrint(const char* text); + +extern int ClientDLL_Key_Event( int down, int keynum, const char *pszCurrentBinding ); +extern void ClientDLL_TempEntUpdate( double ft, double ct, double grav, struct tempent_s **ppFreeTE, struct tempent_s **ppActiveTE, int ( *addTEntity )( struct cl_entity_s *pEntity ), void ( *playTESound )( struct tempent_s *pTemp, float damp ) ); +extern struct cl_entity_s *ClientDLL_GetUserEntity( int index ); +extern void ClientDLL_VoiceStatus(int entindex, qboolean bTalking); +extern void ClientDLL_DirectorMessage( int iSize, void *pbuf ); +extern void ClientDLL_ChatInputPosition( int *x, int *y ); + +//#include "server.h" // server_static_t define for apiproxy +#include "APIProxy.h" + +extern cldll_func_t cl_funcs; +extern cl_enginefunc_t cl_engsrcProxies; + +#ifdef HOOK_ENGINE +#define g_engdstAddrs (*pg_engdstAddrs) +#define g_module (*pg_module) +#endif + +extern cl_enginefunc_dst_t g_engdstAddrs; +extern module_t g_module; + +// Module exports +extern modfuncs_t g_modfuncs; + +// Macros for exported engine funcs +#define RecEngSPR_Load(a) (g_engdstAddrs.pfnSPR_Load(&a)) +#define RecEngSPR_Frames(a) (g_engdstAddrs.pfnSPR_Frames(&a)) +#define RecEngSPR_Height(a, b) (g_engdstAddrs.pfnSPR_Height(&a, &b)) +#define RecEngSPR_Width(a, b) (g_engdstAddrs.pfnSPR_Width(&a, &b)) +#define RecEngSPR_Set(a, b, c, d) (g_engdstAddrs.pfnSPR_Set(&a, &b, &c, &d)) +#define RecEngSPR_Draw(a, b, c, d) (g_engdstAddrs.pfnSPR_Draw(&a, &b, &c, &d)) +#define RecEngSPR_DrawHoles(a, b, c, d) (g_engdstAddrs.pfnSPR_DrawHoles(&a, &b, &c, &d)) +#define RecEngSPR_DrawAdditive(a, b, c, d) (g_engdstAddrs.pfnSPR_DrawAdditive(&a, &b, &c, &d)) +#define RecEngSPR_EnableScissor(a, b, c, d) (g_engdstAddrs.pfnSPR_EnableScissor(&a, &b, &c, &d)) +#define RecEngSPR_DisableScissor() (g_engdstAddrs.pfnSPR_DisableScissor()) +#define RecEngSPR_GetList(a, b) (g_engdstAddrs.pfnSPR_GetList(&a, &b)) +#define RecEngDraw_FillRGBA(a, b, c, d, e, f, g, h) (g_engdstAddrs.pfnFillRGBA(&a, &b, &c, &d, &e, &f, &g, &h)) +#define RecEnghudGetScreenInfo(a) (g_engdstAddrs.pfnGetScreenInfo(&a)) +#define RecEngSetCrosshair(a, b, c, d, e) (g_engdstAddrs.pfnSetCrosshair(&a, &b, &c, &d, &e)) +#define RecEnghudRegisterVariable(a, b, c) (g_engdstAddrs.pfnRegisterVariable(&a, &b, &c)) +#define RecEnghudGetCvarFloat(a) (g_engdstAddrs.pfnGetCvarFloat(&a)) +#define RecEnghudGetCvarString(a) (g_engdstAddrs.pfnGetCvarString(&a)) +#define RecEnghudAddCommand(a, b) (g_engdstAddrs.pfnAddCommand(&a, &b)) +#define RecEnghudHookUserMsg(a, b) (g_engdstAddrs.pfnHookUserMsg(&a, &b)) +#define RecEnghudServerCmd(a) (g_engdstAddrs.pfnServerCmd(&a)) +#define RecEnghudClientCmd(a) (g_engdstAddrs.pfnClientCmd(&a)) +#define RecEngPrimeMusicStream(a, b) (g_engdstAddrs.pfnPrimeMusicStream(&a, &b)) +#define RecEnghudGetPlayerInfo(a, b) (g_engdstAddrs.pfnGetPlayerInfo(&a, &b)) +#define RecEnghudPlaySoundByName(a, b) (g_engdstAddrs.pfnPlaySoundByName(&a, &b)) +#define RecEnghudPlaySoundByNameAtPitch(a, b, c) (g_engdstAddrs.pfnPlaySoundByNameAtPitch(&a, &b, &c)) +#define RecEnghudPlaySoundVoiceByName(a, b) (g_engdstAddrs.pfnPlaySoundVoiceByName(&a, &b)) +#define RecEnghudPlaySoundByIndex(a, b) (g_engdstAddrs.pfnPlaySoundByIndex(&a, &b)) +#define RecEngAngleVectors(a, b, c, d) (g_engdstAddrs.pfnAngleVectors(&a, &b, &c, &d)) +#define RecEngTextMessageGet(a) (g_engdstAddrs.pfnTextMessageGet(&a)) +#define RecEngTextMessageDrawCharacter(a, b, c, d, e, f) (g_engdstAddrs.pfnDrawCharacter(&a, &b, &c, &d, &e, &f)) +#define RecEngDrawConsoleString(a, b, c) (g_engdstAddrs.pfnDrawConsoleString(&a, &b, &c)) +#define RecEngDrawSetTextColor(a, b, c) (g_engdstAddrs.pfnDrawSetTextColor(&a, &b, &c)) +#define RecEnghudDrawConsoleStringLen(a, b, c) (g_engdstAddrs.pfnDrawConsoleStringLen(&a, &b, &c)) +#define RecEnghudConsolePrint(a) (g_engdstAddrs.pfnConsolePrint(&a)) +#define RecEnghudCenterPrint(a) (g_engdstAddrs.pfnCenterPrint(&a)) +#define RecEnghudCenterX() (g_engdstAddrs.GetWindowCenterX()) +#define RecEnghudCenterY() (g_engdstAddrs.GetWindowCenterY()) +#define RecEnghudGetViewAngles(a) (g_engdstAddrs.GetViewAngles(&a)) +#define RecEnghudSetViewAngles(a) (g_engdstAddrs.SetViewAngles(&a)) +#define RecEnghudGetMaxClients() (g_engdstAddrs.GetMaxClients()) +#define RecEngCvar_SetValue(a, b) (g_engdstAddrs.Cvar_SetValue(&a, &b)) +#define RecEngCmd_Argc() (g_engdstAddrs.Cmd_Argc()) +#define RecEngCmd_Argv(a) (g_engdstAddrs.Cmd_Argv(&a)) +#define RecEngCon_Printf(a) (g_engdstAddrs.Con_Printf(&a)) +#define RecEngCon_DPrintf(a) (g_engdstAddrs.Con_DPrintf(&a)) +#define RecEngCon_NPrintf(a, b) (g_engdstAddrs.Con_NPrintf(&a, &b)) +#define RecEngCon_NXPrintf(a, b) (g_engdstAddrs.Con_NXPrintf(&a, &b)) +#define RecEnghudPhysInfo_ValueForKey(a) (g_engdstAddrs.PhysInfo_ValueForKey(&a)) +#define RecEnghudServerInfo_ValueForKey(a) (g_engdstAddrs.ServerInfo_ValueForKey(&a)) +#define RecEnghudGetClientMaxspeed() (g_engdstAddrs.GetClientMaxspeed()) +#define RecEnghudCheckParm(a, b) (g_engdstAddrs.CheckParm(&a, &b)) +#define RecEngKey_Event(a, b) (g_engdstAddrs.Key_Event(&a, &b)) +#define RecEnghudGetMousePosition(a, b) (g_engdstAddrs.GetMousePosition(&a, &b)) +#define RecEnghudIsNoClipping() (g_engdstAddrs.IsNoClipping()) +#define RecEnghudGetLocalPlayer() (g_engdstAddrs.GetLocalPlayer()) +#define RecEnghudGetViewModel() (g_engdstAddrs.GetViewModel()) +#define RecEnghudGetEntityByIndex(a) (g_engdstAddrs.GetEntityByIndex(&a)) +#define RecEnghudGetClientTime() (g_engdstAddrs.GetClientTime()) +#define RecEngV_CalcShake() (g_engdstAddrs.V_CalcShake()) +#define RecEngV_ApplyShake(a, b, c) (g_engdstAddrs.V_ApplyShake(&a, &b, &c)) +#define RecEngPM_PointContents(a, b) (g_engdstAddrs.PM_PointContents(&a, &b)) +#define RecEngPM_WaterEntity(a) (g_engdstAddrs.PM_WaterEntity(&a)) +#define RecEngPM_TraceLine(a, b, c, d, e) (g_engdstAddrs.PM_TraceLine(&a, &b, &c, &d, &e)) +#define RecEngCL_LoadModel(a, b) (g_engdstAddrs.CL_LoadModel(&a, &b)) +#define RecEngCL_CreateVisibleEntity(a, b) (g_engdstAddrs.CL_CreateVisibleEntity(&a, &b)) +#define RecEnghudGetSpritePointer(a) (g_engdstAddrs.GetSpritePointer(&a)) +#define RecEnghudPlaySoundByNameAtLocation(a, b, c) (g_engdstAddrs.pfnPlaySoundByNameAtLocation(&a, &b, &c)) +#define RecEnghudPrecacheEvent(a, b) (g_engdstAddrs.pfnPrecacheEvent(&a, &b)) +#define RecEnghudPlaybackEvent(a, b, c, d, e, f, g, h, i, j, k, l) (g_engdstAddrs.pfnPlaybackEvent(&a, &b, &c, &d, &e, &f, &g, &h, &i, &j, &k, &l)) +#define RecEnghudWeaponAnim(a, b) (g_engdstAddrs.pfnWeaponAnim(&a, &b)) +#define RecEngRandomFloat(a, b) (g_engdstAddrs.pfnRandomFloat(&a, &b)) +#define RecEngRandomLong(a, b) (g_engdstAddrs.pfnRandomLong(&a, &b)) +#define RecEngCL_HookEvent(a, b) (g_engdstAddrs.pfnHookEvent(&a, &b)) +#define RecEngCon_IsVisible() (g_engdstAddrs.Con_IsVisible()) +#define RecEnghudGetGameDir() (g_engdstAddrs.pfnGetGameDirectory()) +#define RecEngCvar_FindVar(a) (g_engdstAddrs.pfnGetCvarPointer(&a)) +#define RecEngKey_NameForBinding(a) (g_engdstAddrs.Key_LookupBinding(&a)) +#define RecEnghudGetLevelName() (g_engdstAddrs.pfnGetLevelName()) +#define RecEnghudGetScreenFade(a) (g_engdstAddrs.pfnGetScreenFade(&a)) +#define RecEnghudSetScreenFade(a) (g_engdstAddrs.pfnSetScreenFade(&a)) +#define RecEngVGuiWrap_GetPanel() (g_engdstAddrs.VGui_GetPanel()) +#define RecEngVGui_ViewportPaintBackground(a) (g_engdstAddrs.VGui_ViewportPaintBackground(&a)) +#define RecEngCOM_LoadFile(a, b, c) (g_engdstAddrs.COM_LoadFile(&a, &b, &c)) +#define RecEngCOM_ParseFile(a, b) (g_engdstAddrs.COM_ParseFile(&a, &b)) +#define RecEngCOM_FreeFile(a) (g_engdstAddrs.COM_FreeFile(&a)) +#define RecEngCL_IsSpectateOnly() (g_engdstAddrs.IsSpectateOnly()) +#define RecEngR_LoadMapSprite(a) (g_engdstAddrs.LoadMapSprite(&a)) +#define RecEngCOM_AddAppDirectoryToSearchPath(a, b) (g_engdstAddrs.COM_AddAppDirectoryToSearchPath(&a, &b)) +#define RecEngClientDLL_ExpandFileName(a, b, c) (g_engdstAddrs.COM_ExpandFilename(&a, &b, &c)) +#define RecEngPlayerInfo_ValueForKey(a, b) (g_engdstAddrs.PlayerInfo_ValueForKey(&a, &b)) +#define RecEngPlayerInfo_SetValueForKey(a, b) (g_engdstAddrs.PlayerInfo_SetValueForKey(&a, &b)) +#define RecEngGetPlayerUniqueID(a, b) (g_engdstAddrs.GetPlayerUniqueID(&a, &b)) +#define RecEngGetTrackerIDForPlayer(a) (g_engdstAddrs.GetTrackerIDForPlayer(&a)) +#define RecEngGetPlayerForTrackerID(a) (g_engdstAddrs.GetPlayerForTrackerID(&a)) +#define RecEnghudServerCmdUnreliable(a) (g_engdstAddrs.pfnServerCmdUnreliable(&a)) +#define RecEngGetMousePos(a) (g_engdstAddrs.pfnGetMousePos(&a)) +#define RecEngSetMousePos(a, b) (g_engdstAddrs.pfnSetMousePos(&a, &b)) +#define RecEngSetMouseEnable(a) (g_engdstAddrs.pfnSetMouseEnable(&a)) +#define RecEngSetFilterMode(a) (g_engdstAddrs.pfnSetFilterMode(&a)) +#define RecEngSetFilterColor(a,b,c) (g_engdstAddrs.pfnSetFilterColor(&a,&b,&c)) +#define RecEngSetFilterBrightness(a) (g_engdstAddrs.pfnSetFilterBrightness(&a)) +#define RecEngSequenceGet(a,b) (g_engdstAddrs.pfnSequenceGet(&a,&b)) +#define RecEngSPR_DrawGeneric(a,b,c,d,e,f,g,h) (g_engdstAddrs.pfnSPR_DrawGeneric(&a, &b, &c, &d, &e, &f, &g, &h)) +#define RecEngSequencePickSentence(a,b,c) (g_engdstAddrs.pfnSequencePickSentence(&a, &b, &c)) +#define RecEngLocalPlayerInfo_ValueForKey(a) (g_engdstAddrs.LocalPlayerInfo_ValueForKey(&a)) +#define RecEngProcessTutorMessageDecayBuffer(a, b) (g_engdstAddrs.pfnProcessTutorMessageDecayBuffer(&a, &b)) +#define RecEngConstructTutorMessageDecayBuffer(a, b) (g_engdstAddrs.pfnConstructTutorMessageDecayBuffer(&a, &b)) +#define RecEngResetTutorMessageDecayBuffer() (g_engdstAddrs.pfnResetTutorMessageDecayBuffer()) +#define RecEngDraw_FillRGBABlend(a, b, c, d, e, f, g, h) (g_engdstAddrs.pfnFillRGBABlend(&a, &b, &c, &d, &e, &f, &g, &h)) + +extern int Initialize(cl_enginefunc_t *pEnginefuncs, int iVersion); +extern int HUD_VidInit(); +extern void HUD_Init(); +extern int HUD_Redraw(float time, int intermission); +extern int HUD_UpdateClientData(client_data_t *pcldata, float flTime); +extern void HUD_Reset(); +extern void HUD_PlayerMove(playermove_t *ppmove, int server); +extern void HUD_PlayerMoveInit(playermove_t *ppmove); +extern char HUD_PlayerMoveTexture(char *name); +extern void IN_ActivateMouse(); +extern void IN_DeactivateMouse(); +extern void IN_MouseEvent(int mstate); +extern void IN_ClearStates(); +extern void IN_Accumulate(); +extern void CL_CreateMove(float frametime, usercmd_t *cmd, int active); +extern int CL_IsThirdPerson(); +extern void CL_CameraOffset(float *ofs); +extern void CAM_Think(); +extern kbutton_t *KB_Find(const char *name); +extern void V_CalcRefdef(ref_params_t *pparams); +extern int HUD_AddEntity(int type, cl_entity_t *ent, const char *modelname); +extern void HUD_CreateEntities(); +extern void HUD_DrawNormalTriangles(); +extern void HUD_DrawTransparentTriangles(); +extern void HUD_StudioEvent(const mstudioevent_s *event, const cl_entity_t *entity); +extern void HUD_Shutdown(); +extern void HUD_TxferLocalOverrides(entity_state_s *state, const clientdata_t *client); +extern void HUD_ProcessPlayerState(entity_state_t *dst, entity_state_t *src); +extern void HUD_TxferPredictionData(entity_state_t *ps, const entity_state_t *pps, clientdata_t *pcd, const clientdata_t *ppcd, weapon_data_t *wd, const weapon_data_t *pwd); +extern void Demo_ReadBuffer(int size, unsigned char *buffer); +extern int HUD_ConnectionlessPacket(const netadr_t *net_from, const char *args, char *response_buffer, int *response_buffer_size); +extern int HUD_GetHullBounds(int hullnumber, float *mins, float *maxs); +extern void HUD_Frame(double time); +extern int HUD_Key_Event(int down, int keynum, const char *pszCurrentBinding); +extern void HUD_PostRunCmd(local_state_t *from, local_state_t *to, usercmd_t *cmd, int runfuncs, double time, unsigned int random_seed); +extern void HUD_TempEntUpdate(double frametime, double client_time, double cl_gravity, TEMPENTITY **ppTempEntFree, TEMPENTITY **ppTempEntActive, int (*Callback_AddVisibleEntity)(cl_entity_t *), void (*Callback_TempEntPlaySound)(TEMPENTITY *, float)); +extern cl_entity_t *HUD_GetUserEntity(int index); +extern void HUD_VoiceStatus(int entindex, qboolean bTalking); +extern void HUD_DirectorMessage(int iSize, void *pbuf); +extern void HUD_WeaponsPostThink(local_state_t *from, local_state_t *to, usercmd_t *cmd, double time, unsigned int random_seed); +extern int HUD_GetStudioModelInterface(int version, r_studio_interface_t **ppinterface, engine_studio_api_t *pstudio); +extern void HUD_ChatInputPosition(int *x, int *y); +extern int HUD_GetPlayerTeam(int iplayer); +extern void *ClientFactory(); + +#ifdef __cplusplus +} +#endif + +extern float g_lastFOV; +extern bool g_bHoldingKnife; +extern bool g_bHoldingShield; diff --git a/dep/hlsdk/engine/client.h b/dep/hlsdk/engine/client.h new file mode 100644 index 0000000..18ffd13 --- /dev/null +++ b/dep/hlsdk/engine/client.h @@ -0,0 +1,364 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" +#include "common.h" +#include "custom.h" +#include "cl_entity.h" +#include "consistency.h" +#include "delta_packet.h" +#include "dlight.h" +#include "entity_state.h" +#include "event.h" +#include "info.h" +#include "net.h" +#include "keys.h" +#include "sound.h" +#include "screenfade.h" +#include "usercmd.h" +#include "model.h" +#include "kbutton.h" + +const int MAX_SCOREBOARDNAME = 32; +const int MAX_DEMOS = 32; + +typedef enum cactive_e +{ + ca_dedicated, + ca_disconnected, + ca_connecting, + ca_connected, + ca_uninitialized, + ca_active, +} cactive_t; + +typedef struct cmd_s +{ + usercmd_t cmd; + float senttime; + float receivedtime; + float frame_lerp; + qboolean processedfuncs; + qboolean heldback; + int sendsize; +} cmd_t; + +typedef struct frame_s +{ + double receivedtime; + double latency; + qboolean invalid; + qboolean choked; + entity_state_t playerstate[32]; + double time; + clientdata_t clientdata; + weapon_data_t weapondata[64]; + packet_entities_t packet_entities; + uint16 clientbytes; + uint16 playerinfobytes; + uint16 packetentitybytes; + uint16 tentitybytes; + uint16 soundbytes; + uint16 eventbytes; + uint16 usrbytes; + uint16 voicebytes; + uint16 msgbytes; +} frame_t; + +typedef struct player_info_s +{ + int userid; + char userinfo[MAX_INFO_STRING]; + char name[MAX_SCOREBOARDNAME]; + int spectator; + int ping; + int packet_loss; + char model[MAX_QPATH]; + int topcolor; + int bottomcolor; + int renderframe; + int gaitsequence; + float gaitframe; + float gaityaw; + vec3_t prevgaitorigin; + customization_t customdata; + char hashedcdkey[16]; + uint64 m_nSteamID; +} player_info_t; + +typedef struct soundfade_s +{ + int nStartPercent; + int nClientSoundFadePercent; + double soundFadeStartTime; + int soundFadeOutTime; + int soundFadeHoldTime; + int soundFadeInTime; +} soundfade_t; + +typedef struct client_static_s +{ + cactive_t state; + netchan_t netchan; + sizebuf_t datagram; + byte datagram_buf[MAX_DATAGRAM]; + double connect_time; + int connect_retry; + int challenge; + byte authprotocol; + int userid; + char trueaddress[32]; + float slist_time; + int signon; + char servername[MAX_PATH]; + char mapstring[64]; + char spawnparms[2048]; + char userinfo[256]; + float nextcmdtime; + int lastoutgoingcommand; + int demonum; + char demos[MAX_DEMOS][16]; + qboolean demorecording; + qboolean demoplayback; + qboolean timedemo; + float demostarttime; + int demostartframe; + int forcetrack; + FileHandle_t demofile; + FileHandle_t demoheader; + qboolean demowaiting; + qboolean demoappending; + char demofilename[MAX_PATH]; + int demoframecount; + int td_lastframe; + int td_startframe; + float td_starttime; + incomingtransfer_t dl; + float packet_loss; + double packet_loss_recalc_time; + int playerbits; + soundfade_t soundfade; + char physinfo[MAX_PHYSINFO_STRING]; + unsigned char md5_clientdll[16]; + netadr_t game_stream; + netadr_t connect_stream; + qboolean passive; + qboolean spectator; + qboolean director; + qboolean fSecureClient; + qboolean isVAC2Secure; + uint64_t GameServerSteamID; + int build_num; +} client_static_t; + +typedef struct client_state_s +{ + int max_edicts; + resource_t resourcesonhand; + resource_t resourcesneeded; + resource_t resourcelist[MAX_RESOURCE_LIST]; + int num_resources; + qboolean need_force_consistency_response; + char serverinfo[512]; + int servercount; + int validsequence; + int parsecount; + int parsecountmod; + int stats[32]; + int weapons; + usercmd_t cmd; + vec3_t viewangles; + vec3_t punchangle; + vec3_t crosshairangle; + vec3_t simorg; + vec3_t simvel; + vec3_t simangles; + vec3_t predicted_origins[64]; + vec3_t prediction_error; + float idealpitch; + vec3_t viewheight; + screenfade_t sf; + qboolean paused; + int onground; + int moving; + int waterlevel; + int usehull; + float maxspeed; + int pushmsec; + int light_level; + int intermission; + double mtime[2]; + double time; + double oldtime; + frame_t frames[64]; + cmd_t commands[64]; + local_state_t predicted_frames[64]; + int delta_sequence; + int playernum; + event_t event_precache[MAX_EVENTS]; + model_t *model_precache[MAX_MODELS]; + int model_precache_count; + sfx_s *sound_precache[MAX_SOUNDS]; + consistency_t consistency_list[MAX_CONSISTENCY_LIST]; + int num_consistency; + int highentity; + char levelname[40]; + int maxclients; + int gametype; + int viewentity; + model_t *worldmodel; + efrag_t *free_efrags; + int num_entities; + int num_statics; + cl_entity_t viewent; + int cdtrack; + int looptrack; + CRC32_t serverCRC; + unsigned char clientdllmd5[16]; + float weaponstarttime; + int weaponsequence; + int fPrecaching; + dlight_t *pLight; + player_info_t players[32]; + entity_state_t instanced_baseline[64]; + int instanced_baseline_number; + CRC32_t mapCRC; + event_state_t events; + char downloadUrl[128]; +} client_state_t; + +typedef enum CareerStateType_e +{ + CAREER_NONE = 0, + CAREER_LOADING = 1, + CAREER_PLAYING = 2, +} CareerStateType; + +extern keydest_t key_dest; +extern client_static_t *cls; +extern client_state_t *cl; + +extern playermove_t g_clmove; +extern qboolean cl_inmovie; + +extern cvar_t cl_name; +extern cvar_t rate_; +extern cvar_t console; + +void CL_RecordHUDCommand(const char *cmdname); +void R_DecalRemoveAll(int textureIndex); +void CL_CheckForResend(); +qboolean CL_CheckFile(sizebuf_t *msg, char *filename); +void CL_ClearClientState(); +void CL_Connect_f(); +void CL_DecayLights(); +void CL_Disconnect(); +void CL_Disconnect_f(); +void CL_EmitEntities(); +void CL_InitClosest(); +void CL_Init(); +void CL_Particle(vec_t *origin, int color, float life, int zpos, int zvel); +void CL_PredictMove(qboolean repredicting); +void CL_PrintLogos(); +void CL_ReadPackets(); +qboolean CL_RequestMissingResources(); +void CL_Move(); +void CL_SendConnectPacket(); +void CL_StopPlayback(); +void CL_UpdateSoundFade(); +void CL_AdjustClock(); +void CL_Save(const char *name); +void CL_HudMessage(const char *pMessage); + +int Key_CountBindings(); +void Key_WriteBindings(FileHandle_t f); +extern "C" void ClientDLL_UpdateClientData(); +extern "C" void ClientDLL_HudVidInit(); +void Chase_Init(); +void Key_Init(); +extern "C" void ClientDLL_Init(); +void Con_Shutdown(); +int DispatchDirectUserMsg(const char *pszName, int iSize, void *pBuf); +void CL_ShutDownUsrMessages(); +void CL_ShutDownClientStatic(); +extern "C" void ClientDLL_MoveClient(struct playermove_s *ppmove); +void CL_Shutdown(); +extern "C" void ClientDLL_Frame(double time); +extern "C" void ClientDLL_CAM_Think(); +void CL_InitEventSystem(); +void CL_CheckClientState(); +void CL_RedoPrediction(); +void CL_SetLastUpdate(); +void Con_NPrintf(int idx, const char *fmt, ...); +void CL_WriteMessageHistory(int starting_count, int cmd); +void CL_MoveSpectatorCamera(); +void CL_AddVoiceToDatagram(qboolean bFinal); +void CL_VoiceIdle(); +void PollDInputDevices(); +void CL_KeepConnectionActive(); +void CL_UpdateModuleC(); +void ConstructTutorMessageDecayBuffer(int *buffer, int bufferLength); +void ProcessTutorMessageDecayBuffer(int *buffer, int bufferLength); +int GetTimesTutorMessageShown(int id); +void RegisterTutorMessageShown(int mid); +void ResetTutorMessageDecayData(); +void SetCareerAudioState(int state); + +int EXT_FUNC VGuiWrap2_IsInCareerMatch(); +int EXT_FUNC VGuiWrap2_GetLocalizedStringLength(const char *label); +void VGuiWrap2_LoadingStarted(const char *resourceType, const char *resourceName); +void *VguiWrap2_GetCareerUI(); +void VguiWrap2_GetMouseDelta(int *x, int *y); +int EXT_FUNC VGuiWrap2_GetLocalizedStringLength(const char *label); +int EXT_FUNC VGuiWrap2_IsInCareerMatch(); +int VGuiWrap2_IsConsoleVisible(); +int VGuiWrap2_Key_Event(int down, int keynum, const char *pszCurrentBinding); +int VGuiWrap2_GameUIKeyPressed(); +int VGuiWrap2_IsGameUIVisible(); +int VGuiWrap2_CallEngineSurfaceAppHandler(void *event, void *userData); +int VGuiWrap2_UseVGUI1(); +void *VGuiWrap2_GetPanel(); +void VGuiWrap2_NotifyOfServerConnect(const char *game, int IP, int port); +void VGuiWrap2_LoadingFinished(const char *resourceType, const char *resourceName); +void VGuiWrap2_LoadingStarted(const char *resourceType, const char *resourceName); +void VGuiWrap2_ConDPrintf(const char *msg); +void VGuiWrap2_Startup(); +void VGuiWrap2_ConPrintf(const char *msg); +void VGuiWrap2_ClearConsole(); +void VGuiWrap2_HideConsole(); +void VGuiWrap2_ShowDemoPlayer(); +void VGuiWrap2_ShowConsole(); +void VGuiWrap2_HideGameUI(); +void VGuiWrap2_NotifyOfServerDisconnect(); +void VGuiWrap2_Paint(); +void VGuiWrap2_SetVisible(int state); +void VGuiWrap2_GetMouse(); +void VGuiWrap2_ReleaseMouse(); +void VGuiWrap2_Shutdown(); diff --git a/dep/hlsdk/engine/cmd.h b/dep/hlsdk/engine/cmd.h new file mode 100644 index 0000000..0efe45b --- /dev/null +++ b/dep/hlsdk/engine/cmd.h @@ -0,0 +1,50 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "archtypes.h" + +typedef void(*xcommand_t)(void); +typedef struct cmd_function_s +{ + struct cmd_function_s *next; + const char *name; + xcommand_t function; + int flags; +} cmd_function_t; + +typedef enum cmd_source_s +{ + src_client = 0, // came in over a net connection as a clc_stringcmd. host_client will be valid during this state. + src_command = 1, // from the command buffer. +} cmd_source_t; + +#define FCMD_HUD_COMMAND BIT(0) +#define FCMD_GAME_COMMAND BIT(1) +#define FCMD_WRAPPER_COMMAND BIT(2) diff --git a/dep/hlsdk/engine/common.cpp b/dep/hlsdk/engine/common.cpp new file mode 100644 index 0000000..58f939f --- /dev/null +++ b/dep/hlsdk/engine/common.cpp @@ -0,0 +1,56 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +// Fills "out" with the file name without path and extension. +void COM_FileBase(const char *in, char *out) +{ + const char *start, *end; + int len; + + *out = 0; + + len = Q_strlen(in); + if (len <= 0) + return; + + start = in + len - 1; + end = in + len; + while (start >= in && *start != '/' && *start != '\\') + { + if (*start == '.') + end = start; + start--; + } + start++; + + len = end - start; + Q_strncpy(out, start, len); + out[len] = 0; +} diff --git a/dep/hlsdk/engine/common.h b/dep/hlsdk/engine/common.h new file mode 100644 index 0000000..2e7e9a7 --- /dev/null +++ b/dep/hlsdk/engine/common.h @@ -0,0 +1,246 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "const.h" +#include "qlimits.h" +#include "bspfile.h" +#include "FileSystem.h" +#include "quakedef.h" +#include "usercmd.h" +#include "info.h" +#include "com_model.h" + +#define COM_TOKEN_LEN 1024 + +// Don't allow overflow +#define SIZEBUF_CHECK_OVERFLOW 0 +#define SIZEBUF_ALLOW_OVERFLOW BIT(0) +#define SIZEBUF_OVERFLOWED BIT(1) + +#define MAX_NUM_ARGVS 50 +#define NUM_SAFE_ARGVS 7 + +#define COM_COPY_CHUNK_SIZE 1024 +#define COM_MAX_CMD_LINE 256 + +typedef struct sizebuf_s +{ + const char *buffername; + uint16 flags; + byte *data; + int maxsize; + int cursize; +} sizebuf_t; + +typedef struct downloadtime_s +{ + qboolean bUsed; + float fTime; + int nBytesRemaining; +} downloadtime_t; + +typedef struct incomingtransfer_s +{ + qboolean doneregistering; + int percent; + qboolean downloadrequested; + downloadtime_t rgStats[8]; + int nCurStat; + int nTotalSize; + int nTotalToTransfer; + int nRemainingToTransfer; + float fLastStatusUpdate; + qboolean custom; +} incomingtransfer_t; + +extern char serverinfo[MAX_INFO_STRING]; + +extern char gpszVersionString[32]; +extern char gpszProductString[32]; + +typedef struct bf_read_s bf_read_t; +typedef struct bf_write_s bf_write_t; + +extern bf_read_t bfread; +extern bf_write_t bfwrite; + +extern int msg_badread; +extern int msg_readcount; + +extern qboolean bigendien; + +extern short(*BigShort)(short l); +extern short(*LittleShort)(short l); +extern int(*BigLong)(int l); +extern int(*LittleLong)(int l); +extern float(*BigFloat)(float l); +extern float(*LittleFloat)(float l); + +extern int com_argc; +extern char **com_argv; + +extern char com_token[COM_TOKEN_LEN]; + +extern qboolean com_ignorecolons; +extern qboolean s_com_token_unget; +extern char com_clientfallback[MAX_PATH]; +extern char com_gamedir[MAX_PATH]; +extern char com_cmdline[COM_MAX_CMD_LINE]; + +extern cache_user_t *loadcache; +extern unsigned char *loadbuf; +extern int loadsize; + +int build_number(void); +char *Info_Serverinfo(void); + +unsigned char COM_Nibble(char c); +void COM_HexConvert(const char *pszInput, int nInputLength, unsigned char *pOutput); +NOXREF char *COM_BinPrintf(unsigned char *buf, int nLen); +void COM_ExplainDisconnection(qboolean bPrint, char *fmt, ...); +NOXREF void COM_ExtendedExplainDisconnection(qboolean bPrint, char *fmt, ...); + +int LongSwap(int l); +short ShortSwap(short l); +short ShortNoSwap(short l); +int LongNoSwap(int l); +float FloatSwap(float f); +float FloatNoSwap(float f); + +void MSG_WriteChar(sizebuf_t *sb, int c); +void MSG_WriteByte(sizebuf_t *sb, int c); +void MSG_WriteShort(sizebuf_t *sb, int c); +void MSG_WriteWord(sizebuf_t *sb, int c); +void MSG_WriteLong(sizebuf_t *sb, int c); +void MSG_WriteFloat(sizebuf_t *sb, float f); +void MSG_WriteString(sizebuf_t *sb, const char *s); +void MSG_WriteBuf(sizebuf_t *sb, int iSize, void *buf); +void MSG_WriteAngle(sizebuf_t *sb, float f); +void MSG_WriteHiresAngle(sizebuf_t *sb, float f); +void MSG_WriteUsercmd(sizebuf_t *buf, usercmd_t *to, usercmd_t *from); +void COM_BitOpsInit(void); +void MSG_WriteOneBit(int nValue); +void MSG_StartBitWriting(sizebuf_t *buf); +NOXREF qboolean MSG_IsBitWriting(void); +void MSG_EndBitWriting(sizebuf_t *buf); +void MSG_WriteBits(uint32 data, int numbits); +void MSG_WriteSBits(int data, int numbits); +void MSG_WriteBitString(const char *p); +void MSG_WriteBitData(void *src, int length); +void MSG_WriteBitAngle(float fAngle, int numbits); +float MSG_ReadBitAngle(int numbits); +int MSG_CurrentBit(void); +NOXREF qboolean MSG_IsBitReading(void); +void MSG_StartBitReading(sizebuf_t *buf); +void MSG_EndBitReading(sizebuf_t *buf); +int MSG_ReadOneBit(void); +uint32 MSG_ReadBits(int numbits); +NOXREF uint32 MSG_PeekBits(int numbits); +int MSG_ReadSBits(int numbits); +NOXREF char *MSG_ReadBitString(void); +int MSG_ReadBitData(void *dest, int length); +NOXREF float MSG_ReadBitCoord(void); +void MSG_WriteBitCoord(const float f); +NOXREF void MSG_ReadBitVec3Coord(vec3_t fa); +void MSG_WriteBitVec3Coord(const vec3_t fa); +NOXREF float MSG_ReadCoord(void); +void MSG_WriteCoord(sizebuf_t *sb, const float f); +NOXREF void MSG_ReadVec3Coord(sizebuf_t *sb, vec3_t fa); +NOXREF void MSG_WriteVec3Coord(sizebuf_t *sb, const vec3_t fa); +void MSG_BeginReading(void); +int MSG_ReadChar(void); +int MSG_ReadByte(void); +int MSG_ReadShort(void); +NOXREF int MSG_ReadWord(void); +int MSG_ReadLong(void); +NOXREF float MSG_ReadFloat(void); +int MSG_ReadBuf(int iSize, void *pbuf); +char *MSG_ReadString(void); +char *MSG_ReadStringLine(void); +NOXREF float MSG_ReadAngle(void); +NOXREF float MSG_ReadHiresAngle(void); +void MSG_ReadUsercmd(usercmd_t *to, usercmd_t *from); + +void SZ_Alloc(const char *name, sizebuf_t *buf, int startsize); +void SZ_Clear(sizebuf_t *buf); +void *SZ_GetSpace(sizebuf_t *buf, int length); +void SZ_Write(sizebuf_t *buf, const void *data, int length); +void SZ_Print(sizebuf_t *buf, const char *data); + +NOXREF char *COM_SkipPath(char *pathname); +void COM_StripExtension(char *in, char *out); +char *COM_FileExtension(char *in); +void COM_FileBase(const char *in, char *out); +void COM_DefaultExtension(char *path, char *extension); +void COM_UngetToken(void); +char *COM_Parse(char *data); +char *COM_ParseLine(char *data); +int COM_TokenWaiting(char *buffer); +int COM_CheckParm(const char *parm); +void COM_InitArgv(int argc, char *argv[]); +void COM_Init(char *basedir); +char *va(char *format, ...); +char *vstr(vec_t *v); +NOXREF int memsearch(unsigned char *start, int count, int search); +NOXREF void COM_WriteFile(char *filename, void *data, int len); +void COM_FixSlashes(char *pname); +void COM_CreatePath(char *path); +NOXREF void COM_CopyFile(char *netpath, char *cachepath); +NOXREF int COM_ExpandFilename(char *filename); +int COM_FileSize(const char *filename); +unsigned char *COM_LoadFile(const char *path, int usehunk, int *pLength); +void COM_FreeFile(void *buffer); +void COM_CopyFileChunk(FileHandle_t dst, FileHandle_t src, int nSize); +NOXREF unsigned char *COM_LoadFileLimit(char *path, int pos, int cbmax, int *pcbread, FileHandle_t *phFile); +unsigned char *COM_LoadHunkFile(char *path); +unsigned char *COM_LoadTempFile(char *path, int *pLength); +void COM_LoadCacheFile(char *path, struct cache_user_s *cu); +NOXREF unsigned char *COM_LoadStackFile(char *path, void *buffer, int bufsize, int *length); +void COM_Shutdown(void); +NOXREF void COM_AddAppDirectory(char *pszBaseDir, const char *appName); +void COM_AddDefaultDir(char *pszDir); +void COM_StripTrailingSlash(char *ppath); +void COM_ParseDirectoryFromCmd(const char *pCmdName, char *pDirName, const char *pDefault); +qboolean COM_SetupDirectories(void); +void COM_CheckPrintMap(dheader_t *header, const char *mapname, qboolean bShowOutdated); +void COM_ListMaps(char *pszSubString); +void COM_Log(char *pszFile, char *fmt, ...); +unsigned char *COM_LoadFileForMe(const char *filename, int *pLength); +int COM_CompareFileTime(char *filename1, char *filename2, int *iCompare); +void COM_GetGameDir(char *szGameDir); +int COM_EntsForPlayerSlots(int nPlayers); +void COM_NormalizeAngles(vec_t *angles); +void COM_Munge(unsigned char *data, int len, int seq); +void COM_UnMunge(unsigned char *data, int len, int seq); +void COM_Munge2(unsigned char *data, int len, int seq); +void COM_UnMunge2(unsigned char *data, int len, int seq); +void COM_Munge3(unsigned char *data, int len, int seq); +NOXREF void COM_UnMunge3(unsigned char *data, int len, int seq); +unsigned int COM_GetApproxWavePlayLength(const char *filepath); diff --git a/dep/hlsdk/engine/consistency.h b/dep/hlsdk/engine/consistency.h new file mode 100644 index 0000000..7ca108c --- /dev/null +++ b/dep/hlsdk/engine/consistency.h @@ -0,0 +1,42 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +const int MAX_CONSISTENCY_LIST = 512; + +typedef struct consistency_s +{ + char *filename; + int issound; + int orig_index; + int value; + int check_type; + float mins[3]; + float maxs[3]; +} consistency_t; diff --git a/dep/hlsdk/engine/crc32c.cpp b/dep/hlsdk/engine/crc32c.cpp new file mode 100644 index 0000000..7e09002 --- /dev/null +++ b/dep/hlsdk/engine/crc32c.cpp @@ -0,0 +1,145 @@ +/* +Copyright (C) 2010 by Ronnie Sahlberg +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, see . +*/ + +#include "crc32c.h" +#include "sys_shared.h" +#include "immintrin.h" + +/*****************************************************************/ +/* */ +/* CRC LOOKUP TABLE */ +/* ================ */ +/* The following CRC lookup table was generated automagically */ +/* by the Rocksoft^tm Model CRC Algorithm Table Generation */ +/* Program V1.0 using the following model parameters: */ +/* */ +/* Width : 4 bytes. */ +/* Poly : 0x1EDC6F41L */ +/* Reverse : TRUE. */ +/* */ +/* For more information on the Rocksoft^tm Model CRC Algorithm, */ +/* see the document titled "A Painless Guide to CRC Error */ +/* Detection Algorithms" by Ross Williams */ +/* (ross@guest.adelaide.edu.au.). This document is likely to be */ +/* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ +/* */ +/*****************************************************************/ + +static uint32 crctable[256] = { + 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, + 0xC79A971FL, 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL, + 0x8AD958CFL, 0x78B2DBCCL, 0x6BE22838L, 0x9989AB3BL, + 0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, 0x5E133C24L, + 0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL, + 0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L, + 0x9A879FA0L, 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L, + 0x5D1D08BFL, 0xAF768BBCL, 0xBC267848L, 0x4E4DFB4BL, + 0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, 0x33ED7D2AL, + 0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L, + 0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L, + 0x6DFE410EL, 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL, + 0x30E349B1L, 0xC288CAB2L, 0xD1D83946L, 0x23B3BA45L, + 0xF779DEAEL, 0x05125DADL, 0x1642AE59L, 0xE4292D5AL, + 0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL, + 0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L, + 0x417B1DBCL, 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L, + 0x86E18AA3L, 0x748A09A0L, 0x67DAFA54L, 0x95B17957L, + 0xCBA24573L, 0x39C9C670L, 0x2A993584L, 0xD8F2B687L, + 0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L, + 0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L, + 0x96BF4DCCL, 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L, + 0xDBFC821CL, 0x2997011FL, 0x3AC7F2EBL, 0xC8AC71E8L, + 0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, 0x0F36E6F7L, + 0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L, + 0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L, + 0xEB1FCBADL, 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L, + 0x2C855CB2L, 0xDEEEDFB1L, 0xCDBE2C45L, 0x3FD5AF46L, + 0x7198540DL, 0x83F3D70EL, 0x90A324FAL, 0x62C8A7F9L, + 0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L, + 0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L, + 0x3CDB9BDDL, 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L, + 0x82F63B78L, 0x709DB87BL, 0x63CD4B8FL, 0x91A6C88CL, + 0x456CAC67L, 0xB7072F64L, 0xA457DC90L, 0x563C5F93L, + 0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L, + 0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL, + 0x92A8FC17L, 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L, + 0x55326B08L, 0xA759E80BL, 0xB4091BFFL, 0x466298FCL, + 0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, 0x0B21572CL, + 0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L, + 0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L, + 0x65D122B9L, 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL, + 0x2892ED69L, 0xDAF96E6AL, 0xC9A99D9EL, 0x3BC21E9DL, + 0xEF087A76L, 0x1D63F975L, 0x0E330A81L, 0xFC588982L, + 0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL, + 0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L, + 0x38CC2A06L, 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L, + 0xFF56BD19L, 0x0D3D3E1AL, 0x1E6DCDEEL, 0xEC064EEDL, + 0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, 0xD0DDD530L, + 0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL, + 0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL, + 0x8ECEE914L, 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L, + 0xD3D3E1ABL, 0x21B862A8L, 0x32E8915CL, 0xC083125FL, + 0x144976B4L, 0xE622F5B7L, 0xF5720643L, 0x07198540L, + 0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L, + 0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL, + 0xE330A81AL, 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL, + 0x24AA3F05L, 0xD6C1BC06L, 0xC5914FF2L, 0x37FACCF1L, + 0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, 0x7AB90321L, + 0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL, + 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, + 0x34F4F86AL, 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, + 0x79B737BAL, 0x8BDCB4B9L, 0x988C474DL, 0x6AE7C44EL, + 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L +}; + +uint32 crc32c_t8_nosse(uint32 iCRC, uint8 u8) { + return (iCRC >> 8) ^ crctable[(iCRC ^ u8) & 0xFF]; +} + +uint32 crc32c_t_nosse(uint32 iCRC, const uint8 *buf, int len) { + uint32 crc = iCRC; + while (len-- > 0) { + crc = (crc >> 8) ^ crctable[(crc ^ (*buf++)) & 0xFF]; + } + return crc; +} + +FUNC_TARGET("sse4.2") +uint32 crc32c_t8_sse(uint32 iCRC, uint8 u8) { + return _mm_crc32_u8(iCRC, u8); +} + +FUNC_TARGET("sse4.2") +uint32 crc32c_t_sse(uint32 iCRC, const uint8 *buf, unsigned int len) { + uint32 crc32cval = iCRC; + unsigned int i = 0; + + for (; i < (len >> 2); i += 4) { + crc32cval = _mm_crc32_u32(crc32cval, *(uint32*)&buf[i]); + } + + for (; i < len; i++) { + crc32cval = _mm_crc32_u8(crc32cval, buf[i]); + } + + return crc32cval; +} + +uint32 crc32c_t(uint32 iCRC, const uint8 *buf, unsigned int len) { + return cpuinfo.sse4_2 ? crc32c_t_sse(iCRC, buf, len) : crc32c_t_nosse(iCRC, buf, len); +} + +uint32 crc32c(const uint8 *buf, int len) { + return crc32c_t(0xffffffff, buf, len); +} diff --git a/dep/hlsdk/engine/crc32c.h b/dep/hlsdk/engine/crc32c.h new file mode 100644 index 0000000..892919b --- /dev/null +++ b/dep/hlsdk/engine/crc32c.h @@ -0,0 +1,22 @@ +/* +Copyright (C) 2010 by Ronnie Sahlberg +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, see . +*/ +#pragma once +#include "archtypes.h" + +extern uint32 crc32c_t8_nosse(uint32 iCRC, uint8 u8); +extern uint32 crc32c_t8_sse(uint32 iCRC, uint8 u8); +extern uint32 crc32c_t_nosse(uint32 iCRC, const uint8 *buf, int len); +extern uint32 crc32c_t_sse(uint32 iCRC, const uint8 *buf, unsigned int len); +extern uint32 crc32c_t(uint32 iCRC, const uint8 *buf, unsigned int len); +extern uint32 crc32c(const uint8 *buf, int len); diff --git a/dep/hlsdk/engine/custom.h b/dep/hlsdk/engine/custom.h new file mode 100644 index 0000000..333a4a0 --- /dev/null +++ b/dep/hlsdk/engine/custom.h @@ -0,0 +1,108 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// Customization.h +#pragma once + +#include "const.h" + +#define MAX_QPATH 64 // Must match value in quakedefs.h +#define MAX_RESOURCE_LIST 1280 + +///////////////// +// Customization +// passed to pfnPlayerCustomization +// For automatic downloading. +typedef enum +{ + t_sound = 0, + t_skin, + t_model, + t_decal, + t_generic, + t_eventscript, + t_world, // Fake type for world, is really t_model + rt_unk, + + rt_max +} resourcetype_t; + + +typedef struct +{ + int size; +} _resourceinfo_t; + +typedef struct resourceinfo_s +{ + _resourceinfo_t info[ rt_max ]; +} resourceinfo_t; + +#define RES_FATALIFMISSING (1<<0) // Disconnect if we can't get this file. +#define RES_WASMISSING (1<<1) // Do we have the file locally, did we get it ok? +#define RES_CUSTOM (1<<2) // Is this resource one that corresponds to another player's customization + // or is it a server startup resource. +#define RES_REQUESTED (1<<3) // Already requested a download of this one +#define RES_PRECACHED (1<<4) // Already precached +#define RES_ALWAYS (1<<5) // download always even if available on client +#define RES_UNK_6 (1<<6) // TODO: what is it? +#define RES_CHECKFILE (1<<7) // check file on client + +#include "crc.h" + +typedef struct resource_s +{ +#ifdef HOOK_HLTV + // NOTE HLTV: array szFileName declared on 260 cell, + // this changes necessary for compatibility hookers. + char szFileName[MAX_PATH]; +#else + char szFileName[MAX_QPATH]; // File name to download/precache. +#endif // HOOK_HLTV + + resourcetype_t type; // t_sound, t_skin, t_model, t_decal. + int nIndex; // For t_decals + int nDownloadSize; // Size in Bytes if this must be downloaded. + unsigned char ucFlags; + +// For handling client to client resource propagation + unsigned char rgucMD5_hash[16]; // To determine if we already have it. + unsigned char playernum; // Which player index this resource is associated with, if it's a custom resource. + + unsigned char rguc_reserved[ 32 ]; // For future expansion + struct resource_s *pNext; // Next in chain. + +#if !defined(HLTV) + struct resource_s *pPrev; +#else + unsigned char *data; +#endif // !defined(HLTV) +} resource_t; + +typedef struct customization_s +{ + qboolean bInUse; // Is this customization in use; + resource_t resource; // The resource_t for this customization + qboolean bTranslated; // Has the raw data been translated into a useable format? + // (e.g., raw decal .wad make into texture_t *) + int nUserData1; // Customization specific data + int nUserData2; // Customization specific data + void *pInfo; // Buffer that holds the data structure that references the data (e.g., the cachewad_t) + void *pBuffer; // Buffer that holds the data for the customization (the raw .wad data) + struct customization_s *pNext; // Next in chain +} customization_t; + +#define FCUST_FROMHPAK ( 1<<0 ) +#define FCUST_WIPEDATA ( 1<<1 ) +#define FCUST_IGNOREINIT ( 1<<2 ) diff --git a/dep/hlsdk/engine/customentity.h b/dep/hlsdk/engine/customentity.h new file mode 100644 index 0000000..0895bee --- /dev/null +++ b/dep/hlsdk/engine/customentity.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef CUSTOMENTITY_H +#define CUSTOMENTITY_H + +// Custom Entities + +// Start/End Entity is encoded as 12 bits of entity index, and 4 bits of attachment (4:12) +#define BEAMENT_ENTITY(x) ((x)&0xFFF) +#define BEAMENT_ATTACHMENT(x) (((x)>>12)&0xF) + +// Beam types, encoded as a byte +enum +{ + BEAM_POINTS = 0, + BEAM_ENTPOINT, + BEAM_ENTS, + BEAM_HOSE, +}; + +#define BEAM_FSINE 0x10 +#define BEAM_FSOLID 0x20 +#define BEAM_FSHADEIN 0x40 +#define BEAM_FSHADEOUT 0x80 + +#endif //CUSTOMENTITY_H diff --git a/dep/hlsdk/engine/d_local.h b/dep/hlsdk/engine/d_local.h new file mode 100644 index 0000000..c2d2f59 --- /dev/null +++ b/dep/hlsdk/engine/d_local.h @@ -0,0 +1,43 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef struct surfcache_s +{ + struct surfcache_s *next; + struct surfcache_s **owner; + int lightadj[4]; + int dlight; + int size; + unsigned width; + unsigned height; + float mipscale; + struct texture_s *texture; + unsigned char data[4]; +} surfcache_t; diff --git a/dep/hlsdk/engine/delta_packet.h b/dep/hlsdk/engine/delta_packet.h new file mode 100644 index 0000000..75bddc0 --- /dev/null +++ b/dep/hlsdk/engine/delta_packet.h @@ -0,0 +1,38 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "entity_state.h" + +typedef struct packet_entities_s +{ + int num_entities; + unsigned char flags[32]; + entity_state_t *entities; +} packet_entities_t; diff --git a/dep/hlsdk/engine/edict.h b/dep/hlsdk/engine/edict.h new file mode 100644 index 0000000..9a38993 --- /dev/null +++ b/dep/hlsdk/engine/edict.h @@ -0,0 +1,36 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#if !defined EDICT_H +#define EDICT_H +#ifdef _WIN32 +#pragma once +#endif +#define MAX_ENT_LEAFS 48 + +#include "progdefs.h" + +struct edict_s +{ + qboolean free; + int serialnumber; + link_t area; // linked to a division node or leaf + + int headnode; // -1 to use normal leaf check + int num_leafs; + short leafnums[MAX_ENT_LEAFS]; + + float freetime; // sv.time when the object was freed + + void* pvPrivateData; // Alloced and freed by engine, used by DLLs + + entvars_t v; // C exported fields from progs + + // other fields from progs come immediately after +}; + +#endif diff --git a/dep/hlsdk/engine/eiface.h b/dep/hlsdk/engine/eiface.h new file mode 100644 index 0000000..63f3b3c --- /dev/null +++ b/dep/hlsdk/engine/eiface.h @@ -0,0 +1,536 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#pragma once + +#include "archtypes.h" // DAL + +#ifdef HLDEMO_BUILD +#define INTERFACE_VERSION 001 +#else // !HLDEMO_BUILD, i.e., regular version of HL +#define INTERFACE_VERSION 140 +#endif // !HLDEMO_BUILD + +#include +#include "custom.h" +#include "cvardef.h" +#include "Sequence.h" +// +// Defines entity interface between engine and DLLs. +// This header file included by engine files and DLL files. +// +// Before including this header, DLLs must: +// include progdefs.h +// This is conveniently done for them in extdll.h +// + +/* +#ifdef _WIN32 +#define DLLEXPORT __stdcall EXT_FUNC +#else +#define DLLEXPORT __attribute__ ((visibility("default"))) EXT_FUNC +#endif +*/ + +enum ALERT_TYPE +{ + at_notice, + at_console, // same as at_notice, but forces a ConPrintf, not a message box + at_aiconsole, // same as at_console, but only shown if developer level is 2! + at_warning, + at_error, + at_logged // Server print to console ( only in multiplayer games ). +}; + +// 4-22-98 JOHN: added for use in pfnClientPrintf +enum PRINT_TYPE +{ + print_console, + print_center, + print_chat, +}; + +// For integrity checking of content on clients +enum FORCE_TYPE +{ + force_exactfile, // File on client must exactly match server's file + force_model_samebounds, // For model files only, the geometry must fit in the same bbox + force_model_specifybounds, // For model files only, the geometry must fit in the specified bbox + force_model_specifybounds_if_avail, // For Steam model files only, the geometry must fit in the specified bbox (if the file is available) +}; + +// Returned by TraceLine +struct TraceResult +{ + int fAllSolid; // if true, plane is not valid + int fStartSolid; // if true, the initial point was in a solid area + int fInOpen; + int fInWater; + float flFraction; // time completed, 1.0 = didn't hit anything + vec3_t vecEndPos; // final position + float flPlaneDist; + vec3_t vecPlaneNormal; // surface normal at impact + edict_t *pHit; // entity the surface is on + int iHitgroup; // 0 == generic, non zero is specific body part +}; + +// CD audio status +typedef struct +{ + int fPlaying;// is sound playing right now? + int fWasPlaying;// if not, CD is paused if WasPlaying is true. + int fInitialized; + int fEnabled; + int fPlayLooping; + float cdvolume; + //BYTE remap[100]; + int fCDRom; + int fPlayTrack; +} CDStatus; + +#include "../common/crc.h" + + +// Engine hands this to DLLs for functionality callbacks +typedef struct enginefuncs_s +{ + int (*pfnPrecacheModel) (const char* s); + int (*pfnPrecacheSound) (const char* s); + void (*pfnSetModel) (edict_t *e, const char *m); + int (*pfnModelIndex) (const char *m); + int (*pfnModelFrames) (int modelIndex); + void (*pfnSetSize) (edict_t *e, const float *rgflMin, const float *rgflMax); + void (*pfnChangeLevel) (const char* s1, const char* s2); + void (*pfnGetSpawnParms) (edict_t *ent); + void (*pfnSaveSpawnParms) (edict_t *ent); + float (*pfnVecToYaw) (const float *rgflVector); + void (*pfnVecToAngles) (const float *rgflVectorIn, float *rgflVectorOut); + void (*pfnMoveToOrigin) (edict_t *ent, const float *pflGoal, float dist, int iMoveType); + void (*pfnChangeYaw) (edict_t* ent); + void (*pfnChangePitch) (edict_t* ent); + edict_t* (*pfnFindEntityByString) (edict_t *pEdictStartSearchAfter, const char *pszField, const char *pszValue); + int (*pfnGetEntityIllum) (edict_t* pEnt); + edict_t* (*pfnFindEntityInSphere) (edict_t *pEdictStartSearchAfter, const float *org, float rad); + edict_t* (*pfnFindClientInPVS) (edict_t *pEdict); + edict_t* (*pfnEntitiesInPVS) (edict_t *pplayer); + void (*pfnMakeVectors) (const float *rgflVector); + void (*pfnAngleVectors) (const float *rgflVector, float *forward, float *right, float *up); + edict_t* (*pfnCreateEntity) (void); + void (*pfnRemoveEntity) (edict_t* e); + edict_t* (*pfnCreateNamedEntity) (int className); + void (*pfnMakeStatic) (edict_t *ent); + int (*pfnEntIsOnFloor) (edict_t *e); + int (*pfnDropToFloor) (edict_t* e); + int (*pfnWalkMove) (edict_t *ent, float yaw, float dist, int iMode); + void (*pfnSetOrigin) (edict_t *e, const float *rgflOrigin); + void (*pfnEmitSound) (edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch); + void (*pfnEmitAmbientSound) (edict_t *entity, float *pos, const char *samp, float vol, float attenuation, int fFlags, int pitch); + void (*pfnTraceLine) (const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceToss) (edict_t* pent, edict_t* pentToIgnore, TraceResult *ptr); + int (*pfnTraceMonsterHull) (edict_t *pEdict, const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceHull) (const float *v1, const float *v2, int fNoMonsters, int hullNumber, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceModel) (const float *v1, const float *v2, int hullNumber, edict_t *pent, TraceResult *ptr); + const char *(*pfnTraceTexture) (edict_t *pTextureEntity, const float *v1, const float *v2 ); + void (*pfnTraceSphere) (const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnGetAimVector) (edict_t* ent, float speed, float *rgflReturn); + void (*pfnServerCommand) (const char* str); + void (*pfnServerExecute) (void); + void (*pfnClientCommand) (edict_t* pEdict, const char* szFmt, ...); + void (*pfnParticleEffect) (const float *org, const float *dir, float color, float count); + void (*pfnLightStyle) (int style, const char* val); + int (*pfnDecalIndex) (const char *name); + int (*pfnPointContents) (const float *rgflVector); + void (*pfnMessageBegin) (int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); + void (*pfnMessageEnd) (void); + void (*pfnWriteByte) (int iValue); + void (*pfnWriteChar) (int iValue); + void (*pfnWriteShort) (int iValue); + void (*pfnWriteLong) (int iValue); + void (*pfnWriteAngle) (float flValue); + void (*pfnWriteCoord) (float flValue); + void (*pfnWriteString) (const char *sz); + void (*pfnWriteEntity) (int iValue); + void (*pfnCVarRegister) (cvar_t *pCvar); + float (*pfnCVarGetFloat) (const char *szVarName); + const char* (*pfnCVarGetString) (const char *szVarName); + void (*pfnCVarSetFloat) (const char *szVarName, float flValue); + void (*pfnCVarSetString) (const char *szVarName, const char *szValue); + void (*pfnAlertMessage) (ALERT_TYPE atype, const char *szFmt, ...); + void (*pfnEngineFprintf) (void *pfile, const char *szFmt, ...); + void* (*pfnPvAllocEntPrivateData) (edict_t *pEdict, int32 cb); + void* (*pfnPvEntPrivateData) (edict_t *pEdict); + void (*pfnFreeEntPrivateData) (edict_t *pEdict); + const char* (*pfnSzFromIndex) (int iString); + int (*pfnAllocString) (const char *szValue); + struct entvars_s* (*pfnGetVarsOfEnt) (edict_t *pEdict); + edict_t* (*pfnPEntityOfEntOffset) (int iEntOffset); + int (*pfnEntOffsetOfPEntity) (const edict_t *pEdict); + int (*pfnIndexOfEdict) (const edict_t *pEdict); + edict_t* (*pfnPEntityOfEntIndex) (int iEntIndex); + edict_t* (*pfnFindEntityByVars) (struct entvars_s* pvars); + void* (*pfnGetModelPtr) (edict_t* pEdict); + int (*pfnRegUserMsg) (const char *pszName, int iSize); + void (*pfnAnimationAutomove) (const edict_t* pEdict, float flTime); + void (*pfnGetBonePosition) (const edict_t* pEdict, int iBone, float *rgflOrigin, float *rgflAngles ); + uint32 (*pfnFunctionFromName) ( const char *pName ); + const char *(*pfnNameForFunction) ( uint32 function ); + void (*pfnClientPrintf) ( edict_t* pEdict, PRINT_TYPE ptype, const char *szMsg ); // JOHN: engine callbacks so game DLL can print messages to individual clients + void (*pfnServerPrint) ( const char *szMsg ); + const char *(*pfnCmd_Args) ( void ); // these 3 added + const char *(*pfnCmd_Argv) ( int argc ); // so game DLL can easily + int (*pfnCmd_Argc) ( void ); // access client 'cmd' strings + void (*pfnGetAttachment) (const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles ); + void (*pfnCRC32_Init) (CRC32_t *pulCRC); + void (*pfnCRC32_ProcessBuffer) (CRC32_t *pulCRC, void *p, int len); + void (*pfnCRC32_ProcessByte) (CRC32_t *pulCRC, unsigned char ch); + CRC32_t (*pfnCRC32_Final) (CRC32_t pulCRC); + int32 (*pfnRandomLong) (int32 lLow, int32 lHigh); + float (*pfnRandomFloat) (float flLow, float flHigh); + void (*pfnSetView) (const edict_t *pClient, const edict_t *pViewent ); + float (*pfnTime) ( void ); + void (*pfnCrosshairAngle) (const edict_t *pClient, float pitch, float yaw); + byte * (*pfnLoadFileForMe) (const char *filename, int *pLength); + void (*pfnFreeFile) (void *buffer); + void (*pfnEndSection) (const char *pszSectionName); // trigger_endsection + int (*pfnCompareFileTime) (char *filename1, char *filename2, int *iCompare); + void (*pfnGetGameDir) (char *szGetGameDir); + void (*pfnCvar_RegisterVariable) (cvar_t *variable); + void (*pfnFadeClientVolume) (const edict_t *pEdict, int fadePercent, int fadeOutSeconds, int holdTime, int fadeInSeconds); + void (*pfnSetClientMaxspeed) (edict_t *pEdict, float fNewMaxspeed); + edict_t * (*pfnCreateFakeClient) (const char *netname); // returns NULL if fake client can't be created + void (*pfnRunPlayerMove) (edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec ); + int (*pfnNumberOfEntities) (void); + char* (*pfnGetInfoKeyBuffer) (edict_t *e); // passing in NULL gets the serverinfo + char* (*pfnInfoKeyValue) (char *infobuffer, const char *key); + void (*pfnSetKeyValue) (char *infobuffer, const char *key, const char *value); + void (*pfnSetClientKeyValue) (int clientIndex, char *infobuffer, const char *key, const char *value); + int (*pfnIsMapValid) (const char *filename); + void (*pfnStaticDecal) ( const float *origin, int decalIndex, int entityIndex, int modelIndex ); + int (*pfnPrecacheGeneric) (const char* s); + int (*pfnGetPlayerUserId) (edict_t *e ); // returns the server assigned userid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients + void (*pfnBuildSoundMsg) (edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); + int (*pfnIsDedicatedServer) (void);// is this a dedicated server? + cvar_t *(*pfnCVarGetPointer) (const char *szVarName); + unsigned int (*pfnGetPlayerWONId) (edict_t *e); // returns the server assigned WONid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients + + // YWB 8/1/99 TFF Physics additions + void (*pfnInfo_RemoveKey) ( char *s, const char *key ); + const char *(*pfnGetPhysicsKeyValue) ( const edict_t *pClient, const char *key ); + void (*pfnSetPhysicsKeyValue) ( const edict_t *pClient, const char *key, const char *value ); + const char *(*pfnGetPhysicsInfoString) ( const edict_t *pClient ); + unsigned short (*pfnPrecacheEvent) ( int type, const char*psz ); + void (*pfnPlaybackEvent) ( int flags, const edict_t *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); + + unsigned char *(*pfnSetFatPVS) ( float *org ); + unsigned char *(*pfnSetFatPAS) ( float *org ); + + int (*pfnCheckVisibility ) ( edict_t *entity, unsigned char *pset ); + + void (*pfnDeltaSetField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaUnsetField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaAddEncoder) ( const char *name, void (*conditionalencode)( struct delta_s *pFields, const unsigned char *from, const unsigned char *to ) ); + int (*pfnGetCurrentPlayer) ( void ); + int (*pfnCanSkipPlayer) ( const edict_t *player ); + int (*pfnDeltaFindField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaSetFieldByIndex) ( struct delta_s *pFields, int fieldNumber ); + void (*pfnDeltaUnsetFieldByIndex)( struct delta_s *pFields, int fieldNumber ); + + void (*pfnSetGroupMask) ( int mask, int op ); + + int (*pfnCreateInstancedBaseline) ( int classname, struct entity_state_s *baseline ); + void (*pfnCvar_DirectSet) ( struct cvar_s *var, const char *value ); + + // Forces the client and server to be running with the same version of the specified file + // ( e.g., a player model ). + // Calling this has no effect in single player + void (*pfnForceUnmodified) ( FORCE_TYPE type, float *mins, float *maxs, const char *filename ); + + void (*pfnGetPlayerStats) ( const edict_t *pClient, int *ping, int *packet_loss ); + + void (*pfnAddServerCommand) ( const char *cmd_name, void (*function) (void) ); + + // For voice communications, set which clients hear eachother. + // NOTE: these functions take player entity indices (starting at 1). + qboolean (*pfnVoice_GetClientListening)(int iReceiver, int iSender); + qboolean (*pfnVoice_SetClientListening)(int iReceiver, int iSender, qboolean bListen); + + const char *(*pfnGetPlayerAuthId) ( edict_t *e ); + + // PSV: Added for CZ training map +// const char *(*pfnKeyNameForBinding) ( const char* pBinding ); + + sequenceEntry_s* (*pfnSequenceGet) ( const char* fileName, const char* entryName ); + sentenceEntry_s* (*pfnSequencePickSentence) ( const char* groupName, int pickMethod, int *picked ); + + // LH: Give access to filesize via filesystem + int (*pfnGetFileSize) ( const char *filename ); + + unsigned int (*pfnGetApproxWavePlayLen) (const char *filepath); + // MDC: Added for CZ career-mode + int (*pfnIsCareerMatch) ( void ); + + // BGC: return the number of characters of the localized string referenced by using "label" + int (*pfnGetLocalizedStringLength) (const char *label); + + // BGC: added to facilitate persistent storage of tutor message decay values for + // different career game profiles. Also needs to persist regardless of mp.dll being + // destroyed and recreated. + void (*pfnRegisterTutorMessageShown) (int mid); + int (*pfnGetTimesTutorMessageShown) (int mid); + void (*pfnProcessTutorMessageDecayBuffer) (int *buffer, int bufferLength); + void (*pfnConstructTutorMessageDecayBuffer) (int *buffer, int bufferLength); + void (*pfnResetTutorMessageDecayData) ( void ); + + // Added 2005/08/11 (no SDK update): + void(*pfnQueryClientCvarValue) (const edict_t *player, const char *cvarName); + + // Added 2005/11/21 (no SDK update): + void(*pfnQueryClientCvarValue2) (const edict_t *player, const char *cvarName, int requestID); + + // Added 2009/06/19 (no SDK update): + int(*pfnEngCheckParm) (const char *pchCmdLineToken, char **ppnext); +} enginefuncs_t; + + +// ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138 + +// Passed to pfnKeyValue +typedef struct KeyValueData_s +{ + char *szClassName; // in: entity classname + char *szKeyName; // in: name of key + char *szValue; // in: value of key + qboolean fHandled; // out: DLL sets to true if key-value pair was understood +} KeyValueData; + + +typedef struct +{ + char mapName[ 32 ]; + char landmarkName[ 32 ]; + edict_t *pentLandmark; + vec3_t vecLandmarkOrigin; +} LEVELLIST; +#define MAX_LEVEL_CONNECTIONS 16 // These are encoded in the lower 16bits of ENTITYTABLE->flags + +typedef struct +{ + int id; // Ordinal ID of this entity (used for entity <--> pointer conversions) + edict_t *pent; // Pointer to the in-game entity + + int location; // Offset from the base data of this entity + int size; // Byte size of this entity's data + int flags; // This could be a short -- bit mask of transitions that this entity is in the PVS of + string_t classname; // entity class name + +} ENTITYTABLE; + +#define FENTTABLE_PLAYER 0x80000000 +#define FENTTABLE_REMOVED 0x40000000 +#define FENTTABLE_MOVEABLE 0x20000000 +#define FENTTABLE_GLOBAL 0x10000000 + +typedef struct saverestore_s SAVERESTOREDATA; + +#ifdef _WIN32 +typedef +#endif +struct saverestore_s +{ + char *pBaseData; // Start of all entity save data + char *pCurrentData; // Current buffer pointer for sequential access + int size; // Current data size + int bufferSize; // Total space for data + int tokenSize; // Size of the linear list of tokens + int tokenCount; // Number of elements in the pTokens table + char **pTokens; // Hash table of entity strings (sparse) + int currentIndex; // Holds a global entity table ID + int tableCount; // Number of elements in the entity table + int connectionCount;// Number of elements in the levelList[] + ENTITYTABLE *pTable; // Array of ENTITYTABLE elements (1 for each entity) + LEVELLIST levelList[ MAX_LEVEL_CONNECTIONS ]; // List of connections from this level + + // smooth transition + int fUseLandmark; + char szLandmarkName[20];// landmark we'll spawn near in next level + vec3_t vecLandmarkOffset;// for landmark transitions + float time; + char szCurrentMapName[32]; // To check global entities + +} +#ifdef _WIN32 +SAVERESTOREDATA +#endif +; + +typedef enum _fieldtypes +{ + FIELD_FLOAT = 0, // Any floating point value + FIELD_STRING, // A string ID (return from ALLOC_STRING) + FIELD_ENTITY, // An entity offset (EOFFSET) + FIELD_CLASSPTR, // CBaseEntity * + FIELD_EHANDLE, // Entity handle + FIELD_EVARS, // EVARS * + FIELD_EDICT, // edict_t *, or edict_t * (same thing) + FIELD_VECTOR, // Any vector + FIELD_POSITION_VECTOR, // A world coordinate (these are fixed up across level transitions automagically) + FIELD_POINTER, // Arbitrary data pointer... to be removed, use an array of FIELD_CHARACTER + FIELD_INTEGER, // Any integer or enum + FIELD_FUNCTION, // A class function pointer (Think, Use, etc) + FIELD_BOOLEAN, // boolean, implemented as an int, I may use this as a hint for compression + FIELD_SHORT, // 2 byte integer + FIELD_CHARACTER, // a byte + FIELD_TIME, // a floating point time (these are fixed up automatically too!) + FIELD_MODELNAME, // Engine string that is a model name (needs precache) + FIELD_SOUNDNAME, // Engine string that is a sound name (needs precache) + + FIELD_TYPECOUNT, // MUST BE LAST +} FIELDTYPE; + +#if !defined(offsetof) && !defined(GNUC) +#define offsetof(s,m) (size_t)&(((s *)0)->m) +#endif + +#define _FIELD(type,name,fieldtype,count,flags) { fieldtype, #name, offsetof(type, name), count, flags } +#define DEFINE_FIELD(type,name,fieldtype) _FIELD(type, name, fieldtype, 1, 0) +#define DEFINE_ARRAY(type,name,fieldtype,count) _FIELD(type, name, fieldtype, count, 0) +#define DEFINE_ENTITY_FIELD(name,fieldtype) _FIELD(entvars_t, name, fieldtype, 1, 0 ) +#define DEFINE_ENTITY_GLOBAL_FIELD(name,fieldtype) _FIELD(entvars_t, name, fieldtype, 1, FTYPEDESC_GLOBAL ) +#define DEFINE_GLOBAL_FIELD(type,name,fieldtype) _FIELD(type, name, fieldtype, 1, FTYPEDESC_GLOBAL ) + + +#define FTYPEDESC_GLOBAL 0x0001 // This field is masked for global entity save/restore + +typedef struct +{ + FIELDTYPE fieldType; + char *fieldName; + int fieldOffset; + short fieldSize; + short flags; +} TYPEDESCRIPTION; + +#ifndef ARRAYSIZE +#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) +#endif + +typedef struct +{ + // Initialize/shutdown the game (one-time call after loading of game .dll ) + void (*pfnGameInit) ( void ); + int (*pfnSpawn) ( edict_t *pent ); + void (*pfnThink) ( edict_t *pent ); + void (*pfnUse) ( edict_t *pentUsed, edict_t *pentOther ); + void (*pfnTouch) ( edict_t *pentTouched, edict_t *pentOther ); + void (*pfnBlocked) ( edict_t *pentBlocked, edict_t *pentOther ); + void (*pfnKeyValue) ( edict_t *pentKeyvalue, KeyValueData *pkvd ); + void (*pfnSave) ( edict_t *pent, SAVERESTOREDATA *pSaveData ); + int (*pfnRestore) ( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity ); + void (*pfnSetAbsBox) ( edict_t *pent ); + + void (*pfnSaveWriteFields) ( SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int ); + void (*pfnSaveReadFields) ( SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int ); + + void (*pfnSaveGlobalState) ( SAVERESTOREDATA * ); + void (*pfnRestoreGlobalState) ( SAVERESTOREDATA * ); + void (*pfnResetGlobalState) ( void ); + + qboolean (*pfnClientConnect) ( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ); + + void (*pfnClientDisconnect) ( edict_t *pEntity ); + void (*pfnClientKill) ( edict_t *pEntity ); + void (*pfnClientPutInServer) ( edict_t *pEntity ); + void (*pfnClientCommand) ( edict_t *pEntity ); + void (*pfnClientUserInfoChanged)( edict_t *pEntity, char *infobuffer ); + + void (*pfnServerActivate) ( edict_t *pEdictList, int edictCount, int clientMax ); + void (*pfnServerDeactivate) ( void ); + + void (*pfnPlayerPreThink) ( edict_t *pEntity ); + void (*pfnPlayerPostThink) ( edict_t *pEntity ); + + void (*pfnStartFrame) ( void ); + void (*pfnParmsNewLevel) ( void ); + void (*pfnParmsChangeLevel) ( void ); + + // Returns string describing current .dll. E.g., TeamFotrress 2, Half-Life + const char *(*pfnGetGameDescription)( void ); + + // Notify dll about a player customization. + void (*pfnPlayerCustomization) ( edict_t *pEntity, customization_t *pCustom ); + + // Spectator funcs + void (*pfnSpectatorConnect) ( edict_t *pEntity ); + void (*pfnSpectatorDisconnect) ( edict_t *pEntity ); + void (*pfnSpectatorThink) ( edict_t *pEntity ); + + // Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint. + void (*pfnSys_Error) ( const char *error_string ); + + void (*pfnPM_Move) ( struct playermove_s *ppmove, qboolean server ); + void (*pfnPM_Init) ( struct playermove_s *ppmove ); + char (*pfnPM_FindTextureType)( char *name ); + void (*pfnSetupVisibility)( struct edict_s *pViewEntity, struct edict_s *pClient, unsigned char **pvs, unsigned char **pas ); + void (*pfnUpdateClientData) ( const struct edict_s *ent, int sendweapons, struct clientdata_s *cd ); + int (*pfnAddToFullPack)( struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet ); + void (*pfnCreateBaseline) ( int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs ); + void (*pfnRegisterEncoders) ( void ); + int (*pfnGetWeaponData) ( struct edict_s *player, struct weapon_data_s *info ); + + void (*pfnCmdStart) ( const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed ); + void (*pfnCmdEnd) ( const edict_t *player ); + + // Return 1 if the packet is valid. Set response_buffer_size if you want to send a response packet. Incoming, it holds the max + // size of the response_buffer, so you must zero it out if you choose not to respond. + int (*pfnConnectionlessPacket ) ( const struct netadr_s *net_from_, const char *args, char *response_buffer, int *response_buffer_size ); + + // Enumerates player hulls. Returns 0 if the hull number doesn't exist, 1 otherwise + int (*pfnGetHullBounds) ( int hullnumber, float *mins, float *maxs ); + + // Create baselines for certain "unplaced" items. + void (*pfnCreateInstancedBaselines) ( void ); + + // One of the pfnForceUnmodified files failed the consistency check for the specified player + // Return 0 to allow the client to continue, 1 to force immediate disconnection ( with an optional disconnect message of up to 256 characters ) + int (*pfnInconsistentFile)( const struct edict_s *player, const char *filename, char *disconnect_message ); + + // The game .dll should return 1 if lag compensation should be allowed ( could also just set + // the sv_unlag cvar. + // Most games right now should return 0, until client-side weapon prediction code is written + // and tested for them. + int (*pfnAllowLagCompensation)( void ); +} DLL_FUNCTIONS; + +extern DLL_FUNCTIONS gEntityInterface; + +// Current version. +#define NEW_DLL_FUNCTIONS_VERSION 1 + +typedef struct +{ + // Called right before the object's memory is freed. + // Calls its destructor. + void (*pfnOnFreeEntPrivateData)(edict_t *pEnt); + void (*pfnGameShutdown)(void); + int (*pfnShouldCollide)( edict_t *pentTouched, edict_t *pentOther ); + void (*pfnCvarValue)( const edict_t *pEnt, const char *value ); + void (*pfnCvarValue2)( const edict_t *pEnt, int requestID, const char *cvarName, const char *value ); +} NEW_DLL_FUNCTIONS; +typedef int(*NEW_DLL_FUNCTIONS_FN)(NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); + +// Pointers will be null if the game DLL doesn't support this API. +extern NEW_DLL_FUNCTIONS gNewDLLFunctions; + +typedef int(*APIFUNCTION)(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion); +typedef int(*APIFUNCTION2)(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); diff --git a/dep/hlsdk/engine/event.h b/dep/hlsdk/engine/event.h new file mode 100644 index 0000000..61dcf52 --- /dev/null +++ b/dep/hlsdk/engine/event.h @@ -0,0 +1,37 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef struct event_s +{ + unsigned short index; + const char *filename; + int filesize; + const char *pszScript; +} event_t; diff --git a/dep/hlsdk/engine/hookchains.h b/dep/hlsdk/engine/hookchains.h new file mode 100644 index 0000000..197b8a3 --- /dev/null +++ b/dep/hlsdk/engine/hookchains.h @@ -0,0 +1,80 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +template +class IHookChain { +protected: + virtual ~IHookChain() {} + +public: + virtual t_ret callNext(t_args... args) = 0; + virtual t_ret callOriginal(t_args... args) = 0; +}; + +template +class IVoidHookChain +{ +protected: + virtual ~IVoidHookChain() {} + +public: + virtual void callNext(t_args... args) = 0; + virtual void callOriginal(t_args... args) = 0; +}; + +// Specifies priorities for hooks call order in the chain. +// For equal priorities first registered hook will be called first. +enum HookChainPriority +{ + HC_PRIORITY_UNINTERRUPTABLE = 255, // Hook will be called before other hooks. + HC_PRIORITY_HIGH = 192, // Hook will be called before hooks with default priority. + HC_PRIORITY_DEFAULT = 128, // Default hook call priority. + HC_PRIORITY_MEDIUM = 64, // Hook will be called after hooks with default priority. + HC_PRIORITY_LOW = 0, // Hook will be called after all other hooks. +}; + +// Hook chain registry(for hooks [un]registration) +template +class IHookChainRegistry { +public: + typedef t_ret(*hookfunc_t)(IHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; + +// Hook chain registry(for hooks [un]registration) +template +class IVoidHookChainRegistry { +public: + typedef void(*hookfunc_t)(IVoidHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; diff --git a/dep/hlsdk/engine/info.h b/dep/hlsdk/engine/info.h new file mode 100644 index 0000000..c12a1fa --- /dev/null +++ b/dep/hlsdk/engine/info.h @@ -0,0 +1,55 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" + +// Max key/value length (with a NULL char) +const int MAX_KV_LEN = 127; + +// Key + value + 2 x slash + NULL +const int MAX_INFO_STRING = 256; + +const int INFO_MAX_BUFFER_VALUES = 4; + +#ifdef REHLDS_FIXES +const int MAX_LOCALINFO = 4096; +#else +const int MAX_LOCALINFO = MAX_INFO_STRING * 128; +#endif // REHLDS_FIXES + +const char *Info_ValueForKey(const char *s, const char *key); +void Info_RemoveKey(char *s, const char *key); +void Info_RemovePrefixedKeys(char *s, const char prefix); +qboolean Info_IsKeyImportant(const char *key); +char *Info_FindLargestKey(char *s, int maxsize); +void Info_SetValueForStarKey(char *s, const char *key, const char *value, int maxsize); +void Info_SetValueForKey(char *s, const char *key, const char *value, int maxsize); +void Info_Print(const char *s); +qboolean Info_IsValid(const char *s); diff --git a/dep/hlsdk/engine/inst_baseline.h b/dep/hlsdk/engine/inst_baseline.h new file mode 100644 index 0000000..173a355 --- /dev/null +++ b/dep/hlsdk/engine/inst_baseline.h @@ -0,0 +1,40 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "entity_state.h" + +const int NUM_BASELINES = 64; + +typedef struct extra_baselines_s +{ + int number; + int classname[NUM_BASELINES]; + entity_state_t baseline[NUM_BASELINES]; +} extra_baselines_t; diff --git a/dep/hlsdk/engine/keydefs.h b/dep/hlsdk/engine/keydefs.h new file mode 100644 index 0000000..ef9b2fc --- /dev/null +++ b/dep/hlsdk/engine/keydefs.h @@ -0,0 +1,131 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// keydefs.h +#ifndef KEYDEFS_H +#define KEYDEFS_H +#ifdef _WIN32 +#ifndef __MINGW32__ +#pragma once +#endif /* not __MINGW32__ */ +#endif + +// +// these are the key numbers that should be passed to Key_Event +// +#define K_TAB 9 +#define K_ENTER 13 +#define K_ESCAPE 27 +#define K_SPACE 32 + +// normal keys should be passed as lowercased ascii + +#define K_BACKSPACE 127 +#define K_UPARROW 128 +#define K_DOWNARROW 129 +#define K_LEFTARROW 130 +#define K_RIGHTARROW 131 + +#define K_ALT 132 +#define K_CTRL 133 +#define K_SHIFT 134 +#define K_F1 135 +#define K_F2 136 +#define K_F3 137 +#define K_F4 138 +#define K_F5 139 +#define K_F6 140 +#define K_F7 141 +#define K_F8 142 +#define K_F9 143 +#define K_F10 144 +#define K_F11 145 +#define K_F12 146 +#define K_INS 147 +#define K_DEL 148 +#define K_PGDN 149 +#define K_PGUP 150 +#define K_HOME 151 +#define K_END 152 + +#define K_KP_HOME 160 +#define K_KP_UPARROW 161 +#define K_KP_PGUP 162 +#define K_KP_LEFTARROW 163 +#define K_KP_5 164 +#define K_KP_RIGHTARROW 165 +#define K_KP_END 166 +#define K_KP_DOWNARROW 167 +#define K_KP_PGDN 168 +#define K_KP_ENTER 169 +#define K_KP_INS 170 +#define K_KP_DEL 171 +#define K_KP_SLASH 172 +#define K_KP_MINUS 173 +#define K_KP_PLUS 174 +#define K_CAPSLOCK 175 + + +// +// joystick buttons +// +#define K_JOY1 203 +#define K_JOY2 204 +#define K_JOY3 205 +#define K_JOY4 206 + +// +// aux keys are for multi-buttoned joysticks to generate so they can use +// the normal binding process +// +#define K_AUX1 207 +#define K_AUX2 208 +#define K_AUX3 209 +#define K_AUX4 210 +#define K_AUX5 211 +#define K_AUX6 212 +#define K_AUX7 213 +#define K_AUX8 214 +#define K_AUX9 215 +#define K_AUX10 216 +#define K_AUX11 217 +#define K_AUX12 218 +#define K_AUX13 219 +#define K_AUX14 220 +#define K_AUX15 221 +#define K_AUX16 222 +#define K_AUX17 223 +#define K_AUX18 224 +#define K_AUX19 225 +#define K_AUX20 226 +#define K_AUX21 227 +#define K_AUX22 228 +#define K_AUX23 229 +#define K_AUX24 230 +#define K_AUX25 231 +#define K_AUX26 232 +#define K_AUX27 233 +#define K_AUX28 234 +#define K_AUX29 235 +#define K_AUX30 236 +#define K_AUX31 237 +#define K_AUX32 238 +#define K_MWHEELDOWN 239 +#define K_MWHEELUP 240 + +#define K_PAUSE 255 + +// +// mouse buttons generate virtual keys +// +#define K_MOUSE1 241 +#define K_MOUSE2 242 +#define K_MOUSE3 243 +#define K_MOUSE4 244 +#define K_MOUSE5 245 + +#endif // KEYDEFS_H diff --git a/dep/hlsdk/engine/keys.h b/dep/hlsdk/engine/keys.h new file mode 100644 index 0000000..c71d378 --- /dev/null +++ b/dep/hlsdk/engine/keys.h @@ -0,0 +1,35 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef enum { + key_game = 0, + key_message = 1, + key_menu = 2, +} keydest_t; diff --git a/dep/hlsdk/engine/maintypes.h b/dep/hlsdk/engine/maintypes.h new file mode 100644 index 0000000..f55bac9 --- /dev/null +++ b/dep/hlsdk/engine/maintypes.h @@ -0,0 +1,70 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MAINTYPES_H +#define MAINTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#include "osconfig.h" +#include "mathlib.h" + +// Has no references on server side. +#define NOXREF +// Function body is not implemented. +#define NOBODY +// Function is not tested at all. +#define UNTESTED + +#define CONST_INTEGER_AS_STRING(x) #x //Wraps the integer in quotes, allowing us to form constant strings with it +#define __HACK_LINE_AS_STRING__(x) CONST_INTEGER_AS_STRING(x) //__LINE__ can only be converted to an actual number by going through this, otherwise the output is literally "__LINE__" +#define __LINE__AS_STRING __HACK_LINE_AS_STRING__(__LINE__) //Gives you the line number in constant string form + +#if defined _MSC_VER || defined __INTEL_COMPILER +#define NOXREFCHECK int __retAddr; __asm { __asm mov eax, [ebp + 4] __asm mov __retAddr, eax }; Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr) +#else +// For EBP based stack (older gcc) (uncomment version apropriate for your compiler) +//#define NOXREFCHECK int __retAddr; __asm__ __volatile__("movl 4(%%ebp), %%eax;" "movl %%eax, %0":"=r"(__retAddr)::"%eax"); Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr); +// For ESP based stack (newer gcc) (uncomment version apropriate for your compiler) +#define NOXREFCHECK int __retAddr; __asm__ __volatile__("movl 16(%%esp), %%eax;" "movl %%eax, %0":"=r"(__retAddr)::"%eax"); Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr); +#endif + +#define BIT(n) (1<<(n)) + +// From engine/pr_comp.h; +typedef unsigned int string_t; + +// From engine/server.h +typedef enum sv_delta_s +{ + sv_packet_nodelta, + sv_packet_delta, +} sv_delta_t; + +#endif // MAINTYPES_H diff --git a/dep/hlsdk/engine/model.h b/dep/hlsdk/engine/model.h new file mode 100644 index 0000000..354a815 --- /dev/null +++ b/dep/hlsdk/engine/model.h @@ -0,0 +1,409 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "const.h" +#include "modelgen.h" +#include "spritegn.h" +#include "bspfile.h" +#include "crc.h" +#include "com_model.h" +#include "commonmacros.h" + +// header +#define ALIAS_MODEL_VERSION 0x006 +#define IDPOLYHEADER MAKEID('I', 'D', 'P', 'O') // little-endian "IDPO" + +#define MAX_LBM_HEIGHT 480 +#define MAX_ALIAS_MODEL_VERTS 2000 + +#define SURF_PLANEBACK 2 +#define SURF_DRAWSKY 4 +#define SURF_DRAWSPRITE 8 +#define SURF_DRAWTURB 0x10 +#define SURF_DRAWTILED 0x20 +#define SURF_DRAWBACKGROUND 0x40 + +#define MAX_MODEL_NAME 64 +#define MIPLEVELS 4 +#define NUM_AMBIENTS 4 // automatic ambient sounds +#define MAXLIGHTMAPS 4 +#define MAX_KNOWN_MODELS 1024 + +typedef struct mvertex_s +{ + vec3_t position; +} mvertex_t; + +typedef struct mplane_s +{ + vec3_t normal; // surface normal + float dist; // closest appoach to origin + byte type; // for texture axis selection and fast side tests + byte signbits; // signx + signy<<1 + signz<<1 + byte pad[2]; +} mplane_t; + +typedef struct texture_s +{ + char name[16]; + unsigned width, height; + +#if !defined(SWDS) && !defined(HLTV) + int gl_texturenum; + struct msurface_s * texturechain; +#endif + + int anim_total; // total tenths in sequence ( 0 = no) + int anim_min, anim_max; // time for this frame min <=time< max + struct texture_s *anim_next; // in the animation sequence + struct texture_s *alternate_anims; // bmodels in frame 1 use these + unsigned offsets[MIPLEVELS]; // four mip maps stored + +#if defined(SWDS) || defined(HLTV) + unsigned paloffset; +#else + byte *pPal; +#endif + +} texture_t; + +typedef struct medge_s +{ + unsigned short v[2]; + unsigned int cachededgeoffset; +} medge_t; + +typedef struct mtexinfo_s +{ + float vecs[2][4]; // [s/t] unit vectors in world space. + // [i][3] is the s/t offset relative to the origin. + // s or t = dot(3Dpoint,vecs[i])+vecs[i][3] + float mipadjust; // ?? mipmap limits for very small surfaces + texture_t *texture; + int flags; // sky or slime, no lightmap or 256 subdivision +} mtexinfo_t; +#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision + +typedef struct msurface_s msurface_t; +typedef struct decal_s decal_t; + +// JAY: Compress this as much as possible +struct decal_s +{ + decal_t *pnext; // linked list for each surface + msurface_t *psurface; // Surface id for persistence / unlinking + short dx; // Offsets into surface texture (in texture coordinates, so we don't need floats) + short dy; + short texture; // Decal texture + byte scale; // Pixel scale + byte flags; // Decal flags + + short entityIndex; // Entity this is attached to +}; + +struct msurface_s +{ + int visframe; // should be drawn when node is crossed + + int dlightframe; // last frame the surface was checked by an animated light + int dlightbits; // dynamically generated. Indicates if the surface illumination + // is modified by an animated light. + + mplane_t *plane; // pointer to shared plane + int flags; // see SURF_ #defines + + int firstedge; // look up in model->surfedges[], negative numbers + int numedges; // are backwards edges + + // surface generation data + struct surfcache_s *cachespots[MIPLEVELS]; + + short texturemins[2]; // smallest s/t position on the surface. + short extents[2]; // ?? s/t texture size, 1..256 for all non-sky surfaces + + mtexinfo_t *texinfo; + + // lighting info + byte styles[MAXLIGHTMAPS]; // index into d_lightstylevalue[] for animated lights + // no one surface can be effected by more than 4 + // animated lights. + color24 *samples; + + decal_t *pdecals; +}; + +typedef struct mnode_s +{ + // common with leaf + int contents; // 0, to differentiate from leafs + int visframe; // node needs to be traversed if current + + short minmaxs[6]; // for bounding box culling + + struct mnode_s *parent; + + // node specific + mplane_t *plane; + struct mnode_s *children[2]; + + unsigned short firstsurface; + unsigned short numsurfaces; +} mnode_t; + +typedef struct mleaf_s +{ + // common with node + int contents; // wil be a negative contents number + int visframe; // node needs to be traversed if current + + short minmaxs[6]; // for bounding box culling + + struct mnode_s *parent; + + // leaf specific + byte *compressed_vis; + struct efrag_s *efrags; + + msurface_t **firstmarksurface; + int nummarksurfaces; + int key; // BSP sequence number for leaf's contents + byte ambient_sound_level[NUM_AMBIENTS]; +} mleaf_t; + +typedef struct hull_s +{ + dclipnode_t *clipnodes; + mplane_t *planes; + int firstclipnode; + int lastclipnode; + vec3_t clip_mins, clip_maxs; +} hull_t; + +typedef struct mspriteframe_t +{ + int width; + int height; + void *pcachespot; + float up, down, left, right; + byte pixels[4]; +} mspriteframe_s; + +typedef struct mspritegroup_s +{ + int numframes; + float *intervals; + mspriteframe_t *frames[1]; +} mspritegroup_t; + +typedef struct mspriteframedesc_s +{ + spriteframetype_t type; + mspriteframe_t *frameptr; +} mspriteframedesc_t; + +typedef struct msprite_s +{ + short int type; + short int texFormat; + int maxwidth, maxheight; + int numframes; + int paloffset; + float beamlength; + void *cachespot; + mspriteframedesc_t frames[1]; +} msprite_t; + +typedef struct maliasframedesc_s +{ + aliasframetype_t type; + trivertx_t bboxmin, bboxmax; + int frame; + char name[16]; +} maliasframedesc_t; + +typedef struct maliasskindesc_s +{ + aliasskintype_t type; + void *pcachespot; + int skin; +} maliasskindesc_t; + +typedef struct maliasgroupframedesc_s +{ + trivertx_t bboxmin, bboxmax; + int frame; +} maliasgroupframedesc_t; + +typedef struct maliasgroup_s +{ + int numframes; + int intervals; + maliasgroupframedesc_t frames[1]; +} maliasgroup_t; + +typedef struct maliasskingroup_s +{ + int numskins; + int intervals; + maliasskindesc_t skindescs[1]; +} maliasskingroup_t; + +typedef struct mtriangle_s +{ + int facesfront; + int vertindex[3]; +} mtriangle_t; + +typedef struct aliashdr_s +{ + int model; + int stverts; + int skindesc; + int triangles; + int palette; + maliasframedesc_t frames[1]; +} aliashdr_t; + +typedef enum modtype_e +{ + mod_bad = -1, + mod_brush, + mod_sprite, + mod_alias, + mod_studio, +} modtype_t; + +typedef struct model_s +{ + char name[MAX_MODEL_NAME]; + + int needload; // bmodels and sprites don't cache normally + + modtype_t type; + int numframes; + synctype_t synctype; + + int flags; + + // + // volume occupied by the model + // + vec3_t mins, maxs; + float radius; + + // + // brush model + // + int firstmodelsurface, nummodelsurfaces; + + int numsubmodels; + dmodel_t *submodels; + + int numplanes; + mplane_t *planes; + + int numleafs; // number of visible leafs, not counting 0 + struct mleaf_s *leafs; + + int numvertexes; + mvertex_t *vertexes; + + int numedges; + medge_t *edges; + + int numnodes; + mnode_t *nodes; + + int numtexinfo; + mtexinfo_t *texinfo; + + int numsurfaces; + msurface_t *surfaces; + + int numsurfedges; + int *surfedges; + + int numclipnodes; + dclipnode_t *clipnodes; + + int nummarksurfaces; + msurface_t **marksurfaces; + + hull_t hulls[MAX_MAP_HULLS]; + + int numtextures; + texture_t **textures; + + byte *visdata; + + color24 *lightdata; + + char *entities; + + // + // additional model data + // + cache_user_t cache; // only access through Mod_Extradata +} model_t; + +typedef struct cachepic_s +{ + char name[64]; + cache_user_t cache; +} cachepic_t; + +typedef struct cachewad_s cachewad_t; + +typedef void(*PFNCACHE)(cachewad_t *, unsigned char *); + +typedef struct cachewad_s +{ + char *name; + cachepic_t *cache; + int cacheCount; + int cacheMax; + struct lumpinfo_s *lumps; + int lumpCount; + int cacheExtra; + PFNCACHE pfnCacheBuild; + int numpaths; + char **basedirs; + int *lumppathindices; +#ifndef SWDS + int tempWad; +#endif // SWDS +} cachewad_t; + +typedef struct mod_known_info_s +{ + qboolean shouldCRC; + qboolean firstCRCDone; + CRC32_t initialCRC; +} mod_known_info_t; + diff --git a/dep/hlsdk/engine/modelgen.h b/dep/hlsdk/engine/modelgen.h new file mode 100644 index 0000000..48fd9b8 --- /dev/null +++ b/dep/hlsdk/engine/modelgen.h @@ -0,0 +1,128 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MODELGEN_H +#define MODELGEN_H +#ifdef _WIN32 +#pragma once +#endif + +typedef enum synctype_e +{ + ST_SYNC = 0, + ST_RAND = 1, +} synctype_t; + +typedef enum aliasframetype_s +{ + ALIAS_SINGLE = 0, + ALIAS_GROUP = 1, +} aliasframetype_t; + +typedef enum aliasskintype_s +{ + ALIAS_SKIN_SINGLE = 0, + ALIAS_SKIN_GROUP = 1, +} aliasskintype_t; + +typedef struct mdl_s +{ + int ident; + int version; + vec3_t scale; + vec3_t scale_origin; + float boundingradius; + vec3_t eyeposition; + int numskins; + int skinwidth; + int skinheight; + int numverts; + int numtris; + int numframes; + synctype_t synctype; + int flags; + float size; +} mdl_t; + +typedef struct stvert_s +{ + int onseam; + int s; + int t; +} stvert_t; + +typedef struct dtriangle_s +{ + int facesfront; + int vertindex[3]; +} dtriangle_t; + +typedef struct trivertx_s +{ + byte v[3]; + byte lightnormalindex; +} trivertx_t; + +typedef struct daliasframe_s +{ + trivertx_t bboxmin, bboxmax; + char name[16]; +} daliasframe_t; + +typedef struct daliasgroup_s +{ + int numframes; + trivertx_t bboxmin, bboxmax; +} daliasgroup_t; + +typedef struct daliasskingroup_s +{ + int numskins; +} daliasskingroup_t; + +typedef struct daliasinterval_s +{ + float interval; +} daliasinterval_t; + +typedef struct daliasskininterval_s +{ + float interval; +} daliasskininterval_t; + +typedef struct daliasframetype_s +{ + aliasframetype_t type; +} daliasframetype_t; + +typedef struct daliasskintype_s +{ + aliasskintype_t type; +} daliasskintype_t; + +#endif // MODELGEN_H diff --git a/dep/hlsdk/engine/net.h b/dep/hlsdk/engine/net.h new file mode 100644 index 0000000..913abc7 --- /dev/null +++ b/dep/hlsdk/engine/net.h @@ -0,0 +1,421 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" +#include "enums.h" +#include "netadr.h" + +const int PROTOCOL_VERSION = 48; + +// MAX_CHALLENGES is made large to prevent a denial +// of service attack that could cycle all of them +// out before legitimate users connected +#ifdef REHLDS_OPT_PEDANTIC +const int MAX_CHALLENGES = 64; +#else +const int MAX_CHALLENGES = 1024; +#endif // REHLDS_OPT_PEDANTIC + +// Client connection is initiated by requesting a challenge value +// the server sends this value back +const char S2C_CHALLENGE = 'A'; // + challenge value + +// Send a userid, client remote address, is this server secure and engine build number +const char S2C_CONNECTION = 'B'; + +// HLMaster rejected a server's connection because the server needs to be updated +const char M2S_REQUESTRESTART = 'O'; + +// Response details about each player on the server +const char S2A_PLAYERS = 'D'; + +// Number of rules + string key and string value pairs +const char S2A_RULES = 'E'; + +// info request +const char S2A_INFO = 'C'; // deprecated goldsrc response + +const char S2A_INFO_DETAILED = 'm'; // New Query protocol, returns dedicated or not, + other performance info. + +// send a log event as key value +const char S2A_LOGSTRING = 'R'; + +// Send a log string +const char S2A_LOGKEY = 'S'; + +// Basic information about the server +const char A2S_INFO = 'T'; + +// Details about each player on the server +const char A2S_PLAYER = 'U'; + +// The rules the server is using +const char A2S_RULES = 'V'; + +// Another user is requesting a challenge value from this machine +const char A2A_GETCHALLENGE = 'W'; // Request challenge # from another machine + +// Generic Ping Request +const char A2A_PING = 'i'; // respond with an A2A_ACK + +// Generic Ack +const char A2A_ACK = 'j'; // general acknowledgement without info + +// Print to client console +const char A2A_PRINT = 'l'; // print a message on client + +// Challenge response from master +const char M2A_CHALLENGE = 's'; // + challenge value + +// 0 == regular, 1 == file stream +enum +{ + FRAG_NORMAL_STREAM = 0, + FRAG_FILE_STREAM, + + MAX_STREAMS +}; + +// Flow control bytes per second limits +const float MAX_RATE = 100000.0f; +const float MIN_RATE = 1000.0f; + +// Default data rate +const float DEFAULT_RATE = 9999.0f; + +// NETWORKING INFO + +// Max size of udp packet payload +const int MAX_UDP_PACKET = 4010; // 9 bytes SPLITHEADER + 4000 payload? + +// Max length of a reliable message +const int MAX_MSGLEN = 3990; // 10 reserved for fragheader? + +// Max length of unreliable message +const int MAX_DATAGRAM = 4000; + +// This is the packet payload without any header bytes (which are attached for actual sending) +const int NET_MAX_PAYLOAD = 65536; + +// This is the payload plus any header info (excluding UDP header) + +// Packet header is: +// 4 bytes of outgoing seq +// 4 bytes of incoming seq +// and for each stream +// { +// byte (on/off) +// int (fragment id) +// short (startpos) +// short (length) +// } +#define HEADER_BYTES (8 + MAX_STREAMS * 9) + +// Pad this to next higher 16 byte boundary +// This is the largest packet that can come in/out over the wire, before processing the header +// bytes will be stripped by the networking channel layer +//#define NET_MAX_MESSAGE PAD_NUMBER( ( MAX_MSGLEN + HEADER_BYTES ), 16 ) +// This is currently used value in the engine. TODO: define above gives 4016, check it why. +const int NET_MAX_MESSAGE = 4037; + +enum svc_commands_e : uint32_t +{ + svc_bad, + svc_nop, + svc_disconnect, + svc_event, + svc_version, + svc_setview, + svc_sound, + svc_time, + svc_print, + svc_stufftext, + svc_setangle, + svc_serverinfo, + svc_lightstyle, + svc_updateuserinfo, + svc_deltadescription, + svc_clientdata, + svc_stopsound, + svc_pings, + svc_particle, + svc_damage, + svc_spawnstatic, + svc_event_reliable, + svc_spawnbaseline, + svc_temp_entity, + svc_setpause, + svc_signonnum, + svc_centerprint, + svc_killedmonster, + svc_foundsecret, + svc_spawnstaticsound, + svc_intermission, + svc_finale, + svc_cdtrack, + svc_restore, + svc_cutscene, + svc_weaponanim, + svc_decalname, + svc_roomtype, + svc_addangle, + svc_newusermsg, + svc_packetentities, + svc_deltapacketentities, + svc_choke, + svc_resourcelist, + svc_newmovevars, + svc_resourcerequest, + svc_customization, + svc_crosshairangle, + svc_soundfade, + svc_filetxferfailed, + svc_hltv, + svc_director, + svc_voiceinit, + svc_voicedata, + svc_sendextrainfo, + svc_timescale, + svc_resourcelocation, + svc_sendcvarvalue, + svc_sendcvarvalue2, + svc_startofusermessages = svc_sendcvarvalue2, + svc_endoflist = 255, +}; + +struct svc_func_t +{ + svc_commands_e opcode; + char *pszName; + void (*pfnParse)(); +}; + +typedef enum clc_commands_e +{ + clc_bad, + clc_nop, + clc_move, + clc_stringcmd, + clc_delta, + clc_resourcelist, + clc_tmove, + clc_fileconsistency, + clc_voicedata, + clc_hltv, + clc_cvarvalue, + clc_cvarvalue2, + clc_endoflist = 255, +} clc_commands_t; + +enum +{ + FLOW_OUTGOING = 0, + FLOW_INCOMING, + + MAX_FLOWS +}; + +// Message data +typedef struct flowstats_s +{ + // Size of message sent/received + int size; + // Time that message was sent/received + double time; +} flowstats_t; + +const int MAX_LATENT = 32; + +typedef struct flow_s +{ + // Data for last MAX_LATENT messages + flowstats_t stats[MAX_LATENT]; + // Current message position + int current; + // Time when we should recompute k/sec data + double nextcompute; + // Average data + float kbytespersec; + float avgkbytespersec; +} flow_t; + +const int FRAGMENT_C2S_MIN_SIZE = 16; +const int FRAGMENT_S2C_MIN_SIZE = 256; +const int FRAGMENT_S2C_MAX_SIZE = 1024; + +const int CLIENT_FRAGMENT_SIZE_ONCONNECT = 128; +const int CUSTOMIZATION_MAX_SIZE = 20480; + +#ifndef REHLDS_FIXES +// Size of fragmentation buffer internal buffers +const int FRAGMENT_MAX_SIZE = 1400; + +const int MAX_FRAGMENTS = 25000; +#else +const int FRAGMENT_MAX_SIZE = 1024; + +// Client sends normal fragments only while connecting +#define MAX_NORMAL_FRAGMENTS (NET_MAX_PAYLOAD / CLIENT_FRAGMENT_SIZE_ONCONNECT) + +// While client is connecting it sending fragments with minimal size, also it transfers sprays with minimal fragments... +// But with sv_delayed_spray_upload it sends with cl_dlmax fragment size +#define MAX_FILE_FRAGMENTS (CUSTOMIZATION_MAX_SIZE / FRAGMENT_C2S_MIN_SIZE) +#endif + +const int UDP_HEADER_SIZE = 28; +const int MAX_RELIABLE_PAYLOAD = 1200; + +#define MAKE_FRAGID(id,count) ((( id & 0xffff) << 16) | (count & 0xffff)) +#define FRAG_GETID(fragid) ((fragid >> 16) & 0xffff) +#define FRAG_GETCOUNT(fragid) (fragid & 0xffff) + +// Generic fragment structure +typedef struct fragbuf_s +{ + // Next buffer in chain + fragbuf_s *next; + // Id of this buffer + int bufferid; + // Message buffer where raw data is stored + sizebuf_t frag_message; + // The actual data sits here + byte frag_message_buf[FRAGMENT_MAX_SIZE]; + // Is this a file buffer? + qboolean isfile; + // Is this file buffer from memory ( custom decal, etc. ). + qboolean isbuffer; + qboolean iscompressed; + // Name of the file to save out on remote host + char filename[MAX_PATH]; + // Offset in file from which to read data + int foffset; + // Size of data to read at that offset + int size; +} fragbuf_t; + +// Waiting list of fragbuf chains +typedef struct fragbufwaiting_s +{ + // Next chain in waiting list + fragbufwaiting_s *next; + // Number of buffers in this chain + int fragbufcount; + // The actual buffers + fragbuf_t *fragbufs; +} fragbufwaiting_t; + +// Network Connection Channel +typedef struct netchan_s +{ + // NS_SERVER or NS_CLIENT, depending on channel. + netsrc_t sock; + + // Address this channel is talking to. + netadr_t remote_address; + + int player_slot; + // For timeouts. Time last message was received. + float last_received; + // Time when channel was connected. + float connect_time; + + // Bandwidth choke + // Bytes per second + double rate; + // If realtime > cleartime, free to send next packet + double cleartime; + + // Sequencing variables + // + // Increasing count of sequence numbers + int incoming_sequence; + // # of last outgoing message that has been ack'd. + int incoming_acknowledged; + // Toggles T/F as reliable messages are received. + int incoming_reliable_acknowledged; + // single bit, maintained local + int incoming_reliable_sequence; + // Message we are sending to remote + int outgoing_sequence; + // Whether the message contains reliable payload, single bit + int reliable_sequence; + // Outgoing sequence number of last send that had reliable data + int last_reliable_sequence; + + void *connection_status; + int (*pfnNetchan_Blocksize)(void *); + + // Staging and holding areas + sizebuf_t message; + byte message_buf[MAX_MSGLEN]; + + // Reliable message buffer. We keep adding to it until reliable is acknowledged. Then we clear it. + int reliable_length; + byte reliable_buf[MAX_MSGLEN]; + + // Waiting list of buffered fragments to go onto queue. Multiple outgoing buffers can be queued in succession. + fragbufwaiting_t *waitlist[MAX_STREAMS]; + + // Is reliable waiting buf a fragment? + int reliable_fragment[MAX_STREAMS]; + // Buffer id for each waiting fragment + unsigned int reliable_fragid[MAX_STREAMS]; + + // The current fragment being set + fragbuf_t *fragbufs[MAX_STREAMS]; + // The total number of fragments in this stream + int fragbufcount[MAX_STREAMS]; + + // Position in outgoing buffer where frag data starts + short int frag_startpos[MAX_STREAMS]; + // Length of frag data in the buffer + short int frag_length[MAX_STREAMS]; + + // Incoming fragments are stored here + fragbuf_t *incomingbufs[MAX_STREAMS]; + // Set to true when incoming data is ready + qboolean incomingready[MAX_STREAMS]; + + // Only referenced by the FRAG_FILE_STREAM component + // Name of file being downloaded + char incomingfilename[MAX_PATH]; + + void *tempbuffer; + int tempbuffersize; + + // Incoming and outgoing flow metrics + flow_t flow[MAX_FLOWS]; +} netchan_t; + +#ifdef REHLDS_FIXES +#define Con_NetPrintf Con_DPrintf +#else // REHLDS_FIXES +#define Con_NetPrintf Con_Printf +#endif // REHLDS_FIXES diff --git a/dep/hlsdk/engine/osconfig.h b/dep/hlsdk/engine/osconfig.h new file mode 100644 index 0000000..f9bc583 --- /dev/null +++ b/dep/hlsdk/engine/osconfig.h @@ -0,0 +1,220 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef _OSCONFIG_H +#define _OSCONFIG_H + +#ifdef _WIN32 // WINDOWS + #pragma warning(disable : 4005) +#endif // _WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef _WIN32 // WINDOWS + #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + #include + #include + #include // for support IPX + #define PSAPI_VERSION 1 + #include + #include + #include + #include + #include + #include +#else // _WIN32 + #include + #include + //#include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#endif // _WIN32 + +#include +#include +#include +#include + +#include +#include + + +#ifdef _WIN32 // WINDOWS + // Define __func__ on VS less than 2015 + #if _MSC_VER < 1900 + #define __func__ __FUNCTION__ + #endif + + #define _CRT_SECURE_NO_WARNINGS + #define WIN32_LEAN_AND_MEAN + + #ifndef CDECL + #define CDECL __cdecl + #endif + #define FASTCALL __fastcall + #define STDCALL __stdcall + #define HIDDEN + #define FORCEINLINE __forceinline + #define NOINLINE __declspec(noinline) + #define ALIGN16 __declspec(align(16)) + #define NORETURN __declspec(noreturn) + #define FORCE_STACK_ALIGN + #define FUNC_TARGET(x) + + #define __builtin_bswap16 _byteswap_ushort + #define __builtin_bswap32 _byteswap_ulong + #define __builtin_bswap64 _byteswap_uint64 + + //inline bool SOCKET_FIONBIO(SOCKET s, int m) { return (ioctlsocket(s, FIONBIO, (u_long*)&m) == 0); } + //inline int SOCKET_MSGLEN(SOCKET s, u_long& r) { return ioctlsocket(s, FIONREAD, (u_long*)&r); } + typedef int socklen_t; + #define SOCKET_FIONBIO(s, m) ioctlsocket(s, FIONBIO, (u_long*)&m) + #define SOCKET_MSGLEN(s, r) ioctlsocket(s, FIONREAD, (u_long*)&r) + #define SIN_GET_ADDR(saddr, r) r = (saddr)->S_un.S_addr + #define SIN_SET_ADDR(saddr, r) (saddr)->S_un.S_addr = (r) + #define SOCKET_CLOSE(s) closesocket(s) + #define SOCKET_AGAIN() (WSAGetLastError() == WSAEWOULDBLOCK) + + inline void* sys_allocmem(unsigned int size) { + return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); + } + + inline void sys_freemem(void* ptr, unsigned int size) { + VirtualFree(ptr, 0, MEM_RELEASE); + } +#else // _WIN32 + #ifndef PAGESIZE + #define PAGESIZE 4096 + #endif + #define ALIGN(addr) (size_t)((size_t)addr & ~(PAGESIZE-1)) + #define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) + + #define _MAX_FNAME NAME_MAX + #define MAX_PATH 260 + + typedef void *HWND; + + typedef unsigned long DWORD; + typedef unsigned short WORD; + typedef unsigned int UNINT32; + + #define FASTCALL + #define CDECL __attribute__ ((cdecl)) + #define STDCALL __attribute__ ((stdcall)) + #define HIDDEN __attribute__((visibility("hidden"))) + #define FORCEINLINE inline + #define NOINLINE __attribute__((noinline)) + #define ALIGN16 __attribute__((aligned(16))) + #define NORETURN __attribute__((noreturn)) + #define FORCE_STACK_ALIGN __attribute__((force_align_arg_pointer)) + +#if defined __INTEL_COMPILER + #define FUNC_TARGET(x) + + #define __builtin_bswap16 _bswap16 + #define __builtin_bswap32 _bswap + #define __builtin_bswap64 _bswap64 +#else + #define FUNC_TARGET(x) __attribute__((target(x))) +#endif // __INTEL_COMPILER + + //inline bool SOCKET_FIONBIO(SOCKET s, int m) { return (ioctl(s, FIONBIO, (int*)&m) == 0); } + //inline int SOCKET_MSGLEN(SOCKET s, u_long& r) { return ioctl(s, FIONREAD, (int*)&r); } + typedef int SOCKET; + #define INVALID_SOCKET (SOCKET)(~0) + #define SOCKET_FIONBIO(s, m) ioctl(s, FIONBIO, (char*)&m) + #define SOCKET_MSGLEN(s, r) ioctl(s, FIONREAD, (char*)&r) + #define SIN_GET_ADDR(saddr, r) r = (saddr)->s_addr + #define SIN_SET_ADDR(saddr, r) (saddr)->s_addr = (r) + #define SOCKET_CLOSE(s) close(s) + #define SOCKET_AGAIN() (errno == EAGAIN) + #define SOCKET_ERROR -1 + + inline int ioctlsocket(int fd, int cmd, unsigned int *argp) { return ioctl(fd, cmd, argp); } + inline int closesocket(int fd) { return close(fd); } + inline int WSAGetLastError() { return errno; } + + inline void* sys_allocmem(unsigned int size) { + return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + } + inline void sys_freemem(void* ptr, unsigned int size) { + munmap(ptr, size); + } + + #define WSAENOPROTOOPT ENOPROTOOPT + + #ifndef FALSE + #define FALSE 0 + #endif + #ifndef TRUE + #define TRUE 1 + #endif +#endif // _WIN32 + +#ifdef _WIN32 + static const bool __isWindows = true; + static const bool __isLinux = false; +#else + static const bool __isWindows = false; + static const bool __isLinux = true; +#endif + +#define EXT_FUNC FORCE_STACK_ALIGN + +// Used to obtain the string name of a variable. +#define nameof_variable(name) template_nameof_variable(name, #name) +template const char* template_nameof_variable(const T& /*validate_type*/, const char* name) { return name; } + +#endif // _OSCONFIG_H diff --git a/dep/hlsdk/engine/pr_dlls.h b/dep/hlsdk/engine/pr_dlls.h new file mode 100644 index 0000000..d7b72c1 --- /dev/null +++ b/dep/hlsdk/engine/pr_dlls.h @@ -0,0 +1,51 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" +#include "eiface.h" + +const int MAX_EXTENSION_DLL = 50; + +typedef struct functiontable_s +{ + uint32 pFunction; + char *pFunctionName; +} functiontable_t; + +typedef struct extensiondll_s +{ + void *lDLLHandle; + functiontable_t *functionTable; + int functionCount; +} extensiondll_t; + +typedef void(*ENTITYINIT)(struct entvars_s *); +typedef void(*DISPATCHFUNCTION)(struct entvars_s *, void *); +typedef void(*FIELDIOFUNCTION)(SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int); diff --git a/dep/hlsdk/engine/progdefs.h b/dep/hlsdk/engine/progdefs.h new file mode 100644 index 0000000..e27dc50 --- /dev/null +++ b/dep/hlsdk/engine/progdefs.h @@ -0,0 +1,224 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PROGDEFS_H +#define PROGDEFS_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct globalvars_s +{ + float time; + float frametime; + float force_retouch; + string_t mapname; + string_t startspot; + float deathmatch_; + float coop_; + float teamplay; + float serverflags; + float found_secrets; + vec3_t v_forward; + vec3_t v_up; + vec3_t v_right; + float trace_allsolid; + float trace_startsolid; + float trace_fraction; + vec3_t trace_endpos; + vec3_t trace_plane_normal; + float trace_plane_dist; + edict_t *trace_ent; + float trace_inopen; + float trace_inwater; + int trace_hitgroup; + int trace_flags; + int msg_entity; + int cdAudioTrack; + int maxClients; + int maxEntities; + const char *pStringBase; + + void *pSaveData; + vec3_t vecLandmarkOffset; +} globalvars_t; + + +typedef struct entvars_s +{ + string_t classname; + string_t globalname; + + vec3_t origin; + vec3_t oldorigin; + vec3_t velocity; + vec3_t basevelocity; + vec3_t clbasevelocity; // Base velocity that was passed in to server physics so + // client can predict conveyors correctly. Server zeroes it, so we need to store here, too. + vec3_t movedir; + + vec3_t angles; // Model angles + vec3_t avelocity; // angle velocity (degrees per second) + vec3_t punchangle; // auto-decaying view angle adjustment + vec3_t v_angle; // Viewing angle (player only) + + // For parametric entities + vec3_t endpos; + vec3_t startpos; + float impacttime; + float starttime; + + int fixangle; // 0:nothing, 1:force view angles, 2:add avelocity + float idealpitch; + float pitch_speed; + float ideal_yaw; + float yaw_speed; + + int modelindex; + string_t model; + + int viewmodel; // player's viewmodel + int weaponmodel; // what other players see + + vec3_t absmin; // BB max translated to world coord + vec3_t absmax; // BB max translated to world coord + vec3_t mins; // local BB min + vec3_t maxs; // local BB max + vec3_t size; // maxs - mins + + float ltime; + float nextthink; + + int movetype; + int solid; + + int skin; + int body; // sub-model selection for studiomodels + int effects; + + float gravity; // % of "normal" gravity + float friction; // inverse elasticity of MOVETYPE_BOUNCE + + int light_level; + + int sequence; // animation sequence + int gaitsequence; // movement animation sequence for player (0 for none) + float frame; // % playback position in animation sequences (0..255) + float animtime; // world time when frame was set + float framerate; // animation playback rate (-8x to 8x) + byte controller[4]; // bone controller setting (0..255) + byte blending[2]; // blending amount between sub-sequences (0..255) + + float scale; // sprite rendering scale (0..255) + + int rendermode; + float renderamt; + vec3_t rendercolor; + int renderfx; + + float health; + float frags; + int weapons; // bit mask for available weapons + float takedamage; + + int deadflag; + vec3_t view_ofs; // eye position + + int button; + int impulse; + + edict_t *chain; // Entity pointer when linked into a linked list + edict_t *dmg_inflictor; + edict_t *enemy; + edict_t *aiment; // entity pointer when MOVETYPE_FOLLOW + edict_t *owner; + edict_t *groundentity; + + int spawnflags; + int flags; + + int colormap; // lowbyte topcolor, highbyte bottomcolor + int team; + + float max_health; + float teleport_time; + float armortype; + float armorvalue; + int waterlevel; + int watertype; + + string_t target; + string_t targetname; + string_t netname; + string_t message; + + float dmg_take; + float dmg_save; + float dmg; + float dmgtime; + + string_t noise; + string_t noise1; + string_t noise2; + string_t noise3; + + float speed; + float air_finished; + float pain_finished; + float radsuit_finished; + + edict_t *pContainingEntity; + + int playerclass; + float maxspeed; + + float fov; + int weaponanim; + + int pushmsec; + + int bInDuck; + int flTimeStepSound; + int flSwimTime; + int flDuckTime; + int iStepLeft; + float flFallVelocity; + + int gamestate; + + int oldbuttons; + + int groupinfo; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; + edict_t *euser1; + edict_t *euser2; + edict_t *euser3; + edict_t *euser4; +} entvars_t; + + +#endif // PROGDEFS_H diff --git a/dep/hlsdk/engine/progs.h b/dep/hlsdk/engine/progs.h new file mode 100644 index 0000000..b8ce179 --- /dev/null +++ b/dep/hlsdk/engine/progs.h @@ -0,0 +1,82 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PROGS_H +#define PROGS_H + +#include "progdefs.h" + +// 16 simultaneous events, max +#define MAX_EVENT_QUEUE 64 + +#define DEFAULT_EVENT_RESENDS 1 + +#include "event_flags.h" + +typedef struct event_info_s event_info_t; + +#include "event_args.h" + +struct event_info_s +{ + unsigned short index; // 0 implies not in use + + short packet_index; // Use data from state info for entity in delta_packet . -1 implies separate info based on event + // parameter signature + short entity_index; // The edict this event is associated with + + float fire_time; // if non-zero, the time when the event should be fired ( fixed up on the client ) + + event_args_t args; + +// CLIENT ONLY + int flags; // Reliable or not, etc. + +}; + +typedef struct event_state_s event_state_t; + +struct event_state_s +{ + struct event_info_s ei[ MAX_EVENT_QUEUE ]; +}; + +#if !defined( ENTITY_STATEH ) +#include "entity_state.h" +#endif + +#if !defined( EDICT_H ) +#include "edict.h" +#endif + +#define STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - (int)&(((t *)0)->m))) +#define EDICT_FROM_AREA(l) STRUCT_FROM_LINK(l,edict_t,area) + +//============================================================================ + +extern char *pr_strings; +extern globalvars_t gGlobalVariables; + +//============================================================================ + +edict_t *ED_Alloc (void); +void ED_Free (edict_t *ed); +void ED_LoadFromFile (char *data); + +edict_t *EDICT_NUM(int n); +int NUM_FOR_EDICT(const edict_t *e); + +#define PROG_TO_EDICT(e) ((edict_t *)((byte *)sv.edicts + e)) + +#endif // PROGS_H diff --git a/dep/hlsdk/engine/server.h b/dep/hlsdk/engine/server.h new file mode 100644 index 0000000..046530b --- /dev/null +++ b/dep/hlsdk/engine/server.h @@ -0,0 +1,138 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "crc.h" +#include "common.h" +#include "net.h" +#include "event.h" +#include "custom.h" +#include "netadr.h" +#include "qlimits.h" +#include "consistency.h" +#include "inst_baseline.h" + +#define MAX_RESOURCE_LIST 1280 + +typedef enum server_state_e +{ + ss_dead = 0, + ss_loading = 1, + ss_active = 2, +} server_state_t; + +typedef struct server_s +{ + qboolean active; + qboolean paused; + qboolean loadgame; + double time; + double oldtime; + int lastcheck; + double lastchecktime; + char name[64]; + char oldname[64]; + char startspot[64]; + char modelname[64]; + struct model_s *worldmodel; + CRC32_t worldmapCRC; + unsigned char clientdllmd5[16]; + resource_t resourcelist[MAX_RESOURCE_LIST]; + int num_resources; + consistency_t consistency_list[MAX_CONSISTENCY_LIST]; + int num_consistency; + const char *model_precache[MAX_MODELS]; + struct model_s *models[MAX_MODELS]; + unsigned char model_precache_flags[MAX_MODELS]; + struct event_s event_precache[MAX_EVENTS]; + const char *sound_precache[MAX_SOUNDS]; + short int sound_precache_hashedlookup[MAX_SOUNDS_HASHLOOKUP_SIZE]; + qboolean sound_precache_hashedlookup_built; + const char *generic_precache[MAX_GENERIC]; + char generic_precache_names[MAX_GENERIC][64]; + int num_generic_names; + const char *lightstyles[MAX_LIGHTSTYLES]; + int num_edicts; + int max_edicts; + edict_t *edicts; + struct entity_state_s *baselines; + extra_baselines_t *instance_baselines; + server_state_t state; + sizebuf_t datagram; + unsigned char datagram_buf[MAX_DATAGRAM]; + sizebuf_t reliable_datagram; + unsigned char reliable_datagram_buf[MAX_DATAGRAM]; + sizebuf_t multicast; + unsigned char multicast_buf[1024]; + sizebuf_t spectator; + unsigned char spectator_buf[1024]; + sizebuf_t signon; + unsigned char signon_data[32768]; +} server_t; + +typedef struct server_log_s +{ + qboolean active; + qboolean net_log_; + netadr_t net_address_; + void *file; +} server_log_t; + +typedef struct server_stats_s +{ + int num_samples; + int at_capacity; + int at_empty; + float capacity_percent; + float empty_percent; + int minusers; + int maxusers; + float cumulative_occupancy; + float occupancy; + int num_sessions; + float cumulative_sessiontime; + float average_session_len; + float cumulative_latency; + float average_latency; +} server_stats_t; + +typedef struct server_static_s +{ + qboolean dll_initialized; + struct client_s *clients; + int maxclients; + int maxclientslimit; + int spawncount; + int serverflags; + server_log_t log; + double next_cleartime; + double next_sampletime; + server_stats_t stats; + qboolean isSecure; +} server_static_t; + +extern server_t *sv; diff --git a/dep/hlsdk/engine/shake.h b/dep/hlsdk/engine/shake.h new file mode 100644 index 0000000..1146a5e --- /dev/null +++ b/dep/hlsdk/engine/shake.h @@ -0,0 +1,57 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef SHAKE_H +#define SHAKE_H + +// Screen / View effects + +// screen shake +extern int gmsgShake; + +// This structure is sent over the net to describe a screen shake event +typedef struct +{ + unsigned short amplitude; // FIXED 4.12 amount of shake + unsigned short duration; // FIXED 4.12 seconds duration + unsigned short frequency; // FIXED 8.8 noise frequency (low frequency is a jerk,high frequency is a rumble) +} ScreenShake; + +extern void V_ApplyShake( float *origin, float *angles, float factor ); +extern void V_CalcShake( void ); +extern int V_ScreenShake( const char *pszName, int iSize, void *pbuf ); +extern int V_ScreenFade( const char *pszName, int iSize, void *pbuf ); + + +// Fade in/out +extern int gmsgFade; + +#define FFADE_IN 0x0000 // Just here so we don't pass 0 into the function +#define FFADE_OUT 0x0001 // Fade out (not in) +#define FFADE_MODULATE 0x0002 // Modulate (don't blend) +#define FFADE_STAYOUT 0x0004 // ignores the duration, stays faded out until new ScreenFade message received +#define FFADE_LONGFADE 0x0008 // used to indicate the fade can be longer than 16 seconds (added for czero) + + +// This structure is sent over the net to describe a screen fade event +typedef struct +{ + unsigned short duration; // FIXED 4.12 seconds duration + unsigned short holdTime; // FIXED 4.12 seconds duration until reset (fade & hold) + short fadeFlags; // flags + byte r, g, b, a; // fade to color ( max alpha ) +} ScreenFade; + +#endif // SHAKE_H + diff --git a/dep/hlsdk/engine/sound.h b/dep/hlsdk/engine/sound.h new file mode 100644 index 0000000..e7ccad0 --- /dev/null +++ b/dep/hlsdk/engine/sound.h @@ -0,0 +1,67 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "quakedef.h" + +// max number of sentences in game. NOTE: this must match CVOXFILESENTENCEMAX in dlls\util.h!!! +const int CVOXFILESENTENCEMAX = 1536; + +typedef struct sfx_s +{ + char name[64]; + cache_user_t cache; + int servercount; +} sfx_t; + +void S_Init(); +void S_AmbientOff(); +void S_AmbientOn(); +void S_Shutdown(); +void S_TouchSound(char *sample); +void S_ClearBuffer(); +void S_StartStaticSound(int entnum, int entchannel, sfx_t *sfx, vec_t *origin, float vol, float attenuation, int flags, int pitch); +void S_StartDynamicSound(int entnum, int entchannel, sfx_t *sfx, vec_t *origin, float fvol, float attenuation, int flags, int pitch); +void S_StopSound(int entnum, int entchannel); +sfx_t *S_PrecacheSound(char *sample); +void S_ClearPrecache(); +void S_Update(vec_t * origin, vec_t * v_forward, vec_t * v_right, vec_t * v_up); +void S_StopAllSounds(qboolean clear); +void S_BeginPrecaching(); +void S_EndPrecaching(); +void S_ExtraUpdate(); +void S_LocalSound(char * s); +void S_BlockSound(); +void S_PrintStats(); +qboolean Voice_RecordStart(const char * pUncompressedFile, const char * pDecompressedFile, const char * pMicInputFile); +qboolean Voice_IsRecording(); +void Voice_RegisterCvars(); +void Voice_Deinit(); +void Voice_Idle(float frametime); +qboolean Voice_RecordStop(); diff --git a/dep/hlsdk/engine/spritegn.h b/dep/hlsdk/engine/spritegn.h new file mode 100644 index 0000000..f6145d7 --- /dev/null +++ b/dep/hlsdk/engine/spritegn.h @@ -0,0 +1,84 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef SPRITEGN_H +#define SPRITEGN_H +#ifdef _WIN32 +#pragma once +#endif + +#include "modelgen.h" +#include "commonmacros.h" + +#define SPRITE_VERSION 2 // Half-Life sprites +#define IDSPRITEHEADER MAKEID('I', 'D', 'S', 'P') // little-endian "IDSP" + +typedef enum spriteframetype_e +{ + SPR_SINGLE = 0, + SPR_GROUP, + SPR_ANGLED +} spriteframetype_t; + +typedef struct dsprite_s +{ + int ident; + int version; + int type; + int texFormat; + float boundingradius; + int width; + int height; + int numframes; + float beamlength; + synctype_t synctype; +} dsprite_t; + +typedef struct dspriteframe_s +{ + int origin[2]; + int width; + int height; +} dspriteframe_t; + +typedef struct dspritegroup_s +{ + int numframes; +} dspritegroup_t; + +typedef struct dspriteinterval_s +{ + float interval; +} dspriteinterval_t; + +typedef struct dspriteframetype_s +{ + spriteframetype_t type; +} dspriteframetype_t; + +#endif // SPRITEGN_H diff --git a/dep/hlsdk/engine/static_map.h b/dep/hlsdk/engine/static_map.h new file mode 100644 index 0000000..d19033a --- /dev/null +++ b/dep/hlsdk/engine/static_map.h @@ -0,0 +1,257 @@ +#pragma once + +#include "archtypes.h" +#include "crc32c.h" + +template +class CStaticMap { +protected: + virtual uint32 hash(const T_KEY& val) { + return crc32c((const unsigned char*)&val, sizeof(T_KEY)); + } + + virtual bool equals(const T_KEY& val1, const T_KEY& val2) { + return 0 == memcmp(&val1, &val2, sizeof(T_KEY)); + } + + struct map_node_t { + map_node_t* prev; + map_node_t* next; + T_KEY key; + T_VAL val; + }; + +private: + map_node_t* m_RootNodes[1 << ASSOC_2N]; + map_node_t m_AllNodes[MAX_VALS]; + map_node_t* m_FreeRoot; + + unsigned int GetRoodNodeId(const T_KEY& val) { return hash(val) & (0xFFFFFFFF >> (32 - ASSOC_2N)); } + + void unlink(map_node_t* node) { + map_node_t* prev = node->prev; + map_node_t* next = node->next; + + if (prev) { + prev->next = next; + } + + if (next) { + next->prev = prev; + } + + if (!prev) { + // this was a root node + unsigned int rootId = GetRoodNodeId(node->key); + if (m_RootNodes[rootId] != node) { + Sys_Error("%s: invalid root node", __func__); + return; + } + + m_RootNodes[rootId] = next; + } + } + + void link(map_node_t* node) { + unsigned int rootId = GetRoodNodeId(node->key); + map_node_t* root = m_RootNodes[rootId]; + node->prev = NULL; + node->next = root; + + if (root) { + root->prev = node; + } + + m_RootNodes[rootId] = node; + } + + void linkToFreeStack(map_node_t* node) { + node->next = m_FreeRoot; + if (m_FreeRoot) { + m_FreeRoot->prev = node; + } + m_FreeRoot = node; + } + +public: + CStaticMap() { + clear(); + } + + void clear() { + memset(m_RootNodes, 0, sizeof(m_RootNodes)); + memset(m_AllNodes, 0, sizeof(m_AllNodes)); + m_FreeRoot = NULL; + + for (int i = 0; i < MAX_VALS; i++) { + linkToFreeStack(&m_AllNodes[i]); + } + } + + map_node_t* get(const T_KEY& key) { + unsigned int rootId = GetRoodNodeId(key); + map_node_t* n = m_RootNodes[rootId]; + while (n) { + if (equals(n->key, key)) { + return n; + } + n = n->next; + } + return NULL; + } + + bool put(const T_KEY& key, T_VAL& val) { + map_node_t* n = get(key); + if (n) { + n->val = val; + return true; + } + + if (!m_FreeRoot) { + return false; + } + + n = m_FreeRoot; + m_FreeRoot = m_FreeRoot->next; + + n->key = key; + n->val = val; + + unsigned int rootId = GetRoodNodeId(key); + map_node_t* root = m_RootNodes[rootId]; + + if (root) { + root->prev = n; + } + + n->prev = NULL; + n->next = root; + m_RootNodes[rootId] = n; + + return true; + } + + void remove(map_node_t* node) { + unlink(node); + linkToFreeStack(node); + } + + bool remove(const T_KEY& key) { + map_node_t* n = get(key); + if (!n) { + return false; + } + + remove(n); + return true; + } + + class Iterator { + friend class CStaticMap; + protected: + CStaticMap* m_Map; + map_node_t** m_RootNodes; + unsigned int m_NextRootNode; + map_node_t* m_CurNode; + + void searchForNextNode() { + if (m_CurNode && m_CurNode->next) { + m_CurNode = m_CurNode->next; + return; + } + + m_CurNode = NULL; + while (!m_CurNode) { + if (m_NextRootNode >= (1 << ASSOC_2N)) { + return; + } + m_CurNode = m_RootNodes[m_NextRootNode++]; + } + } + + + Iterator(CStaticMap* m) { + m_Map = m; + m_RootNodes = m_Map->m_RootNodes; + m_NextRootNode = 0; + m_CurNode = NULL; + searchForNextNode(); + } + + public: + map_node_t* next() { + searchForNextNode(); + return m_CurNode; + } + + map_node_t* current() { + return m_CurNode; + } + + void remove() { + m_Map->remove(m_CurNode); + m_CurNode = NULL; + } + + bool hasElement() { + return m_CurNode != NULL; + } + }; + + Iterator iterator() { + return Iterator(this); + } +}; + +template +class CStringKeyStaticMap : public CStaticMap { +protected: + virtual uint32 hash(const char* const &val) { + return crc32c((const unsigned char*)val, strlen(val)); + } + + virtual bool equals(const char* const &val1, const char* const &val2) { + return !strcmp(val1, val2); + } + +public: + CStringKeyStaticMap() { + } + +}; + +template +class CICaseStringKeyStaticMap : public CStaticMap { +protected: + virtual uint32 hash(const char* const &val) { + uint32 cksum = 0; + const char* pcc = val; + if (cpuinfo.sse4_2) { + while (*pcc) { + char cc = *(pcc++); + if (cc >= 'A' || cc <= 'Z') { + cc |= 0x20; + } + cksum = crc32c_t8_sse(cksum, cc); + } + } else { + while (*pcc) { + char cc = *(pcc++); + if (cc >= 'A' || cc <= 'Z') { + cc |= 0x20; + } + cksum = crc32c_t8_nosse(cksum, cc); + } + } + return cksum; + } + + virtual bool equals(const char* const &val1, const char* const &val2) { + return !_stricmp(val1, val2); + } + +public: + CICaseStringKeyStaticMap() { + } + +}; diff --git a/dep/hlsdk/engine/studio.h b/dep/hlsdk/engine/studio.h new file mode 100644 index 0000000..2f1601d --- /dev/null +++ b/dep/hlsdk/engine/studio.h @@ -0,0 +1,364 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#pragma once + +/* +============================================================================== + +STUDIO MODELS + +Studio models are position independent, so the cache manager can move them. +============================================================================== +*/ + + +#define MAXSTUDIOTRIANGLES 20000 // TODO: tune this +#define MAXSTUDIOVERTS 2048 // TODO: tune this +#define MAXSTUDIOSEQUENCES 2048 // total animation sequences +#define MAXSTUDIOSKINS 100 // total textures +#define MAXSTUDIOSRCBONES 512 // bones allowed at source movement +#define MAXSTUDIOBONES 128 // total bones actually used +#define MAXSTUDIOMODELS 32 // sub-models per model +#define MAXSTUDIOBODYPARTS 32 +#define MAXSTUDIOGROUPS 16 +#define MAXSTUDIOANIMATIONS 2048 // per sequence +#define MAXSTUDIOMESHES 256 +#define MAXSTUDIOEVENTS 1024 +#define MAXSTUDIOPIVOTS 256 +#define MAXSTUDIOCONTROLLERS 8 + +typedef struct +{ + int id; + int version; + + char name[64]; + int length; + + vec3_t eyeposition; // ideal eye position + vec3_t min; // ideal movement hull size + vec3_t max; + + vec3_t bbmin; // clipping bounding box + vec3_t bbmax; + + int flags; + + int numbones; // bones + int boneindex; + + int numbonecontrollers; // bone controllers + int bonecontrollerindex; + + int numhitboxes; // complex bounding boxes + int hitboxindex; + + int numseq; // animation sequences + int seqindex; + + int numseqgroups; // demand loaded sequences + int seqgroupindex; + + int numtextures; // raw textures + int textureindex; + int texturedataindex; + + int numskinref; // replaceable textures + int numskinfamilies; + int skinindex; + + int numbodyparts; + int bodypartindex; + + int numattachments; // queryable attachable points + int attachmentindex; + + int soundtable; + int soundindex; + int soundgroups; + int soundgroupindex; + + int numtransitions; // animation node to animation node transition graph + int transitionindex; +} studiohdr_t; + +// header for demand loaded sequence group data +typedef struct +{ + int id; + int version; + + char name[64]; + int length; +} studioseqhdr_t; + +// bones +typedef struct +{ + char name[32]; // bone name for symbolic links + int parent; // parent bone + int flags; // ?? + int bonecontroller[6]; // bone controller index, -1 == none + float value[6]; // default DoF values + float scale[6]; // scale for delta DoF values +} mstudiobone_t; + + +// bone controllers +typedef struct +{ + int bone; // -1 == 0 + int type; // X, Y, Z, XR, YR, ZR, M + float start; + float end; + int rest; // byte index value at rest + int index; // 0-3 user set controller, 4 mouth +} mstudiobonecontroller_t; + +// intersection boxes +typedef struct +{ + int bone; + int group; // intersection group + vec3_t bbmin; // bounding box + vec3_t bbmax; +} mstudiobbox_t; + +// demand loaded sequence groups +typedef struct +{ + char label[32]; // textual name + char name[64]; // file name + int32 unused1; // was "cache" - index pointer + int unused2; // was "data" - hack for group 0 +} mstudioseqgroup_t; + +// sequence descriptions +typedef struct +{ + char label[32]; // sequence label + + float fps; // frames per second + int flags; // looping/non-looping flags + + int activity; + int actweight; + + int numevents; + int eventindex; + + int numframes; // number of frames per sequence + + int numpivots; // number of foot pivots + int pivotindex; + + int motiontype; + int motionbone; + vec3_t linearmovement; + int automoveposindex; + int automoveangleindex; + + vec3_t bbmin; // per sequence bounding box + vec3_t bbmax; + + int numblends; + int animindex; // mstudioanim_t pointer relative to start of sequence group data + // [blend][bone][X, Y, Z, XR, YR, ZR] + + int blendtype[2]; // X, Y, Z, XR, YR, ZR + float blendstart[2]; // starting value + float blendend[2]; // ending value + int blendparent; + + int seqgroup; // sequence group for demand loading + + int entrynode; // transition node at entry + int exitnode; // transition node at exit + int nodeflags; // transition rules + + int nextseq; // auto advancing sequences +} mstudioseqdesc_t; + +// events +#include "studio_event.h" +/* +typedef struct +{ + int frame; + int event; + int type; + char options[64]; +} mstudioevent_t; +*/ + +// pivots +typedef struct +{ + vec3_t org; // pivot point + int start; + int end; +} mstudiopivot_t; + +// attachment +typedef struct +{ + char name[32]; + int type; + int bone; + vec3_t org; // attachment point + vec3_t vectors[3]; +} mstudioattachment_t; + +typedef struct +{ + unsigned short offset[6]; +} mstudioanim_t; + +// animation frames +typedef union +{ + struct { + byte valid; + byte total; + } num; + short value; +} mstudioanimvalue_t; + + + +// body part index +typedef struct +{ + char name[64]; + int nummodels; + int base; + int modelindex; // index into models array +} mstudiobodyparts_t; + + + +// skin info +typedef struct +{ + char name[64]; + int flags; + int width; + int height; + int index; +} mstudiotexture_t; + + +// skin families +// short index[skinfamilies][skinref] + +// studio models +typedef struct +{ + char name[64]; + + int type; + + float boundingradius; + + int nummesh; + int meshindex; + + int numverts; // number of unique vertices + int vertinfoindex; // vertex bone info + int vertindex; // vertex vec3_t + int numnorms; // number of unique surface normals + int norminfoindex; // normal bone info + int normindex; // normal vec3_t + + int numgroups; // deformation groups + int groupindex; +} mstudiomodel_t; + + +// vec3_t boundingbox[model][bone][2]; // complex intersection info + + +// meshes +typedef struct +{ + int numtris; + int triindex; + int skinref; + int numnorms; // per mesh normals + int normindex; // normal vec3_t +} mstudiomesh_t; + +// triangles +#if 0 +typedef struct +{ + short vertindex; // index into vertex array + short normindex; // index into normal array + short s,t; // s,t position on skin +} mstudiotrivert_t; +#endif + +#define STUDIO_DYNAMIC_LIGHT 0x0100 // dynamically get lighting from floor or ceil (flying monsters) +#define STUDIO_TRACE_HITBOX 0x0200 // always use hitbox trace instead of bbox + +// lighting options +#define STUDIO_NF_FLATSHADE 0x0001 +#define STUDIO_NF_CHROME 0x0002 +#define STUDIO_NF_FULLBRIGHT 0x0004 +#define STUDIO_NF_NOMIPS 0x0008 +#define STUDIO_NF_ALPHA 0x0010 +#define STUDIO_NF_ADDITIVE 0x0020 +#define STUDIO_NF_MASKED 0x0040 + +// motion flags +#define STUDIO_X 0x0001 +#define STUDIO_Y 0x0002 +#define STUDIO_Z 0x0004 +#define STUDIO_XR 0x0008 +#define STUDIO_YR 0x0010 +#define STUDIO_ZR 0x0020 +#define STUDIO_LX 0x0040 +#define STUDIO_LY 0x0080 +#define STUDIO_LZ 0x0100 +#define STUDIO_AX 0x0200 +#define STUDIO_AY 0x0400 +#define STUDIO_AZ 0x0800 +#define STUDIO_AXR 0x1000 +#define STUDIO_AYR 0x2000 +#define STUDIO_AZR 0x4000 +#define STUDIO_TYPES 0x7FFF +#define STUDIO_RLOOP 0x8000 // controller that wraps shortest distance + +// bonecontroller types +#define STUDIO_MOUTH 4 // hardcoded + +// sequence flags +#define STUDIO_LOOPING 0x0001 + +// bone flags +#define STUDIO_HAS_NORMALS 0x0001 +#define STUDIO_HAS_VERTICES 0x0002 +#define STUDIO_HAS_BBOX 0x0004 +#define STUDIO_HAS_CHROME 0x0008 // if any of the textures have chrome on them + +#define RAD_TO_STUDIO (32768.0/M_PI) +#define STUDIO_TO_RAD (M_PI/32768.0) + + +#define STUDIO_NUM_HULLS 128 +#define STUDIO_NUM_PLANES (STUDIO_NUM_HULLS * 6) +#define STUDIO_CACHE_SIZE 16 + + diff --git a/dep/hlsdk/engine/sys_shared.cpp b/dep/hlsdk/engine/sys_shared.cpp new file mode 100644 index 0000000..b9a5033 --- /dev/null +++ b/dep/hlsdk/engine/sys_shared.cpp @@ -0,0 +1,74 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#include "sys_shared.h" + +#if defined(__GNUC__) +#include +#elif _MSC_VER >= 1400 && !defined(ASMLIB_H) +#include // __cpuidex +#endif + +#define SSE3_FLAG (1<<0) +#define SSSE3_FLAG (1<<9) +#define SSE4_1_FLAG (1<<19) +#define SSE4_2_FLAG (1<<20) +#define POPCNT_FLAG (1<<23) +#define AVX_FLAG (1<<28) +#define AVX2_FLAG (1<<5) + +cpuinfo_t cpuinfo; + +void Sys_CheckCpuInstructionsSupport(void) +{ + unsigned int cpuid_data[4]; + +#if defined ASMLIB_H + cpuid_ex((int *)cpuid_data, 1, 0); +#elif defined(__GNUC__) + __get_cpuid(0x1, &cpuid_data[0], &cpuid_data[1], &cpuid_data[2], &cpuid_data[3]); +#else + __cpuidex((int *)cpuid_data, 1, 0); +#endif + + cpuinfo.sse3 = (cpuid_data[2] & SSE3_FLAG) ? 1 : 0; // ecx + cpuinfo.ssse3 = (cpuid_data[2] & SSSE3_FLAG) ? 1 : 0; + cpuinfo.sse4_1 = (cpuid_data[2] & SSE4_1_FLAG) ? 1 : 0; + cpuinfo.sse4_2 = (cpuid_data[2] & SSE4_2_FLAG) ? 1 : 0; + cpuinfo.popcnt = (cpuid_data[2] & POPCNT_FLAG) ? 1 : 0; + cpuinfo.avx = (cpuid_data[2] & AVX_FLAG) ? 1 : 0; + +#if defined ASMLIB_H + cpuid_ex((int *)cpuid_data, 7, 0); +#elif defined(__GNUC__) + __get_cpuid(0x7, &cpuid_data[0], &cpuid_data[1], &cpuid_data[2], &cpuid_data[3]); +#else + __cpuidex((int *)cpuid_data, 7, 0); +#endif + + cpuinfo.avx2 = (cpuid_data[1] & AVX2_FLAG) ? 1 : 0; // ebx +} diff --git a/dep/hlsdk/engine/sys_shared.h b/dep/hlsdk/engine/sys_shared.h new file mode 100644 index 0000000..5b5da98 --- /dev/null +++ b/dep/hlsdk/engine/sys_shared.h @@ -0,0 +1,39 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include + +typedef struct cpuinfo_s +{ + uint8 sse3, ssse3, sse4_1, sse4_2, avx, avx2, popcnt; +} cpuinfo_t; + +extern cpuinfo_t cpuinfo; + +void Sys_CheckCpuInstructionsSupport(void); diff --git a/dep/hlsdk/engine/userid.h b/dep/hlsdk/engine/userid.h new file mode 100644 index 0000000..53b76f4 --- /dev/null +++ b/dep/hlsdk/engine/userid.h @@ -0,0 +1,46 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "archtypes.h" + +// Authentication types +enum AUTH_IDTYPE +{ + AUTH_IDTYPE_UNKNOWN = 0, + AUTH_IDTYPE_STEAM = 1, + AUTH_IDTYPE_VALVE = 2, + AUTH_IDTYPE_LOCAL = 3 +}; + +typedef struct USERID_s +{ + int idtype; + uint64 m_SteamID; + unsigned int clientip; +} USERID_t; diff --git a/dep/hlsdk/engine/usermsg.h b/dep/hlsdk/engine/usermsg.h new file mode 100644 index 0000000..e3b0897 --- /dev/null +++ b/dep/hlsdk/engine/usermsg.h @@ -0,0 +1,51 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" +#include "quakedef.h" + +#include +#include + +#define g_pClientUserMsgs (*pg_pClientUserMsgs) + +typedef struct _UserMsg +{ + int iMsg; + int iSize; + char szName[16]; + struct _UserMsg *next; + pfnUserMsgHook pfn; +} UserMsg; + +bool HookUserMsg(char *pszMsgName, pfnUserMsgHook pfn); + +extern UserMsg *g_pClientUserMsgs; +extern std::map g_ClientUserMsgsMap; diff --git a/dep/hlsdk/game_shared/GameEvent.h b/dep/hlsdk/game_shared/GameEvent.h new file mode 100644 index 0000000..c585fff --- /dev/null +++ b/dep/hlsdk/game_shared/GameEvent.h @@ -0,0 +1,138 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +enum GameEventType +{ + EVENT_INVALID = 0, + EVENT_WEAPON_FIRED, // tell bots the player is attack (argumens: 1 = attacker, 2 = NULL) + EVENT_WEAPON_FIRED_ON_EMPTY, // tell bots the player is attack without clip ammo (argumens: 1 = attacker, 2 = NULL) + EVENT_WEAPON_RELOADED, // tell bots the player is reloading his weapon (argumens: 1 = reloader, 2 = NULL) + + EVENT_HE_GRENADE_EXPLODED, // tell bots the HE grenade is exploded (argumens: 1 = grenade thrower, 2 = NULL) + EVENT_FLASHBANG_GRENADE_EXPLODED, // tell bots the flashbang grenade is exploded (argumens: 1 = grenade thrower, 2 = explosion origin) + EVENT_SMOKE_GRENADE_EXPLODED, // tell bots the smoke grenade is exploded (argumens: 1 = grenade thrower, 2 = NULL) + EVENT_GRENADE_BOUNCED, + + EVENT_BEING_SHOT_AT, + EVENT_PLAYER_BLINDED_BY_FLASHBANG, // tell bots the player is flashed (argumens: 1 = flashed player, 2 = NULL) + EVENT_PLAYER_FOOTSTEP, // tell bots the player is running (argumens: 1 = runner, 2 = NULL) + EVENT_PLAYER_JUMPED, // tell bots the player is jumped (argumens: 1 = jumper, 2 = NULL) + EVENT_PLAYER_DIED, // tell bots the player is killed (argumens: 1 = victim, 2 = killer) + EVENT_PLAYER_LANDED_FROM_HEIGHT, // tell bots the player is fell with some damage (argumens: 1 = felled player, 2 = NULL) + EVENT_PLAYER_TOOK_DAMAGE, // tell bots the player is take damage (argumens: 1 = victim, 2 = attacker) + EVENT_HOSTAGE_DAMAGED, // tell bots the player has injured a hostage (argumens: 1 = hostage, 2 = injurer) + EVENT_HOSTAGE_KILLED, // tell bots the player has killed a hostage (argumens: 1 = hostage, 2 = killer) + + EVENT_DOOR, // tell bots the door is moving (argumens: 1 = door, 2 = NULL) + EVENT_BREAK_GLASS, // tell bots the glass has break (argumens: 1 = glass, 2 = NULL) + EVENT_BREAK_WOOD, // tell bots the wood has break (argumens: 1 = wood, 2 = NULL) + EVENT_BREAK_METAL, // tell bots the metal/computer has break (argumens: 1 = metal/computer, 2 = NULL) + EVENT_BREAK_FLESH, // tell bots the flesh has break (argumens: 1 = flesh, 2 = NULL) + EVENT_BREAK_CONCRETE, // tell bots the concrete has break (argumens: 1 = concrete, 2 = NULL) + + EVENT_BOMB_PLANTED, // tell bots the bomb has been planted (argumens: 1 = planter, 2 = NULL) + EVENT_BOMB_DROPPED, // tell bots the bomb has been dropped (argumens: 1 = NULL, 2 = NULL) + EVENT_BOMB_PICKED_UP, // let the bots hear the bomb pickup (argumens: 1 = player that pickup c4, 2 = NULL) + EVENT_BOMB_BEEP, // let the bots hear the bomb beeping (argumens: 1 = c4, 2 = NULL) + EVENT_BOMB_DEFUSING, // tell the bots someone has started defusing (argumens: 1 = defuser, 2 = NULL) + EVENT_BOMB_DEFUSE_ABORTED, // tell the bots someone has aborted defusing (argumens: 1 = NULL, 2 = NULL) + EVENT_BOMB_DEFUSED, // tell the bots the bomb is defused (argumens: 1 = defuser, 2 = NULL) + EVENT_BOMB_EXPLODED, // let the bots hear the bomb exploding (argumens: 1 = NULL, 2 = NULL) + + EVENT_HOSTAGE_USED, // tell bots the hostage is used (argumens: 1 = user, 2 = NULL) + EVENT_HOSTAGE_RESCUED, // tell bots the hostage is rescued (argumens: 1 = rescuer (CBasePlayer *), 2 = hostage (CHostage *)) + EVENT_ALL_HOSTAGES_RESCUED, // tell bots the all hostages are rescued (argumens: 1 = NULL, 2 = NULL) + + EVENT_VIP_ESCAPED, // tell bots the VIP is escaped (argumens: 1 = NULL, 2 = NULL) + EVENT_VIP_ASSASSINATED, // tell bots the VIP is assassinated (argumens: 1 = NULL, 2 = NULL) + EVENT_TERRORISTS_WIN, // tell bots the terrorists won the round (argumens: 1 = NULL, 2 = NULL) + EVENT_CTS_WIN, // tell bots the CTs won the round (argumens: 1 = NULL, 2 = NULL) + EVENT_ROUND_DRAW, // tell bots the round was a draw (argumens: 1 = NULL, 2 = NULL) + EVENT_ROUND_WIN, // tell carreer the round was a win (argumens: 1 = NULL, 2 = NULL) + EVENT_ROUND_LOSS, // tell carreer the round was a loss (argumens: 1 = NULL, 2 = NULL) + EVENT_ROUND_START, // tell bots the round was started (when freeze period is expired) (argumens: 1 = NULL, 2 = NULL) + EVENT_PLAYER_SPAWNED, // tell bots the player is spawned (argumens: 1 = spawned player, 2 = NULL) + EVENT_CLIENT_CORPSE_SPAWNED, + EVENT_BUY_TIME_START, + EVENT_PLAYER_LEFT_BUY_ZONE, + EVENT_DEATH_CAMERA_START, + EVENT_KILL_ALL, + EVENT_ROUND_TIME, + EVENT_DIE, + EVENT_KILL, + EVENT_HEADSHOT, + EVENT_KILL_FLASHBANGED, + EVENT_TUTOR_BUY_MENU_OPENNED, + EVENT_TUTOR_AUTOBUY, + EVENT_PLAYER_BOUGHT_SOMETHING, + EVENT_TUTOR_NOT_BUYING_ANYTHING, + EVENT_TUTOR_NEED_TO_BUY_PRIMARY_WEAPON, + EVENT_TUTOR_NEED_TO_BUY_PRIMARY_AMMO, + EVENT_TUTOR_NEED_TO_BUY_SECONDARY_AMMO, + EVENT_TUTOR_NEED_TO_BUY_ARMOR, + EVENT_TUTOR_NEED_TO_BUY_DEFUSE_KIT, + EVENT_TUTOR_NEED_TO_BUY_GRENADE, + EVENT_CAREER_TASK_DONE, + + EVENT_START_RADIO_1, + EVENT_RADIO_COVER_ME, + EVENT_RADIO_YOU_TAKE_THE_POINT, + EVENT_RADIO_HOLD_THIS_POSITION, + EVENT_RADIO_REGROUP_TEAM, + EVENT_RADIO_FOLLOW_ME, + EVENT_RADIO_TAKING_FIRE, + EVENT_START_RADIO_2, + EVENT_RADIO_GO_GO_GO, + EVENT_RADIO_TEAM_FALL_BACK, + EVENT_RADIO_STICK_TOGETHER_TEAM, + EVENT_RADIO_GET_IN_POSITION_AND_WAIT, + EVENT_RADIO_STORM_THE_FRONT, + EVENT_RADIO_REPORT_IN_TEAM, + EVENT_START_RADIO_3, + EVENT_RADIO_AFFIRMATIVE, + EVENT_RADIO_ENEMY_SPOTTED, + EVENT_RADIO_NEED_BACKUP, + EVENT_RADIO_SECTOR_CLEAR, + EVENT_RADIO_IN_POSITION, + EVENT_RADIO_REPORTING_IN, + EVENT_RADIO_GET_OUT_OF_THERE, + EVENT_RADIO_NEGATIVE, + EVENT_RADIO_ENEMY_DOWN, + EVENT_END_RADIO, + + EVENT_NEW_MATCH, // tell bots the game is new (argumens: 1 = NULL, 2 = NULL) + EVENT_PLAYER_CHANGED_TEAM, // tell bots the player is switch his team (also called from ClientPutInServer()) (argumens: 1 = switcher, 2 = NULL) + EVENT_BULLET_IMPACT, // tell bots the player is shoot at wall (argumens: 1 = shooter, 2 = shoot trace end position) + EVENT_GAME_COMMENCE, // tell bots the game is commencing (argumens: 1 = NULL, 2 = NULL) + EVENT_WEAPON_ZOOMED, // tell bots the player is switch weapon zoom (argumens: 1 = zoom switcher, 2 = NULL) + EVENT_HOSTAGE_CALLED_FOR_HELP, // tell bots the hostage is talking (argumens: 1 = listener, 2 = NULL) + NUM_GAME_EVENTS, +}; + +extern const char *GameEventName[ NUM_GAME_EVENTS + 1 ]; diff --git a/dep/hlsdk/game_shared/bitvec.h b/dep/hlsdk/game_shared/bitvec.h new file mode 100644 index 0000000..f541bff --- /dev/null +++ b/dep/hlsdk/game_shared/bitvec.h @@ -0,0 +1,157 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class CBitVecAccessor { +public: + CBitVecAccessor(uint32 *pDWords, int iBit); + + void operator=(int val); + operator uint32(); + +private: + uint32 *m_pDWords; + int m_iBit; +}; + +// CBitVec allows you to store a list of bits and do operations on them like they were +// an atomic type +template +class CBitVec { +public: + CBitVec(); + + // Set all values to the specified value (0 or 1..) + void Init(int val = 0); + + // Access the bits like an array. + CBitVecAccessor operator[](int i); + + // Operations on other bit vectors. + CBitVec &operator=(CBitVec const &other); + bool operator==(CBitVec const &other); + bool operator!=(CBitVec const &other); + + // Get underlying dword representations of the bits. + int GetNumDWords() { return NUM_DWORDS; } + uint32 GetDWord(int i); + void SetDWord(int i, uint32 val); + int GetNumBits(); + +private: + enum { NUM_DWORDS = NUM_BITS / 32 + !!(NUM_BITS & 31) }; + + unsigned int m_DWords[ NUM_DWORDS ]; +}; + +inline CBitVecAccessor::CBitVecAccessor(uint32 *pDWords, int iBit) +{ + m_pDWords = pDWords; + m_iBit = iBit; +} + +inline void CBitVecAccessor::operator=(int val) +{ + if (val) + m_pDWords[m_iBit >> 5] |= (1 << (m_iBit & 31)); + else + m_pDWords[m_iBit >> 5] &= ~(uint32)(1 << (m_iBit & 31)); +} + +inline CBitVecAccessor::operator uint32() +{ + return m_pDWords[m_iBit >> 5] & (1 << (m_iBit & 31)); +} + +template +inline int CBitVec::GetNumBits() +{ + return NUM_BITS; +} + +template +inline CBitVec::CBitVec() +{ + for (int i = 0; i < NUM_DWORDS; ++i) + m_DWords[i] = 0; +} + +template +inline void CBitVec::Init(int val) +{ + for (int i = 0; i < GetNumBits(); ++i) + { + (*this)[i] = val; + } +} + +template +inline CBitVec &CBitVec::operator=(CBitVec const &other) +{ + Q_memcpy(m_DWords, other.m_DWords, sizeof(m_DWords)); + return *this; +} + +template +inline CBitVecAccessor CBitVec::operator[](int i) +{ + assert(i >= 0 && i < GetNumBits()); + return CBitVecAccessor(m_DWords, i); +} + +template +inline bool CBitVec::operator==(CBitVec const &other) +{ + for (int i = 0; i < NUM_DWORDS; ++i) + { + if (m_DWords[i] != other.m_DWords[i]) + return false; + } + + return true; +} + +template +inline bool CBitVec::operator!=(CBitVec const &other) +{ + return !(*this == other); +} + +template +inline uint32 CBitVec::GetDWord(int i) +{ + assert(i >= 0 && i < NUM_DWORDS); + return m_DWords[i]; +} + +template +inline void CBitVec::SetDWord(int i, uint32 val) +{ + assert(i >= 0 && i < NUM_DWORDS); + m_DWords[i] = val; +} diff --git a/dep/hlsdk/game_shared/bot/bot.h b/dep/hlsdk/game_shared/bot/bot.h new file mode 100644 index 0000000..c391ec2 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/bot.h @@ -0,0 +1,164 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class BotProfile; + +// The base bot class from which bots for specific games are derived +class CBot: public CBasePlayer { +public: + virtual void Spawn() = 0; + + // invoked when injured by something + virtual BOOL TakeDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType) = 0; + + // invoked when killed + virtual void Killed(entvars_t *pevAttacker, int iGib) = 0; + virtual BOOL IsNetClient() = 0; + virtual void Think() = 0; + virtual BOOL IsBot() = 0; + virtual Vector GetAutoaimVector(float flDelta) = 0; + + // invoked when in contact with a CWeaponBox + virtual void OnTouchingWeapon(CWeaponBox *box) = 0; + virtual bool Initialize(const BotProfile *profile) = 0; + virtual void SpawnBot() = 0; + + // lightweight maintenance, invoked frequently + virtual void Upkeep() = 0; + + // heavyweight algorithms, invoked less often + virtual void Update() = 0; + + virtual void Run() = 0; + virtual void Walk() = 0; + virtual void Crouch() = 0; + virtual void StandUp() = 0; + virtual void MoveForward() = 0; + virtual void MoveBackward() = 0; + virtual void StrafeLeft() = 0; + virtual void StrafeRight() = 0; + + // returns true if jump was started + #define MUST_JUMP true + virtual bool Jump(bool mustJump = false) = 0; + + // zero any MoveForward(), Jump(), etc + virtual void ClearMovement() = 0; + + // Weapon interface + virtual void UseEnvironment() = 0; + virtual void PrimaryAttack() = 0; + virtual void ClearPrimaryAttack() = 0; + virtual void TogglePrimaryAttack() = 0; + virtual void SecondaryAttack() = 0; + virtual void Reload() = 0; + + // invoked when event occurs in the game (some events have NULL entities) + virtual void OnEvent(GameEventType event, CBaseEntity *entity = NULL, CBaseEntity *other = NULL) = 0; + + // return true if we can see the point + virtual bool IsVisible(const Vector *pos, bool testFOV = false) const = 0; + + // return true if we can see any part of the player + virtual bool IsVisible(CBasePlayer *player, bool testFOV = false, unsigned char *visParts = NULL) const = 0; + + enum VisiblePartType:uint8 + { + NONE = 0x00, + CHEST = 0x01, + HEAD = 0x02, + LEFT_SIDE = 0x04, // the left side of the object from our point of view (not their left side) + RIGHT_SIDE = 0x08, // the right side of the object from our point of view (not their right side) + FEET = 0x10 + }; + + // if enemy is visible, return the part we see + virtual bool IsEnemyPartVisible(VisiblePartType part) const = 0; + + // return true if player is facing towards us + virtual bool IsPlayerFacingMe(CBasePlayer *other) const = 0; + + // returns true if other player is pointing right at us + virtual bool IsPlayerLookingAtMe(CBasePlayer *other) const = 0; + virtual void ExecuteCommand() = 0; + virtual void SetModel(const char *modelName) = 0; + +public: + unsigned int GetID() const { return m_id; } + bool IsRunning() const { return m_isRunning; } + bool IsCrouching() const { return m_isCrouching; } + + // return time last jump began + float GetJumpTimestamp() const { return m_jumpTimestamp; } + + // return our personality profile + const BotProfile *GetProfile() const { return m_profile; } + +public: + // the "personality" profile of this bot + const BotProfile *m_profile; + + // unique bot ID + unsigned int m_id; + + // Think mechanism variables + float m_flNextBotThink; + float m_flNextFullBotThink; + + // Command interface variables + float m_flPreviousCommandTime; + + // run/walk mode + bool m_isRunning; + + // true if crouching (ducking) + bool m_isCrouching; + float m_forwardSpeed; + float m_strafeSpeed; + float m_verticalSpeed; + + // bitfield of movement buttons + unsigned short m_buttonFlags; + + // time when we last began a jump + float m_jumpTimestamp; + + // the PostureContext represents the current settings of walking and crouching + struct PostureContext + { + bool isRunning; + bool isCrouching; + }; + + enum { MAX_POSTURE_STACK = 8 }; + PostureContext m_postureStack[MAX_POSTURE_STACK]; + + // index of top of stack + int m_postureStackIndex; +}; diff --git a/dep/hlsdk/game_shared/bot/bot_constants.h b/dep/hlsdk/game_shared/bot/bot_constants.h new file mode 100644 index 0000000..14438b5 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/bot_constants.h @@ -0,0 +1,47 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// We'll define our own version of this, because everyone else does. +// This needs to stay in sync with MAX_CLIENTS, but there's no header with the #define. +#define BOT_MAX_CLIENTS 32 + +// version number is MAJOR.MINOR +#define BOT_VERSION_MAJOR 1 +#define BOT_VERSION_MINOR 50 + +// Difficulty levels +enum BotDifficultyType +{ + BOT_EASY = 0, + BOT_NORMAL, + BOT_HARD, + BOT_EXPERT, + + NUM_DIFFICULTY_LEVELS +}; diff --git a/dep/hlsdk/game_shared/bot/bot_manager.h b/dep/hlsdk/game_shared/bot/bot_manager.h new file mode 100644 index 0000000..5be97b0 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/bot_manager.h @@ -0,0 +1,72 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// STL uses exceptions, but we are not compiling with them - ignore warning +#pragma warning(disable : 4530) + +#include + +class CNavArea; +class CGrenade; + +class ActiveGrenade { +public: + int m_id; + CGrenade *m_entity; + Vector m_detonationPosition; + float m_dieTimestamp; +}; + +typedef std::list ActiveGrenadeList; + +class CBotManager { +public: + virtual ~CBotManager() {} + + virtual void ClientDisconnect(CBasePlayer *pPlayer) = 0; + virtual BOOL ClientCommand(CBasePlayer *pPlayer, const char *pcmd) = 0; + + virtual void ServerActivate() = 0; + virtual void ServerDeactivate() = 0; + + virtual void ServerCommand(const char *pcmd) = 0; + virtual void AddServerCommand(const char *cmd) = 0; + virtual void AddServerCommands() = 0; + + virtual void RestartRound() = 0; + virtual void StartFrame() = 0; + + // Events are propogated to all bots. + virtual void OnEvent(GameEventType event, CBaseEntity *entity = NULL, CBaseEntity *other = NULL) = 0; // Invoked when event occurs in the game (some events have NULL entity). + virtual unsigned int GetPlayerPriority(CBasePlayer *player) const = 0; // return priority of player (0 = max pri) + +public: + // the list of active grenades the bots are aware of + ActiveGrenadeList m_activeGrenadeList; +}; diff --git a/dep/hlsdk/game_shared/bot/bot_profile.h b/dep/hlsdk/game_shared/bot/bot_profile.h new file mode 100644 index 0000000..5f000f5 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/bot_profile.h @@ -0,0 +1,116 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// long STL names get truncated in browse info. +#pragma warning(disable : 4786) + +#ifndef _WIN32 +#include +#include +#endif // _WIN32 + +#undef min +#undef max + +#include +#include + +#include "bot_constants.h" + +enum +{ + FirstCustomSkin = 100, + NumCustomSkins = 100, + LastCustomSkin = FirstCustomSkin + NumCustomSkins - 1, +}; + +enum BotProfileTeamType +{ + BOT_TEAM_T, + BOT_TEAM_CT, + BOT_TEAM_ANY +}; + +class BotProfile { +public: + const char *GetName() const { return m_name; } + float GetAggression() const { return m_aggression; } + float GetSkill() const { return m_skill; } + float GetTeamwork() const { return m_teamwork; } + int GetWeaponPreference(int i) const { return m_weaponPreference[i]; } + int GetWeaponPreferenceCount() const { return m_weaponPreferenceCount; } + int GetCost() const { return m_cost; } + int GetSkin() const { return m_skin; } + int GetVoicePitch() const { return m_voicePitch; } + float GetReactionTime() const { return m_reactionTime; } + float GetAttackDelay() const { return m_attackDelay; } + int GetVoiceBank() const { return m_voiceBank; } + bool PrefersSilencer() const { return m_prefersSilencer; } +public: + friend class BotProfileManager; + + char *m_name; + float m_aggression; + float m_skill; + float m_teamwork; + + enum { MAX_WEAPON_PREFS = 16 }; + + int m_weaponPreference[MAX_WEAPON_PREFS]; + int m_weaponPreferenceCount; + + int m_cost; + int m_skin; + + unsigned char m_difficultyFlags; + int m_voicePitch; + float m_reactionTime; + float m_attackDelay; + enum BotProfileTeamType m_teams; + bool m_prefersSilencer; + int m_voiceBank; +}; + +typedef std::list BotProfileList; + +class BotProfileManager { +public: + typedef std::vector VoiceBankList; + const BotProfileList *GetProfileList() const { return &m_profileList; } + const VoiceBankList *GetVoiceBanks() const { return &m_voiceBanks; } + +public: + BotProfileList m_profileList; + VoiceBankList m_voiceBanks; + + char *m_skins[NumCustomSkins]; + char *m_skinModelnames[NumCustomSkins]; + char *m_skinFilenames[NumCustomSkins]; + int m_nextSkin; +}; diff --git a/dep/hlsdk/game_shared/bot/bot_util.h b/dep/hlsdk/game_shared/bot/bot_util.h new file mode 100644 index 0000000..776d421 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/bot_util.h @@ -0,0 +1,141 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define COS_TABLE_SIZE 256 + +#define RAD_TO_DEG(deg) ((deg) * 180.0 / M_PI) +#define DEG_TO_RAD(rad) ((rad) * M_PI / 180.0) + +#define SIGN(num) (((num) < 0) ? -1 : 1) +#define ABS(num) (SIGN(num) * (num)) + +class CBasePlayer; +class BotProfile; + +enum PriorityType +{ + PRIORITY_LOW, PRIORITY_MEDIUM, PRIORITY_HIGH, PRIORITY_UNINTERRUPTABLE +}; + +// Simple class for tracking intervals of game time +class IntervalTimer { +public: + IntervalTimer() { m_timestamp = -1.0f; } + void Reset() { m_timestamp = gpGlobals->time; } + void Start() { m_timestamp = gpGlobals->time; } + void Invalidate() { m_timestamp = -1.0f; } + + bool HasStarted() const { return (m_timestamp > 0.0f); } + + // if not started, elapsed time is very large + float GetElapsedTime() const { return (HasStarted()) ? (gpGlobals->time - m_timestamp) : 99999.9f; } + bool IsLessThen(float duration) const { return (gpGlobals->time - m_timestamp < duration) ? true : false; } + bool IsGreaterThen(float duration) const { return (gpGlobals->time - m_timestamp > duration) ? true : false; } + +private: + float m_timestamp; +}; + +// Simple class for counting down a short interval of time +class CountdownTimer { +public: + CountdownTimer() { m_timestamp = -1.0f; m_duration = 0.0f; } + void Reset() { m_timestamp = gpGlobals->time + m_duration; } + + void Start(float duration) { m_timestamp = gpGlobals->time + duration; m_duration = duration; } + bool HasStarted() const { return (m_timestamp > 0.0f); } + + void Invalidate() { m_timestamp = -1.0f; } + bool IsElapsed() const { return (gpGlobals->time > m_timestamp); } + +private: + float m_duration; + float m_timestamp; +}; + +// Return true if the given entity is valid +inline bool IsEntityValid(CBaseEntity *entity) +{ + if (entity == NULL) + return false; + + if (FNullEnt(entity->pev)) + return false; + + if (FStrEq(STRING(entity->pev->netname), "")) + return false; + + if (entity->pev->flags & FL_DORMANT) + return false; + + return true; +} + +// Given two line segments: startA to endA, and startB to endB, return true if they intesect +// and put the intersection point in "result". +// Note that this computes the intersection of the 2D (x,y) projection of the line segments. +inline bool IsIntersecting2D(const Vector &startA, const Vector &endA, const Vector &startB, const Vector &endB, Vector *result = NULL) +{ + float denom = (endA.x - startA.x) * (endB.y - startB.y) - (endA.y - startA.y) * (endB.x - startB.x); + if (denom == 0.0f) + { + // parallel + return false; + } + + float numS = (startA.y - startB.y) * (endB.x - startB.x) - (startA.x - startB.x) * (endB.y - startB.y); + if (numS == 0.0f) + { + // coincident + return true; + } + + float numT = (startA.y - startB.y) * (endA.x - startA.x) - (startA.x - startB.x) * (endA.y - startA.y); + float s = numS / denom; + if (s < 0.0f || s > 1.0f) + { + // intersection is not within line segment of startA to endA + return false; + } + + float t = numT / denom; + if (t < 0.0f || t > 1.0f) + { + // intersection is not within line segment of startB to endB + return false; + } + + // compute intesection point + if (result != NULL) + { + *result = startA + s * (endA - startA); + } + + return true; +} diff --git a/dep/hlsdk/game_shared/bot/improv.h b/dep/hlsdk/game_shared/bot/improv.h new file mode 100644 index 0000000..e04d26d --- /dev/null +++ b/dep/hlsdk/game_shared/bot/improv.h @@ -0,0 +1,120 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class CBaseEntity; +class CNavLadder; + +// Improv-specific events +class IImprovEvent { +public: + virtual void OnMoveToSuccess(const Vector &goal) {}; // invoked when an improv reaches its MoveTo goal + + enum MoveToFailureType + { + FAIL_INVALID_PATH = 0, + FAIL_STUCK, + FAIL_FELL_OFF, + }; + + virtual void OnMoveToFailure(const Vector &goal, MoveToFailureType reason) {} // invoked when an improv fails to reach a MoveTo goal + virtual void OnInjury(float amount) {} // invoked when the improv is injured +}; + +// The Improv interface definition +// An "Improv" is an improvisational actor that simulates the +// behavor of a human in an unscripted, "make it up as you go" manner. +class CImprov: public IImprovEvent { +public: + virtual ~CImprov() {} + virtual bool IsAlive() const = 0; // return true if this improv is alive + + virtual void MoveTo(const Vector &goal) = 0; // move improv towards far-away goal (pathfind) + virtual void LookAt(const Vector &target) = 0; // define desired view target + virtual void ClearLookAt() = 0; // remove view goal + virtual void FaceTo(const Vector &goal) = 0; // orient body towards goal + virtual void ClearFaceTo() = 0; // remove body orientation goal + + virtual bool IsAtMoveGoal(float error = 20.0f) const = 0; // return true if improv is standing on its movement goal + virtual bool HasLookAt() const = 0; // return true if improv has a look at goal + virtual bool HasFaceTo() const = 0; // return true if improv has a face to goal + virtual bool IsAtFaceGoal() const = 0; // return true if improv is facing towards its face goal + virtual bool IsFriendInTheWay(const Vector &goalPos) const = 0; // return true if a friend is blocking our line to the given goal position + virtual bool IsFriendInTheWay(CBaseEntity *myFriend, const Vector &goalPos) const = 0; // return true if the given friend is blocking our line to the given goal position + + virtual void MoveForward() = 0; + virtual void MoveBackward() = 0; + virtual void StrafeLeft() = 0; + virtual void StrafeRight() = 0; + virtual bool Jump() = 0; + virtual void Crouch() = 0; + virtual void StandUp() = 0; // "un-crouch" + + virtual void TrackPath(const Vector &pathGoal, float deltaT) = 0; // move along path by following "pathGoal" + virtual void StartLadder(const CNavLadder *ladder, enum NavTraverseType how, const Vector *approachPos, const Vector *departPos) = 0; // invoked when a ladder is encountered while following a path + + virtual bool TraverseLadder(const CNavLadder *ladder, enum NavTraverseType how, const Vector *approachPos, const Vector *departPos, float deltaT) = 0; // traverse given ladder + virtual bool GetSimpleGroundHeightWithFloor(const Vector *pos, float *height, Vector *normal = NULL) = 0; // find "simple" ground height, treating current nav area as part of the floor + + virtual void Run() = 0; + virtual void Walk() = 0; + virtual void Stop() = 0; + + virtual float GetMoveAngle() const = 0; // return direction of movement + virtual float GetFaceAngle() const = 0; // return direction of view + + virtual const Vector &GetFeet() const = 0; // return position of "feet" - point below centroid of improv at feet level + virtual const Vector &GetCentroid() const = 0; + virtual const Vector &GetEyes() const = 0; + + virtual bool IsRunning() const = 0; + virtual bool IsWalking() const = 0; + virtual bool IsStopped() const = 0; + + virtual bool IsCrouching() const = 0; + virtual bool IsJumping() const = 0; + virtual bool IsUsingLadder() const = 0; + virtual bool IsOnGround() const = 0; + virtual bool IsMoving() const = 0; // if true, improv is walking, crawling, running somewhere + + virtual bool CanRun() const = 0; + virtual bool CanCrouch() const = 0; + virtual bool CanJump() const = 0; + virtual bool IsVisible(const Vector &pos, bool testFOV = false) const = 0; // return true if improv can see position + virtual bool IsPlayerLookingAtMe(CBasePlayer *other, float cosTolerance = 0.95f) const = 0; // return true if 'other' is looking right at me + virtual CBasePlayer *IsAnyPlayerLookingAtMe(int team = 0, float cosTolerance = 0.95f) const = 0; // return player on given team that is looking right at me (team == 0 means any team), NULL otherwise + + virtual CBasePlayer *GetClosestPlayerByTravelDistance(int team = 0, float *range = NULL) const = 0; // return actual travel distance to closest player on given team (team == 0 means any team) + virtual CNavArea *GetLastKnownArea() const = 0; + + virtual void OnUpdate(float deltaT) = 0; // a less frequent, full update 'tick' + virtual void OnUpkeep(float deltaT) = 0; // a frequent, lightweight update 'tick' + virtual void OnReset() = 0; // reset improv to initial state + virtual void OnGameEvent(GameEventType event, CBaseEntity *entity, CBaseEntity *other) = 0; // invoked when an event occurs in the game + virtual void OnTouch(CBaseEntity *other) = 0; // "other" has touched us +}; diff --git a/dep/hlsdk/game_shared/bot/nav.h b/dep/hlsdk/game_shared/bot/nav.h new file mode 100644 index 0000000..7f6cf34 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/nav.h @@ -0,0 +1,409 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// STL uses exceptions, but we are not compiling with them - ignore warning +#pragma warning(disable : 4530) + +// to help identify nav files +#define NAV_MAGIC_NUMBER 0xFEEDFACE + +// version +// 1 = hiding spots as plain vector array +// 2 = hiding spots as HidingSpot objects +// 3 = Encounter spots use HidingSpot ID's instead of storing vector again +// 4 = Includes size of source bsp file to verify nav data correlation +// ---- Beta Release at V4 ----- +// 5 = Added Place info +#define NAV_VERSION 5 + +// A place is a named group of navigation areas +typedef unsigned int Place; + +// ie: "no place" +#define UNDEFINED_PLACE 0 +#define ANY_PLACE 0xFFFF + +#define WALK_THRU_DOORS 0x01 +#define WALK_THRU_BREAKABLES 0x02 +#define WALK_THRU_EVERYTHING (WALK_THRU_DOORS | WALK_THRU_BREAKABLES) + +enum NavErrorType +{ + NAV_OK, + NAV_CANT_ACCESS_FILE, + NAV_INVALID_FILE, + NAV_BAD_FILE_VERSION, + NAV_CORRUPT_DATA, +}; + +enum NavAttributeType +{ + NAV_CROUCH = 0x01, // must crouch to use this node/area + NAV_JUMP = 0x02, // must jump to traverse this area + NAV_PRECISE = 0x04, // do not adjust for obstacles, just move along area + NAV_NO_JUMP = 0x08, // inhibit discontinuity jumping +}; + +enum NavDirType +{ + NORTH = 0, + EAST, + SOUTH, + WEST, + + NUM_DIRECTIONS +}; + +// Defines possible ways to move from one area to another +enum NavTraverseType +{ + // NOTE: First 4 directions MUST match NavDirType + GO_NORTH = 0, + GO_EAST, + GO_SOUTH, + GO_WEST, + GO_LADDER_UP, + GO_LADDER_DOWN, + GO_JUMP, + + NUM_TRAVERSE_TYPES +}; + +enum NavCornerType +{ + NORTH_WEST = 0, + NORTH_EAST, + SOUTH_EAST, + SOUTH_WEST, + + NUM_CORNERS +}; + +enum NavRelativeDirType +{ + FORWARD = 0, + RIGHT, + BACKWARD, + LEFT, + UP, + DOWN, + + NUM_RELATIVE_DIRECTIONS +}; + +const float GenerationStepSize = 25.0f; // (30) was 20, but bots can't fit always fit +const float StepHeight = 18.0f; // if delta Z is greater than this, we have to jump to get up +const float JumpHeight = 41.8f; // if delta Z is less than this, we can jump up on it +const float JumpCrouchHeight = 58.0f; // (48) if delta Z is less than or equal to this, we can jumpcrouch up on it + +// Strictly speaking, you CAN get up a slope of 1.643 (about 59 degrees), but you move very, very slowly +// This slope will represent the slope you can navigate without much slowdown +// rise/run - if greater than this, we can't move up it (de_survivor canyon ramps) +const float MaxSlope = 1.4f; + +// instead of MaxSlope, we are using the following max Z component of a unit normal +const float MaxUnitZSlope = 0.7f; + +const float BotRadius = 10.0f; // circular extent that contains bot +const float DeathDrop = 200.0f; // (300) distance at which we will die if we fall - should be about 600, and pay attention to fall damage during pathfind + +const float HalfHumanWidth = 16.0f; +const float HalfHumanHeight = 36.0f; +const float HumanHeight = 72.0f; + +struct Extent +{ + Vector lo; + Vector hi; + + float SizeX() const { return hi.x - lo.x; } + float SizeY() const { return hi.y - lo.y; } + float SizeZ() const { return hi.z - lo.z; } + float Area() const { return SizeX() * SizeY(); } + + // return true if 'pos' is inside of this extent + bool Contains(const Vector *pos) const + { + return (pos->x >= lo.x && pos->x <= hi.x && + pos->y >= lo.y && pos->y <= hi.y && + pos->z >= lo.z && pos->z <= hi.z); + } +}; + +struct Ray +{ + Vector from; + Vector to; +}; + +inline NavDirType OppositeDirection(NavDirType dir) +{ + switch (dir) + { + case NORTH: + return SOUTH; + case EAST: + return WEST; + case SOUTH: + return NORTH; + case WEST: + return EAST; + } + + return NORTH; +} + +inline NavDirType DirectionLeft(NavDirType dir) +{ + switch (dir) + { + case NORTH: + return WEST; + case SOUTH: + return EAST; + case EAST: + return NORTH; + case WEST: + return SOUTH; + } + + return NORTH; +} + +inline NavDirType DirectionRight(NavDirType dir) +{ + switch (dir) + { + case NORTH: + return EAST; + case SOUTH: + return WEST; + case EAST: + return SOUTH; + case WEST: + return NORTH; + } + + return NORTH; +} + +inline void AddDirectionVector(Vector *v, NavDirType dir, float amount) +{ + switch (dir) + { + case NORTH: + v->y -= amount; + return; + case SOUTH: + v->y += amount; + return; + case EAST: + v->x += amount; + return; + case WEST: + v->x -= amount; + return; + } +} + +inline float DirectionToAngle(NavDirType dir) +{ + switch (dir) + { + case NORTH: + return 270.0f; + case EAST: + return 0.0f; + case SOUTH: + return 90.0f; + case WEST: + return 180.0f; + } + + return 0.0f; +} + +inline NavDirType AngleToDirection(float angle) +{ + while (angle < 0.0f) + angle += 360.0f; + + while (angle > 360.0f) + angle -= 360.0f; + + if (angle < 45 || angle > 315) + return EAST; + + if (angle >= 45 && angle < 135) + return SOUTH; + + if (angle >= 135 && angle < 225) + return WEST; + + return NORTH; +} + +inline void DirectionToVector2D(NavDirType dir, Vector2D *v) +{ + switch (dir) + { + case NORTH: + v->x = 0.0f; + v->y = -1.0f; + break; + case SOUTH: + v->x = 0.0f; + v->y = 1.0f; + break; + case EAST: + v->x = 1.0f; + v->y = 0.0f; + break; + case WEST: + v->x = -1.0f; + v->y = 0.0f; + break; + } +} + +inline void SnapToGrid(Vector *pos) +{ + int cx = pos->x / GenerationStepSize; + int cy = pos->y / GenerationStepSize; + pos->x = cx * GenerationStepSize; + pos->y = cy * GenerationStepSize; +} + +inline void SnapToGrid(float *value) +{ + int c = *value / GenerationStepSize; + *value = c * GenerationStepSize; +} + +// custom +inline float SnapToGrid(float value) +{ + int c = value / GenerationStepSize; + return c * GenerationStepSize; +} + +inline float NormalizeAngle(float angle) +{ + while (angle < -180.0f) + angle += 360.0f; + + while (angle > 180.0f) + angle -= 360.0f; + + return angle; +} + +inline float NormalizeAnglePositive(float angle) +{ + while (angle < 0.0f) + angle += 360.0f; + + while (angle >= 360.0f) + angle -= 360.0f; + + return angle; +} + +inline float AngleDifference(float a, float b) +{ + float angleDiff = a - b; + + while (angleDiff > 180.0f) + angleDiff -= 360.0f; + + while (angleDiff < -180.0f) + angleDiff += 360.0f; + + return angleDiff; +} + +inline bool AnglesAreEqual(float a, float b, float tolerance = 5.0f) +{ + if (abs(int64(AngleDifference(a, b))) < tolerance) + return true; + + return false; +} + +inline bool VectorsAreEqual(const Vector *a, const Vector *b, float tolerance = 0.1f) +{ + if (abs(a->x - b->x) < tolerance + && abs(a->y - b->y) < tolerance + && abs(a->z - b->z) < tolerance) + return true; + + return false; +} + +inline bool IsEntityWalkable(entvars_t *entity, unsigned int flags) +{ + // if we hit a door, assume its walkable because it will open when we touch it + if (FClassnameIs(entity, "func_door") || FClassnameIs(entity, "func_door_rotating")) + return (flags & WALK_THRU_DOORS) ? true : false; + + // if we hit a breakable object, assume its walkable because we will shoot it when we touch it + if (FClassnameIs(entity, "func_breakable") && entity->takedamage == DAMAGE_YES) + return (flags & WALK_THRU_BREAKABLES) ? true : false; + + return false; +} + +// Check LOS, ignoring any entities that we can walk through +inline bool IsWalkableTraceLineClear(Vector &from, Vector &to, unsigned int flags = 0) +{ + TraceResult result; + edict_t *ignore = NULL; + Vector useFrom = from; + + while (true) + { + UTIL_TraceLine(useFrom, to, ignore_monsters, ignore, &result); + + if (result.flFraction != 1.0f && IsEntityWalkable(VARS(result.pHit), flags)) + { + ignore = result.pHit; + + Vector dir = to - from; + dir.NormalizeInPlace(); + useFrom = result.vecEndPos + 5.0f * dir; + } + else + break; + } + + if (result.flFraction == 1.0f) + return true; + + return false; +} diff --git a/dep/hlsdk/game_shared/bot/nav_area.h b/dep/hlsdk/game_shared/bot/nav_area.h new file mode 100644 index 0000000..5c40b2a --- /dev/null +++ b/dep/hlsdk/game_shared/bot/nav_area.h @@ -0,0 +1,320 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include + +class CNavArea; +enum NavEditCmdType +{ + EDIT_NONE, + EDIT_DELETE, // delete current area + EDIT_SPLIT, // split current area + EDIT_MERGE, // merge adjacent areas + EDIT_JOIN, // define connection between areas + EDIT_BREAK, // break connection between areas + EDIT_MARK, // mark an area for further operations + EDIT_ATTRIB_CROUCH, // toggle crouch attribute on current area + EDIT_ATTRIB_JUMP, // toggle jump attribute on current area + EDIT_ATTRIB_PRECISE, // toggle precise attribute on current area + EDIT_ATTRIB_NO_JUMP, // toggle inhibiting discontinuity jumping in current area + EDIT_BEGIN_AREA, // begin creating a new nav area + EDIT_END_AREA, // end creation of the new nav area + EDIT_CONNECT, // connect marked area to selected area + EDIT_DISCONNECT, // disconnect marked area from selected area + EDIT_SPLICE, // create new area in between marked and selected areas + EDIT_TOGGLE_PLACE_MODE, // switch between normal and place editing + EDIT_TOGGLE_PLACE_PAINTING, // switch between "painting" places onto areas + EDIT_PLACE_FLOODFILL, // floodfill areas out from current area + EDIT_PLACE_PICK, // "pick up" the place at the current area + EDIT_MARK_UNNAMED, // mark an unnamed area for further operations + EDIT_WARP_TO_MARK, // warp a spectating local player to the selected mark + EDIT_SELECT_CORNER, // select a corner on the current area + EDIT_RAISE_CORNER, // raise a corner on the current area + EDIT_LOWER_CORNER, // lower a corner on the current area +}; + +enum RouteType +{ + FASTEST_ROUTE, + SAFEST_ROUTE, +}; + +union NavConnect +{ + unsigned int id; + CNavArea *area; + + bool operator==(const NavConnect &other) const { return (area == other.area) ? true : false; } +}; + +typedef std::list NavConnectList; + +enum LadderDirectionType +{ + LADDER_UP = 0, + LADDER_DOWN, + NUM_LADDER_DIRECTIONS +}; + +class CNavLadder { +public: + Vector m_top; + Vector m_bottom; + float m_length; + NavDirType m_dir; + Vector2D m_dirVector; + CBaseEntity *m_entity; + + CNavArea *m_topForwardArea; + CNavArea *m_topLeftArea; + CNavArea *m_topRightArea; + CNavArea *m_topBehindArea; + CNavArea *m_bottomArea; + + bool m_isDangling; + + void OnDestroyNotify(CNavArea *dead) + { + if (dead == m_topForwardArea) + m_topForwardArea = NULL; + + if (dead == m_topLeftArea) + m_topLeftArea = NULL; + + if (dead == m_topRightArea) + m_topRightArea = NULL; + + if (dead == m_topBehindArea) + m_topBehindArea = NULL; + + if (dead == m_bottomArea) + m_bottomArea = NULL; + } +}; + +typedef std::list NavLadderList; + +class HidingSpot { +public: + enum + { + IN_COVER = 0x01, + GOOD_SNIPER_SPOT = 0x02, + IDEAL_SNIPER_SPOT = 0x04 + }; + + bool HasGoodCover() const { return (m_flags & IN_COVER) ? true : false; } + bool IsGoodSniperSpot() const { return (m_flags & GOOD_SNIPER_SPOT) ? true : false; } + bool IsIdealSniperSpot() const { return (m_flags & IDEAL_SNIPER_SPOT) ? true : false; } + + void SetFlags(unsigned char flags) { m_flags |= flags; } + unsigned char GetFlags() const { return m_flags; } + + const Vector *GetPosition() const { return &m_pos; } + unsigned int GetID() const { return m_id; } + +private: + Vector m_pos; + unsigned int m_id; + unsigned int m_marker; + unsigned char m_flags; +}; + +typedef std::list HidingSpotList; + +struct SpotOrder +{ + float t; + union + { + HidingSpot *spot; + unsigned int id; + }; +}; + +typedef std::list SpotOrderList; + +struct SpotEncounter +{ + NavConnect from; + NavDirType fromDir; + NavConnect to; + NavDirType toDir; + Ray path; // the path segment + SpotOrderList spotList; // list of spots to look at, in order of occurrence +}; + +typedef std::list SpotEncounterList; +typedef std::list NavAreaList; + +// A CNavArea is a rectangular region defining a walkable area in the map +class CNavArea { +public: + unsigned int GetID() const { return m_id; } + void SetAttributes(unsigned char bits) { m_attributeFlags = bits; } + unsigned char GetAttributes() const { return m_attributeFlags; } + void SetPlace(Place place) { m_place = place; } // set place descriptor + Place GetPlace() const { return m_place; } // get place descriptor + + int GetAdjacentCount(NavDirType dir) const { return m_connect[dir].size(); } // return number of connected areas in given direction + const NavConnectList *GetAdjacentList(NavDirType dir) const { return &m_connect[dir]; } + + const NavLadderList *GetLadderList(LadderDirectionType dir) const { return &m_ladder[dir]; } + + // for hunting algorithm + void SetClearedTimestamp(int teamID) { m_clearedTimestamp[teamID] = gpGlobals->time; } // set this area's "clear" timestamp to now + float GetClearedTimestamp(int teamID) { return m_clearedTimestamp[teamID]; } // get time this area was marked "clear" + + // hiding spots + const HidingSpotList *GetHidingSpotList() const { return &m_hidingSpotList; } + + float GetSizeX() const { return m_extent.hi.x - m_extent.lo.x; } + float GetSizeY() const { return m_extent.hi.y - m_extent.lo.y; } + + const Extent *GetExtent() const { return &m_extent; } + const Vector *GetCenter() const { return &m_center; } + + // approach areas + struct ApproachInfo + { + NavConnect here; // the approach area + NavConnect prev; // the area just before the approach area on the path + NavTraverseType prevToHereHow; + NavConnect next; // the area just after the approach area on the path + NavTraverseType hereToNextHow; + }; + + const ApproachInfo *GetApproachInfo(int i) const { return &m_approach[i]; } + int GetApproachInfoCount() const { return m_approachCount; } + + void SetParent(CNavArea *parent, NavTraverseType how = NUM_TRAVERSE_TYPES) { m_parent = parent; m_parentHow = how; } + CNavArea *GetParent() const { return m_parent; } + NavTraverseType GetParentHow() const { return m_parentHow; } + + void SetTotalCost(float value) { m_totalCost = value; } + float GetTotalCost() const { return m_totalCost; } + + void SetCostSoFar(float value) { m_costSoFar = value; } + float GetCostSoFar() const { return m_costSoFar; } + +public: + friend class CNavAreaGrid; + friend class CCSBotManager; + + unsigned int m_id; // unique area ID + Extent m_extent; // extents of area in world coords (NOTE: lo.z is not necessarily the minimum Z, but corresponds to Z at point (lo.x, lo.y), etc + Vector m_center; // centroid of area + unsigned char m_attributeFlags; // set of attribute bit flags (see NavAttributeType) + Place m_place; // place descriptor + + // height of the implicit corners + float m_neZ; + float m_swZ; + + enum { MAX_AREA_TEAMS = 2 }; + + // for hunting + float m_clearedTimestamp[MAX_AREA_TEAMS]; // time this area was last "cleared" of enemies + + // danger + float m_danger[MAX_AREA_TEAMS]; // danger of this area, allowing bots to avoid areas where they died in the past - zero is no danger + float m_dangerTimestamp[MAX_AREA_TEAMS]; // time when danger value was set - used for decaying + + // hiding spots + HidingSpotList m_hidingSpotList; + + // encounter spots + SpotEncounterList m_spotEncounterList; // list of possible ways to move thru this area, and the spots to look at as we do + + // approach areas + enum { MAX_APPROACH_AREAS = 16 }; + ApproachInfo m_approach[MAX_APPROACH_AREAS]; + unsigned char m_approachCount; + + // A* pathfinding algorithm + unsigned int m_marker; // used to flag the area as visited + CNavArea *m_parent; // the area just prior to this on in the search path + NavTraverseType m_parentHow; // how we get from parent to us + float m_totalCost; // the distance so far plus an estimate of the distance left + float m_costSoFar; // distance travelled so far + + CNavArea *m_nextOpen, *m_prevOpen; // only valid if m_openMarker == m_masterMarker + unsigned int m_openMarker; // if this equals the current marker value, we are on the open list + + // connections to adjacent areas + NavConnectList m_connect[ NUM_DIRECTIONS ]; // a list of adjacent areas for each direction + NavLadderList m_ladder[ NUM_LADDER_DIRECTIONS ]; // list of ladders leading up and down from this area + + CNavNode *m_node[ NUM_CORNERS ]; // nav nodes at each corner of the area + NavAreaList m_overlapList; // list of areas that overlap this area + + CNavArea *m_prevHash, *m_nextHash; // for hash table in CNavAreaGrid +}; + +// The CNavAreaGrid is used to efficiently access navigation areas by world position +// Each cell of the grid contains a list of areas that overlap it +// Given a world position, the corresponding grid cell is ( x/cellsize, y/cellsize ) +class CNavAreaGrid { +public: + const float m_cellSize; + NavAreaList *m_grid; + int m_gridSizeX; + int m_gridSizeY; + float m_minX; + float m_minY; + unsigned int m_areaCount; // total number of nav areas + + enum { HASH_TABLE_SIZE = 256 }; + CNavArea *m_hashTable[HASH_TABLE_SIZE]; // hash table to optimize lookup by ID + inline int ComputeHashKey(unsigned int id) const // returns a hash key for the given nav area ID + { + return id & 0xFF; + } + inline int WorldToGridX(float wx) const + { + int x = (wx - m_minX) / m_cellSize; + if (x < 0) + x = 0; + + else if (x >= m_gridSizeX) + x = m_gridSizeX - 1; + + return x; + } + inline int WorldToGridY(float wy) const + { + int y = (wy - m_minY) / m_cellSize; + if (y < 0) + y = 0; + else if (y >= m_gridSizeY) + y = m_gridSizeY - 1; + + return y; + } +}; diff --git a/dep/hlsdk/game_shared/bot/nav_node.h b/dep/hlsdk/game_shared/bot/nav_node.h new file mode 100644 index 0000000..4c434a1 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/nav_node.h @@ -0,0 +1,110 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class CNavNode { +public: + // get navigation node connected in given direction, or NULL if cant go that way + CNavNode *GetConnectedNode(NavDirType dir) const; + const Vector *GetPosition() const; + const Vector *GetNormal() const { return &m_normal; } + unsigned int GetID() const { return m_id; } + + CNavNode *GetNext() { return m_next; } + + // create a connection FROM this node TO the given node, in the given direction + CNavNode *GetParent() const; + + void MarkAsVisited(NavDirType dir); // mark the given direction as having been visited + BOOL HasVisited(NavDirType dir); // return TRUE if the given direction has already been searched + + void Cover() { m_isCovered = true; } // TODO: Should pass in area that is covering + BOOL IsCovered() const { return m_isCovered; } // return true if this node has been covered by an area + + void AssignArea(CNavArea *area); // assign the given area to this node + CNavArea *GetArea() const; // return associated area + + void SetAttributes(unsigned char bits) { m_attributeFlags = bits; } + unsigned char GetAttributes() const { return m_attributeFlags; } + +public: + friend void DestroyNavigationMap(); + + Vector m_pos; // position of this node in the world + Vector m_normal; // surface normal at this location + CNavNode *m_to[ NUM_DIRECTIONS ]; // links to north, south, east, and west. NULL if no link + unsigned int m_id; // unique ID of this node + unsigned char m_attributeFlags; // set of attribute bit flags (see NavAttributeType) + + CNavNode *m_next; // next link in master list + + // below are only needed when generating + // flags for automatic node generation. If direction bit is clear, that direction hasn't been explored yet. + unsigned char m_visited; + CNavNode *m_parent; // the node prior to this in the search, which we pop back to when this node's search is done (a stack) + BOOL m_isCovered; // true when this node is "covered" by a CNavArea + CNavArea *m_area; // the area this node is contained within +}; + +inline CNavNode *CNavNode::GetConnectedNode(NavDirType dir) const +{ + return m_to[ dir ]; +} + +inline const Vector *CNavNode::GetPosition() const +{ + return &m_pos; +} + +inline CNavNode *CNavNode::GetParent() const +{ + return m_parent; +} + +inline void CNavNode::MarkAsVisited(NavDirType dir) +{ + m_visited |= (1 << dir); +} + +inline BOOL CNavNode::HasVisited(NavDirType dir) +{ + if (m_visited & (1 << dir)) + return true; + + return false; +} + +inline void CNavNode::AssignArea(CNavArea *area) +{ + m_area = area; +} + +inline CNavArea *CNavNode::GetArea() const +{ + return m_area; +} diff --git a/dep/hlsdk/game_shared/bot/nav_path.h b/dep/hlsdk/game_shared/bot/nav_path.h new file mode 100644 index 0000000..614aa06 --- /dev/null +++ b/dep/hlsdk/game_shared/bot/nav_path.h @@ -0,0 +1,99 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// STL uses exceptions, but we are not compiling with them - ignore warning +#pragma warning(disable : 4530) + +class CNavPath { +public: + CNavPath() { m_segmentCount = 0; } + + struct PathSegment + { + CNavArea *area; // the area along the path + NavTraverseType how; // how to enter this area from the previous one + Vector pos; // our movement goal position at this point in the path + const CNavLadder *ladder; // if "how" refers to a ladder, this is it + }; + + const PathSegment *operator[](int i) { return (i >= 0 && i < m_segmentCount) ? &m_path[i] : NULL; } + int GetSegmentCount() const { return m_segmentCount; } + const Vector &GetEndpoint() const { return m_path[ m_segmentCount - 1 ].pos; } + + bool IsValid() const { return (m_segmentCount > 0); } + void Invalidate() { m_segmentCount = 0; } +public: + enum { MAX_PATH_SEGMENTS = 256 }; + PathSegment m_path[ MAX_PATH_SEGMENTS ]; + int m_segmentCount; + + bool ComputePathPositions(); // determine actual path positions + bool BuildTrivialPath(const Vector *start, const Vector *goal); // utility function for when start and goal are in the same area + int FindNextOccludedNode(int anchor_); // used by Optimize() +}; + +// Monitor improv movement and determine if it becomes stuck +class CStuckMonitor { +public: + bool IsStuck() const { return m_isStuck; } + float GetDuration() const { return m_isStuck ? m_stuckTimer.GetElapsedTime() : 0.0f; } +public: + bool m_isStuck; // if true, we are stuck + Vector m_stuckSpot; // the location where we became stuck + IntervalTimer m_stuckTimer; // how long we have been stuck + + enum { MAX_VEL_SAMPLES = 5 }; + + float m_avgVel[ MAX_VEL_SAMPLES ]; + int m_avgVelIndex; + int m_avgVelCount; + Vector m_lastCentroid; + float m_lastTime; +}; + +// The CNavPathFollower class implements path following behavior +class CNavPathFollower { +public: + void SetImprov(CImprov *improv) { m_improv = improv; } + void SetPath(CNavPath *path) { m_path = path; } + + void Debug(bool status) { m_isDebug = status; } // turn debugging on/off +public: + int FindOurPositionOnPath(Vector *close, bool local) const; // return the closest point to our current position on current path + int FindPathPoint(float aheadRange, Vector *point, int *prevIndex); // compute a point a fixed distance ahead along our path. + + CImprov *m_improv; // who is doing the path following + CNavPath *m_path; // the path being followed + int m_segmentIndex; // the point on the path the improv is moving towards + int m_behindIndex; // index of the node on the path just behind us + Vector m_goal; // last computed follow goal + bool m_isLadderStarted; + bool m_isDebug; + CStuckMonitor m_stuckMonitor; +}; diff --git a/dep/hlsdk/game_shared/bot/simple_state_machine.h b/dep/hlsdk/game_shared/bot/simple_state_machine.h new file mode 100644 index 0000000..baa931e --- /dev/null +++ b/dep/hlsdk/game_shared/bot/simple_state_machine.h @@ -0,0 +1,101 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// Encapsulation of a finite-state-machine state +template +class SimpleState { +public: + SimpleState() { m_parent = NULL; } + + virtual ~SimpleState() {}; + virtual void OnEnter(T userData) {}; // when state is entered + virtual void OnUpdate(T userData) {}; // state behavior + virtual void OnExit(T userData) {}; // when state exited + virtual const char *GetName() const = 0; // return state name + + void SetParent(SimpleState *parent) + { + m_parent = parent; + } + SimpleState *GetParent() const + { + return m_parent; + } + +private: + // the parent state that contains this state + SimpleState *m_parent; +}; + +// Encapsulation of a finite state machine +template +class SimpleStateMachine { +public: + SimpleStateMachine() + { + m_state = NULL; + } + void Reset(T userData) + { + m_userData = userData; + m_state = NULL; + } + // change behavior state - WARNING: not re-entrant. Do not SetState() from within OnEnter() or OnExit() + void SetState(S *newState) + { + if (m_state) + m_state->OnExit(m_userData); + + newState->OnEnter(m_userData); + + m_state = newState; + m_stateTimer.Start(); + } + // how long have we been in the current state + float GetStateDuration() const + { + return m_stateTimer.GetElapsedTime(); + } + // return true if given state is current state of machine + bool IsState(const S *state) const + { + return (state == m_state); + } + // execute current state of machine + void Update() + { + if (m_state) + m_state->OnUpdate(m_userData); + } + +protected: + S *m_state; // current behavior state + IntervalTimer m_stateTimer; // how long have we been in the current state + T m_userData; +}; diff --git a/dep/hlsdk/game_shared/counter.h b/dep/hlsdk/game_shared/counter.h new file mode 100644 index 0000000..0b55e02 --- /dev/null +++ b/dep/hlsdk/game_shared/counter.h @@ -0,0 +1,188 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + #include + #include + #include +#else + #include + #include + #include + #include + #ifdef OSX + #include + #else + #include + #endif + #include +#endif + +#include +#include +#include +#include +#include + +class CCounter +{ +public: + CCounter(); + + bool Init(); + double GetCurTime(); + +private: + int m_iLowShift; + double m_flPerfCounterFreq; + double m_flCurrentTime; + double m_flLastCurrentTime; +}; + +inline CCounter::CCounter() : + m_iLowShift(0), + m_flPerfCounterFreq(0), + m_flCurrentTime(0), + m_flLastCurrentTime(0) +{ + Init(); +} + +inline bool CCounter::Init() +{ +#ifdef _WIN32 + + LARGE_INTEGER performanceFreq; + if (!QueryPerformanceFrequency(&performanceFreq)) + return false; + + // get 32 out of the 64 time bits such that we have around + // 1 microsecond resolution + unsigned int lowpart, highpart; + lowpart = (unsigned int)performanceFreq.LowPart; + highpart = (unsigned int)performanceFreq.HighPart; + m_iLowShift = 0; + + while (highpart || (lowpart > 2000000.0)) + { + m_iLowShift++; + lowpart >>= 1; + lowpart |= (highpart & 1) << 31; + highpart >>= 1; + } + + m_flPerfCounterFreq = 1.0 / (double)lowpart; + +#endif // _WIN32 + + return true; +} + +inline double CCounter::GetCurTime() +{ +#ifdef _WIN32 + + static int sametimecount; + static unsigned int oldtime; + static int first = 1; + LARGE_INTEGER PerformanceCount; + unsigned int temp, t2; + double time; + + QueryPerformanceCounter(&PerformanceCount); + if (m_iLowShift == 0) + { + temp = (unsigned int)PerformanceCount.LowPart; + } + else + { + temp = ((unsigned int)PerformanceCount.LowPart >> m_iLowShift) | + ((unsigned int)PerformanceCount.HighPart << (32 - m_iLowShift)); + } + + if (first) + { + oldtime = temp; + first = 0; + } + else + { + // check for turnover or backward time + if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000)) + { + // so we can't get stuck + oldtime = temp; + } + else + { + t2 = temp - oldtime; + + time = (double)t2 * m_flPerfCounterFreq; + oldtime = temp; + + m_flCurrentTime += time; + + if (m_flCurrentTime == m_flLastCurrentTime) + { + if (++sametimecount > 100000) + { + m_flCurrentTime += 1.0; + sametimecount = 0; + } + } + else + { + sametimecount = 0; + } + + m_flLastCurrentTime = m_flCurrentTime; + } + } + + return m_flCurrentTime; + +#else // _WIN32 + + struct timeval tp; + static int secbase = 0; + + gettimeofday(&tp, NULL); + + if (!secbase) + { + secbase = tp.tv_sec; + return (tp.tv_usec / 1000000.0); + } + + return ((tp.tv_sec - secbase) + tp.tv_usec / 1000000.0); + +#endif // _WIN32 +} diff --git a/dep/hlsdk/game_shared/shared_util.h b/dep/hlsdk/game_shared/shared_util.h new file mode 100644 index 0000000..c12156f --- /dev/null +++ b/dep/hlsdk/game_shared/shared_util.h @@ -0,0 +1,63 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#ifndef _WIN32 +#include +#include +#endif + +// Simple utility function to allocate memory and duplicate a string +inline char *CloneString(const char *str) +{ + if (!str) + { + char *cloneStr = new char[1]; + cloneStr[0] = '\0'; + return cloneStr; + } + + char *cloneStr = new char [strlen(str) + 1]; + strcpy(cloneStr, str); + return cloneStr; +} + +// Simple utility function to allocate memory and duplicate a wide string +inline wchar_t *CloneWString(const wchar_t *str) +{ + if (!str) + { + wchar_t *cloneStr = new wchar_t[1]; + cloneStr[0] = L'\0'; + return cloneStr; + } + + wchar_t *cloneStr = new wchar_t [wcslen(str) + 1]; + wcscpy(cloneStr, str); + return cloneStr; +} diff --git a/dep/hlsdk/game_shared/simple_checksum.h b/dep/hlsdk/game_shared/simple_checksum.h new file mode 100644 index 0000000..236e765 --- /dev/null +++ b/dep/hlsdk/game_shared/simple_checksum.h @@ -0,0 +1,49 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef SIMPLE_CHECKSUM_H +#define SIMPLE_CHECKSUM_H +#ifdef _WIN32 +#pragma once +#endif + +// Compute a simple checksum for the given data. +// Each byte in the data is multiplied by its position to track re-ordering changes +inline unsigned int ComputeSimpleChecksum(const unsigned char *dataPointer, int dataLength) +{ + unsigned int checksum = 0; + for (int i = 1; i <= dataLength; i++) + { + checksum += (*dataPointer) * i; + ++dataPointer; + } + + return checksum; +} + +#endif // SIMPLE_CHECKSUM_H diff --git a/dep/hlsdk/game_shared/steam_util.h b/dep/hlsdk/game_shared/steam_util.h new file mode 100644 index 0000000..5431679 --- /dev/null +++ b/dep/hlsdk/game_shared/steam_util.h @@ -0,0 +1,76 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class SteamFile +{ +public: + SteamFile(const char *filename); + ~SteamFile(); + + bool IsValid() const { return (m_fileData) ? true : false; } + bool Read(void *data, int length); + +private: + byte *m_fileData; + int m_fileDataLength; + + byte *m_cursor; + int m_bytesLeft; +}; + +inline SteamFile::SteamFile(const char *filename) +{ + m_fileData = (byte *)LOAD_FILE_FOR_ME(const_cast(filename), &m_fileDataLength); + m_cursor = m_fileData; + m_bytesLeft = m_fileDataLength; +} + +inline SteamFile::~SteamFile() +{ + if (m_fileData) + { + FREE_FILE(m_fileData); + m_fileData = NULL; + } +} + +inline bool SteamFile::Read(void *data, int length) +{ + if (length > m_bytesLeft || m_cursor == NULL || m_bytesLeft <= 0) + return false; + + byte *readCursor = static_cast(data); + for (int i = 0; i < length; ++i) + { + *readCursor++ = *m_cursor++; + --m_bytesLeft; + } + + return true; +} diff --git a/dep/hlsdk/game_shared/voice_common.h b/dep/hlsdk/game_shared/voice_common.h new file mode 100644 index 0000000..82dfb39 --- /dev/null +++ b/dep/hlsdk/game_shared/voice_common.h @@ -0,0 +1,36 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "bitvec.h" + +// TODO: this should just be set to MAX_CLIENTS +#define VOICE_MAX_PLAYERS 32 +#define VOICE_MAX_PLAYERS_DW ((VOICE_MAX_PLAYERS / 32) + !!(VOICE_MAX_PLAYERS & 31)) + +typedef CBitVec< VOICE_MAX_PLAYERS > CPlayerBitVec; diff --git a/dep/hlsdk/game_shared/voice_gamemgr.h b/dep/hlsdk/game_shared/voice_gamemgr.h new file mode 100644 index 0000000..851c93a --- /dev/null +++ b/dep/hlsdk/game_shared/voice_gamemgr.h @@ -0,0 +1,56 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define UPDATE_INTERVAL 0.3 + +#include "voice_common.h" + +class CGameRules; +class CBasePlayer; + +class IVoiceGameMgrHelper { +public: + virtual ~IVoiceGameMgrHelper() = 0; + + // Called each frame to determine which players are allowed to hear each other. This overrides + // whatever squelch settings players have. + virtual bool CanPlayerHearPlayer(CBasePlayer *pListener, CBasePlayer *pTalker) = 0; +}; + +// CVoiceGameMgr manages which clients can hear which other clients. +class CVoiceGameMgr { +public: + virtual ~CVoiceGameMgr() {}; +public: + int m_msgPlayerVoiceMask; + int m_msgRequestState; + IVoiceGameMgrHelper *m_pHelper; + int m_nMaxPlayers; + double m_UpdateInterval; // How long since the last update. +}; diff --git a/dep/hlsdk/pm_shared/pm_debug.h b/dep/hlsdk/pm_shared/pm_debug.h new file mode 100644 index 0000000..6eca1f0 --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_debug.h @@ -0,0 +1,26 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PM_DEBUG_H +#define PM_DEBUG_H +#ifdef _WIN32 +#pragma once +#endif + +void PM_ViewEntity( void ); +void PM_DrawBBox(vec3_t mins, vec3_t maxs, vec3_t origin, int pcolor, float life); +void PM_ParticleLine(vec3_t start, vec3_t end, int pcolor, float life, float vert); +void PM_ShowClipBox( void ); + +#endif // PMOVEDBG_H diff --git a/dep/hlsdk/pm_shared/pm_defs.h b/dep/hlsdk/pm_shared/pm_defs.h new file mode 100644 index 0000000..04bea26 --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_defs.h @@ -0,0 +1,192 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "pm_info.h" +#include "pmtrace.h" + +#ifndef USERCMD_H +#include "usercmd.h" +#endif + +#include "const.h" + +#define MAX_PHYSENTS 600 // Must have room for all entities in the world. +#define MAX_MOVEENTS 64 +#define MAX_CLIP_PLANES 5 + +#define PM_NORMAL 0x00000000 +#define PM_STUDIO_IGNORE 0x00000001 // Skip studio models +#define PM_STUDIO_BOX 0x00000002 // Use boxes for non-complex studio models (even in traceline) +#define PM_GLASS_IGNORE 0x00000004 // Ignore entities with non-normal rendermode +#define PM_WORLD_ONLY 0x00000008 // Only trace against the world + +#define PM_TRACELINE_PHYSENTSONLY 0 +#define PM_TRACELINE_ANYVISIBLE 1 + +typedef struct physent_s +{ + char name[32]; // Name of model, or "player" or "world". + int player; + vec3_t origin; // Model's origin in world coordinates. + struct model_s *model; // only for bsp models + struct model_s *studiomodel; // SOLID_BBOX, but studio clip intersections. + vec3_t mins, maxs; // only for non-bsp models + int info; // For client or server to use to identify (index into edicts or cl_entities) + vec3_t angles; // rotated entities need this info for hull testing to work. + + int solid; // Triggers and func_door type WATER brushes are SOLID_NOT + int skin; // BSP Contents for such things like fun_door water brushes. + int rendermode; // So we can ignore glass + + float frame; + int sequence; + byte controller[4]; + byte blending[2]; + + int movetype; + int takedamage; + int blooddecal; + int team; + int classnumber; + + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; + +} physent_t; + +typedef struct playermove_s +{ + int player_index; // So we don't try to run the PM_CheckStuck nudging too quickly. + qboolean server; // For debugging, are we running physics code on server side? + qboolean multiplayer; // 1 == multiplayer server + float time; // realtime on host, for reckoning duck timing + float frametime; // Duration of this frame + vec3_t forward, right, up; // Vectors for angles + vec3_t origin; // Movement origin. + vec3_t angles; // Movement view angles. + vec3_t oldangles; // Angles before movement view angles were looked at. + vec3_t velocity; // Current movement direction. + vec3_t movedir; // For waterjumping, a forced forward velocity so we can fly over lip of ledge. + vec3_t basevelocity; // Velocity of the conveyor we are standing, e.g. + vec3_t view_ofs; // For ducking/dead + // Our eye position. + float flDuckTime; // Time we started duck + qboolean bInDuck; // In process of ducking or ducked already? + int flTimeStepSound; // For walking/falling + // Next time we can play a step sound + int iStepLeft; + float flFallVelocity; + vec3_t punchangle; + float flSwimTime; + float flNextPrimaryAttack; + int effects; // MUZZLE FLASH, e.g. + int flags; // FL_ONGROUND, FL_DUCKING, etc. + int usehull; // 0 = regular player hull, 1 = ducked player hull, 2 = point hull + float gravity; // Our current gravity and friction. + float friction; + int oldbuttons; // Buttons last usercmd + float waterjumptime; // Amount of time left in jumping out of water cycle. + qboolean dead; // Are we a dead player? + int deadflag; + int spectator; // Should we use spectator physics model? + int movetype; // Our movement type, NOCLIP, WALK, FLY + int onground; // -1 = in air, else pmove entity number + int waterlevel; + int watertype; + int oldwaterlevel; + char sztexturename[256]; + char chtexturetype; + float maxspeed; + float clientmaxspeed; + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; + int numphysent; // world state + // Number of entities to clip against. + physent_t physents[MAX_PHYSENTS]; + int nummoveent; // Number of momvement entities (ladders) + physent_t moveents[MAX_MOVEENTS]; // just a list of ladders + int numvisent; // All things being rendered, for tracing against things you don't actually collide with + physent_t visents[MAX_PHYSENTS]; + usercmd_t cmd; // input to run through physics. + int numtouch; // Trace results for objects we collided with. + pmtrace_t touchindex[MAX_PHYSENTS]; + char physinfo[MAX_PHYSINFO_STRING]; // Physics info string + struct movevars_s *movevars; + vec_t _player_mins[4][3]; + vec_t _player_maxs[4][3]; + + const char *(*PM_Info_ValueForKey)(const char *s, const char *key); + void (*PM_Particle)(float *origin, int color, float life, int zpos, int zvel); + int (*PM_TestPlayerPosition)(float *pos, pmtrace_t *ptrace); + void (*Con_NPrintf)(int idx, char *fmt, ...); + void (*Con_DPrintf)(char *fmt, ...); + void (*Con_Printf)(char *fmt, ...); + double (*Sys_FloatTime)(); + void (*PM_StuckTouch)(int hitent, pmtrace_t *ptraceresult); + int (*PM_PointContents)(float *p, int *truecontents); + int (*PM_TruePointContents)(float *p); + int (*PM_HullPointContents)(struct hull_s *hull, int num, float *p); + pmtrace_t (*PM_PlayerTrace)(float *start, float *end, int traceFlags, int ignore_pe); + struct pmtrace_s *(*PM_TraceLine)(float *start, float *end, int flags, int usehulll, int ignore_pe); + int32 (*RandomLong)(int32 lLow, int32 lHigh); + float (*RandomFloat)(float flLow, float flHigh); + int (*PM_GetModelType)(struct model_s *mod); + void (*PM_GetModelBounds)(struct model_s *mod, float *mins, float *maxs); + void *(*PM_HullForBsp)(physent_t *pe, float *offset); + float (*PM_TraceModel)(physent_t *pEnt, float *start, float *end, trace_t *trace); + int (*COM_FileSize)(char *filename); + byte *(*COM_LoadFile)(char *path, int usehunk, int *pLength); + void (*COM_FreeFile)(void *buffer); + char *(*memfgets)(byte *pMemFile, int fileSize, int *pFilePos, char *pBuffer, int bufferSize); + qboolean runfuncs; + void (*PM_PlaySound)(int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch); + const char *(*PM_TraceTexture)(int ground, float *vstart, float *vend); + void (*PM_PlaybackEventFull)(int flags, int clientindex, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2); + +} playermove_t; diff --git a/dep/hlsdk/pm_shared/pm_info.h b/dep/hlsdk/pm_shared/pm_info.h new file mode 100644 index 0000000..68375db --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_info.h @@ -0,0 +1,30 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define MAX_PHYSINFO_STRING 256 diff --git a/dep/hlsdk/pm_shared/pm_materials.h b/dep/hlsdk/pm_shared/pm_materials.h new file mode 100644 index 0000000..6468273 --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_materials.h @@ -0,0 +1,45 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define CTEXTURESMAX 1024 // max number of textures loaded +#define CBTEXTURENAMEMAX 17 // only load first n chars of name + +#define CHAR_TEX_CONCRETE 'C' // texture types +#define CHAR_TEX_METAL 'M' +#define CHAR_TEX_DIRT 'D' +#define CHAR_TEX_VENT 'V' +#define CHAR_TEX_GRATE 'G' +#define CHAR_TEX_TILE 'T' +#define CHAR_TEX_SLOSH 'S' +#define CHAR_TEX_WOOD 'W' +#define CHAR_TEX_COMPUTER 'P' +#define CHAR_TEX_GRASS 'X' +#define CHAR_TEX_GLASS 'Y' +#define CHAR_TEX_FLESH 'F' +#define CHAR_TEX_SNOW 'N' diff --git a/dep/hlsdk/pm_shared/pm_movevars.h b/dep/hlsdk/pm_shared/pm_movevars.h new file mode 100644 index 0000000..9d22d02 --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_movevars.h @@ -0,0 +1,59 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +typedef struct movevars_s +{ + float gravity; // Gravity for map + float stopspeed; // Deceleration when not moving + float maxspeed; // Max allowed speed + float spectatormaxspeed; + float accelerate; // Acceleration factor + float airaccelerate; // Same for when in open air + float wateraccelerate; // Same for when in water + float friction; + float edgefriction; // Extra friction near dropofs + float waterfriction; // Less in water + float entgravity; // 1.0 + float bounce; // Wall bounce value. 1.0 + float stepsize; // sv_stepsize; + float maxvelocity; // maximum server velocity. + float zmax; // Max z-buffer range (for GL) + float waveHeight; // Water wave height (for GL) + qboolean footsteps; // Play footstep sounds + char skyName[32]; // Name of the sky map + float rollangle; + float rollspeed; + float skycolor_r; // Sky color + float skycolor_g; + float skycolor_b; + float skyvec_x; // Sky vector + float skyvec_y; + float skyvec_z; + +} movevars_t; diff --git a/dep/hlsdk/pm_shared/pm_shared.h b/dep/hlsdk/pm_shared/pm_shared.h new file mode 100644 index 0000000..73a5371 --- /dev/null +++ b/dep/hlsdk/pm_shared/pm_shared.h @@ -0,0 +1,75 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#define PM_DEAD_VIEWHEIGHT -8 + +#define OBS_NONE 0 +#define OBS_CHASE_LOCKED 1 +#define OBS_CHASE_FREE 2 +#define OBS_ROAMING 3 +#define OBS_IN_EYE 4 +#define OBS_MAP_FREE 5 +#define OBS_MAP_CHASE 6 + +#define STEP_CONCRETE 0 +#define STEP_METAL 1 +#define STEP_DIRT 2 +#define STEP_VENT 3 +#define STEP_GRATE 4 +#define STEP_TILE 5 +#define STEP_SLOSH 6 +#define STEP_WADE 7 +#define STEP_LADDER 8 +#define STEP_SNOW 9 + +#define WJ_HEIGHT 8 +#define STOP_EPSILON 0.1 +#define MAX_CLIMB_SPEED 200 +#define PLAYER_DUCKING_MULTIPLIER 0.333 +#define PM_CHECKSTUCK_MINTIME 0.05 // Don't check again too quickly. + +#define PLAYER_LONGJUMP_SPEED 350.0f // how fast we longjump + +// Ducking time +#define TIME_TO_DUCK 0.4 +#define STUCK_MOVEUP 1 + +#define PM_VEC_DUCK_HULL_MIN -18 +#define PM_VEC_HULL_MIN -36 +#define PM_VEC_DUCK_VIEW 12 +#define PM_VEC_VIEW 17 + +#define PM_PLAYER_MAX_SAFE_FALL_SPEED 580 // approx 20 feet +#define PM_PLAYER_MIN_BOUNCE_SPEED 350 +#define PM_PLAYER_FALL_PUNCH_THRESHHOLD 250 // won't punch player's screen/make scrape noise unless player falling at least this fast. + +// Only allow bunny jumping up to 1.2x server / player maxspeed setting +#define BUNNYJUMP_MAX_SPEED_FACTOR 1.2f + +extern struct playermove_s *pmove; diff --git a/dep/hlsdk/public/FileSystem.h b/dep/hlsdk/public/FileSystem.h new file mode 100644 index 0000000..4a0f045 --- /dev/null +++ b/dep/hlsdk/public/FileSystem.h @@ -0,0 +1,196 @@ +//========= Copyright � 1996-2001, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef FILESYSTEM_H +#define FILESYSTEM_H +#ifdef _WIN32 +#pragma once +#endif + +#include "interface.h" +#include +#include + +#ifdef _WIN32 + #define STDIO_FILESYSTEM_LIB "filesystem_stdio.dll" + #define STEAM_FILESYSTEM_LIB "filesystem_steam.dll" +#else + #define STDIO_FILESYSTEM_LIB "filesystem_stdio.so" + #define STEAM_FILESYSTEM_LIB "filesystem_steam.so" +#endif // _WIN32 + +//----------------------------------------------------------------------------- +// Forward declarations +//----------------------------------------------------------------------------- +typedef FILE * FileHandle_t; +typedef int FileFindHandle_t; +typedef int WaitForResourcesHandle_t; + + +//----------------------------------------------------------------------------- +// Enums used by the interface +//----------------------------------------------------------------------------- +#ifndef FILESYSTEM_INTERNAL_H +typedef enum +{ + FILESYSTEM_SEEK_HEAD = 0, + FILESYSTEM_SEEK_CURRENT, + FILESYSTEM_SEEK_TAIL, +} FileSystemSeek_t; + +enum +{ + FILESYSTEM_INVALID_FIND_HANDLE = -1 +}; + +typedef enum +{ + // Don't print anything + FILESYSTEM_WARNING_QUIET = 0, + + // On shutdown, report names of files left unclosed + FILESYSTEM_WARNING_REPORTUNCLOSED, + + // Report number of times a file was opened, closed + FILESYSTEM_WARNING_REPORTUSAGE, + + // Report all open/close events to console ( !slow! ) + FILESYSTEM_WARNING_REPORTALLACCESSES +} FileWarningLevel_t; + +#define FILESYSTEM_INVALID_HANDLE ( FileHandle_t )0 +#endif + +// turn off any windows defines +#undef GetCurrentDirectory + +//----------------------------------------------------------------------------- +// Purpose: Main file system interface +//----------------------------------------------------------------------------- +class IFileSystem : public IBaseInterface +{ +public: + // Mount and unmount the filesystem + virtual void Mount( void ) = 0; + virtual void Unmount( void ) = 0; + + // Remove all search paths (including write path?) + virtual void RemoveAllSearchPaths( void ) = 0; + + // Add paths in priority order (mod dir, game dir, ....) + // If one or more .pak files are in the specified directory, then they are + // added after the file system path + // If the path is the relative path to a .bsp file, then any previous .bsp file + // override is cleared and the current .bsp is searched for an embedded PAK file + // and this file becomes the highest priority search path ( i.e., it's looked at first + // even before the mod's file system path ). + virtual void AddSearchPath( const char *pPath, const char *pathID ) = 0; + virtual bool RemoveSearchPath( const char *pPath ) = 0; + + // Deletes a file + virtual void RemoveFile( const char *pRelativePath, const char *pathID ) = 0; + + // this isn't implementable on STEAM as is. + virtual void CreateDirHierarchy( const char *path, const char *pathID ) = 0; + + // File I/O and info + virtual bool FileExists( const char *pFileName ) = 0; + virtual bool IsDirectory( const char *pFileName ) = 0; + + // opens a file + // if pathID is NULL, all paths will be searched for the file + virtual FileHandle_t Open( const char *pFileName, const char *pOptions, const char *pathID = 0L ) = 0; + + virtual void Close( FileHandle_t file ) = 0; + + virtual void Seek( FileHandle_t file, int pos, FileSystemSeek_t seekType ) = 0; + virtual unsigned int Tell( FileHandle_t file ) = 0; + + virtual unsigned int Size( FileHandle_t file ) = 0; + virtual unsigned int Size( const char *pFileName ) = 0; + + virtual long GetFileTime( const char *pFileName ) = 0; + virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, long fileTime ) = 0; + + virtual bool IsOk( FileHandle_t file ) = 0; + + virtual void Flush( FileHandle_t file ) = 0; + virtual bool EndOfFile( FileHandle_t file ) = 0; + + virtual int Read( void* pOutput, int size, FileHandle_t file ) = 0; + virtual int Write( void const* pInput, int size, FileHandle_t file ) = 0; + virtual char *ReadLine( char *pOutput, int maxChars, FileHandle_t file ) = 0; + virtual int FPrintf( FileHandle_t file, char *pFormat, ... ) = 0; + + // direct filesystem buffer access + // returns a handle to a buffer containing the file data + // this is the optimal way to access the complete data for a file, + // since the file preloader has probably already got it in memory + virtual void *GetReadBuffer( FileHandle_t file, int *outBufferSize, bool failIfNotInCache ) = 0; + virtual void ReleaseReadBuffer( FileHandle_t file, void *readBuffer ) = 0; + + // FindFirst/FindNext + virtual const char *FindFirst( const char *pWildCard, FileFindHandle_t *pHandle, const char *pathID = 0L ) = 0; + virtual const char *FindNext( FileFindHandle_t handle ) = 0; + virtual bool FindIsDirectory( FileFindHandle_t handle ) = 0; + virtual void FindClose( FileFindHandle_t handle ) = 0; + + virtual void GetLocalCopy( const char *pFileName ) = 0; + + virtual const char *GetLocalPath( const char *pFileName, char *pLocalPath, int localPathBufferSize ) = 0; + + // Note: This is sort of a secondary feature; but it's really useful to have it here + virtual char *ParseFile( char* pFileBytes, char* pToken, bool* pWasQuoted ) = 0; + + // Returns true on success ( based on current list of search paths, otherwise false if it can't be resolved ) + virtual bool FullPathToRelativePath( const char *pFullpath, char *pRelative ) = 0; + + // Gets the current working directory + virtual bool GetCurrentDirectory( char* pDirectory, int maxlen ) = 0; + + // Dump to printf/OutputDebugString the list of files that have not been closed + virtual void PrintOpenedFiles( void ) = 0; + + virtual void SetWarningFunc( void (*pfnWarning)( const char *fmt, ... ) ) = 0; + virtual void SetWarningLevel( FileWarningLevel_t level ) = 0; + + virtual void LogLevelLoadStarted( const char *name ) = 0; + virtual void LogLevelLoadFinished( const char *name ) = 0; + virtual int HintResourceNeed( const char *hintlist, int forgetEverything ) = 0; + virtual int PauseResourcePreloading( void ) = 0; + virtual int ResumeResourcePreloading( void ) = 0; + virtual int SetVBuf( FileHandle_t stream, char *buffer, int mode, long size ) = 0; + virtual void GetInterfaceVersion( char *p, int maxlen ) = 0; + virtual bool IsFileImmediatelyAvailable(const char *pFileName) = 0; + + // starts waiting for resources to be available + // returns FILESYSTEM_INVALID_HANDLE if there is nothing to wait on + virtual WaitForResourcesHandle_t WaitForResources( const char *resourcelist ) = 0; + // get progress on waiting for resources; progress is a float [0, 1], complete is true on the waiting being done + // returns false if no progress is available + // any calls after complete is true or on an invalid handle will return false, 0.0f, true + virtual bool GetWaitForResourcesProgress( WaitForResourcesHandle_t handle, float *progress /* out */ , bool *complete /* out */ ) = 0; + // cancels a progress call + virtual void CancelWaitForResources( WaitForResourcesHandle_t handle ) = 0; + // returns true if the appID has all its caches fully preloaded + virtual bool IsAppReadyForOfflinePlay( int appID ) = 0; + + // interface for custom pack files > 4Gb + virtual bool AddPackFile( const char *fullpath, const char *pathID ) = 0; + + // open a file but force the data to come from the steam cache, NOT from disk + virtual FileHandle_t OpenFromCacheForRead( const char *pFileName, const char *pOptions, const char *pathID = 0L ) = 0; + + virtual void AddSearchPathNoWrite( const char *pPath, const char *pathID ) = 0; +}; + +// Steam3/Src compat +#define IBaseFileSystem IFileSystem + +#define FILESYSTEM_INTERFACE_VERSION "VFileSystem009" + +#endif // FILESYSTEM_H diff --git a/dep/hlsdk/public/HLTV/IBSPModel.h b/dep/hlsdk/public/HLTV/IBSPModel.h new file mode 100644 index 0000000..22a6438 --- /dev/null +++ b/dep/hlsdk/public/HLTV/IBSPModel.h @@ -0,0 +1,45 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IBaseSystem; +class IBSPModel { +public: + virtual ~IBSPModel() {}; + + virtual void Init(IBaseSystem *system) = 0; + virtual void Clear() = 0; + virtual bool Load(const char *name, bool minimal) = 0; + virtual bool IsValid() = 0; + virtual bool IsMinimal() = 0; + virtual void SetPVS(float *point) = 0; + virtual bool InPVS(float *point) = 0; + virtual bool TraceLine(float *start, float *end, float *impact) = 0; + virtual int TruePointContents(float *point) = 0; +}; diff --git a/dep/hlsdk/public/HLTV/IClient.h b/dep/hlsdk/public/HLTV/IClient.h new file mode 100644 index 0000000..fe51503 --- /dev/null +++ b/dep/hlsdk/public/HLTV/IClient.h @@ -0,0 +1,51 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IWorld; +class InfoString; +class IClient: virtual public ISystemModule { +public: + virtual ~IClient() {} + + virtual bool Connect(INetSocket *socket, NetAddress *adr, char *userinfo) = 0; + virtual void Send(unsigned char *data, int length, bool isReliable) = 0; + virtual void Disconnect(const char *reason = nullptr) = 0; + virtual void Reconnect() = 0; + virtual void SetWorld(IWorld *world) = 0; + virtual int GetClientType() = 0; + virtual char *GetClientName() = 0; + virtual InfoString *GetUserInfo() = 0; + virtual NetAddress *GetAddress() = 0; + virtual bool IsActive() = 0; + virtual bool IsHearingVoices() = 0; + virtual bool HasChatEnabled() = 0; +}; + +#define CLIENT_INTERFACE_VERSION "client001" diff --git a/dep/hlsdk/public/HLTV/IDirector.h b/dep/hlsdk/public/HLTV/IDirector.h new file mode 100644 index 0000000..b840662 --- /dev/null +++ b/dep/hlsdk/public/HLTV/IDirector.h @@ -0,0 +1,52 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class IWorld; +class IProxy; +class BitBuffer; +class DirectorCmd; +class IObjectContainer; + +class IDirector: virtual public ISystemModule { +public: + virtual ~IDirector() {} + + virtual void NewGame(IWorld *world, IProxy *proxy) = 0; + virtual char *GetModName() = 0; + virtual void WriteCommands(BitBuffer *stream, float startTime, float endTime) = 0; + virtual int AddCommand(DirectorCmd *cmd) = 0; + virtual bool RemoveCommand(int index) = 0; + virtual DirectorCmd *GetLastCommand() = 0; + virtual IObjectContainer *GetCommands() = 0; +}; + +#define DIRECTOR_INTERFACE_VERSION "director001" diff --git a/dep/hlsdk/public/HLTV/INetChannel.h b/dep/hlsdk/public/HLTV/INetChannel.h new file mode 100644 index 0000000..dad99f6 --- /dev/null +++ b/dep/hlsdk/public/HLTV/INetChannel.h @@ -0,0 +1,60 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class INetSocket; +class IBaseSystem; +class INetChannel { +public: + virtual ~INetChannel() {} + + virtual bool Create(IBaseSystem *system, INetSocket *netsocket = nullptr, NetAddress *adr = nullptr) = 0; + virtual NetAddress *GetTargetAddress() = 0; + virtual void Close() = 0; + virtual void Clear() = 0; + virtual void Reset() = 0; + virtual bool IsConnected() = 0; + virtual bool IsReadyToSend() = 0; + virtual bool IsCrashed() = 0; + virtual bool IsTimedOut() = 0; + virtual bool IsFakeChannel() = 0; + virtual bool KeepAlive() = 0; + virtual void SetRate(int newRate) = 0; + virtual void SetUpdateRate(int newupdaterate) = 0; + virtual void SetTimeOut(float time) = 0; + virtual void SetKeepAlive(bool flag) = 0; + virtual float GetIdleTime() = 0; + virtual int GetRate() = 0; + virtual int GetUpdateRate() = 0; + virtual float GetLoss() = 0; + virtual void TransmitOutgoing() = 0; + virtual void ProcessIncoming(unsigned char *data, int size) = 0; + virtual void OutOfBandPrintf(const char *format, ...) = 0; + virtual void FakeAcknowledgement() = 0; +}; diff --git a/dep/hlsdk/public/HLTV/INetSocket.h b/dep/hlsdk/public/HLTV/INetSocket.h new file mode 100644 index 0000000..972d441 --- /dev/null +++ b/dep/hlsdk/public/HLTV/INetSocket.h @@ -0,0 +1,55 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class INetwork; +class INetChannel; +class NetPacket; + +class INetSocket { +public: + virtual ~INetSocket() {}; + + virtual NetPacket *ReceivePacket() = 0; + virtual void FreePacket(NetPacket *packet) = 0; + virtual bool SendPacket(NetPacket *packet) = 0; + virtual bool SendPacket(NetAddress *to, const void *data, int length) = 0; + virtual void AddPacket(NetPacket *packet) = 0; + virtual bool AddChannel(INetChannel *channel) = 0; + virtual bool RemoveChannel(INetChannel *channel) = 0; + + virtual INetwork *GetNetwork() = 0; + virtual void OutOfBandPrintf(NetAddress *to, const char *format, ...) = 0; + virtual void Flush() = 0; + virtual void GetFlowStats(float *totalIn, float *totalOut) = 0; + virtual bool LeaveGroup(NetAddress *group) = 0; + virtual bool JoinGroup(NetAddress *group) = 0; + virtual void Close() = 0; + virtual int GetPort() = 0; +}; diff --git a/dep/hlsdk/public/HLTV/INetwork.h b/dep/hlsdk/public/HLTV/INetwork.h new file mode 100644 index 0000000..05c31a0 --- /dev/null +++ b/dep/hlsdk/public/HLTV/INetwork.h @@ -0,0 +1,62 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class INetSocket; +class INetwork { +public: + virtual ~INetwork() {}; + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual INetSocket *CreateSocket(int port, bool reuse = false, bool loopback = false) = 0; + virtual bool RemoveSocket(INetSocket *netsocket) = 0; + virtual NetAddress *GetLocalAddress() = 0; + virtual bool ResolveAddress(char *string, NetAddress *address) = 0; + virtual void GetFlowStats(float *totalIn, float *totalOut) = 0; + virtual int GetLastErrorCode() = 0; + virtual char *GetErrorText(int code) = 0; +}; + +#define NETWORK_INTERFACE_VERSION "network001" diff --git a/dep/hlsdk/public/HLTV/IProxy.h b/dep/hlsdk/public/HLTV/IProxy.h new file mode 100644 index 0000000..6724897 --- /dev/null +++ b/dep/hlsdk/public/HLTV/IProxy.h @@ -0,0 +1,107 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" +#include "custom.h" + +class IWorld; +class IServer; +class IDirector; +class INetSocket; +class BitBuffer; +class NetAddress; +class IObjectContainer; + +#define MAX_PROXY_CLIENTS 255 + +#define GROUP_CLIENT 0x00001 // Broadcast to client +#define GROUP_PROXY 0x00002 // Broadcast to proxy +#define GROUP_DEMO 0x00004 // Broadcast to demo file +#define GROUP_UNKNOWN 0x00008 // Broadcast to UNKNOWN: unused +#define GROUP_VOICE 0x00010 // Broadcast to voice enabled clients +#define GROUP_CHAT 0x00020 // Broadcast to chat enabled clients + +#define GROUP_CLIENT_ALL GROUP_CLIENT | GROUP_PROXY | GROUP_DEMO | GROUP_UNKNOWN + +enum ChatMode_e : int +{ + CHAT_OFF, // Spectators can't chat. + CHAT_LOCAL, // Only spectators connected to the same proxy can see their chat messages. + CHAT_GLOBAL, // All spectators can chat between each other (then Master and all Relay proxies must have set chatmode 2). +}; + +class IProxy: virtual public ISystemModule { +public: + virtual ~IProxy() {} + + virtual void Reset() = 0; + virtual void Broadcast(byte *data, int length, int groupType, bool isReliable) = 0; + virtual void IncreaseCheering(int votes) = 0; + virtual void ParseStatusMsg(BitBuffer *stream) = 0; + virtual void ParseStatusReport(NetAddress *from, BitBuffer *stream) = 0; + virtual bool ProcessConnectionlessMessage(NetAddress *from, BitBuffer *stream) = 0; + virtual void ChatCommentator(char *nick, char *text) = 0; + virtual void ChatSpectator(char *nick, char *text) = 0; + virtual void CountLocalClients(int &spectators, int &proxies) = 0; + virtual struct resource_s *AddResource(char *fileName, resourcetype_t type, char *asFileName = nullptr) = 0; + virtual bool IsLanOnly() = 0; + virtual bool IsMaster() = 0; + virtual bool IsActive() = 0; + virtual bool IsPublicGame() = 0; + virtual bool IsPasswordProtected() = 0; + virtual bool IsStressed() = 0; + virtual void SetDelay(float seconds) = 0; + virtual void SetClientTime(double time, bool relative) = 0; + virtual void SetClientTimeScale(float scale) = 0; + virtual void SetMaxRate(int rate) = 0; + virtual void SetMaxLoss(float maxloss) = 0; + virtual void SetMaxUpdateRate(int updaterate) = 0; + virtual bool SetMaxClients(int number) = 0; + virtual void SetRegion(unsigned char region) = 0; + virtual float GetDelay() = 0; + virtual double GetSpectatorTime() = 0; + virtual double GetProxyTime() = 0; + virtual int GetMaxClients() = 0; + virtual IWorld *GetWorld() = 0; + virtual IServer *GetServer() = 0; + virtual IDirector *GetDirector() = 0; + virtual INetSocket *GetSocket() = 0; + virtual ChatMode_e GetChatMode() = 0; + virtual void GetStatistics(int &proxies, int &slots, int &spectators) = 0; + virtual int GetMaxRate() = 0; + virtual int GetMaxUpdateRate() = 0; + virtual struct resource_s *GetResource(char *fileName) = 0; + virtual int GetDispatchMode() = 0; + virtual unsigned char GetRegion() = 0; + virtual IObjectContainer *GetClients() = 0; + virtual bool WriteSignonData(int type, BitBuffer *stream) = 0; +}; + +#define PROXY_INTERFACE_VERSION "proxy001" diff --git a/dep/hlsdk/public/HLTV/IServer.h b/dep/hlsdk/public/HLTV/IServer.h new file mode 100644 index 0000000..37640cf --- /dev/null +++ b/dep/hlsdk/public/HLTV/IServer.h @@ -0,0 +1,101 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class IWorld; +class IProxy; +class IDirector; +class INetSocket; +class ISystemModule; +class IBaseSystem; + +class NetAddress; +class InfoString; +class BitBuffer; + +class IServer { +public: + virtual ~IServer() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual bool Connect(IWorld *world, NetAddress *adr, INetSocket *socket) = 0; + virtual bool LoadDemo(IWorld *world, char *filename, bool forceHLTV, bool continuous) = 0; + virtual void Reconnect() = 0; + virtual void Disconnect() = 0; + virtual void Retry() = 0; + virtual void StopRetry() = 0; + virtual void SendStringCommand(char *command) = 0; + virtual void SendHLTVCommand(BitBuffer *msg) = 0; + virtual bool IsConnected() = 0; + virtual bool IsDemoFile() = 0; + virtual bool IsGameServer() = 0; + virtual bool IsRelayProxy() = 0; + virtual bool IsVoiceBlocking() = 0; + virtual void SetProxy(IProxy *proxy) = 0; + virtual void SetDirector(IDirector *director) = 0; + virtual void SetPlayerName(char *newName) = 0; + virtual void SetDelayReconnect(bool state) = 0; + virtual void SetAutoRetry(bool state) = 0; + virtual void SetVoiceBlocking(bool state) = 0; + virtual void SetRate(int rate) = 0; + virtual void SetUpdateRate(int updaterate) = 0; + virtual void SetUserInfo(char *key, char *value) = 0; + virtual bool SetProtocol(int version) = 0; + virtual void SetGameDirectory(const char *defaultDir, const char *gameDir = nullptr) = 0; + virtual int GetRate() = 0; + virtual int GetUpdateRate() = 0; + virtual InfoString *GetServerInfoString() = 0; + virtual char *GetPlayerName() = 0; + virtual float GetTime() = 0; + virtual IWorld *GetWorld() = 0; + virtual char *GetDemoFileName() = 0; + virtual NetAddress *GetAddress() = 0; + virtual char *GetHostName() = 0; + virtual bool GetAutoRetry() = 0; + virtual float GetPacketLoss() = 0; + virtual int GetProtocol() = 0; +}; + +#define SERVER_INTERFACE_VERSION "server001" diff --git a/dep/hlsdk/public/HLTV/IWorld.h b/dep/hlsdk/public/HLTV/IWorld.h new file mode 100644 index 0000000..8e24c26 --- /dev/null +++ b/dep/hlsdk/public/HLTV/IWorld.h @@ -0,0 +1,163 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IBSPModel.h" +#include "IDirector.h" +#include "ISystemModule.h" +#include "common/ServerInfo.h" + +#include "pm_movevars.h" +#include "usermsg.h" +#include "entity_state.h" + +typedef struct frame_s +{ + float time; + unsigned int seqnr; + unsigned char *data; + void *entities; + unsigned int entitiesSize; + unsigned int entitynum; + void *clientData; + unsigned int clientDataSize; + unsigned char *events; + unsigned int eventsSize; + unsigned int eventnum; + unsigned char *reliableData; + unsigned int reliableDataSize; + unsigned char *unreliableData; + unsigned int unreliableDataSize; + unsigned char *userMessages; + unsigned int userMessagesSize; + unsigned char *voiceData; + unsigned int voiceDataSize; + unsigned char *demoData; + unsigned int demoDataSize; + void *demoInfo; + unsigned int delta; +} frame_t; + +class InfoString; +class NetAddress; + +class IWorld { +public: + virtual ~IWorld() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual double GetTime() = 0; + virtual NetAddress *GetGameServerAddress() = 0; + virtual char *GetLevelName() = 0; + virtual char *GetGameDir() = 0; + virtual frame_t *GetFrameByTime(double time) = 0; + virtual frame_t *GetFrameBySeqNr(unsigned int seqnr) = 0; + virtual frame_t *GetLastFrame() = 0; + virtual frame_t *GetFirstFrame() = 0; + virtual int GetServerCount() = 0; + virtual int GetSlotNumber() = 0; + virtual int GetMaxClients() = 0; + virtual int GetNumPlayers() = 0; + virtual IBSPModel *GetWorldModel() = 0; + virtual InfoString *GetServerInfoString() = 0; + virtual bool GetPlayerInfoString(int playerNum, InfoString *infoString) = 0; + virtual UserMsg *GetUserMsg(int msgNumber) = 0; + virtual char *GetHostName() = 0; + virtual serverinfo_t *GetServerInfo() = 0; + virtual bool IsPlayerIndex(int index) = 0; + virtual bool IsVoiceEnabled() = 0; + virtual bool IsActive() = 0; + virtual bool IsPaused() = 0; + virtual bool IsComplete() = 0; + virtual bool IsHLTV() = 0; + virtual void Reset() = 0; + virtual void SetServerInfo(int protocol, CRC32_t nserverCRC, byte *nclientdllmd5, int nmaxclients, int nplayernum, int ngametype, char *ngamedir, char *nservername, char *nlevelname) = 0; + virtual void SetServerInfoString(char *infostring) = 0; + virtual void SetServerInfo(serverinfo_t *serverinfo) = 0; + virtual void UpdateServerInfo() = 0; + virtual void SetPaused(bool state) = 0; + virtual void SetTime(double newTime) = 0; + virtual void SetBufferSize(float seconds) = 0; + virtual void SetVoiceEnabled(bool state) = 0; + virtual void SetMoveVars(movevars_t *nmovevars) = 0; + virtual void SetCDInfo(int ncdtrack, int nlooptrack) = 0; + virtual void SetHLTV(bool state) = 0; + virtual void SetExtraInfo(char *nclientfallback, int nallowCheats) = 0; + virtual void SetViewEntity(int nviewentity) = 0; + virtual void SetGameServerAddress(NetAddress *address) = 0; + virtual void SetHostName(char *name) = 0; + virtual void NewGame(int newServerCount) = 0; + virtual void FinishGame() = 0; + virtual bool SaveAsDemo(char *filename, IDirector *director) = 0; + virtual void StopGame() = 0; + virtual int FindUserMsgByName(char *name) = 0; + virtual void ParseDeltaDescription(BitBuffer *stream) = 0; + virtual void ParseBaseline(BitBuffer *stream) = 0; + virtual void ParseEvent(BitBuffer *stream) = 0; + virtual void ParseClientData(BitBuffer *stream, unsigned int deltaSeqNr, BitBuffer *to, clientdata_t *clientData) = 0; + virtual bool GetUncompressedFrame(unsigned int seqNr, frame_t *frame) = 0; + virtual bool UncompressEntitiesFromStream(frame_t *frame, BitBuffer *stream) = 0; + virtual bool UncompressEntitiesFromStream(frame_t *frame, BitBuffer *stream, unsigned int from) = 0; + virtual bool GetClientData(unsigned int SeqNr, clientdata_t *clientData) = 0; + virtual bool GetClientData(frame_t *frame, clientdata_t *clientData) = 0; + virtual int AddFrame(frame_t *newFrame) = 0; + virtual bool AddResource(resource_t *resource) = 0; + virtual void AddLightStyle(int index, char *style) = 0; + virtual bool AddSignonData(unsigned char type, unsigned char *data, int size) = 0; + virtual bool AddUserMessage(int msgNumber, int size, char *name) = 0; + virtual void AddBaselineEntity(int index, entity_state_t *ent) = 0; + virtual void AddInstancedBaselineEntity(int index, entity_state_t *ent) = 0; + virtual void UpdatePlayer(int playerNum, int userId, char *infostring, char *hashedcdkey) = 0; + virtual void WriteFrame(frame_t *frame, unsigned int lastFrameSeqnr, BitBuffer *reliableStream, BitBuffer *unreliableStream, unsigned int deltaSeqNr, unsigned int clientDelta, bool addVoice) = 0; + virtual void WriteNewData(BitBuffer *stream) = 0; + virtual void WriteClientUpdate(BitBuffer *stream, int playerIndex) = 0; + virtual void WriteMovevars(BitBuffer *stream) = 0; + virtual void WriteSigonData(BitBuffer *stream) = 0; + virtual void WriteLightStyles(BitBuffer *stream) = 0; + virtual int RemoveFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; + virtual int DuplicateFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; + virtual int MoveFrames(unsigned int startSeqNr, unsigned int endSeqNr, double destSeqnr) = 0; + virtual int RevertFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; +}; + +#define WORLD_INTERFACE_VERSION "world001" diff --git a/dep/hlsdk/public/asmlib.h b/dep/hlsdk/public/asmlib.h new file mode 100644 index 0000000..c1bc9af --- /dev/null +++ b/dep/hlsdk/public/asmlib.h @@ -0,0 +1,123 @@ +/*************************** asmlib.h *************************************** +* Author: Agner Fog +* Date created: 2003-12-12 +* Last modified: 2013-10-04 +* Project: asmlib.zip +* Source URL: www.agner.org/optimize +* +* Description: +* Header file for the asmlib function library. +* This library is available in many versions for different platforms. +* See asmlib-instructions.pdf for details. +* +* (c) Copyright 2003 - 2013 by Agner Fog. +* GNU General Public License http://www.gnu.org/licenses/gpl.html +*****************************************************************************/ + + +#ifndef ASMLIB_H +#define ASMLIB_H + + +/*********************************************************************** +Define compiler-specific types and directives +***********************************************************************/ + +// Define type size_t +#ifndef _SIZE_T_DEFINED +#include "stddef.h" +#endif + +// Define integer types with known size: int32_t, uint32_t, int64_t, uint64_t. +// If this doesn't work then insert compiler-specific definitions here: +#if defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1600) + // Compilers supporting C99 or C++0x have stdint.h defining these integer types + #include + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#elif defined(_MSC_VER) + // Older Microsoft compilers have their own definition + typedef signed __int16 int16_t; + typedef unsigned __int16 uint16_t; + typedef signed __int32 int32_t; + typedef unsigned __int32 uint32_t; + typedef signed __int64 int64_t; + typedef unsigned __int64 uint64_t; + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#else + // This works with most compilers + typedef signed short int int16_t; + typedef unsigned short int uint16_t; + typedef signed int int32_t; + typedef unsigned int uint32_t; + typedef long long int64_t; + typedef unsigned long long uint64_t; + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#endif + + +// Turn off name mangling +#ifdef __cplusplus +extern "C" { +#endif + +/*********************************************************************** +Function prototypes, memory and string functions +***********************************************************************/ +void * A_memcpy (void * dest, const void * src, size_t count); // Copy count bytes from src to dest +void * A_memmove(void * dest, const void * src, size_t count); // Same as memcpy, allows overlap between src and dest +void * A_memset (void * dest, int c, size_t count); // Set count bytes in dest to (char)c +int A_memcmp (const void * buf1, const void * buf2, size_t num); // Compares two blocks of memory +size_t GetMemcpyCacheLimit(void); // Data blocks bigger than this will be copied uncached by memcpy and memmove +void SetMemcpyCacheLimit(size_t); // Change limit in GetMemcpyCacheLimit +size_t GetMemsetCacheLimit(void); // Data blocks bigger than this will be stored uncached by memset +void SetMemsetCacheLimit(size_t); // Change limit in GetMemsetCacheLimit +char * A_strcat (char * dest, const char * src); // Concatenate strings dest and src. Store result in dest +char * A_strcpy (char * dest, const char * src); // Copy string src to dest +size_t A_strlen (const char * str); // Get length of zero-terminated string +int A_strcmp (const char * a, const char * b); // Compare strings. Case sensitive +int A_stricmp (const char *string1, const char *string2); // Compare strings. Case insensitive for A-Z only +char * A_strstr (char * haystack, const char * needle); // Search for substring in string +void A_strtolower(char * string); // Convert string to lower case for A-Z only +void A_strtoupper(char * string); // Convert string to upper case for a-z only +size_t A_substring(char * dest, const char * source, size_t pos, size_t len); // Copy a substring for source into dest +size_t A_strspn (const char * str, const char * set); // Find span of characters that belong to set +size_t A_strcspn(const char * str, const char * set); // Find span of characters that don't belong to set +size_t strCountInSet(const char * str, const char * set); // Count characters that belong to set +size_t strcount_UTF8(const char * str); // Counts the number of characters in a UTF-8 encoded string + + +/*********************************************************************** +Function prototypes, miscellaneous functions +***********************************************************************/ +uint32_t A_popcount(uint32_t x); // Count 1-bits in 32-bit integer +int RoundD (double x); // Round to nearest or even +int RoundF (float x); // Round to nearest or even +int InstructionSet(void); // Tell which instruction set is supported +char * ProcessorName(void); // ASCIIZ text describing microprocessor +void CpuType(int * vendor, int * family, int * model); // Get CPU vendor, family and model +size_t DataCacheSize(int level); // Get size of data cache +void A_DebugBreak(void); // Makes a debug breakpoint +#ifdef INT64_SUPPORTED + uint64_t ReadTSC(void); // Read microprocessor internal clock (64 bits) +#else + uint32_t ReadTSC(void); // Read microprocessor internal clock (only 32 bits supported by compiler) +#endif +void cpuid_ex (int abcd[4], int eax, int ecx); // call CPUID instruction +static inline void cpuid_abcd (int abcd[4], int eax) { + cpuid_ex(abcd, eax, 0);} + +#ifdef __cplusplus +} // end of extern "C" + +// Define overloaded versions if compiling as C++ + +static inline int Round (double x) { // Overload name Round + return RoundD(x);} +static inline int Round (float x) { // Overload name Round + return RoundF(x);} +static inline const char * A_strstr(const char * haystack, const char * needle) { + return A_strstr((char*)haystack, needle);} // Overload A_strstr with const char * version + +#endif // __cplusplus + +#endif // ASMLIB_H diff --git a/dep/hlsdk/public/basetypes.h b/dep/hlsdk/public/basetypes.h new file mode 100644 index 0000000..4a1e0d5 --- /dev/null +++ b/dep/hlsdk/public/basetypes.h @@ -0,0 +1,78 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef BASETYPES_H +#define BASETYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#include "osconfig.h" +#include "commonmacros.h" + +#include "archtypes.h" +#include "mathlib.h" + +// For backward compatibilty only... +#include "tier0/platform.h" + +// stdio.h +#ifndef NULL +#define NULL 0 +#endif + +// Pad a number so it lies on an N byte boundary. +// So PAD_NUMBER(0,4) is 0 and PAD_NUMBER(1,4) is 4 +#define PAD_NUMBER(number, boundary) \ + (((number) + ((boundary) - 1)) / (boundary)) * (boundary) + +#ifndef FALSE +#define FALSE 0 +#define TRUE (!FALSE) +#endif + +typedef int BOOL; +typedef int qboolean; +typedef unsigned long ULONG; +typedef unsigned char BYTE; +typedef unsigned char byte; +typedef unsigned short word; + +typedef float vec_t; + +#ifndef UNUSED +#define UNUSED(x) (x = x) // for pesky compiler / lint warnings +#endif + +struct vrect_t +{ + int x, y, width, height; + vrect_t *pnext; +}; + +#endif // BASETYPES_H diff --git a/dep/hlsdk/public/cl_dll/IGameClientExports.h b/dep/hlsdk/public/cl_dll/IGameClientExports.h new file mode 100644 index 0000000..d45d53a --- /dev/null +++ b/dep/hlsdk/public/cl_dll/IGameClientExports.h @@ -0,0 +1,34 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef IGAMECLIENTEXPORTS_H +#define IGAMECLIENTEXPORTS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "interface.h" + +//----------------------------------------------------------------------------- +// Purpose: Exports a set of functions for the GameUI interface to interact with the game client +//----------------------------------------------------------------------------- +class IGameClientExports : public IBaseInterface +{ +public: + // returns the name of the server the user is connected to, if any + virtual const char *GetServerHostName() = 0; + + // ingame voice manipulation + virtual bool IsPlayerGameVoiceMuted(int playerIndex) = 0; + virtual void MutePlayerGameVoice(int playerIndex) = 0; + virtual void UnmutePlayerGameVoice(int playerIndex) = 0; +}; + +#define GAMECLIENTEXPORTS_INTERFACE_VERSION "GameClientExports001" + + +#endif // IGAMECLIENTEXPORTS_H diff --git a/dep/hlsdk/public/commonmacros.h b/dep/hlsdk/public/commonmacros.h new file mode 100644 index 0000000..e82bfd6 --- /dev/null +++ b/dep/hlsdk/public/commonmacros.h @@ -0,0 +1,30 @@ +#ifndef COMMONMACROS_H +#define COMMONMACROS_H +#pragma once + + +// ------------------------------------------------------- +// +// commonmacros.h +// +// This should contain ONLY general purpose macros that are +// appropriate for use in engine/launcher/all tools +// +// ------------------------------------------------------- + +#include "osconfig.h" +// Makes a 4-byte "packed ID" int out of 4 characters +#define MAKEID(d,c,b,a) ( ((int)(a) << 24) | ((int)(b) << 16) | ((int)(c) << 8) | ((int)(d)) ) + +// Compares a string with a 4-byte packed ID constant +#define STRING_MATCHES_ID( p, id ) ( (*((int *)(p)) == (id) ) ? true : false ) +#define ID_TO_STRING( id, p ) ( (p)[3] = (((id)>>24) & 0xFF), (p)[2] = (((id)>>16) & 0xFF), (p)[1] = (((id)>>8) & 0xFF), (p)[0] = (((id)>>0) & 0xFF) ) + +#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) + +// Keeps clutter down a bit, when using a float as a bit-vector +#define SetBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) | (bits)) +#define ClearBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) & ~(bits)) +#define FBitSet(flBitVector, bit) ((int)(flBitVector) & (bit)) + +#endif // COMMONMACROS_H diff --git a/dep/hlsdk/public/engine_hlds_api.h b/dep/hlsdk/public/engine_hlds_api.h new file mode 100644 index 0000000..53ceb36 --- /dev/null +++ b/dep/hlsdk/public/engine_hlds_api.h @@ -0,0 +1,49 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +#ifdef _WIN32 + #define ENGINE_LIB "swds.dll" +#else + #define ENGINE_LIB "engine_i486.so" +#endif // _WIN32 + +class IDedicatedServerAPI : public IBaseInterface +{ +public: + virtual bool Init(char *basedir, char *cmdline, CreateInterfaceFn launcherFactory, CreateInterfaceFn filesystemFactory) = 0; + virtual int Shutdown() = 0; + virtual bool RunFrame() = 0; + virtual void AddConsoleText(char *text) = 0; + virtual void UpdateStatus(float *fps, int *nActive, int *nMaxPlayers, char *pszMap) = 0; +}; + +#define VENGINE_HLDS_API_VERSION "VENGINE_HLDS_API_VERSION002" diff --git a/dep/hlsdk/public/engine_launcher_api.h b/dep/hlsdk/public/engine_launcher_api.h new file mode 100644 index 0000000..fe9b51e --- /dev/null +++ b/dep/hlsdk/public/engine_launcher_api.h @@ -0,0 +1,52 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef ENGINE_LAUNCHER_API_H +#define ENGINE_LAUNCHER_API_H +#ifdef _WIN32 +#pragma once +#endif + +#include "interface.h" + +#ifdef _WIN32 + #define ENGINE_CLIENT_LIB "hw.dll" + #define ENGINE_CLIENT_SOFT_LIB "sw.dll" +#else + #define ENGINE_CLIENT_LIB "hw.so" +#endif // _WIN32 + +class IEngineAPI : public IBaseInterface +{ +public: + virtual int Run(void *instance, char *basedir, char *cmdline, char *postRestartCmdLineArgs, CreateInterfaceFn launcherFactory, CreateInterfaceFn filesystemFactory) = 0; +}; + +#define VENGINE_LAUNCHER_API_VERSION "VENGINE_LAUNCHER_API_VERSION002" + +#endif // ENGINE_LAUNCHER_API_H diff --git a/dep/hlsdk/public/icommandline.h b/dep/hlsdk/public/icommandline.h new file mode 100644 index 0000000..a06ba94 --- /dev/null +++ b/dep/hlsdk/public/icommandline.h @@ -0,0 +1,47 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Interface to engine command line +class ICommandLine { +public: + virtual void CreateCmdLine(const char *commandline) = 0; + virtual void CreateCmdLine(int argc, const char **argv) = 0; + virtual const char *GetCmdLine() const = 0; + + // Check whether a particular parameter exists + virtual const char *CheckParm(const char *psz, char **ppszValue = nullptr) const = 0; + virtual void RemoveParm(const char *pszParm) = 0; + virtual void AppendParm(const char *pszParm, const char *pszValues) = 0; + + virtual void SetParm(const char *pszParm, const char *pszValues) = 0; + virtual void SetParm(const char *pszParm, int iValue) = 0; +}; + +ICommandLine *CommandLine(); diff --git a/dep/hlsdk/public/idedicatedexports.h b/dep/hlsdk/public/idedicatedexports.h new file mode 100644 index 0000000..5cbe36c --- /dev/null +++ b/dep/hlsdk/public/idedicatedexports.h @@ -0,0 +1,40 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +class IDedicatedExports : public IBaseInterface +{ +public: + virtual ~IDedicatedExports() {}; + virtual void Sys_Printf(char *text) = 0; +}; + +#define VENGINE_DEDICATEDEXPORTS_API_VERSION "VENGINE_DEDICATEDEXPORTS_API_VERSION001" diff --git a/dep/hlsdk/public/interface.cpp b/dep/hlsdk/public/interface.cpp new file mode 100644 index 0000000..36002fe --- /dev/null +++ b/dep/hlsdk/public/interface.cpp @@ -0,0 +1,231 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +// InterfaceReg +InterfaceReg *InterfaceReg::s_pInterfaceRegs = nullptr; + +InterfaceReg::InterfaceReg(InstantiateInterfaceFn fn, const char *pName) : m_pName(pName) +{ + m_CreateFn = fn; + m_pNext = s_pInterfaceRegs; + s_pInterfaceRegs = this; +} + +// This is the primary exported function by a dll, referenced by name via dynamic binding +// that exposes an opqaue function pointer to the interface. +// +// We have the Internal variant so Sys_GetFactoryThis() returns the correct internal +// symbol under GCC/Linux/Mac as CreateInterface is DLL_EXPORT so its global so the loaders +// on those OS's pick exactly 1 of the CreateInterface symbols to be the one that is process wide and +// all Sys_GetFactoryThis() calls find that one, which doesn't work. Using the internal walkthrough here +// makes sure Sys_GetFactoryThis() has the dll specific symbol and GetProcAddress() returns the module specific +// function for CreateInterface again getting the dll specific symbol we need. +EXPORT_FUNCTION IBaseInterface *CreateInterface(const char *pName, int *pReturnCode) +{ + InterfaceReg *pCur; + for (pCur = InterfaceReg::s_pInterfaceRegs; pCur; pCur = pCur->m_pNext) + { + if (strcmp(pCur->m_pName, pName) == 0) + { + if (pReturnCode) + { + *pReturnCode = IFACE_OK; + } + + return pCur->m_CreateFn(); + } + } + + if (pReturnCode) + { + *pReturnCode = IFACE_FAILED; + } + + return nullptr; +} + +#ifndef _WIN32 +// Linux doesn't have this function so this emulates its functionality +void *GetModuleHandle(const char *name) +{ + void *handle; + if (name == nullptr) + { + // hmm, how can this be handled under linux.... + // is it even needed? + return nullptr; + } + + if ((handle = dlopen(name, RTLD_NOW)) == nullptr) + { + //printf("Error:%s\n",dlerror()); + // couldn't open this file + return nullptr; + } + + // read "man dlopen" for details + // in short dlopen() inc a ref count + // so dec the ref count by performing the close + dlclose(handle); + return handle; +} +#endif // _WIN32 + +// Purpose: returns a pointer to a function, given a module +// Input : pModuleName - module name +// *pName - proc name +//static hlds_run wants to use this function +void *Sys_GetProcAddress(const char *pModuleName, const char *pName) +{ + return GetProcAddress(GetModuleHandle(pModuleName), pName); +} + +// Purpose: returns a pointer to a function, given a module +// Input : pModuleName - module name +// *pName - proc name +// hlds_run wants to use this function +void *Sys_GetProcAddress(void *pModuleHandle, const char *pName) +{ + return GetProcAddress((HMODULE)pModuleHandle, pName); +} + +// Purpose: Loads a DLL/component from disk and returns a handle to it +// Input : *pModuleName - filename of the component +// Output : opaque handle to the module (hides system dependency) +CSysModule *Sys_LoadModule(const char *pModuleName) +{ +#ifdef _WIN32 + HMODULE hDLL = LoadLibrary(pModuleName); +#else + HMODULE hDLL = nullptr; + char szAbsoluteModuleName[1024]; + if (pModuleName[0] != '/') + { + char szCwd[1024]; + getcwd(szCwd, sizeof(szCwd)); + if (szCwd[strlen(szCwd) - 1] == '/') + szCwd[strlen(szCwd) - 1] = '\0'; + + _snprintf(szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s/%s", szCwd, pModuleName); + hDLL = dlopen(szAbsoluteModuleName, RTLD_NOW); + } + else + { + _snprintf(szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s", pModuleName); + hDLL = dlopen(pModuleName, RTLD_NOW); + } +#endif // _WIN32 + + if (!hDLL) + { + char str[512]; + +#if defined(_WIN32) + _snprintf(str, sizeof(str), "%s.dll", pModuleName); + hDLL = LoadLibrary(str); +#elif defined(OSX) + printf("Error: %s\n", dlerror()); + _snprintf(str, sizeof(str), "%s.dylib", szAbsoluteModuleName); + hDLL = dlopen(str, RTLD_NOW); +#else + printf("Error: %s\n", dlerror()); + _snprintf(str, sizeof(str), "%s.so", szAbsoluteModuleName); + hDLL = dlopen(str, RTLD_NOW); +#endif + } + + return reinterpret_cast(hDLL); +} + +// Purpose: Unloads a DLL/component from +// Input : *pModuleName - filename of the component +// Output : opaque handle to the module (hides system dependency) +void Sys_UnloadModule(CSysModule *pModule) +{ + if (!pModule) + return; + + HMODULE hDLL = reinterpret_cast(pModule); + +#ifdef _WIN32 + FreeLibrary(hDLL); +#else + dlclose(hDLL); +#endif // _WIN32 +} + +// Purpose: returns a pointer to a function, given a module +// Input : module - windows HMODULE from Sys_LoadModule() +// *pName - proc name +// Output : factory for this module +CreateInterfaceFn Sys_GetFactory(CSysModule *pModule) +{ + if (!pModule) + return nullptr; + + return reinterpret_cast(Sys_GetProcAddress(pModule, CREATEINTERFACE_PROCNAME)); +} + +// Purpose: returns the instance of this module +// Output : CreateInterfaceFn +CreateInterfaceFn Sys_GetFactoryThis() +{ + return CreateInterface; +} + +// Purpose: returns the instance of the named module +// Input : *pModuleName - name of the module +// Output : CreateInterfaceFn - instance of that module +CreateInterfaceFn Sys_GetFactory(const char *pModuleName) +{ + return reinterpret_cast(Sys_GetProcAddress(pModuleName, CREATEINTERFACE_PROCNAME)); +} + +// Purpose: finds a particular interface in the factory set +void *InitializeInterface(char const *interfaceName, CreateInterfaceFn *factoryList, int numFactories) +{ + void *retval; + + for (int i = 0; i < numFactories; i++) + { + CreateInterfaceFn factory = factoryList[ i ]; + if (!factory) + continue; + + retval = factory(interfaceName, nullptr); + if (retval) + return retval; + } + + // No provider for requested interface!!! + // assert(!"No provider for requested interface!!!"); + + return nullptr; +} diff --git a/dep/hlsdk/public/interface.h b/dep/hlsdk/public/interface.h new file mode 100644 index 0000000..2dd8760 --- /dev/null +++ b/dep/hlsdk/public/interface.h @@ -0,0 +1,123 @@ +// This header defines the interface convention used in the valve engine. +// To make an interface and expose it: +// 1. Derive from IBaseInterface. +// 2. The interface must be ALL pure virtuals, and have no data members. +// 3. Define a name for it. +// 4. In its implementation file, use EXPOSE_INTERFACE or EXPOSE_SINGLE_INTERFACE. + +// Versioning +// There are two versioning cases that are handled by this: +// 1. You add functions to the end of an interface, so it is binary compatible with the previous interface. In this case, +// you need two EXPOSE_INTERFACEs: one to expose your class as the old interface and one to expose it as the new interface. +// 2. You update an interface so it's not compatible anymore (but you still want to be able to expose the old interface +// for legacy code). In this case, you need to make a new version name for your new interface, and make a wrapper interface and +// expose it for the old interface. + +#pragma once + +#ifndef _WIN32 + +#include // dlopen, dlclose, et al +#include + +#define HMODULE void * +#define GetProcAddress dlsym + +#define _snprintf snprintf + +#endif // _WIN32 + +void *Sys_GetProcAddress(const char *pModuleName, const char *pName); +void *Sys_GetProcAddress(void *pModuleHandle, const char *pName); + +// All interfaces derive from this. +class IBaseInterface +{ +public: + virtual ~IBaseInterface() {} +}; + +#define CREATEINTERFACE_PROCNAME "CreateInterface" + +typedef IBaseInterface *(*CreateInterfaceFn)(const char *pName, int *pReturnCode); +typedef IBaseInterface *(*InstantiateInterfaceFn)(); + +// Used internally to register classes. +class InterfaceReg +{ +public: + InterfaceReg(InstantiateInterfaceFn fn, const char *pName); + +public: + + InstantiateInterfaceFn m_CreateFn; + const char *m_pName; + + InterfaceReg *m_pNext; // For the global list. + static InterfaceReg *s_pInterfaceRegs; +}; + +// Use this to expose an interface that can have multiple instances. +// e.g.: +// EXPOSE_INTERFACE(CInterfaceImp, IInterface, "MyInterface001") +// This will expose a class called CInterfaceImp that implements IInterface (a pure class) +// clients can receive a pointer to this class by calling CreateInterface("MyInterface001") +// +// In practice, the shared header file defines the interface (IInterface) and version name ("MyInterface001") +// so that each component can use these names/vtables to communicate +// +// A single class can support multiple interfaces through multiple inheritance +// +// Use this if you want to write the factory function. +#define EXPOSE_INTERFACE_FN(functionName, interfaceName, versionName)\ + static InterfaceReg __g_Create##interfaceName##_reg(functionName, versionName); + +#define EXPOSE_INTERFACE(className, interfaceName, versionName)\ + static IBaseInterface *__Create##className##_interface() {return (interfaceName *)new className;}\ + static InterfaceReg __g_Create##className##_reg(__Create##className##_interface, versionName); + +// Use this to expose a singleton interface with a global variable you've created. +#define EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, globalVarName)\ + static IBaseInterface *__Create##className##interfaceName##_interface() {return (IBaseInterface *)&globalVarName;}\ + static InterfaceReg __g_Create##className##interfaceName##_reg(__Create##className##interfaceName##_interface, versionName); + +// Use this to expose a singleton interface. This creates the global variable for you automatically. +#define EXPOSE_SINGLE_INTERFACE(className, interfaceName, versionName)\ + static className __g_##className##_singleton;\ + EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, __g_##className##_singleton) + +#ifdef _WIN32 + #define EXPORT_FUNCTION __declspec(dllexport) +#else + #define EXPORT_FUNCTION __attribute__((visibility("default"))) +#endif // _WIN32 + +// This function is automatically exported and allows you to access any interfaces exposed with the above macros. +// if pReturnCode is set, it will return one of the following values +// extend this for other error conditions/code +enum +{ + IFACE_OK = 0, + IFACE_FAILED +}; + +extern "C" +{ + EXPORT_FUNCTION IBaseInterface *CreateInterface(const char *pName, int *pReturnCode); +}; + +extern CreateInterfaceFn Sys_GetFactoryThis(); + +// UNDONE: This is obsolete, use the module load/unload/get instead!!! +extern CreateInterfaceFn Sys_GetFactory(const char *pModuleName); + +// load/unload components +class CSysModule; + +// Load & Unload should be called in exactly one place for each module +// The factory for that module should be passed on to dependent components for +// proper versioning. +extern CSysModule *Sys_LoadModule(const char *pModuleName); +extern void Sys_UnloadModule(CSysModule *pModule); +extern CreateInterfaceFn Sys_GetFactory(CSysModule *pModule); +extern void *InitializeInterface(char const *interfaceName, CreateInterfaceFn *factoryList, int numFactories); diff --git a/dep/hlsdk/public/iregistry.h b/dep/hlsdk/public/iregistry.h new file mode 100644 index 0000000..eb732c0 --- /dev/null +++ b/dep/hlsdk/public/iregistry.h @@ -0,0 +1,48 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Purpose: Interface to registry +class IRegistry +{ +public: + // Init/shutdown + virtual void Init() = 0; + virtual void Shutdown() = 0; + + // Read/write integers + virtual int ReadInt(const char *key, int defaultValue = 0) = 0; + virtual void WriteInt(const char *key, int value) = 0; + + // Read/write strings + virtual const char *ReadString(const char *key, const char *defaultValue = nullptr) = 0; + virtual void WriteString(const char *key, const char *value) = 0; +}; + +extern IRegistry *registry; diff --git a/dep/hlsdk/public/keydefs.h b/dep/hlsdk/public/keydefs.h new file mode 100644 index 0000000..6f1e43f --- /dev/null +++ b/dep/hlsdk/public/keydefs.h @@ -0,0 +1,124 @@ +// keydefs.h +#ifndef KEYDEFS_H +#define KEYDEFS_H +#ifdef _WIN32 +#pragma once +#endif + +// +// these are the key numbers that should be passed to Key_Event +// +#define K_TAB 9 +#define K_ENTER 13 +#define K_ESCAPE 27 +#define K_SPACE 32 + +// normal keys should be passed as lowercased ascii + +#define K_BACKSPACE 127 +#define K_UPARROW 128 +#define K_DOWNARROW 129 +#define K_LEFTARROW 130 +#define K_RIGHTARROW 131 + +#define K_ALT 132 +#define K_CTRL 133 +#define K_SHIFT 134 +#define K_F1 135 +#define K_F2 136 +#define K_F3 137 +#define K_F4 138 +#define K_F5 139 +#define K_F6 140 +#define K_F7 141 +#define K_F8 142 +#define K_F9 143 +#define K_F10 144 +#define K_F11 145 +#define K_F12 146 +#define K_INS 147 +#define K_DEL 148 +#define K_PGDN 149 +#define K_PGUP 150 +#define K_HOME 151 +#define K_END 152 + +#define K_KP_HOME 160 +#define K_KP_UPARROW 161 +#define K_KP_PGUP 162 +#define K_KP_LEFTARROW 163 +#define K_KP_5 164 +#define K_KP_RIGHTARROW 165 +#define K_KP_END 166 +#define K_KP_DOWNARROW 167 +#define K_KP_PGDN 168 +#define K_KP_ENTER 169 +#define K_KP_INS 170 +#define K_KP_DEL 171 +#define K_KP_SLASH 172 +#define K_KP_MINUS 173 +#define K_KP_PLUS 174 +#define K_CAPSLOCK 175 +#define K_KP_MUL 176 +#define K_WIN 177 + + +// +// joystick buttons +// +#define K_JOY1 203 +#define K_JOY2 204 +#define K_JOY3 205 +#define K_JOY4 206 + +// +// aux keys are for multi-buttoned joysticks to generate so they can use +// the normal binding process +// +#define K_AUX1 207 +#define K_AUX2 208 +#define K_AUX3 209 +#define K_AUX4 210 +#define K_AUX5 211 +#define K_AUX6 212 +#define K_AUX7 213 +#define K_AUX8 214 +#define K_AUX9 215 +#define K_AUX10 216 +#define K_AUX11 217 +#define K_AUX12 218 +#define K_AUX13 219 +#define K_AUX14 220 +#define K_AUX15 221 +#define K_AUX16 222 +#define K_AUX17 223 +#define K_AUX18 224 +#define K_AUX19 225 +#define K_AUX20 226 +#define K_AUX21 227 +#define K_AUX22 228 +#define K_AUX23 229 +#define K_AUX24 230 +#define K_AUX25 231 +#define K_AUX26 232 +#define K_AUX27 233 +#define K_AUX28 234 +#define K_AUX29 235 +#define K_AUX30 236 +#define K_AUX31 237 +#define K_AUX32 238 +#define K_MWHEELDOWN 239 +#define K_MWHEELUP 240 + +#define K_PAUSE 255 + +// +// mouse buttons generate virtual keys +// +#define K_MOUSE1 241 +#define K_MOUSE2 242 +#define K_MOUSE3 243 +#define K_MOUSE4 244 +#define K_MOUSE5 245 + +#endif // KEYDEFS_H diff --git a/dep/hlsdk/public/particleman.h b/dep/hlsdk/public/particleman.h new file mode 100644 index 0000000..0f9b702 --- /dev/null +++ b/dep/hlsdk/public/particleman.h @@ -0,0 +1,101 @@ +#ifndef PARTICLEMAN_H +#define PARTICLEMAN_H + +#include "interface.h" +#include "pman_triangleffect.h" + +#define PARTICLEMAN_INTERFACE "create_particleman" + +#ifdef _WIN32 +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.dll" +#elif defined(OSX) +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.dylib" +#elif defined(LINUX) +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.so" +#else +#error +#endif + +class CBaseParticle; + +class IParticleMan : public IBaseInterface +{ + +protected: + virtual ~IParticleMan() {} + +public: + + virtual void SetUp( cl_enginefunc_t *pEnginefuncs ) = 0; + virtual void Update ( void ) = 0; + virtual void SetVariables ( float flGravity, Vector vViewAngles ) = 0; + virtual void ResetParticles ( void ) = 0; + virtual void ApplyForce ( Vector vOrigin, Vector vDirection, float flRadius, float flStrength, float flDuration ) = 0; + virtual void AddCustomParticleClassSize ( unsigned long lSize ) = 0; + + //Use this if you want to create a new particle without any overloaded functions, Think, Touch, etc. + //Just call this function, set the particle's behavior and let it rip. + virtual CBaseParticle *CreateParticle( Vector org, Vector normal, model_s * sprite, float size, float brightness, const char *classname ) = 0; + + //Use this to take a block from the mempool for custom particles ( used in new ). + virtual char *RequestNewMemBlock( int iSize ) = 0; + + //These ones are used along a custom Create for new particles you want to override their behavior. + //You can call these whenever you want, but they are mainly used by CBaseParticle. + virtual void CoreInitializeSprite ( CCoreTriangleEffect *pParticle, Vector org, Vector normal, model_s *sprite, float size, float brightness ) = 0; //Only use this for TrianglePlanes + virtual void CoreThink( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreDraw( CCoreTriangleEffect *pParticle ) = 0; + virtual void CoreAnimate( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreAnimateAndDie( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreExpand ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreContract ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreFade ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreSpin ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreCalculateVelocity( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreCheckCollision( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreTouch ( CCoreTriangleEffect *pParticle, Vector pos, Vector normal, int index ) = 0; + virtual void CoreDie ( CCoreTriangleEffect *pParticle ) = 0; + virtual void CoreForce ( CCoreTriangleEffect *pParticle ) = 0; + virtual bool CoreCheckVisibility ( CCoreTriangleEffect *pParticle ) = 0; + virtual void SetRender( int iRender ) = 0; +}; + +extern IParticleMan *g_pParticleMan; + +class CBaseParticle : public CCoreTriangleEffect +{ +public: + virtual void Think( float time ){ g_pParticleMan->CoreThink( this, time ); } + virtual void Draw( void ) { g_pParticleMan->CoreDraw( this ); } + virtual void Animate( float time ) { g_pParticleMan->CoreAnimate( this, time ); } + virtual void AnimateAndDie( float time ) { g_pParticleMan->CoreAnimateAndDie( this, time ); } + virtual void Expand( float time ) { g_pParticleMan->CoreExpand( this, time ); } + virtual void Contract( float time ) { g_pParticleMan->CoreContract( this, time ); } + virtual void Fade( float time ) { g_pParticleMan->CoreFade( this, time ); } + virtual void Spin( float time ) { g_pParticleMan->CoreSpin( this, time ); } + virtual void CalculateVelocity( float time ) { g_pParticleMan->CoreCalculateVelocity( this, time ); } + virtual void CheckCollision( float time ) { g_pParticleMan->CoreCheckCollision( this, time ); } + virtual void Touch(Vector pos, Vector normal, int index) { g_pParticleMan->CoreTouch( this, pos, normal, index ); } + virtual void Die ( void ) { g_pParticleMan->CoreDie( this ); } + virtual void Force ( void ) { g_pParticleMan->CoreForce( this ); } + virtual bool CheckVisibility ( void ) { return g_pParticleMan->CoreCheckVisibility( this ); } + + virtual void InitializeSprite( Vector org, Vector normal, model_s *sprite, float size, float brightness ) + { + g_pParticleMan->CoreInitializeSprite ( this, org, normal, sprite, size, brightness ); + } + + void * operator new( size_t size ) //this asks for a new block of memory from the MiniMem class + { + return( g_pParticleMan->RequestNewMemBlock( size ) ); + } +#ifdef POSIX + void * operator new( size_t size, const std::nothrow_t&) throw() //this asks for a new block of memory from the MiniMem class + { + return( g_pParticleMan->RequestNewMemBlock( size ) ); + } +#endif +}; + + +#endif //PARTICLEMAN_H diff --git a/dep/hlsdk/public/pman_particlemem.h b/dep/hlsdk/public/pman_particlemem.h new file mode 100644 index 0000000..e2a03fc --- /dev/null +++ b/dep/hlsdk/public/pman_particlemem.h @@ -0,0 +1,197 @@ +#ifndef PARTICLEMEM_H__ +#define PARTICLEMEM_H__ + +#ifdef _WIN32 +#pragma once +#endif + +#include + +class CCoreTriangleEffect; + +#define TRIANGLE_FPS 30 + +typedef struct visibleparticles_s +{ + CCoreTriangleEffect *pVisibleParticle; +} visibleparticles_t; + +//--------------------------------------------------------------------------- +// Memory block record. +class MemoryBlock +{ +private: + char *m_pData; + //bool m_bBlockIsInUse; +public: + MemoryBlock(long lBlockSize) + : next(NULL), prev(NULL) + //m_bBlockIsInUse(false) // Initialize block to 'free' state. + { + // Allocate memory here. + m_pData = new char[lBlockSize]; + } + + virtual ~MemoryBlock() + { + // Free memory. + delete[] m_pData; + } + + inline char *Memory(void) { return m_pData; } + + MemoryBlock * next; + MemoryBlock * prev; +}; + +class MemList +{ +public: + MemList() : m_pHead(NULL) {} + + ~MemList() { Reset(); } + + void Push(MemoryBlock * newItem) + { + if(!m_pHead) + { + m_pHead = newItem; + newItem->next = NULL; + newItem->prev = NULL; + return; + } + + MemoryBlock * temp = m_pHead; + m_pHead = newItem; + m_pHead->next = temp; + m_pHead->prev = NULL; + + temp->prev = m_pHead; + } + + + MemoryBlock * Front( void ) + { + return(m_pHead); + } + + MemoryBlock * Pop( void ) + { + if(!m_pHead) + return(NULL); + + MemoryBlock * temp = m_pHead; + + m_pHead = m_pHead->next; + + if(m_pHead) + m_pHead->prev = NULL; + + temp->next = NULL; + temp->prev = NULL; + + return(temp); + } + + void Delete( MemoryBlock * pItem) + { + + if(m_pHead == pItem) + { + MemoryBlock * temp = m_pHead; + + m_pHead = m_pHead->next; + if(m_pHead) + m_pHead->prev = NULL; + + temp->next = NULL; + temp->prev = NULL; + return; + } + + MemoryBlock * prev = pItem->prev; + MemoryBlock * next = pItem->next; + + if(prev) + prev->next = next; + + if(next) + next->prev = prev; + + pItem->next = NULL; + pItem->prev = NULL; + } + + void Reset( void ) + { + while(m_pHead) + Delete(m_pHead); + } + +private: + MemoryBlock * m_pHead; +}; + + +// Some helpful typedefs. +typedef std::vector VectorOfMemoryBlocks; +typedef VectorOfMemoryBlocks::iterator MemoryBlockIterator; + +// Mini memory manager - singleton. +class CMiniMem +{ +private: + // Main memory pool. Array is fine, but vectors are + // easier. :) + static VectorOfMemoryBlocks m_vecMemoryPool; + // Size of memory blocks in pool. + static long m_lMemoryBlockSize; + static long m_lMaxBlocks; + static long m_lMemoryPoolSize; + static CMiniMem *_instance; + + int m_iTotalParticles; + int m_iParticlesDrawn; + +protected: + // private constructor and destructor. + CMiniMem(long lMemoryPoolSize, long lMaxBlockSize); + virtual ~CMiniMem(); + + // ------------ Memory pool manager calls. + // Find a free block and mark it as "in use". Return NULL + // if no free blocks found. + char *AllocateFreeBlock(void); +public: + + // Return a pointer to usable block of memory. + char *newBlock(void); + + // Mark a target memory item as no longer "in use". + void deleteBlock(MemoryBlock *p); + + // Return the remaining capacity of the memory pool as a percent. + long PercentUsed(void); + + void ProcessAll( void ); //Processes all + + void Reset( void ); //clears memory, setting all particles to not used. + + static int ApplyForce( Vector vOrigin, Vector vDirection, float flRadius, float flStrength ); + + static CMiniMem *Instance(void); + static long MaxBlockSize(void); + + bool CheckSize( int iSize ); + + int GetTotalParticles( void ) { return m_iTotalParticles; } + int GetDrawnParticles( void ) { return m_iParticlesDrawn; } + void IncreaseParticlesDrawn( void ){ m_iParticlesDrawn++; } + + void Shutdown( void ); + + visibleparticles_t *m_pVisibleParticles; +}; + + +#endif//PARTICLEMEM_H__ diff --git a/dep/hlsdk/public/pman_triangleffect.h b/dep/hlsdk/public/pman_triangleffect.h new file mode 100644 index 0000000..6af4c2b --- /dev/null +++ b/dep/hlsdk/public/pman_triangleffect.h @@ -0,0 +1,209 @@ +#ifndef TRIANGLEEFFECT_H__ +#define TRIANGLEEFFECT_H__ + +#ifdef _WIN32 +#pragma once +#endif + +#define TRI_COLLIDEWORLD 0x00000020 +#define TRI_COLLIDEALL 0x00001000 // will collide with world and slideboxes +#define TRI_COLLIDEKILL 0x00004000 // tent is removed upon collision with anything +#define TRI_SPIRAL 0x00008000 +#define TRI_ANIMATEDIE 0x00016000 //animate once and then die +#define TRI_WATERTRACE 0x00032000 + + +#define CULL_FRUSTUM_POINT ( 1 << 0 ) +#define CULL_FRUSTUM_SPHERE ( 1 << 1 ) +#define CULL_FRUSTUM_PLANE ( 1 << 2 ) +#define CULL_PVS ( 1 << 3 ) + +#define LIGHT_NONE ( 1 << 4 ) +#define LIGHT_COLOR ( 1 << 5 ) +#define LIGHT_INTENSITY ( 1 << 6 ) + +#define RENDER_FACEPLAYER ( 1 << 7 ) // m_vAngles == Player view angles +#define RENDER_FACEPLAYER_ROTATEZ ( 1 << 8 ) //Just like above but m_vAngles.z is untouched so the sprite can rotate. + + +#include "pman_particlemem.h" + +//pure virtual baseclass +class CCoreTriangleEffect +{ +private: + int m_iRenderFlags; + float m_flNextPVSCheck; + bool m_bInPVS; + + int m_iCollisionFlags; + float m_flPlayerDistance; //Used for sorting the particles, DO NOT TOUCH. + +public: + + void * operator new(size_t size) + { + // Requested size should match size of class. + if ( size != sizeof( CCoreTriangleEffect ) ) +#ifdef _WIN32 + throw "Error in requested size of new particle class instance."; +#else + return NULL; +#endif + + return((CCoreTriangleEffect *) CMiniMem::Instance()->newBlock()); + + }//this asks for a new block of memory from the MiniMen class + + virtual void Think( float time ) = 0; + virtual bool CheckVisibility ( void ) = 0; + virtual void Draw( void ) = 0; + virtual void Animate( float time ) = 0; + virtual void AnimateAndDie( float time ) = 0; + virtual void Expand( float time ) = 0; + virtual void Contract( float time ) = 0; + virtual void Fade( float time ) = 0; + virtual void Spin( float time ) = 0; + virtual void CalculateVelocity( float time ) = 0; + virtual void CheckCollision( float time ) = 0; + virtual void Touch(Vector pos, Vector normal, int index) = 0; + virtual void Die ( void ) = 0; + virtual void InitializeSprite( Vector org, Vector normal, model_s * sprite, float size, float brightness ) = 0; + virtual void Force ( void ) = 0; + + float m_flSize; //scale of object + float m_flScaleSpeed; //speed at which object expands + float m_flContractSpeed; //speed at which object expands + + float m_flStretchX; + float m_flStretchY; + + float m_flBrightness; //transparency of object + float m_flFadeSpeed; //speed at which object fades + + float m_flTimeCreated; //time object was instanced + float m_flDieTime; //time to remove an object + + float m_flGravity; //how effected by gravity is this object + float m_flAfterDampGrav; + float m_flDampingVelocity; + float m_flDampingTime; + + int m_iFramerate; + int m_iNumFrames; + int m_iFrame; + int m_iRendermode; + + Vector m_vOrigin; //object's position + Vector m_vAngles; //normal angles of object + + Vector m_vAVelocity; + + Vector m_vVelocity; + + Vector m_vLowLeft; + Vector m_vLowRight; + Vector m_vTopLeft; + + Vector m_vColor; + float m_flMass; + + model_s * m_pTexture; + + float m_flBounceFactor; + + char m_szClassname[32]; + + bool m_bInWater; + bool m_bAffectedByForce; + + int m_iAfterDampFlags; + + void SetLightFlag ( int iFlag ) + { + m_iRenderFlags &= ~( LIGHT_NONE | LIGHT_INTENSITY | LIGHT_COLOR ); + m_iRenderFlags |= iFlag; + } + + void SetCullFlag( int iFlag ) + { + m_iRenderFlags &= ~( CULL_PVS | CULL_FRUSTUM_POINT | CULL_FRUSTUM_PLANE | CULL_FRUSTUM_SPHERE ); + m_iRenderFlags |= iFlag; + } + + int GetRenderFlags( void ) + { + return m_iRenderFlags; + } + + bool GetParticlePVS ( void ) + { + return m_bInPVS; + } + + void SetParticlePVS ( bool bPVSStat ) + { + m_bInPVS = bPVSStat; + } + + float GetNextPVSCheck( void ) + { + return m_flNextPVSCheck; + } + + void SetNextPVSCheck( float flTime ) + { + m_flNextPVSCheck = flTime; + } + + void SetCollisionFlags ( int iFlag ) + { + m_iCollisionFlags |= iFlag; + } + + void ClearCollisionFlags ( int iFlag ) + { + m_iCollisionFlags &= ~iFlag; + } + + int GetCollisionFlags ( void ) + { + return m_iCollisionFlags; + } + + void SetRenderFlag( int iFlag ) + { + m_iRenderFlags |= iFlag; + } + + float GetPlayerDistance ( void ) { return m_flPlayerDistance; } + void SetPlayerDistance ( float flDistance ) { m_flPlayerDistance = flDistance; } + +protected: + float m_flOriginalSize; + Vector m_vOriginalAngles; + float m_flOriginalBrightness; + Vector m_vPrevOrigin; + + float m_flNextCollisionTime; + +protected: + static bool CheckSize(int size) + { + // This check will help prevent a class frome being defined later, + // that is larger than the max size MemoryPool is expecting, + // from being successfully allocated. + if (size > (unsigned long) CMiniMem::Instance()->MaxBlockSize()) + { +#ifdef _WIN32 + throw "New particle class is larger than memory pool max size, update lMaxParticleClassSize() function."; +#endif + return(false); + } + + return(true); + } +}; + + +#endif//TRIANGLEEFFECT_H__ diff --git a/dep/hlsdk/public/registry.cpp b/dep/hlsdk/public/registry.cpp new file mode 100644 index 0000000..96c2c91 --- /dev/null +++ b/dep/hlsdk/public/registry.cpp @@ -0,0 +1,254 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#ifndef _WIN32 +typedef int HKEY; +#endif + +// Exposes registry interface to rest of launcher +class CRegistry: public IRegistry +{ +public: + CRegistry(); + virtual ~CRegistry(); + + void Init(); + void Shutdown(); + + int ReadInt(const char *key, int defaultValue = 0); + void WriteInt(const char *key, int value); + + const char *ReadString(const char *key, const char *defaultValue = nullptr); + void WriteString(const char *key, const char *value); + +private: + bool m_bValid; + HKEY m_hKey; +}; + +// Expose to launcher +static CRegistry g_Registry; +IRegistry *registry = &g_Registry; + +CRegistry::CRegistry() +{ + // Assume failure + m_bValid = false; + m_hKey = 0; +} + +CRegistry::~CRegistry() +{ +} + +// Purpose: Read integer from registry +// Input : *key - +// defaultValue - +// Output : int +int CRegistry::ReadInt(const char *key, int defaultValue) +{ +#ifdef _WIN32 + LONG lResult; // Registry function result code + DWORD dwType; // Type of key + DWORD dwSize; // Size of element data + + int value; + + if (!m_bValid) + { + return defaultValue; + } + + dwSize = sizeof(DWORD); + + lResult = RegQueryValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + &dwType, // type buffer + (LPBYTE)&value, // data buffer + &dwSize); // size of data buffer + + if (lResult != ERROR_SUCCESS) // Failure + return defaultValue; + + if (dwType != REG_DWORD) + return defaultValue; + + return value; +#else + return defaultValue; +#endif +} + +// Purpose: Save integer to registry +// Input : *key - +// value - +void CRegistry::WriteInt(const char *key, int value) +{ +#ifdef _WIN32 + // Size of element data + DWORD dwSize; + + if (!m_bValid) + { + return; + } + + dwSize = sizeof(DWORD); + + RegSetValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + REG_DWORD, // type buffer + (LPBYTE)&value, // data buffer + dwSize); // size of data buffer +#endif +} + +// Purpose: Read string value from registry +// Input : *key - +// *defaultValue - +// Output : const char +const char *CRegistry::ReadString(const char *key, const char *defaultValue) +{ +#ifdef _WIN32 + LONG lResult; // Type of key + DWORD dwType; // Size of element data + DWORD dwSize = 512; + + static char value[512]; + + value[0] = 0; + + if (!m_bValid) + { + return defaultValue; + } + + lResult = RegQueryValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + &dwType, // type buffer + (unsigned char *)value, // data buffer + &dwSize); // size of data buffer + + if (lResult != ERROR_SUCCESS) + { + return defaultValue; + } + + if (dwType != REG_SZ) + { + return defaultValue; + } + + return value; +#else + return defaultValue; +#endif +} + +// Purpose: Save string to registry +// Input : *key - +// *value - +void CRegistry::WriteString(const char *key, const char *value) +{ +#ifdef _WIN32 + DWORD dwSize; // Size of element data + + if (!m_bValid) + { + return; + } + + dwSize = strlen(value) + 1; + + RegSetValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + REG_SZ, // type buffer + (LPBYTE)value, // data buffer + dwSize); // size of data buffer +#endif +} + +// FIXME: SHould be "steam" +static char *GetPlatformName() +{ + return "Half-Life"; +} + +// Purpose: Open default launcher key based on game directory +void CRegistry::Init() +{ +#ifdef _WIN32 + LONG lResult; // Registry function result code + DWORD dwDisposition; // Type of key opening event + + char szModelKey[1024]; + wsprintf(szModelKey, "Software\\Valve\\%s\\Settings\\", GetPlatformName()); + + lResult = RegCreateKeyEx( + HKEY_CURRENT_USER, // handle of open key + szModelKey, // address of name of subkey to open + 0, // DWORD ulOptions, // reserved + NULL, // Type of value + REG_OPTION_NON_VOLATILE, // Store permanently in reg. + KEY_ALL_ACCESS, // REGSAM samDesired, // security access mask + NULL, + &m_hKey, // Key we are creating + &dwDisposition); // Type of creation + + if (lResult != ERROR_SUCCESS) + { + m_bValid = false; + return; + } + + // Success + m_bValid = true; +#endif +} + +void CRegistry::Shutdown() +{ +#ifdef _WIN32 + if (!m_bValid) + return; + + // Make invalid + m_bValid = false; + RegCloseKey(m_hKey); +#endif +} diff --git a/dep/hlsdk/public/savegame_version.h b/dep/hlsdk/public/savegame_version.h new file mode 100644 index 0000000..f14564d --- /dev/null +++ b/dep/hlsdk/public/savegame_version.h @@ -0,0 +1,35 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "commonmacros.h" + +#define SAVEFILE_HEADER MAKEID('V','A','L','V') // little-endian "VALV" +#define SAVEGAME_HEADER MAKEID('J','S','A','V') // little-endian "JSAV" +#define SAVEGAME_VERSION 0x0071 // Version 0.71 diff --git a/dep/hlsdk/public/steam/isteamapps.h b/dep/hlsdk/public/steam/isteamapps.h new file mode 100644 index 0000000..7021a35 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamapps.h @@ -0,0 +1,127 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to app data in Steam +// +//============================================================================= + +#ifndef ISTEAMAPPS_H +#define ISTEAMAPPS_H +#ifdef _WIN32 +#pragma once +#endif + +const int k_cubAppProofOfPurchaseKeyMax = 64; // max bytes of a legacy cd key we support + + +//----------------------------------------------------------------------------- +// Purpose: interface to app data +//----------------------------------------------------------------------------- +class ISteamApps +{ +public: + virtual bool BIsSubscribed() = 0; + virtual bool BIsLowViolence() = 0; + virtual bool BIsCybercafe() = 0; + virtual bool BIsVACBanned() = 0; + virtual const char *GetCurrentGameLanguage() = 0; + virtual const char *GetAvailableGameLanguages() = 0; + + // only use this member if you need to check ownership of another game related to yours, a demo for example + virtual bool BIsSubscribedApp( AppId_t appID ) = 0; + + // Takes AppID of DLC and checks if the user owns the DLC & if the DLC is installed + virtual bool BIsDlcInstalled( AppId_t appID ) = 0; + + // returns the Unix time of the purchase of the app + virtual uint32 GetEarliestPurchaseUnixTime( AppId_t nAppID ) = 0; + + // Checks if the user is subscribed to the current app through a free weekend + // This function will return false for users who have a retail or other type of license + // Before using, please ask your Valve technical contact how to package and secure your free weekened + virtual bool BIsSubscribedFromFreeWeekend() = 0; + + // Returns the number of DLC pieces for the running app + virtual int GetDLCCount() = 0; + + // Returns metadata for DLC by index, of range [0, GetDLCCount()] + virtual bool BGetDLCDataByIndex( int iDLC, AppId_t *pAppID, bool *pbAvailable, char *pchName, int cchNameBufferSize ) = 0; + + // Install/Uninstall control for optional DLC + virtual void InstallDLC( AppId_t nAppID ) = 0; + virtual void UninstallDLC( AppId_t nAppID ) = 0; + + // Request cd-key for yourself or owned DLC. If you are interested in this + // data then make sure you provide us with a list of valid keys to be distributed + // to users when they purchase the game, before the game ships. + // You'll receive an AppProofOfPurchaseKeyResponse_t callback when + // the key is available (which may be immediately). + virtual void RequestAppProofOfPurchaseKey( AppId_t nAppID ) = 0; + + virtual bool GetCurrentBetaName( char *pchName, int cchNameBufferSize ) = 0; // returns current beta branch name, 'public' is the default branch + virtual bool MarkContentCorrupt( bool bMissingFilesOnly ) = 0; // signal Steam that game files seems corrupt or missing + virtual uint32 GetInstalledDepots( DepotId_t *pvecDepots, uint32 cMaxDepots ) = 0; // return installed depots in mount order + + // returns current app install folder for AppID, returns folder name length + virtual uint32 GetAppInstallDir( AppId_t appID, char *pchFolder, uint32 cchFolderBufferSize ) = 0; + +#ifdef _PS3 + // Result returned in a RegisterActivationCodeResponse_t callresult + virtual SteamAPICall_t RegisterActivationCode( const char *pchActivationCode ) = 0; +#endif +}; + +#define STEAMAPPS_INTERFACE_VERSION "STEAMAPPS_INTERFACE_VERSION005" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +//----------------------------------------------------------------------------- +// Purpose: posted after the user gains ownership of DLC & that DLC is installed +//----------------------------------------------------------------------------- +struct DlcInstalled_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 5 }; + AppId_t m_nAppID; // AppID of the DLC +}; + + +//----------------------------------------------------------------------------- +// Purpose: possible results when registering an activation code +//----------------------------------------------------------------------------- +enum ERegisterActivationCodeResult +{ + k_ERegisterActivationCodeResultOK = 0, + k_ERegisterActivationCodeResultFail = 1, + k_ERegisterActivationCodeResultAlreadyRegistered = 2, + k_ERegisterActivationCodeResultTimeout = 3, + k_ERegisterActivationCodeAlreadyOwned = 4, +}; + + +//----------------------------------------------------------------------------- +// Purpose: response to RegisterActivationCode() +//----------------------------------------------------------------------------- +struct RegisterActivationCodeResponse_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 8 }; + ERegisterActivationCodeResult m_eResult; + uint32 m_unPackageRegistered; // package that was registered. Only set on success +}; + +//----------------------------------------------------------------------------- +// Purpose: response to RegisterActivationCode() +//----------------------------------------------------------------------------- +struct AppProofOfPurchaseKeyResponse_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 13 }; + EResult m_eResult; + uint32 m_nAppID; + char m_rgchKey[ k_cubAppProofOfPurchaseKeyMax ]; +}; +#pragma pack( pop ) +#endif // ISTEAMAPPS_H diff --git a/dep/hlsdk/public/steam/isteambilling.h b/dep/hlsdk/public/steam/isteambilling.h new file mode 100644 index 0000000..7bf63b8 --- /dev/null +++ b/dep/hlsdk/public/steam/isteambilling.h @@ -0,0 +1,108 @@ +//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= +// +// Purpose: interface to Billings data in Steam +// +//============================================================================= + +#ifndef ISTEAMBILLING_H +#define ISTEAMBILLING_H +#ifdef _WIN32 +#pragma once +#endif + +//----------------------------------------------------------------------------- +// Purpose: interface to billing +//----------------------------------------------------------------------------- +class ISteamBilling +{ +public: + // Sets the billing address in the ISteamBilling object for use by other ISteamBilling functions (not stored on server) + virtual bool SetBillingAddress( const char *pchName, + const char *pchAddress1, + const char *pchAddress2, + const char *pchCity, + const char *pchPostcode, + const char *pchState, + const char *pchCountry, + const char *pchPhone ) = 0; + // Gets any previous set billing address in the ISteamBilling object (not stored on server) + virtual bool GetBillingAddress( char *pchName, + char *pchAddress1, + char *pchAddress2, + char *pchCity, + char *pchPostcode, + char *pchState, + char *pchCountry, + char *pchPhone ) = 0; + // Sets the billing address in the ISteamBilling object for use by other ISteamBilling functions (not stored on server) + virtual bool SetShippingAddress( const char *pchName, + const char *pchAddress1, + const char *pchAddress2, + const char *pchCity, + const char *pchPostcode, + const char *pchState, + const char *pchCountry, + const char *pchPhone ) = 0; + // Gets any previous set billing address in the ISteamBilling object (not stored on server) + virtual bool GetShippingAddress( char *pchName, + char *pchAddress1, + char *pchAddress2, + char *pchCity, + char *pchPostcode, + char *pchState, + char *pchCountry, + char *pchPhone ) = 0; + // Ask the server for the final price of package: requires that ISteamBilling billing & shipping address are set (can be same) + virtual bool GetFinalPrice( int32 nPackageID ) = 0; + + // Sets the credit card info in the ISteamBilling object for use by other ISteamBilling functions (may eventually also be stored on server) + virtual bool SetCardInfo( int32 eCreditCardType, + const char *pchCardNumber, + const char *pchCardHolderName, + const char *pchCardExpYear, + const char *pchCardExpMonth, + const char *pchCardCVV2 ) = 0; + // Gets any credit card info in the ISteamBilling object (not stored on server) + virtual bool GetCardInfo( int32 *eCreditCardType, + char *pchCardNumber, + char *pchCardHolderName, + char *pchCardExpYear, + char *pchCardExpMonth, + char *pchCardCVV2 ) = 0; + + // Ask the server to purchase a package: requires that ISteamBilling cardinfo, billing & shipping address are set + virtual bool Purchase( int32 nPackageID, + int32 nExpectedCostCents, + uint64 gidCardID, // if non-NIL, use a server stored card + bool bStoreCardInfo ) = 0; // Should this cardinfo also be stored on the server +}; + + +#define STEAMBILLING_INTERFACE_VERSION "SteamBilling001" + + +enum { k_iSteamBillingCallbacks = 400 }; + +//----------------------------------------------------------------------------- +// Purpose: called when this client has received a finalprice message from a Billing +//----------------------------------------------------------------------------- +struct FinalPriceMsg_t +{ + enum { k_iCallback = k_iSteamBillingCallbacks + 1 }; + + uint32 m_bSuccess; + uint32 m_nBaseCost; + uint32 m_nTotalDiscount; + uint32 m_nTax; + uint32 m_nShippingCost; +}; + +struct PurchaseMsg_t +{ + enum { k_iCallback = k_iSteamBillingCallbacks + 2 }; + + uint32 m_bSuccess; + int32 m_EPurchaseResultDetail; // Detailed result information +}; + +#endif // ISTEAMBILLING_H diff --git a/dep/hlsdk/public/steam/isteamclient.h b/dep/hlsdk/public/steam/isteamclient.h new file mode 100644 index 0000000..43a2076 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamclient.h @@ -0,0 +1,349 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: Main interface for loading and accessing Steamworks API's from the +// Steam client. +// For most uses, this code is wrapped inside of SteamAPI_Init() +//============================================================================= + +#ifndef ISTEAMCLIENT_H +#define ISTEAMCLIENT_H +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" + +// Define compile time assert macros to let us validate the structure sizes. +#define VALVE_COMPILE_TIME_ASSERT( pred ) typedef char compile_time_assert_type[(pred) ? 1 : -1]; + +#if defined(__linux__) || defined(__APPLE__) +// The 32-bit version of gcc has the alignment requirement for uint64 and double set to +// 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. +// The 64-bit version of gcc has the alignment requirement for these types set to +// 8 meaning that unless we use #pragma pack(4) our structures will get bigger. +// The 64-bit structure packing has to match the 32-bit structure packing for each platform. +#define VALVE_CALLBACK_PACK_SMALL +#else +#define VALVE_CALLBACK_PACK_LARGE +#endif + +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error ??? +#endif + +typedef struct +{ + uint32 m_u32; + uint64 m_u64; + uint16 m_u16; + double m_d; +} ValvePackingSentinel_t; + +#pragma pack( pop ) + + +#if defined(VALVE_CALLBACK_PACK_SMALL) +VALVE_COMPILE_TIME_ASSERT( sizeof(ValvePackingSentinel_t) == 24 ) +#elif defined(VALVE_CALLBACK_PACK_LARGE) +VALVE_COMPILE_TIME_ASSERT( sizeof(ValvePackingSentinel_t) == 32 ) +#else +#error ??? +#endif + + +// handle to a communication pipe to the Steam client +typedef int32 HSteamPipe; +// handle to single instance of a steam user +typedef int32 HSteamUser; +// function prototype +#if defined( POSIX ) +#define __cdecl +#endif +extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); + +#if defined( __SNC__ ) + #pragma diag_suppress=1700 // warning 1700: class "%s" has virtual functions but non-virtual destructor +#endif + +// interface predec +class ISteamUser; +class ISteamGameServer; +class ISteamFriends; +class ISteamUtils; +class ISteamMatchmaking; +class ISteamContentServer; +class ISteamMatchmakingServers; +class ISteamUserStats; +class ISteamApps; +class ISteamNetworking; +class ISteamRemoteStorage; +class ISteamScreenshots; +class ISteamGameServerStats; +class ISteamPS3OverlayRender; +class ISteamHTTP; +class ISteamUnifiedMessages; + +//----------------------------------------------------------------------------- +// Purpose: Interface to creating a new steam instance, or to +// connect to an existing steam instance, whether it's in a +// different process or is local. +// +// For most scenarios this is all handled automatically via SteamAPI_Init(). +// You'll only need to use these interfaces if you have a more complex versioning scheme, +// where you want to get different versions of the same interface in different dll's in your project. +//----------------------------------------------------------------------------- +class ISteamClient +{ +public: + // Creates a communication pipe to the Steam client + virtual HSteamPipe CreateSteamPipe() = 0; + + // Releases a previously created communications pipe + virtual bool BReleaseSteamPipe( HSteamPipe hSteamPipe ) = 0; + + // connects to an existing global user, failing if none exists + // used by the game to coordinate with the steamUI + virtual HSteamUser ConnectToGlobalUser( HSteamPipe hSteamPipe ) = 0; + + // used by game servers, create a steam user that won't be shared with anyone else + virtual HSteamUser CreateLocalUser( HSteamPipe *phSteamPipe, EAccountType eAccountType ) = 0; + + // removes an allocated user + virtual void ReleaseUser( HSteamPipe hSteamPipe, HSteamUser hUser ) = 0; + + // retrieves the ISteamUser interface associated with the handle + virtual ISteamUser *GetISteamUser( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // retrieves the ISteamGameServer interface associated with the handle + virtual ISteamGameServer *GetISteamGameServer( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // set the local IP and Port to bind to + // this must be set before CreateLocalUser() + virtual void SetLocalIPBinding( uint32 unIP, uint16 usPort ) = 0; + + // returns the ISteamFriends interface + virtual ISteamFriends *GetISteamFriends( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamUtils interface + virtual ISteamUtils *GetISteamUtils( HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamMatchmaking interface + virtual ISteamMatchmaking *GetISteamMatchmaking( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamMatchmakingServers interface + virtual ISteamMatchmakingServers *GetISteamMatchmakingServers( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the a generic interface + virtual void *GetISteamGenericInterface( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamUserStats interface + virtual ISteamUserStats *GetISteamUserStats( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamGameServerStats interface + virtual ISteamGameServerStats *GetISteamGameServerStats( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns apps interface + virtual ISteamApps *GetISteamApps( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // networking + virtual ISteamNetworking *GetISteamNetworking( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // remote storage + virtual ISteamRemoteStorage *GetISteamRemoteStorage( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // user screenshots + virtual ISteamScreenshots *GetISteamScreenshots( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + + // this needs to be called every frame to process matchmaking results + // redundant if you're already calling SteamAPI_RunCallbacks() + virtual void RunFrame() = 0; + + // returns the number of IPC calls made since the last time this function was called + // Used for perf debugging so you can understand how many IPC calls your game makes per frame + // Every IPC call is at minimum a thread context switch if not a process one so you want to rate + // control how often you do them. + virtual uint32 GetIPCCallCount() = 0; + + // API warning handling + // 'int' is the severity; 0 for msg, 1 for warning + // 'const char *' is the text of the message + // callbacks will occur directly after the API function is called that generated the warning or message + virtual void SetWarningMessageHook( SteamAPIWarningMessageHook_t pFunction ) = 0; + + // Trigger global shutdown for the DLL + virtual bool BShutdownIfAllPipesClosed() = 0; + +#ifdef _PS3 + virtual ISteamPS3OverlayRender *GetISteamPS3OverlayRender() = 0; +#endif + + // Expose HTTP interface + virtual ISteamHTTP *GetISteamHTTP( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // Exposes the ISteamUnifiedMessages interface + virtual ISteamUnifiedMessages *GetISteamUnifiedMessages( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + +}; + +#define STEAMCLIENT_INTERFACE_VERSION "SteamClient012" + +//----------------------------------------------------------------------------- +// Purpose: Base values for callback identifiers, each callback must +// have a unique ID. +//----------------------------------------------------------------------------- +enum { k_iSteamUserCallbacks = 100 }; +enum { k_iSteamGameServerCallbacks = 200 }; +enum { k_iSteamFriendsCallbacks = 300 }; +enum { k_iSteamBillingCallbacks = 400 }; +enum { k_iSteamMatchmakingCallbacks = 500 }; +enum { k_iSteamContentServerCallbacks = 600 }; +enum { k_iSteamUtilsCallbacks = 700 }; +enum { k_iClientFriendsCallbacks = 800 }; +enum { k_iClientUserCallbacks = 900 }; +enum { k_iSteamAppsCallbacks = 1000 }; +enum { k_iSteamUserStatsCallbacks = 1100 }; +enum { k_iSteamNetworkingCallbacks = 1200 }; +enum { k_iClientRemoteStorageCallbacks = 1300 }; +enum { k_iSteamUserItemsCallbacks = 1400 }; +enum { k_iSteamGameServerItemsCallbacks = 1500 }; +enum { k_iClientUtilsCallbacks = 1600 }; +enum { k_iSteamGameCoordinatorCallbacks = 1700 }; +enum { k_iSteamGameServerStatsCallbacks = 1800 }; +enum { k_iSteam2AsyncCallbacks = 1900 }; +enum { k_iSteamGameStatsCallbacks = 2000 }; +enum { k_iClientHTTPCallbacks = 2100 }; +enum { k_iClientScreenshotsCallbacks = 2200 }; +enum { k_iSteamScreenshotsCallbacks = 2300 }; +enum { k_iClientAudioCallbacks = 2400 }; +enum { k_iClientUnifiedMessagesCallbacks = 2500 }; +enum { k_iSteamStreamLauncherCallbacks = 2600 }; +enum { k_iClientControllerCallbacks = 2700 }; +enum { k_iSteamControllerCallbacks = 2800 }; +enum { k_iClientParentalSettingsCallbacks = 2900 }; +enum { k_iClientDeviceAuthCallbacks = 3000 }; +enum { k_iClientNetworkDeviceManagerCallbacks = 3100 }; + + +//----------------------------------------------------------------------------- +// The CALLBACK macros are for client side callback logging enabled with +// log_callback +// Do not change any of these. +//----------------------------------------------------------------------------- + +class CSteamCallback +{ +public: + virtual const char *GetCallbackName() const = 0; + virtual uint32 GetCallbackID() const = 0; + virtual uint8 *GetFixedData() const = 0; + virtual uint32 GetFixedSize() const = 0; + virtual uint32 GetNumMemberVariables() const = 0; + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const = 0; +}; + +#define DEFINE_CALLBACK( callbackname, callbackid ) \ +struct callbackname##_t { \ + enum { k_iCallback = callbackid }; \ + static callbackname##_t *GetNullPointer() { return 0; } + +#define CALLBACK_MEMBER( varidx, vartype, varname ) \ + public: vartype varname ; \ + static void GetMemberVar_##varidx( unsigned int &varOffset, unsigned int &varSize, uint32 &varCount, const char **pszName, const char **pszType ) { \ + varOffset = (unsigned int)(size_t)&GetNullPointer()->varname; \ + varSize = sizeof( vartype ); \ + varCount = 1; \ + *pszName = #varname; *pszType = #vartype; } + +#define CALLBACK_ARRAY( varidx, vartype, varname, varcount ) \ + public: vartype varname [ varcount ]; \ + static void GetMemberVar_##varidx( unsigned int &varOffset, unsigned int &varSize, uint32 &varCount, const char **pszName, const char **pszType ) { \ + varOffset = (unsigned int)(size_t)&GetNullPointer()->varname[0]; \ + varSize = sizeof( vartype ); \ + varCount = varcount; \ + *pszName = #varname; *pszType = #vartype; } + + +#define END_CALLBACK_INTERNAL_BEGIN( callbackname, numvars ) }; \ +class C##callbackname : public CSteamCallback { \ +public: callbackname##_t m_Data; \ + C##callbackname () { memset( &m_Data, 0, sizeof(m_Data) ); } \ + virtual const char *GetCallbackName() const { return #callbackname; } \ + virtual uint32 GetCallbackID() const { return callbackname##_t::k_iCallback; } \ + virtual uint32 GetFixedSize() const { return sizeof( m_Data ); } \ + virtual uint8 *GetFixedData() const { return (uint8*)&m_Data; } \ + virtual uint32 GetNumMemberVariables() const { return numvars; } \ + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const { \ + switch ( index ) { default : return false; + + +#define END_CALLBACK_INTERNAL_SWITCH( varidx ) case varidx : m_Data.GetMemberVar_##varidx( varOffset, varSize, varCount, pszName, pszType ); return true; + +#define END_CALLBACK_INTERNAL_END() }; }; }; + +#define END_DEFINE_CALLBACK_0( callbackname ) }; \ +class C##callbackname : public CSteamCallback { \ +public: callbackname##_t m_Data; \ + virtual const char *GetCallbackName() const { return #callbackname; } \ + virtual uint32 GetCallbackID() const { return callbackname##_t::k_iCallback; } \ + virtual uint32 GetFixedSize() const { return sizeof( m_Data ); } \ + virtual uint8 *GetFixedData() const { return (uint8*)&m_Data; } \ + virtual uint32 GetNumMemberVariables() const { return 0; } \ + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const { return false; } \ + }; \ + + +#define END_DEFINE_CALLBACK_1( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_2( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_3( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_4( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_END() + + +#define END_DEFINE_CALLBACK_6( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 6 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 5 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_7( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 7 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 5 ) \ + END_CALLBACK_INTERNAL_SWITCH( 6 ) \ + END_CALLBACK_INTERNAL_END() + +#endif // ISTEAMCLIENT_H diff --git a/dep/hlsdk/public/steam/isteamcontroller.h b/dep/hlsdk/public/steam/isteamcontroller.h new file mode 100644 index 0000000..6975e56 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamcontroller.h @@ -0,0 +1,62 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to valve controller +// +//============================================================================= + +#ifndef ISTEAMCONTROLLER_H +#define ISTEAMCONTROLLER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + + +#pragma pack( pop ) + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing stats, achievements, and leaderboard information +//----------------------------------------------------------------------------- +class ISteamController +{ +public: + +}; + +#define STEAMCONTROLLER_INTERFACE_VERSION "STEAMCONTROLLER_INTERFACE_VERSION" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +/* +struct ControllerCallback_t +{ + enum { k_iCallback = k_iSteamControllerCallbacks + 1 }; + +}; +*/ + + +#pragma pack( pop ) + + +#endif // ISTEAMCONTROLLER_H diff --git a/dep/hlsdk/public/steam/isteamfriends.h b/dep/hlsdk/public/steam/isteamfriends.h new file mode 100644 index 0000000..fc0a8e7 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamfriends.h @@ -0,0 +1,606 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to both friends list data and general information about users +// +//============================================================================= + +#ifndef ISTEAMFRIENDS_H +#define ISTEAMFRIENDS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "steamclientpublic.h" + + +//----------------------------------------------------------------------------- +// Purpose: set of relationships to other users +//----------------------------------------------------------------------------- +enum EFriendRelationship +{ + k_EFriendRelationshipNone = 0, + k_EFriendRelationshipBlocked = 1, + k_EFriendRelationshipRequestRecipient = 2, + k_EFriendRelationshipFriend = 3, + k_EFriendRelationshipRequestInitiator = 4, + k_EFriendRelationshipIgnored = 5, + k_EFriendRelationshipIgnoredFriend = 6, + k_EFriendRelationshipSuggested = 7, + + // keep this updated + k_EFriendRelationshipMax = 8, +}; + +// maximum length of friend group name (not including terminating nul!) +const int k_cchMaxFriendsGroupName = 64; + +// maximum number of groups a single user is allowed +const int k_cFriendsGroupLimit = 100; + +const int k_cEnumerateFollowersMax = 50; + + +//----------------------------------------------------------------------------- +// Purpose: list of states a friend can be in +//----------------------------------------------------------------------------- +enum EPersonaState +{ + k_EPersonaStateOffline = 0, // friend is not currently logged on + k_EPersonaStateOnline = 1, // friend is logged on + k_EPersonaStateBusy = 2, // user is on, but busy + k_EPersonaStateAway = 3, // auto-away feature + k_EPersonaStateSnooze = 4, // auto-away for a long time + k_EPersonaStateLookingToTrade = 5, // Online, trading + k_EPersonaStateLookingToPlay = 6, // Online, wanting to play + k_EPersonaStateMax, +}; + + +//----------------------------------------------------------------------------- +// Purpose: flags for enumerating friends list, or quickly checking a the relationship between users +//----------------------------------------------------------------------------- +enum EFriendFlags +{ + k_EFriendFlagNone = 0x00, + k_EFriendFlagBlocked = 0x01, + k_EFriendFlagFriendshipRequested = 0x02, + k_EFriendFlagImmediate = 0x04, // "regular" friend + k_EFriendFlagClanMember = 0x08, + k_EFriendFlagOnGameServer = 0x10, + // k_EFriendFlagHasPlayedWith = 0x20, // not currently used + // k_EFriendFlagFriendOfFriend = 0x40, // not currently used + k_EFriendFlagRequestingFriendship = 0x80, + k_EFriendFlagRequestingInfo = 0x100, + k_EFriendFlagIgnored = 0x200, + k_EFriendFlagIgnoredFriend = 0x400, + k_EFriendFlagSuggested = 0x800, + k_EFriendFlagAll = 0xFFFF, +}; + + +// friend game played information +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct FriendGameInfo_t +{ + CGameID m_gameID; + uint32 m_unGameIP; + uint16 m_usGamePort; + uint16 m_usQueryPort; + CSteamID m_steamIDLobby; +}; +#pragma pack( pop ) + +// maximum number of characters in a user's name. Two flavors; one for UTF-8 and one for UTF-16. +// The UTF-8 version has to be very generous to accomodate characters that get large when encoded +// in UTF-8. +enum +{ + k_cchPersonaNameMax = 128, + k_cwchPersonaNameMax = 32, +}; + +//----------------------------------------------------------------------------- +// Purpose: user restriction flags +//----------------------------------------------------------------------------- +enum EUserRestriction +{ + k_nUserRestrictionNone = 0, // no known chat/content restriction + k_nUserRestrictionUnknown = 1, // we don't know yet (user offline) + k_nUserRestrictionAnyChat = 2, // user is not allowed to (or can't) send/recv any chat + k_nUserRestrictionVoiceChat = 4, // user is not allowed to (or can't) send/recv voice chat + k_nUserRestrictionGroupChat = 8, // user is not allowed to (or can't) send/recv group chat + k_nUserRestrictionRating = 16, // user is too young according to rating in current region + k_nUserRestrictionGameInvites = 32, // user cannot send or recv game invites (e.g. mobile) + k_nUserRestrictionTrading = 64, // user cannot participate in trading (console, mobile) +}; + +//----------------------------------------------------------------------------- +// Purpose: information about user sessions +//----------------------------------------------------------------------------- +struct FriendSessionStateInfo_t +{ + uint32 m_uiOnlineSessionInstances; + uint8 m_uiPublishedToFriendsSessionInstance; +}; + + + +// size limit on chat room or member metadata +const uint32 k_cubChatMetadataMax = 8192; + +// size limits on Rich Presence data +enum { k_cchMaxRichPresenceKeys = 20 }; +enum { k_cchMaxRichPresenceKeyLength = 64 }; +enum { k_cchMaxRichPresenceValueLength = 256 }; + +// These values are passed as parameters to the store +enum EOverlayToStoreFlag +{ + k_EOverlayToStoreFlag_None = 0, + k_EOverlayToStoreFlag_AddToCart = 1, + k_EOverlayToStoreFlag_AddToCartAndShow = 2, +}; + +//----------------------------------------------------------------------------- +// Purpose: interface to accessing information about individual users, +// that can be a friend, in a group, on a game server or in a lobby with the local user +//----------------------------------------------------------------------------- +class ISteamFriends +{ +public: + // returns the local players name - guaranteed to not be NULL. + // this is the same name as on the users community profile page + // this is stored in UTF-8 format + // like all the other interface functions that return a char *, it's important that this pointer is not saved + // off; it will eventually be free'd or re-allocated + virtual const char *GetPersonaName() = 0; + + // Sets the player name, stores it on the server and publishes the changes to all friends who are online. + // Changes take place locally immediately, and a PersonaStateChange_t is posted, presuming success. + // + // The final results are available through the return value SteamAPICall_t, using SetPersonaNameResponse_t. + // + // If the name change fails to happen on the server, then an additional global PersonaStateChange_t will be posted + // to change the name back, in addition to the SetPersonaNameResponse_t callback. + virtual SteamAPICall_t SetPersonaName( const char *pchPersonaName ) = 0; + + // gets the status of the current user + virtual EPersonaState GetPersonaState() = 0; + + // friend iteration + // takes a set of k_EFriendFlags, and returns the number of users the client knows about who meet that criteria + // then GetFriendByIndex() can then be used to return the id's of each of those users + virtual int GetFriendCount( int iFriendFlags ) = 0; + + // returns the steamID of a user + // iFriend is a index of range [0, GetFriendCount()) + // iFriendsFlags must be the same value as used in GetFriendCount() + // the returned CSteamID can then be used by all the functions below to access details about the user + virtual CSteamID GetFriendByIndex( int iFriend, int iFriendFlags ) = 0; + + // returns a relationship to a user + virtual EFriendRelationship GetFriendRelationship( CSteamID steamIDFriend ) = 0; + + // returns the current status of the specified user + // this will only be known by the local user if steamIDFriend is in their friends list; on the same game server; in a chat room or lobby; or in a small group with the local user + virtual EPersonaState GetFriendPersonaState( CSteamID steamIDFriend ) = 0; + + // returns the name another user - guaranteed to not be NULL. + // same rules as GetFriendPersonaState() apply as to whether or not the user knowns the name of the other user + // note that on first joining a lobby, chat room or game server the local user will not known the name of the other users automatically; that information will arrive asyncronously + // + virtual const char *GetFriendPersonaName( CSteamID steamIDFriend ) = 0; + + // returns true if the friend is actually in a game, and fills in pFriendGameInfo with an extra details + virtual bool GetFriendGamePlayed( CSteamID steamIDFriend, FriendGameInfo_t *pFriendGameInfo ) = 0; + // accesses old friends names - returns an empty string when their are no more items in the history + virtual const char *GetFriendPersonaNameHistory( CSteamID steamIDFriend, int iPersonaName ) = 0; + + // returns true if the specified user meets any of the criteria specified in iFriendFlags + // iFriendFlags can be the union (binary or, |) of one or more k_EFriendFlags values + virtual bool HasFriend( CSteamID steamIDFriend, int iFriendFlags ) = 0; + + // clan (group) iteration and access functions + virtual int GetClanCount() = 0; + virtual CSteamID GetClanByIndex( int iClan ) = 0; + virtual const char *GetClanName( CSteamID steamIDClan ) = 0; + virtual const char *GetClanTag( CSteamID steamIDClan ) = 0; + // returns the most recent information we have about what's happening in a clan + virtual bool GetClanActivityCounts( CSteamID steamIDClan, int *pnOnline, int *pnInGame, int *pnChatting ) = 0; + // for clans a user is a member of, they will have reasonably up-to-date information, but for others you'll have to download the info to have the latest + virtual SteamAPICall_t DownloadClanActivityCounts( CSteamID *psteamIDClans, int cClansToRequest ) = 0; + + // iterators for getting users in a chat room, lobby, game server or clan + // note that large clans that cannot be iterated by the local user + // note that the current user must be in a lobby to retrieve CSteamIDs of other users in that lobby + // steamIDSource can be the steamID of a group, game server, lobby or chat room + virtual int GetFriendCountFromSource( CSteamID steamIDSource ) = 0; + virtual CSteamID GetFriendFromSourceByIndex( CSteamID steamIDSource, int iFriend ) = 0; + + // returns true if the local user can see that steamIDUser is a member or in steamIDSource + virtual bool IsUserInSource( CSteamID steamIDUser, CSteamID steamIDSource ) = 0; + + // User is in a game pressing the talk button (will suppress the microphone for all voice comms from the Steam friends UI) + virtual void SetInGameVoiceSpeaking( CSteamID steamIDUser, bool bSpeaking ) = 0; + + // activates the game overlay, with an optional dialog to open + // valid options are "Friends", "Community", "Players", "Settings", "OfficialGameGroup", "Stats", "Achievements" + virtual void ActivateGameOverlay( const char *pchDialog ) = 0; + + // activates game overlay to a specific place + // valid options are + // "steamid" - opens the overlay web browser to the specified user or groups profile + // "chat" - opens a chat window to the specified user, or joins the group chat + // "jointrade" - opens a window to a Steam Trading session that was started with the ISteamEconomy/StartTrade Web API + // "stats" - opens the overlay web browser to the specified user's stats + // "achievements" - opens the overlay web browser to the specified user's achievements + // "friendadd" - opens the overlay in minimal mode prompting the user to add the target user as a friend + // "friendremove" - opens the overlay in minimal mode prompting the user to remove the target friend + // "friendrequestaccept" - opens the overlay in minimal mode prompting the user to accept an incoming friend invite + // "friendrequestignore" - opens the overlay in minimal mode prompting the user to ignore an incoming friend invite + virtual void ActivateGameOverlayToUser( const char *pchDialog, CSteamID steamID ) = 0; + + // activates game overlay web browser directly to the specified URL + // full address with protocol type is required, e.g. http://www.steamgames.com/ + virtual void ActivateGameOverlayToWebPage( const char *pchURL ) = 0; + + // activates game overlay to store page for app + virtual void ActivateGameOverlayToStore( AppId_t nAppID, EOverlayToStoreFlag eFlag ) = 0; + + // Mark a target user as 'played with'. This is a client-side only feature that requires that the calling user is + // in game + virtual void SetPlayedWith( CSteamID steamIDUserPlayedWith ) = 0; + + // activates game overlay to open the invite dialog. Invitations will be sent for the provided lobby. + virtual void ActivateGameOverlayInviteDialog( CSteamID steamIDLobby ) = 0; + + // gets the small (32x32) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + virtual int GetSmallFriendAvatar( CSteamID steamIDFriend ) = 0; + + // gets the medium (64x64) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + virtual int GetMediumFriendAvatar( CSteamID steamIDFriend ) = 0; + + // gets the large (184x184) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + // returns -1 if this image has yet to be loaded, in this case wait for a AvatarImageLoaded_t callback and then call this again + virtual int GetLargeFriendAvatar( CSteamID steamIDFriend ) = 0; + + // requests information about a user - persona name & avatar + // if bRequireNameOnly is set, then the avatar of a user isn't downloaded + // - it's a lot slower to download avatars and churns the local cache, so if you don't need avatars, don't request them + // if returns true, it means that data is being requested, and a PersonaStateChanged_t callback will be posted when it's retrieved + // if returns false, it means that we already have all the details about that user, and functions can be called immediately + virtual bool RequestUserInformation( CSteamID steamIDUser, bool bRequireNameOnly ) = 0; + + // requests information about a clan officer list + // when complete, data is returned in ClanOfficerListResponse_t call result + // this makes available the calls below + // you can only ask about clans that a user is a member of + // note that this won't download avatars automatically; if you get an officer, + // and no avatar image is available, call RequestUserInformation( steamID, false ) to download the avatar + virtual SteamAPICall_t RequestClanOfficerList( CSteamID steamIDClan ) = 0; + + // iteration of clan officers - can only be done when a RequestClanOfficerList() call has completed + + // returns the steamID of the clan owner + virtual CSteamID GetClanOwner( CSteamID steamIDClan ) = 0; + // returns the number of officers in a clan (including the owner) + virtual int GetClanOfficerCount( CSteamID steamIDClan ) = 0; + // returns the steamID of a clan officer, by index, of range [0,GetClanOfficerCount) + virtual CSteamID GetClanOfficerByIndex( CSteamID steamIDClan, int iOfficer ) = 0; + // if current user is chat restricted, he can't send or receive any text/voice chat messages. + // the user can't see custom avatars. But the user can be online and send/recv game invites. + // a chat restricted user can't add friends or join any groups. + virtual uint32 GetUserRestrictions() = 0; + + // Rich Presence data is automatically shared between friends who are in the same game + // Each user has a set of Key/Value pairs + // Up to 20 different keys can be set + // There are two magic keys: + // "status" - a UTF-8 string that will show up in the 'view game info' dialog in the Steam friends list + // "connect" - a UTF-8 string that contains the command-line for how a friend can connect to a game + // GetFriendRichPresence() returns an empty string "" if no value is set + // SetRichPresence() to a NULL or an empty string deletes the key + // You can iterate the current set of keys for a friend with GetFriendRichPresenceKeyCount() + // and GetFriendRichPresenceKeyByIndex() (typically only used for debugging) + virtual bool SetRichPresence( const char *pchKey, const char *pchValue ) = 0; + virtual void ClearRichPresence() = 0; + virtual const char *GetFriendRichPresence( CSteamID steamIDFriend, const char *pchKey ) = 0; + virtual int GetFriendRichPresenceKeyCount( CSteamID steamIDFriend ) = 0; + virtual const char *GetFriendRichPresenceKeyByIndex( CSteamID steamIDFriend, int iKey ) = 0; + // Requests rich presence for a specific user. + virtual void RequestFriendRichPresence( CSteamID steamIDFriend ) = 0; + + // rich invite support + // if the target accepts the invite, the pchConnectString gets added to the command-line for launching the game + // if the game is already running, a GameRichPresenceJoinRequested_t callback is posted containing the connect string + // invites can only be sent to friends + virtual bool InviteUserToGame( CSteamID steamIDFriend, const char *pchConnectString ) = 0; + + // recently-played-with friends iteration + // this iterates the entire list of users recently played with, across games + // GetFriendCoplayTime() returns as a unix time + virtual int GetCoplayFriendCount() = 0; + virtual CSteamID GetCoplayFriend( int iCoplayFriend ) = 0; + virtual int GetFriendCoplayTime( CSteamID steamIDFriend ) = 0; + virtual AppId_t GetFriendCoplayGame( CSteamID steamIDFriend ) = 0; + + // chat interface for games + // this allows in-game access to group (clan) chats from in the game + // the behavior is somewhat sophisticated, because the user may or may not be already in the group chat from outside the game or in the overlay + // use ActivateGameOverlayToUser( "chat", steamIDClan ) to open the in-game overlay version of the chat + virtual SteamAPICall_t JoinClanChatRoom( CSteamID steamIDClan ) = 0; + virtual bool LeaveClanChatRoom( CSteamID steamIDClan ) = 0; + virtual int GetClanChatMemberCount( CSteamID steamIDClan ) = 0; + virtual CSteamID GetChatMemberByIndex( CSteamID steamIDClan, int iUser ) = 0; + virtual bool SendClanChatMessage( CSteamID steamIDClanChat, const char *pchText ) = 0; + virtual int GetClanChatMessage( CSteamID steamIDClanChat, int iMessage, void *prgchText, int cchTextMax, EChatEntryType *, CSteamID * ) = 0; + virtual bool IsClanChatAdmin( CSteamID steamIDClanChat, CSteamID steamIDUser ) = 0; + + // interact with the Steam (game overlay / desktop) + virtual bool IsClanChatWindowOpenInSteam( CSteamID steamIDClanChat ) = 0; + virtual bool OpenClanChatWindowInSteam( CSteamID steamIDClanChat ) = 0; + virtual bool CloseClanChatWindowInSteam( CSteamID steamIDClanChat ) = 0; + + // peer-to-peer chat interception + // this is so you can show P2P chats inline in the game + virtual bool SetListenForFriendsMessages( bool bInterceptEnabled ) = 0; + virtual bool ReplyToFriendMessage( CSteamID steamIDFriend, const char *pchMsgToSend ) = 0; + virtual int GetFriendMessage( CSteamID steamIDFriend, int iMessageID, void *pvData, int cubData, EChatEntryType *peChatEntryType ) = 0; + + // following apis + virtual SteamAPICall_t GetFollowerCount( CSteamID steamID ) = 0; + virtual SteamAPICall_t IsFollowing( CSteamID steamID ) = 0; + virtual SteamAPICall_t EnumerateFollowingList( uint32 unStartIndex ) = 0; +}; + +#define STEAMFRIENDS_INTERFACE_VERSION "SteamFriends013" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when a friends' status changes +//----------------------------------------------------------------------------- +struct PersonaStateChange_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 4 }; + + uint64 m_ulSteamID; // steamID of the friend who changed + int m_nChangeFlags; // what's changed +}; + + +// used in PersonaStateChange_t::m_nChangeFlags to describe what's changed about a user +// these flags describe what the client has learned has changed recently, so on startup you'll see a name, avatar & relationship change for every friend +enum EPersonaChange +{ + k_EPersonaChangeName = 0x0001, + k_EPersonaChangeStatus = 0x0002, + k_EPersonaChangeComeOnline = 0x0004, + k_EPersonaChangeGoneOffline = 0x0008, + k_EPersonaChangeGamePlayed = 0x0010, + k_EPersonaChangeGameServer = 0x0020, + k_EPersonaChangeAvatar = 0x0040, + k_EPersonaChangeJoinedSource= 0x0080, + k_EPersonaChangeLeftSource = 0x0100, + k_EPersonaChangeRelationshipChanged = 0x0200, + k_EPersonaChangeNameFirstSet = 0x0400, + k_EPersonaChangeFacebookInfo = 0x0800, + k_EPersonaChangeNickname = 0x1000, + k_EPersonaChangeSteamLevel = 0x2000, +}; + + +//----------------------------------------------------------------------------- +// Purpose: posted when game overlay activates or deactivates +// the game can use this to be pause or resume single player games +//----------------------------------------------------------------------------- +struct GameOverlayActivated_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 31 }; + uint8 m_bActive; // true if it's just been activated, false otherwise +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a different game server from their friends list +// game client should attempt to connect to specified server when this is received +//----------------------------------------------------------------------------- +struct GameServerChangeRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 32 }; + char m_rgchServer[64]; // server address ("127.0.0.1:27015", "tf2.valvesoftware.com") + char m_rgchPassword[64]; // server password, if any +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a lobby from their friends list +// game client should attempt to connect to specified lobby when this is received +//----------------------------------------------------------------------------- +struct GameLobbyJoinRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 33 }; + CSteamID m_steamIDLobby; + + // The friend they did the join via (will be invalid if not directly via a friend) + // + // On PS3, the friend will be invalid if this was triggered by a PSN invite via the XMB, but + // the account type will be console user so you can tell at least that this was from a PSN friend + // rather than a Steam friend. + CSteamID m_steamIDFriend; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when an avatar is loaded in from a previous GetLargeFriendAvatar() call +// if the image wasn't already available +//----------------------------------------------------------------------------- +struct AvatarImageLoaded_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 34 }; + CSteamID m_steamID; // steamid the avatar has been loaded for + int m_iImage; // the image index of the now loaded image + int m_iWide; // width of the loaded image + int m_iTall; // height of the loaded image +}; + + +//----------------------------------------------------------------------------- +// Purpose: marks the return of a request officer list call +//----------------------------------------------------------------------------- +struct ClanOfficerListResponse_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 35 }; + CSteamID m_steamIDClan; + int m_cOfficers; + uint8 m_bSuccess; +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating updated data about friends rich presence information +//----------------------------------------------------------------------------- +struct FriendRichPresenceUpdate_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 36 }; + CSteamID m_steamIDFriend; // friend who's rich presence has changed + AppId_t m_nAppID; // the appID of the game (should always be the current game) +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a game from their friends list +// rich presence will have been set with the "connect" key which is set here +//----------------------------------------------------------------------------- +struct GameRichPresenceJoinRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 37 }; + CSteamID m_steamIDFriend; // the friend they did the join via (will be invalid if not directly via a friend) + char m_rgchConnect[k_cchMaxRichPresenceValueLength]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a chat message has been received for a clan chat the game has joined +//----------------------------------------------------------------------------- +struct GameConnectedClanChatMsg_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 38 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; + int m_iMessageID; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a user has joined a clan chat +//----------------------------------------------------------------------------- +struct GameConnectedChatJoin_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 39 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a user has left the chat we're in +//----------------------------------------------------------------------------- +struct GameConnectedChatLeave_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 40 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; + bool m_bKicked; // true if admin kicked + bool m_bDropped; // true if Steam connection dropped +}; + + +//----------------------------------------------------------------------------- +// Purpose: a DownloadClanActivityCounts() call has finished +//----------------------------------------------------------------------------- +struct DownloadClanActivityCountsResult_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 41 }; + bool m_bSuccess; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a JoinClanChatRoom() call has finished +//----------------------------------------------------------------------------- +struct JoinClanChatRoomCompletionResult_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 42 }; + CSteamID m_steamIDClanChat; + EChatRoomEnterResponse m_eChatRoomEnterResponse; +}; + +//----------------------------------------------------------------------------- +// Purpose: a chat message has been received from a user +//----------------------------------------------------------------------------- +struct GameConnectedFriendChatMsg_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 43 }; + CSteamID m_steamIDUser; + int m_iMessageID; +}; + + +struct FriendsGetFollowerCount_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 44 }; + EResult m_eResult; + CSteamID m_steamID; + int m_nCount; +}; + + +struct FriendsIsFollowing_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 45 }; + EResult m_eResult; + CSteamID m_steamID; + bool m_bIsFollowing; +}; + + +struct FriendsEnumerateFollowingList_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 46 }; + EResult m_eResult; + CSteamID m_rgSteamID[ k_cEnumerateFollowersMax ]; + int32 m_nResultsReturned; + int32 m_nTotalResultCount; +}; + +//----------------------------------------------------------------------------- +// Purpose: reports the result of an attempt to change the user's persona name +//----------------------------------------------------------------------------- +struct SetPersonaNameResponse_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 47 }; + + bool m_bSuccess; // true if name change succeeded completely. + bool m_bLocalSuccess; // true if name change was retained locally. (We might not have been able to communicate with Steam) + EResult m_result; // detailed result code +}; + + +#pragma pack( pop ) + +#endif // ISTEAMFRIENDS_H diff --git a/dep/hlsdk/public/steam/isteamgameserver.h b/dep/hlsdk/public/steam/isteamgameserver.h new file mode 100644 index 0000000..c5667c1 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamgameserver.h @@ -0,0 +1,391 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam for game servers +// +//============================================================================= + +#ifndef ISTEAMGAMESERVER_H +#define ISTEAMGAMESERVER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +#define MASTERSERVERUPDATERPORT_USEGAMESOCKETSHARE ((uint16)-1) + +//----------------------------------------------------------------------------- +// Purpose: Functions for authenticating users via Steam to play on a game server +//----------------------------------------------------------------------------- +class ISteamGameServer +{ +public: + +// +// Basic server data. These properties, if set, must be set before before calling LogOn. They +// may not be changed after logged in. +// + + /// This is called by SteamGameServer_Init, and you will usually not need to call it directly + virtual bool InitGameServer( uint32 unIP, uint16 usGamePort, uint16 usQueryPort, uint32 unFlags, AppId_t nGameAppId, const char *pchVersionString ) = 0; + + /// Game product identifier. This is currently used by the master server for version checking purposes. + /// It's a required field, but will eventually will go away, and the AppID will be used for this purpose. + virtual void SetProduct( const char *pszProduct ) = 0; + + /// Description of the game. This is a required field and is displayed in the steam server browser....for now. + /// This is a required field, but it will go away eventually, as the data should be determined from the AppID. + virtual void SetGameDescription( const char *pszGameDescription ) = 0; + + /// If your game is a "mod," pass the string that identifies it. The default is an empty string, meaning + /// this application is the original game, not a mod. + /// + /// @see k_cbMaxGameServerGameDir + virtual void SetModDir( const char *pszModDir ) = 0; + + /// Is this is a dedicated server? The default value is false. + virtual void SetDedicatedServer( bool bDedicated ) = 0; + +// +// Login +// + + /// Begin process to login to a persistent game server account + /// + /// You need to register for callbacks to determine the result of this operation. + /// @see SteamServersConnected_t + /// @see SteamServerConnectFailure_t + /// @see SteamServersDisconnected_t + virtual void LogOn( + const char *pszAccountName, + const char *pszPassword + ) = 0; + + /// Login to a generic, anonymous account. + /// + /// Note: in previous versions of the SDK, this was automatically called within SteamGameServer_Init, + /// but this is no longer the case. + virtual void LogOnAnonymous() = 0; + + /// Begin process of logging game server out of steam + virtual void LogOff() = 0; + + // status functions + virtual bool BLoggedOn() = 0; + virtual bool BSecure() = 0; + virtual CSteamID GetSteamID() = 0; + + /// Returns true if the master server has requested a restart. + /// Only returns true once per request. + virtual bool WasRestartRequested() = 0; + +// +// Server state. These properties may be changed at any time. +// + + /// Max player count that will be reported to server browser and client queries + virtual void SetMaxPlayerCount( int cPlayersMax ) = 0; + + /// Number of bots. Default value is zero + virtual void SetBotPlayerCount( int cBotplayers ) = 0; + + /// Set the name of server as it will appear in the server browser + /// + /// @see k_cbMaxGameServerName + virtual void SetServerName( const char *pszServerName ) = 0; + + /// Set name of map to report in the server browser + /// + /// @see k_cbMaxGameServerName + virtual void SetMapName( const char *pszMapName ) = 0; + + /// Let people know if your server will require a password + virtual void SetPasswordProtected( bool bPasswordProtected ) = 0; + + /// Spectator server. The default value is zero, meaning the service + /// is not used. + virtual void SetSpectatorPort( uint16 unSpectatorPort ) = 0; + + /// Name of the spectator server. (Only used if spectator port is nonzero.) + /// + /// @see k_cbMaxGameServerMapName + virtual void SetSpectatorServerName( const char *pszSpectatorServerName ) = 0; + + /// Call this to clear the whole list of key/values that are sent in rules queries. + virtual void ClearAllKeyValues() = 0; + + /// Call this to add/update a key/value pair. + virtual void SetKeyValue( const char *pKey, const char *pValue ) = 0; + + /// Sets a string defining the "gametags" for this server, this is optional, but if it is set + /// it allows users to filter in the matchmaking/server-browser interfaces based on the value + /// + /// @see k_cbMaxGameServerTags + virtual void SetGameTags( const char *pchGameTags ) = 0; + + /// Sets a string defining the "gamedata" for this server, this is optional, but if it is set + /// it allows users to filter in the matchmaking/server-browser interfaces based on the value + /// don't set this unless it actually changes, its only uploaded to the master once (when + /// acknowledged) + /// + /// @see k_cbMaxGameServerGameData + virtual void SetGameData( const char *pchGameData) = 0; + + /// Region identifier. This is an optional field, the default value is empty, meaning the "world" region + virtual void SetRegion( const char *pszRegion ) = 0; + +// +// Player list management / authentication +// + + // Handles receiving a new connection from a Steam user. This call will ask the Steam + // servers to validate the users identity, app ownership, and VAC status. If the Steam servers + // are off-line, then it will validate the cached ticket itself which will validate app ownership + // and identity. The AuthBlob here should be acquired on the game client using SteamUser()->InitiateGameConnection() + // and must then be sent up to the game server for authentication. + // + // Return Value: returns true if the users ticket passes basic checks. pSteamIDUser will contain the Steam ID of this user. pSteamIDUser must NOT be NULL + // If the call succeeds then you should expect a GSClientApprove_t or GSClientDeny_t callback which will tell you whether authentication + // for the user has succeeded or failed (the steamid in the callback will match the one returned by this call) + virtual bool SendUserConnectAndAuthenticate( uint32 unIPClient, const void *pvAuthBlob, uint32 cubAuthBlobSize, CSteamID *pSteamIDUser ) = 0; + + // Creates a fake user (ie, a bot) which will be listed as playing on the server, but skips validation. + // + // Return Value: Returns a SteamID for the user to be tracked with, you should call HandleUserDisconnect() + // when this user leaves the server just like you would for a real user. + virtual CSteamID CreateUnauthenticatedUserConnection() = 0; + + // Should be called whenever a user leaves our game server, this lets Steam internally + // track which users are currently on which servers for the purposes of preventing a single + // account being logged into multiple servers, showing who is currently on a server, etc. + virtual void SendUserDisconnect( CSteamID steamIDUser ) = 0; + + // Update the data to be displayed in the server browser and matchmaking interfaces for a user + // currently connected to the server. For regular users you must call this after you receive a + // GSUserValidationSuccess callback. + // + // Return Value: true if successful, false if failure (ie, steamIDUser wasn't for an active player) + virtual bool BUpdateUserData( CSteamID steamIDUser, const char *pchPlayerName, uint32 uScore ) = 0; + + // New auth system APIs - do not mix with the old auth system APIs. + // ---------------------------------------------------------------- + + // Retrieve ticket to be sent to the entity who wishes to authenticate you ( using BeginAuthSession API ). + // pcbTicket retrieves the length of the actual ticket. + virtual HAuthTicket GetAuthSessionTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + + // Authenticate ticket ( from GetAuthSessionTicket ) from entity steamID to be sure it is valid and isnt reused + // Registers for callbacks if the entity goes offline or cancels the ticket ( see ValidateAuthTicketResponse_t callback and EAuthSessionResponse ) + virtual EBeginAuthSessionResult BeginAuthSession( const void *pAuthTicket, int cbAuthTicket, CSteamID steamID ) = 0; + + // Stop tracking started by BeginAuthSession - called when no longer playing game with this entity + virtual void EndAuthSession( CSteamID steamID ) = 0; + + // Cancel auth ticket from GetAuthSessionTicket, called when no longer playing game with the entity you gave the ticket to + virtual void CancelAuthTicket( HAuthTicket hAuthTicket ) = 0; + + // After receiving a user's authentication data, and passing it to SendUserConnectAndAuthenticate, use this function + // to determine if the user owns downloadable content specified by the provided AppID. + virtual EUserHasLicenseForAppResult UserHasLicenseForApp( CSteamID steamID, AppId_t appID ) = 0; + + // Ask if a user in in the specified group, results returns async by GSUserGroupStatus_t + // returns false if we're not connected to the steam servers and thus cannot ask + virtual bool RequestUserGroupStatus( CSteamID steamIDUser, CSteamID steamIDGroup ) = 0; + +// +// Query steam for server data +// + + // Ask for the gameplay stats for the server. Results returned in a callback + virtual void GetGameplayStats( ) = 0; + + // Gets the reputation score for the game server. This API also checks if the server or some + // other server on the same IP is banned from the Steam master servers. + virtual SteamAPICall_t GetServerReputation( ) = 0; + + // Returns the public IP of the server according to Steam, useful when the server is + // behind NAT and you want to advertise its IP in a lobby for other clients to directly + // connect to + virtual uint32 GetPublicIP() = 0; + +// These are in GameSocketShare mode, where instead of ISteamGameServer creating its own +// socket to talk to the master server on, it lets the game use its socket to forward messages +// back and forth. This prevents us from requiring server ops to open up yet another port +// in their firewalls. +// +// the IP address and port should be in host order, i.e 127.0.0.1 == 0x7f000001 + + // These are used when you've elected to multiplex the game server's UDP socket + // rather than having the master server updater use its own sockets. + // + // Source games use this to simplify the job of the server admins, so they + // don't have to open up more ports on their firewalls. + + // Call this when a packet that starts with 0xFFFFFFFF comes in. That means + // it's for us. + virtual bool HandleIncomingPacket( const void *pData, int cbData, uint32 srcIP, uint16 srcPort ) = 0; + + // AFTER calling HandleIncomingPacket for any packets that came in that frame, call this. + // This gets a packet that the master server updater needs to send out on UDP. + // It returns the length of the packet it wants to send, or 0 if there are no more packets to send. + // Call this each frame until it returns 0. + virtual int GetNextOutgoingPacket( void *pOut, int cbMaxOut, uint32 *pNetAdr, uint16 *pPort ) = 0; + +// +// Control heartbeats / advertisement with master server +// + + // Call this as often as you like to tell the master server updater whether or not + // you want it to be active (default: off). + virtual void EnableHeartbeats( bool bActive ) = 0; + + // You usually don't need to modify this. + // Pass -1 to use the default value for iHeartbeatInterval. + // Some mods change this. + virtual void SetHeartbeatInterval( int iHeartbeatInterval ) = 0; + + // Force a heartbeat to steam at the next opportunity + virtual void ForceHeartbeat() = 0; + + // associate this game server with this clan for the purposes of computing player compat + virtual SteamAPICall_t AssociateWithClan( CSteamID steamIDClan ) = 0; + + // ask if any of the current players dont want to play with this new player - or vice versa + virtual SteamAPICall_t ComputeNewPlayerCompatibility( CSteamID steamIDNewPlayer ) = 0; + +}; + +#define STEAMGAMESERVER_INTERFACE_VERSION "SteamGameServer011" + +// game server flags +const uint32 k_unServerFlagNone = 0x00; +const uint32 k_unServerFlagActive = 0x01; // server has users playing +const uint32 k_unServerFlagSecure = 0x02; // server wants to be secure +const uint32 k_unServerFlagDedicated = 0x04; // server is dedicated +const uint32 k_unServerFlagLinux = 0x08; // linux build +const uint32 k_unServerFlagPassworded = 0x10; // password protected +const uint32 k_unServerFlagPrivate = 0x20; // server shouldn't list on master server and + // won't enforce authentication of users that connect to the server. + // Useful when you run a server where the clients may not + // be connected to the internet but you want them to play (i.e LANs) + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + + +// client has been approved to connect to this game server +struct GSClientApprove_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 1 }; + CSteamID m_SteamID; +}; + + +// client has been denied to connection to this game server +struct GSClientDeny_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 2 }; + CSteamID m_SteamID; + EDenyReason m_eDenyReason; + char m_rgchOptionalText[128]; +}; + + +// request the game server should kick the user +struct GSClientKick_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 3 }; + CSteamID m_SteamID; + EDenyReason m_eDenyReason; +}; + +// NOTE: callback values 4 and 5 are skipped because they are used for old deprecated callbacks, +// do not reuse them here. + + +// client achievement info +struct GSClientAchievementStatus_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 6 }; + uint64 m_SteamID; + char m_pchAchievement[128]; + bool m_bUnlocked; +}; + +// received when the game server requests to be displayed as secure (VAC protected) +// m_bSecure is true if the game server should display itself as secure to users, false otherwise +struct GSPolicyResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 15 }; + uint8 m_bSecure; +}; + +// GS gameplay stats info +struct GSGameplayStats_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 7 }; + EResult m_eResult; // Result of the call + int32 m_nRank; // Overall rank of the server (0-based) + uint32 m_unTotalConnects; // Total number of clients who have ever connected to the server + uint32 m_unTotalMinutesPlayed; // Total number of minutes ever played on the server +}; + +// send as a reply to RequestUserGroupStatus() +struct GSClientGroupStatus_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 8 }; + CSteamID m_SteamIDUser; + CSteamID m_SteamIDGroup; + bool m_bMember; + bool m_bOfficer; +}; + +// Sent as a reply to GetServerReputation() +struct GSReputation_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 9 }; + EResult m_eResult; // Result of the call; + uint32 m_unReputationScore; // The reputation score for the game server + bool m_bBanned; // True if the server is banned from the Steam + // master servers + + // The following members are only filled out if m_bBanned is true. They will all + // be set to zero otherwise. Master server bans are by IP so it is possible to be + // banned even when the score is good high if there is a bad server on another port. + // This information can be used to determine which server is bad. + + uint32 m_unBannedIP; // The IP of the banned server + uint16 m_usBannedPort; // The port of the banned server + uint64 m_ulBannedGameID; // The game ID the banned server is serving + uint32 m_unBanExpires; // Time the ban expires, expressed in the Unix epoch (seconds since 1/1/1970) +}; + +// Sent as a reply to AssociateWithClan() +struct AssociateWithClanResult_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 10 }; + EResult m_eResult; // Result of the call; +}; + +// Sent as a reply to ComputeNewPlayerCompatibility() +struct ComputeNewPlayerCompatibilityResult_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 11 }; + EResult m_eResult; // Result of the call; + int m_cPlayersThatDontLikeCandidate; + int m_cPlayersThatCandidateDoesntLike; + int m_cClanPlayersThatDontLikeCandidate; + CSteamID m_SteamIDCandidate; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMGAMESERVER_H diff --git a/dep/hlsdk/public/steam/isteamgameserverstats.h b/dep/hlsdk/public/steam/isteamgameserverstats.h new file mode 100644 index 0000000..8d53186 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamgameserverstats.h @@ -0,0 +1,99 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface for game servers to steam stats and achievements +// +//============================================================================= + +#ifndef ISTEAMGAMESERVERSTATS_H +#define ISTEAMGAMESERVERSTATS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +//----------------------------------------------------------------------------- +// Purpose: Functions for authenticating users via Steam to play on a game server +//----------------------------------------------------------------------------- +class ISteamGameServerStats +{ +public: + // downloads stats for the user + // returns a GSStatsReceived_t callback when completed + // if the user has no stats, GSStatsReceived_t.m_eResult will be set to k_EResultFail + // these stats will only be auto-updated for clients playing on the server. For other + // users you'll need to call RequestUserStats() again to refresh any data + virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; + + // requests stat information for a user, usable after a successful call to RequestUserStats() + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; + virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; + + // Set / update stats and achievements. + // Note: These updates will work only on stats game servers are allowed to edit and only for + // game servers that have been declared as officially controlled by the game creators. + // Set the IP range of your official servers on the Steamworks page + virtual bool SetUserStat( CSteamID steamIDUser, const char *pchName, int32 nData ) = 0; + virtual bool SetUserStat( CSteamID steamIDUser, const char *pchName, float fData ) = 0; + virtual bool UpdateUserAvgRateStat( CSteamID steamIDUser, const char *pchName, float flCountThisSession, double dSessionLength ) = 0; + + virtual bool SetUserAchievement( CSteamID steamIDUser, const char *pchName ) = 0; + virtual bool ClearUserAchievement( CSteamID steamIDUser, const char *pchName ) = 0; + + // Store the current data on the server, will get a GSStatsStored_t callback when set. + // + // If the callback has a result of k_EResultInvalidParam, one or more stats + // uploaded has been rejected, either because they broke constraints + // or were out of date. In this case the server sends back updated values. + // The stats should be re-iterated to keep in sync. + virtual SteamAPICall_t StoreUserStats( CSteamID steamIDUser ) = 0; +}; + +#define STEAMGAMESERVERSTATS_INTERFACE_VERSION "SteamGameServerStats001" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when the latests stats and achievements have been received +// from the server +//----------------------------------------------------------------------------- +struct GSStatsReceived_t +{ + enum { k_iCallback = k_iSteamGameServerStatsCallbacks }; + EResult m_eResult; // Success / error fetching the stats + CSteamID m_steamIDUser; // The user for whom the stats are retrieved for +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the user stats for a game +//----------------------------------------------------------------------------- +struct GSStatsStored_t +{ + enum { k_iCallback = k_iSteamGameServerStatsCallbacks + 1 }; + EResult m_eResult; // success / error + CSteamID m_steamIDUser; // The user for whom the stats were stored +}; + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that a user's stats have been unloaded. +// Call RequestUserStats again to access stats for this user +//----------------------------------------------------------------------------- +struct GSStatsUnloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 }; + CSteamID m_steamIDUser; // User whose stats have been unloaded +}; + +#pragma pack( pop ) + + +#endif // ISTEAMGAMESERVERSTATS_H diff --git a/dep/hlsdk/public/steam/isteamhttp.h b/dep/hlsdk/public/steam/isteamhttp.h new file mode 100644 index 0000000..15b6528 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamhttp.h @@ -0,0 +1,176 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to http client +// +//============================================================================= + +#ifndef ISTEAMHTTP_H +#define ISTEAMHTTP_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "steamhttpenums.h" + +// Handle to a HTTP Request handle +typedef uint32 HTTPRequestHandle; +#define INVALID_HTTPREQUEST_HANDLE 0 + +//----------------------------------------------------------------------------- +// Purpose: interface to http client +//----------------------------------------------------------------------------- +class ISteamHTTP +{ +public: + + // Initializes a new HTTP request, returning a handle to use in further operations on it. Requires + // the method (GET or POST) and the absolute URL for the request. Only http requests (ie, not https) are + // currently supported, so this string must start with http:// or https:// and should look like http://store.steampowered.com/app/250/ + // or such. + virtual HTTPRequestHandle CreateHTTPRequest( EHTTPMethod eHTTPRequestMethod, const char *pchAbsoluteURL ) = 0; + + // Set a context value for the request, which will be returned in the HTTPRequestCompleted_t callback after + // sending the request. This is just so the caller can easily keep track of which callbacks go with which request data. + virtual bool SetHTTPRequestContextValue( HTTPRequestHandle hRequest, uint64 ulContextValue ) = 0; + + // Set a timeout in seconds for the HTTP request, must be called prior to sending the request. Default + // timeout is 60 seconds if you don't call this. Returns false if the handle is invalid, or the request + // has already been sent. + virtual bool SetHTTPRequestNetworkActivityTimeout( HTTPRequestHandle hRequest, uint32 unTimeoutSeconds ) = 0; + + // Set a request header value for the request, must be called prior to sending the request. Will + // return false if the handle is invalid or the request is already sent. + virtual bool SetHTTPRequestHeaderValue( HTTPRequestHandle hRequest, const char *pchHeaderName, const char *pchHeaderValue ) = 0; + + // Set a GET or POST parameter value on the request, which is set will depend on the EHTTPMethod specified + // when creating the request. Must be called prior to sending the request. Will return false if the + // handle is invalid or the request is already sent. + virtual bool SetHTTPRequestGetOrPostParameter( HTTPRequestHandle hRequest, const char *pchParamName, const char *pchParamValue ) = 0; + + // Sends the HTTP request, will return false on a bad handle, otherwise use SteamCallHandle to wait on + // asynchronous response via callback. + // + // Note: If the user is in offline mode in Steam, then this will add a only-if-cached cache-control + // header and only do a local cache lookup rather than sending any actual remote request. + virtual bool SendHTTPRequest( HTTPRequestHandle hRequest, SteamAPICall_t *pCallHandle ) = 0; + + // Sends the HTTP request, will return false on a bad handle, otherwise use SteamCallHandle to wait on + // asynchronous response via callback for completion, and listen for HTTPRequestHeadersReceived_t and + // HTTPRequestDataReceived_t callbacks while streaming. + virtual bool SendHTTPRequestAndStreamResponse( HTTPRequestHandle hRequest, SteamAPICall_t *pCallHandle ) = 0; + + // Defers a request you have sent, the actual HTTP client code may have many requests queued, and this will move + // the specified request to the tail of the queue. Returns false on invalid handle, or if the request is not yet sent. + virtual bool DeferHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Prioritizes a request you have sent, the actual HTTP client code may have many requests queued, and this will move + // the specified request to the head of the queue. Returns false on invalid handle, or if the request is not yet sent. + virtual bool PrioritizeHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Checks if a response header is present in a HTTP response given a handle from HTTPRequestCompleted_t, also + // returns the size of the header value if present so the caller and allocate a correctly sized buffer for + // GetHTTPResponseHeaderValue. + virtual bool GetHTTPResponseHeaderSize( HTTPRequestHandle hRequest, const char *pchHeaderName, uint32 *unResponseHeaderSize ) = 0; + + // Gets header values from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // header is not present or if your buffer is too small to contain it's value. You should first call + // BGetHTTPResponseHeaderSize to check for the presence of the header and to find out the size buffer needed. + virtual bool GetHTTPResponseHeaderValue( HTTPRequestHandle hRequest, const char *pchHeaderName, uint8 *pHeaderValueBuffer, uint32 unBufferSize ) = 0; + + // Gets the size of the body data from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // handle is invalid. + virtual bool GetHTTPResponseBodySize( HTTPRequestHandle hRequest, uint32 *unBodySize ) = 0; + + // Gets the body data from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // handle is invalid or is to a streaming response, or if the provided buffer is not the correct size. Use BGetHTTPResponseBodySize first to find out + // the correct buffer size to use. + virtual bool GetHTTPResponseBodyData( HTTPRequestHandle hRequest, uint8 *pBodyDataBuffer, uint32 unBufferSize ) = 0; + + // Gets the body data from a streaming HTTP response given a handle from HTTPRequestDataReceived_t. Will return false if the + // handle is invalid or is to a non-streaming response (meaning it wasn't sent with SendHTTPRequestAndStreamResponse), or if the buffer size and offset + // do not match the size and offset sent in HTTPRequestDataReceived_t. + virtual bool GetHTTPStreamingResponseBodyData( HTTPRequestHandle hRequest, uint32 cOffset, uint8 *pBodyDataBuffer, uint32 unBufferSize ) = 0; + + // Releases an HTTP response handle, should always be called to free resources after receiving a HTTPRequestCompleted_t + // callback and finishing using the response. + virtual bool ReleaseHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Gets progress on downloading the body for the request. This will be zero unless a response header has already been + // received which included a content-length field. For responses that contain no content-length it will report + // zero for the duration of the request as the size is unknown until the connection closes. + virtual bool GetHTTPDownloadProgressPct( HTTPRequestHandle hRequest, float *pflPercentOut ) = 0; + + // Sets the body for an HTTP Post request. Will fail and return false on a GET request, and will fail if POST params + // have already been set for the request. Setting this raw body makes it the only contents for the post, the pchContentType + // parameter will set the content-type header for the request so the server may know how to interpret the body. + virtual bool SetHTTPRequestRawPostBody( HTTPRequestHandle hRequest, const char *pchContentType, uint8 *pubBody, uint32 unBodyLen ) = 0; +}; + +#define STEAMHTTP_INTERFACE_VERSION "STEAMHTTP_INTERFACE_VERSION002" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct HTTPRequestCompleted_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 1 }; + + // Handle value for the request that has completed. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; + + // This will be true if we actually got any sort of response from the server (even an error). + // It will be false if we failed due to an internal error or client side network failure. + bool m_bRequestSuccessful; + + // Will be the HTTP status code value returned by the server, k_EHTTPStatusCode200OK is the normal + // OK response, if you get something else you probably need to treat it as a failure. + EHTTPStatusCode m_eStatusCode; +}; + + +struct HTTPRequestHeadersReceived_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 2 }; + + // Handle value for the request that has received headers. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; +}; + +struct HTTPRequestDataReceived_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 3 }; + + // Handle value for the request that has received data. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; + + + // Offset to provide to GetHTTPStreamingResponseBodyData to get this chunk of data + uint32 m_cOffset; + + // Size to provide to GetHTTPStreamingResponseBodyData to get this chunk of data + uint32 m_cBytesReceived; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMHTTP_H diff --git a/dep/hlsdk/public/steam/isteammatchmaking.h b/dep/hlsdk/public/steam/isteammatchmaking.h new file mode 100644 index 0000000..3d664f5 --- /dev/null +++ b/dep/hlsdk/public/steam/isteammatchmaking.h @@ -0,0 +1,731 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam managing game server/client match making +// +//============================================================================= + +#ifndef ISTEAMMATCHMAKING +#define ISTEAMMATCHMAKING +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" +#include "matchmakingtypes.h" +#include "isteamclient.h" +#include "isteamfriends.h" + +// lobby type description +enum ELobbyType +{ + k_ELobbyTypePrivate = 0, // only way to join the lobby is to invite to someone else + k_ELobbyTypeFriendsOnly = 1, // shows for friends or invitees, but not in lobby list + k_ELobbyTypePublic = 2, // visible for friends and in lobby list + k_ELobbyTypeInvisible = 3, // returned by search, but not visible to other friends + // useful if you want a user in two lobbies, for example matching groups together + // a user can be in only one regular lobby, and up to two invisible lobbies +}; + +// lobby search filter tools +enum ELobbyComparison +{ + k_ELobbyComparisonEqualToOrLessThan = -2, + k_ELobbyComparisonLessThan = -1, + k_ELobbyComparisonEqual = 0, + k_ELobbyComparisonGreaterThan = 1, + k_ELobbyComparisonEqualToOrGreaterThan = 2, + k_ELobbyComparisonNotEqual = 3, +}; + +// lobby search distance. Lobby results are sorted from closest to farthest. +enum ELobbyDistanceFilter +{ + k_ELobbyDistanceFilterClose, // only lobbies in the same immediate region will be returned + k_ELobbyDistanceFilterDefault, // only lobbies in the same region or near by regions + k_ELobbyDistanceFilterFar, // for games that don't have many latency requirements, will return lobbies about half-way around the globe + k_ELobbyDistanceFilterWorldwide, // no filtering, will match lobbies as far as India to NY (not recommended, expect multiple seconds of latency between the clients) +}; + +// maximum number of characters a lobby metadata key can be +#define k_nMaxLobbyKeyLength 255 + +//----------------------------------------------------------------------------- +// Purpose: Functions for match making services for clients to get to favorites +// and to operate on game lobbies. +//----------------------------------------------------------------------------- +class ISteamMatchmaking +{ +public: + // game server favorites storage + // saves basic details about a multiplayer game server locally + + // returns the number of favorites servers the user has stored + virtual int GetFavoriteGameCount() = 0; + + // returns the details of the game server + // iGame is of range [0,GetFavoriteGameCount()) + // *pnIP, *pnConnPort are filled in the with IP:port of the game server + // *punFlags specify whether the game server was stored as an explicit favorite or in the history of connections + // *pRTime32LastPlayedOnServer is filled in the with the Unix time the favorite was added + virtual bool GetFavoriteGame( int iGame, AppId_t *pnAppID, uint32 *pnIP, uint16 *pnConnPort, uint16 *pnQueryPort, uint32 *punFlags, uint32 *pRTime32LastPlayedOnServer ) = 0; + + // adds the game server to the local list; updates the time played of the server if it already exists in the list + virtual int AddFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags, uint32 rTime32LastPlayedOnServer ) =0; + + // removes the game server from the local storage; returns true if one was removed + virtual bool RemoveFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags ) = 0; + + /////// + // Game lobby functions + + // Get a list of relevant lobbies + // this is an asynchronous request + // results will be returned by LobbyMatchList_t callback & call result, with the number of lobbies found + // this will never return lobbies that are full + // to add more filter, the filter calls below need to be call before each and every RequestLobbyList() call + // use the CCallResult<> object in steam_api.h to match the SteamAPICall_t call result to a function in an object, e.g. + /* + class CMyLobbyListManager + { + CCallResult m_CallResultLobbyMatchList; + void FindLobbies() + { + // SteamMatchmaking()->AddRequestLobbyListFilter*() functions would be called here, before RequestLobbyList() + SteamAPICall_t hSteamAPICall = SteamMatchmaking()->RequestLobbyList(); + m_CallResultLobbyMatchList.Set( hSteamAPICall, this, &CMyLobbyListManager::OnLobbyMatchList ); + } + + void OnLobbyMatchList( LobbyMatchList_t *pLobbyMatchList, bool bIOFailure ) + { + // lobby list has be retrieved from Steam back-end, use results + } + } + */ + // + virtual SteamAPICall_t RequestLobbyList() = 0; + // filters for lobbies + // this needs to be called before RequestLobbyList() to take effect + // these are cleared on each call to RequestLobbyList() + virtual void AddRequestLobbyListStringFilter( const char *pchKeyToMatch, const char *pchValueToMatch, ELobbyComparison eComparisonType ) = 0; + // numerical comparison + virtual void AddRequestLobbyListNumericalFilter( const char *pchKeyToMatch, int nValueToMatch, ELobbyComparison eComparisonType ) = 0; + // returns results closest to the specified value. Multiple near filters can be added, with early filters taking precedence + virtual void AddRequestLobbyListNearValueFilter( const char *pchKeyToMatch, int nValueToBeCloseTo ) = 0; + // returns only lobbies with the specified number of slots available + virtual void AddRequestLobbyListFilterSlotsAvailable( int nSlotsAvailable ) = 0; + // sets the distance for which we should search for lobbies (based on users IP address to location map on the Steam backed) + virtual void AddRequestLobbyListDistanceFilter( ELobbyDistanceFilter eLobbyDistanceFilter ) = 0; + // sets how many results to return, the lower the count the faster it is to download the lobby results & details to the client + virtual void AddRequestLobbyListResultCountFilter( int cMaxResults ) = 0; + + virtual void AddRequestLobbyListCompatibleMembersFilter( CSteamID steamIDLobby ) = 0; + + // returns the CSteamID of a lobby, as retrieved by a RequestLobbyList call + // should only be called after a LobbyMatchList_t callback is received + // iLobby is of the range [0, LobbyMatchList_t::m_nLobbiesMatching) + // the returned CSteamID::IsValid() will be false if iLobby is out of range + virtual CSteamID GetLobbyByIndex( int iLobby ) = 0; + + // Create a lobby on the Steam servers. + // If private, then the lobby will not be returned by any RequestLobbyList() call; the CSteamID + // of the lobby will need to be communicated via game channels or via InviteUserToLobby() + // this is an asynchronous request + // results will be returned by LobbyCreated_t callback and call result; lobby is joined & ready to use at this point + // a LobbyEnter_t callback will also be received (since the local user is joining their own lobby) + virtual SteamAPICall_t CreateLobby( ELobbyType eLobbyType, int cMaxMembers ) = 0; + + // Joins an existing lobby + // this is an asynchronous request + // results will be returned by LobbyEnter_t callback & call result, check m_EChatRoomEnterResponse to see if was successful + // lobby metadata is available to use immediately on this call completing + virtual SteamAPICall_t JoinLobby( CSteamID steamIDLobby ) = 0; + + // Leave a lobby; this will take effect immediately on the client side + // other users in the lobby will be notified by a LobbyChatUpdate_t callback + virtual void LeaveLobby( CSteamID steamIDLobby ) = 0; + + // Invite another user to the lobby + // the target user will receive a LobbyInvite_t callback + // will return true if the invite is successfully sent, whether or not the target responds + // returns false if the local user is not connected to the Steam servers + // if the other user clicks the join link, a GameLobbyJoinRequested_t will be posted if the user is in-game, + // or if the game isn't running yet the game will be launched with the parameter +connect_lobby <64-bit lobby id> + virtual bool InviteUserToLobby( CSteamID steamIDLobby, CSteamID steamIDInvitee ) = 0; + + // Lobby iteration, for viewing details of users in a lobby + // only accessible if the lobby user is a member of the specified lobby + // persona information for other lobby members (name, avatar, etc.) will be asynchronously received + // and accessible via ISteamFriends interface + + // returns the number of users in the specified lobby + virtual int GetNumLobbyMembers( CSteamID steamIDLobby ) = 0; + // returns the CSteamID of a user in the lobby + // iMember is of range [0,GetNumLobbyMembers()) + // note that the current user must be in a lobby to retrieve CSteamIDs of other users in that lobby + virtual CSteamID GetLobbyMemberByIndex( CSteamID steamIDLobby, int iMember ) = 0; + + // Get data associated with this lobby + // takes a simple key, and returns the string associated with it + // "" will be returned if no value is set, or if steamIDLobby is invalid + virtual const char *GetLobbyData( CSteamID steamIDLobby, const char *pchKey ) = 0; + // Sets a key/value pair in the lobby metadata + // each user in the lobby will be broadcast this new value, and any new users joining will receive any existing data + // this can be used to set lobby names, map, etc. + // to reset a key, just set it to "" + // other users in the lobby will receive notification of the lobby data change via a LobbyDataUpdate_t callback + virtual bool SetLobbyData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue ) = 0; + + // returns the number of metadata keys set on the specified lobby + virtual int GetLobbyDataCount( CSteamID steamIDLobby ) = 0; + + // returns a lobby metadata key/values pair by index, of range [0, GetLobbyDataCount()) + virtual bool GetLobbyDataByIndex( CSteamID steamIDLobby, int iLobbyData, char *pchKey, int cchKeyBufferSize, char *pchValue, int cchValueBufferSize ) = 0; + + // removes a metadata key from the lobby + virtual bool DeleteLobbyData( CSteamID steamIDLobby, const char *pchKey ) = 0; + + // Gets per-user metadata for someone in this lobby + virtual const char *GetLobbyMemberData( CSteamID steamIDLobby, CSteamID steamIDUser, const char *pchKey ) = 0; + // Sets per-user metadata (for the local user implicitly) + virtual void SetLobbyMemberData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue ) = 0; + + // Broadcasts a chat message to the all the users in the lobby + // users in the lobby (including the local user) will receive a LobbyChatMsg_t callback + // returns true if the message is successfully sent + // pvMsgBody can be binary or text data, up to 4k + // if pvMsgBody is text, cubMsgBody should be strlen( text ) + 1, to include the null terminator + virtual bool SendLobbyChatMsg( CSteamID steamIDLobby, const void *pvMsgBody, int cubMsgBody ) = 0; + // Get a chat message as specified in a LobbyChatMsg_t callback + // iChatID is the LobbyChatMsg_t::m_iChatID value in the callback + // *pSteamIDUser is filled in with the CSteamID of the member + // *pvData is filled in with the message itself + // return value is the number of bytes written into the buffer + virtual int GetLobbyChatEntry( CSteamID steamIDLobby, int iChatID, CSteamID *pSteamIDUser, void *pvData, int cubData, EChatEntryType *peChatEntryType ) = 0; + + // Refreshes metadata for a lobby you're not necessarily in right now + // you never do this for lobbies you're a member of, only if your + // this will send down all the metadata associated with a lobby + // this is an asynchronous call + // returns false if the local user is not connected to the Steam servers + // results will be returned by a LobbyDataUpdate_t callback + // if the specified lobby doesn't exist, LobbyDataUpdate_t::m_bSuccess will be set to false + virtual bool RequestLobbyData( CSteamID steamIDLobby ) = 0; + + // sets the game server associated with the lobby + // usually at this point, the users will join the specified game server + // either the IP/Port or the steamID of the game server has to be valid, depending on how you want the clients to be able to connect + virtual void SetLobbyGameServer( CSteamID steamIDLobby, uint32 unGameServerIP, uint16 unGameServerPort, CSteamID steamIDGameServer ) = 0; + // returns the details of a game server set in a lobby - returns false if there is no game server set, or that lobby doesn't exist + virtual bool GetLobbyGameServer( CSteamID steamIDLobby, uint32 *punGameServerIP, uint16 *punGameServerPort, CSteamID *psteamIDGameServer ) = 0; + + // set the limit on the # of users who can join the lobby + virtual bool SetLobbyMemberLimit( CSteamID steamIDLobby, int cMaxMembers ) = 0; + // returns the current limit on the # of users who can join the lobby; returns 0 if no limit is defined + virtual int GetLobbyMemberLimit( CSteamID steamIDLobby ) = 0; + + // updates which type of lobby it is + // only lobbies that are k_ELobbyTypePublic or k_ELobbyTypeInvisible, and are set to joinable, will be returned by RequestLobbyList() calls + virtual bool SetLobbyType( CSteamID steamIDLobby, ELobbyType eLobbyType ) = 0; + + // sets whether or not a lobby is joinable - defaults to true for a new lobby + // if set to false, no user can join, even if they are a friend or have been invited + virtual bool SetLobbyJoinable( CSteamID steamIDLobby, bool bLobbyJoinable ) = 0; + + // returns the current lobby owner + // you must be a member of the lobby to access this + // there always one lobby owner - if the current owner leaves, another user will become the owner + // it is possible (bur rare) to join a lobby just as the owner is leaving, thus entering a lobby with self as the owner + virtual CSteamID GetLobbyOwner( CSteamID steamIDLobby ) = 0; + + // changes who the lobby owner is + // you must be the lobby owner for this to succeed, and steamIDNewOwner must be in the lobby + // after completion, the local user will no longer be the owner + virtual bool SetLobbyOwner( CSteamID steamIDLobby, CSteamID steamIDNewOwner ) = 0; + + // link two lobbies for the purposes of checking player compatibility + // you must be the lobby owner of both lobbies + virtual bool SetLinkedLobby( CSteamID steamIDLobby, CSteamID steamIDLobbyDependent ) = 0; + +#ifdef _PS3 + // changes who the lobby owner is + // you must be the lobby owner for this to succeed, and steamIDNewOwner must be in the lobby + // after completion, the local user will no longer be the owner + virtual void CheckForPSNGameBootInvite( unsigned int iGameBootAttributes ) = 0; +#endif +}; +#define STEAMMATCHMAKING_INTERFACE_VERSION "SteamMatchMaking009" + + +//----------------------------------------------------------------------------- +// Callback interfaces for server list functions (see ISteamMatchmakingServers below) +// +// The idea here is that your game code implements objects that implement these +// interfaces to receive callback notifications after calling asynchronous functions +// inside the ISteamMatchmakingServers() interface below. +// +// This is different than normal Steam callback handling due to the potentially +// large size of server lists. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typedef for handle type you will receive when requesting server list. +//----------------------------------------------------------------------------- +typedef void* HServerListRequest; + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after a server list refresh +// or an individual server update. +// +// Since you get these callbacks after requesting full list refreshes you will +// usually implement this interface inside an object like CServerBrowser. If that +// object is getting destructed you should use ISteamMatchMakingServers()->CancelQuery() +// to cancel any in-progress queries so you don't get a callback into the destructed +// object and crash. +//----------------------------------------------------------------------------- +class ISteamMatchmakingServerListResponse +{ +public: + // Server has responded ok with updated data + virtual void ServerResponded( HServerListRequest hRequest, int iServer ) = 0; + + // Server has failed to respond + virtual void ServerFailedToRespond( HServerListRequest hRequest, int iServer ) = 0; + + // A list refresh you had initiated is now 100% completed + virtual void RefreshComplete( HServerListRequest hRequest, EMatchMakingServerResponse response ) = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after pinging an individual server +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->PingServer() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingPingResponse +{ +public: + // Server has responded successfully and has updated data + virtual void ServerResponded( gameserveritem_t &server ) = 0; + + // Server failed to respond to the ping request + virtual void ServerFailedToRespond() = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after requesting details on +// who is playing on a particular server. +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->PlayerDetails() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingPlayersResponse +{ +public: + // Got data on a new player on the server -- you'll get this callback once per player + // on the server which you have requested player data on. + virtual void AddPlayerToList( const char *pchName, int nScore, float flTimePlayed ) = 0; + + // The server failed to respond to the request for player details + virtual void PlayersFailedToRespond() = 0; + + // The server has finished responding to the player details request + // (ie, you won't get anymore AddPlayerToList callbacks) + virtual void PlayersRefreshComplete() = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after requesting rules +// details on a particular server. +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->ServerRules() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingRulesResponse +{ +public: + // Got data on a rule on the server -- you'll get one of these per rule defined on + // the server you are querying + virtual void RulesResponded( const char *pchRule, const char *pchValue ) = 0; + + // The server failed to respond to the request for rule details + virtual void RulesFailedToRespond() = 0; + + // The server has finished responding to the rule details request + // (ie, you won't get anymore RulesResponded callbacks) + virtual void RulesRefreshComplete() = 0; +}; + + +//----------------------------------------------------------------------------- +// Typedef for handle type you will receive when querying details on an individual server. +//----------------------------------------------------------------------------- +typedef int HServerQuery; +const int HSERVERQUERY_INVALID = 0xffffffff; + +//----------------------------------------------------------------------------- +// Purpose: Functions for match making services for clients to get to game lists and details +//----------------------------------------------------------------------------- +class ISteamMatchmakingServers +{ +public: + // Request a new list of servers of a particular type. These calls each correspond to one of the EMatchMakingType values. + // Each call allocates a new asynchronous request object. + // Request object must be released by calling ReleaseRequest( hServerListRequest ) + virtual HServerListRequest RequestInternetServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestLANServerList( AppId_t iApp, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestFriendsServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestFavoritesServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestHistoryServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestSpectatorServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + + // Releases the asynchronous request object and cancels any pending query on it if there's a pending query in progress. + // RefreshComplete callback is not posted when request is released. + virtual void ReleaseRequest( HServerListRequest hServerListRequest ) = 0; + + /* the filter operation codes that go in the key part of MatchMakingKeyValuePair_t should be one of these: + + "map" + - Server passes the filter if the server is playing the specified map. + "gamedataand" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) contains all of the + specified strings. The value field is a comma-delimited list of strings to match. + "gamedataor" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) contains at least one of the + specified strings. The value field is a comma-delimited list of strings to match. + "gamedatanor" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) does not contain any + of the specified strings. The value field is a comma-delimited list of strings to check. + "gametagsand" + - Server passes the filter if the server's game tags (ISteamGameServer::SetGameTags) contains all + of the specified strings. The value field is a comma-delimited list of strings to check. + "gametagsnor" + - Server passes the filter if the server's game tags (ISteamGameServer::SetGameTags) does not contain any + of the specified strings. The value field is a comma-delimited list of strings to check. + "and" (x1 && x2 && ... && xn) + "or" (x1 || x2 || ... || xn) + "nand" !(x1 && x2 && ... && xn) + "nor" !(x1 || x2 || ... || xn) + - Performs Boolean operation on the following filters. The operand to this filter specifies + the "size" of the Boolean inputs to the operation, in Key/value pairs. (The keyvalue + pairs must immediately follow, i.e. this is a prefix logical operator notation.) + In the simplest case where Boolean expressions are not nested, this is simply + the number of operands. + + For example, to match servers on a particular map or with a particular tag, would would + use these filters. + + ( server.map == "cp_dustbowl" || server.gametags.contains("payload") ) + "or", "2" + "map", "cp_dustbowl" + "gametagsand", "payload" + + If logical inputs are nested, then the operand specifies the size of the entire + "length" of its operands, not the number of immediate children. + + ( server.map == "cp_dustbowl" || ( server.gametags.contains("payload") && !server.gametags.contains("payloadrace") ) ) + "or", "4" + "map", "cp_dustbowl" + "and", "2" + "gametagsand", "payload" + "gametagsnor", "payloadrace" + + Unary NOT can be achieved using either "nand" or "nor" with a single operand. + + "addr" + - Server passes the filter if the server's query address matches the specified IP or IP:port. + "gameaddr" + - Server passes the filter if the server's game address matches the specified IP or IP:port. + + The following filter operations ignore the "value" part of MatchMakingKeyValuePair_t + + "dedicated" + - Server passes the filter if it passed true to SetDedicatedServer. + "secure" + - Server passes the filter if the server is VAC-enabled. + "notfull" + - Server passes the filter if the player count is less than the reported max player count. + "hasplayers" + - Server passes the filter if the player count is greater than zero. + "noplayers" + - Server passes the filter if it doesn't have any players. + "linux" + - Server passes the filter if it's a linux server + */ + + // Get details on a given server in the list, you can get the valid range of index + // values by calling GetServerCount(). You will also receive index values in + // ISteamMatchmakingServerListResponse::ServerResponded() callbacks + virtual gameserveritem_t *GetServerDetails( HServerListRequest hRequest, int iServer ) = 0; + + // Cancel an request which is operation on the given list type. You should call this to cancel + // any in-progress requests before destructing a callback object that may have been passed + // to one of the above list request calls. Not doing so may result in a crash when a callback + // occurs on the destructed object. + // Canceling a query does not release the allocated request handle. + // The request handle must be released using ReleaseRequest( hRequest ) + virtual void CancelQuery( HServerListRequest hRequest ) = 0; + + // Ping every server in your list again but don't update the list of servers + // Query callback installed when the server list was requested will be used + // again to post notifications and RefreshComplete, so the callback must remain + // valid until another RefreshComplete is called on it or the request + // is released with ReleaseRequest( hRequest ) + virtual void RefreshQuery( HServerListRequest hRequest ) = 0; + + // Returns true if the list is currently refreshing its server list + virtual bool IsRefreshing( HServerListRequest hRequest ) = 0; + + // How many servers in the given list, GetServerDetails above takes 0... GetServerCount() - 1 + virtual int GetServerCount( HServerListRequest hRequest ) = 0; + + // Refresh a single server inside of a query (rather than all the servers ) + virtual void RefreshServer( HServerListRequest hRequest, int iServer ) = 0; + + + //----------------------------------------------------------------------------- + // Queries to individual servers directly via IP/Port + //----------------------------------------------------------------------------- + + // Request updated ping time and other details from a single server + virtual HServerQuery PingServer( uint32 unIP, uint16 usPort, ISteamMatchmakingPingResponse *pRequestServersResponse ) = 0; + + // Request the list of players currently playing on a server + virtual HServerQuery PlayerDetails( uint32 unIP, uint16 usPort, ISteamMatchmakingPlayersResponse *pRequestServersResponse ) = 0; + + // Request the list of rules that the server is running (See ISteamGameServer::SetKeyValue() to set the rules server side) + virtual HServerQuery ServerRules( uint32 unIP, uint16 usPort, ISteamMatchmakingRulesResponse *pRequestServersResponse ) = 0; + + // Cancel an outstanding Ping/Players/Rules query from above. You should call this to cancel + // any in-progress requests before destructing a callback object that may have been passed + // to one of the above calls to avoid crashing when callbacks occur. + virtual void CancelServerQuery( HServerQuery hServerQuery ) = 0; +}; +#define STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION "SteamMatchMakingServers002" + +// game server flags +const uint32 k_unFavoriteFlagNone = 0x00; +const uint32 k_unFavoriteFlagFavorite = 0x01; // this game favorite entry is for the favorites list +const uint32 k_unFavoriteFlagHistory = 0x02; // this game favorite entry is for the history list + + +//----------------------------------------------------------------------------- +// Purpose: Used in ChatInfo messages - fields specific to a chat member - must fit in a uint32 +//----------------------------------------------------------------------------- +enum EChatMemberStateChange +{ + // Specific to joining / leaving the chatroom + k_EChatMemberStateChangeEntered = 0x0001, // This user has joined or is joining the chat room + k_EChatMemberStateChangeLeft = 0x0002, // This user has left or is leaving the chat room + k_EChatMemberStateChangeDisconnected = 0x0004, // User disconnected without leaving the chat first + k_EChatMemberStateChangeKicked = 0x0008, // User kicked + k_EChatMemberStateChangeBanned = 0x0010, // User kicked and banned +}; + +// returns true of the flags indicate that a user has been removed from the chat +#define BChatMemberStateChangeRemoved( rgfChatMemberStateChangeFlags ) ( rgfChatMemberStateChangeFlags & ( k_EChatMemberStateChangeDisconnected | k_EChatMemberStateChangeLeft | k_EChatMemberStateChangeKicked | k_EChatMemberStateChangeBanned ) ) + + +//----------------------------------------------------------------------------- +// Callbacks for ISteamMatchmaking (which go through the regular Steam callback registration system) +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: a server was added/removed from the favorites list, you should refresh now +//----------------------------------------------------------------------------- +struct FavoritesListChanged_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 2 }; + uint32 m_nIP; // an IP of 0 means reload the whole list, any other value means just one server + uint32 m_nQueryPort; + uint32 m_nConnPort; + uint32 m_nAppID; + uint32 m_nFlags; + bool m_bAdd; // true if this is adding the entry, otherwise it is a remove +}; + + +//----------------------------------------------------------------------------- +// Purpose: Someone has invited you to join a Lobby +// normally you don't need to do anything with this, since +// the Steam UI will also display a ' has invited you to the lobby, join?' dialog +// +// if the user outside a game chooses to join, your game will be launched with the parameter "+connect_lobby <64-bit lobby id>", +// or with the callback GameLobbyJoinRequested_t if they're already in-game +//----------------------------------------------------------------------------- +struct LobbyInvite_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 3 }; + + uint64 m_ulSteamIDUser; // Steam ID of the person making the invite + uint64 m_ulSteamIDLobby; // Steam ID of the Lobby + uint64 m_ulGameID; // GameID of the Lobby +}; + + +//----------------------------------------------------------------------------- +// Purpose: Sent on entering a lobby, or on failing to enter +// m_EChatRoomEnterResponse will be set to k_EChatRoomEnterResponseSuccess on success, +// or a higher value on failure (see enum EChatRoomEnterResponse) +//----------------------------------------------------------------------------- +struct LobbyEnter_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 4 }; + + uint64 m_ulSteamIDLobby; // SteamID of the Lobby you have entered + uint32 m_rgfChatPermissions; // Permissions of the current user + bool m_bLocked; // If true, then only invited users may join + uint32 m_EChatRoomEnterResponse; // EChatRoomEnterResponse +}; + + +//----------------------------------------------------------------------------- +// Purpose: The lobby metadata has changed +// if m_ulSteamIDMember is the steamID of a lobby member, use GetLobbyMemberData() to access per-user details +// if m_ulSteamIDMember == m_ulSteamIDLobby, use GetLobbyData() to access lobby metadata +//----------------------------------------------------------------------------- +struct LobbyDataUpdate_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 5 }; + + uint64 m_ulSteamIDLobby; // steamID of the Lobby + uint64 m_ulSteamIDMember; // steamID of the member whose data changed, or the room itself + uint8 m_bSuccess; // true if we lobby data was successfully changed; + // will only be false if RequestLobbyData() was called on a lobby that no longer exists +}; + + +//----------------------------------------------------------------------------- +// Purpose: The lobby chat room state has changed +// this is usually sent when a user has joined or left the lobby +//----------------------------------------------------------------------------- +struct LobbyChatUpdate_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 6 }; + + uint64 m_ulSteamIDLobby; // Lobby ID + uint64 m_ulSteamIDUserChanged; // user who's status in the lobby just changed - can be recipient + uint64 m_ulSteamIDMakingChange; // Chat member who made the change (different from SteamIDUserChange if kicking, muting, etc.) + // for example, if one user kicks another from the lobby, this will be set to the id of the user who initiated the kick + uint32 m_rgfChatMemberStateChange; // bitfield of EChatMemberStateChange values +}; + + +//----------------------------------------------------------------------------- +// Purpose: A chat message for this lobby has been sent +// use GetLobbyChatEntry( m_iChatID ) to retrieve the contents of this message +//----------------------------------------------------------------------------- +struct LobbyChatMsg_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 7 }; + + uint64 m_ulSteamIDLobby; // the lobby id this is in + uint64 m_ulSteamIDUser; // steamID of the user who has sent this message + uint8 m_eChatEntryType; // type of message + uint32 m_iChatID; // index of the chat entry to lookup +}; + + +//----------------------------------------------------------------------------- +// Purpose: A game created a game for all the members of the lobby to join, +// as triggered by a SetLobbyGameServer() +// it's up to the individual clients to take action on this; the usual +// game behavior is to leave the lobby and connect to the specified game server +//----------------------------------------------------------------------------- +struct LobbyGameCreated_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 9 }; + + uint64 m_ulSteamIDLobby; // the lobby we were in + uint64 m_ulSteamIDGameServer; // the new game server that has been created or found for the lobby members + uint32 m_unIP; // IP & Port of the game server (if any) + uint16 m_usPort; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Number of matching lobbies found +// iterate the returned lobbies with GetLobbyByIndex(), from values 0 to m_nLobbiesMatching-1 +//----------------------------------------------------------------------------- +struct LobbyMatchList_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 10 }; + uint32 m_nLobbiesMatching; // Number of lobbies that matched search criteria and we have SteamIDs for +}; + + +//----------------------------------------------------------------------------- +// Purpose: posted if a user is forcefully removed from a lobby +// can occur if a user loses connection to Steam +//----------------------------------------------------------------------------- +struct LobbyKicked_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 12 }; + uint64 m_ulSteamIDLobby; // Lobby + uint64 m_ulSteamIDAdmin; // User who kicked you - possibly the ID of the lobby itself + uint8 m_bKickedDueToDisconnect; // true if you were kicked from the lobby due to the user losing connection to Steam (currently always true) +}; + + +//----------------------------------------------------------------------------- +// Purpose: Result of our request to create a Lobby +// m_eResult == k_EResultOK on success +// at this point, the lobby has been joined and is ready for use +// a LobbyEnter_t callback will also be received (since the local user is joining their own lobby) +//----------------------------------------------------------------------------- +struct LobbyCreated_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 13 }; + + EResult m_eResult; // k_EResultOK - the lobby was successfully created + // k_EResultNoConnection - your Steam client doesn't have a connection to the back-end + // k_EResultTimeout - you the message to the Steam servers, but it didn't respond + // k_EResultFail - the server responded, but with an unknown internal error + // k_EResultAccessDenied - your game isn't set to allow lobbies, or your client does haven't rights to play the game + // k_EResultLimitExceeded - your game client has created too many lobbies + + uint64 m_ulSteamIDLobby; // chat room, zero if failed +}; + +// used by now obsolete RequestFriendsLobbiesResponse_t +// enum { k_iCallback = k_iSteamMatchmakingCallbacks + 14 }; + + +//----------------------------------------------------------------------------- +// Purpose: Result of CheckForPSNGameBootInvite +// m_eResult == k_EResultOK on success +// at this point, the local user may not have finishing joining this lobby; +// game code should wait until the subsequent LobbyEnter_t callback is received +//----------------------------------------------------------------------------- +struct PSNGameBootInviteResult_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 15 }; + + bool m_bGameBootInviteExists; + CSteamID m_steamIDLobby; // Should be valid if m_bGameBootInviteExists == true +}; +#pragma pack( pop ) + + +#endif // ISTEAMMATCHMAKING diff --git a/dep/hlsdk/public/steam/isteamnetworking.h b/dep/hlsdk/public/steam/isteamnetworking.h new file mode 100644 index 0000000..c77f7bf --- /dev/null +++ b/dep/hlsdk/public/steam/isteamnetworking.h @@ -0,0 +1,306 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam managing network connections between game clients & servers +// +//============================================================================= + +#ifndef ISTEAMNETWORKING +#define ISTEAMNETWORKING +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" + + +// list of possible errors returned by SendP2PPacket() API +// these will be posted in the P2PSessionConnectFail_t callback +enum EP2PSessionError +{ + k_EP2PSessionErrorNone = 0, + k_EP2PSessionErrorNotRunningApp = 1, // target is not running the same game + k_EP2PSessionErrorNoRightsToApp = 2, // local user doesn't own the app that is running + k_EP2PSessionErrorDestinationNotLoggedIn = 3, // target user isn't connected to Steam + k_EP2PSessionErrorTimeout = 4, // target isn't responding, perhaps not calling AcceptP2PSessionWithUser() + // corporate firewalls can also block this (NAT traversal is not firewall traversal) + // make sure that UDP ports 3478, 4379, and 4380 are open in an outbound direction + k_EP2PSessionErrorMax = 5 +}; + +// SendP2PPacket() send types +// Typically k_EP2PSendUnreliable is what you want for UDP-like packets, k_EP2PSendReliable for TCP-like packets +enum EP2PSend +{ + // Basic UDP send. Packets can't be bigger than 1200 bytes (your typical MTU size). Can be lost, or arrive out of order (rare). + // The sending API does have some knowledge of the underlying connection, so if there is no NAT-traversal accomplished or + // there is a recognized adjustment happening on the connection, the packet will be batched until the connection is open again. + k_EP2PSendUnreliable = 0, + + // As above, but if the underlying p2p connection isn't yet established the packet will just be thrown away. Using this on the first + // packet sent to a remote host almost guarantees the packet will be dropped. + // This is only really useful for kinds of data that should never buffer up, i.e. voice payload packets + k_EP2PSendUnreliableNoDelay = 1, + + // Reliable message send. Can send up to 1MB of data in a single message. + // Does fragmentation/re-assembly of messages under the hood, as well as a sliding window for efficient sends of large chunks of data. + k_EP2PSendReliable = 2, + + // As above, but applies the Nagle algorithm to the send - sends will accumulate + // until the current MTU size (typically ~1200 bytes, but can change) or ~200ms has passed (Nagle algorithm). + // Useful if you want to send a set of smaller messages but have the coalesced into a single packet + // Since the reliable stream is all ordered, you can do several small message sends with k_EP2PSendReliableWithBuffering and then + // do a normal k_EP2PSendReliable to force all the buffered data to be sent. + k_EP2PSendReliableWithBuffering = 3, + +}; + + +// connection state to a specified user, returned by GetP2PSessionState() +// this is under-the-hood info about what's going on with a SendP2PPacket(), shouldn't be needed except for debuggin +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct P2PSessionState_t +{ + uint8 m_bConnectionActive; // true if we've got an active open connection + uint8 m_bConnecting; // true if we're currently trying to establish a connection + uint8 m_eP2PSessionError; // last error recorded (see enum above) + uint8 m_bUsingRelay; // true if it's going through a relay server (TURN) + int32 m_nBytesQueuedForSend; + int32 m_nPacketsQueuedForSend; + uint32 m_nRemoteIP; // potential IP:Port of remote host. Could be TURN server. + uint16 m_nRemotePort; // Only exists for compatibility with older authentication api's +}; +#pragma pack( pop ) + + +// handle to a socket +typedef uint32 SNetSocket_t; // CreateP2PConnectionSocket() +typedef uint32 SNetListenSocket_t; // CreateListenSocket() + +// connection progress indicators, used by CreateP2PConnectionSocket() +enum ESNetSocketState +{ + k_ESNetSocketStateInvalid = 0, + + // communication is valid + k_ESNetSocketStateConnected = 1, + + // states while establishing a connection + k_ESNetSocketStateInitiated = 10, // the connection state machine has started + + // p2p connections + k_ESNetSocketStateLocalCandidatesFound = 11, // we've found our local IP info + k_ESNetSocketStateReceivedRemoteCandidates = 12,// we've received information from the remote machine, via the Steam back-end, about their IP info + + // direct connections + k_ESNetSocketStateChallengeHandshake = 15, // we've received a challenge packet from the server + + // failure states + k_ESNetSocketStateDisconnecting = 21, // the API shut it down, and we're in the process of telling the other end + k_ESNetSocketStateLocalDisconnect = 22, // the API shut it down, and we've completed shutdown + k_ESNetSocketStateTimeoutDuringConnect = 23, // we timed out while trying to creating the connection + k_ESNetSocketStateRemoteEndDisconnected = 24, // the remote end has disconnected from us + k_ESNetSocketStateConnectionBroken = 25, // connection has been broken; either the other end has disappeared or our local network connection has broke + +}; + +// describes how the socket is currently connected +enum ESNetSocketConnectionType +{ + k_ESNetSocketConnectionTypeNotConnected = 0, + k_ESNetSocketConnectionTypeUDP = 1, + k_ESNetSocketConnectionTypeUDPRelay = 2, +}; + + +//----------------------------------------------------------------------------- +// Purpose: Functions for making connections and sending data between clients, +// traversing NAT's where possible +//----------------------------------------------------------------------------- +class ISteamNetworking +{ +public: + //////////////////////////////////////////////////////////////////////////////////////////// + // Session-less connection functions + // automatically establishes NAT-traversing or Relay server connections + + // Sends a P2P packet to the specified user + // UDP-like, unreliable and a max packet size of 1200 bytes + // the first packet send may be delayed as the NAT-traversal code runs + // if we can't get through to the user, an error will be posted via the callback P2PSessionConnectFail_t + // see EP2PSend enum above for the descriptions of the different ways of sending packets + // + // nChannel is a routing number you can use to help route message to different systems - you'll have to call ReadP2PPacket() + // with the same channel number in order to retrieve the data on the other end + // using different channels to talk to the same user will still use the same underlying p2p connection, saving on resources + virtual bool SendP2PPacket( CSteamID steamIDRemote, const void *pubData, uint32 cubData, EP2PSend eP2PSendType, int nChannel = 0 ) = 0; + + // returns true if any data is available for read, and the amount of data that will need to be read + virtual bool IsP2PPacketAvailable( uint32 *pcubMsgSize, int nChannel = 0 ) = 0; + + // reads in a packet that has been sent from another user via SendP2PPacket() + // returns the size of the message and the steamID of the user who sent it in the last two parameters + // if the buffer passed in is too small, the message will be truncated + // this call is not blocking, and will return false if no data is available + virtual bool ReadP2PPacket( void *pubDest, uint32 cubDest, uint32 *pcubMsgSize, CSteamID *psteamIDRemote, int nChannel = 0 ) = 0; + + // AcceptP2PSessionWithUser() should only be called in response to a P2PSessionRequest_t callback + // P2PSessionRequest_t will be posted if another user tries to send you a packet that you haven't talked to yet + // if you don't want to talk to the user, just ignore the request + // if the user continues to send you packets, another P2PSessionRequest_t will be posted periodically + // this may be called multiple times for a single user + // (if you've called SendP2PPacket() on the other user, this implicitly accepts the session request) + virtual bool AcceptP2PSessionWithUser( CSteamID steamIDRemote ) = 0; + + // call CloseP2PSessionWithUser() when you're done talking to a user, will free up resources under-the-hood + // if the remote user tries to send data to you again, another P2PSessionRequest_t callback will be posted + virtual bool CloseP2PSessionWithUser( CSteamID steamIDRemote ) = 0; + + // call CloseP2PChannelWithUser() when you're done talking to a user on a specific channel. Once all channels + // open channels to a user have been closed, the open session to the user will be closed and new data from this + // user will trigger a P2PSessionRequest_t callback + virtual bool CloseP2PChannelWithUser( CSteamID steamIDRemote, int nChannel ) = 0; + + // fills out P2PSessionState_t structure with details about the underlying connection to the user + // should only needed for debugging purposes + // returns false if no connection exists to the specified user + virtual bool GetP2PSessionState( CSteamID steamIDRemote, P2PSessionState_t *pConnectionState ) = 0; + + // Allow P2P connections to fall back to being relayed through the Steam servers if a direct connection + // or NAT-traversal cannot be established. Only applies to connections created after setting this value, + // or to existing connections that need to automatically reconnect after this value is set. + // + // P2P packet relay is allowed by default + virtual bool AllowP2PPacketRelay( bool bAllow ) = 0; + + + //////////////////////////////////////////////////////////////////////////////////////////// + // LISTEN / CONNECT style interface functions + // + // This is an older set of functions designed around the Berkeley TCP sockets model + // it's preferential that you use the above P2P functions, they're more robust + // and these older functions will be removed eventually + // + //////////////////////////////////////////////////////////////////////////////////////////// + + + // creates a socket and listens others to connect + // will trigger a SocketStatusCallback_t callback on another client connecting + // nVirtualP2PPort is the unique ID that the client will connect to, in case you have multiple ports + // this can usually just be 0 unless you want multiple sets of connections + // unIP is the local IP address to bind to + // pass in 0 if you just want the default local IP + // unPort is the port to use + // pass in 0 if you don't want users to be able to connect via IP/Port, but expect to be always peer-to-peer connections only + virtual SNetListenSocket_t CreateListenSocket( int nVirtualP2PPort, uint32 nIP, uint16 nPort, bool bAllowUseOfPacketRelay ) = 0; + + // creates a socket and begin connection to a remote destination + // can connect via a known steamID (client or game server), or directly to an IP + // on success will trigger a SocketStatusCallback_t callback + // on failure or timeout will trigger a SocketStatusCallback_t callback with a failure code in m_eSNetSocketState + virtual SNetSocket_t CreateP2PConnectionSocket( CSteamID steamIDTarget, int nVirtualPort, int nTimeoutSec, bool bAllowUseOfPacketRelay ) = 0; + virtual SNetSocket_t CreateConnectionSocket( uint32 nIP, uint16 nPort, int nTimeoutSec ) = 0; + + // disconnects the connection to the socket, if any, and invalidates the handle + // any unread data on the socket will be thrown away + // if bNotifyRemoteEnd is set, socket will not be completely destroyed until the remote end acknowledges the disconnect + virtual bool DestroySocket( SNetSocket_t hSocket, bool bNotifyRemoteEnd ) = 0; + // destroying a listen socket will automatically kill all the regular sockets generated from it + virtual bool DestroyListenSocket( SNetListenSocket_t hSocket, bool bNotifyRemoteEnd ) = 0; + + // sending data + // must be a handle to a connected socket + // data is all sent via UDP, and thus send sizes are limited to 1200 bytes; after this, many routers will start dropping packets + // use the reliable flag with caution; although the resend rate is pretty aggressive, + // it can still cause stalls in receiving data (like TCP) + virtual bool SendDataOnSocket( SNetSocket_t hSocket, void *pubData, uint32 cubData, bool bReliable ) = 0; + + // receiving data + // returns false if there is no data remaining + // fills out *pcubMsgSize with the size of the next message, in bytes + virtual bool IsDataAvailableOnSocket( SNetSocket_t hSocket, uint32 *pcubMsgSize ) = 0; + + // fills in pubDest with the contents of the message + // messages are always complete, of the same size as was sent (i.e. packetized, not streaming) + // if *pcubMsgSize < cubDest, only partial data is written + // returns false if no data is available + virtual bool RetrieveDataFromSocket( SNetSocket_t hSocket, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize ) = 0; + + // checks for data from any socket that has been connected off this listen socket + // returns false if there is no data remaining + // fills out *pcubMsgSize with the size of the next message, in bytes + // fills out *phSocket with the socket that data is available on + virtual bool IsDataAvailable( SNetListenSocket_t hListenSocket, uint32 *pcubMsgSize, SNetSocket_t *phSocket ) = 0; + + // retrieves data from any socket that has been connected off this listen socket + // fills in pubDest with the contents of the message + // messages are always complete, of the same size as was sent (i.e. packetized, not streaming) + // if *pcubMsgSize < cubDest, only partial data is written + // returns false if no data is available + // fills out *phSocket with the socket that data is available on + virtual bool RetrieveData( SNetListenSocket_t hListenSocket, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize, SNetSocket_t *phSocket ) = 0; + + // returns information about the specified socket, filling out the contents of the pointers + virtual bool GetSocketInfo( SNetSocket_t hSocket, CSteamID *pSteamIDRemote, int *peSocketStatus, uint32 *punIPRemote, uint16 *punPortRemote ) = 0; + + // returns which local port the listen socket is bound to + // *pnIP and *pnPort will be 0 if the socket is set to listen for P2P connections only + virtual bool GetListenSocketInfo( SNetListenSocket_t hListenSocket, uint32 *pnIP, uint16 *pnPort ) = 0; + + // returns true to describe how the socket ended up connecting + virtual ESNetSocketConnectionType GetSocketConnectionType( SNetSocket_t hSocket ) = 0; + + // max packet size, in bytes + virtual int GetMaxPacketSize( SNetSocket_t hSocket ) = 0; +}; +#define STEAMNETWORKING_INTERFACE_VERSION "SteamNetworking005" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +// callback notification - a user wants to talk to us over the P2P channel via the SendP2PPacket() API +// in response, a call to AcceptP2PPacketsFromUser() needs to be made, if you want to talk with them +struct P2PSessionRequest_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 2 }; + CSteamID m_steamIDRemote; // user who wants to talk to us +}; + + +// callback notification - packets can't get through to the specified user via the SendP2PPacket() API +// all packets queued packets unsent at this point will be dropped +// further attempts to send will retry making the connection (but will be dropped if we fail again) +struct P2PSessionConnectFail_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 3 }; + CSteamID m_steamIDRemote; // user we were sending packets to + uint8 m_eP2PSessionError; // EP2PSessionError indicating why we're having trouble +}; + + +// callback notification - status of a socket has changed +// used as part of the CreateListenSocket() / CreateP2PConnectionSocket() +struct SocketStatusCallback_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 1 }; + SNetSocket_t m_hSocket; // the socket used to send/receive data to the remote host + SNetListenSocket_t m_hListenSocket; // this is the server socket that we were listening on; NULL if this was an outgoing connection + CSteamID m_steamIDRemote; // remote steamID we have connected to, if it has one + int m_eSNetSocketState; // socket state, ESNetSocketState +}; + +#pragma pack( pop ) + +#endif // ISTEAMNETWORKING diff --git a/dep/hlsdk/public/steam/isteamremotestorage.h b/dep/hlsdk/public/steam/isteamremotestorage.h new file mode 100644 index 0000000..68f0f7e --- /dev/null +++ b/dep/hlsdk/public/steam/isteamremotestorage.h @@ -0,0 +1,610 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: public interface to user remote file storage in Steam +// +//============================================================================= + +#ifndef ISTEAMREMOTESTORAGE_H +#define ISTEAMREMOTESTORAGE_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + + +//----------------------------------------------------------------------------- +// Purpose: Defines the largest allowed file size. Cloud files cannot be written +// in a single chunk over 100MB (and cannot be over 200MB total.) +//----------------------------------------------------------------------------- +const uint32 k_unMaxCloudFileChunkSize = 100 * 1024 * 1024; + + +//----------------------------------------------------------------------------- +// Purpose: Structure that contains an array of const char * strings and the number of those strings +//----------------------------------------------------------------------------- +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct SteamParamStringArray_t +{ + const char ** m_ppStrings; + int32 m_nNumStrings; +}; +#pragma pack( pop ) + +// A handle to a piece of user generated content +typedef uint64 UGCHandle_t; +typedef uint64 PublishedFileUpdateHandle_t; +typedef uint64 PublishedFileId_t; +const UGCHandle_t k_UGCHandleInvalid = 0xffffffffffffffffull; +const PublishedFileUpdateHandle_t k_PublishedFileUpdateHandleInvalid = 0xffffffffffffffffull; + +// Handle for writing to Steam Cloud +typedef uint64 UGCFileWriteStreamHandle_t; +const UGCFileWriteStreamHandle_t k_UGCFileStreamHandleInvalid = 0xffffffffffffffffull; + +const uint32 k_cchPublishedDocumentTitleMax = 128 + 1; +const uint32 k_cchPublishedDocumentDescriptionMax = 8000; +const uint32 k_cchPublishedDocumentChangeDescriptionMax = 8000; +const uint32 k_unEnumeratePublishedFilesMaxResults = 50; +const uint32 k_cchTagListMax = 1024 + 1; +const uint32 k_cchFilenameMax = 260; +const uint32 k_cchPublishedFileURLMax = 256; + +// Ways to handle a synchronization conflict +enum EResolveConflict +{ + k_EResolveConflictKeepClient = 1, // The local version of each file will be used to overwrite the server version + k_EResolveConflictKeepServer = 2, // The server version of each file will be used to overwrite the local version +}; + +enum ERemoteStoragePlatform +{ + k_ERemoteStoragePlatformNone = 0, + k_ERemoteStoragePlatformWindows = (1 << 0), + k_ERemoteStoragePlatformOSX = (1 << 1), + k_ERemoteStoragePlatformPS3 = (1 << 2), + k_ERemoteStoragePlatformLinux = (1 << 3), + k_ERemoteStoragePlatformReserved2 = (1 << 4), + + k_ERemoteStoragePlatformAll = 0xffffffff +}; + +enum ERemoteStoragePublishedFileVisibility +{ + k_ERemoteStoragePublishedFileVisibilityPublic = 0, + k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1, + k_ERemoteStoragePublishedFileVisibilityPrivate = 2, +}; + + +enum EWorkshopFileType +{ + k_EWorkshopFileTypeFirst = 0, + + k_EWorkshopFileTypeCommunity = 0, + k_EWorkshopFileTypeMicrotransaction = 1, + k_EWorkshopFileTypeCollection = 2, + k_EWorkshopFileTypeArt = 3, + k_EWorkshopFileTypeVideo = 4, + k_EWorkshopFileTypeScreenshot = 5, + k_EWorkshopFileTypeGame = 6, + k_EWorkshopFileTypeSoftware = 7, + k_EWorkshopFileTypeConcept = 8, + k_EWorkshopFileTypeWebGuide = 9, + k_EWorkshopFileTypeIntegratedGuide = 10, + k_EWorkshopFileTypeMerch = 11, + + // Update k_EWorkshopFileTypeMax if you add values + k_EWorkshopFileTypeMax = 12 + +}; + +enum EWorkshopVote +{ + k_EWorkshopVoteUnvoted = 0, + k_EWorkshopVoteFor = 1, + k_EWorkshopVoteAgainst = 2, +}; + +enum EWorkshopFileAction +{ + k_EWorkshopFileActionPlayed = 0, + k_EWorkshopFileActionCompleted = 1, +}; + +enum EWorkshopEnumerationType +{ + k_EWorkshopEnumerationTypeRankedByVote = 0, + k_EWorkshopEnumerationTypeRecent = 1, + k_EWorkshopEnumerationTypeTrending = 2, + k_EWorkshopEnumerationTypeFavoritesOfFriends = 3, + k_EWorkshopEnumerationTypeVotedByFriends = 4, + k_EWorkshopEnumerationTypeContentByFriends = 5, + k_EWorkshopEnumerationTypeRecentFromFollowedUsers = 6, +}; + +enum EWorkshopVideoProvider +{ + k_EWorkshopVideoProviderNone = 0, + k_EWorkshopVideoProviderYoutube = 1 +}; + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing, reading and writing files stored remotely +// and cached locally +//----------------------------------------------------------------------------- +class ISteamRemoteStorage +{ + public: + // NOTE + // + // Filenames are case-insensitive, and will be converted to lowercase automatically. + // So "foo.bar" and "Foo.bar" are the same file, and if you write "Foo.bar" then + // iterate the files, the filename returned will be "foo.bar". + // + + // file operations + virtual bool FileWrite( const char *pchFile, const void *pvData, int32 cubData ) = 0; + virtual int32 FileRead( const char *pchFile, void *pvData, int32 cubDataToRead ) = 0; + virtual bool FileForget( const char *pchFile ) = 0; + virtual bool FileDelete( const char *pchFile ) = 0; + virtual SteamAPICall_t FileShare( const char *pchFile ) = 0; + virtual bool SetSyncPlatforms( const char *pchFile, ERemoteStoragePlatform eRemoteStoragePlatform ) = 0; + + // file operations that cause network IO + virtual UGCFileWriteStreamHandle_t FileWriteStreamOpen( const char *pchFile ) = 0; + virtual bool FileWriteStreamWriteChunk( UGCFileWriteStreamHandle_t writeHandle, const void *pvData, int32 cubData ) = 0; + virtual bool FileWriteStreamClose( UGCFileWriteStreamHandle_t writeHandle ) = 0; + virtual bool FileWriteStreamCancel( UGCFileWriteStreamHandle_t writeHandle ) = 0; + + // file information + virtual bool FileExists( const char *pchFile ) = 0; + virtual bool FilePersisted( const char *pchFile ) = 0; + virtual int32 GetFileSize( const char *pchFile ) = 0; + virtual int64 GetFileTimestamp( const char *pchFile ) = 0; + virtual ERemoteStoragePlatform GetSyncPlatforms( const char *pchFile ) = 0; + + // iteration + virtual int32 GetFileCount() = 0; + virtual const char *GetFileNameAndSize( int iFile, int32 *pnFileSizeInBytes ) = 0; + + // configuration management + virtual bool GetQuota( int32 *pnTotalBytes, int32 *puAvailableBytes ) = 0; + virtual bool IsCloudEnabledForAccount() = 0; + virtual bool IsCloudEnabledForApp() = 0; + virtual void SetCloudEnabledForApp( bool bEnabled ) = 0; + + // user generated content + + // Downloads a UGC file. A priority value of 0 will download the file immediately, + // otherwise it will wait to download the file until all downloads with a lower priority + // value are completed. Downloads with equal priority will occur simultaneously. + virtual SteamAPICall_t UGCDownload( UGCHandle_t hContent, uint32 unPriority ) = 0; + + // Gets the amount of data downloaded so far for a piece of content. pnBytesExpected can be 0 if function returns false + // or if the transfer hasn't started yet, so be careful to check for that before dividing to get a percentage + virtual bool GetUGCDownloadProgress( UGCHandle_t hContent, int32 *pnBytesDownloaded, int32 *pnBytesExpected ) = 0; + + // Gets metadata for a file after it has been downloaded. This is the same metadata given in the RemoteStorageDownloadUGCResult_t call result + virtual bool GetUGCDetails( UGCHandle_t hContent, AppId_t *pnAppID, char **ppchName, int32 *pnFileSizeInBytes, CSteamID *pSteamIDOwner ) = 0; + + // After download, gets the content of the file. + // Small files can be read all at once by calling this function with an offset of 0 and cubDataToRead equal to the size of the file. + // Larger files can be read in chunks to reduce memory usage (since both sides of the IPC client and the game itself must allocate + // enough memory for each chunk). Once the last byte is read, the file is implicitly closed and further calls to UGCRead will fail + // unless UGCDownload is called again. + // For especially large files (anything over 100MB) it is a requirement that the file is read in chunks. + virtual int32 UGCRead( UGCHandle_t hContent, void *pvData, int32 cubDataToRead, uint32 cOffset ) = 0; + + // Functions to iterate through UGC that has finished downloading but has not yet been read via UGCRead() + virtual int32 GetCachedUGCCount() = 0; + virtual UGCHandle_t GetCachedUGCHandle( int32 iCachedContent ) = 0; + + // The following functions are only necessary on the Playstation 3. On PC & Mac, the Steam client will handle these operations for you + // On Playstation 3, the game controls which files are stored in the cloud, via FilePersist, FileFetch, and FileForget. + +#if defined(_PS3) || defined(_SERVER) + // Connect to Steam and get a list of files in the Cloud - results in a RemoteStorageAppSyncStatusCheck_t callback + virtual void GetFileListFromServer() = 0; + // Indicate this file should be downloaded in the next sync + virtual bool FileFetch( const char *pchFile ) = 0; + // Indicate this file should be persisted in the next sync + virtual bool FilePersist( const char *pchFile ) = 0; + // Pull any requested files down from the Cloud - results in a RemoteStorageAppSyncedClient_t callback + virtual bool SynchronizeToClient() = 0; + // Upload any requested files to the Cloud - results in a RemoteStorageAppSyncedServer_t callback + virtual bool SynchronizeToServer() = 0; + // Reset any fetch/persist/etc requests + virtual bool ResetFileRequestState() = 0; +#endif + + // publishing UGC + virtual SteamAPICall_t PublishWorkshopFile( const char *pchFile, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags, EWorkshopFileType eWorkshopFileType ) = 0; + virtual PublishedFileUpdateHandle_t CreatePublishedFileUpdateRequest( PublishedFileId_t unPublishedFileId ) = 0; + virtual bool UpdatePublishedFileFile( PublishedFileUpdateHandle_t updateHandle, const char *pchFile ) = 0; + virtual bool UpdatePublishedFilePreviewFile( PublishedFileUpdateHandle_t updateHandle, const char *pchPreviewFile ) = 0; + virtual bool UpdatePublishedFileTitle( PublishedFileUpdateHandle_t updateHandle, const char *pchTitle ) = 0; + virtual bool UpdatePublishedFileDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchDescription ) = 0; + virtual bool UpdatePublishedFileVisibility( PublishedFileUpdateHandle_t updateHandle, ERemoteStoragePublishedFileVisibility eVisibility ) = 0; + virtual bool UpdatePublishedFileTags( PublishedFileUpdateHandle_t updateHandle, SteamParamStringArray_t *pTags ) = 0; + virtual SteamAPICall_t CommitPublishedFileUpdate( PublishedFileUpdateHandle_t updateHandle ) = 0; + // Gets published file details for the given publishedfileid. If unMaxSecondsOld is greater than 0, + // cached data may be returned, depending on how long ago it was cached. A value of 0 will force a refresh, + // a value of -1 will use cached data if it exists, no matter how old it is. + virtual SteamAPICall_t GetPublishedFileDetails( PublishedFileId_t unPublishedFileId, uint32 unMaxSecondsOld ) = 0; + virtual SteamAPICall_t DeletePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + // enumerate the files that the current user published with this app + virtual SteamAPICall_t EnumerateUserPublishedFiles( uint32 unStartIndex ) = 0; + virtual SteamAPICall_t SubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t EnumerateUserSubscribedFiles( uint32 unStartIndex ) = 0; + virtual SteamAPICall_t UnsubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + virtual bool UpdatePublishedFileSetChangeDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchChangeDescription ) = 0; + virtual SteamAPICall_t GetPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t UpdateUserPublishedItemVote( PublishedFileId_t unPublishedFileId, bool bVoteUp ) = 0; + virtual SteamAPICall_t GetUserPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t EnumerateUserSharedWorkshopFiles( CSteamID steamId, uint32 unStartIndex, SteamParamStringArray_t *pRequiredTags, SteamParamStringArray_t *pExcludedTags ) = 0; + virtual SteamAPICall_t PublishVideo( EWorkshopVideoProvider eVideoProvider, const char *pchVideoAccount, const char *pchVideoIdentifier, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags ) = 0; + virtual SteamAPICall_t SetUserPublishedFileAction( PublishedFileId_t unPublishedFileId, EWorkshopFileAction eAction ) = 0; + virtual SteamAPICall_t EnumeratePublishedFilesByUserAction( EWorkshopFileAction eAction, uint32 unStartIndex ) = 0; + // this method enumerates the public view of workshop files + virtual SteamAPICall_t EnumeratePublishedWorkshopFiles( EWorkshopEnumerationType eEnumerationType, uint32 unStartIndex, uint32 unCount, uint32 unDays, SteamParamStringArray_t *pTags, SteamParamStringArray_t *pUserTags ) = 0; + + virtual SteamAPICall_t UGCDownloadToLocation( UGCHandle_t hContent, const char *pchLocation, uint32 unPriority ) = 0; +}; + +#define STEAMREMOTESTORAGE_INTERFACE_VERSION "STEAMREMOTESTORAGE_INTERFACE_VERSION011" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: sent when the local file cache is fully synced with the server for an app +// That means that an application can be started and has all latest files +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncedClient_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 1 }; + AppId_t m_nAppID; + EResult m_eResult; + int m_unNumDownloads; +}; + +//----------------------------------------------------------------------------- +// Purpose: sent when the server is fully synced with the local file cache for an app +// That means that we can shutdown Steam and our data is stored on the server +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncedServer_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 2 }; + AppId_t m_nAppID; + EResult m_eResult; + int m_unNumUploads; +}; + +//----------------------------------------------------------------------------- +// Purpose: Status of up and downloads during a sync session +// +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncProgress_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 3 }; + char m_rgchCurrentFile[k_cchFilenameMax]; // Current file being transferred + AppId_t m_nAppID; // App this info relates to + uint32 m_uBytesTransferredThisChunk; // Bytes transferred this chunk + double m_dAppPercentComplete; // Percent complete that this app's transfers are + bool m_bUploading; // if false, downloading +}; + +// +// IMPORTANT! k_iClientRemoteStorageCallbacks + 4 is used, see iclientremotestorage.h +// + + +//----------------------------------------------------------------------------- +// Purpose: Sent after we've determined the list of files that are out of sync +// with the server. +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncStatusCheck_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 5 }; + AppId_t m_nAppID; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: Sent after a conflict resolution attempt. +//----------------------------------------------------------------------------- +struct RemoteStorageConflictResolution_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 6 }; + AppId_t m_nAppID; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to FileShare() +//----------------------------------------------------------------------------- +struct RemoteStorageFileShareResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 7 }; + EResult m_eResult; // The result of the operation + UGCHandle_t m_hFile; // The handle that can be shared with users and features +}; + + +// k_iClientRemoteStorageCallbacks + 8 is deprecated! Do not reuse + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to PublishFile() +//----------------------------------------------------------------------------- +struct RemoteStoragePublishFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 9 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + bool m_bUserNeedsToAcceptWorkshopLegalAgreement; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to DeletePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageDeletePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 11 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to EnumerateUserPublishedFiles() +//----------------------------------------------------------------------------- +struct RemoteStorageEnumerateUserPublishedFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 12 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to SubscribePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageSubscribePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 13 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to EnumerateSubscribePublishedFiles() +//----------------------------------------------------------------------------- +struct RemoteStorageEnumerateUserSubscribedFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 14 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + uint32 m_rgRTimeSubscribed[ k_unEnumeratePublishedFilesMaxResults ]; +}; + +#if defined(VALVE_CALLBACK_PACK_SMALL) + VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 ); +#elif defined(VALVE_CALLBACK_PACK_LARGE) + VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 + 4 ); +#else +#warning You must first include isteamclient.h +#endif + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UnsubscribePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageUnsubscribePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 15 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to CommitPublishedFileUpdate() +//----------------------------------------------------------------------------- +struct RemoteStorageUpdatePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 16 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + bool m_bUserNeedsToAcceptWorkshopLegalAgreement; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UGCDownload() +//----------------------------------------------------------------------------- +struct RemoteStorageDownloadUGCResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 17 }; + EResult m_eResult; // The result of the operation. + UGCHandle_t m_hFile; // The handle to the file that was attempted to be downloaded. + AppId_t m_nAppID; // ID of the app that created this file. + int32 m_nSizeInBytes; // The size of the file that was downloaded, in bytes. + char m_pchFileName[k_cchFilenameMax]; // The name of the file that was downloaded. + uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to GetPublishedFileDetails() +//----------------------------------------------------------------------------- +struct RemoteStorageGetPublishedFileDetailsResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 18 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + AppId_t m_nCreatorAppID; // ID of the app that created this file. + AppId_t m_nConsumerAppID; // ID of the app that will consume this file. + char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document + char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document + UGCHandle_t m_hFile; // The handle of the primary file + UGCHandle_t m_hPreviewFile; // The handle of the preview file + uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. + uint32 m_rtimeCreated; // time when the published file was created + uint32 m_rtimeUpdated; // time when the published file was last updated + ERemoteStoragePublishedFileVisibility m_eVisibility; + bool m_bBanned; + char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file + bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer + char m_pchFileName[k_cchFilenameMax]; // The name of the primary file + int32 m_nFileSize; // Size of the primary file + int32 m_nPreviewFileSize; // Size of the preview file + char m_rgchURL[k_cchPublishedFileURLMax]; // URL (for a video or a website) + EWorkshopFileType m_eFileType; // Type of the file +}; + + +struct RemoteStorageEnumerateWorkshopFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 19 }; + EResult m_eResult; + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + float m_rgScore[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of GetPublishedItemVoteDetails +//----------------------------------------------------------------------------- +struct RemoteStorageGetPublishedItemVoteDetailsResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 20 }; + EResult m_eResult; + PublishedFileId_t m_unPublishedFileId; + int32 m_nVotesFor; + int32 m_nVotesAgainst; + int32 m_nReports; + float m_fScore; +}; + + +//----------------------------------------------------------------------------- +// Purpose: User subscribed to a file for the app (from within the app or on the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileSubscribed_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 21 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + +//----------------------------------------------------------------------------- +// Purpose: User unsubscribed from a file for the app (from within the app or on the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileUnsubscribed_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 22 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + + +//----------------------------------------------------------------------------- +// Purpose: Published file that a user owns was deleted (from within the app or the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileDeleted_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 23 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UpdateUserPublishedItemVote() +//----------------------------------------------------------------------------- +struct RemoteStorageUpdateUserPublishedItemVoteResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 24 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to GetUserPublishedItemVoteDetails() +//----------------------------------------------------------------------------- +struct RemoteStorageUserVoteDetails_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 25 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id + EWorkshopVote m_eVote; // what the user voted +}; + +struct RemoteStorageEnumerateUserSharedWorkshopFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 26 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; +}; + +struct RemoteStorageSetUserPublishedFileActionResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 27 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id + EWorkshopFileAction m_eAction; // the action that was attempted +}; + +struct RemoteStorageEnumeratePublishedFilesByUserActionResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 28 }; + EResult m_eResult; // The result of the operation. + EWorkshopFileAction m_eAction; // the action that was filtered on + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + uint32 m_rgRTimeUpdated[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Called periodically while a PublishWorkshopFile is in progress +//----------------------------------------------------------------------------- +struct RemoteStoragePublishFileProgress_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 29 }; + double m_dPercentFile; + bool m_bPreview; +}; + + + +#pragma pack( pop ) + + +#endif // ISTEAMREMOTESTORAGE_H diff --git a/dep/hlsdk/public/steam/isteamscreenshots.h b/dep/hlsdk/public/steam/isteamscreenshots.h new file mode 100644 index 0000000..1636c16 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamscreenshots.h @@ -0,0 +1,96 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: public interface to user remote file storage in Steam +// +//============================================================================= + +#ifndef ISTEAMSCREENSHOTS_H +#define ISTEAMSCREENSHOTS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +const uint32 k_nScreenshotMaxTaggedUsers = 32; +const uint32 k_nScreenshotMaxTaggedPublishedFiles = 32; +const int k_cubUFSTagTypeMax = 255; +const int k_cubUFSTagValueMax = 255; + +// Required with of a thumbnail provided to AddScreenshotToLibrary. If you do not provide a thumbnail +// one will be generated. +const int k_ScreenshotThumbWidth = 200; + +// Handle is valid for the lifetime of your process and no longer +typedef uint32 ScreenshotHandle; +#define INVALID_SCREENSHOT_HANDLE 0 + +//----------------------------------------------------------------------------- +// Purpose: Functions for adding screenshots to the user's screenshot library +//----------------------------------------------------------------------------- +class ISteamScreenshots +{ +public: + // Writes a screenshot to the user's screenshot library given the raw image data, which must be in RGB format. + // The return value is a handle that is valid for the duration of the game process and can be used to apply tags. + virtual ScreenshotHandle WriteScreenshot( void *pubRGB, uint32 cubRGB, int nWidth, int nHeight ) = 0; + + // Adds a screenshot to the user's screenshot library from disk. If a thumbnail is provided, it must be 200 pixels wide and the same aspect ratio + // as the screenshot, otherwise a thumbnail will be generated if the user uploads the screenshot. The screenshots must be in either JPEG or TGA format. + // The return value is a handle that is valid for the duration of the game process and can be used to apply tags. + // JPEG, TGA, and PNG formats are supported. + virtual ScreenshotHandle AddScreenshotToLibrary( const char *pchFilename, const char *pchThumbnailFilename, int nWidth, int nHeight ) = 0; + + // Causes the Steam overlay to take a screenshot. If screenshots are being hooked by the game then a ScreenshotRequested_t callback is sent back to the game instead. + virtual void TriggerScreenshot() = 0; + + // Toggles whether the overlay handles screenshots when the user presses the screenshot hotkey, or the game handles them. If the game is hooking screenshots, + // then the ScreenshotRequested_t callback will be sent if the user presses the hotkey, and the game is expected to call WriteScreenshot or AddScreenshotToLibrary + // in response. + virtual void HookScreenshots( bool bHook ) = 0; + + // Sets metadata about a screenshot's location (for example, the name of the map) + virtual bool SetLocation( ScreenshotHandle hScreenshot, const char *pchLocation ) = 0; + + // Tags a user as being visible in the screenshot + virtual bool TagUser( ScreenshotHandle hScreenshot, CSteamID steamID ) = 0; + + // Tags a published file as being visible in the screenshot + virtual bool TagPublishedFile( ScreenshotHandle hScreenshot, PublishedFileId_t unPublishedFileID ) = 0; +}; + +#define STEAMSCREENSHOTS_INTERFACE_VERSION "STEAMSCREENSHOTS_INTERFACE_VERSION002" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +//----------------------------------------------------------------------------- +// Purpose: Screenshot successfully written or otherwise added to the library +// and can now be tagged +//----------------------------------------------------------------------------- +struct ScreenshotReady_t +{ + enum { k_iCallback = k_iSteamScreenshotsCallbacks + 1 }; + ScreenshotHandle m_hLocal; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: Screenshot has been requested by the user. Only sent if +// HookScreenshots() has been called, in which case Steam will not take +// the screenshot itself. +//----------------------------------------------------------------------------- +struct ScreenshotRequested_t +{ + enum { k_iCallback = k_iSteamScreenshotsCallbacks + 2 }; +}; + +#pragma pack( pop ) + + +#endif // ISTEAMSCREENSHOTS_H diff --git a/dep/hlsdk/public/steam/isteamunifiedmessages.h b/dep/hlsdk/public/steam/isteamunifiedmessages.h new file mode 100644 index 0000000..edee4a4 --- /dev/null +++ b/dep/hlsdk/public/steam/isteamunifiedmessages.h @@ -0,0 +1,63 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: Interface to unified messages client +// +// You should not need to use this interface except if your product is using a language other than C++. +// Contact your Steam Tech contact for more details. +// +//============================================================================= + +#ifndef ISTEAMUNIFIEDMESSAGES_H +#define ISTEAMUNIFIEDMESSAGES_H +#ifdef _WIN32 +#pragma once +#endif + +typedef uint64 ClientUnifiedMessageHandle; + +class ISteamUnifiedMessages +{ +public: + static const ClientUnifiedMessageHandle k_InvalidUnifiedMessageHandle = 0; + + // Sends a service method (in binary serialized form) using the Steam Client. + // Returns a unified message handle (k_InvalidUnifiedMessageHandle if could not send the message). + virtual ClientUnifiedMessageHandle SendMethod( const char *pchServiceMethod, const void *pRequestBuffer, uint32 unRequestBufferSize, uint64 unContext ) = 0; + + // Gets the size of the response and the EResult. Returns false if the response is not ready yet. + virtual bool GetMethodResponseInfo( ClientUnifiedMessageHandle hHandle, uint32 *punResponseSize, EResult *peResult ) = 0; + + // Gets a response in binary serialized form (and optionally release the corresponding allocated memory). + virtual bool GetMethodResponseData( ClientUnifiedMessageHandle hHandle, void *pResponseBuffer, uint32 unResponseBufferSize, bool bAutoRelease ) = 0; + + // Releases the message and its corresponding allocated memory. + virtual bool ReleaseMethod( ClientUnifiedMessageHandle hHandle ) = 0; + + // Sends a service notification (in binary serialized form) using the Steam Client. + // Returns true if the notification was sent successfully. + virtual bool SendNotification( const char *pchServiceNotification, const void *pNotificationBuffer, uint32 unNotificationBufferSize ) = 0; +}; + +#define STEAMUNIFIEDMESSAGES_INTERFACE_VERSION "STEAMUNIFIEDMESSAGES_INTERFACE_VERSION001" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct SteamUnifiedMessagesSendMethodResult_t +{ + enum { k_iCallback = k_iClientUnifiedMessagesCallbacks + 1 }; + ClientUnifiedMessageHandle m_hHandle; // The handle returned by SendMethod(). + uint64 m_unContext; // Context provided when calling SendMethod(). + EResult m_eResult; // The result of the method call. + uint32 m_unResponseSize; // The size of the response. +}; + +#pragma pack( pop ) + +#endif // ISTEAMUNIFIEDMESSAGES_H diff --git a/dep/hlsdk/public/steam/isteamuser.h b/dep/hlsdk/public/steam/isteamuser.h new file mode 100644 index 0000000..5470acb --- /dev/null +++ b/dep/hlsdk/public/steam/isteamuser.h @@ -0,0 +1,339 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to user account information in Steam +// +//============================================================================= + +#ifndef ISTEAMUSER_H +#define ISTEAMUSER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +// structure that contains client callback data +// see callbacks documentation for more details +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct CallbackMsg_t +{ + HSteamUser m_hSteamUser; + int m_iCallback; + uint8 *m_pubParam; + int m_cubParam; +}; +#pragma pack( pop ) + +// reference to a steam call, to filter results by +typedef int32 HSteamCall; + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing and manipulating a steam account +// associated with one client instance +//----------------------------------------------------------------------------- +class ISteamUser +{ +public: + // returns the HSteamUser this interface represents + // this is only used internally by the API, and by a few select interfaces that support multi-user + virtual HSteamUser GetHSteamUser() = 0; + + // returns true if the Steam client current has a live connection to the Steam servers. + // If false, it means there is no active connection due to either a networking issue on the local machine, or the Steam server is down/busy. + // The Steam client will automatically be trying to recreate the connection as often as possible. + virtual bool BLoggedOn() = 0; + + // returns the CSteamID of the account currently logged into the Steam client + // a CSteamID is a unique identifier for an account, and used to differentiate users in all parts of the Steamworks API + virtual CSteamID GetSteamID() = 0; + + // Multiplayer Authentication functions + + // InitiateGameConnection() starts the state machine for authenticating the game client with the game server + // It is the client portion of a three-way handshake between the client, the game server, and the steam servers + // + // Parameters: + // void *pAuthBlob - a pointer to empty memory that will be filled in with the authentication token. + // int cbMaxAuthBlob - the number of bytes of allocated memory in pBlob. Should be at least 2048 bytes. + // CSteamID steamIDGameServer - the steamID of the game server, received from the game server by the client + // CGameID gameID - the ID of the current game. For games without mods, this is just CGameID( ) + // uint32 unIPServer, uint16 usPortServer - the IP address of the game server + // bool bSecure - whether or not the client thinks that the game server is reporting itself as secure (i.e. VAC is running) + // + // return value - returns the number of bytes written to pBlob. If the return is 0, then the buffer passed in was too small, and the call has failed + // The contents of pBlob should then be sent to the game server, for it to use to complete the authentication process. + virtual int InitiateGameConnection( void *pAuthBlob, int cbMaxAuthBlob, CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer, bool bSecure ) = 0; + + // notify of disconnect + // needs to occur when the game client leaves the specified game server, needs to match with the InitiateGameConnection() call + virtual void TerminateGameConnection( uint32 unIPServer, uint16 usPortServer ) = 0; + + // Legacy functions + + // used by only a few games to track usage events + virtual void TrackAppUsageEvent( CGameID gameID, int eAppUsageEvent, const char *pchExtraInfo = "" ) = 0; + + // get the local storage folder for current Steam account to write application data, e.g. save games, configs etc. + // this will usually be something like "C:\Progam Files\Steam\userdata\\\local" + virtual bool GetUserDataFolder( char *pchBuffer, int cubBuffer ) = 0; + + // Starts voice recording. Once started, use GetVoice() to get the data + virtual void StartVoiceRecording( ) = 0; + + // Stops voice recording. Because people often release push-to-talk keys early, the system will keep recording for + // a little bit after this function is called. GetVoice() should continue to be called until it returns + // k_eVoiceResultNotRecording + virtual void StopVoiceRecording( ) = 0; + + // Determine the amount of captured audio data that is available in bytes. + // This provides both the compressed and uncompressed data. Please note that the uncompressed + // data is not the raw feed from the microphone: data may only be available if audible + // levels of speech are detected. + // nUncompressedVoiceDesiredSampleRate is necessary to know the number of bytes to return in pcbUncompressed - can be set to 0 if you don't need uncompressed (the usual case) + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nUncompressedVoiceDesiredSampleRate + virtual EVoiceResult GetAvailableVoice(uint32 *pcbCompressed, uint32 *pcbUncompressed, uint32 nUncompressedVoiceDesiredSampleRate) = 0; + + // Gets the latest voice data from the microphone. Compressed data is an arbitrary format, and is meant to be handed back to + // DecompressVoice() for playback later as a binary blob. Uncompressed data is 16-bit, signed integer, 11025Hz PCM format. + // Please note that the uncompressed data is not the raw feed from the microphone: data may only be available if audible + // levels of speech are detected, and may have passed through denoising filters, etc. + // This function should be called as often as possible once recording has started; once per frame at least. + // nBytesWritten is set to the number of bytes written to pDestBuffer. + // nUncompressedBytesWritten is set to the number of bytes written to pUncompressedDestBuffer. + // You must grab both compressed and uncompressed here at the same time, if you want both. + // Matching data that is not read during this call will be thrown away. + // GetAvailableVoice() can be used to determine how much data is actually available. + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nUncompressedVoiceDesiredSampleRate + virtual EVoiceResult GetVoice( bool bWantCompressed, void *pDestBuffer, uint32 cbDestBufferSize, uint32 *nBytesWritten, bool bWantUncompressed, void *pUncompressedDestBuffer, uint32 cbUncompressedDestBufferSize, uint32 *nUncompressBytesWritten, uint32 nUncompressedVoiceDesiredSampleRate ) = 0; + + // Decompresses a chunk of compressed data produced by GetVoice(). + // nBytesWritten is set to the number of bytes written to pDestBuffer unless the return value is k_EVoiceResultBufferTooSmall. + // In that case, nBytesWritten is set to the size of the buffer required to decompress the given + // data. The suggested buffer size for the destination buffer is 22 kilobytes. + // The output format of the data is 16-bit signed at the requested samples per second. + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nDesiredSampleRate + virtual EVoiceResult DecompressVoice( const void *pCompressed, uint32 cbCompressed, void *pDestBuffer, uint32 cbDestBufferSize, uint32 *nBytesWritten, uint32 nDesiredSampleRate ) = 0; + + // This returns the frequency of the voice data as it's stored internally; calling DecompressVoice() with this size will yield the best results + virtual uint32 GetVoiceOptimalSampleRate() = 0; + + // Retrieve ticket to be sent to the entity who wishes to authenticate you. + // pcbTicket retrieves the length of the actual ticket. + virtual HAuthTicket GetAuthSessionTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + + // Authenticate ticket from entity steamID to be sure it is valid and isnt reused + // Registers for callbacks if the entity goes offline or cancels the ticket ( see ValidateAuthTicketResponse_t callback and EAuthSessionResponse ) + virtual EBeginAuthSessionResult BeginAuthSession( const void *pAuthTicket, int cbAuthTicket, CSteamID steamID ) = 0; + + // Stop tracking started by BeginAuthSession - called when no longer playing game with this entity + virtual void EndAuthSession( CSteamID steamID ) = 0; + + // Cancel auth ticket from GetAuthSessionTicket, called when no longer playing game with the entity you gave the ticket to + virtual void CancelAuthTicket( HAuthTicket hAuthTicket ) = 0; + + // After receiving a user's authentication data, and passing it to BeginAuthSession, use this function + // to determine if the user owns downloadable content specified by the provided AppID. + virtual EUserHasLicenseForAppResult UserHasLicenseForApp( CSteamID steamID, AppId_t appID ) = 0; + + // returns true if this users looks like they are behind a NAT device. Only valid once the user has connected to steam + // (i.e a SteamServersConnected_t has been issued) and may not catch all forms of NAT. + virtual bool BIsBehindNAT() = 0; + + // set data to be replicated to friends so that they can join your game + // CSteamID steamIDGameServer - the steamID of the game server, received from the game server by the client + // uint32 unIPServer, uint16 usPortServer - the IP address of the game server + virtual void AdvertiseGame( CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer ) = 0; + + // Requests a ticket encrypted with an app specific shared key + // pDataToInclude, cbDataToInclude will be encrypted into the ticket + // ( This is asynchronous, you must wait for the ticket to be completed by the server ) + virtual SteamAPICall_t RequestEncryptedAppTicket( void *pDataToInclude, int cbDataToInclude ) = 0; + + // retrieve a finished ticket + virtual bool GetEncryptedAppTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + +#ifdef _PS3 + // Initiates PS3 Logon request using just PSN ticket. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. + // + // Listen for SteamServersConnected_t or SteamServerConnectFailure_t for status. SteamServerConnectFailure_t + // may return with EResult k_EResultExternalAccountUnlinked if the PSN account is unknown to Steam. You should + // then call LogOnAndLinkSteamAccountToPSN() after prompting the user for credentials to establish a link. + // Future calls to LogOn() after the one time link call should succeed as long as the user is connected to PSN. + virtual void LogOn( bool bInteractive ) = 0; + + // Initiates a request to logon with a specific steam username/password and create a PSN account link at + // the same time. Should call this only if LogOn() has failed and indicated the PSN account is unlinked. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. pchUserName + // should be the users Steam username, and pchPassword should be the users Steam password. + // + // Listen for SteamServersConnected_t or SteamServerConnectFailure_t for status. SteamServerConnectFailure_t + // may return with EResult k_EResultOtherAccountAlreadyLinked if already linked to another account. + virtual void LogOnAndLinkSteamAccountToPSN( bool bInteractive, const char *pchUserName, const char *pchPassword ) = 0; + + // Final logon option for PS3, this logs into an existing account if already linked, but if not already linked + // creates a new account using the info in the PSN ticket to generate a unique account name. The new account is + // then linked to the PSN ticket. This is the faster option for new users who don't have an existing Steam account + // to get into multiplayer. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. + virtual void LogOnAndCreateNewSteamAccountIfNeeded( bool bInteractive ) = 0; + + // Returns a special SteamID that represents the user's PSN information. Can be used to query the user's PSN avatar, + // online name, etc. through the standard Steamworks interfaces. + virtual CSteamID GetConsoleSteamID() = 0; +#endif + +}; + +#define STEAMUSER_INTERFACE_VERSION "SteamUser016" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when a connections to the Steam back-end has been established +// this means the Steam client now has a working connection to the Steam servers +// usually this will have occurred before the game has launched, and should +// only be seen if the user has dropped connection due to a networking issue +// or a Steam server update +//----------------------------------------------------------------------------- +struct SteamServersConnected_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 1 }; +}; + +//----------------------------------------------------------------------------- +// Purpose: called when a connection attempt has failed +// this will occur periodically if the Steam client is not connected, +// and has failed in it's retry to establish a connection +//----------------------------------------------------------------------------- +struct SteamServerConnectFailure_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 2 }; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called if the client has lost connection to the Steam servers +// real-time services will be disabled until a matching SteamServersConnected_t has been posted +//----------------------------------------------------------------------------- +struct SteamServersDisconnected_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 3 }; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Sent by the Steam server to the client telling it to disconnect from the specified game server, +// which it may be in the process of or already connected to. +// The game client should immediately disconnect upon receiving this message. +// This can usually occur if the user doesn't have rights to play on the game server. +//----------------------------------------------------------------------------- +struct ClientGameServerDeny_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 13 }; + + uint32 m_uAppID; + uint32 m_unGameServerIP; + uint16 m_usGameServerPort; + uint16 m_bSecure; + uint32 m_uReason; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the callback system for this client is in an error state (and has flushed pending callbacks) +// When getting this message the client should disconnect from Steam, reset any stored Steam state and reconnect. +// This usually occurs in the rare event the Steam client has some kind of fatal error. +//----------------------------------------------------------------------------- +struct IPCFailure_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 17 }; + enum EFailureType + { + k_EFailureFlushedCallbackQueue, + k_EFailurePipeFail, + }; + uint8 m_eFailureType; +}; + + +//----------------------------------------------------------------------------- +// callback for BeginAuthSession +//----------------------------------------------------------------------------- +struct ValidateAuthTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 43 }; + CSteamID m_SteamID; + EAuthSessionResponse m_eAuthSessionResponse; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when a user has responded to a microtransaction authorization request +//----------------------------------------------------------------------------- +struct MicroTxnAuthorizationResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 52 }; + + uint32 m_unAppID; // AppID for this microtransaction + uint64 m_ulOrderID; // OrderID provided for the microtransaction + uint8 m_bAuthorized; // if user authorized transaction +}; + + +//----------------------------------------------------------------------------- +// Purpose: Result from RequestEncryptedAppTicket +//----------------------------------------------------------------------------- +struct EncryptedAppTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 54 }; + + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// callback for GetAuthSessionTicket +//----------------------------------------------------------------------------- +struct GetAuthSessionTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 63 }; + HAuthTicket m_hAuthTicket; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: sent to your game in response to a steam://gamewebcallback/ command +//----------------------------------------------------------------------------- +struct GameWebCallback_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 64 }; + char m_szURL[256]; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMUSER_H diff --git a/dep/hlsdk/public/steam/isteamuserstats.h b/dep/hlsdk/public/steam/isteamuserstats.h new file mode 100644 index 0000000..c5847cf --- /dev/null +++ b/dep/hlsdk/public/steam/isteamuserstats.h @@ -0,0 +1,463 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to stats, achievements, and leaderboards +// +//============================================================================= + +#ifndef ISTEAMUSERSTATS_H +#define ISTEAMUSERSTATS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "isteamremotestorage.h" + +// size limit on stat or achievement name (UTF-8 encoded) +enum { k_cchStatNameMax = 128 }; + +// maximum number of bytes for a leaderboard name (UTF-8 encoded) +enum { k_cchLeaderboardNameMax = 128 }; + +// maximum number of details int32's storable for a single leaderboard entry +enum { k_cLeaderboardDetailsMax = 64 }; + +// handle to a single leaderboard +typedef uint64 SteamLeaderboard_t; + +// handle to a set of downloaded entries in a leaderboard +typedef uint64 SteamLeaderboardEntries_t; + +// type of data request, when downloading leaderboard entries +enum ELeaderboardDataRequest +{ + k_ELeaderboardDataRequestGlobal = 0, + k_ELeaderboardDataRequestGlobalAroundUser = 1, + k_ELeaderboardDataRequestFriends = 2, + k_ELeaderboardDataRequestUsers = 3 +}; + +// the sort order of a leaderboard +enum ELeaderboardSortMethod +{ + k_ELeaderboardSortMethodNone = 0, + k_ELeaderboardSortMethodAscending = 1, // top-score is lowest number + k_ELeaderboardSortMethodDescending = 2, // top-score is highest number +}; + +// the display type (used by the Steam Community web site) for a leaderboard +enum ELeaderboardDisplayType +{ + k_ELeaderboardDisplayTypeNone = 0, + k_ELeaderboardDisplayTypeNumeric = 1, // simple numerical score + k_ELeaderboardDisplayTypeTimeSeconds = 2, // the score represents a time, in seconds + k_ELeaderboardDisplayTypeTimeMilliSeconds = 3, // the score represents a time, in milliseconds +}; + +enum ELeaderboardUploadScoreMethod +{ + k_ELeaderboardUploadScoreMethodNone = 0, + k_ELeaderboardUploadScoreMethodKeepBest = 1, // Leaderboard will keep user's best score + k_ELeaderboardUploadScoreMethodForceUpdate = 2, // Leaderboard will always replace score with specified +}; + +// a single entry in a leaderboard, as returned by GetDownloadedLeaderboardEntry() +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct LeaderboardEntry_t +{ + CSteamID m_steamIDUser; // user with the entry - use SteamFriends()->GetFriendPersonaName() & SteamFriends()->GetFriendAvatar() to get more info + int32 m_nGlobalRank; // [1..N], where N is the number of users with an entry in the leaderboard + int32 m_nScore; // score as set in the leaderboard + int32 m_cDetails; // number of int32 details available for this entry + UGCHandle_t m_hUGC; // handle for UGC attached to the entry +}; + +#pragma pack( pop ) + + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing stats, achievements, and leaderboard information +//----------------------------------------------------------------------------- +class ISteamUserStats +{ +public: + // Ask the server to send down this user's data and achievements for this game + virtual bool RequestCurrentStats() = 0; + + // Data accessors + virtual bool GetStat( const char *pchName, int32 *pData ) = 0; + virtual bool GetStat( const char *pchName, float *pData ) = 0; + + // Set / update data + virtual bool SetStat( const char *pchName, int32 nData ) = 0; + virtual bool SetStat( const char *pchName, float fData ) = 0; + virtual bool UpdateAvgRateStat( const char *pchName, float flCountThisSession, double dSessionLength ) = 0; + + // Achievement flag accessors + virtual bool GetAchievement( const char *pchName, bool *pbAchieved ) = 0; + virtual bool SetAchievement( const char *pchName ) = 0; + virtual bool ClearAchievement( const char *pchName ) = 0; + + // Get the achievement status, and the time it was unlocked if unlocked. + // If the return value is true, but the unlock time is zero, that means it was unlocked before Steam + // began tracking achievement unlock times (December 2009). Time is seconds since January 1, 1970. + virtual bool GetAchievementAndUnlockTime( const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; + + // Store the current data on the server, will get a callback when set + // And one callback for every new achievement + // + // If the callback has a result of k_EResultInvalidParam, one or more stats + // uploaded has been rejected, either because they broke constraints + // or were out of date. In this case the server sends back updated values. + // The stats should be re-iterated to keep in sync. + virtual bool StoreStats() = 0; + + // Achievement / GroupAchievement metadata + + // Gets the icon of the achievement, which is a handle to be used in ISteamUtils::GetImageRGBA(), or 0 if none set. + // A return value of 0 may indicate we are still fetching data, and you can wait for the UserAchievementIconFetched_t callback + // which will notify you when the bits are ready. If the callback still returns zero, then there is no image set for the + // specified achievement. + virtual int GetAchievementIcon( const char *pchName ) = 0; + + // Get general attributes for an achievement. Accepts the following keys: + // - "name" and "desc" for retrieving the localized achievement name and description (returned in UTF8) + // - "hidden" for retrieving if an achievement is hidden (returns "0" when not hidden, "1" when hidden) + virtual const char *GetAchievementDisplayAttribute( const char *pchName, const char *pchKey ) = 0; + + // Achievement progress - triggers an AchievementProgress callback, that is all. + // Calling this w/ N out of N progress will NOT set the achievement, the game must still do that. + virtual bool IndicateAchievementProgress( const char *pchName, uint32 nCurProgress, uint32 nMaxProgress ) = 0; + + // Used for iterating achievements. In general games should not need these functions because they should have a + // list of existing achievements compiled into them + virtual uint32 GetNumAchievements() = 0; + // Get achievement name iAchievement in [0,GetNumAchievements) + virtual const char *GetAchievementName( uint32 iAchievement ) = 0; + + // Friends stats & achievements + + // downloads stats for the user + // returns a UserStatsReceived_t received when completed + // if the other user has no stats, UserStatsReceived_t.m_eResult will be set to k_EResultFail + // these stats won't be auto-updated; you'll need to call RequestUserStats() again to refresh any data + virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; + + // requests stat information for a user, usable after a successful call to RequestUserStats() + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; + virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; + // See notes for GetAchievementAndUnlockTime above + virtual bool GetUserAchievementAndUnlockTime( CSteamID steamIDUser, const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; + + // Reset stats + virtual bool ResetAllStats( bool bAchievementsToo ) = 0; + + // Leaderboard functions + + // asks the Steam back-end for a leaderboard by name, and will create it if it's not yet + // This call is asynchronous, with the result returned in LeaderboardFindResult_t + virtual SteamAPICall_t FindOrCreateLeaderboard( const char *pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType ) = 0; + + // as above, but won't create the leaderboard if it's not found + // This call is asynchronous, with the result returned in LeaderboardFindResult_t + virtual SteamAPICall_t FindLeaderboard( const char *pchLeaderboardName ) = 0; + + // returns the name of a leaderboard + virtual const char *GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the total number of entries in a leaderboard, as of the last request + virtual int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the sort method of the leaderboard + virtual ELeaderboardSortMethod GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the display type of the leaderboard + virtual ELeaderboardDisplayType GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // Asks the Steam back-end for a set of rows in the leaderboard. + // This call is asynchronous, with the result returned in LeaderboardScoresDownloaded_t + // LeaderboardScoresDownloaded_t will contain a handle to pull the results from GetDownloadedLeaderboardEntries() (below) + // You can ask for more entries than exist, and it will return as many as do exist. + // k_ELeaderboardDataRequestGlobal requests rows in the leaderboard from the full table, with nRangeStart & nRangeEnd in the range [1, TotalEntries] + // k_ELeaderboardDataRequestGlobalAroundUser requests rows around the current user, nRangeStart being negate + // e.g. DownloadLeaderboardEntries( hLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -3, 3 ) will return 7 rows, 3 before the user, 3 after + // k_ELeaderboardDataRequestFriends requests all the rows for friends of the current user + virtual SteamAPICall_t DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) = 0; + // as above, but downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers + // if a user doesn't have a leaderboard entry, they won't be included in the result + // a max of 100 users can be downloaded at a time, with only one outstanding call at a time + virtual SteamAPICall_t DownloadLeaderboardEntriesForUsers( SteamLeaderboard_t hSteamLeaderboard, CSteamID *prgUsers, int cUsers ) = 0; + + // Returns data about a single leaderboard entry + // use a for loop from 0 to LeaderboardScoresDownloaded_t::m_cEntryCount to get all the downloaded entries + // e.g. + // void OnLeaderboardScoresDownloaded( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded ) + // { + // for ( int index = 0; index < pLeaderboardScoresDownloaded->m_cEntryCount; index++ ) + // { + // LeaderboardEntry_t leaderboardEntry; + // int32 details[3]; // we know this is how many we've stored previously + // GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries, index, &leaderboardEntry, details, 3 ); + // assert( leaderboardEntry.m_cDetails == 3 ); + // ... + // } + // once you've accessed all the entries, the data will be free'd, and the SteamLeaderboardEntries_t handle will become invalid + virtual bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry_t *pLeaderboardEntry, int32 *pDetails, int cDetailsMax ) = 0; + + // Uploads a user score to the Steam back-end. + // This call is asynchronous, with the result returned in LeaderboardScoreUploaded_t + // Details are extra game-defined information regarding how the user got that score + // pScoreDetails points to an array of int32's, cScoreDetailsCount is the number of int32's in the list + virtual SteamAPICall_t UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int32 nScore, const int32 *pScoreDetails, int cScoreDetailsCount ) = 0; + + // Attaches a piece of user generated content the user's entry on a leaderboard. + // hContent is a handle to a piece of user generated content that was shared using ISteamUserRemoteStorage::FileShare(). + // This call is asynchronous, with the result returned in LeaderboardUGCSet_t. + virtual SteamAPICall_t AttachLeaderboardUGC( SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ) = 0; + + // Retrieves the number of players currently playing your game (online + offline) + // This call is asynchronous, with the result returned in NumberOfCurrentPlayers_t + virtual SteamAPICall_t GetNumberOfCurrentPlayers() = 0; + + // Requests that Steam fetch data on the percentage of players who have received each achievement + // for the game globally. + // This call is asynchronous, with the result returned in GlobalAchievementPercentagesReady_t. + virtual SteamAPICall_t RequestGlobalAchievementPercentages() = 0; + + // Get the info on the most achieved achievement for the game, returns an iterator index you can use to fetch + // the next most achieved afterwards. Will return -1 if there is no data on achievement + // percentages (ie, you haven't called RequestGlobalAchievementPercentages and waited on the callback). + virtual int GetMostAchievedAchievementInfo( char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; + + // Get the info on the next most achieved achievement for the game. Call this after GetMostAchievedAchievementInfo or another + // GetNextMostAchievedAchievementInfo call passing the iterator from the previous call. Returns -1 after the last + // achievement has been iterated. + virtual int GetNextMostAchievedAchievementInfo( int iIteratorPrevious, char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; + + // Returns the percentage of users who have achieved the specified achievement. + virtual bool GetAchievementAchievedPercent( const char *pchName, float *pflPercent ) = 0; + + // Requests global stats data, which is available for stats marked as "aggregated". + // This call is asynchronous, with the results returned in GlobalStatsReceived_t. + // nHistoryDays specifies how many days of day-by-day history to retrieve in addition + // to the overall totals. The limit is 60. + virtual SteamAPICall_t RequestGlobalStats( int nHistoryDays ) = 0; + + // Gets the lifetime totals for an aggregated stat + virtual bool GetGlobalStat( const char *pchStatName, int64 *pData ) = 0; + virtual bool GetGlobalStat( const char *pchStatName, double *pData ) = 0; + + // Gets history for an aggregated stat. pData will be filled with daily values, starting with today. + // So when called, pData[0] will be today, pData[1] will be yesterday, and pData[2] will be two days ago, + // etc. cubData is the size in bytes of the pubData buffer. Returns the number of + // elements actually set. + virtual int32 GetGlobalStatHistory( const char *pchStatName, int64 *pData, uint32 cubData ) = 0; + virtual int32 GetGlobalStatHistory( const char *pchStatName, double *pData, uint32 cubData ) = 0; + +#ifdef _PS3 + // Call to kick off installation of the PS3 trophies. This call is asynchronous, and the results will be returned in a PS3TrophiesInstalled_t + // callback. + virtual bool InstallPS3Trophies() = 0; + + // Returns the amount of space required at boot to install trophies. This value can be used when comparing the amount of space needed + // by the game to the available space value passed to the game at boot. The value is set during InstallPS3Trophies(). + virtual uint64 GetTrophySpaceRequiredBeforeInstall() = 0; + + // On PS3, user stats & achievement progress through Steam must be stored with the user's saved game data. + // At startup, before calling RequestCurrentStats(), you must pass the user's stats data to Steam via this method. + // If you do not have any user data, call this function with pvData = NULL and cubData = 0 + virtual bool SetUserStatsData( const void *pvData, uint32 cubData ) = 0; + + // Call to get the user's current stats data. You should retrieve this data after receiving successful UserStatsReceived_t & UserStatsStored_t + // callbacks, and store the data with the user's save game data. You can call this method with pvData = NULL and cubData = 0 to get the required + // buffer size. + virtual bool GetUserStatsData( void *pvData, uint32 cubData, uint32 *pcubWritten ) = 0; +#endif +}; + +#define STEAMUSERSTATS_INTERFACE_VERSION "STEAMUSERSTATS_INTERFACE_VERSION011" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when the latests stats and achievements have been received +// from the server +//----------------------------------------------------------------------------- +struct UserStatsReceived_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 1 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // Success / error fetching the stats + CSteamID m_steamIDUser; // The user for whom the stats are retrieved for +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the user stats for a game +//----------------------------------------------------------------------------- +struct UserStatsStored_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 2 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // success / error +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the achievements for a game, or an +// "indicate progress" call. If both m_nCurProgress and m_nMaxProgress +// are zero, that means the achievement has been fully unlocked. +//----------------------------------------------------------------------------- +struct UserAchievementStored_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 3 }; + + uint64 m_nGameID; // Game this is for + bool m_bGroupAchievement; // if this is a "group" achievement + char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement + uint32 m_nCurProgress; // current progress towards the achievement + uint32 m_nMaxProgress; // "out of" this many +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result for finding a leaderboard, returned as a result of FindOrCreateLeaderboard() or FindLeaderboard() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardFindResult_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 4 }; + SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard serarched for, 0 if no leaderboard found + uint8 m_bLeaderboardFound; // 0 if no leaderboard found +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating scores for a leaderboard have been downloaded and are ready to be retrieved, returned as a result of DownloadLeaderboardEntries() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardScoresDownloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 5 }; + SteamLeaderboard_t m_hSteamLeaderboard; + SteamLeaderboardEntries_t m_hSteamLeaderboardEntries; // the handle to pass into GetDownloadedLeaderboardEntries() + int m_cEntryCount; // the number of entries downloaded +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating scores has been uploaded, returned as a result of UploadLeaderboardScore() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardScoreUploaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 6 }; + uint8 m_bSuccess; // 1 if the call was successful + SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was + int32 m_nScore; // the score that was attempted to set + uint8 m_bScoreChanged; // true if the score in the leaderboard change, false if the existing score was better + int m_nGlobalRankNew; // the new global rank of the user in this leaderboard + int m_nGlobalRankPrevious; // the previous global rank of the user in this leaderboard; 0 if the user had no existing entry in the leaderboard +}; + +struct NumberOfCurrentPlayers_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 7 }; + uint8 m_bSuccess; // 1 if the call was successful + int32 m_cPlayers; // Number of players currently playing +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that a user's stats have been unloaded. +// Call RequestUserStats again to access stats for this user +//----------------------------------------------------------------------------- +struct UserStatsUnloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 }; + CSteamID m_steamIDUser; // User whose stats have been unloaded +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that an achievement icon has been fetched +//----------------------------------------------------------------------------- +struct UserAchievementIconFetched_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 9 }; + + CGameID m_nGameID; // Game this is for + char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement + bool m_bAchieved; // Is the icon for the achieved or not achieved version? + int m_nIconHandle; // Handle to the image, which can be used in SteamUtils()->GetImageRGBA(), 0 means no image is set for the achievement +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that global achievement percentages are fetched +//----------------------------------------------------------------------------- +struct GlobalAchievementPercentagesReady_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 10 }; + + uint64 m_nGameID; // Game this is for + EResult m_eResult; // Result of the operation +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating UGC has been uploaded, returned as a result of SetLeaderboardUGC() +//----------------------------------------------------------------------------- +struct LeaderboardUGCSet_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 11 }; + EResult m_eResult; // The result of the operation + SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating that PS3 trophies have been installed +//----------------------------------------------------------------------------- +struct PS3TrophiesInstalled_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // The result of the operation + uint64 m_ulRequiredDiskSpace; // If m_eResult is k_EResultDiskFull, will contain the amount of space needed to install trophies + +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating global stats have been received. +// Returned as a result of RequestGlobalStats() +//----------------------------------------------------------------------------- +struct GlobalStatsReceived_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; + uint64 m_nGameID; // Game global stats were requested for + EResult m_eResult; // The result of the request +}; + +#pragma pack( pop ) + + +#endif // ISTEAMUSER_H diff --git a/dep/hlsdk/public/steam/isteamutils.h b/dep/hlsdk/public/steam/isteamutils.h new file mode 100644 index 0000000..ab032df --- /dev/null +++ b/dep/hlsdk/public/steam/isteamutils.h @@ -0,0 +1,304 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to utility functions in Steam +// +//============================================================================= + +#ifndef ISTEAMUTILS_H +#define ISTEAMUTILS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + + +// Steam API call failure results +enum ESteamAPICallFailure +{ + k_ESteamAPICallFailureNone = -1, // no failure + k_ESteamAPICallFailureSteamGone = 0, // the local Steam process has gone away + k_ESteamAPICallFailureNetworkFailure = 1, // the network connection to Steam has been broken, or was already broken + // SteamServersDisconnected_t callback will be sent around the same time + // SteamServersConnected_t will be sent when the client is able to talk to the Steam servers again + k_ESteamAPICallFailureInvalidHandle = 2, // the SteamAPICall_t handle passed in no longer exists + k_ESteamAPICallFailureMismatchedCallback = 3,// GetAPICallResult() was called with the wrong callback type for this API call +}; + + +// Input modes for the Big Picture gamepad text entry +enum EGamepadTextInputMode +{ + k_EGamepadTextInputModeNormal = 0, + k_EGamepadTextInputModePassword = 1 +}; + + +// Controls number of allowed lines for the Big Picture gamepad text entry +enum EGamepadTextInputLineMode +{ + k_EGamepadTextInputLineModeSingleLine = 0, + k_EGamepadTextInputLineModeMultipleLines = 1 +}; + + +// function prototype for warning message hook +#if defined( POSIX ) +#define __cdecl +#endif +extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); + +//----------------------------------------------------------------------------- +// Purpose: interface to user independent utility functions +//----------------------------------------------------------------------------- +class ISteamUtils +{ +public: + // return the number of seconds since the user + virtual uint32 GetSecondsSinceAppActive() = 0; + virtual uint32 GetSecondsSinceComputerActive() = 0; + + // the universe this client is connecting to + virtual EUniverse GetConnectedUniverse() = 0; + + // Steam server time - in PST, number of seconds since January 1, 1970 (i.e unix time) + virtual uint32 GetServerRealTime() = 0; + + // returns the 2 digit ISO 3166-1-alpha-2 format country code this client is running in (as looked up via an IP-to-location database) + // e.g "US" or "UK". + virtual const char *GetIPCountry() = 0; + + // returns true if the image exists, and valid sizes were filled out + virtual bool GetImageSize( int iImage, uint32 *pnWidth, uint32 *pnHeight ) = 0; + + // returns true if the image exists, and the buffer was successfully filled out + // results are returned in RGBA format + // the destination buffer size should be 4 * height * width * sizeof(char) + virtual bool GetImageRGBA( int iImage, uint8 *pubDest, int nDestBufferSize ) = 0; + + // returns the IP of the reporting server for valve - currently only used in Source engine games + virtual bool GetCSERIPPort( uint32 *unIP, uint16 *usPort ) = 0; + + // return the amount of battery power left in the current system in % [0..100], 255 for being on AC power + virtual uint8 GetCurrentBatteryPower() = 0; + + // returns the appID of the current process + virtual uint32 GetAppID() = 0; + + // Sets the position where the overlay instance for the currently calling game should show notifications. + // This position is per-game and if this function is called from outside of a game context it will do nothing. + virtual void SetOverlayNotificationPosition( ENotificationPosition eNotificationPosition ) = 0; + + // API asynchronous call results + // can be used directly, but more commonly used via the callback dispatch API (see steam_api.h) + virtual bool IsAPICallCompleted( SteamAPICall_t hSteamAPICall, bool *pbFailed ) = 0; + virtual ESteamAPICallFailure GetAPICallFailureReason( SteamAPICall_t hSteamAPICall ) = 0; + virtual bool GetAPICallResult( SteamAPICall_t hSteamAPICall, void *pCallback, int cubCallback, int iCallbackExpected, bool *pbFailed ) = 0; + + // this needs to be called every frame to process matchmaking results + // redundant if you're already calling SteamAPI_RunCallbacks() + virtual void RunFrame() = 0; + + // returns the number of IPC calls made since the last time this function was called + // Used for perf debugging so you can understand how many IPC calls your game makes per frame + // Every IPC call is at minimum a thread context switch if not a process one so you want to rate + // control how often you do them. + virtual uint32 GetIPCCallCount() = 0; + + // API warning handling + // 'int' is the severity; 0 for msg, 1 for warning + // 'const char *' is the text of the message + // callbacks will occur directly after the API function is called that generated the warning or message + virtual void SetWarningMessageHook( SteamAPIWarningMessageHook_t pFunction ) = 0; + + // Returns true if the overlay is running & the user can access it. The overlay process could take a few seconds to + // start & hook the game process, so this function will initially return false while the overlay is loading. + virtual bool IsOverlayEnabled() = 0; + + // Normally this call is unneeded if your game has a constantly running frame loop that calls the + // D3D Present API, or OGL SwapBuffers API every frame. + // + // However, if you have a game that only refreshes the screen on an event driven basis then that can break + // the overlay, as it uses your Present/SwapBuffers calls to drive it's internal frame loop and it may also + // need to Present() to the screen any time an even needing a notification happens or when the overlay is + // brought up over the game by a user. You can use this API to ask the overlay if it currently need a present + // in that case, and then you can check for this periodically (roughly 33hz is desirable) and make sure you + // refresh the screen with Present or SwapBuffers to allow the overlay to do it's work. + virtual bool BOverlayNeedsPresent() = 0; + +#ifndef _PS3 + // Asynchronous call to check if an executable file has been signed using the public key set on the signing tab + // of the partner site, for example to refuse to load modified executable files. + // The result is returned in CheckFileSignature_t. + // k_ECheckFileSignatureNoSignaturesFoundForThisApp - This app has not been configured on the signing tab of the partner site to enable this function. + // k_ECheckFileSignatureNoSignaturesFoundForThisFile - This file is not listed on the signing tab for the partner site. + // k_ECheckFileSignatureFileNotFound - The file does not exist on disk. + // k_ECheckFileSignatureInvalidSignature - The file exists, and the signing tab has been set for this file, but the file is either not signed or the signature does not match. + // k_ECheckFileSignatureValidSignature - The file is signed and the signature is valid. + virtual SteamAPICall_t CheckFileSignature( const char *szFileName ) = 0; +#endif + +#ifdef _PS3 + virtual void PostPS3SysutilCallback( uint64 status, uint64 param, void* userdata ) = 0; + virtual bool BIsReadyToShutdown() = 0; + virtual bool BIsPSNOnline() = 0; + + // Call this with localized strings for the language the game is running in, otherwise default english + // strings will be used by Steam. + virtual void SetPSNGameBootInviteStrings( const char *pchSubject, const char *pchBody ) = 0; +#endif + + // Activates the Big Picture text input dialog which only supports gamepad input + virtual bool ShowGamepadTextInput( EGamepadTextInputMode eInputMode, EGamepadTextInputLineMode eLineInputMode, const char *pchDescription, uint32 unCharMax ) = 0; + + // Returns previously entered text & length + virtual uint32 GetEnteredGamepadTextLength() = 0; + virtual bool GetEnteredGamepadTextInput( char *pchText, uint32 cchText ) = 0; + + // returns the language the steam client is running in, you probably want ISteamApps::GetCurrentGameLanguage instead, this is for very special usage cases + virtual const char *GetSteamUILanguage() = 0; +}; + +#define STEAMUTILS_INTERFACE_VERSION "SteamUtils006" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: The country of the user changed +//----------------------------------------------------------------------------- +struct IPCountry_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 1 }; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Fired when running on a laptop and less than 10 minutes of battery is left, fires then every minute +//----------------------------------------------------------------------------- +struct LowBatteryPower_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 2 }; + uint8 m_nMinutesBatteryLeft; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when a SteamAsyncCall_t has completed (or failed) +//----------------------------------------------------------------------------- +struct SteamAPICallCompleted_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 3 }; + SteamAPICall_t m_hAsyncCall; +}; + + +//----------------------------------------------------------------------------- +// called when Steam wants to shutdown +//----------------------------------------------------------------------------- +struct SteamShutdown_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 4 }; +}; + +//----------------------------------------------------------------------------- +// results for CheckFileSignature +//----------------------------------------------------------------------------- +enum ECheckFileSignature +{ + k_ECheckFileSignatureInvalidSignature = 0, + k_ECheckFileSignatureValidSignature = 1, + k_ECheckFileSignatureFileNotFound = 2, + k_ECheckFileSignatureNoSignaturesFoundForThisApp = 3, + k_ECheckFileSignatureNoSignaturesFoundForThisFile = 4, +}; + +//----------------------------------------------------------------------------- +// callback for CheckFileSignature +//----------------------------------------------------------------------------- +struct CheckFileSignature_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 5 }; + ECheckFileSignature m_eCheckFileSignature; +}; + +#ifdef _PS3 +//----------------------------------------------------------------------------- +// callback for NetCtlNetStartDialog finishing on PS3 +//----------------------------------------------------------------------------- +struct NetStartDialogFinished_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 6 }; +}; + +//----------------------------------------------------------------------------- +// callback for NetCtlNetStartDialog unloaded on PS3 +//----------------------------------------------------------------------------- +struct NetStartDialogUnloaded_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 7 }; +}; + +//----------------------------------------------------------------------------- +// callback for system menu closing on PS3 - should trigger resyncronizing friends list, etc. +//----------------------------------------------------------------------------- +struct PS3SystemMenuClosed_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 8 }; +}; + +//----------------------------------------------------------------------------- +// callback for NP message being selected by user on PS3 - should trigger handling of message if it's a lobby invite, etc. +//----------------------------------------------------------------------------- +struct PS3NPMessageSelected_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 9 }; + uint32 dataid; +}; + +//----------------------------------------------------------------------------- +// callback for when the PS3 keyboard dialog closes +//----------------------------------------------------------------------------- +struct PS3KeyboardDialogFinished_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 10 }; +}; + +// k_iSteamUtilsCallbacks + 11 is taken + +//----------------------------------------------------------------------------- +// callback for PSN status changing on PS3 +//----------------------------------------------------------------------------- +struct PS3PSNStatusChange_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 12 }; + bool m_bPSNOnline; +}; + +#endif + +// k_iSteamUtilsCallbacks + 13 is taken + + +//----------------------------------------------------------------------------- +// Big Picture gamepad text input has been closed +//----------------------------------------------------------------------------- +struct GamepadTextInputDismissed_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 14 }; + bool m_bSubmitted; // true if user entered & accepted text (Call ISteamUtils::GetEnteredGamepadTextInput() for text), false if canceled input + uint32 m_unSubmittedText; +}; + +// k_iSteamUtilsCallbacks + 15 is taken + +#pragma pack( pop ) + +#endif // ISTEAMUTILS_H diff --git a/dep/hlsdk/public/steam/matchmakingtypes.h b/dep/hlsdk/public/steam/matchmakingtypes.h new file mode 100644 index 0000000..d79ee7e --- /dev/null +++ b/dep/hlsdk/public/steam/matchmakingtypes.h @@ -0,0 +1,249 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef MATCHMAKINGTYPES_H +#define MATCHMAKINGTYPES_H + +#ifdef _WIN32 +#pragma once +#endif + +#ifdef POSIX +#ifndef _snprintf +#define _snprintf snprintf +#endif +#endif + +#include +#include + +#include "common.h" //Q_snprinf + +// +// Max size (in bytes of UTF-8 data, not in characters) of server fields, including null terminator. +// WARNING: These cannot be changed easily, without breaking clients using old interfaces. +// +const int k_cbMaxGameServerGameDir = 32; +const int k_cbMaxGameServerMapName = 32; +const int k_cbMaxGameServerGameDescription = 64; +const int k_cbMaxGameServerName = 64; +const int k_cbMaxGameServerTags = 128; +const int k_cbMaxGameServerGameData = 2048; + +struct MatchMakingKeyValuePair_t +{ + MatchMakingKeyValuePair_t() { m_szKey[0] = m_szValue[0] = 0; } + MatchMakingKeyValuePair_t( const char *pchKey, const char *pchValue ) + { + strncpy( m_szKey, pchKey, sizeof(m_szKey) ); // this is a public header, use basic c library string funcs only! + m_szKey[ sizeof( m_szKey ) - 1 ] = '\0'; + strncpy( m_szValue, pchValue, sizeof(m_szValue) ); + m_szValue[ sizeof( m_szValue ) - 1 ] = '\0'; + } + char m_szKey[ 256 ]; + char m_szValue[ 256 ]; +}; + + +enum EMatchMakingServerResponse +{ + eServerResponded = 0, + eServerFailedToRespond, + eNoServersListedOnMasterServer // for the Internet query type, returned in response callback if no servers of this type match +}; + +// servernetadr_t is all the addressing info the serverbrowser needs to know about a game server, +// namely: its IP, its connection port, and its query port. +class servernetadr_t +{ +public: + + void Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ); + +// Uncompatible feature commented +//#ifdef NETADR_H +// netadr_t GetIPAndQueryPort(); +//#endif + + // Access the query port. + uint16 GetQueryPort() const; + void SetQueryPort( uint16 usPort ); + + // Access the connection port. + uint16 GetConnectionPort() const; + void SetConnectionPort( uint16 usPort ); + + // Access the IP + uint32 GetIP() const; + void SetIP( uint32 ); + + // This gets the 'a.b.c.d:port' string with the connection port (instead of the query port). + const char *GetConnectionAddressString() const; + const char *GetQueryAddressString() const; + + // Comparison operators and functions. + bool operator<(const servernetadr_t &netadr) const; + void operator=( const servernetadr_t &that ) + { + m_usConnectionPort = that.m_usConnectionPort; + m_usQueryPort = that.m_usQueryPort; + m_unIP = that.m_unIP; + } + + +private: + const char *ToString( uint32 unIP, uint16 usPort ) const; + uint16 m_usConnectionPort; // (in HOST byte order) + uint16 m_usQueryPort; + uint32 m_unIP; +}; + + +inline void servernetadr_t::Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ) +{ + m_unIP = ip; + m_usQueryPort = usQueryPort; + m_usConnectionPort = usConnectionPort; +} + +// Uncompatible feature commented +//#ifdef NETADR_H +//inline netadr_t servernetadr_t::GetIPAndQueryPort() +//{ +// return netadr_t( m_unIP, m_usQueryPort ); +//} +//#endif + +inline uint16 servernetadr_t::GetQueryPort() const +{ + return m_usQueryPort; +} + +inline void servernetadr_t::SetQueryPort( uint16 usPort ) +{ + m_usQueryPort = usPort; +} + +inline uint16 servernetadr_t::GetConnectionPort() const +{ + return m_usConnectionPort; +} + +inline void servernetadr_t::SetConnectionPort( uint16 usPort ) +{ + m_usConnectionPort = usPort; +} + +inline uint32 servernetadr_t::GetIP() const +{ + return m_unIP; +} + +inline void servernetadr_t::SetIP( uint32 unIP ) +{ + m_unIP = unIP; +} + +inline const char *servernetadr_t::ToString( uint32 unIP, uint16 usPort ) const +{ + static char s[4][64]; + static int nBuf = 0; + unsigned char *ipByte = (unsigned char *)&unIP; +#ifdef VALVE_BIG_ENDIAN + Q_snprintf (s[nBuf], sizeof( s[nBuf] ), "%u.%u.%u.%u:%i", (int)(ipByte[0]), (int)(ipByte[1]), (int)(ipByte[2]), (int)(ipByte[3]), usPort ); +#else + Q_snprintf (s[nBuf], sizeof( s[nBuf] ), "%u.%u.%u.%u:%i", (int)(ipByte[3]), (int)(ipByte[2]), (int)(ipByte[1]), (int)(ipByte[0]), usPort ); +#endif + const char *pchRet = s[nBuf]; + ++nBuf; + nBuf %= ( (sizeof(s)/sizeof(s[0])) ); + return pchRet; +} + +inline const char* servernetadr_t::GetConnectionAddressString() const +{ + return ToString( m_unIP, m_usConnectionPort ); +} + +inline const char* servernetadr_t::GetQueryAddressString() const +{ + return ToString( m_unIP, m_usQueryPort ); +} + +inline bool servernetadr_t::operator<(const servernetadr_t &netadr) const +{ + return ( m_unIP < netadr.m_unIP ) || ( m_unIP == netadr.m_unIP && m_usQueryPort < netadr.m_usQueryPort ); +} + +//----------------------------------------------------------------------------- +// Purpose: Data describing a single server +//----------------------------------------------------------------------------- +class gameserveritem_t +{ +public: + gameserveritem_t(); + + const char* GetName() const; + void SetName( const char *pName ); + +public: + servernetadr_t m_NetAdr; ///< IP/Query Port/Connection Port for this server + int m_nPing; ///< current ping time in milliseconds + bool m_bHadSuccessfulResponse; ///< server has responded successfully in the past + bool m_bDoNotRefresh; ///< server is marked as not responding and should no longer be refreshed + char m_szGameDir[k_cbMaxGameServerGameDir]; ///< current game directory + char m_szMap[k_cbMaxGameServerMapName]; ///< current map + char m_szGameDescription[k_cbMaxGameServerGameDescription]; ///< game description + uint32 m_nAppID; ///< Steam App ID of this server + int m_nPlayers; ///< total number of players currently on the server. INCLUDES BOTS!! + int m_nMaxPlayers; ///< Maximum players that can join this server + int m_nBotPlayers; ///< Number of bots (i.e simulated players) on this server + bool m_bPassword; ///< true if this server needs a password to join + bool m_bSecure; ///< Is this server protected by VAC + uint32 m_ulTimeLastPlayed; ///< time (in unix time) when this server was last played on (for favorite/history servers) + int m_nServerVersion; ///< server version as reported to Steam + +private: + + /// Game server name + char m_szServerName[k_cbMaxGameServerName]; + + // For data added after SteamMatchMaking001 add it here +public: + /// the tags this server exposes + char m_szGameTags[k_cbMaxGameServerTags]; + + /// steamID of the game server - invalid if it's doesn't have one (old server, or not connected to Steam) + CSteamID m_steamID; +}; + + +inline gameserveritem_t::gameserveritem_t() +{ + m_szGameDir[0] = m_szMap[0] = m_szGameDescription[0] = m_szServerName[0] = 0; + m_bHadSuccessfulResponse = m_bDoNotRefresh = m_bPassword = m_bSecure = false; + m_nPing = m_nAppID = m_nPlayers = m_nMaxPlayers = m_nBotPlayers = m_ulTimeLastPlayed = m_nServerVersion = 0; + m_szGameTags[0] = 0; +} + +inline const char* gameserveritem_t::GetName() const +{ + // Use the IP address as the name if nothing is set yet. + if ( m_szServerName[0] == 0 ) + return m_NetAdr.GetConnectionAddressString(); + else + return m_szServerName; +} + +inline void gameserveritem_t::SetName( const char *pName ) +{ + strncpy( m_szServerName, pName, sizeof( m_szServerName ) ); + m_szServerName[ sizeof( m_szServerName ) - 1 ] = '\0'; +} + + +#endif // MATCHMAKINGTYPES_H diff --git a/dep/hlsdk/public/steam/steam_api.h b/dep/hlsdk/public/steam/steam_api.h new file mode 100644 index 0000000..17e68b2 --- /dev/null +++ b/dep/hlsdk/public/steam/steam_api.h @@ -0,0 +1,545 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAM_API_H +#define STEAM_API_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "isteamuser.h" +#include "isteamfriends.h" +#include "isteamutils.h" +#include "isteammatchmaking.h" +#include "isteamuserstats.h" +#include "isteamapps.h" +#include "isteamnetworking.h" +#include "isteamremotestorage.h" +#include "isteamscreenshots.h" +#include "isteamhttp.h" +#include "isteamunifiedmessages.h" +#include "isteamcontroller.h" + +#if defined( _PS3 ) +#include "steamps3params.h" +#endif + +// Steam API export macro +#if defined( _WIN32 ) && !defined( _X360 ) + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" __declspec( dllexport ) + #elif defined( STEAM_API_NODLL ) + #define S_API extern "C" + #else + #define S_API extern "C" __declspec( dllimport ) + #endif // STEAM_API_EXPORTS +#elif defined( GNUC ) + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" __attribute__ ((visibility("default"))) + #else + #define S_API extern "C" + #endif // STEAM_API_EXPORTS +#else // !WIN32 + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" + #else + #define S_API extern "C" + #endif // STEAM_API_EXPORTS +#endif + +class CCallbackBase; + +#ifdef REHLDS_SELF +#include "rehlds/platform.h" +#endif + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// Steam API setup & shutdown +// +// These functions manage loading, initializing and shutdown of the steamclient.dll +// +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +// S_API void SteamAPI_Init(); (see below) +S_API void SteamAPI_Shutdown(); + +// checks if a local Steam client is running +S_API bool SteamAPI_IsSteamRunning(); + +// Detects if your executable was launched through the Steam client, and restarts your game through +// the client if necessary. The Steam client will be started if it is not running. +// +// Returns: true if your executable was NOT launched through the Steam client. This function will +// then start your application through the client. Your current process should exit. +// +// false if your executable was started through the Steam client or a steam_appid.txt file +// is present in your game's directory (for development). Your current process should continue. +// +// NOTE: This function should be used only if you are using CEG or not using Steam's DRM. Once applied +// to your executable, Steam's DRM will handle restarting through Steam if necessary. +S_API bool SteamAPI_RestartAppIfNecessary( uint32 unOwnAppID ); + +// crash dump recording functions +S_API void SteamAPI_WriteMiniDump( uint32 uStructuredExceptionCode, void* pvExceptionInfo, uint32 uBuildID ); +S_API void SteamAPI_SetMiniDumpComment( const char *pchMsg ); + +// interface pointers, configured by SteamAPI_Init() +S_API ISteamClient *SteamClient(); + + +// +// VERSION_SAFE_STEAM_API_INTERFACES is usually not necessary, but it provides safety against releasing +// new steam_api.dll's without recompiling/rereleasing modules that use it. +// +// If you use VERSION_SAFE_STEAM_API_INTERFACES, then you should call SteamAPI_InitSafe(). Also, to get the +// Steam interfaces, you must create and Init() a CSteamAPIContext (below) and use the interfaces in there. +// +// If you don't use VERSION_SAFE_STEAM_API_INTERFACES, then you can use SteamAPI_Init() and the SteamXXXX() +// functions below to get at the Steam interfaces. +// +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamAPI_InitSafe(); +#else + +#if defined(_PS3) +S_API bool SteamAPI_Init( SteamPS3Params_t *pParams ); +#else +S_API bool SteamAPI_Init(); +#endif + +S_API ISteamUser *SteamUser(); +S_API ISteamFriends *SteamFriends(); +S_API ISteamUtils *SteamUtils(); +S_API ISteamMatchmaking *SteamMatchmaking(); +S_API ISteamUserStats *SteamUserStats(); +S_API ISteamApps *SteamApps(); +S_API ISteamNetworking *SteamNetworking(); +S_API ISteamMatchmakingServers *SteamMatchmakingServers(); +S_API ISteamRemoteStorage *SteamRemoteStorage(); +S_API ISteamScreenshots *SteamScreenshots(); +S_API ISteamHTTP *SteamHTTP(); +S_API ISteamUnifiedMessages *SteamUnifiedMessages(); +#ifdef _PS3 +S_API ISteamPS3OverlayRender * SteamPS3OverlayRender(); +#endif +#endif // VERSION_SAFE_STEAM_API_INTERFACES + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steam callback helper functions +// +// The following classes/macros are used to be able to easily multiplex callbacks +// from the Steam API into various objects in the app in a thread-safe manner +// +// These functors are triggered via the SteamAPI_RunCallbacks() function, mapping the callback +// to as many functions/objects as are registered to it +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API void SteamAPI_RunCallbacks(); + + + +// functions used by the utility CCallback objects to receive callbacks +S_API void SteamAPI_RegisterCallback( class CCallbackBase *pCallback, int iCallback ); +S_API void SteamAPI_UnregisterCallback( class CCallbackBase *pCallback ); +// functions used by the utility CCallResult objects to receive async call results +S_API void SteamAPI_RegisterCallResult( class CCallbackBase *pCallback, SteamAPICall_t hAPICall ); +S_API void SteamAPI_UnregisterCallResult( class CCallbackBase *pCallback, SteamAPICall_t hAPICall ); + + +//----------------------------------------------------------------------------- +// Purpose: base for callbacks, +// used only by CCallback, shouldn't be used directly +//----------------------------------------------------------------------------- +class CCallbackBase +{ +public: + CCallbackBase() { m_nCallbackFlags = 0; m_iCallback = 0; } + // don't add a virtual destructor because we export this binary interface across dll's + virtual void Run( void *pvParam ) = 0; + virtual void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ) = 0; + int GetICallback() { return m_iCallback; } + virtual int GetCallbackSizeBytes() = 0; + + //Added for hooking support + uint8 GetFlags() { return m_nCallbackFlags; } + void SetFlags(uint8 flags) { m_nCallbackFlags = flags; } + void SetICallback(int cb) { m_iCallback = cb; } + +protected: + enum { k_ECallbackFlagsRegistered = 0x01, k_ECallbackFlagsGameServer = 0x02 }; + uint8 m_nCallbackFlags; + int m_iCallback; + friend class CCallbackMgr; +}; + + +//----------------------------------------------------------------------------- +// Purpose: maps a steam async call result to a class member function +// template params: T = local class, P = parameter struct +//----------------------------------------------------------------------------- +template< class T, class P > +class CCallResult : private CCallbackBase +{ +public: + typedef void (T::*func_t)( P*, bool ); + + CCallResult() + { + m_hAPICall = k_uAPICallInvalid; + m_pObj = NULL; + m_Func = NULL; + m_iCallback = P::k_iCallback; + } + + void Set( SteamAPICall_t hAPICall, T *p, func_t func ) + { + if ( m_hAPICall ) + SteamAPI_UnregisterCallResult( this, m_hAPICall ); + + m_hAPICall = hAPICall; + m_pObj = p; + m_Func = func; + + if ( hAPICall ) + SteamAPI_RegisterCallResult( this, hAPICall ); + } + + bool IsActive() const + { + return ( m_hAPICall != k_uAPICallInvalid ); + } + + void Cancel() + { + if ( m_hAPICall != k_uAPICallInvalid ) + { + SteamAPI_UnregisterCallResult( this, m_hAPICall ); + m_hAPICall = k_uAPICallInvalid; + } + + } + + ~CCallResult() + { + Cancel(); + } + + void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } +private: + virtual void Run( void *pvParam ) + { + m_hAPICall = k_uAPICallInvalid; // caller unregisters for us + (m_pObj->*m_Func)( (P *)pvParam, false ); + } + void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ) + { + if ( hSteamAPICall == m_hAPICall ) + { + m_hAPICall = k_uAPICallInvalid; // caller unregisters for us + (m_pObj->*m_Func)( (P *)pvParam, bIOFailure ); + } + } + int GetCallbackSizeBytes() + { + return sizeof( P ); + } + + SteamAPICall_t m_hAPICall; + T *m_pObj; + func_t m_Func; +}; + + + +//----------------------------------------------------------------------------- +// Purpose: maps a steam callback to a class member function +// template params: T = local class, P = parameter struct +//----------------------------------------------------------------------------- +template< class T, class P, bool bGameServer > +class CCallback : protected CCallbackBase +{ +public: + typedef void (T::*func_t)( P* ); + + // If you can't support constructing a callback with the correct parameters + // then uncomment the empty constructor below and manually call + // ::Register() for your object + // Or, just call the regular constructor with (NULL, NULL) + // CCallback() {} + + // constructor for initializing this object in owner's constructor + CCallback( T *pObj, func_t func ) : m_pObj( pObj ), m_Func( func ) + { + if ( pObj && func ) + Register( pObj, func ); + } + + ~CCallback() + { + if ( m_nCallbackFlags & k_ECallbackFlagsRegistered ) + Unregister(); + } + + // manual registration of the callback + void Register( T *pObj, func_t func ) + { + if ( !pObj || !func ) + return; + + if ( m_nCallbackFlags & k_ECallbackFlagsRegistered ) + Unregister(); + + if ( bGameServer ) + { + m_nCallbackFlags |= k_ECallbackFlagsGameServer; + } + m_pObj = pObj; + m_Func = func; + // SteamAPI_RegisterCallback sets k_ECallbackFlagsRegistered + +#ifdef REHLDS_SELF + CRehldsPlatformHolder::get()->SteamAPI_RegisterCallback(this, P::k_iCallback); +#else + SteamAPI_RegisterCallback(this, P::k_iCallback); +#endif // REHLDS_SELF + } + + void Unregister() + { + // SteamAPI_UnregisterCallback removes k_ECallbackFlagsRegistered + +#ifdef REHLDS_SELF + CRehldsPlatformHolder::get()->SteamAPI_UnregisterCallback(this); +#else + SteamAPI_UnregisterCallback(this); +#endif // REHLDS_SELF + } + + void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } +protected: + virtual void Run( void *pvParam ) + { + (m_pObj->*m_Func)( (P *)pvParam ); + } + virtual void Run( void *pvParam, bool, SteamAPICall_t ) + { + (m_pObj->*m_Func)( (P *)pvParam ); + } + int GetCallbackSizeBytes() + { + return sizeof( P ); + } + + T *m_pObj; + func_t m_Func; +}; + +// Allows you to defer registration of the callback +template< class T, class P, bool bGameServer > +class CCallbackManual : public CCallback< T, P, bGameServer > +{ +public: + CCallbackManual() : CCallback< T, P, bGameServer >( NULL, NULL ) {} +}; + +// utility macro for declaring the function and callback object together +#define STEAM_CALLBACK( thisclass, func, param, var ) CCallback< thisclass, param, false > var; void func( param *pParam ) + +// same as above, but lets you defer the callback binding by calling Register later +#define STEAM_CALLBACK_MANUAL( thisclass, func, param, var ) CCallbackManual< thisclass, param, false > var; void func( param *pParam ) + + +#ifdef _WIN32 +// disable this warning; this pattern need for steam callback registration +#pragma warning( disable: 4355 ) // 'this' : used in base member initializer list +#endif + + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steamclient.dll private wrapper functions +// +// The following functions are part of abstracting API access to the steamclient.dll, but should only be used in very specific cases +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +// pumps out all the steam messages, calling the register callback +S_API void Steam_RunCallbacks( HSteamPipe hSteamPipe, bool bGameServerCallbacks ); + +// register the callback funcs to use to interact with the steam dll +S_API void Steam_RegisterInterfaceFuncs( void *hModule ); + +// returns the HSteamUser of the last user to dispatch a callback +S_API HSteamUser Steam_GetHSteamUserCurrent(); + +// returns the filename path of the current running Steam process, used if you need to load an explicit steam dll by name +S_API const char *SteamAPI_GetSteamInstallPath(); + +// returns the pipe we are communicating to Steam with +S_API HSteamPipe SteamAPI_GetHSteamPipe(); + +// sets whether or not Steam_RunCallbacks() should do a try {} catch (...) {} around calls to issuing callbacks +S_API void SteamAPI_SetTryCatchCallbacks( bool bTryCatchCallbacks ); + +// backwards compat export, passes through to SteamAPI_ variants +S_API HSteamPipe GetHSteamPipe(); +S_API HSteamUser GetHSteamUser(); + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// VERSION_SAFE_STEAM_API_INTERFACES uses CSteamAPIContext to provide interfaces to each module in a way that +// lets them each specify the interface versions they are compiled with. +// +// It's important that these stay inlined in the header so the calling module specifies the interface versions +// for whatever Steam API version it has. +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API HSteamUser SteamAPI_GetHSteamUser(); + +class CSteamAPIContext +{ +public: + CSteamAPIContext(); + void Clear(); + + bool Init(); + + ISteamUser* SteamUser() { return m_pSteamUser; } + ISteamFriends* SteamFriends() { return m_pSteamFriends; } + ISteamUtils* SteamUtils() { return m_pSteamUtils; } + ISteamMatchmaking* SteamMatchmaking() { return m_pSteamMatchmaking; } + ISteamUserStats* SteamUserStats() { return m_pSteamUserStats; } + ISteamApps* SteamApps() { return m_pSteamApps; } + ISteamMatchmakingServers* SteamMatchmakingServers() { return m_pSteamMatchmakingServers; } + ISteamNetworking* SteamNetworking() { return m_pSteamNetworking; } + ISteamRemoteStorage* SteamRemoteStorage() { return m_pSteamRemoteStorage; } + ISteamScreenshots* SteamScreenshots() { return m_pSteamScreenshots; } + ISteamHTTP* SteamHTTP() { return m_pSteamHTTP; } + ISteamUnifiedMessages* SteamUnifiedMessages() { return m_pSteamUnifiedMessages; } +#ifdef _PS3 + ISteamPS3OverlayRender* SteamPS3OverlayRender() { return m_pSteamPS3OverlayRender; } +#endif + +private: + ISteamUser *m_pSteamUser; + ISteamFriends *m_pSteamFriends; + ISteamUtils *m_pSteamUtils; + ISteamMatchmaking *m_pSteamMatchmaking; + ISteamUserStats *m_pSteamUserStats; + ISteamApps *m_pSteamApps; + ISteamMatchmakingServers *m_pSteamMatchmakingServers; + ISteamNetworking *m_pSteamNetworking; + ISteamRemoteStorage *m_pSteamRemoteStorage; + ISteamScreenshots *m_pSteamScreenshots; + ISteamHTTP *m_pSteamHTTP; + ISteamUnifiedMessages*m_pSteamUnifiedMessages; + ISteamController *m_pController; +#ifdef _PS3 + ISteamPS3OverlayRender *m_pSteamPS3OverlayRender; +#endif +}; + +inline CSteamAPIContext::CSteamAPIContext() +{ + Clear(); +} + +inline void CSteamAPIContext::Clear() +{ + m_pSteamUser = NULL; + m_pSteamFriends = NULL; + m_pSteamUtils = NULL; + m_pSteamMatchmaking = NULL; + m_pSteamUserStats = NULL; + m_pSteamApps = NULL; + m_pSteamMatchmakingServers = NULL; + m_pSteamNetworking = NULL; + m_pSteamRemoteStorage = NULL; + m_pSteamHTTP = NULL; + m_pSteamScreenshots = NULL; + m_pSteamUnifiedMessages = NULL; +#ifdef _PS3 + m_pSteamPS3OverlayRender = NULL; +#endif +} + +// This function must be inlined so the module using steam_api.dll gets the version names they want. +inline bool CSteamAPIContext::Init() +{ + if ( !SteamClient() ) + return false; + + HSteamUser hSteamUser = SteamAPI_GetHSteamUser(); + HSteamPipe hSteamPipe = SteamAPI_GetHSteamPipe(); + + m_pSteamUser = SteamClient()->GetISteamUser( hSteamUser, hSteamPipe, STEAMUSER_INTERFACE_VERSION ); + if ( !m_pSteamUser ) + return false; + + m_pSteamFriends = SteamClient()->GetISteamFriends( hSteamUser, hSteamPipe, STEAMFRIENDS_INTERFACE_VERSION ); + if ( !m_pSteamFriends ) + return false; + + m_pSteamUtils = SteamClient()->GetISteamUtils( hSteamPipe, STEAMUTILS_INTERFACE_VERSION ); + if ( !m_pSteamUtils ) + return false; + + m_pSteamMatchmaking = SteamClient()->GetISteamMatchmaking( hSteamUser, hSteamPipe, STEAMMATCHMAKING_INTERFACE_VERSION ); + if ( !m_pSteamMatchmaking ) + return false; + + m_pSteamMatchmakingServers = SteamClient()->GetISteamMatchmakingServers( hSteamUser, hSteamPipe, STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION ); + if ( !m_pSteamMatchmakingServers ) + return false; + + m_pSteamUserStats = SteamClient()->GetISteamUserStats( hSteamUser, hSteamPipe, STEAMUSERSTATS_INTERFACE_VERSION ); + if ( !m_pSteamUserStats ) + return false; + + m_pSteamApps = SteamClient()->GetISteamApps( hSteamUser, hSteamPipe, STEAMAPPS_INTERFACE_VERSION ); + if ( !m_pSteamApps ) + return false; + + m_pSteamNetworking = SteamClient()->GetISteamNetworking( hSteamUser, hSteamPipe, STEAMNETWORKING_INTERFACE_VERSION ); + if ( !m_pSteamNetworking ) + return false; + + m_pSteamRemoteStorage = SteamClient()->GetISteamRemoteStorage( hSteamUser, hSteamPipe, STEAMREMOTESTORAGE_INTERFACE_VERSION ); + if ( !m_pSteamRemoteStorage ) + return false; + + m_pSteamScreenshots = SteamClient()->GetISteamScreenshots( hSteamUser, hSteamPipe, STEAMSCREENSHOTS_INTERFACE_VERSION ); + if ( !m_pSteamScreenshots ) + return false; + + m_pSteamHTTP = SteamClient()->GetISteamHTTP( hSteamUser, hSteamPipe, STEAMHTTP_INTERFACE_VERSION ); + if ( !m_pSteamHTTP ) + return false; + + m_pSteamUnifiedMessages = SteamClient()->GetISteamUnifiedMessages( hSteamUser, hSteamPipe, STEAMUNIFIEDMESSAGES_INTERFACE_VERSION ); + if ( !m_pSteamUnifiedMessages ) + return false; + +#ifdef _PS3 + m_pSteamPS3OverlayRender = SteamClient()->GetISteamPS3OverlayRender(); +#endif + + return true; +} + +#endif // VERSION_SAFE_STEAM_API_INTERFACES + +#if defined(USE_BREAKPAD_HANDLER) || defined(STEAM_API_EXPORTS) +// this should be called before the game initialized the steam APIs +// pchDate should be of the format "Mmm dd yyyy" (such as from the __DATE __ macro ) +// pchTime should be of the format "hh:mm:ss" (such as from the __TIME __ macro ) +// bFullMemoryDumps (Win32 only) -- writes out a uuid-full.dmp in the client/dumps folder +// pvContext-- can be NULL, will be the void * context passed into m_pfnPreMinidumpCallback +// PFNPreMinidumpCallback m_pfnPreMinidumpCallback -- optional callback which occurs just before a .dmp file is written during a crash. Applications can hook this to allow adding additional information into the .dmp comment stream. +S_API void SteamAPI_UseBreakpadCrashHandler( char const *pchVersion, char const *pchDate, char const *pchTime, bool bFullMemoryDumps, void *pvContext, PFNPreMinidumpCallback m_pfnPreMinidumpCallback ); +S_API void SteamAPI_SetBreakpadAppID( uint32 unAppID ); +#endif + +#endif // STEAM_API_H diff --git a/dep/hlsdk/public/steam/steam_gameserver.h b/dep/hlsdk/public/steam/steam_gameserver.h new file mode 100644 index 0000000..e031e31 --- /dev/null +++ b/dep/hlsdk/public/steam/steam_gameserver.h @@ -0,0 +1,163 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAM_GAMESERVER_H +#define STEAM_GAMESERVER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "steam_api.h" +#include "isteamgameserver.h" +#include "isteamgameserverstats.h" + +enum EServerMode +{ + eServerModeInvalid = 0, // DO NOT USE + eServerModeNoAuthentication = 1, // Don't authenticate user logins and don't list on the server list + eServerModeAuthentication = 2, // Authenticate users, list on the server list, don't run VAC on clients that connect + eServerModeAuthenticationAndSecure = 3, // Authenticate users, list on the server list and VAC protect clients +}; + +// Initialize ISteamGameServer interface object, and set server properties which may not be changed. +// +// After calling this function, you should set any additional server parameters, and then +// call ISteamGameServer::LogOnAnonymous() or ISteamGameServer::LogOn() +// +// - usSteamPort is the local port used to communicate with the steam servers. +// - usGamePort is the port that clients will connect to for gameplay. +// - usQueryPort is the port that will manage server browser related duties and info +// pings from clients. If you pass MASTERSERVERUPDATERPORT_USEGAMESOCKETSHARE for usQueryPort, then it +// will use "GameSocketShare" mode, which means that the game is responsible for sending and receiving +// UDP packets for the master server updater. See references to GameSocketShare in isteamgameserver.h. +// - The version string is usually in the form x.x.x.x, and is used by the master server to detect when the +// server is out of date. (Only servers with the latest version will be listed.) +#ifndef _PS3 + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamGameServer_InitSafe( uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#else +S_API bool SteamGameServer_Init( uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#endif + +#else + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamGameServer_InitSafe( const SteamPS3Params_t *ps3Params, uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#else +S_API bool SteamGameServer_Init( const SteamPS3Params_t *ps3Params, uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#endif + +#endif + +#ifndef VERSION_SAFE_STEAM_API_INTERFACES +S_API ISteamGameServer *SteamGameServer(); +S_API ISteamUtils *SteamGameServerUtils(); +S_API ISteamNetworking *SteamGameServerNetworking(); +S_API ISteamGameServerStats *SteamGameServerStats(); +S_API ISteamHTTP *SteamGameServerHTTP(); +#endif + +S_API void SteamGameServer_Shutdown(); +S_API void SteamGameServer_RunCallbacks(); + +S_API bool SteamGameServer_BSecure(); +S_API uint64 SteamGameServer_GetSteamID(); + +#define STEAM_GAMESERVER_CALLBACK( thisclass, func, param, var ) CCallback< thisclass, param, true > var; void func( param *pParam ) + + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steamclient.dll private wrapper functions +// +// The following functions are part of abstracting API access to the steamclient.dll, but should only be used in very specific cases +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +S_API HSteamPipe SteamGameServer_GetHSteamPipe(); + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// VERSION_SAFE_STEAM_API_INTERFACES uses CSteamAPIContext to provide interfaces to each module in a way that +// lets them each specify the interface versions they are compiled with. +// +// It's important that these stay inlined in the header so the calling module specifies the interface versions +// for whatever Steam API version it has. +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API HSteamUser SteamGameServer_GetHSteamUser(); + +class CSteamGameServerAPIContext +{ +public: + CSteamGameServerAPIContext(); + void Clear(); + + bool Init(); + + ISteamGameServer *SteamGameServer() { return m_pSteamGameServer; } + ISteamUtils *SteamGameServerUtils() { return m_pSteamGameServerUtils; } + ISteamNetworking *SteamGameServerNetworking() { return m_pSteamGameServerNetworking; } + ISteamGameServerStats *SteamGameServerStats() { return m_pSteamGameServerStats; } + ISteamHTTP *SteamHTTP() { return m_pSteamHTTP; } + +private: + ISteamGameServer *m_pSteamGameServer; + ISteamUtils *m_pSteamGameServerUtils; + ISteamNetworking *m_pSteamGameServerNetworking; + ISteamGameServerStats *m_pSteamGameServerStats; + ISteamHTTP *m_pSteamHTTP; +}; + +inline CSteamGameServerAPIContext::CSteamGameServerAPIContext() +{ + Clear(); +} + +inline void CSteamGameServerAPIContext::Clear() +{ + m_pSteamGameServer = NULL; + m_pSteamGameServerUtils = NULL; + m_pSteamGameServerNetworking = NULL; + m_pSteamGameServerStats = NULL; + m_pSteamHTTP = NULL; +} + +S_API ISteamClient *g_pSteamClientGameServer; +// This function must be inlined so the module using steam_api.dll gets the version names they want. +inline bool CSteamGameServerAPIContext::Init() +{ + if ( !g_pSteamClientGameServer ) + return false; + + HSteamUser hSteamUser = SteamGameServer_GetHSteamUser(); + HSteamPipe hSteamPipe = SteamGameServer_GetHSteamPipe(); + + m_pSteamGameServer = g_pSteamClientGameServer->GetISteamGameServer( hSteamUser, hSteamPipe, STEAMGAMESERVER_INTERFACE_VERSION ); + if ( !m_pSteamGameServer ) + return false; + + m_pSteamGameServerUtils = g_pSteamClientGameServer->GetISteamUtils( hSteamPipe, STEAMUTILS_INTERFACE_VERSION ); + if ( !m_pSteamGameServerUtils ) + return false; + + m_pSteamGameServerNetworking = g_pSteamClientGameServer->GetISteamNetworking( hSteamUser, hSteamPipe, STEAMNETWORKING_INTERFACE_VERSION ); + if ( !m_pSteamGameServerNetworking ) + return false; + + m_pSteamGameServerStats = g_pSteamClientGameServer->GetISteamGameServerStats( hSteamUser, hSteamPipe, STEAMGAMESERVERSTATS_INTERFACE_VERSION ); + if ( !m_pSteamGameServerStats ) + return false; + + m_pSteamHTTP = g_pSteamClientGameServer->GetISteamHTTP( hSteamUser, hSteamPipe, STEAMHTTP_INTERFACE_VERSION ); + if ( !m_pSteamGameServerStats ) + return false; + + return true; +} + +#endif // VERSION_SAFE_STEAM_API_INTERFACES + + +#endif // STEAM_GAMESERVER_H diff --git a/dep/hlsdk/public/steam/steamclientpublic.h b/dep/hlsdk/public/steam/steamclientpublic.h new file mode 100644 index 0000000..b129267 --- /dev/null +++ b/dep/hlsdk/public/steam/steamclientpublic.h @@ -0,0 +1,1086 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMCLIENTPUBLIC_H +#define STEAMCLIENTPUBLIC_H +#ifdef _WIN32 +#pragma once +#endif +//lint -save -e1931 -e1927 -e1924 -e613 -e726 + +// This header file defines the interface between the calling application and the code that +// knows how to communicate with the connection manager (CM) from the Steam service + +// This header file is intended to be portable; ideally this 1 header file plus a lib or dll +// is all you need to integrate the client library into some other tree. So please avoid +// including or requiring other header files if possible. This header should only describe the +// interface layer, no need to include anything about the implementation. + +#include "steamtypes.h" + + +// General result codes +enum EResult +{ + k_EResultOK = 1, // success + k_EResultFail = 2, // generic failure + k_EResultNoConnection = 3, // no/failed network connection +// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed + k_EResultInvalidPassword = 5, // password/ticket is invalid + k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere + k_EResultInvalidProtocolVer = 7, // protocol version is incorrect + k_EResultInvalidParam = 8, // a parameter is incorrect + k_EResultFileNotFound = 9, // file was not found + k_EResultBusy = 10, // called method busy - action not taken + k_EResultInvalidState = 11, // called object was in an invalid state + k_EResultInvalidName = 12, // name is invalid + k_EResultInvalidEmail = 13, // email is invalid + k_EResultDuplicateName = 14, // name is not unique + k_EResultAccessDenied = 15, // access is denied + k_EResultTimeout = 16, // operation timed out + k_EResultBanned = 17, // VAC2 banned + k_EResultAccountNotFound = 18, // account not found + k_EResultInvalidSteamID = 19, // steamID is invalid + k_EResultServiceUnavailable = 20, // The requested service is currently unavailable + k_EResultNotLoggedOn = 21, // The user is not logged on + k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party) + k_EResultEncryptionFailure = 23, // Encryption or Decryption failed + k_EResultInsufficientPrivilege = 24, // Insufficient privilege + k_EResultLimitExceeded = 25, // Too much of a good thing + k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes) + k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired + k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again + k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time + k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user + k_EResultIPNotFound = 31, // IP address not found + k_EResultPersistFailed = 32, // failed to write change to the data store + k_EResultLockingFailed = 33, // failed to acquire access lock for this operation + k_EResultLogonSessionReplaced = 34, + k_EResultConnectFailed = 35, + k_EResultHandshakeFailed = 36, + k_EResultIOFailure = 37, + k_EResultRemoteDisconnect = 38, + k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested + k_EResultBlocked = 40, // a user didn't allow it + k_EResultIgnored = 41, // target is ignoring sender + k_EResultNoMatch = 42, // nothing matching the request found + k_EResultAccountDisabled = 43, + k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now + k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available + k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin + k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol. + k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another. + k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed. + k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait + k_EResultSuspended = 51, // Long running operation (content download) suspended/paused + k_EResultCancelled = 52, // Operation canceled (typically by user: content download) + k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable + k_EResultDiskFull = 54, // Operation canceled - not enough disk space. + k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed + k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side + k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account + k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid + k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first + k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files + k_EResultIllegalPassword = 61, // The requested new password is not legal + k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer ) + k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure + k_EResultCannotUseOldPassword = 64, // The requested new password is not legal + k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid + k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent + k_EResultHardwareNotCapableOfIPT = 67, // + k_EResultIPTInitError = 68, // + k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user + k_EResultFacebookQueryError = 70, // Facebook query returned an error + k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired + k_EResultIPLoginRestrictionFailed = 72, + k_EResultAccountLockedDown = 73, + k_EResultAccountLogonDeniedVerifiedEmailRequired = 74, + k_EResultNoMatchingURL = 75, + k_EResultBadResponse = 76, // parse failure, missing field, etc. + k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password + k_EResultValueOutOfRange = 78 // the value entered is outside the acceptable range +}; + +// Error codes for use with the voice functions +enum EVoiceResult +{ + k_EVoiceResultOK = 0, + k_EVoiceResultNotInitialized = 1, + k_EVoiceResultNotRecording = 2, + k_EVoiceResultNoData = 3, + k_EVoiceResultBufferTooSmall = 4, + k_EVoiceResultDataCorrupted = 5, + k_EVoiceResultRestricted = 6, + k_EVoiceResultUnsupportedCodec = 7, + +}; + +// Result codes to GSHandleClientDeny/Kick +typedef enum +{ + k_EDenyInvalid = 0, + k_EDenyInvalidVersion = 1, + k_EDenyGeneric = 2, + k_EDenyNotLoggedOn = 3, + k_EDenyNoLicense = 4, + k_EDenyCheater = 5, + k_EDenyLoggedInElseWhere = 6, + k_EDenyUnknownText = 7, + k_EDenyIncompatibleAnticheat = 8, + k_EDenyMemoryCorruption = 9, + k_EDenyIncompatibleSoftware = 10, + k_EDenySteamConnectionLost = 11, + k_EDenySteamConnectionError = 12, + k_EDenySteamResponseTimedOut = 13, + k_EDenySteamValidationStalled = 14, + k_EDenySteamOwnerLeftGuestUser = 15, +} EDenyReason; + +// return type of GetAuthSessionTicket +typedef uint32 HAuthTicket; +const HAuthTicket k_HAuthTicketInvalid = 0; + +// results from BeginAuthSession +typedef enum +{ + k_EBeginAuthSessionResultOK = 0, // Ticket is valid for this game and this steamID. + k_EBeginAuthSessionResultInvalidTicket = 1, // Ticket is not valid. + k_EBeginAuthSessionResultDuplicateRequest = 2, // A ticket has already been submitted for this steamID + k_EBeginAuthSessionResultInvalidVersion = 3, // Ticket is from an incompatible interface version + k_EBeginAuthSessionResultGameMismatch = 4, // Ticket is not for this game + k_EBeginAuthSessionResultExpiredTicket = 5, // Ticket has expired +} EBeginAuthSessionResult; + +// Callback values for callback ValidateAuthTicketResponse_t which is a response to BeginAuthSession +typedef enum +{ + k_EAuthSessionResponseOK = 0, // Steam has verified the user is online, the ticket is valid and ticket has not been reused. + k_EAuthSessionResponseUserNotConnectedToSteam = 1, // The user in question is not connected to steam + k_EAuthSessionResponseNoLicenseOrExpired = 2, // The license has expired. + k_EAuthSessionResponseVACBanned = 3, // The user is VAC banned for this game. + k_EAuthSessionResponseLoggedInElseWhere = 4, // The user account has logged in elsewhere and the session containing the game instance has been disconnected. + k_EAuthSessionResponseVACCheckTimedOut = 5, // VAC has been unable to perform anti-cheat checks on this user + k_EAuthSessionResponseAuthTicketCanceled = 6, // The ticket has been canceled by the issuer + k_EAuthSessionResponseAuthTicketInvalidAlreadyUsed = 7, // This ticket has already been used, it is not valid. + k_EAuthSessionResponseAuthTicketInvalid = 8, // This ticket is not from a user instance currently connected to steam. +} EAuthSessionResponse; + +// results from UserHasLicenseForApp +typedef enum +{ + k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app + k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app + k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated +} EUserHasLicenseForAppResult; + + +// Steam universes. Each universe is a self-contained Steam instance. +enum EUniverse +{ + k_EUniverseInvalid = 0, + k_EUniversePublic = 1, + k_EUniverseBeta = 2, + k_EUniverseInternal = 3, + k_EUniverseDev = 4, + // k_EUniverseRC = 5, // no such universe anymore + k_EUniverseMax +}; + +// Steam account types +enum EAccountType +{ + k_EAccountTypeInvalid = 0, + k_EAccountTypeIndividual = 1, // single user account + k_EAccountTypeMultiseat = 2, // multiseat (e.g. cybercafe) account + k_EAccountTypeGameServer = 3, // game server account + k_EAccountTypeAnonGameServer = 4, // anonymous game server account + k_EAccountTypePending = 5, // pending + k_EAccountTypeContentServer = 6, // content server + k_EAccountTypeClan = 7, + k_EAccountTypeChat = 8, + k_EAccountTypeConsoleUser = 9, // Fake SteamID for local PSN account on PS3 or Live account on 360, etc. + k_EAccountTypeAnonUser = 10, + + // Max of 16 items in this field + k_EAccountTypeMax +}; + + + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +enum EAppReleaseState +{ + k_EAppReleaseState_Unknown = 0, // unknown, required appinfo or license info is missing + k_EAppReleaseState_Unavailable = 1, // even if user 'just' owns it, can see game at all + k_EAppReleaseState_Prerelease = 2, // can be purchased and is visible in games list, nothing else. Common appInfo section released + k_EAppReleaseState_PreloadOnly = 3, // owners can preload app, not play it. AppInfo fully released. + k_EAppReleaseState_Released = 4, // owners can download and play app. +}; + + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +enum EAppOwernshipFlags +{ + k_EAppOwernshipFlags_None = 0, // unknown + k_EAppOwernshipFlags_OwnsLicense = 1, // owns license for this game + k_EAppOwernshipFlags_FreeLicense = 2, // not paid for game + k_EAppOwernshipFlags_RegionRestricted = 4, // owns app, but not allowed to play in current region + k_EAppOwernshipFlags_LowViolence = 8, // only low violence version + k_EAppOwernshipFlags_InvalidPlatform = 16, // app not supported on current platform + k_EAppOwernshipFlags_DeviceLicense = 32, // license was granted by authorized local device +}; + + +//----------------------------------------------------------------------------- +// Purpose: designed as flags to allow filters masks +//----------------------------------------------------------------------------- +enum EAppType +{ + k_EAppType_Invalid = 0x000, // unknown / invalid + k_EAppType_Game = 0x001, // playable game, default type + k_EAppType_Application = 0x002, // software application + k_EAppType_Tool = 0x004, // SDKs, editors & dedicated servers + k_EAppType_Demo = 0x008, // game demo + k_EAppType_Media = 0x010, // media trailer + k_EAppType_DLC = 0x020, // down loadable content + k_EAppType_Guide = 0x040, // game guide, PDF etc + k_EAppType_Driver = 0x080, // hardware driver updater (ATI, Razor etc) + + k_EAppType_Shortcut = 0x40000000, // just a shortcut, client side only + k_EAppType_DepotOnly = 0x80000000, // placeholder since depots and apps share the same namespace +}; + + +//----------------------------------------------------------------------------- +// types of user game stats fields +// WARNING: DO NOT RENUMBER EXISTING VALUES - STORED IN DATABASE +//----------------------------------------------------------------------------- +enum ESteamUserStatType +{ + k_ESteamUserStatTypeINVALID = 0, + k_ESteamUserStatTypeINT = 1, + k_ESteamUserStatTypeFLOAT = 2, + // Read as FLOAT, set with count / session length + k_ESteamUserStatTypeAVGRATE = 3, + k_ESteamUserStatTypeACHIEVEMENTS = 4, + k_ESteamUserStatTypeGROUPACHIEVEMENTS = 5, + + // max, for sanity checks + k_ESteamUserStatTypeMAX +}; + + +//----------------------------------------------------------------------------- +// Purpose: Chat Entry Types (previously was only friend-to-friend message types) +//----------------------------------------------------------------------------- +enum EChatEntryType +{ + k_EChatEntryTypeInvalid = 0, + k_EChatEntryTypeChatMsg = 1, // Normal text message from another user + k_EChatEntryTypeTyping = 2, // Another user is typing (not used in multi-user chat) + k_EChatEntryTypeInviteGame = 3, // Invite from other user into that users current game + k_EChatEntryTypeEmote = 4, // text emote message (deprecated, should be treated as ChatMsg) + //k_EChatEntryTypeLobbyGameStart = 5, // lobby game is starting (dead - listen for LobbyGameCreated_t callback instead) + k_EChatEntryTypeLeftConversation = 6, // user has left the conversation ( closed chat window ) + // Above are previous FriendMsgType entries, now merged into more generic chat entry types + k_EChatEntryTypeEntered = 7, // user has entered the conversation (used in multi-user chat and group chat) + k_EChatEntryTypeWasKicked = 8, // user was kicked (data: 64-bit steamid of actor performing the kick) + k_EChatEntryTypeWasBanned = 9, // user was banned (data: 64-bit steamid of actor performing the ban) + k_EChatEntryTypeDisconnected = 10, // user disconnected + k_EChatEntryTypeHistoricalChat = 11, // a chat message from user's chat history or offilne message + +}; + + +//----------------------------------------------------------------------------- +// Purpose: Chat Room Enter Responses +//----------------------------------------------------------------------------- +enum EChatRoomEnterResponse +{ + k_EChatRoomEnterResponseSuccess = 1, // Success + k_EChatRoomEnterResponseDoesntExist = 2, // Chat doesn't exist (probably closed) + k_EChatRoomEnterResponseNotAllowed = 3, // General Denied - You don't have the permissions needed to join the chat + k_EChatRoomEnterResponseFull = 4, // Chat room has reached its maximum size + k_EChatRoomEnterResponseError = 5, // Unexpected Error + k_EChatRoomEnterResponseBanned = 6, // You are banned from this chat room and may not join + k_EChatRoomEnterResponseLimited = 7, // Joining this chat is not allowed because you are a limited user (no value on account) + k_EChatRoomEnterResponseClanDisabled = 8, // Attempt to join a clan chat when the clan is locked or disabled + k_EChatRoomEnterResponseCommunityBan = 9, // Attempt to join a chat when the user has a community lock on their account + k_EChatRoomEnterResponseMemberBlockedYou = 10, // Join failed - some member in the chat has blocked you from joining + k_EChatRoomEnterResponseYouBlockedMember = 11, // Join failed - you have blocked some member already in the chat + // k_EChatRoomEnterResponseNoRankingDataLobby = 12, // No longer used + // k_EChatRoomEnterResponseNoRankingDataUser = 13, // No longer used + // k_EChatRoomEnterResponseRankOutOfRange = 14, // No longer used +}; + + +//----------------------------------------------------------------------------- +// Purpose: Status of a given depot version, these are stored in the DB, don't renumber +//----------------------------------------------------------------------------- +enum EStatusDepotVersion +{ + k_EStatusDepotVersionInvalid = 0, + k_EStatusDepotVersionDisabled = 1, // version was disabled, no manifest & content available + k_EStatusDepotVersionAvailable = 2, // manifest & content is available, but not current + k_EStatusDepotVersionCurrent = 3, // current depot version. The can be multiple, one for public and one for each beta key +}; + + +typedef void (*PFNLegacyKeyRegistration)( const char *pchCDKey, const char *pchInstallPath ); +typedef bool (*PFNLegacyKeyInstalled)(); + +const unsigned int k_unSteamAccountIDMask = 0xFFFFFFFF; +const unsigned int k_unSteamAccountInstanceMask = 0x000FFFFF; +// we allow 3 simultaneous user account instances right now, 1= desktop, 2 = console, 4 = web, 0 = all +const unsigned int k_unSteamUserDesktopInstance = 1; +const unsigned int k_unSteamUserConsoleInstance = 2; +const unsigned int k_unSteamUserWebInstance = 4; + +// Special flags for Chat accounts - they go in the top 8 bits +// of the steam ID's "instance", leaving 12 for the actual instances +enum EChatSteamIDInstanceFlags +{ + k_EChatAccountInstanceMask = 0x00000FFF, // top 8 bits are flags + + k_EChatInstanceFlagClan = ( k_unSteamAccountInstanceMask + 1 ) >> 1, // top bit + k_EChatInstanceFlagLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 2, // next one down, etc + k_EChatInstanceFlagMMSLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 3, // next one down, etc + + // Max of 8 flags +}; + + +//----------------------------------------------------------------------------- +// Purpose: Marketing message flags that change how a client should handle them +//----------------------------------------------------------------------------- +enum EMarketingMessageFlags +{ + k_EMarketingMessageFlagsNone = 0, + k_EMarketingMessageFlagsHighPriority = 1 << 0, + k_EMarketingMessageFlagsPlatformWindows = 1 << 1, + k_EMarketingMessageFlagsPlatformMac = 1 << 2, + k_EMarketingMessageFlagsPlatformLinux = 1 << 3, + + //aggregate flags + k_EMarketingMessageFlagsPlatformRestrictions = + k_EMarketingMessageFlagsPlatformWindows | + k_EMarketingMessageFlagsPlatformMac | + k_EMarketingMessageFlagsPlatformLinux, +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Possible positions to tell the overlay to show notifications in +//----------------------------------------------------------------------------- +enum ENotificationPosition +{ + k_EPositionTopLeft = 0, + k_EPositionTopRight = 1, + k_EPositionBottomLeft = 2, + k_EPositionBottomRight = 3, +}; + + +#pragma pack( push, 1 ) + +#define CSTEAMID_DEFINED + +// Steam ID structure (64 bits total) +class CSteamID +{ +public: + + //----------------------------------------------------------------------------- + // Purpose: Constructor + //----------------------------------------------------------------------------- + CSteamID() + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; + m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + CSteamID( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) + { + Set( unAccountID, eUniverse, eAccountType ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : unAccountID - 32-bit account ID + // unAccountInstance - instance + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + CSteamID( uint32 unAccountID, unsigned int unAccountInstance, EUniverse eUniverse, EAccountType eAccountType ) + { +#if defined(_SERVER) && defined(Assert) + Assert( ! ( ( k_EAccountTypeIndividual == eAccountType ) && ( unAccountInstance > k_unSteamUserWebInstance ) ) ); // enforce that for individual accounts, instance is always 1 +#endif // _SERVER + InstancedSet( unAccountID, unAccountInstance, eUniverse, eAccountType ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : ulSteamID - 64-bit representation of a Steam ID + // Note: Will not accept a uint32 or int32 as input, as that is a probable mistake. + // See the stubbed out overloads in the private: section for more info. + //----------------------------------------------------------------------------- + CSteamID( uint64 ulSteamID ) + { + SetFromUint64( ulSteamID ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Sets parameters for steam ID + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + void Set( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = unAccountID; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + + if ( eAccountType == k_EAccountTypeClan ) + { + m_steamid.m_comp.m_unAccountInstance = 0; + } + else + { + // by default we pick the desktop instance + m_steamid.m_comp.m_unAccountInstance = k_unSteamUserDesktopInstance; + } + } + + + //----------------------------------------------------------------------------- + // Purpose: Sets parameters for steam ID + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + void InstancedSet( uint32 unAccountID, uint32 unInstance, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = unAccountID; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + m_steamid.m_comp.m_unAccountInstance = unInstance; + } + + + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from its 52 bit parts and universe/type + // Input : ulIdentifier - 52 bits of goodness + //----------------------------------------------------------------------------- + void FullSet( uint64 ulIdentifier, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = ( ulIdentifier & k_unSteamAccountIDMask ); // account ID is low 32 bits + m_steamid.m_comp.m_unAccountInstance = ( ( ulIdentifier >> 32 ) & k_unSteamAccountInstanceMask ); // account instance is next 20 bits + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + } + + + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from its 64-bit representation + // Input : ulSteamID - 64-bit representation of a Steam ID + //----------------------------------------------------------------------------- + void SetFromUint64( uint64 ulSteamID ) + { + m_steamid.m_unAll64Bits = ulSteamID; + } + + + //----------------------------------------------------------------------------- + // Purpose: Clear all fields, leaving an invalid ID. + //----------------------------------------------------------------------------- + void Clear() + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; + m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + +#if defined( INCLUDED_STEAM_COMMON_STEAMCOMMON_H ) + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from a Steam2 ID structure + // Input: pTSteamGlobalUserID - Steam2 ID to convert + // eUniverse - universe this ID belongs to + //----------------------------------------------------------------------------- + void SetFromSteam2( TSteamGlobalUserID *pTSteamGlobalUserID, EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits * 2 + + pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits; + m_steamid.m_comp.m_EUniverse = eUniverse; // set the universe + m_steamid.m_comp.m_EAccountType = k_EAccountTypeIndividual; // Steam 2 accounts always map to account type of individual + m_steamid.m_comp.m_unAccountInstance = k_unSteamUserDesktopInstance; // Steam2 only knew desktop instances + } + + //----------------------------------------------------------------------------- + // Purpose: Fills out a Steam2 ID structure + // Input: pTSteamGlobalUserID - Steam2 ID to write to + //----------------------------------------------------------------------------- + void ConvertToSteam2( TSteamGlobalUserID *pTSteamGlobalUserID ) const + { + // only individual accounts have any meaning in Steam 2, only they can be mapped + // Assert( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ); + + pTSteamGlobalUserID->m_SteamInstanceID = 0; + pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits = m_steamid.m_comp.m_unAccountID % 2; + pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits = m_steamid.m_comp.m_unAccountID / 2; + } +#endif // defined( INCLUDED_STEAM_COMMON_STEAMCOMMON_H ) + + //----------------------------------------------------------------------------- + // Purpose: Converts steam ID to its 64-bit representation + // Output : 64-bit representation of a Steam ID + //----------------------------------------------------------------------------- + uint64 ConvertToUint64() const + { + return m_steamid.m_unAll64Bits; + } + + + //----------------------------------------------------------------------------- + // Purpose: Converts the static parts of a steam ID to a 64-bit representation. + // For multiseat accounts, all instances of that account will have the + // same static account key, so they can be grouped together by the static + // account key. + // Output : 64-bit static account key + //----------------------------------------------------------------------------- + uint64 GetStaticAccountKey() const + { + // note we do NOT include the account instance (which is a dynamic property) in the static account key + return (uint64) ( ( ( (uint64) m_steamid.m_comp.m_EUniverse ) << 56 ) + ((uint64) m_steamid.m_comp.m_EAccountType << 52 ) + m_steamid.m_comp.m_unAccountID ); + } + + + //----------------------------------------------------------------------------- + // Purpose: create an anonymous game server login to be filled in by the AM + //----------------------------------------------------------------------------- + void CreateBlankAnonLogon( EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonGameServer; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + + //----------------------------------------------------------------------------- + // Purpose: create an anonymous game server login to be filled in by the AM + //----------------------------------------------------------------------------- + void CreateBlankAnonUserLogon( EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonUser; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous game server login that will be filled in? + //----------------------------------------------------------------------------- + bool BBlankAnonAccount() const + { + return m_steamid.m_comp.m_unAccountID == 0 && BAnonAccount() && m_steamid.m_comp.m_unAccountInstance == 0; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a game server account id? (Either persistent or anonymous) + //----------------------------------------------------------------------------- + bool BGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a persistent (not anonymous) game server account id? + //----------------------------------------------------------------------------- + bool BPersistentGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous game server account id? + //----------------------------------------------------------------------------- + bool BAnonGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a content server account id? + //----------------------------------------------------------------------------- + bool BContentServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeContentServer; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this a clan account id? + //----------------------------------------------------------------------------- + bool BClanAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this a chat account id? + //----------------------------------------------------------------------------- + bool BChatAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a chat account id? + //----------------------------------------------------------------------------- + bool IsLobby() const + { + return ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat ) + && ( m_steamid.m_comp.m_unAccountInstance & k_EChatInstanceFlagLobby ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this an individual user account id? + //----------------------------------------------------------------------------- + bool BIndividualAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual || m_steamid.m_comp.m_EAccountType == k_EAccountTypeConsoleUser; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous account? + //----------------------------------------------------------------------------- + bool BAnonAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous user account? ( used to create an account or reset a password ) + //----------------------------------------------------------------------------- + bool BAnonUserAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a faked up Steam ID for a PSN friend account? + //----------------------------------------------------------------------------- + bool BConsoleUserAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeConsoleUser; + } + + // simple accessors + void SetAccountID( uint32 unAccountID ) { m_steamid.m_comp.m_unAccountID = unAccountID; } + void SetAccountInstance( uint32 unInstance ){ m_steamid.m_comp.m_unAccountInstance = unInstance; } + void ClearIndividualInstance() { if ( BIndividualAccount() ) m_steamid.m_comp.m_unAccountInstance = 0; } + bool HasNoIndividualInstance() const { return BIndividualAccount() && (m_steamid.m_comp.m_unAccountInstance==0); } + AccountID_t GetAccountID() const { return m_steamid.m_comp.m_unAccountID; } + uint32 GetUnAccountInstance() const { return m_steamid.m_comp.m_unAccountInstance; } + EAccountType GetEAccountType() const { return ( EAccountType ) m_steamid.m_comp.m_EAccountType; } + EUniverse GetEUniverse() const { return m_steamid.m_comp.m_EUniverse; } + void SetEUniverse( EUniverse eUniverse ) { m_steamid.m_comp.m_EUniverse = eUniverse; } + bool IsValid() const; + + // this set of functions is hidden, will be moved out of class + explicit CSteamID( const char *pchSteamID, EUniverse eDefaultUniverse = k_EUniverseInvalid ); + const char * Render() const; // renders this steam ID to string + static const char * Render( uint64 ulSteamID ); // static method to render a uint64 representation of a steam ID to a string + + void SetFromString( const char *pchSteamID, EUniverse eDefaultUniverse ); + // SetFromString allows many partially-correct strings, constraining how + // we might be able to change things in the future. + // SetFromStringStrict requires the exact string forms that we support + // and is preferred when the caller knows it's safe to be strict. + // Returns whether the string parsed correctly. + bool SetFromStringStrict( const char *pchSteamID, EUniverse eDefaultUniverse ); + bool SetFromSteam2String( const char *pchSteam2ID, EUniverse eUniverse ); + + inline bool operator==( const CSteamID &val ) const { return m_steamid.m_unAll64Bits == val.m_steamid.m_unAll64Bits; } + inline bool operator!=( const CSteamID &val ) const { return !operator==( val ); } + inline bool operator<( const CSteamID &val ) const { return m_steamid.m_unAll64Bits < val.m_steamid.m_unAll64Bits; } + inline bool operator>( const CSteamID &val ) const { return m_steamid.m_unAll64Bits > val.m_steamid.m_unAll64Bits; } + + // DEBUG function + bool BValidExternalSteamID() const; + +private: + // These are defined here to prevent accidental implicit conversion of a u32AccountID to a CSteamID. + // If you get a compiler error about an ambiguous constructor/function then it may be because you're + // passing a 32-bit int to a function that takes a CSteamID. You should explicitly create the SteamID + // using the correct Universe and account Type/Instance values. + CSteamID( uint32 ); + CSteamID( int32 ); + + // 64 bits total + union SteamID_t + { + struct SteamIDComponent_t + { +#ifdef VALVE_BIG_ENDIAN + EUniverse m_EUniverse : 8; // universe this account belongs to + unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference + unsigned int m_unAccountInstance : 20; // dynamic instance ID + uint32 m_unAccountID : 32; // unique account identifier +#else + uint32 m_unAccountID : 32; // unique account identifier + unsigned int m_unAccountInstance : 20; // dynamic instance ID + unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference + EUniverse m_EUniverse : 8; // universe this account belongs to +#endif + } m_comp; + + uint64 m_unAll64Bits; + } m_steamid; +}; + +inline bool CSteamID::IsValid() const +{ + if ( m_steamid.m_comp.m_EAccountType <= k_EAccountTypeInvalid || m_steamid.m_comp.m_EAccountType >= k_EAccountTypeMax ) + return false; + + if ( m_steamid.m_comp.m_EUniverse <= k_EUniverseInvalid || m_steamid.m_comp.m_EUniverse >= k_EUniverseMax ) + return false; + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance > k_unSteamUserWebInstance ) + return false; + } + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 0 ) + return false; + } + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 ) + return false; + // Any limit on instances? We use them for local users and bots + } + return true; +} + +// generic invalid CSteamID +#define k_steamIDNil CSteamID() + +// This steamID comes from a user game connection to an out of date GS that hasnt implemented the protocol +// to provide its steamID +#define k_steamIDOutofDateGS CSteamID( 0, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) +// This steamID comes from a user game connection to an sv_lan GS +#define k_steamIDLanModeGS CSteamID( 0, 0, k_EUniversePublic, k_EAccountTypeInvalid ) +// This steamID can come from a user game connection to a GS that has just booted but hasnt yet even initialized +// its steam3 component and started logging on. +#define k_steamIDNotInitYetGS CSteamID( 1, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) +// This steamID can come from a user game connection to a GS that isn't using the steam authentication system but still +// wants to support the "Join Game" option in the friends list +#define k_steamIDNonSteamGS CSteamID( 2, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) + + +#ifdef STEAM +// Returns the matching chat steamID, with the default instance of 0 +// If the steamID passed in is already of type k_EAccountTypeChat it will be returned with the same instance +CSteamID ChatIDFromSteamID( const CSteamID &steamID ); +// Returns the matching clan steamID, with the default instance of 0 +// If the steamID passed in is already of type k_EAccountTypeClan it will be returned with the same instance +CSteamID ClanIDFromSteamID( const CSteamID &steamID ); +// Asserts steamID type before conversion +CSteamID ChatIDFromClanID( const CSteamID &steamIDClan ); +// Asserts steamID type before conversion +CSteamID ClanIDFromChatID( const CSteamID &steamIDChat ); + +#endif // _STEAM + + +//----------------------------------------------------------------------------- +// Purpose: encapsulates an appID/modID pair +//----------------------------------------------------------------------------- +class CGameID +{ +public: + + CGameID() + { + m_gameID.m_nType = k_EGameIDTypeApp; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nModID = 0; + } + + explicit CGameID( uint64 ulGameID ) + { + m_ulGameID = ulGameID; + } + + explicit CGameID( int32 nAppID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + } + + explicit CGameID( uint32 nAppID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + } + + CGameID( uint32 nAppID, uint32 nModID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + m_gameID.m_nModID = nModID; + m_gameID.m_nType = k_EGameIDTypeGameMod; + } + + // Hidden functions used only by Steam + explicit CGameID( const char *pchGameID ); + const char *Render() const; // render this Game ID to string + static const char *Render( uint64 ulGameID ); // static method to render a uint64 representation of a Game ID to a string + + // must include checksum_crc.h first to get this functionality +#if defined( CHECKSUM_CRC_H ) + CGameID( uint32 nAppID, const char *pchModPath ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + m_gameID.m_nType = k_EGameIDTypeGameMod; + + char rgchModDir[MAX_PATH]; + Q_FileBase( pchModPath, rgchModDir, sizeof( rgchModDir ) ); + CRC32_t crc32; + CRC32_Init( &crc32 ); + CRC32_ProcessBuffer( &crc32, rgchModDir, Q_strlen( rgchModDir ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + + CGameID( const char *pchExePath, const char *pchAppName ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nType = k_EGameIDTypeShortcut; + + CRC32_t crc32; + CRC32_Init( &crc32 ); + CRC32_ProcessBuffer( &crc32, pchExePath, Q_strlen( pchExePath ) ); + CRC32_ProcessBuffer( &crc32, pchAppName, Q_strlen( pchAppName ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + +#if defined( VSTFILEID_H ) + + CGameID( VstFileID vstFileID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nType = k_EGameIDTypeP2P; + + CRC32_t crc32; + CRC32_Init( &crc32 ); + const char *pchFileId = vstFileID.Render(); + CRC32_ProcessBuffer( &crc32, pchFileId, Q_strlen( pchFileId ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + +#endif /* VSTFILEID_H */ + +#endif /* CHECKSUM_CRC_H */ + + + uint64 ToUint64() const + { + return m_ulGameID; + } + + uint64 *GetUint64Ptr() + { + return &m_ulGameID; + } + + void Set( uint64 ulGameID ) + { + m_ulGameID = ulGameID; + } + + bool IsMod() const + { + return ( m_gameID.m_nType == k_EGameIDTypeGameMod ); + } + + bool IsShortcut() const + { + return ( m_gameID.m_nType == k_EGameIDTypeShortcut ); + } + + bool IsP2PFile() const + { + return ( m_gameID.m_nType == k_EGameIDTypeP2P ); + } + + bool IsSteamApp() const + { + return ( m_gameID.m_nType == k_EGameIDTypeApp ); + } + + uint32 ModID() const + { + return m_gameID.m_nModID; + } + + uint32 AppID() const + { + return m_gameID.m_nAppID; + } + + bool operator == ( const CGameID &rhs ) const + { + return m_ulGameID == rhs.m_ulGameID; + } + + bool operator != ( const CGameID &rhs ) const + { + return !(*this == rhs); + } + + bool operator < ( const CGameID &rhs ) const + { + return ( m_ulGameID < rhs.m_ulGameID ); + } + + bool IsValid() const + { + // each type has it's own invalid fixed point: + switch( m_gameID.m_nType ) + { + case k_EGameIDTypeApp: + return m_gameID.m_nAppID != k_uAppIdInvalid; + + case k_EGameIDTypeGameMod: + return m_gameID.m_nAppID != k_uAppIdInvalid && m_gameID.m_nModID & 0x80000000; + + case k_EGameIDTypeShortcut: + return (m_gameID.m_nModID & 0x80000000) != 0; + + case k_EGameIDTypeP2P: + return m_gameID.m_nAppID == k_uAppIdInvalid && m_gameID.m_nModID & 0x80000000; + + default: +#if defined(Assert) + Assert(false); +#endif + return false; + } + + } + + void Reset() + { + m_ulGameID = 0; + } + + + +private: + + enum EGameIDType + { + k_EGameIDTypeApp = 0, + k_EGameIDTypeGameMod = 1, + k_EGameIDTypeShortcut = 2, + k_EGameIDTypeP2P = 3, + }; + + struct GameID_t + { +#ifdef VALVE_BIG_ENDIAN + unsigned int m_nModID : 32; + unsigned int m_nType : 8; + unsigned int m_nAppID : 24; +#else + unsigned int m_nAppID : 24; + unsigned int m_nType : 8; + unsigned int m_nModID : 32; +#endif + }; + + union + { + uint64 m_ulGameID; + GameID_t m_gameID; + }; +}; + +#pragma pack( pop ) + +const int k_cchGameExtraInfoMax = 64; + + +//----------------------------------------------------------------------------- +// Constants used for query ports. +//----------------------------------------------------------------------------- + +#define QUERY_PORT_NOT_INITIALIZED 0xFFFF // We haven't asked the GS for this query port's actual value yet. +#define QUERY_PORT_ERROR 0xFFFE // We were unable to get the query port for this server. + + +//----------------------------------------------------------------------------- +// Purpose: Passed as argument to SteamAPI_UseBreakpadCrashHandler to enable optional callback +// just before minidump file is captured after a crash has occurred. (Allows app to append additional comment data to the dump, etc.) +//----------------------------------------------------------------------------- +typedef void (*PFNPreMinidumpCallback)(void *context); + +//----------------------------------------------------------------------------- +// Purpose: Used by ICrashHandler interfaces to reference particular installed crash handlers +//----------------------------------------------------------------------------- +typedef void *BREAKPAD_HANDLE; +#define BREAKPAD_INVALID_HANDLE (BREAKPAD_HANDLE)0 + +#endif // STEAMCLIENTPUBLIC_H diff --git a/dep/hlsdk/public/steam/steamhttpenums.h b/dep/hlsdk/public/steam/steamhttpenums.h new file mode 100644 index 0000000..59782d5 --- /dev/null +++ b/dep/hlsdk/public/steam/steamhttpenums.h @@ -0,0 +1,94 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: HTTP related enums, stuff that is shared by both clients and servers, and our +// UI projects goes here. +// +//============================================================================= + +#ifndef STEAMHTTPENUMS_H +#define STEAMHTTPENUMS_H +#ifdef _WIN32 +#pragma once +#endif + +// HTTP related types + +// This enum is used in client API methods, do not re-number existing values. +enum EHTTPMethod +{ + k_EHTTPMethodInvalid = 0, + k_EHTTPMethodGET, + k_EHTTPMethodHEAD, + k_EHTTPMethodPOST, + + // The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for + // a compliant general purpose server. We'll likely add more as we find uses for them. + + // k_EHTTPMethodOPTIONS, + k_EHTTPMethodPUT, + k_EHTTPMethodDELETE, + // k_EHTTPMethodTRACE, + // k_EHTTPMethodCONNECT +}; + + +// HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions +// of each of these. +enum EHTTPStatusCode +{ + // Invalid status code (this isn't defined in HTTP, used to indicate unset in our code) + k_EHTTPStatusCodeInvalid = 0, + + // Informational codes + k_EHTTPStatusCode100Continue = 100, + k_EHTTPStatusCode101SwitchingProtocols = 101, + + // Success codes + k_EHTTPStatusCode200OK = 200, + k_EHTTPStatusCode201Created = 201, + k_EHTTPStatusCode202Accepted = 202, + k_EHTTPStatusCode203NonAuthoritative = 203, + k_EHTTPStatusCode204NoContent = 204, + k_EHTTPStatusCode205ResetContent = 205, + k_EHTTPStatusCode206PartialContent = 206, + + // Redirection codes + k_EHTTPStatusCode300MultipleChoices = 300, + k_EHTTPStatusCode301MovedPermanently = 301, + k_EHTTPStatusCode302Found = 302, + k_EHTTPStatusCode303SeeOther = 303, + k_EHTTPStatusCode304NotModified = 304, + k_EHTTPStatusCode305UseProxy = 305, + //k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1) + k_EHTTPStatusCode307TemporaryRedirect = 307, + + // Error codes + k_EHTTPStatusCode400BadRequest = 400, + k_EHTTPStatusCode401Unauthorized = 401, + k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients + k_EHTTPStatusCode403Forbidden = 403, + k_EHTTPStatusCode404NotFound = 404, + k_EHTTPStatusCode405MethodNotAllowed = 405, + k_EHTTPStatusCode406NotAcceptable = 406, + k_EHTTPStatusCode407ProxyAuthRequired = 407, + k_EHTTPStatusCode408RequestTimeout = 408, + k_EHTTPStatusCode409Conflict = 409, + k_EHTTPStatusCode410Gone = 410, + k_EHTTPStatusCode411LengthRequired = 411, + k_EHTTPStatusCode412PreconditionFailed = 412, + k_EHTTPStatusCode413RequestEntityTooLarge = 413, + k_EHTTPStatusCode414RequestURITooLong = 414, + k_EHTTPStatusCode415UnsupportedMediaType = 415, + k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416, + k_EHTTPStatusCode417ExpectationFailed = 417, + + // Server error codes + k_EHTTPStatusCode500InternalServerError = 500, + k_EHTTPStatusCode501NotImplemented = 501, + k_EHTTPStatusCode502BadGateway = 502, + k_EHTTPStatusCode503ServiceUnavailable = 503, + k_EHTTPStatusCode504GatewayTimeout = 504, + k_EHTTPStatusCode505HTTPVersionNotSupported = 505, +}; + +#endif // STEAMHTTPENUMS_H diff --git a/dep/hlsdk/public/steam/steamtypes.h b/dep/hlsdk/public/steam/steamtypes.h new file mode 100644 index 0000000..57ffc93 --- /dev/null +++ b/dep/hlsdk/public/steam/steamtypes.h @@ -0,0 +1,120 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMTYPES_H +#define STEAMTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +// Steam-specific types. Defined here so this header file can be included in other code bases. +#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 + +// Make sure VALVE_BIG_ENDIAN gets set on PS3, may already be set previously in Valve internal code. +#if !defined(VALVE_BIG_ENDIAN) && defined(_PS3) +#define VALVE_BIG_ENDIAN +#endif + +#if defined( _WIN32 ) + +#ifdef X64BITS +typedef __int64 intp; // intp is an integer that can accomodate a pointer +typedef unsigned __int64 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) +#else +typedef __int32 intp; +typedef unsigned __int32 uintp; +#endif + +#else // _WIN32 + +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif // else _WIN32 + +const int k_cubSaltSize = 8; +typedef uint8 Salt_t[ k_cubSaltSize ]; + +//----------------------------------------------------------------------------- +// GID (GlobalID) stuff +// This is a globally unique identifier. It's guaranteed to be unique across all +// racks and servers for as long as a given universe persists. +//----------------------------------------------------------------------------- +// NOTE: for GID parsing/rendering and other utils, see gid.h +typedef uint64 GID_t; + +const GID_t k_GIDNil = 0xffffffffffffffffull; + +// For convenience, we define a number of types that are just new names for GIDs +typedef GID_t JobID_t; // Each Job has a unique ID +typedef GID_t TxnID_t; // Each financial transaction has a unique ID + +const GID_t k_TxnIDNil = k_GIDNil; +const GID_t k_TxnIDUnknown = 0; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +typedef uint32 PackageId_t; +const PackageId_t k_uPackageIdFreeSub = 0x0; +const PackageId_t k_uPackageIdInvalid = 0xFFFFFFFF; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +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; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. AppIds and DepotIDs also presently +// share the same namespace, but since we'd like to change that in the future +// I've defined it seperately here. +typedef uint32 DepotId_t; +const DepotId_t k_uDepotIdInvalid = 0x0; + +// RTime32 +// We use this 32 bit time representing real world time. +// It offers 1 second resolution beginning on January 1, 1970 (Unix time) +typedef uint32 RTime32; + +typedef uint32 CellID_t; +const CellID_t k_uCellIDInvalid = 0xFFFFFFFF; + +// handle to a Steam API call +typedef uint64 SteamAPICall_t; +const SteamAPICall_t k_uAPICallInvalid = 0x0; + +typedef uint32 AccountID_t; + +typedef uint32 PartnerId_t; +const PartnerId_t k_uPartnerIdInvalid = 0; + +#endif // STEAMTYPES_H diff --git a/dep/hlsdk/public/steamid.cpp b/dep/hlsdk/public/steamid.cpp new file mode 100644 index 0000000..db24cea --- /dev/null +++ b/dep/hlsdk/public/steamid.cpp @@ -0,0 +1,32 @@ +#include "precompiled.h" + +bool CSteamID::SetFromSteam2String(const char *pchSteam2ID, EUniverse eUniverse) +{ + Assert(pchSteam2ID); + + // Convert the Steam2 ID string to a Steam2 ID structure + TSteamGlobalUserID steam2ID; + steam2ID.m_SteamInstanceID = 0; + steam2ID.m_SteamLocalUserID.Split.High32bits = 0; + steam2ID.m_SteamLocalUserID.Split.Low32bits = 0; + + const char *pchTSteam2ID = pchSteam2ID; + + // Customer support is fond of entering steam IDs in the following form: STEAM_n:x:y + char *pchOptionalLeadString = "STEAM_"; + if (Q_strnicmp(pchSteam2ID, pchOptionalLeadString, Q_strlen(pchOptionalLeadString)) == 0) + pchTSteam2ID = pchSteam2ID + Q_strlen(pchOptionalLeadString); + + char cExtraCharCheck = 0; + + int cFieldConverted = sscanf(pchTSteam2ID, "%hu:%u:%u%c", &steam2ID.m_SteamInstanceID, + &steam2ID.m_SteamLocalUserID.Split.High32bits, &steam2ID.m_SteamLocalUserID.Split.Low32bits, &cExtraCharCheck); + + // Validate the conversion ... a special case is steam2 instance ID 1 which is reserved for special DoD handling + if (cExtraCharCheck != 0 || cFieldConverted == EOF || cFieldConverted < 2 || (cFieldConverted < 3 && steam2ID.m_SteamInstanceID != 1)) + return false; + + // Now convert to steam ID from the Steam2 ID structure + SetFromSteam2(&steam2ID, eUniverse); + return true; +} diff --git a/dep/hlsdk/public/strtools.h b/dep/hlsdk/public/strtools.h new file mode 100644 index 0000000..8b414bf --- /dev/null +++ b/dep/hlsdk/public/strtools.h @@ -0,0 +1,211 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#ifdef _WIN32 +const char CORRECT_PATH_SEPARATOR = '\\'; +const char INCORRECT_PATH_SEPARATOR = '/'; +#else +const char CORRECT_PATH_SEPARATOR = '/'; +const char INCORRECT_PATH_SEPARATOR = '\\'; +#endif + +#if !defined(_WIN32) +inline char *_strupr(char *start) +{ + char *str = start; + while (str && *str) + { + *str = (char)toupper(*str); + str++; + } + + return start; +} + +inline char *_strlwr(char *start) +{ + char *str = start; + while (str && *str) + { + *str = (char)tolower(*str); + str++; + } + + return start; +} +#endif + +#if defined(ASMLIB_H) && defined(HAVE_OPT_STRTOOLS) + #define Q_memset A_memset + #define Q_memcpy A_memcpy + #define Q_memcmp A_memcmp + #define Q_memmove A_memmove + #define Q_strlen A_strlen + #define Q_strcpy A_strcpy + #define Q_strncpy strncpy + #define Q_strcat A_strcat + #define Q_strncat strncat + #define Q_strcmp A_strcmp + #define Q_strncmp strncmp + #define Q_strdup _strdup + #define Q_stricmp A_stricmp + #define Q_strnicmp _strnicmp + #define Q_strstr A_strstr + #define Q_strchr strchr + #define Q_strrchr strrchr + #define Q_strlwr A_strtolower + #define Q_strupr A_strtoupper + #define Q_sprintf sprintf + #define Q_snprintf _snprintf + #define Q_vsnprintf _vsnprintf + #define Q_vsnwprintf _vsnwprintf + #define Q_atoi atoi + #define Q_atof atof + #define Q_sqrt M_sqrt + #define Q_min M_min + #define Q_max M_max + #define Q_clamp M_clamp + #define Q_abs abs + #define Q_fabs fabs + #define Q_tan tan + #define Q_atan atan + #define Q_atan2 atan2 + #define Q_acos acos + #define Q_cos cos + #define Q_sin sin + #define Q_pow pow + #define Q_fmod fmod +#else + #define Q_memset memset + #define Q_memcpy memcpy + #define Q_memcmp memcmp + #define Q_memmove memmove + #define Q_strlen strlen + #define Q_strcpy strcpy + #define Q_strncpy strncpy + #define Q_strcat strcat + #define Q_strncat strncat + #define Q_strcmp strcmp + #define Q_strncmp strncmp + #define Q_strdup _strdup + #define Q_stricmp _stricmp + #define Q_strnicmp _strnicmp + #define Q_strstr strstr + #define Q_strchr strchr + #define Q_strrchr strrchr + #define Q_strlwr _strlwr + #define Q_strupr _strupr + #define Q_sprintf sprintf + #define Q_snprintf _snprintf + #define Q_vsnprintf _vsnprintf + #define Q_vsnwprintf _vsnwprintf + #define Q_atoi atoi + #define Q_atof atof + #define Q_sqrt sqrt + #define Q_min min + #define Q_max max + #define Q_clamp clamp + #define Q_abs abs + #define Q_fabs fabs + #define Q_tan tan + #define Q_atan atan + #define Q_atan2 atan2 + #define Q_acos acos + #define Q_cos cos + #define Q_sin sin + #define Q_pow pow + #define Q_fmod fmod +#endif // #if defined(ASMLIB_H) && defined(HAVE_OPT_STRTOOLS) + +// a safe variant of strcpy that truncates the result to fit in the destination buffer +template +char *Q_strlcpy(char (&dest)[size], const char *src) { + Q_strncpy(dest, src, size - 1); + dest[size - 1] = '\0'; + return dest; +} + +inline char *Q_strnlcpy(char *dest, const char *src, size_t n) { + Q_strncpy(dest, src, n - 1); + dest[n - 1] = '\0'; + return dest; +} + +// safely concatenate two strings. +// a variant of strcat that truncates the result to fit in the destination buffer +template +size_t Q_strlcat(char (&dest)[size], const char *src) +{ + size_t srclen; // Length of source string + size_t dstlen; // Length of destination string + + // Figure out how much room is left + dstlen = Q_strlen(dest); + size_t length = size - dstlen + 1; + + if (!length) { + // No room, return immediately + return dstlen; + } + + // Figure out how much room is needed + srclen = Q_strlen(src); + + // Copy the appropriate amount + if (srclen > length) { + srclen = length; + } + + Q_memcpy(dest + dstlen, src, srclen); + dest[dstlen + srclen] = '\0'; + + return dstlen + srclen; +} + +// Force slashes of either type to be = separator character +inline void Q_FixSlashes(char *pname, char separator = CORRECT_PATH_SEPARATOR) +{ + while (*pname) + { + if (*pname == INCORRECT_PATH_SEPARATOR || *pname == CORRECT_PATH_SEPARATOR) + { + *pname = separator; + } + + pname++; + } +} + +// strcpy that works correctly with overlapping src and dst buffers +inline char *Q_strcpy_s(char *dst, char *src) { + int len = Q_strlen(src); + Q_memmove(dst, src, len + 1); + return dst; +} diff --git a/dep/hlsdk/public/tier0/dbg.cpp b/dep/hlsdk/public/tier0/dbg.cpp new file mode 100644 index 0000000..07edddf --- /dev/null +++ b/dep/hlsdk/public/tier0/dbg.cpp @@ -0,0 +1,400 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +// internal structures +enum +{ + MAX_GROUP_NAME_LENGTH = 48 +}; + +struct SpewGroup_t +{ + char m_GroupName[MAX_GROUP_NAME_LENGTH]; + int m_Level; +}; + +// Templates to assist in validating pointers: +void _AssertValidReadPtr(void* ptr, int count/* = 1*/) +{ +#ifdef _WIN32 + Assert(!IsBadReadPtr(ptr, count)); +#else + Assert(ptr); +#endif + +} + +void _AssertValidWritePtr(void* ptr, int count/* = 1*/) +{ +#ifdef _WIN32 + Assert(!IsBadWritePtr(ptr, count)); +#else + Assert(ptr); +#endif +} + +void _AssertValidReadWritePtr(void* ptr, int count/* = 1*/) +{ +#ifdef _WIN32 + Assert(!(IsBadWritePtr(ptr, count) || IsBadReadPtr(ptr, count))); +#else + Assert(ptr); +#endif +} + +void AssertValidStringPtr(const char* ptr, int maxchar/* = 0xFFFFFF */) +{ +#ifdef _WIN32 + Assert(!IsBadStringPtr(ptr, maxchar)); +#else + Assert(ptr); +#endif +} + +// globals +SpewRetval_t DefaultSpewFunc(SpewType_t type, char const *pMsg) +{ + printf("%s", pMsg); + if (type == SPEW_ASSERT) + return SPEW_DEBUGGER; + else if (type == SPEW_ERROR) + return SPEW_ABORT; + else + return SPEW_CONTINUE; +} + +static SpewOutputFunc_t s_SpewOutputFunc = DefaultSpewFunc; + +static char const* s_pFileName; +static int s_Line; +static SpewType_t s_SpewType; + +static SpewGroup_t* s_pSpewGroups = 0; +static int s_GroupCount = 0; +static int s_DefaultLevel = 0; + +// Spew output management. +void SpewOutputFunc(SpewOutputFunc_t func) +{ + s_SpewOutputFunc = func ? func : DefaultSpewFunc; +} + +SpewOutputFunc_t GetSpewOutputFunc(void) +{ + if (s_SpewOutputFunc) + { + return s_SpewOutputFunc; + } + else + { + return DefaultSpewFunc; + } +} + +// Spew functions +void _SpewInfo(SpewType_t type, char const* pFile, int line) +{ + // Only grab the file name. Ignore the path. + char const* pSlash = strrchr(pFile, '\\'); + char const* pSlash2 = strrchr(pFile, '/'); + if (pSlash < pSlash2) pSlash = pSlash2; + + s_pFileName = pSlash ? pSlash + 1 : pFile; + s_Line = line; + s_SpewType = type; +} + +SpewRetval_t _SpewMessage(SpewType_t spewType, char const* pMsgFormat, va_list args) +{ + char pTempBuffer[1024]; + + // Printf the file and line for warning + assert only... + int len = 0; + if ((spewType == SPEW_ASSERT)) + { + len = sprintf(pTempBuffer, "%s (%d) : ", s_pFileName, s_Line); + } + + // Create the message.... + len += vsprintf(&pTempBuffer[len], pMsgFormat, args); + + // Add \n for warning and assert + if ((spewType == SPEW_ASSERT)) + { + len += sprintf(&pTempBuffer[len], "\n"); + } + + assert(len < 1024); // use normal assert here; to avoid recursion. + assert(s_SpewOutputFunc); + + // direct it to the appropriate target(s) + SpewRetval_t ret = s_SpewOutputFunc(spewType, pTempBuffer); + switch (ret) + { + // Put the break into the macro so it would occur in the right place + // case SPEW_DEBUGGER: + // DebuggerBreak(); + // break; + + case SPEW_ABORT: + // MessageBox(NULL,"Error in _SpewMessage","Error",MB_OK); + exit(0); + default: + break; + } + + return ret; +} + +SpewRetval_t _SpewMessage(char const* pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + SpewRetval_t ret = _SpewMessage(s_SpewType, pMsgFormat, args); + va_end(args); + return ret; +} + +SpewRetval_t _DSpewMessage(char const *pGroupName, int level, char const* pMsgFormat, ...) +{ + if (!IsSpewActive(pGroupName, level)) + return SPEW_CONTINUE; + + va_list args; + va_start(args, pMsgFormat); + SpewRetval_t ret = _SpewMessage(s_SpewType, pMsgFormat, args); + va_end(args); + return ret; +} + +void Msg(char const* pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_MESSAGE, pMsgFormat, args); + va_end(args); +} + +void DMsg(char const *pGroupName, int level, char const *pMsgFormat, ...) +{ + if (!IsSpewActive(pGroupName, level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_MESSAGE, pMsgFormat, args); + va_end(args); +} + +void Warning(char const *pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_WARNING, pMsgFormat, args); + va_end(args); +} + +void DWarning(char const *pGroupName, int level, char const *pMsgFormat, ...) +{ + if (!IsSpewActive(pGroupName, level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_WARNING, pMsgFormat, args); + va_end(args); +} + +void Log(char const *pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_LOG, pMsgFormat, args); + va_end(args); +} + +void DLog(char const *pGroupName, int level, char const *pMsgFormat, ...) +{ + if (!IsSpewActive(pGroupName, level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_LOG, pMsgFormat, args); + va_end(args); +} + +void Error(char const *pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_ERROR, pMsgFormat, args); + va_end(args); +} + +// A couple of super-common dynamic spew messages, here for convenience +// These looked at the "developer" group, print if it's level 1 or higher +void DevMsg(int level, char const* pMsgFormat, ...) +{ + if (!IsSpewActive("developer", level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_MESSAGE, pMsgFormat, args); + va_end(args); +} + +void DevWarning(int level, char const *pMsgFormat, ...) +{ + if (!IsSpewActive("developer", level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_WARNING, pMsgFormat, args); + va_end(args); +} + +void DevLog(int level, char const *pMsgFormat, ...) +{ + if (!IsSpewActive("developer", level)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_LOG, pMsgFormat, args); + va_end(args); +} + +void DevMsg(char const *pMsgFormat, ...) +{ + if (!IsSpewActive("developer", 1)) + return; + + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_MESSAGE, pMsgFormat, args); + va_end(args); +} + +void DevWarning(char const *pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_WARNING, pMsgFormat, args); + va_end(args); +} + +void DevLog(char const *pMsgFormat, ...) +{ + va_list args; + va_start(args, pMsgFormat); + _SpewMessage(SPEW_LOG, pMsgFormat, args); + va_end(args); +} + +// Find a group, return true if found, false if not. Return in ind the +// index of the found group, or the index of the group right before where the +// group should be inserted into the list to maintain sorted order. +bool FindSpewGroup(char const* pGroupName, int* pInd) +{ + int s = 0; + if (s_GroupCount) + { + int e = (int)(s_GroupCount - 1); + while (s <= e) + { + int m = (s + e) >> 1; + int cmp = Q_stricmp(pGroupName, s_pSpewGroups[m].m_GroupName); + if (!cmp) + { + *pInd = m; + return true; + } + if (cmp < 0) + e = m - 1; + else + s = m + 1; + } + } + *pInd = s; + return false; +} + +// Sets the priority level for a spew group +void SpewActivate(char const* pGroupName, int level) +{ + Assert(pGroupName); + + // check for the default group first... + if ((pGroupName[0] == '*') && (pGroupName[1] == '\0')) + { + s_DefaultLevel = level; + return; + } + + // Normal case, search in group list using binary search. + // If not found, grow the list of groups and insert it into the + // right place to maintain sorted order. Then set the level. + int ind; + if (!FindSpewGroup(pGroupName, &ind)) + { + // not defined yet, insert an entry. + ++s_GroupCount; + if (s_pSpewGroups) + { + s_pSpewGroups = (SpewGroup_t*)realloc(s_pSpewGroups, + s_GroupCount * sizeof(SpewGroup_t)); + + // shift elements down to preserve order + int numToMove = s_GroupCount - ind - 1; + memmove(&s_pSpewGroups[ind + 1], &s_pSpewGroups[ind], + numToMove * sizeof(SpewGroup_t)); + } + else + s_pSpewGroups = (SpewGroup_t*)malloc(s_GroupCount * sizeof(SpewGroup_t)); + + Assert(strlen(pGroupName) < MAX_GROUP_NAME_LENGTH); + strcpy(s_pSpewGroups[ind].m_GroupName, pGroupName); + } + s_pSpewGroups[ind].m_Level = level; +} + +// Tests to see if a particular spew is active +bool IsSpewActive(char const* pGroupName, int level) +{ + // If we don't find the spew group, use the default level. + int ind; + if (FindSpewGroup(pGroupName, &ind)) + return s_pSpewGroups[ind].m_Level >= level; + else + return s_DefaultLevel >= level; +} diff --git a/dep/hlsdk/public/tier0/dbg.h b/dep/hlsdk/public/tier0/dbg.h new file mode 100644 index 0000000..8cd3bea --- /dev/null +++ b/dep/hlsdk/public/tier0/dbg.h @@ -0,0 +1,427 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "basetypes.h" + +#include +#include +#include + +// dll export stuff +#ifdef TIER0_DLL_EXPORT +#define DBG_INTERFACE DLL_EXPORT +#define DBG_OVERLOAD DLL_GLOBAL_EXPORT +#define DBG_CLASS DLL_CLASS_EXPORT +#else +#define DBG_INTERFACE DLL_IMPORT +#define DBG_OVERLOAD DLL_GLOBAL_IMPORT +#define DBG_CLASS DLL_CLASS_IMPORT +#endif + +// Usage model for the Dbg library +// +// 1. Spew. +// +// Spew can be used in a static and a dynamic mode. The static +// mode allows us to display assertions and other messages either only +// in debug builds, or in non-release builds. The dynamic mode allows us to +// turn on and off certain spew messages while the application is running. +// +// Static Spew messages: +// +// Assertions are used to detect and warn about invalid states +// Spews are used to display a particular status/warning message. +// +// To use an assertion, use +// +// Assert( (f == 5) ); +// AssertMsg( (f == 5), ("F needs to be %d here!\n", 5) ); +// AssertFunc( (f == 5), BadFunc() ); +// AssertEquals( f, 5 ); +// AssertFloatEquals( f, 5.0f, 1e-3 ); +// +// The first will simply report that an assertion failed on a particular +// code file and line. The second version will display a print-f formatted message +// along with the file and line, the third will display a generic message and +// will also cause the function BadFunc to be executed, and the last two +// will report an error if f is not equal to 5 (the last one asserts within +// a particular tolerance). +// +// To use a warning, use +// +// Warning("Oh I feel so %s all over\n", "yummy"); +// +// Warning will do its magic in only Debug builds. To perform spew in *all* +// builds, use RelWarning. +// +// Three other spew types, Msg, Log, and Error, are compiled into all builds. +// These error types do *not* need two sets of parenthesis. +// +// Msg( "Isn't this exciting %d?", 5 ); +// Error( "I'm just thrilled" ); +// +// Dynamic Spew messages +// +// It is possible to dynamically turn spew on and off. Dynamic spew is +// identified by a spew group and priority level. To turn spew on for a +// particular spew group, use SpewActivate( "group", level ). This will +// cause all spew in that particular group with priority levels <= the +// level specified in the SpewActivate function to be printed. Use DSpew +// to perform the spew: +// +// DWarning( "group", level, "Oh I feel even yummier!\n" ); +// +// Priority level 0 means that the spew will *always* be printed, and group +// '*' is the default spew group. If a DWarning is encountered using a group +// whose priority has not been set, it will use the priority of the default +// group. The priority of the default group is initially set to 0. +// +// Spew output +// +// The output of the spew system can be redirected to an externally-supplied +// function which is responsible for outputting the spew. By default, the +// spew is simply printed using printf. +// +// To redirect spew output, call SpewOutput. +// +// SpewOutputFunc( OutputFunc ); +// +// This will cause OutputFunc to be called every time a spew message is +// generated. OutputFunc will be passed a spew type and a message to print. +// It must return a value indicating whether the debugger should be invoked, +// whether the program should continue running, or whether the program +// should abort. +// +// 2. Code activation +// +// To cause code to be run only in debug builds, use DBG_CODE: +// An example is below. +// +// DBG_CODE( +// { +// int x = 5; +// ++x; +// } +// ); +// +// Code can be activated based on the dynamic spew groups also. Use +// +// DBG_DCODE( "group", level, +// { int x = 5; ++x; } +// ); +// +// 3. Breaking into the debugger. +// +// To cause an unconditional break into the debugger in debug builds only, use DBG_BREAK +// +// DBG_BREAK(); +// +// You can force a break in any build (release or debug) using +// +// DebuggerBreak(); +//----------------------------------------------------------------------------- + +// Various types of spew messages +// I'm sure you're asking yourself why SPEW_ instead of DBG_ ? +// It's because DBG_ is used all over the place in windows.h +// For example, DBG_CONTINUE is defined. Feh. +enum SpewType_t +{ + SPEW_MESSAGE = 0, + SPEW_WARNING, + SPEW_ASSERT, + SPEW_ERROR, + SPEW_LOG, + + SPEW_TYPE_COUNT +}; + +enum SpewRetval_t +{ + SPEW_DEBUGGER = 0, + SPEW_CONTINUE, + SPEW_ABORT +}; + +// type of externally defined function used to display debug spew +typedef SpewRetval_t(*SpewOutputFunc_t)(SpewType_t spewType, char const *pMsg); + +// Used to redirect spew output +void SpewOutputFunc(SpewOutputFunc_t func); + +// Used ot get the current spew output function +SpewOutputFunc_t GetSpewOutputFunc(void); + +// Used to manage spew groups and subgroups +void SpewActivate(char const* pGroupName, int level); +bool IsSpewActive(char const* pGroupName, int level); + +// Used to display messages, should never be called directly. +void _SpewInfo(SpewType_t type, char const* pFile, int line); +SpewRetval_t _SpewMessage(char const* pMsg, ...); +SpewRetval_t _DSpewMessage(char const *pGroupName, int level, char const* pMsg, ...); + +// Used to define macros, never use these directly. +#define _Assert( _exp ) do { \ + if (!(_exp)) \ + { \ + _SpewInfo( SPEW_ASSERT, __FILE__, __LINE__ ); \ + if (_SpewMessage("Assertion Failed: " #_exp) == SPEW_DEBUGGER) \ + { \ + DebuggerBreak(); \ + } \ + } \ + } while (0) + +#define _AssertMsg( _exp, _msg ) do { \ + if (!(_exp)) \ + { \ + _SpewInfo( SPEW_ASSERT, __FILE__, __LINE__ ); \ + if (_SpewMessage(_msg) == SPEW_DEBUGGER) \ + { \ + DebuggerBreak(); \ + } \ + } \ + } while (0) + +#define _AssertFunc( _exp, _f ) do { \ + if (!(_exp)) \ + { \ + _SpewInfo( SPEW_ASSERT, __FILE__, __LINE__ ); \ + SpewRetval_t ret = _SpewMessage("Assertion Failed!" #_exp); \ + _f; \ + if (ret == SPEW_DEBUGGER) \ + { \ + DebuggerBreak(); \ + } \ + } \ + } while (0) + +#define _AssertEquals( _exp, _expectedValue ) \ + do { \ + if ((_exp) != (_expectedValue)) \ + { \ + _SpewInfo( SPEW_ASSERT, __FILE__, __LINE__ ); \ + SpewRetval_t ret = _SpewMessage("Expected %d but got %d!", (_expectedValue), (_exp)); \ + if (ret == SPEW_DEBUGGER) \ + { \ + DebuggerBreak(); \ + } \ + } \ + } while (0) + +#define _AssertFloatEquals( _exp, _expectedValue, _tol ) \ + do { \ + if (fabs((_exp) - (_expectedValue)) > (_tol)) \ + { \ + _SpewInfo( SPEW_ASSERT, __FILE__, __LINE__ ); \ + SpewRetval_t ret = _SpewMessage("Expected %f but got %f!", (_expectedValue), (_exp)); \ + if (ret == SPEW_DEBUGGER) \ + { \ + DebuggerBreak(); \ + } \ + } \ + } while (0) + +// Spew macros... + +#ifdef _DEBUG + +#define Assert( _exp ) _Assert( _exp ) +#define AssertMsg( _exp, _msg ) _AssertMsg( _exp, _msg ) +#define AssertFunc( _exp, _f ) _AssertFunc( _exp, _f ) +#define AssertEquals( _exp, _expectedValue ) _AssertEquals( _exp, _expectedValue ) +#define AssertFloatEquals( _exp, _expectedValue, _tol ) _AssertFloatEquals( _exp, _expectedValue, _tol ) +#define Verify( _exp ) _Assert( _exp ) + +#define AssertMsg1( _exp, _msg, a1 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1 ) ) +#define AssertMsg2( _exp, _msg, a1, a2 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2 ) ) +#define AssertMsg3( _exp, _msg, a1, a2, a3 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3 ) ) +#define AssertMsg4( _exp, _msg, a1, a2, a3, a4 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4 ) ) +#define AssertMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5 ) ) +#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6 ) ) +#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6 ) ) +#define AssertMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7 ) ) +#define AssertMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) ) +#define AssertMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) _AssertMsg( _exp, CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) ) + + +#else // Not _DEBUG + +#define Assert( _exp ) ((void)0) +#define AssertMsg( _exp, _msg ) ((void)0) +#define AssertFunc( _exp, _f ) ((void)0) +#define AssertEquals( _exp, _expectedValue ) ((void)0) +#define AssertFloatEquals( _exp, _expectedValue, _tol ) ((void)0) +#define Verify( _exp ) (_exp) + +#define AssertMsg1( _exp, _msg, a1 ) ((void)0) +#define AssertMsg2( _exp, _msg, a1, a2 ) ((void)0) +#define AssertMsg3( _exp, _msg, a1, a2, a3 ) ((void)0) +#define AssertMsg4( _exp, _msg, a1, a2, a3, a4 ) ((void)0) +#define AssertMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) ((void)0) +#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) +#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) +#define AssertMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) ((void)0) +#define AssertMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) ((void)0) +#define AssertMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) ((void)0) + +#endif // _DEBUG + +// These are always compiled in +void Msg(char const* pMsg, ...); +void DMsg(char const *pGroupName, int level, char const *pMsg, ...); + +void Warning(char const *pMsg, ...); +void DWarning(char const *pGroupName, int level, char const *pMsg, ...); + +void Log(char const *pMsg, ...); +void DLog(char const *pGroupName, int level, char const *pMsg, ...); + +void Error(char const *pMsg, ...); + +// You can use this macro like a runtime assert macro. +// If the condition fails, then Error is called with the message. This macro is called +// like AssertMsg, where msg must be enclosed in parenthesis: +// +// ErrorIfNot( bCondition, ("a b c %d %d %d", 1, 2, 3) ); +#define ErrorIfNot( condition, msg ) \ + if ( (condition) ) \ + ; \ + else \ + { \ + Error msg; \ + } + +// A couple of super-common dynamic spew messages, here for convenience +// These looked at the "developer" group +void DevMsg(int level, char const* pMsg, ...); +void DevWarning(int level, char const *pMsg, ...); +void DevLog(int level, char const *pMsg, ...); + +// default level versions (level 1) +void DevMsg(char const* pMsg, ...); +void DevWarning(char const *pMsg, ...); +void DevLog(char const *pMsg, ...); + +// Code macros, debugger interface + +#ifdef _DEBUG + +#define DBG_CODE( _code ) if (0) ; else { _code } +#define DBG_DCODE( _g, _l, _code ) if (IsSpewActive( _g, _l )) { _code } else {} +#define DBG_BREAK() DebuggerBreak() // defined in platform.h + +#else // not _DEBUG + +#define DBG_CODE( _code ) ((void)0) +#define DBG_DCODE( _g, _l, _code ) ((void)0) +#define DBG_BREAK() ((void)0) + +#endif // _DEBUG + +// Macro to assist in asserting constant invariants during compilation +#define UID_PREFIX generated_id_ +#define UID_CAT1(a,c) a ## c +#define UID_CAT2(a,c) UID_CAT1(a,c) +#define UNIQUE_ID UID_CAT2(UID_PREFIX,__LINE__) + +#ifdef _DEBUG +#define COMPILE_TIME_ASSERT( pred ) switch(0){case 0:case pred:;} +#define ASSERT_INVARIANT( pred ) static void UNIQUE_ID() { COMPILE_TIME_ASSERT( pred ) } +#else +#define COMPILE_TIME_ASSERT( pred ) +#define ASSERT_INVARIANT( pred ) +#endif + +// Templates to assist in validating pointers: +// Have to use these stubs so we don't have to include windows.h here. +void _AssertValidReadPtr(void* ptr, int count = 1); +void _AssertValidWritePtr(void* ptr, int count = 1); +void _AssertValidReadWritePtr(void* ptr, int count = 1); + + void AssertValidStringPtr(const char* ptr, int maxchar = 0xFFFFFF); +template inline void AssertValidReadPtr(T* ptr, int count = 1) { _AssertValidReadPtr((void*)ptr, count); } +template inline void AssertValidWritePtr(T* ptr, int count = 1) { _AssertValidWritePtr((void*)ptr, count); } +template inline void AssertValidReadWritePtr(T* ptr, int count = 1) { _AssertValidReadWritePtr((void*)ptr, count); } + +#define AssertValidThis() AssertValidReadWritePtr(this,sizeof(*this)) + +// Macro to protect functions that are not reentrant +#ifdef _DEBUG +class CReentryGuard +{ +public: + CReentryGuard(int *pSemaphore) + : m_pSemaphore(pSemaphore) + { + ++(*m_pSemaphore); + } + + ~CReentryGuard() + { + --(*m_pSemaphore); + } + +private: + int *m_pSemaphore; +}; + +#define ASSERT_NO_REENTRY() \ + static int fSemaphore##__LINE__; \ + Assert( !fSemaphore##__LINE__ ); \ + CReentryGuard ReentryGuard##__LINE__( &fSemaphore##__LINE__ ) +#else +#define ASSERT_NO_REENTRY() +#endif + +// Purpose: Inline string formatter +class CDbgFmtMsg +{ +public: + CDbgFmtMsg(const char *pszFormat, ...) + { + va_list arg_ptr; + + va_start(arg_ptr, pszFormat); + _vsnprintf(m_szBuf, sizeof(m_szBuf) - 1, pszFormat, arg_ptr); + va_end(arg_ptr); + + m_szBuf[sizeof(m_szBuf) - 1] = 0; + } + + operator const char *() const + { + return m_szBuf; + } + +private: + char m_szBuf[256]; +}; diff --git a/dep/hlsdk/public/tier0/platform.h b/dep/hlsdk/public/tier0/platform.h new file mode 100644 index 0000000..b2b1f22 --- /dev/null +++ b/dep/hlsdk/public/tier0/platform.h @@ -0,0 +1,129 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "osconfig.h" + +#include // need this for _alloca +#include // need this for memset + +#include "archtypes.h" + +// Defines MAX_PATH +#ifndef MAX_PATH +#define MAX_PATH 260 +#endif + +// Used to step into the debugger +#define DebuggerBreak() __asm { int 3 } + +// C functions for external declarations that call the appropriate C++ methods +#ifndef EXPORT +#ifdef _WIN32 +#define EXPORT __declspec(dllexport) +#else +#define EXPORT /* */ +#endif +#endif + +#ifdef _WIN32 +// Used for dll exporting and importing +#define DLL_EXPORT extern "C" __declspec(dllexport) +#define DLL_IMPORT extern "C" __declspec(dllimport) + +// Can't use extern "C" when DLL exporting a class +#define DLL_CLASS_EXPORT __declspec(dllexport) +#define DLL_CLASS_IMPORT __declspec(dllimport) + +// Can't use extern "C" when DLL exporting a global +#define DLL_GLOBAL_EXPORT extern __declspec(dllexport) +#define DLL_GLOBAL_IMPORT extern __declspec(dllimport) +#elif defined __linux__ + +// Used for dll exporting and importing +#define DLL_EXPORT extern "C" +#define DLL_IMPORT extern "C" + +// Can't use extern "C" when DLL exporting a class +#define DLL_CLASS_EXPORT +#define DLL_CLASS_IMPORT + +// Can't use extern "C" when DLL exporting a global +#define DLL_GLOBAL_EXPORT extern +#define DLL_GLOBAL_IMPORT extern + +#else +#error "Unsupported Platform." +#endif + +#ifdef _WIN32 +// Remove warnings from warning level 4. +#pragma warning(disable : 4514) // warning C4514: 'acosl' : unreferenced inline function has been removed +#pragma warning(disable : 4100) // warning C4100: 'hwnd' : unreferenced formal parameter +#pragma warning(disable : 4127) // warning C4127: conditional expression is constant +#pragma warning(disable : 4512) // warning C4512: 'InFileRIFF' : assignment operator could not be generated +#pragma warning(disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable +#pragma warning(disable : 4706) // warning C4706: assignment within conditional expression +#pragma warning(disable : 4710) // warning C4710: function 'x' not inlined +#pragma warning(disable : 4702) // warning C4702: unreachable code +#pragma warning(disable : 4505) // unreferenced local function has been removed +#pragma warning(disable : 4239) // nonstandard extension used : 'argument' ( conversion from class Vector to class Vector& ) +#pragma warning(disable : 4097) // typedef-name 'BaseClass' used as synonym for class-name 'CFlexCycler::CBaseFlex' +#pragma warning(disable : 4324) // Padding was added at the end of a structure +#pragma warning(disable : 4244) // type conversion warning. +#pragma warning(disable : 4305) // truncation from 'const double ' to 'float ' +#pragma warning(disable : 4786) // Disable warnings about long symbol names + +#if _MSC_VER >= 1300 +#pragma warning(disable : 4511) // Disable warnings about private copy constructors +#endif +#endif + +// Methods to invoke the constructor, copy constructor, and destructor +template +inline void Construct(T *pMemory) +{ + new(pMemory) T; +} + +template +inline void CopyConstruct(T *pMemory, T const &src) +{ + new(pMemory) T(src); +} + +template +inline void Destruct(T *pMemory) +{ + pMemory->~T(); + +#ifdef _DEBUG + memset(pMemory, 0xDD, sizeof(T)); +#endif +} diff --git a/dep/hlsdk/public/utlbuffer.cpp b/dep/hlsdk/public/utlbuffer.cpp new file mode 100644 index 0000000..53ad7f4 --- /dev/null +++ b/dep/hlsdk/public/utlbuffer.cpp @@ -0,0 +1,419 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// $Header: $ +// $NoKeywords: $ +// +// Serialization buffer +//============================================================================= + +#include "precompiled.h" + +//----------------------------------------------------------------------------- +// constructors +//----------------------------------------------------------------------------- +CUtlBuffer::CUtlBuffer(int growSize, int initSize, bool text) : +m_Memory(growSize, initSize), m_Error(0) +{ + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + { + m_Flags |= TEXT_BUFFER; + } +} + +CUtlBuffer::CUtlBuffer(void const* pBuffer, int size, bool text) : +m_Memory((unsigned char*)pBuffer, size), m_Error(0) +{ + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + m_Flags |= TEXT_BUFFER; +} + + +//----------------------------------------------------------------------------- +// Attaches the buffer to external memory.... +//----------------------------------------------------------------------------- +void CUtlBuffer::SetExternalBuffer(void* pMemory, int numElements, bool text) +{ + m_Memory.SetExternalBuffer((unsigned char*)pMemory, numElements); + + // Reset all indices; we just changed memory + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + m_Flags |= TEXT_BUFFER; +} + + +//----------------------------------------------------------------------------- +// Makes sure we've got at least this much memory +//----------------------------------------------------------------------------- +void CUtlBuffer::EnsureCapacity(int num) +{ + m_Memory.EnsureCapacity(num); +} + + +//----------------------------------------------------------------------------- +// Base get method from which all others derive +//----------------------------------------------------------------------------- +void CUtlBuffer::Get(void* pMem, int size) +{ + Assert(m_Get + size <= m_Memory.NumAllocated()); + memcpy(pMem, &m_Memory[m_Get], size); + m_Get += size; +} + + +//----------------------------------------------------------------------------- +// Eats whitespace +//----------------------------------------------------------------------------- +void CUtlBuffer::EatWhiteSpace() +{ + if (IsText() && IsValid()) + { + int lastpos = Size(); + while (m_Get < lastpos) + { + if (!isspace(*(char*)&m_Memory[m_Get])) + break; + m_Get += sizeof(char); + } + } +} + + +//----------------------------------------------------------------------------- +// Reads a null-terminated string +//----------------------------------------------------------------------------- +void CUtlBuffer::GetString(char* pString, int nMaxLen) +{ + if (!IsValid()) + { + *pString = 0; + return; + } + + if (nMaxLen == 0) + { + nMaxLen = INT_MAX; + } + + if (!IsText()) + { + int len = strlen((char*)&m_Memory[m_Get]) + 1; + if (len <= nMaxLen) + { + Get(pString, len); + } + else + { + Get(pString, nMaxLen); + pString[nMaxLen - 1] = 0; + SeekGet(SEEK_CURRENT, len - nMaxLen); + } + } + else + { + // eat all whitespace + EatWhiteSpace(); + + // Eat characters + int nCount = 0; + int nLastPos = Size(); + while (m_Get < nLastPos) + { + char c = *(char*)&m_Memory[m_Get]; + if (isspace(c) || (!c)) + break; + + if (nCount < nMaxLen - 1) + { + *pString++ = c; + } + ++nCount; + ++m_Get; + } + + // Terminate + *pString = 0; + } +} + + +//----------------------------------------------------------------------------- +// Checks if a get is ok +//----------------------------------------------------------------------------- +bool CUtlBuffer::CheckGet(int size) +{ + if (m_Error) + return false; + + if (m_Memory.NumAllocated() >= m_Get + size) + return true; + + m_Error |= GET_OVERFLOW; + return false; +} + + +//----------------------------------------------------------------------------- +// Change where I'm reading +//----------------------------------------------------------------------------- +void CUtlBuffer::SeekGet(SeekType_t type, int offset) +{ + switch (type) + { + case SEEK_HEAD: + m_Get = offset; + break; + + case SEEK_CURRENT: + m_Get += offset; + break; + + case SEEK_TAIL: + m_Get = m_Memory.NumAllocated() - offset; + break; + } +} + + +//----------------------------------------------------------------------------- +// Parse... +//----------------------------------------------------------------------------- + +#pragma warning ( disable : 4706 ) + +int CUtlBuffer::VaScanf(char const* pFmt, va_list list) +{ + Assert(pFmt); + if (m_Error || !IsText()) + return 0; + + int numScanned = 0; + + char c; + char* pEnd; + while (c = *pFmt++) + { + // Stop if we hit the end of the buffer + if (m_Get >= Size()) + { + m_Error |= GET_OVERFLOW; + break; + } + + switch (c) + { + case ' ': + // eat all whitespace + EatWhiteSpace(); + break; + + case '%': + { + // Conversion character... try to convert baby! + char type = *pFmt++; + if (type == 0) + return numScanned; + + switch (type) + { + case 'c': + { + char* ch = va_arg(list, char *); + *ch = (char)m_Memory[m_Get]; + ++m_Get; + } + break; + + case 'i': + case 'd': + { + int* i = va_arg(list, int *); + *i = strtol((char*)PeekGet(), &pEnd, 10); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'x': + { + int* i = va_arg(list, int *); + *i = strtol((char*)PeekGet(), &pEnd, 16); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'u': + { + unsigned int* u = va_arg(list, unsigned int *); + *u = strtoul((char*)PeekGet(), &pEnd, 10); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'f': + { + float* f = va_arg(list, float *); + *f = (float)strtod((char*)PeekGet(), &pEnd); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 's': + { + char* s = va_arg(list, char *); + GetString(s); + } + break; + + default: + { + // unimplemented scanf type + Assert(0); + return numScanned; + } + break; + } + + ++numScanned; + } + break; + + default: + { + // Here we have to match the format string character + // against what's in the buffer or we're done. + if (c != m_Memory[m_Get]) + return numScanned; + ++m_Get; + } + } + } + return numScanned; +} + +#pragma warning ( default : 4706 ) + +int CUtlBuffer::Scanf(char const* pFmt, ...) +{ + va_list args; + + va_start(args, pFmt); + int count = VaScanf(pFmt, args); + va_end(args); + + return count; +} + + +//----------------------------------------------------------------------------- +// Serialization +//----------------------------------------------------------------------------- + +void CUtlBuffer::Put(void const* pMem, int size) +{ + if (CheckPut(size)) + { + memcpy(&m_Memory[m_Put], pMem, size); + m_Put += size; + } +} + + +//----------------------------------------------------------------------------- +// Writes a null-terminated string +//----------------------------------------------------------------------------- + +void CUtlBuffer::PutString(char const* pString) +{ + int len = strlen(pString); + + // Not text? append a null at the end. + if (!IsText()) + ++len; + + Put(pString, len); +} + +void CUtlBuffer::VaPrintf(char const* pFmt, va_list list) +{ + char temp[2048]; + int len = vsprintf(temp, pFmt, list); + Assert(len < 2048); + + // Not text? append a null at the end. + if (!IsText()) + ++len; + + Put(temp, len); +} + +void CUtlBuffer::Printf(char const* pFmt, ...) +{ + va_list args; + + va_start(args, pFmt); + VaPrintf(pFmt, args); + va_end(args); +} + + +//----------------------------------------------------------------------------- +// Checks if a put is ok +//----------------------------------------------------------------------------- + +bool CUtlBuffer::CheckPut(int size) +{ + if (m_Error) + return false; + + while (m_Memory.NumAllocated() < m_Put + size) + { + if (m_Memory.IsExternallyAllocated()) + { + m_Error |= PUT_OVERFLOW; + return false; + } + + m_Memory.Grow(); + } + return true; +} + +void CUtlBuffer::SeekPut(SeekType_t type, int offset) +{ + switch (type) + { + case SEEK_HEAD: + m_Put = offset; + break; + + case SEEK_CURRENT: + m_Put += offset; + break; + + case SEEK_TAIL: + m_Put = m_Memory.NumAllocated() - offset; + break; + } +} diff --git a/dep/hlsdk/public/utlbuffer.h b/dep/hlsdk/public/utlbuffer.h new file mode 100644 index 0000000..2351249 --- /dev/null +++ b/dep/hlsdk/public/utlbuffer.h @@ -0,0 +1,341 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// $Header: $ +// $NoKeywords: $ +// +// Serialization/unserialization buffer +//============================================================================= + +#ifndef UTLBUFFER_H +#define UTLBUFFER_H + +#include "osconfig.h" +#include "utlmemory.h" +#include + +//----------------------------------------------------------------------------- +// Command parsing.. +//----------------------------------------------------------------------------- + +class CUtlBuffer +{ +public: + enum SeekType_t + { + SEEK_HEAD = 0, + SEEK_CURRENT, + SEEK_TAIL + }; + + CUtlBuffer(int growSize = 0, int initSize = 0, bool text = false); + CUtlBuffer(void const* pBuffer, int size, bool text = false); + + // Makes sure we've got at least this much memory + void EnsureCapacity(int num); + + // Attaches the buffer to external memory.... + void SetExternalBuffer(void* pMemory, int numElements, bool text = false); + + // Read stuff out. + // Binary mode: it'll just read the bits directly in, and characters will be + // read for strings until a null character is reached. + // Text mode: it'll parse the file, turning text #s into real numbers. + // GetString will read a string until a space is reaced + char GetChar(); + unsigned char GetUnsignedChar(); + short GetShort(); + unsigned short GetUnsignedShort(); + int GetInt(); + int GetIntHex(); + unsigned int GetUnsignedInt(); + float GetFloat(); + double GetDouble(); + void GetString(char* pString, int nMaxLen = 0); + void Get(void* pMem, int size); + + // Just like scanf, but doesn't work in binary mode + int Scanf(char const* pFmt, ...); + int VaScanf(char const* pFmt, va_list list); + + // Eats white space, advances Get index + void EatWhiteSpace(); + + // Write stuff in + // Binary mode: it'll just write the bits directly in, and strings will be + // written with a null terminating character + // Text mode: it'll convert the numbers to text versions + // PutString will not write a terminating character + void PutChar(char c); + void PutUnsignedChar(unsigned char uc); + void PutShort(short s); + void PutUnsignedShort(unsigned short us); + void PutInt(int i); + void PutUnsignedInt(unsigned int u); + void PutFloat(float f); + void PutDouble(double d); + void PutString(char const* pString); + void Put(void const* pMem, int size); + + // Just like printf, writes a terminating zero in binary mode + void Printf(char const* pFmt, ...); + void VaPrintf(char const* pFmt, va_list list); + + // What am I writing (put)/reading (get)? + void* PeekPut(int offset = 0); + void const* PeekGet(int offset = 0) const; + + // Where am I writing (put)/reading (get)? + int TellPut() const; + int TellGet() const; + + // Change where I'm writing (put)/reading (get) + void SeekPut(SeekType_t type, int offset); + void SeekGet(SeekType_t type, int offset); + + // Buffer base + void const* Base() const; + void* Base(); + + // memory allocation size, does *not* reflect size written or read, + // use TellPut or TellGet for that + int Size() const; + + // Am I a text buffer? + inline bool IsText() const { return (m_Flags & TEXT_BUFFER) != 0; } + + // Am I valid? (overflow or underflow error), Once invalid it stays invalid + inline bool IsValid() const { return m_Error == 0; } + +private: + // error flags + enum + { + PUT_OVERFLOW = 0x1, + GET_OVERFLOW = 0x2, + }; + + // flags + enum + { + TEXT_BUFFER = 0x1, + }; + + // Checks if a get/put is ok + bool CheckPut(int size); + bool CheckGet(int size); + + CUtlMemory m_Memory; + int m_Get; + int m_Put; + unsigned char m_Error; + unsigned char m_Flags; +}; + + +//----------------------------------------------------------------------------- +// Where am I reading? +//----------------------------------------------------------------------------- + +inline int CUtlBuffer::TellGet() const +{ + return m_Get; +} + + +//----------------------------------------------------------------------------- +// What am I reading? +//----------------------------------------------------------------------------- +inline void const* CUtlBuffer::PeekGet(int offset) const +{ + return &m_Memory[m_Get + offset]; +} + + +//----------------------------------------------------------------------------- +// Unserialization +//----------------------------------------------------------------------------- +#define GET_TYPE( _type, _val, _fmt ) \ + if (!IsText()) \ + { \ + if (CheckGet( sizeof(_type) )) \ + { \ + _val = *(_type *)PeekGet(); \ + m_Get += sizeof(_type); \ + } \ + else \ + { \ + _val = 0; \ + } \ + } \ + else \ + { \ + _val = 0; \ + Scanf( _fmt, &_val ); \ + } + +inline char CUtlBuffer::GetChar() +{ + char c; + GET_TYPE(char, c, "%c"); + return c; +} + +inline unsigned char CUtlBuffer::GetUnsignedChar() +{ + unsigned char c; + GET_TYPE(unsigned char, c, "%u"); + return c; +} + +inline short CUtlBuffer::GetShort() +{ + short s; + GET_TYPE(short, s, "%d"); + return s; +} + +inline unsigned short CUtlBuffer::GetUnsignedShort() +{ + unsigned short s; + GET_TYPE(unsigned short, s, "%u"); + return s; +} + +inline int CUtlBuffer::GetInt() +{ + int i; + GET_TYPE(int, i, "%d"); + return i; +} + +inline int CUtlBuffer::GetIntHex() +{ + int i; + GET_TYPE(int, i, "%x"); + return i; +} + +inline unsigned int CUtlBuffer::GetUnsignedInt() +{ + unsigned int u; + GET_TYPE(unsigned int, u, "%u"); + return u; +} + +inline float CUtlBuffer::GetFloat() +{ + float f; + GET_TYPE(float, f, "%f"); + return f; +} + +inline double CUtlBuffer::GetDouble() +{ + double d; + GET_TYPE(double, d, "%f"); + return d; +} + + +//----------------------------------------------------------------------------- +// Where am I writing? +//----------------------------------------------------------------------------- +inline int CUtlBuffer::TellPut() const +{ + return m_Put; +} + + +//----------------------------------------------------------------------------- +// What am I reading? +//----------------------------------------------------------------------------- +inline void* CUtlBuffer::PeekPut(int offset) +{ + return &m_Memory[m_Put + offset]; +} + + +//----------------------------------------------------------------------------- +// Various put methods +//----------------------------------------------------------------------------- +#define PUT_TYPE( _type, _val, _fmt ) \ + if (!IsText()) \ + { \ + if (CheckPut( sizeof(_type) )) \ + { \ + *(_type *)PeekPut() = _val; \ + m_Put += sizeof(_type); \ + } \ + } \ + else \ + { \ + Printf( _fmt, _val ); \ + } + + +inline void CUtlBuffer::PutChar(char c) +{ + PUT_TYPE(char, c, "%c"); +} + +inline void CUtlBuffer::PutUnsignedChar(unsigned char c) +{ + PUT_TYPE(unsigned char, c, "%u"); +} + +inline void CUtlBuffer::PutShort(short s) +{ + PUT_TYPE(short, s, "%d"); +} + +inline void CUtlBuffer::PutUnsignedShort(unsigned short s) +{ + PUT_TYPE(unsigned short, s, "%u"); +} + +inline void CUtlBuffer::PutInt(int i) +{ + PUT_TYPE(int, i, "%d"); +} + +inline void CUtlBuffer::PutUnsignedInt(unsigned int u) +{ + PUT_TYPE(unsigned int, u, "%u"); +} + +inline void CUtlBuffer::PutFloat(float f) +{ + PUT_TYPE(float, f, "%f"); +} + +inline void CUtlBuffer::PutDouble(double d) +{ + PUT_TYPE(double, d, "%f"); +} + +//----------------------------------------------------------------------------- +// Buffer base and size +//----------------------------------------------------------------------------- + +inline void const* CUtlBuffer::Base() const +{ + return m_Memory.Base(); +} + +inline void* CUtlBuffer::Base() +{ + return m_Memory.Base(); +} + +inline int CUtlBuffer::Size() const +{ + return m_Memory.NumAllocated(); +} + + +#endif // UTLBUFFER_H diff --git a/dep/hlsdk/public/utllinkedlist.h b/dep/hlsdk/public/utllinkedlist.h new file mode 100644 index 0000000..5dbf1fc --- /dev/null +++ b/dep/hlsdk/public/utllinkedlist.h @@ -0,0 +1,692 @@ +//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ======== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// Purpose: Linked list container class +// +// $Revision: $ +// $NoKeywords: $ +//============================================================================= + +#ifndef UTLLINKEDLIST_H +#define UTLLINKEDLIST_H + +#ifdef _WIN32 +#pragma once +#endif + +#include "basetypes.h" +#include "utlmemory.h" +#include "tier0/dbg.h" + + +// This is a useful macro to iterate from head to tail in a linked list. +#define FOR_EACH_LL( listName, iteratorName ) \ + for( int iteratorName=listName.Head(); iteratorName != listName.InvalidIndex(); iteratorName = listName.Next( iteratorName ) ) + +#define INVALID_LLIST_IDX ((I)~0) + +//----------------------------------------------------------------------------- +// class CUtlLinkedList: +// description: +// A lovely index-based linked list! T is the class type, I is the index +// type, which usually should be an unsigned short or smaller. +//----------------------------------------------------------------------------- + +template +class CUtlLinkedList +{ +public: + typedef T ElemType_t; + typedef I IndexType_t; + + // constructor, destructor + CUtlLinkedList(int growSize = 0, int initSize = 0); + CUtlLinkedList(void *pMemory, int memsize); + ~CUtlLinkedList(); + + // gets particular elements + T& Element(I i); + T const& Element(I i) const; + T& operator[](I i); + T const& operator[](I i) const; + + // Make sure we have a particular amount of memory + void EnsureCapacity(int num); + + // Memory deallocation + void Purge(); + + // Delete all the elements then call Purge. + void PurgeAndDeleteElements(); + + // Insertion methods.... + I InsertBefore(I before); + I InsertAfter(I after); + I AddToHead(); + I AddToTail(); + + I InsertBefore(I before, T const& src); + I InsertAfter(I after, T const& src); + I AddToHead(T const& src); + I AddToTail(T const& src); + + // Find an element and return its index or InvalidIndex() if it couldn't be found. + I Find(const T &src) const; + + // Look for the element. If it exists, remove it and return true. Otherwise, return false. + bool FindAndRemove(const T &src); + + // Removal methods + void Remove(I elem); + void RemoveAll(); + + // Allocation/deallocation methods + // If multilist == true, then list list may contain many + // non-connected lists, and IsInList and Head + Tail are meaningless... + I Alloc(bool multilist = false); + void Free(I elem); + + // list modification + void LinkBefore(I before, I elem); + void LinkAfter(I after, I elem); + void Unlink(I elem); + void LinkToHead(I elem); + void LinkToTail(I elem); + + // invalid index + inline static I InvalidIndex() { return INVALID_LLIST_IDX; } + inline static size_t ElementSize() { return sizeof(ListElem_t); } + + // list statistics + int Count() const; + I MaxElementIndex() const; + + // Traversing the list + I Head() const; + I Tail() const; + I Previous(I i) const; + I Next(I i) const; + + // Are nodes in the list or valid? + bool IsValidIndex(I i) const; + bool IsInList(I i) const; + +protected: + // What the linked list element looks like + struct ListElem_t + { + T m_Element; + I m_Previous; + I m_Next; + + private: + // No copy constructor for these... + ListElem_t(const ListElem_t&); + }; + + // constructs the class + I AllocInternal(bool multilist = false); + void ConstructList(); + + // Gets at the list element.... + ListElem_t& InternalElement(I i) { return m_Memory[i]; } + ListElem_t const& InternalElement(I i) const { return m_Memory[i]; } + + void ResetDbgInfo() + { + m_pElements = m_Memory.Base(); + } + + // copy constructors not allowed + CUtlLinkedList(CUtlLinkedList const& list) { Assert(0); } + + CUtlMemory m_Memory; + I m_Head; + I m_Tail; + I m_FirstFree; + I m_ElementCount; // The number actually in the list + I m_TotalElements; // The number allocated + + // For debugging purposes; + // it's in release builds so this can be used in libraries correctly + ListElem_t *m_pElements; +}; + + +//----------------------------------------------------------------------------- +// constructor, destructor +//----------------------------------------------------------------------------- + +template +CUtlLinkedList::CUtlLinkedList(int growSize, int initSize) : +m_Memory(growSize, initSize) +{ + ConstructList(); + ResetDbgInfo(); +} + +template +CUtlLinkedList::CUtlLinkedList(void* pMemory, int memsize) : +m_Memory((ListElem_t *)pMemory, memsize / sizeof(ListElem_t)) +{ + ConstructList(); + ResetDbgInfo(); +} + +template +CUtlLinkedList::~CUtlLinkedList() +{ + RemoveAll(); +} + +template +void CUtlLinkedList::ConstructList() +{ + m_Head = InvalidIndex(); + m_Tail = InvalidIndex(); + m_FirstFree = InvalidIndex(); + m_ElementCount = m_TotalElements = 0; +} + + +//----------------------------------------------------------------------------- +// gets particular elements +//----------------------------------------------------------------------------- + +template +inline T& CUtlLinkedList::Element(I i) +{ + return m_Memory[i].m_Element; +} + +template +inline T const& CUtlLinkedList::Element(I i) const +{ + return m_Memory[i].m_Element; +} + +template +inline T& CUtlLinkedList::operator[](I i) +{ + return m_Memory[i].m_Element; +} + +template +inline T const& CUtlLinkedList::operator[](I i) const +{ + return m_Memory[i].m_Element; +} + +//----------------------------------------------------------------------------- +// list statistics +//----------------------------------------------------------------------------- + +template +inline int CUtlLinkedList::Count() const +{ + return m_ElementCount; +} + +template +inline I CUtlLinkedList::MaxElementIndex() const +{ + return m_Memory.NumAllocated(); +} + + +//----------------------------------------------------------------------------- +// Traversing the list +//----------------------------------------------------------------------------- + +template +inline I CUtlLinkedList::Head() const +{ + return m_Head; +} + +template +inline I CUtlLinkedList::Tail() const +{ + return m_Tail; +} + +template +inline I CUtlLinkedList::Previous(I i) const +{ + Assert(IsValidIndex(i)); + return InternalElement(i).m_Previous; +} + +template +inline I CUtlLinkedList::Next(I i) const +{ + Assert(IsValidIndex(i)); + return InternalElement(i).m_Next; +} + + +//----------------------------------------------------------------------------- +// Are nodes in the list or valid? +//----------------------------------------------------------------------------- + +template +inline bool CUtlLinkedList::IsValidIndex(I i) const +{ + return (i < m_TotalElements) && (i >= 0) && + ((m_Memory[i].m_Previous != i) || (m_Memory[i].m_Next == i)); +} + +template +inline bool CUtlLinkedList::IsInList(I i) const +{ + return (i < m_TotalElements) && (i >= 0) && (Previous(i) != i); +} + +//----------------------------------------------------------------------------- +// Makes sure we have enough memory allocated to store a requested # of elements +//----------------------------------------------------------------------------- + +template< class T, class I > +void CUtlLinkedList::EnsureCapacity(int num) +{ + m_Memory.EnsureCapacity(num); + ResetDbgInfo(); +} + + +//----------------------------------------------------------------------------- +// Deallocate memory +//----------------------------------------------------------------------------- + +template +void CUtlLinkedList::Purge() +{ + RemoveAll(); + m_Memory.Purge(); + m_FirstFree = InvalidIndex(); + m_TotalElements = 0; + ResetDbgInfo(); + +} + + +template +void CUtlLinkedList::PurgeAndDeleteElements() +{ + int iNext; + for (int i = Head(); i != InvalidIndex(); i = iNext) + { + iNext = Next(i); + delete Element(i); + } + + Purge(); +} + + +//----------------------------------------------------------------------------- +// Node allocation/deallocation +//----------------------------------------------------------------------------- +template +I CUtlLinkedList::AllocInternal(bool multilist) +{ + I elem; + if (m_FirstFree == InvalidIndex()) + { + // Nothing in the free list; add. + // Since nothing is in the free list, m_TotalElements == total # of elements + // the list knows about. + if (m_TotalElements == m_Memory.NumAllocated()) + m_Memory.Grow(); + + Assert(m_TotalElements != InvalidIndex()); + + elem = (I)m_TotalElements; + ++m_TotalElements; + + if (elem == InvalidIndex()) + { + Error("CUtlLinkedList overflow!\n"); + } + } + else + { + elem = m_FirstFree; + m_FirstFree = InternalElement(m_FirstFree).m_Next; + } + + if (!multilist) + InternalElement(elem).m_Next = InternalElement(elem).m_Previous = elem; + else + InternalElement(elem).m_Next = InternalElement(elem).m_Previous = InvalidIndex(); + + ResetDbgInfo(); + + return elem; +} + +template +I CUtlLinkedList::Alloc(bool multilist) +{ + I elem = AllocInternal(multilist); + Construct(&Element(elem)); + + return elem; +} + +template +void CUtlLinkedList::Free(I elem) +{ + Assert(IsValidIndex(elem)); + Unlink(elem); + + ListElem_t &internalElem = InternalElement(elem); + Destruct(&internalElem.m_Element); + internalElem.m_Next = m_FirstFree; + m_FirstFree = elem; +} + +//----------------------------------------------------------------------------- +// Insertion methods; allocates and links (uses default constructor) +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::InsertBefore(I before) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkBefore(before, newNode); + + // Construct the data + Construct(&Element(newNode)); + + return newNode; +} + +template +I CUtlLinkedList::InsertAfter(I after) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkAfter(after, newNode); + + // Construct the data + Construct(&Element(newNode)); + + return newNode; +} + +template +inline I CUtlLinkedList::AddToHead() +{ + return InsertAfter(InvalidIndex()); +} + +template +inline I CUtlLinkedList::AddToTail() +{ + return InsertBefore(InvalidIndex()); +} + + +//----------------------------------------------------------------------------- +// Insertion methods; allocates and links (uses copy constructor) +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::InsertBefore(I before, T const& src) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkBefore(before, newNode); + + // Construct the data + CopyConstruct(&Element(newNode), src); + + return newNode; +} + +template +I CUtlLinkedList::InsertAfter(I after, T const& src) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkAfter(after, newNode); + + // Construct the data + CopyConstruct(&Element(newNode), src); + + return newNode; +} + +template +inline I CUtlLinkedList::AddToHead(T const& src) +{ + return InsertAfter(InvalidIndex(), src); +} + +template +inline I CUtlLinkedList::AddToTail(T const& src) +{ + return InsertBefore(InvalidIndex(), src); +} + + +//----------------------------------------------------------------------------- +// Removal methods +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::Find(const T &src) const +{ + for (I i = Head(); i != InvalidIndex(); i = Next(i)) + { + if (Element(i) == src) + return i; + } + return InvalidIndex(); +} + + +template +bool CUtlLinkedList::FindAndRemove(const T &src) +{ + I i = Find(src); + if (i == InvalidIndex()) + { + return false; + } + else + { + Remove(i); + return true; + } +} + + +template +void CUtlLinkedList::Remove(I elem) +{ + Free(elem); +} + +template +void CUtlLinkedList::RemoveAll() +{ + if (m_TotalElements == 0) + return; + + // Put everything into the free list + I prev = InvalidIndex(); + for (int i = (int)m_TotalElements; --i >= 0;) + { + // Invoke the destructor + if (IsValidIndex((I)i)) + Destruct(&Element((I)i)); + + // next points to the next free list item + InternalElement((I)i).m_Next = prev; + + // Indicates it's in the free list + InternalElement((I)i).m_Previous = (I)i; + prev = (I)i; + } + + // First free points to the first element + m_FirstFree = 0; + + // Clear everything else out + m_Head = InvalidIndex(); + m_Tail = InvalidIndex(); + m_ElementCount = 0; +} + + +//----------------------------------------------------------------------------- +// list modification +//----------------------------------------------------------------------------- + +template +void CUtlLinkedList::LinkBefore(I before, I elem) +{ + Assert(IsValidIndex(elem)); + + // Unlink it if it's in the list at the moment + Unlink(elem); + + ListElem_t& newElem = InternalElement(elem); + + // The element *after* our newly linked one is the one we linked before. + newElem.m_Next = before; + + if (before == InvalidIndex()) + { + // In this case, we're linking to the end of the list, so reset the tail + newElem.m_Previous = m_Tail; + m_Tail = elem; + } + else + { + // Here, we're not linking to the end. Set the prev pointer to point to + // the element we're linking. + Assert(IsInList(before)); + ListElem_t& beforeElem = InternalElement(before); + newElem.m_Previous = beforeElem.m_Previous; + beforeElem.m_Previous = elem; + } + + // Reset the head if we linked to the head of the list + if (newElem.m_Previous == InvalidIndex()) + m_Head = elem; + else + InternalElement(newElem.m_Previous).m_Next = elem; + + // one more element baby + ++m_ElementCount; +} + +template +void CUtlLinkedList::LinkAfter(I after, I elem) +{ + Assert(IsValidIndex(elem)); + + // Unlink it if it's in the list at the moment + if (IsInList(elem)) + Unlink(elem); + + ListElem_t& newElem = InternalElement(elem); + + // The element *before* our newly linked one is the one we linked after + newElem.m_Previous = after; + if (after == InvalidIndex()) + { + // In this case, we're linking to the head of the list, reset the head + newElem.m_Next = m_Head; + m_Head = elem; + } + else + { + // Here, we're not linking to the end. Set the next pointer to point to + // the element we're linking. + Assert(IsInList(after)); + ListElem_t& afterElem = InternalElement(after); + newElem.m_Next = afterElem.m_Next; + afterElem.m_Next = elem; + } + + // Reset the tail if we linked to the tail of the list + if (newElem.m_Next == InvalidIndex()) + m_Tail = elem; + else + InternalElement(newElem.m_Next).m_Previous = elem; + + // one more element baby + ++m_ElementCount; +} + +template +void CUtlLinkedList::Unlink(I elem) +{ + Assert(IsValidIndex(elem)); + if (IsInList(elem)) + { + ListElem_t *pBase = m_Memory.Base(); + ListElem_t *pOldElem = &pBase[elem]; + + // If we're the first guy, reset the head + // otherwise, make our previous node's next pointer = our next + if (pOldElem->m_Previous != INVALID_LLIST_IDX) + { + pBase[pOldElem->m_Previous].m_Next = pOldElem->m_Next; + } + else + { + m_Head = pOldElem->m_Next; + } + + // If we're the last guy, reset the tail + // otherwise, make our next node's prev pointer = our prev + if (pOldElem->m_Next != INVALID_LLIST_IDX) + { + pBase[pOldElem->m_Next].m_Previous = pOldElem->m_Previous; + } + else + { + m_Tail = pOldElem->m_Previous; + } + + // This marks this node as not in the list, + // but not in the free list either + pOldElem->m_Previous = pOldElem->m_Next = elem; + + // One less puppy + --m_ElementCount; + } +} + +template +inline void CUtlLinkedList::LinkToHead(I elem) +{ + LinkAfter(InvalidIndex(), elem); +} + +template +inline void CUtlLinkedList::LinkToTail(I elem) +{ + LinkBefore(InvalidIndex(), elem); +} + + +#endif // UTLLINKEDLIST_H diff --git a/dep/hlsdk/public/utlmap.h b/dep/hlsdk/public/utlmap.h new file mode 100644 index 0000000..4433f26 --- /dev/null +++ b/dep/hlsdk/public/utlmap.h @@ -0,0 +1,261 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "tier0/dbg.h" +#include "utlrbtree.h" + +// Purpose: An associative container. Pretty much identical to std::map. +// This is a useful macro to iterate from start to end in order in a map +#define FOR_EACH_MAP(mapName, iteratorName)\ + for (int iteratorName = (mapName).FirstInorder(); (mapName).IsUtlMap && iteratorName != (mapName).InvalidIndex(); iteratorName = (mapName).NextInorder(iteratorName)) + +// faster iteration, but in an unspecified order +#define FOR_EACH_MAP_FAST(mapName, iteratorName)\ + for (int iteratorName = 0; (mapName).IsUtlMap && iteratorName < (mapName).MaxElement(); ++iteratorName) if (!(mapName).IsValidIndex(iteratorName)) continue; else + +struct base_utlmap_t +{ +public: + // This enum exists so that FOR_EACH_MAP and FOR_EACH_MAP_FAST cannot accidentally + // be used on a type that is not a CUtlMap. If the code compiles then all is well. + // The check for IsUtlMap being true should be free. + // Using an enum rather than a static const bool ensures that this trick works even + // with optimizations disabled on gcc. + enum CompileTimeCheck + { + IsUtlMap = 1 + }; +}; + +template +class CUtlMap: public base_utlmap_t +{ +public: + typedef K KeyType_t; + typedef T ElemType_t; + typedef I IndexType_t; + + // Less func typedef + // Returns true if the first parameter is "less" than the second + typedef bool (*LessFunc_t)(const KeyType_t &, const KeyType_t &); + + // constructor, destructor + // Left at growSize = 0, the memory will first allocate 1 element and double in size + // at each increment. + // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below + CUtlMap(int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0) + : m_Tree(growSize, initSize, CKeyLess(lessfunc)) + { + if (!lessfunc) { + SetLessFunc(DefLessFunc(K)); + } + } + + CUtlMap(LessFunc_t lessfunc) + : m_Tree(CKeyLess(lessfunc)) + { + if (!lessfunc) { + SetLessFunc(DefLessFunc(K)); + } + } + + void EnsureCapacity(int num) { m_Tree.EnsureCapacity(num); } + + // gets particular elements + ElemType_t & Element(IndexType_t i) { return m_Tree.Element(i).elem; } + const ElemType_t & Element(IndexType_t i) const { return m_Tree.Element(i).elem; } + ElemType_t & operator[](IndexType_t i) { return m_Tree.Element(i).elem; } + const ElemType_t & operator[](IndexType_t i) const { return m_Tree.Element(i).elem; } + KeyType_t & Key(IndexType_t i) { return m_Tree.Element(i).key; } + const KeyType_t & Key(IndexType_t i) const { return m_Tree.Element(i).key; } + + + // Num elements + unsigned int Count() const { return m_Tree.Count(); } + + // Max "size" of the vector + IndexType_t MaxElement() const { return m_Tree.MaxElement(); } + + // Checks if a node is valid and in the map + bool IsValidIndex(IndexType_t i) const { return m_Tree.IsValidIndex(i); } + + // Checks if the map as a whole is valid + bool IsValid() const { return m_Tree.IsValid(); } + + // Invalid index + static IndexType_t InvalidIndex() { return CTree::InvalidIndex(); } + + // Sets the less func + void SetLessFunc(LessFunc_t func) + { + m_Tree.SetLessFunc(CKeyLess(func)); + } + + // Insert method (inserts in order) + IndexType_t Insert(const KeyType_t &key, const ElemType_t &insert) + { + Node_t node; + node.key = key; + node.elem = insert; + return m_Tree.Insert(node); + } + + IndexType_t Insert(const KeyType_t &key) + { + Node_t node; + node.key = key; + return m_Tree.Insert(node); + } + + // Find method + IndexType_t Find(const KeyType_t &key) const + { + Node_t dummyNode; + dummyNode.key = key; + return m_Tree.Find(dummyNode); + } + + // Remove methods + void RemoveAt(IndexType_t i) { m_Tree.RemoveAt(i); } + bool Remove(const KeyType_t &key) + { + Node_t dummyNode; + dummyNode.key = key; + return m_Tree.Remove(dummyNode); + } + + void RemoveAll() { m_Tree.RemoveAll(); } + void Purge() { m_Tree.Purge(); } + + // Purges the list and calls delete on each element in it. + void PurgeAndDeleteElements(); + + // Iteration + IndexType_t FirstInorder() const { return m_Tree.FirstInorder(); } + IndexType_t NextInorder(IndexType_t i) const { return m_Tree.NextInorder(i); } + IndexType_t PrevInorder(IndexType_t i) const { return m_Tree.PrevInorder(i); } + IndexType_t LastInorder() const { return m_Tree.LastInorder(); } + + // If you change the search key, this can be used to reinsert the + // element into the map. + void Reinsert(const KeyType_t &key, IndexType_t i) + { + m_Tree[i].key = key; + m_Tree.Reinsert(i); + } + + IndexType_t InsertOrReplace(const KeyType_t &key, const ElemType_t &insert) + { + IndexType_t i = Find(key); + if (i != InvalidIndex()) + { + Element(i) = insert; + return i; + } + + return Insert(key, insert); + } + + void Swap(CUtlMap &that) + { + m_Tree.Swap(that.m_Tree); + } + + struct Node_t + { + Node_t() + { + } + + Node_t(const Node_t &from) + : key(from.key), + elem(from.elem) + { + } + + KeyType_t key; + ElemType_t elem; + }; + + class CKeyLess + { + public: + CKeyLess(LessFunc_t lessFunc) : m_LessFunc(lessFunc) {} + + bool operator!() const + { + return !m_LessFunc; + } + + bool operator()(const Node_t &left, const Node_t &right) const + { + return m_LessFunc(left.key, right.key); + } + + LessFunc_t m_LessFunc; + }; + + typedef CUtlRBTree CTree; + + CTree *AccessTree() { return &m_Tree; } + +protected: + CTree m_Tree; +}; + +// Purges the list and calls delete on each element in it. +template +inline void CUtlMap::PurgeAndDeleteElements() +{ + for (I i = 0; i < MaxElement(); ++i) + { + if (!IsValidIndex(i)) + continue; + + delete Element(i); + } + + Purge(); +} + +// This is horrible and slow and meant to be used only when you're dealing with really +// non-time/memory-critical code and desperately want to copy a whole map element-by-element +// for whatever reason. +template +void DeepCopyMap(const CUtlMap &pmapIn, CUtlMap *out_pmapOut) +{ + Assert(out_pmapOut); + + out_pmapOut->Purge(); + FOR_EACH_MAP_FAST(pmapIn, i) + { + out_pmapOut->Insert(pmapIn.Key(i), pmapIn.Element(i)); + } +} diff --git a/dep/hlsdk/public/utlmemory.h b/dep/hlsdk/public/utlmemory.h new file mode 100644 index 0000000..4aecc6c --- /dev/null +++ b/dep/hlsdk/public/utlmemory.h @@ -0,0 +1,334 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "osconfig.h" +#include "tier0/dbg.h" +#include + +#pragma warning (disable:4100) +#pragma warning (disable:4514) + +// The CUtlMemory class: +// A growable memory class which doubles in size by default. +template +class CUtlMemory +{ +public: + // constructor, destructor + CUtlMemory(int nGrowSize = 0, int nInitSize = 0); + CUtlMemory(T *pMemory, int numElements); + ~CUtlMemory(); + + // Set the size by which the memory grows + void Init(int nGrowSize = 0, int nInitSize = 0); + + class Iterator_t + { + public: + Iterator_t(I i) : m_index(i) {} + I m_index; + + bool operator==(const Iterator_t it) const { return m_index == it.m_index; } + bool operator!=(const Iterator_t it) const { return m_index != it.m_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()); } + + // element access + T& Element(I i); + T const& Element(I i) const; + T& operator[](I i); + T const& operator[](I i) const; + + // Can we use this index? + bool IsIdxValid(I i) const; + + // Specify the invalid ('null') index that we'll only return on failure + static const I INVALID_INDEX = (I)-1; // For use with COMPILE_TIME_ASSERT + static I InvalidIndex() { return INVALID_INDEX; } + + // Gets the base address (can change when adding elements!) + T *Base(); + T const *Base() const; + + // Attaches the buffer to external memory.... + void SetExternalBuffer(T *pMemory, int numElements); + + // Size + int NumAllocated() const; + int Count() const; + + // Grows the memory, so that at least allocated + num elements are allocated + void Grow(int num = 1); + + // Makes sure we've got at least this much memory + void EnsureCapacity(int num); + + // Memory deallocation + void Purge(); + + // is the memory externally allocated? + bool IsExternallyAllocated() const; + + // Set the size by which the memory grows + void SetGrowSize(int size); + +private: + enum + { + EXTERNAL_BUFFER_MARKER = -1, + }; + + T *m_pMemory; + int m_nAllocationCount; + int m_nGrowSize; +}; + +// constructor, destructor +template +CUtlMemory::CUtlMemory(int nGrowSize, int nInitSize) : m_pMemory(0), +m_nAllocationCount(nInitSize), m_nGrowSize(nGrowSize) +{ + Assert((nGrowSize >= 0) && (nGrowSize != EXTERNAL_BUFFER_MARKER)); + if (m_nAllocationCount) + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +template +CUtlMemory::CUtlMemory(T *pMemory, int numElements) : m_pMemory(pMemory), +m_nAllocationCount(numElements) +{ + // Special marker indicating externally supplied memory + m_nGrowSize = EXTERNAL_BUFFER_MARKER; +} + +template +CUtlMemory::~CUtlMemory() +{ + Purge(); +} + +template +void CUtlMemory::Init(int nGrowSize, int nInitSize) +{ + Purge(); + + m_nGrowSize = nGrowSize; + m_nAllocationCount = nInitSize; + Assert(nGrowSize >= 0); + if (m_nAllocationCount) + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Attaches the buffer to external memory.... +template +void CUtlMemory::SetExternalBuffer(T *pMemory, int numElements) +{ + // Blow away any existing allocated memory + Purge(); + + m_pMemory = pMemory; + m_nAllocationCount = numElements; + + // Indicate that we don't own the memory + m_nGrowSize = EXTERNAL_BUFFER_MARKER; +} + +// element access +template +inline T& CUtlMemory::operator[](I i) +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T const& CUtlMemory::operator[](I i) const +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T& CUtlMemory::Element(I i) +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T const& CUtlMemory::Element(I i) const +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +// is the memory externally allocated? +template +bool CUtlMemory::IsExternallyAllocated() const +{ + return m_nGrowSize == EXTERNAL_BUFFER_MARKER; +} + +template +void CUtlMemory::SetGrowSize(int nSize) +{ + Assert((nSize >= 0) && (nSize != EXTERNAL_BUFFER_MARKER)); + m_nGrowSize = nSize; +} + +// Gets the base address (can change when adding elements!) +template +inline T *CUtlMemory::Base() +{ + return m_pMemory; +} + +template +inline T const *CUtlMemory::Base() const +{ + return m_pMemory; +} + +// Size +template +inline int CUtlMemory::NumAllocated() const +{ + return m_nAllocationCount; +} + +template +inline int CUtlMemory::Count() const +{ + return m_nAllocationCount; +} + +// Is element index valid? +template +inline bool CUtlMemory::IsIdxValid(I i) const +{ + return (((int)i) >= 0) && (((int) i) < m_nAllocationCount); +} + +// Grows the memory +template +void CUtlMemory::Grow(int num) +{ + Assert(num > 0); + + if (IsExternallyAllocated()) + { + // Can't grow a buffer whose memory was externally allocated + Assert(0); + return; + } + + // Make sure we have at least numallocated + num allocations. + // Use the grow rules specified for this memory (in m_nGrowSize) + int nAllocationRequested = m_nAllocationCount + num; + while (m_nAllocationCount < nAllocationRequested) + { + if (m_nAllocationCount != 0) + { + if (m_nGrowSize) + { + m_nAllocationCount += m_nGrowSize; + } + else + { + m_nAllocationCount += m_nAllocationCount; + } + } + else + { + // Compute an allocation which is at least as big as a cache line... + m_nAllocationCount = (31 + sizeof(T)) / sizeof(T); + Assert(m_nAllocationCount != 0); + } + } + + if (m_pMemory) + { + m_pMemory = (T *)realloc(m_pMemory, m_nAllocationCount * sizeof(T)); + } + else + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Makes sure we've got at least this much memory +template +inline void CUtlMemory::EnsureCapacity(int num) +{ + if (m_nAllocationCount >= num) + return; + + if (IsExternallyAllocated()) + { + // Can't grow a buffer whose memory was externally allocated + Assert(0); + return; + } + + m_nAllocationCount = num; + if (m_pMemory) + { + m_pMemory = (T *)realloc(m_pMemory, m_nAllocationCount * sizeof(T)); + } + else + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Memory deallocation +template +void CUtlMemory::Purge() +{ + if (!IsExternallyAllocated()) + { + if (m_pMemory) + { + free((void *)m_pMemory); + m_pMemory = 0; + } + m_nAllocationCount = 0; + } +} diff --git a/dep/hlsdk/public/utlrbtree.h b/dep/hlsdk/public/utlrbtree.h new file mode 100644 index 0000000..e8fca65 --- /dev/null +++ b/dep/hlsdk/public/utlrbtree.h @@ -0,0 +1,1295 @@ +//=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. =========== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// Purpose: +// +// $Header: $ +// $NoKeywords: $ +//============================================================================= + +#ifndef UTLRBTREE_H +#define UTLRBTREE_H + +//#include +#include "utlmemory.h" + +//----------------------------------------------------------------------------- +// Tool to generate a default compare function for any type that implements +// operator<, including all simple types +//----------------------------------------------------------------------------- + +template +class CDefOps +{ +public: + static bool LessFunc( const T &lhs, const T &rhs ) { return ( lhs < rhs ); } +}; + +#define DefLessFunc( type ) CDefOps::LessFunc + +//------------------------------------- + +inline bool StringLessThan( const char * const &lhs, const char * const &rhs) { return ( strcmp( lhs, rhs) < 0 ); } +inline bool CaselessStringLessThan( const char * const &lhs, const char * const &rhs ) { return ( _stricmp( lhs, rhs) < 0 ); } + +//------------------------------------- +// inline these two templates to stop multiple definitions of the same code +template <> inline bool CDefOps::LessFunc( const char * const &lhs, const char * const &rhs ) { return StringLessThan( lhs, rhs ); } +template <> inline bool CDefOps::LessFunc( char * const &lhs, char * const &rhs ) { return StringLessThan( lhs, rhs ); } + +//------------------------------------- + +template +void SetDefLessFunc( RBTREE_T &RBTree ) +{ +#ifdef _WIN32 + RBTree.SetLessFunc( DefLessFunc( RBTREE_T::KeyType_t ) ); +#elif _LINUX + RBTree.SetLessFunc( DefLessFunc( typename RBTREE_T::KeyType_t ) ); +#endif +} + +//----------------------------------------------------------------------------- +// A red-black binary search tree +//----------------------------------------------------------------------------- + +template +class CUtlRBTree +{ +public: + // Less func typedef + // Returns true if the first parameter is "less" than the second + typedef bool (*LessFunc_t)( T const &, T const & ); + + typedef T KeyType_t; + typedef T ElemType_t; + typedef I IndexType_t; + + // constructor, destructor + // Left at growSize = 0, the memory will first allocate 1 element and double in size + // at each increment. + // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below + CUtlRBTree( int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0 ); + ~CUtlRBTree( ); + + // gets particular elements + T& Element( I i ); + T const &Element( I i ) const; + T& operator[]( I i ); + T const &operator[]( I i ) const; + + // Gets the root + I Root() const; + + // Num elements + unsigned int Count() const; + + // Max "size" of the vector + I MaxElement() const; + + // Gets the children + I Parent( I i ) const; + I LeftChild( I i ) const; + I RightChild( I i ) const; + + // Tests if a node is a left or right child + bool IsLeftChild( I i ) const; + bool IsRightChild( I i ) const; + + // Tests if root or leaf + bool IsRoot( I i ) const; + bool IsLeaf( I i ) const; + + // Checks if a node is valid and in the tree + bool IsValidIndex( I i ) const; + + // Checks if the tree as a whole is valid + bool IsValid() const; + + // Invalid index + static I InvalidIndex(); + + // returns the tree depth (not a very fast operation) + int Depth( I node ) const; + int Depth() const; + + // Sets the less func + void SetLessFunc( LessFunc_t func ); + + // Allocation method + I NewNode(); + + // Insert method (inserts in order) + I Insert( T const &insert ); + void Insert( const T *pArray, int nItems ); + + // Find method + I Find( T const &search ) const; + + // Remove methods + void RemoveAt( I i ); + bool Remove( T const &remove ); + void RemoveAll( ); + + // Allocation, deletion + void FreeNode( I i ); + + // Iteration + I FirstInorder() const; + I NextInorder( I i ) const; + I PrevInorder( I i ) const; + I LastInorder() const; + + I FirstPreorder() const; + I NextPreorder( I i ) const; + I PrevPreorder( I i ) const; + I LastPreorder( ) const; + + I FirstPostorder() const; + I NextPostorder( I i ) const; + + // If you change the search key, this can be used to reinsert the + // element into the tree. + void Reinsert( I elem ); + + +protected: + enum NodeColor_t + { + RED = 0, + BLACK + }; + + struct Links_t + { + I m_Left; + I m_Right; + I m_Parent; + I m_Tag; + }; + + struct Node_t : public Links_t + { + T m_Data; + }; + + // Sets the children + void SetParent( I i, I parent ); + void SetLeftChild( I i, I child ); + void SetRightChild( I i, I child ); + void LinkToParent( I i, I parent, bool isLeft ); + + // Gets at the links + Links_t const &Links( I i ) const; + Links_t &Links( I i ); + + // Checks if a link is red or black + bool IsRed( I i ) const; + bool IsBlack( I i ) const; + + // Sets/gets node color + NodeColor_t Color( I i ) const; + void SetColor( I i, NodeColor_t c ); + + // operations required to preserve tree balance + void RotateLeft(I i); + void RotateRight(I i); + void InsertRebalance(I i); + void RemoveRebalance(I i); + + // Insertion, removal + I InsertAt( I parent, bool leftchild ); + + // copy constructors not allowed + CUtlRBTree( CUtlRBTree const &tree ); + + // Inserts a node into the tree, doesn't copy the data in. + void FindInsertionPosition( T const &insert, I &parent, bool &leftchild ); + + // Remove and add back an element in the tree. + void Unlink( I elem ); + void Link( I elem ); + + // Used for sorting. + LessFunc_t m_LessFunc; + + CUtlMemory m_Elements; + I m_Root; + I m_NumElements; + I m_FirstFree; + I m_TotalElements; + + Node_t* m_pElements; + + void ResetDbgInfo() + { + m_pElements = (Node_t*)m_Elements.Base(); + } +}; + + +//----------------------------------------------------------------------------- +// constructor, destructor +//----------------------------------------------------------------------------- + +template +CUtlRBTree::CUtlRBTree( int growSize, int initSize, LessFunc_t lessfunc ) : + m_Elements( growSize, initSize ), + m_LessFunc( lessfunc ), + m_Root( InvalidIndex() ), + m_NumElements( 0 ), m_TotalElements( 0 ), + m_FirstFree( InvalidIndex() ) +{ + ResetDbgInfo(); +} + +template +CUtlRBTree::~CUtlRBTree() +{ +} + +//----------------------------------------------------------------------------- +// gets particular elements +//----------------------------------------------------------------------------- + +template +inline T &CUtlRBTree::Element( I i ) +{ + return m_Elements[i].m_Data; +} + +template +inline T const &CUtlRBTree::Element( I i ) const +{ + return m_Elements[i].m_Data; +} + +template +inline T &CUtlRBTree::operator[]( I i ) +{ + return Element(i); +} + +template +inline T const &CUtlRBTree::operator[]( I i ) const +{ + return Element(i); +} + +//----------------------------------------------------------------------------- +// +// various accessors +// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Gets the root +//----------------------------------------------------------------------------- + +template +inline I CUtlRBTree::Root() const +{ + return m_Root; +} + +//----------------------------------------------------------------------------- +// Num elements +//----------------------------------------------------------------------------- + +template +inline unsigned int CUtlRBTree::Count() const +{ + return (unsigned int)m_NumElements; +} + +//----------------------------------------------------------------------------- +// Max "size" of the vector +//----------------------------------------------------------------------------- + +template +inline I CUtlRBTree::MaxElement() const +{ + return (I)m_TotalElements; +} + + +//----------------------------------------------------------------------------- +// Gets the children +//----------------------------------------------------------------------------- + +template +inline I CUtlRBTree::Parent( I i ) const +{ + return Links(i).m_Parent; +} + +template +inline I CUtlRBTree::LeftChild( I i ) const +{ + return Links(i).m_Left; +} + +template +inline I CUtlRBTree::RightChild( I i ) const +{ + return Links(i).m_Right; +} + +//----------------------------------------------------------------------------- +// Tests if a node is a left or right child +//----------------------------------------------------------------------------- + +template +inline bool CUtlRBTree::IsLeftChild( I i ) const +{ + return LeftChild(Parent(i)) == i; +} + +template +inline bool CUtlRBTree::IsRightChild( I i ) const +{ + return RightChild(Parent(i)) == i; +} + + +//----------------------------------------------------------------------------- +// Tests if root or leaf +//----------------------------------------------------------------------------- + +template +inline bool CUtlRBTree::IsRoot( I i ) const +{ + return i == m_Root; +} + +template +inline bool CUtlRBTree::IsLeaf( I i ) const +{ + return (LeftChild(i) == InvalidIndex()) && (RightChild(i) == InvalidIndex()); +} + + +//----------------------------------------------------------------------------- +// Checks if a node is valid and in the tree +//----------------------------------------------------------------------------- + +template +inline bool CUtlRBTree::IsValidIndex( I i ) const +{ + return LeftChild(i) != i; +} + + +//----------------------------------------------------------------------------- +// Invalid index +//----------------------------------------------------------------------------- + +template +I CUtlRBTree::InvalidIndex() +{ + return (I)~0; +} + + +//----------------------------------------------------------------------------- +// returns the tree depth (not a very fast operation) +//----------------------------------------------------------------------------- + +template +inline int CUtlRBTree::Depth() const +{ + return Depth(Root()); +} + +//----------------------------------------------------------------------------- +// Sets the children +//----------------------------------------------------------------------------- + +template +inline void CUtlRBTree::SetParent( I i, I parent ) +{ + Links(i).m_Parent = parent; +} + +template +inline void CUtlRBTree::SetLeftChild( I i, I child ) +{ + Links(i).m_Left = child; +} + +template +inline void CUtlRBTree::SetRightChild( I i, I child ) +{ + Links(i).m_Right = child; +} + +//----------------------------------------------------------------------------- +// Gets at the links +//----------------------------------------------------------------------------- + +template +inline typename CUtlRBTree::Links_t const &CUtlRBTree::Links( I i ) const +{ + // Sentinel node, makes life easier + static Links_t s_Sentinel = + { + InvalidIndex(), InvalidIndex(), InvalidIndex(), CUtlRBTree::BLACK + }; + + return (i != InvalidIndex()) ? *(Links_t*)&m_Elements[i] : + *(Links_t*)&s_Sentinel; +} + +template +inline typename CUtlRBTree::Links_t &CUtlRBTree::Links( I i ) +{ + Assert(i != InvalidIndex()); + return *(Links_t *)&m_Elements[i]; +} + +//----------------------------------------------------------------------------- +// Checks if a link is red or black +//----------------------------------------------------------------------------- + +template +inline bool CUtlRBTree::IsRed( I i ) const +{ + return (Links(i).m_Tag == RED); +} + +template +inline bool CUtlRBTree::IsBlack( I i ) const +{ + return (Links(i).m_Tag == BLACK); +} + + +//----------------------------------------------------------------------------- +// Sets/gets node color +//----------------------------------------------------------------------------- + +template +inline typename CUtlRBTree::NodeColor_t CUtlRBTree::Color( I i ) const +{ + return (NodeColor_t)Links(i).m_Tag; +} + +template +inline void CUtlRBTree::SetColor( I i, typename CUtlRBTree::NodeColor_t c ) +{ + Links(i).m_Tag = (I)c; +} + +//----------------------------------------------------------------------------- +// Allocates/ deallocates nodes +//----------------------------------------------------------------------------- + +template +I CUtlRBTree::NewNode() +{ + I newElem; + + // Nothing in the free list; add. + if (m_FirstFree == InvalidIndex()) + { + if (m_Elements.NumAllocated() == m_TotalElements) + m_Elements.Grow(); + newElem = m_TotalElements++; + } + else + { + newElem = m_FirstFree; + m_FirstFree = RightChild(m_FirstFree); + } + +#ifdef _DEBUG + // reset links to invalid.... + Links_t &node = Links(newElem); + node.m_Left = node.m_Right = node.m_Parent = InvalidIndex(); +#endif + + Construct( &Element(newElem) ); + ResetDbgInfo(); + + return newElem; +} + +template +void CUtlRBTree::FreeNode( I i ) +{ + Assert( IsValidIndex(i) && (i != InvalidIndex()) ); + Destruct( &Element(i) ); + SetLeftChild( i, i ); // indicates it's in not in the tree + SetRightChild( i, m_FirstFree ); + m_FirstFree = i; +} + + +//----------------------------------------------------------------------------- +// Rotates node i to the left +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::RotateLeft(I elem) +{ + I rightchild = RightChild(elem); + SetRightChild( elem, LeftChild(rightchild) ); + if (LeftChild(rightchild) != InvalidIndex()) + SetParent( LeftChild(rightchild), elem ); + + if (rightchild != InvalidIndex()) + SetParent( rightchild, Parent(elem) ); + if (!IsRoot(elem)) + { + if (IsLeftChild(elem)) + SetLeftChild( Parent(elem), rightchild ); + else + SetRightChild( Parent(elem), rightchild ); + } + else + m_Root = rightchild; + + SetLeftChild( rightchild, elem ); + if (elem != InvalidIndex()) + SetParent( elem, rightchild ); +} + + +//----------------------------------------------------------------------------- +// Rotates node i to the right +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::RotateRight(I elem) +{ + I leftchild = LeftChild(elem); + SetLeftChild( elem, RightChild(leftchild) ); + if (RightChild(leftchild) != InvalidIndex()) + SetParent( RightChild(leftchild), elem ); + + if (leftchild != InvalidIndex()) + SetParent( leftchild, Parent(elem) ); + if (!IsRoot(elem)) + { + if (IsRightChild(elem)) + SetRightChild( Parent(elem), leftchild ); + else + SetLeftChild( Parent(elem), leftchild ); + } + else + m_Root = leftchild; + + SetRightChild( leftchild, elem ); + if (elem != InvalidIndex()) + SetParent( elem, leftchild ); +} + + +//----------------------------------------------------------------------------- +// Rebalances the tree after an insertion +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::InsertRebalance(I elem) +{ + while ( !IsRoot(elem) && (Color(Parent(elem)) == RED) ) + { + I parent = Parent(elem); + I grandparent = Parent(parent); + + /* we have a violation */ + if (IsLeftChild(parent)) + { + I uncle = RightChild(grandparent); + if (IsRed(uncle)) + { + /* uncle is RED */ + SetColor(parent, BLACK); + SetColor(uncle, BLACK); + SetColor(grandparent, RED); + elem = grandparent; + } + else + { + /* uncle is BLACK */ + if (IsRightChild(elem)) + { + /* make x a left child, will change parent and grandparent */ + elem = parent; + RotateLeft(elem); + parent = Parent(elem); + grandparent = Parent(parent); + } + /* recolor and rotate */ + SetColor(parent, BLACK); + SetColor(grandparent, RED); + RotateRight(grandparent); + } + } + else + { + /* mirror image of above code */ + I uncle = LeftChild(grandparent); + if (IsRed(uncle)) + { + /* uncle is RED */ + SetColor(parent, BLACK); + SetColor(uncle, BLACK); + SetColor(grandparent, RED); + elem = grandparent; + } + else + { + /* uncle is BLACK */ + if (IsLeftChild(elem)) + { + /* make x a right child, will change parent and grandparent */ + elem = parent; + RotateRight(parent); + parent = Parent(elem); + grandparent = Parent(parent); + } + /* recolor and rotate */ + SetColor(parent, BLACK); + SetColor(grandparent, RED); + RotateLeft(grandparent); + } + } + } + SetColor( m_Root, BLACK ); +} + + +//----------------------------------------------------------------------------- +// Insert a node into the tree +//----------------------------------------------------------------------------- + +template +I CUtlRBTree::InsertAt( I parent, bool leftchild ) +{ + I i = NewNode(); + LinkToParent( i, parent, leftchild ); + ++m_NumElements; + return i; +} + +template +void CUtlRBTree::LinkToParent( I i, I parent, bool isLeft ) +{ + Links_t &elem = Links(i); + elem.m_Parent = parent; + elem.m_Left = elem.m_Right = InvalidIndex(); + elem.m_Tag = RED; + + /* insert node in tree */ + if (parent != InvalidIndex()) + { + if (isLeft) + Links(parent).m_Left = i; + else + Links(parent).m_Right = i; + } + else + { + m_Root = i; + } + + InsertRebalance(i); + + Assert(IsValid()); +} + +//----------------------------------------------------------------------------- +// Rebalance the tree after a deletion +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::RemoveRebalance(I elem) +{ + while (elem != m_Root && IsBlack(elem)) + { + I parent = Parent(elem); + + // If elem is the left child of the parent + if (elem == LeftChild(parent)) + { + // Get our sibling + I sibling = RightChild(parent); + if (IsRed(sibling)) + { + SetColor(sibling, BLACK); + SetColor(parent, RED); + RotateLeft(parent); + + // We may have a new parent now + parent = Parent(elem); + sibling = RightChild(parent); + } + if ( (IsBlack(LeftChild(sibling))) && (IsBlack(RightChild(sibling))) ) + { + if (sibling != InvalidIndex()) + SetColor(sibling, RED); + elem = parent; + } + else + { + if (IsBlack(RightChild(sibling))) + { + SetColor(LeftChild(sibling), BLACK); + SetColor(sibling, RED); + RotateRight(sibling); + + // rotation may have changed this + parent = Parent(elem); + sibling = RightChild(parent); + } + SetColor( sibling, Color(parent) ); + SetColor( parent, BLACK ); + SetColor( RightChild(sibling), BLACK ); + RotateLeft( parent ); + elem = m_Root; + } + } + else + { + // Elem is the right child of the parent + I sibling = LeftChild(parent); + if (IsRed(sibling)) + { + SetColor(sibling, BLACK); + SetColor(parent, RED); + RotateRight(parent); + + // We may have a new parent now + parent = Parent(elem); + sibling = LeftChild(parent); + } + if ( (IsBlack(RightChild(sibling))) && (IsBlack(LeftChild(sibling))) ) + { + if (sibling != InvalidIndex()) + SetColor( sibling, RED ); + elem = parent; + } + else + { + if (IsBlack(LeftChild(sibling))) + { + SetColor( RightChild(sibling), BLACK ); + SetColor( sibling, RED ); + RotateLeft( sibling ); + + // rotation may have changed this + parent = Parent(elem); + sibling = LeftChild(parent); + } + SetColor( sibling, Color(parent) ); + SetColor( parent, BLACK ); + SetColor( LeftChild(sibling), BLACK ); + RotateRight( parent ); + elem = m_Root; + } + } + } + SetColor( elem, BLACK ); +} + +template +void CUtlRBTree::Unlink( I elem ) +{ + if ( elem != InvalidIndex() ) + { + I x, y; + + if ((LeftChild(elem) == InvalidIndex()) || + (RightChild(elem) == InvalidIndex())) + { + /* y has a NIL node as a child */ + y = elem; + } + else + { + /* find tree successor with a NIL node as a child */ + y = RightChild(elem); + while (LeftChild(y) != InvalidIndex()) + y = LeftChild(y); + } + + /* x is y's only child */ + if (LeftChild(y) != InvalidIndex()) + x = LeftChild(y); + else + x = RightChild(y); + + /* remove y from the parent chain */ + if (x != InvalidIndex()) + SetParent( x, Parent(y) ); + if (!IsRoot(y)) + { + if (IsLeftChild(y)) + SetLeftChild( Parent(y), x ); + else + SetRightChild( Parent(y), x ); + } + else + m_Root = x; + + // need to store this off now, we'll be resetting y's color + NodeColor_t ycolor = Color(y); + if (y != elem) + { + // Standard implementations copy the data around, we cannot here. + // Hook in y to link to the same stuff elem used to. + SetParent( y, Parent(elem) ); + SetRightChild( y, RightChild(elem) ); + SetLeftChild( y, LeftChild(elem) ); + + if (!IsRoot(elem)) + if (IsLeftChild(elem)) + SetLeftChild( Parent(elem), y ); + else + SetRightChild( Parent(elem), y ); + else + m_Root = y; + + if (LeftChild(y) != InvalidIndex()) + SetParent( LeftChild(y), y ); + if (RightChild(y) != InvalidIndex()) + SetParent( RightChild(y), y ); + + SetColor( y, Color(elem) ); + } + + if ((x != InvalidIndex()) && (ycolor == BLACK)) + RemoveRebalance(x); + } +} + +template +void CUtlRBTree::Link( I elem ) +{ + if ( elem != InvalidIndex() ) + { + I parent; + bool leftchild; + + FindInsertionPosition( Element( elem ), parent, leftchild ); + + LinkToParent( elem, parent, leftchild ); + } +} + +//----------------------------------------------------------------------------- +// Delete a node from the tree +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::RemoveAt(I elem) +{ + if ( elem != InvalidIndex() ) + { + Unlink( elem ); + + FreeNode(elem); + --m_NumElements; + } +} + + +//----------------------------------------------------------------------------- +// remove a node in the tree +//----------------------------------------------------------------------------- + +template bool CUtlRBTree::Remove( T const &search ) +{ + I node = Find( search ); + if (node != InvalidIndex()) + { + RemoveAt(node); + return true; + } + return false; +} + + +//----------------------------------------------------------------------------- +// Removes all nodes from the tree +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::RemoveAll() +{ + // Just iterate through the whole list and add to free list + // much faster than doing all of the rebalancing + // also, do it so the free list is pointing to stuff in order + // to get better cache coherence when re-adding stuff to this tree. + I prev = InvalidIndex(); + for (int i = (int)m_TotalElements; --i >= 0; ) + { + I idx = (I)i; + if (IsValidIndex(idx)) + Destruct( &Element(idx) ); + SetRightChild( idx, prev ); + SetLeftChild( idx, idx ); + prev = idx; + } + m_FirstFree = m_TotalElements ? (I)0 : InvalidIndex(); + m_Root = InvalidIndex(); + m_NumElements = 0; +} + + +//----------------------------------------------------------------------------- +// iteration +//----------------------------------------------------------------------------- + +template +I CUtlRBTree::FirstInorder() const +{ + I i = m_Root; + while (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + return i; +} + +template +I CUtlRBTree::NextInorder( I i ) const +{ + Assert(IsValidIndex(i)); + + if (RightChild(i) != InvalidIndex()) + { + i = RightChild(i); + while (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + return i; + } + + I parent = Parent(i); + while (IsRightChild(i)) + { + i = parent; + if (i == InvalidIndex()) break; + parent = Parent(i); + } + return parent; +} + +template +I CUtlRBTree::PrevInorder( I i ) const +{ + Assert(IsValidIndex(i)); + + if (LeftChild(i) != InvalidIndex()) + { + i = LeftChild(i); + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + return i; + } + + I parent = Parent(i); + while (IsLeftChild(i)) + { + i = parent; + if (i == InvalidIndex()) break; + parent = Parent(i); + } + return parent; +} + +template +I CUtlRBTree::LastInorder() const +{ + I i = m_Root; + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + return i; +} + +template +I CUtlRBTree::FirstPreorder() const +{ + return m_Root; +} + +template +I CUtlRBTree::NextPreorder( I i ) const +{ + if (LeftChild(i) != InvalidIndex()) + return LeftChild(i); + + if (RightChild(i) != InvalidIndex()) + return RightChild(i); + + I parent = Parent(i); + while( parent != InvalidIndex()) + { + if (IsLeftChild(i) && (RightChild(parent) != InvalidIndex())) + return RightChild(parent); + i = parent; + parent = Parent(parent); + } + return InvalidIndex(); +} + +template +I CUtlRBTree::PrevPreorder( I i ) const +{ + Assert(0); // not implemented yet + return InvalidIndex(); +} + +template +I CUtlRBTree::LastPreorder() const +{ + I i = m_Root; + while (1) + { + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + + if (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + else + break; + } + return i; +} + +template +I CUtlRBTree::FirstPostorder() const +{ + I i = m_Root; + while (!IsLeaf(i)) + { + if (LeftChild(i)) + i = LeftChild(i); + else + i = RightChild(i); + } + return i; +} + +template +I CUtlRBTree::NextPostorder( I i ) const +{ + I parent = Parent(i); + if (parent == InvalidIndex()) + return InvalidIndex(); + + if (IsRightChild(i)) + return parent; + + if (RightChild(parent) == InvalidIndex()) + return parent; + + i = RightChild(parent); + while (!IsLeaf(i)) + { + if (LeftChild(i)) + i = LeftChild(i); + else + i = RightChild(i); + } + return i; +} + + +template +void CUtlRBTree::Reinsert( I elem ) +{ + Unlink( elem ); + Link( elem ); +} + + +//----------------------------------------------------------------------------- +// returns the tree depth (not a very fast operation) +//----------------------------------------------------------------------------- + +template +int CUtlRBTree::Depth( I node ) const +{ + if (node == InvalidIndex()) + return 0; + + int depthright = Depth( RightChild(node) ); + int depthleft = Depth( LeftChild(node) ); + return Q_max(depthright, depthleft) + 1; +} + + +//----------------------------------------------------------------------------- +// Makes sure the tree is valid after every operation +//----------------------------------------------------------------------------- + +template +bool CUtlRBTree::IsValid() const +{ + if ( !Count() ) + return true; + + if (( Root() >= MaxElement()) || ( Parent( Root() ) != InvalidIndex() )) + goto InvalidTree; + +#ifdef UTLTREE_PARANOID + + // First check to see that mNumEntries matches reality. + // count items on the free list + int numFree = 0; + int curr = m_FirstFree; + while (curr != InvalidIndex()) + { + ++numFree; + curr = RightChild(curr); + if ( (curr > MaxElement()) && (curr != InvalidIndex()) ) + goto InvalidTree; + } + if (MaxElement() - numFree != Count()) + goto InvalidTree; + + // iterate over all elements, looking for validity + // based on the self pointers + int numFree2 = 0; + for (curr = 0; curr < MaxElement(); ++curr) + { + if (!IsValidIndex(curr)) + ++numFree2; + else + { + int right = RightChild(curr); + int left = LeftChild(curr); + if ((right == left) && (right != InvalidIndex()) ) + goto InvalidTree; + + if (right != InvalidIndex()) + { + if (!IsValidIndex(right)) + goto InvalidTree; + if (Parent(right) != curr) + goto InvalidTree; + if (IsRed(curr) && IsRed(right)) + goto InvalidTree; + } + + if (left != InvalidIndex()) + { + if (!IsValidIndex(left)) + goto InvalidTree; + if (Parent(left) != curr) + goto InvalidTree; + if (IsRed(curr) && IsRed(left)) + goto InvalidTree; + } + } + } + if (numFree2 != numFree) + goto InvalidTree; + +#endif // UTLTREE_PARANOID + + return true; + +InvalidTree: + return false; +} + + +//----------------------------------------------------------------------------- +// Sets the less func +//----------------------------------------------------------------------------- + +template +void CUtlRBTree::SetLessFunc( typename CUtlRBTree::LessFunc_t func ) +{ + if (!m_LessFunc) + m_LessFunc = func; + else + { + // need to re-sort the tree here.... + Assert(0); + } +} + + +//----------------------------------------------------------------------------- +// inserts a node into the tree +//----------------------------------------------------------------------------- + +// Inserts a node into the tree, doesn't copy the data in. +template +void CUtlRBTree::FindInsertionPosition( T const &insert, I &parent, bool &leftchild ) +{ + Assert( m_LessFunc ); + + /* find where node belongs */ + I current = m_Root; + parent = InvalidIndex(); + leftchild = false; + while (current != InvalidIndex()) + { + parent = current; + if (m_LessFunc( insert, Element(current) )) + { + leftchild = true; current = LeftChild(current); + } + else + { + leftchild = false; current = RightChild(current); + } + } +} + +template +I CUtlRBTree::Insert( T const &insert ) +{ + // use copy constructor to copy it in + I parent; + bool leftchild; + FindInsertionPosition( insert, parent, leftchild ); + I newNode = InsertAt( parent, leftchild ); + CopyConstruct( &Element( newNode ), insert ); + return newNode; +} + + +template +void CUtlRBTree::Insert( const T *pArray, int nItems ) +{ + while ( nItems-- ) + { + Insert( *pArray++ ); + } +} + +//----------------------------------------------------------------------------- +// finds a node in the tree +//----------------------------------------------------------------------------- + +template +I CUtlRBTree::Find( T const &search ) const +{ + Assert( m_LessFunc ); + + I current = m_Root; + while (current != InvalidIndex()) + { + if (m_LessFunc( search, Element(current) )) + current = LeftChild(current); + else if (m_LessFunc( Element(current), search )) + current = RightChild(current); + else + break; + } + return current; +} + + + + + +#endif // UTLRBTREE_H diff --git a/dep/hlsdk/public/utlvector.h b/dep/hlsdk/public/utlvector.h new file mode 100644 index 0000000..5181a64 --- /dev/null +++ b/dep/hlsdk/public/utlvector.h @@ -0,0 +1,574 @@ +//=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. =========== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// $Header: $ +// $NoKeywords: $ +// +// A growable memory class. +//============================================================================= + +#ifndef UTLVECTOR_H +#define UTLVECTOR_H +#ifdef _WIN32 +#pragma once +#endif + +#include "utlmemory.h" +#include "tier0/platform.h" + +template +class CUtlVector +{ +public: + typedef T ElemType_t; + + // constructor, destructor + CUtlVector( int growSize = 0, int initSize = 0 ); + CUtlVector( T* pMemory, int numElements ); + ~CUtlVector(); + + // Copy the array. + CUtlVector& operator=( const CUtlVector &other ); + + // element access + T& operator[]( int i ); + T const& operator[]( int i ) const; + T& Element( int i ); + T const& Element( int i ) const; + + // Gets the base address (can change when adding elements!) + T* Base(); + T const* Base() const; + + // Returns the number of elements in the vector + // SIZE IS DEPRECATED! + int Count() const; + int Size() const; // don't use me! + + // Is element index valid? + bool IsValidIndex( int i ) const; + static int InvalidIndex( void ); + + // Adds an element, uses default constructor + int AddToHead(); + int AddToTail(); + int InsertBefore( int elem ); + int InsertAfter( int elem ); + + // Adds an element, uses copy constructor + int AddToHead( T const& src ); + int AddToTail( T const& src ); + int InsertBefore( int elem, T const& src ); + int InsertAfter( int elem, T const& src ); + + // Adds multiple elements, uses default constructor + int AddMultipleToHead( int num ); + int AddMultipleToTail( int num, const T *pToCopy=NULL ); + int InsertMultipleBefore( int elem, int num, const T *pToCopy=NULL ); // If pToCopy is set, then it's an array of length 'num' and + int InsertMultipleAfter( int elem, int num ); + + // Calls RemoveAll() then AddMultipleToTail. + void SetSize( int size ); + void SetCount( int count ); + + // Calls SetSize and copies each element. + void CopyArray( T const *pArray, int size ); + + // Add the specified array to the tail. + int AddVectorToTail( CUtlVector const &src ); + + // Finds an element (element needs operator== defined) + int Find( T const& src ) const; + + bool HasElement( T const& src ); + + // Makes sure we have enough memory allocated to store a requested # of elements + void EnsureCapacity( int num ); + + // Makes sure we have at least this many elements + void EnsureCount( int num ); + + // Element removal + void FastRemove( int elem ); // doesn't preserve order + void Remove( int elem ); // preserves order, shifts elements + void FindAndRemove( T const& src ); // removes first occurrence of src, preserves order, shifts elements + void RemoveMultiple( int elem, int num ); // preserves order, shifts elements + void RemoveAll(); // doesn't deallocate memory + + // Memory deallocation + void Purge(); + + // Purges the list and calls delete on each element in it. + void PurgeAndDeleteElements(); + + // Set the size by which it grows when it needs to allocate more memory. + void SetGrowSize( int size ); + +protected: + // Can't copy this unless we explicitly do it! + CUtlVector( CUtlVector const& vec ) { assert(0); + } + + // Grows the vector + void GrowVector( int num = 1 ); + + // Shifts elements.... + void ShiftElementsRight( int elem, int num = 1 ); + void ShiftElementsLeft( int elem, int num = 1 ); + + // For easier access to the elements through the debugger + void ResetDbgInfo(); + + CUtlMemory m_Memory; + int m_Size; + + // For easier access to the elements through the debugger + // it's in release builds so this can be used in libraries correctly + T *m_pElements; +}; + +//----------------------------------------------------------------------------- +// For easier access to the elements through the debugger +//----------------------------------------------------------------------------- +template< class T > +inline void CUtlVector::ResetDbgInfo() +{ + m_pElements = m_Memory.Base(); +} + +//----------------------------------------------------------------------------- +// constructor, destructor +//----------------------------------------------------------------------------- +template< class T > +inline CUtlVector::CUtlVector( int growSize, int initSize ) : + m_Memory(growSize, initSize), m_Size(0) +{ + ResetDbgInfo(); +} + +template< class T > +inline CUtlVector::CUtlVector( T* pMemory, int numElements ) : + m_Memory(pMemory, numElements), m_Size(0) +{ + ResetDbgInfo(); +} + +template< class T > +inline CUtlVector::~CUtlVector() +{ + Purge(); +} + +template +inline CUtlVector& CUtlVector::operator=( const CUtlVector &other ) +{ + CopyArray( other.Base(), other.Count() ); + return *this; +} + +//----------------------------------------------------------------------------- +// element access +//----------------------------------------------------------------------------- +template< class T > +inline T& CUtlVector::operator[]( int i ) +{ + assert( IsValidIndex(i) ); + return m_Memory[i]; +} + +template< class T > +inline T const& CUtlVector::operator[]( int i ) const +{ + assert( IsValidIndex(i) ); + return m_Memory[i]; +} + +template< class T > +inline T& CUtlVector::Element( int i ) +{ + assert( IsValidIndex(i) ); + return m_Memory[i]; +} + +template< class T > +inline T const& CUtlVector::Element( int i ) const +{ + assert( IsValidIndex(i) ); + return m_Memory[i]; +} + +//----------------------------------------------------------------------------- +// Gets the base address (can change when adding elements!) +//----------------------------------------------------------------------------- +template< class T > +inline T* CUtlVector::Base() +{ + return m_Memory.Base(); +} + +template< class T > +inline T const* CUtlVector::Base() const +{ + return m_Memory.Base(); +} + +//----------------------------------------------------------------------------- +// Count +//----------------------------------------------------------------------------- +template< class T > +inline int CUtlVector::Size() const +{ + return m_Size; +} + +template< class T > +inline int CUtlVector::Count() const +{ + return m_Size; +} + +//----------------------------------------------------------------------------- +// Is element index valid? +//----------------------------------------------------------------------------- +template< class T > +inline bool CUtlVector::IsValidIndex( int i ) const +{ + return (i >= 0) && (i < m_Size); +} + +//----------------------------------------------------------------------------- +// Returns in invalid index +//----------------------------------------------------------------------------- +template< class T > +inline int CUtlVector::InvalidIndex( void ) +{ + return -1; +} + +//----------------------------------------------------------------------------- +// Grows the vector +//----------------------------------------------------------------------------- +template< class T > +void CUtlVector::GrowVector( int num ) +{ + if (m_Size + num - 1 >= m_Memory.NumAllocated()) + { + m_Memory.Grow( m_Size + num - m_Memory.NumAllocated() ); + } + + m_Size += num; + ResetDbgInfo(); +} + +//----------------------------------------------------------------------------- +// Makes sure we have enough memory allocated to store a requested # of elements +//----------------------------------------------------------------------------- +template< class T > +void CUtlVector::EnsureCapacity( int num ) +{ + m_Memory.EnsureCapacity(num); + ResetDbgInfo(); +} + +//----------------------------------------------------------------------------- +// Makes sure we have at least this many elements +//----------------------------------------------------------------------------- +template< class T > +void CUtlVector::EnsureCount( int num ) +{ + if (Count() < num) + AddMultipleToTail( num - Count() ); +} + +//----------------------------------------------------------------------------- +// Shifts elements +//----------------------------------------------------------------------------- +template< class T > +void CUtlVector::ShiftElementsRight( int elem, int num ) +{ + assert( IsValidIndex(elem) || ( m_Size == 0 ) || ( num == 0 )); + int numToMove = m_Size - elem - num; + if ((numToMove > 0) && (num > 0)) + memmove( &Element(elem+num), &Element(elem), numToMove * sizeof(T) ); +} + +template< class T > +void CUtlVector::ShiftElementsLeft( int elem, int num ) +{ + assert( IsValidIndex(elem) || ( m_Size == 0 ) || ( num == 0 )); + int numToMove = m_Size - elem - num; + if ((numToMove > 0) && (num > 0)) + { + memmove( &Element(elem), &Element(elem+num), numToMove * sizeof(T) ); + +#ifdef _DEBUG + memset( &Element(m_Size-num), 0xDD, num * sizeof(T) ); +#endif + } +} + +//----------------------------------------------------------------------------- +// Adds an element, uses default constructor +//----------------------------------------------------------------------------- + +template< class T > +inline int CUtlVector::AddToHead() +{ + return InsertBefore(0); +} + +template< class T > +inline int CUtlVector::AddToTail() +{ + return InsertBefore( m_Size ); +} + +template< class T > +inline int CUtlVector::InsertAfter( int elem ) +{ + return InsertBefore( elem + 1 ); +} + +template< class T > +int CUtlVector::InsertBefore( int elem ) +{ + // Can insert at the end + assert( (elem == Count()) || IsValidIndex(elem) ); + + GrowVector(); + ShiftElementsRight(elem); + Construct( &Element(elem) ); + return elem; +} + +//----------------------------------------------------------------------------- +// Adds an element, uses copy constructor +//----------------------------------------------------------------------------- + +template< class T > +inline int CUtlVector::AddToHead( T const& src ) +{ + return InsertBefore( 0, src ); +} + +template< class T > +inline int CUtlVector::AddToTail( T const& src ) +{ + return InsertBefore( m_Size, src ); +} + +template< class T > +inline int CUtlVector::InsertAfter( int elem, T const& src ) +{ + return InsertBefore( elem + 1, src ); +} + +template< class T > +int CUtlVector::InsertBefore( int elem, T const& src ) +{ + // Can insert at the end + assert( (elem == Count()) || IsValidIndex(elem) ); + + GrowVector(); + ShiftElementsRight(elem); + CopyConstruct( &Element(elem), src ); + return elem; +} + + +//----------------------------------------------------------------------------- +// Adds multiple elements, uses default constructor +//----------------------------------------------------------------------------- + +template< class T > +inline int CUtlVector::AddMultipleToHead( int num ) +{ + return InsertMultipleBefore( 0, num ); +} + +template< class T > +inline int CUtlVector::AddMultipleToTail( int num, const T *pToCopy ) +{ + return InsertMultipleBefore( m_Size, num, pToCopy ); +} + +template< class T > +int CUtlVector::InsertMultipleAfter( int elem, int num ) +{ + return InsertMultipleBefore( elem + 1, num ); +} + + +template< class T > +void CUtlVector::SetCount( int count ) +{ + RemoveAll(); + AddMultipleToTail( count ); +} + +template< class T > +inline void CUtlVector::SetSize( int size ) +{ + SetCount( size ); +} + +template< class T > +void CUtlVector::CopyArray( T const *pArray, int size ) +{ + SetSize( size ); + for( int i=0; i < size; i++ ) + (*this)[i] = pArray[i]; +} + +template< class T > +int CUtlVector::AddVectorToTail( CUtlVector const &src ) +{ + int base = Count(); + + // Make space. + AddMultipleToTail( src.Count() ); + + // Copy the elements. + for ( int i=0; i < src.Count(); i++ ) + (*this)[base + i] = src[i]; + + return base; +} + +template< class T > +inline int CUtlVector::InsertMultipleBefore( int elem, int num, const T *pToInsert ) +{ + if( num == 0 ) + return elem; + + // Can insert at the end + assert( (elem == Count()) || IsValidIndex(elem) ); + + GrowVector(num); + ShiftElementsRight(elem, num); + + // Invoke default constructors + for (int i = 0; i < num; ++i) + Construct( &Element(elem+i) ); + + // Copy stuff in? + if ( pToInsert ) + { + for ( int i=0; i < num; i++ ) + { + Element( elem+i ) = pToInsert[i]; + } + } + + return elem; +} + +//----------------------------------------------------------------------------- +// Finds an element (element needs operator== defined) +//----------------------------------------------------------------------------- +template< class T > +int CUtlVector::Find( T const& src ) const +{ + for ( int i = 0; i < Count(); ++i ) + { + if (Element(i) == src) + return i; + } + return -1; +} + +template< class T > +bool CUtlVector::HasElement( T const& src ) +{ + return ( Find(src) >= 0 ); +} + +//----------------------------------------------------------------------------- +// Element removal +//----------------------------------------------------------------------------- + +template< class T > +void CUtlVector::FastRemove( int elem ) +{ + assert( IsValidIndex(elem) ); + + Destruct( &Element(elem) ); + if (m_Size > 0) + { + memcpy( &Element(elem), &Element(m_Size-1), sizeof(T) ); + --m_Size; + } +} + +template< class T > +void CUtlVector::Remove( int elem ) +{ + Destruct( &Element(elem) ); + ShiftElementsLeft(elem); + --m_Size; +} + +template< class T > +void CUtlVector::FindAndRemove( T const& src ) +{ + int elem = Find( src ); + if ( elem != -1 ) + { + Remove( elem ); + } +} + +template< class T > +void CUtlVector::RemoveMultiple( int elem, int num ) +{ + assert( IsValidIndex(elem) ); + assert( elem + num <= Count() ); + + for (int i = elem + num; --i >= elem; ) + Destruct(&Element(i)); + + ShiftElementsLeft(elem, num); + m_Size -= num; +} + +template< class T > +void CUtlVector::RemoveAll() +{ + for (int i = m_Size; --i >= 0; ) + Destruct(&Element(i)); + + m_Size = 0; +} + +//----------------------------------------------------------------------------- +// Memory deallocation +//----------------------------------------------------------------------------- + +template< class T > +void CUtlVector::Purge() +{ + RemoveAll(); + m_Memory.Purge( ); + ResetDbgInfo(); +} + +template +inline void CUtlVector::PurgeAndDeleteElements() +{ + for( int i=0; i < m_Size; i++ ) + delete Element(i); + + Purge(); +} + +template< class T > +void CUtlVector::SetGrowSize( int size ) +{ + m_Memory.SetGrowSize( size ); +} + +#endif // CCVECTOR_H diff --git a/dep/hlsdk/public/vgui/VGUI.h b/dep/hlsdk/public/vgui/VGUI.h new file mode 100644 index 0000000..cdaed0d --- /dev/null +++ b/dep/hlsdk/public/vgui/VGUI.h @@ -0,0 +1,30 @@ +#pragma once + +#ifdef _WIN32 + #define VGUI2_LIB "vgui2.dll" +#else + #define VGUI2_LIB "vgui2.so" +#endif // _WIN32 + +namespace vgui2 +{ +// handle to an internal vgui panel +// this is the only handle to a panel that is valid across dll boundaries +typedef unsigned int VPANEL; + +// handles to vgui objects +// NULL values signify an invalid value +typedef unsigned long HScheme; +typedef unsigned long HTexture; +typedef unsigned long HCursor; + +typedef int HContext; +typedef unsigned long HPanel; +typedef unsigned long HFont; + +// the value of an invalid font handle +const VPANEL NULL_PANEL = 0; +const HFont INVALID_FONT = 0; +const HPanel INVALID_PANEL = 0xffffffff; + +} // namespace vgui2 diff --git a/dep/metamod/dllapi.h b/dep/metamod/dllapi.h new file mode 100644 index 0000000..f922a3d --- /dev/null +++ b/dep/metamod/dllapi.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +#ifndef DLLEXPORT +#ifdef _WIN32 +#define DLLEXPORT __declspec(dllexport) +#else +#define DLLEXPORT __attribute__((visibility("default"))) +#endif // _WIN32 +#endif // DLLEXPORT + +#ifndef C_DLLEXPORT +#define C_DLLEXPORT extern "C" DLLEXPORT +#endif + +typedef void (*FN_GAMEINIT)(); + +// Typedefs for these are provided in SDK engine/eiface.h, but I didn't +// like the names (APIFUNCTION, APIFUNCTION2, NEW_DLL_FUNCTIONS_FN). +typedef int (*GETENTITYAPI_FN)(DLL_FUNCTIONS* pFunctionTable, int interfaceVersion); +typedef int (*GETENTITYAPI2_FN)(DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); +typedef int (*GETNEWDLLFUNCTIONS_FN)(NEW_DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); + +C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS* pFunctionTable, int interfaceVersion); +C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); +C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS* pNewFunctionTable, int* interfaceVersion); diff --git a/dep/metamod/engine_api.h b/dep/metamod/engine_api.h new file mode 100644 index 0000000..234fe57 --- /dev/null +++ b/dep/metamod/engine_api.h @@ -0,0 +1,20 @@ +#pragma once + +struct enginefuncs_s; + +// Plugin's GetEngineFunctions, called by metamod. +typedef int (*GET_ENGINE_FUNCTIONS_FN)(enginefuncs_s* pengfuncsFromEngine, int* interfaceVersion); + +// According to SDK engine/eiface.h: +// ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138 +#define ENGINE_INTERFACE_VERSION 138 + +// Protect against other projects which use this include file but use the +// normal enginefuncs_t type for their meta_engfuncs. +#ifdef METAMOD_CORE +extern enginefuncs_t g_meta_engfuncs; + +void compile_engine_callbacks(); +#else + extern enginefuncs_t meta_engfuncs; +#endif diff --git a/dep/metamod/enginecallbacks.h b/dep/metamod/enginecallbacks.h new file mode 100644 index 0000000..db1536a --- /dev/null +++ b/dep/metamod/enginecallbacks.h @@ -0,0 +1,24 @@ +#pragma once + +// This file is a wrapper around the SDK's enginecallback.h file. We need +// this because we use a different type for the global object g_engfuncs, +// which is still compatible with the enginefuncs_t that the SDK +// uses. +// This is only done for files that belong to Metamod, not other projects +// like plugins that use this file, or others that include it, too. +// Since we don't have a clean seperation of include files right now we +// "hack" our way around that by using a flag METAMOD_CORE which is set +// when compiling Metamod proper. + +#include // ALERT, etc + +// Also, create some additional macros for engine callback functions, which +// weren't in SDK dlls/enginecallbacks.h but probably should have been. +#define GET_INFOKEYBUFFER (*g_engfuncs.pfnGetInfoKeyBuffer) +#define INFOKEY_VALUE (*g_engfuncs.pfnInfoKeyValue) +#define SET_CLIENT_KEYVALUE (*g_engfuncs.pfnSetClientKeyValue) +#define REG_SVR_COMMAND (*g_engfuncs.pfnAddServerCommand) +#define SERVER_PRINT (*g_engfuncs.pfnServerPrint) +#define SET_SERVER_KEYVALUE (*g_engfuncs.pfnSetKeyValue) +#define QUERY_CLIENT_CVAR_VALUE (*g_engfuncs.pfnQueryClientCvarValue) +#define QUERY_CLIENT_CVAR_VALUE2 (*g_engfuncs.pfnQueryClientCvarValue2) diff --git a/dep/metamod/h_export.h b/dep/metamod/h_export.h new file mode 100644 index 0000000..9f95777 --- /dev/null +++ b/dep/metamod/h_export.h @@ -0,0 +1,5 @@ +#pragma once + +// Our GiveFnptrsToDll, called by engine. +typedef void (WINAPI *GIVE_ENGINE_FUNCTIONS_FN)(enginefuncs_t* pengfuncsFromEngine, globalvars_t* pGlobals); +C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t* pengfuncsFromEngine, globalvars_t* pGlobals); diff --git a/dep/metamod/meta_api.h b/dep/metamod/meta_api.h new file mode 100644 index 0000000..78de915 --- /dev/null +++ b/dep/metamod/meta_api.h @@ -0,0 +1,189 @@ +#pragma once + +#include "dllapi.h" // GETENTITYAPI_FN, etc +#include "engine_api.h" // GET_ENGINE_FUNCTIONS_FN, etc +#include "enginecallbacks.h" +#include "h_export.h" +#include "plinfo.h" // plugin_info_t, etc +#include "mutil.h" + +// Version consists of "major:minor", two separate integer numbers. +// Version 1 original +// Version 2 added plugin_info_t **pinfo +// Version 3 init split into query and attach, added detach +// Version 4 added (PLUG_LOADTIME now) to attach +// Version 5 changed mm ifvers int* to string, moved pl ifvers to info +// Version 5:1 added link support for entity "adminmod_timer" (adminmod) +// Version 5:2 added gamedll_funcs to meta_attach() [v1.0-rc2] +// Version 5:3 added mutil_funcs to meta_query() [v1.05] +// Version 5:4 added centersay utility functions [v1.06] +// Version 5:5 added Meta_Init to plugin API [v1.08] +// Version 5:6 added CallGameEntity utility function [v1.09] +// Version 5:7 added GetUserMsgID, GetUserMsgName util funcs [v1.11] +// Version 5:8 added GetPluginPath [v1.11] +// Version 5:9 added GetGameInfo [v1.14] +// Version 5:10 added GINFO_REALDLL_FULLPATH for GetGameInfo [v1.17] +// Version 5:11 added plugin loading and unloading API [v1.18] +// Version 5:12 added IS_QUERYING_CLIENT_CVAR to mutils [v1.18] +// Version 5:13 added MAKE_REQUESTID and GET_HOOK_TABLES to mutils [v1.19] +#define META_INTERFACE_VERSION "5:13" + +// Flags returned by a plugin's api function. +// NOTE: order is crucial, as greater/less comparisons are made. +enum META_RES +{ + MRES_UNSET = 0, + MRES_IGNORED, // plugin didn't take any action + MRES_HANDLED, // plugin did something, but real function should still be called + MRES_OVERRIDE, // call real function, but use my return value + MRES_SUPERCEDE, // skip real function; use my return value +}; + +// Variables provided to plugins. +struct meta_globals_t +{ + META_RES mres; // writable; plugin's return flag + META_RES prev_mres; // readable; return flag of the previous plugin called + META_RES status; // readable; "highest" return flag so far + void *orig_ret; // readable; return value from "real" function + void *override_ret; // readable; return value from overriding/superceding plugin + +#ifdef METAMOD_CORE + uint32* esp_save; +#endif +}; + +extern meta_globals_t *gpMetaGlobals; +#define SET_META_RESULT(result) gpMetaGlobals->mres = result + +#define RETURN_META(result) \ + do { gpMetaGlobals->mres = result; return; } while (0) + +#define RETURN_META_VALUE(result, value) \ + do { gpMetaGlobals->mres = result; return value; } while (0) + +#define META_RESULT_STATUS gpMetaGlobals->status +#define META_RESULT_PREVIOUS gpMetaGlobals->prev_mres +#define META_RESULT_ORIG_RET(type) *(type *)gpMetaGlobals->orig_ret +#define META_RESULT_OVERRIDE_RET(type) *(type *)gpMetaGlobals->override_ret + +// Table of getapi functions, retrieved from each plugin. +struct META_FUNCTIONS +{ + GETENTITYAPI_FN pfnGetEntityAPI; + GETENTITYAPI_FN pfnGetEntityAPI_Post; + GETENTITYAPI2_FN pfnGetEntityAPI2; + GETENTITYAPI2_FN pfnGetEntityAPI2_Post; + GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions; + GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions_Post; + GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions; + GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions_Post; +}; + +// Pair of function tables provided by game DLL. +struct gamedll_funcs_t +{ + DLL_FUNCTIONS *dllapi_table; + NEW_DLL_FUNCTIONS *newapi_table; +}; + +// Declared in plugin; referenced in macros. +extern gamedll_funcs_t *gpGamedllFuncs; +extern mutil_funcs_t *gpMetaUtilFuncs; + +// Tell the dll that we'll be loading it as a metamod plugin, in case it +// needs to do something special prior to the standard query/attach +// procedure. In particular, this will allow for DLL's that can be used as +// both standalone DLL's and metamod plugins. (optional; not required in +// plugin) +C_DLLEXPORT void Meta_Init(); +typedef void (*META_INIT_FN)(); + +// Get info about plugin, compare meta_interface versions, provide meta +// utility callback functions. +C_DLLEXPORT int Meta_Query(char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs); +typedef int (*META_QUERY_FN) (char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs); + +// Attach the plugin to the API; get the table of getapi functions; give +// meta_globals and gamedll_funcs. +C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs); +typedef int (*META_ATTACH_FN) (PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs); + +// Detach the plugin; tell why and when. +C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); +typedef int (*META_DETACH_FN) (PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + +// Standard HL SDK interface function prototypes. +C_DLLEXPORT int GetEntityAPI_Post(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion ); +C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion ); + +// Additional SDK-like interface function prototypes. +C_DLLEXPORT int GetNewDLLFunctions_Post(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion ); +C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion); +C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion); + +// Convenience macros for accessing GameDLL functions. Note: these talk +// _directly_ to the gamedll, and are not multiplexed through Metamod to +// the other plugins. + +// DLL API functions: +#define MDLL_FUNC gpGamedllFuncs->dllapi_table + +#define MDLL_GameDLLInit MDLL_FUNC->pfnGameInit +#define MDLL_Spawn MDLL_FUNC->pfnSpawn +#define MDLL_Think MDLL_FUNC->pfnThink +#define MDLL_Use MDLL_FUNC->pfnUse +#define MDLL_Touch MDLL_FUNC->pfnTouch +#define MDLL_Blocked MDLL_FUNC->pfnBlocked +#define MDLL_KeyValue MDLL_FUNC->pfnKeyValue +#define MDLL_Save MDLL_FUNC->pfnSave +#define MDLL_Restore MDLL_FUNC->pfnRestore +#define MDLL_ObjectCollsionBox MDLL_FUNC->pfnAbsBox +#define MDLL_SaveWriteFields MDLL_FUNC->pfnSaveWriteFields +#define MDLL_SaveReadFields MDLL_FUNC->pfnSaveReadFields +#define MDLL_SaveGlobalState MDLL_FUNC->pfnSaveGlobalState +#define MDLL_RestoreGlobalState MDLL_FUNC->pfnRestoreGlobalState +#define MDLL_ResetGlobalState MDLL_FUNC->pfnResetGlobalState +#define MDLL_ClientConnect MDLL_FUNC->pfnClientConnect +#define MDLL_ClientDisconnect MDLL_FUNC->pfnClientDisconnect +#define MDLL_ClientKill MDLL_FUNC->pfnClientKill +#define MDLL_ClientPutInServer MDLL_FUNC->pfnClientPutInServer +#define MDLL_ClientCommand MDLL_FUNC->pfnClientCommand +#define MDLL_ClientUserInfoChanged MDLL_FUNC->pfnClientUserInfoChanged +#define MDLL_ServerActivate MDLL_FUNC->pfnServerActivate +#define MDLL_ServerDeactivate MDLL_FUNC->pfnServerDeactivate +#define MDLL_PlayerPreThink MDLL_FUNC->pfnPlayerPreThink +#define MDLL_PlayerPostThink MDLL_FUNC->pfnPlayerPostThink +#define MDLL_StartFrame MDLL_FUNC->pfnStartFrame +#define MDLL_ParmsNewLevel MDLL_FUNC->pfnParmsNewLevel +#define MDLL_ParmsChangeLevel MDLL_FUNC->pfnParmsChangeLevel +#define MDLL_GetGameDescription MDLL_FUNC->pfnGetGameDescription +#define MDLL_PlayerCustomization MDLL_FUNC->pfnPlayerCustomization +#define MDLL_SpectatorConnect MDLL_FUNC->pfnSpectatorConnect +#define MDLL_SpectatorDisconnect MDLL_FUNC->pfnSpectatorDisconnect +#define MDLL_SpectatorThink MDLL_FUNC->pfnSpectatorThink +#define MDLL_Sys_Error MDLL_FUNC->pfnSys_Error +#define MDLL_PM_Move MDLL_FUNC->pfnPM_Move +#define MDLL_PM_Init MDLL_FUNC->pfnPM_Init +#define MDLL_PM_FindTextureType MDLL_FUNC->pfnPM_FindTextureType +#define MDLL_SetupVisibility MDLL_FUNC->pfnSetupVisibility +#define MDLL_UpdateClientData MDLL_FUNC->pfnUpdateClientData +#define MDLL_AddToFullPack MDLL_FUNC->pfnAddToFullPack +#define MDLL_CreateBaseline MDLL_FUNC->pfnCreateBaseline +#define MDLL_RegisterEncoders MDLL_FUNC->pfnRegisterEncoders +#define MDLL_GetWeaponData MDLL_FUNC->pfnGetWeaponData +#define MDLL_CmdStart MDLL_FUNC->pfnCmdStart +#define MDLL_CmdEnd MDLL_FUNC->pfnCmdEnd +#define MDLL_ConnectionlessPacket MDLL_FUNC->pfnConnectionlessPacket +#define MDLL_GetHullBounds MDLL_FUNC->pfnGetHullBounds +#define MDLL_CreateInstancedBaselines MDLL_FUNC->pfnCreateInstancedBaselines +#define MDLL_InconsistentFile MDLL_FUNC->pfnInconsistentFile +#define MDLL_AllowLagCompensation MDLL_FUNC->pfnAllowLagCompensation + +// NEW API functions: +#define MNEW_FUNC gpGamedllFuncs->newapi_table + +#define MNEW_OnFreeEntPrivateData MNEW_FUNC->pfnOnFreeEntPrivateData +#define MNEW_GameShutdown MNEW_FUNC->pfnGameShutdown +#define MNEW_ShouldCollide MNEW_FUNC->pfnShouldCollide +#define MNEW_CvarValue MNEW_FUNC->pfnCvarValue diff --git a/dep/metamod/mutil.h b/dep/metamod/mutil.h new file mode 100644 index 0000000..449c257 --- /dev/null +++ b/dep/metamod/mutil.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include "plinfo.h" + +// For GetGameInfo: +enum ginfo_t +{ + GINFO_NAME = 0, + GINFO_DESC, + GINFO_GAMEDIR, + GINFO_DLL_FULLPATH, + GINFO_DLL_FILENAME, + GINFO_REALDLL_FULLPATH, +}; + +// Meta Utility Function table type. +struct mutil_funcs_t +{ + void (*pfnLogConsole) (plid_t plid, const char *fmt, ...); + void (*pfnLogMessage) (plid_t plid, const char *fmt, ...); + void (*pfnLogError) (plid_t plid, const char *fmt, ...); + void (*pfnLogDeveloper) (plid_t plid, const char *fmt, ...); + void (*pfnCenterSay) (plid_t plid, const char *fmt, ...); + void (*pfnCenterSayParms) (plid_t plid, hudtextparms_t tparms, const char *fmt, ...); + void (*pfnCenterSayVarargs) (plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap); + qboolean (*pfnCallGameEntity) (plid_t plid, const char *entStr, entvars_t *pev); + int (*pfnGetUserMsgID) (plid_t plid, const char *msgname, int *size); + const char* (*pfnGetUserMsgName) (plid_t plid, int msgid, int *size); + const char* (*pfnGetPluginPath) (plid_t plid); + const char* (*pfnGetGameInfo) (plid_t plid, ginfo_t tag); + int (*pfnLoadPlugin) (plid_t plid, const char *cmdline, PLUG_LOADTIME now, void **plugin_handle); + int (*pfnUnloadPlugin) (plid_t plid, const char *cmdline, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + int (*pfnUnloadPluginByHandle)(plid_t plid, void *plugin_handle, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + const char* (*pfnIsQueryingClientCvar)(plid_t plid, const edict_t *pEdict); + int (*pfnMakeRequestId) (plid_t plid); + void (*pfnGetHookTables) (plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); +}; + +extern mutil_funcs_t g_MetaUtilFunctions; + +// Meta Utility Functions +void mutil_LogConsole(plid_t plid, const char *fmt, ...); +void mutil_LogMessage(plid_t plid, const char *fmt, ...); +void mutil_LogError(plid_t plid, const char *fmt, ...); +void mutil_LogDeveloper(plid_t plid, const char *fmt, ...); + +void mutil_CenterSay(plid_t plid, const char *fmt, ...); +void mutil_CenterSayParms(plid_t plid, hudtextparms_t tparms, const char *fmt, ...); +void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap); + +qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev); + +int mutil_GetUserMsgID(plid_t plid, const char *name, int *size); +const char *mutil_GetUserMsgName(plid_t plid, int msgid, int *size); +const char *mutil_GetPluginPath(plid_t plid); +const char *mutil_GetGameInfo(plid_t plid, ginfo_t tag); +const char *mutil_IsQueryingClientCvar(plid_t plid, const edict_t *pEdict); +int mutil_MakeRequestId(plid_t plid); +void mutil_GetHookTables(plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); + +// Convenience macros for MetaUtil functions +#define LOG_CONSOLE (*gpMetaUtilFuncs->pfnLogConsole) +#define LOG_MESSAGE (*gpMetaUtilFuncs->pfnLogMessage) +#define LOG_ERROR (*gpMetaUtilFuncs->pfnLogError) +#define LOG_DEVELOPER (*gpMetaUtilFuncs->pfnLogDeveloper) +#define CENTER_SAY (*gpMetaUtilFuncs->pfnCenterSay) +#define CENTER_SAY_PARMS (*gpMetaUtilFuncs->pfnCenterSayParms) +#define CENTER_SAY_VARARGS (*gpMetaUtilFuncs->pfnCenterSayVarargs) +#define CALL_GAME_ENTITY (*gpMetaUtilFuncs->pfnCallGameEntity) +#define GET_USER_MSG_ID (*gpMetaUtilFuncs->pfnGetUserMsgID) +#define GET_USER_MSG_NAME (*gpMetaUtilFuncs->pfnGetUserMsgName) +#define GET_PLUGIN_PATH (*gpMetaUtilFuncs->pfnGetPluginPath) +#define GET_GAME_INFO (*gpMetaUtilFuncs->pfnGetGameInfo) +#define LOAD_PLUGIN (*gpMetaUtilFuncs->pfnLoadPlugin) +#define UNLOAD_PLUGIN (*gpMetaUtilFuncs->pfnUnloadPlugin) +#define UNLOAD_PLUGIN_BY_HANDLE (*gpMetaUtilFuncs->pfnUnloadPluginByHandle) +#define IS_QUERYING_CLIENT_CVAR (*gpMetaUtilFuncs->pfnIsQueryingClientCvar) +#define MAKE_REQUESTID (*gpMetaUtilFuncs->pfnMakeRequestId) +#define GET_HOOK_TABLES (*gpMetaUtilFuncs->pfnGetHookTables) diff --git a/dep/metamod/plinfo.h b/dep/metamod/plinfo.h new file mode 100644 index 0000000..2fb30b0 --- /dev/null +++ b/dep/metamod/plinfo.h @@ -0,0 +1,48 @@ +#pragma once + +// Flags for plugin to indicate when it can be be loaded/unloaded. +// NOTE: order is crucial, as greater/less comparisons are made. +enum PLUG_LOADTIME +{ + PT_NEVER, + PT_STARTUP, // should only be loaded/unloaded at initial hlds execution + PT_CHANGELEVEL, // can be loaded/unloaded between maps + PT_ANYTIME, // can be loaded/unloaded at any time + PT_ANYPAUSE, // can be loaded/unloaded at any time, and can be "paused" during a map +}; + +// Flags to indicate why the plugin is being unloaded. +enum PL_UNLOAD_REASON +{ + PNL_NULL, + PNL_INI_DELETED, // was deleted from plugins.ini + PNL_FILE_NEWER, // file on disk is newer than last load + PNL_COMMAND, // requested by server/console command + PNL_CMD_FORCED, // forced by server/console command + PNL_DELAYED, // delayed from previous request; can't tell origin + + // only used for 'real_reason' on MPlugin::unload() + PNL_PLUGIN, // requested by plugin function call + PNL_PLG_FORCED, // forced by plugin function call + PNL_RELOAD, // forced unload by reload() +}; + +// Information plugin provides about itself. +struct plugin_info_t +{ + const char* ifvers; // meta_interface version + const char* name; // full name of plugin + const char* version; // version + const char* date; // date + const char* author; // author name/email + const char* url; // URL + const char* logtag; // log message prefix (unused right now) + PLUG_LOADTIME loadable; // when loadable + PLUG_LOADTIME unloadable; // when unloadable +}; + +extern plugin_info_t Plugin_info; + +// Plugin identifier, passed to all Meta Utility Functions. +typedef plugin_info_t *plid_t; +#define PLID &Plugin_info diff --git a/dep/sys_module.cpp b/dep/sys_module.cpp new file mode 100644 index 0000000..ef3d1ad --- /dev/null +++ b/dep/sys_module.cpp @@ -0,0 +1,489 @@ +#include "precompiled.h" + +const size_t CSysModule::BASE_OFFSET = 0x01D00000; +const module_handle_t CSysModule::INVALID_HANDLE = (module_handle_t)0; + +CSysModule::CSysModule() : m_handle(INVALID_HANDLE), m_base(nullptr), m_size(0), m_free(true) +{ +} + +CSysModule::~CSysModule() +{ +} + +bool CSysModule::Init(const char *szModuleName, const char *pszFile) +{ + m_handle = GetModuleHandle(szModuleName); + + if (!m_handle) { + return false; + } + + MODULEINFO module_info; + if (GetModuleInformation(GetCurrentProcess(), m_handle, &module_info, sizeof(module_info))) + { + m_base = (byteptr_t)module_info.lpBaseOfDll; + m_size = module_info.SizeOfImage; + } + + m_debug.SetFile(pszFile); + return true; +} + +const char *CSysModule::getFileName() +{ + static char szFileName[MAX_PATH] = ""; + if (m_handle == INVALID_HANDLE) { + return ""; + } + + GetModuleFileName(m_handle, szFileName, sizeof(szFileName)); + return szFileName; +} + +void CSysModule::Printf(const char *fmt, ...) +{ + va_list argptr; + static char string[4096]; + + va_start(argptr, fmt); + Q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); + + m_debug.Printf("%s", string); +} + +void CSysModule::TraceLog(const char *fmt, ...) +{ + va_list argptr; + static char string[4096]; + + va_start(argptr, fmt); + Q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); + + m_debug.TraceLog("%s", string); +} + +module_handle_t CSysModule::load(void *addr) +{ + if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(addr), &m_handle)) { + return INVALID_HANDLE; + } + + MEMORY_BASIC_INFORMATION mem; + if (!VirtualQuery(m_handle, &mem, sizeof(mem))) + return INVALID_HANDLE; + + if (mem.State != MEM_COMMIT) + return INVALID_HANDLE; + + if (!mem.AllocationBase) + return INVALID_HANDLE; + + IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)mem.AllocationBase; + IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS *)((uintptr_t)dos + (uintptr_t)dos->e_lfanew); + + if (pe->Signature != IMAGE_NT_SIGNATURE) + return INVALID_HANDLE; + + m_free = false; + m_base = (byteptr_t)mem.AllocationBase; + m_size = (size_t)pe->OptionalHeader.SizeOfImage; + + return m_handle; +} + +module_handle_t CSysModule::find(void *addr) +{ + module_handle_t hHandle = INVALID_HANDLE; + if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(addr), &hHandle)) { + return INVALID_HANDLE; + } + + return hHandle; +} + +module_handle_t CSysModule::load(const char *filepath) +{ + if (!m_handle) { + m_handle = LoadLibrary(filepath); + + MODULEINFO module_info; + if (GetModuleInformation(GetCurrentProcess(), m_handle, &module_info, sizeof(module_info))) { + m_base = (byteptr_t)module_info.lpBaseOfDll; + m_size = module_info.SizeOfImage; + } + } + + return m_handle; +} + +bool CSysModule::unload() +{ + if (m_handle == INVALID_HANDLE) { + return false; + } + + bool ret = true; + if (m_free) { + ret = FreeLibrary(m_handle) != ERROR; + } + + m_handle = INVALID_HANDLE; + m_base = 0; + m_size = 0; + + return ret; +} + +bool CSysModule::is_opened() const +{ + return m_handle != INVALID_HANDLE; +} + +byteptr_t CSysModule::find_pattern(byteptr_t pStart, size_t range, const char *pattern) const +{ + return m_pattern.find(pStart, range, (byteptr_t)pattern, Q_strlen(pattern)); +} + +byteptr_t CSysModule::find_pattern_back(byteptr_t pStart, size_t range, const char *pattern) const +{ + return m_pattern.find_back(pStart, range, (byteptr_t)pattern, Q_strlen(pattern)); +} + +byteptr_t CSysModule::find_string(const char *string, int8_t opcode) const +{ + auto ptr = m_pattern.find(m_base, m_size, (byteptr_t)string, Q_strlen(string) + 1); + if (!ptr) { + return nullptr; + } + + return m_pattern.find_ref(m_base, m_base + m_size - 5, (uint32_t)ptr, opcode); +} + +byteptr_t CSysModule::getsym(const char *name) const +{ + return m_handle ? (byteptr_t)GetProcAddress(m_handle, name) : nullptr; +} + +module_handle_t CSysModule::gethandle() const +{ + return m_handle; +} + +byteptr_t CSysModule::getbase() const +{ + return m_base; +} + +size_t CSysModule::getsize() const +{ + return m_size; +} + +const char *CSysModule::getloaderror() +{ +#ifdef _WIN32 + static char buf[1024]; + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buf, sizeof(buf) - 1, nullptr); + return buf; +#else + return dlerror(); +#endif +} + +bool CSysModule::CPattern::compare(byteptr_t pStart, const byteptr_t pattern, size_t len) const +{ + for (auto c = pattern, pattern_end = pattern + len; c < pattern_end; c++, pStart++) + { + if (*c == *pStart || *c == OP_ANY) { + continue; + } + + return false; + } + + return true; +} + +byteptr_t CSysModule::CPattern::find(byteptr_t pStart, size_t range, const byteptr_t pattern, size_t len) const +{ + for (auto c = pStart + range - len; pStart < c; pStart++) { + if (compare(pStart, pattern, len)) + return pStart; + } + + return nullptr; +} + +byteptr_t CSysModule::CPattern::find_back(byteptr_t pStart, size_t range, const byteptr_t pattern, size_t len) const +{ + for (auto c = pStart - range - len; pStart > c; pStart--) { + if (compare(pStart, pattern, len)) + return pStart; + } + + return nullptr; +} + +byteptr_t CSysModule::CPattern::find_ref(byteptr_t pStart, byteptr_t pEnd, uint32_t ref, int8_t opcode, bool relative) const +{ + for (; pStart < pEnd; pStart++) + { + if (opcode != OP_ANY && *pStart != opcode) { + continue; + } + + if (relative) + { + if ((uint32_t)pStart + 5 + *(uint32_t *)(pStart + 1) == ref) + return pStart; + } + else + { + if (*(uint32_t *)(pStart + 1) == ref) + return pStart; + } + } + + return nullptr; +} + +byteptr_t CSysModule::CPattern::find_ref_back(byteptr_t pStart, byteptr_t pBase, uint32_t ref, int8_t opcode, bool relative) const +{ + for (; pStart > pBase; pStart--) + { + if (opcode != OP_ANY && *pStart != opcode) { + continue; + } + + if (relative) + { + if ((uint32_t)pStart + 5 + *(uint32_t *)(pStart + 1) == ref) + return pStart; + } + else + { + if (*(uint32_t *)(pStart + 1) == ref) + return pStart; + } + } + + return nullptr; +} + +bool CSysModule::SetHook(byteptr_t addr, hook_t *hook) +{ + if (!addr) + { + return false; + } + + hook->SetFunc(addr); + + // copy original bytes + Q_memcpy(hook->m_originalBytes, addr, sizeof(hook->m_originalBytes)); + + // make patch + return patch(addr, &hook->m_jmpBytes, sizeof(hook->m_jmpBytes)); +} + +bool CSysModule::set(hook_t *hook) +{ + if (!hook->m_addr) + return false; + + return patch(hook->m_addr, &hook->m_jmpBytes, hook->m_size); +} + +bool CSysModule::unset(hook_t *hook) +{ + if (!hook->m_addr) + return false; + + return patch(hook->m_addr, hook->m_originalBytes, hook->m_size); +} + +bool CSysModule::patch(void *dst, void *src, size_t size) +{ + static HANDLE process = 0; + + DWORD OldProtection = 0; + DWORD NewProtection = PAGE_EXECUTE_READWRITE; + + if (!process) + process = GetCurrentProcess(); + + auto ret = false; + if (VirtualProtect(dst, size, NewProtection, &OldProtection)) + { + Q_memcpy(dst, src, size); + ret = !!VirtualProtect(dst, size, OldProtection, &NewProtection); + } + + FlushInstructionCache(process, dst, size); + return ret; +} + +// Prints assembler code in the runtime like IDA Pro +// but not all opcodes can correctly to handle +void CSysModule::StartDumpBytes(byteptr_t pStart, size_t range) +{ + m_debug.TraceLog(" -> START DUMP: (%p)\n", pStart); + + size_t nPos; + for (nPos = 0; nPos < range; nPos++) { + pStart += dumpBytes(pStart, true); + } + + m_debug.TraceLog(" -> END DUMP: (%p), pos: (%d)\n", pStart, nPos); +} + +size_t CSysModule::dumpBytes(byteptr_t pStart, bool collect_nopBytes) const +{ + static bool prevNopBytes = false; + byteptr_t pBytes = pStart; + + // print address + if (!prevNopBytes || pBytes[0] != 0x90) + { + m_debug.TraceLog("%s0%X: ", prevNopBytes ? "\n" : "", (pStart - m_base + BASE_OFFSET)); + prevNopBytes = false; + } + + int iNumBytesOnLines = 1; + switch (pBytes[0]) + { + case 0x68: // push + iNumBytesOnLines = 5; + break; + + case 0xE8: // call + case 0xE9: // jmp + case 0xEB: // jmp + case 0xB8: // mov + case 0xBF: // mov + case 0xA2: // mov + iNumBytesOnLines = 5; + break; + + case 0x8D: // lea + case 0x81: // cmp + case 0xD8: // fcomp + case 0xD9: // fld + case 0x0F: // jnz + iNumBytesOnLines = 6; + break; + + case 0xC6: // mov + iNumBytesOnLines = 7; + break; + + case 0x75: // jnz + case 0x72: // jb + case 0x84: // test + case 0xDF: // fnstsw + case 0x7A: // jp + iNumBytesOnLines = 2; + break; + + case 0x8B: // mov + { + if (pBytes[1] == 0x5D) + { + iNumBytesOnLines = 3; + break; + } + else if (pBytes[1] == 0x35) + { + iNumBytesOnLines = 6; + break; + } + + iNumBytesOnLines = 2; + break; + } + case 0x33: // xor + case 0x83: // add + case 0xF6: // test + iNumBytesOnLines = 3; + break; + + case 0x90: + if (!collect_nopBytes) + { + iNumBytesOnLines = 1; + break; + } + + m_debug.TraceLog(" 90"); + prevNopBytes = true; + return 1; + + default: + iNumBytesOnLines = 1; + break; + } + + for (int i = 0; i < iNumBytesOnLines; i++) + { + //m_pattern.find(nullptr, 0, nullptr, 1); + + m_debug.Printf(""); + + m_debug.TraceLog(" %s%X", (pBytes[i] <= 0x0A) ? "0" : "", pBytes[i]); + } + + if (!prevNopBytes) + { + m_debug.TraceLog("\n"); + } + + return iNumBytesOnLines; +} + +CSysModule::CMemDebug::CMemDebug() +{ + m_DebugFile[0] = '\0'; +} + +void CSysModule::CMemDebug::SetFile(const char *pszFileName) +{ + Q_strlcpy(m_DebugFile, pszFileName); +} + +void CSysModule::CMemDebug::TraceLog(const char *fmt, ...) const +{ + va_list argptr; + static char string[4096]; + + va_start(argptr, fmt); + Q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); + + if (m_DebugFile[0] == '\0') { + Printf(string); + return; + } + + FILE *fp = fopen(m_DebugFile, "a+"); + if (!fp) { + return; + } + + fprintf(fp, "%s", string); + fclose(fp); +} + +void CSysModule::CMemDebug::Printf(const char *fmt, ...) const +{ + va_list argptr; + static char string[4096]; + + va_start(argptr, fmt); + Q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); + + printf("%s", string); +} diff --git a/dep/sys_module.h b/dep/sys_module.h new file mode 100644 index 0000000..2647ab2 --- /dev/null +++ b/dep/sys_module.h @@ -0,0 +1,181 @@ +#pragma once + +#include + +#define ResolveFunc(addr, func)\ + (void *)((size_t)func - (size_t)addr - 5) + +#pragma pack(push, 1) +struct jmp_t +{ + char _jmp; + void *addr; +}; +#pragma pack(pop) + +constexpr size_t MAX_JUMP_SIZE = sizeof(jmp_t); + +struct hook_t +{ + hook_t(int8_t opcode, void *handler) + { + m_addr = nullptr; + m_handler = handler; + + m_jmpBytes._jmp = opcode; + m_jmpBytes.addr = nullptr; + + memset(&m_originalBytes, 0, sizeof(m_originalBytes)); + } + + void SetFunc(byteptr_t addr) + { + if (m_handler) + { + m_addr = addr; + m_jmpBytes.addr = ResolveFunc(addr, m_handler); + } + } + + void *m_addr; + void *m_handler; + size_t m_size; + jmp_t m_jmpBytes; + byte m_originalBytes[MAX_JUMP_SIZE]; +}; + +class CSysModule: virtual public ISysModule +{ +public: + CSysModule(); + ~CSysModule(); + + bool Init(const char *szModuleName, const char *pszFile = nullptr); + + module_handle_t load(void *addr); + module_handle_t load(const char *filename); + bool unload(); + + void Printf(const char *fmt, ...); + void TraceLog(const char *fmt, ...); + + byteptr_t getsym(const char *name) const; + module_handle_t gethandle() const; + byteptr_t getbase() const; + size_t getsize() const; + bool is_opened() const; + const char *getFileName(); + + bool set(hook_t *hook); + bool unset(hook_t *hook); + bool patch(void *dst, void *src, size_t size); + + bool SetHook(byteptr_t addr, hook_t *hook); + + template + size_t GetFunc(byteptr_t addr, TMethod *(*method) = nullptr); + + template + size_t GetFunc(byteptr_t addr, TMethod *(T::*method) = nullptr); + + template + byteptr_t find_pattern(const char (&pattern)[size]) const; + + template + byteptr_t find_pattern(byteptr_t pStart, const char (&pattern)[size]) const; + + template + byteptr_t find_pattern_back(byteptr_t pStart, const char (&pattern)[size]) const; + + byteptr_t find_pattern(byteptr_t pStart, size_t range, const char *pattern) const; + byteptr_t find_pattern_back(byteptr_t pStart, size_t range, const char *pattern) const; + byteptr_t find_string(const char *string, int8_t opcode = OP_ANY) const; + + void StartDumpBytes(byteptr_t pStart, size_t range); + + static module_handle_t find(void *addr); + static const char *getloaderror(); + static const module_handle_t INVALID_HANDLE; + static const size_t BASE_OFFSET; + +private: + module_handle_t m_handle; + +protected: + size_t dumpBytes(byteptr_t pStart, bool collect_nopBytes = true) const; + + class CPattern + { + public: + byteptr_t find(byteptr_t pStart, size_t range, byteptr_t pattern, size_t len) const; + byteptr_t find_ref(byteptr_t pStart, byteptr_t pEnd, uint32_t ref, int8_t opcode = OP_ANY, bool relative = false) const; + + byteptr_t find_back(byteptr_t pStart, size_t range, byteptr_t pattern, size_t len) const; + byteptr_t find_ref_back(byteptr_t pStart, byteptr_t pBase, uint32_t ref, int8_t opcode = OP_ANY, bool relative = false) const; + + bool compare(byteptr_t pStart, const byteptr_t pattern, size_t len) const; + }; + + class CMemDebug + { + public: + CMemDebug(); + + void SetFile (const char *pszFileName); + void TraceLog(const char *fmt, ...) const; + void Printf (const char *fmt, ...) const; + + protected: + friend class CSysModule; + char m_DebugFile[MAX_PATH]; + }; + +protected: + CMemDebug m_debug; + CPattern m_pattern; + byteptr_t m_base; + size_t m_size; + bool m_free; // m_handle should be released +}; + +template +byteptr_t CSysModule::find_pattern(byteptr_t pStart, const char (&pattern)[size]) const +{ + return m_pattern.find(pStart, m_size, (byteptr_t)pattern, size - 1); +} + +template +byteptr_t CSysModule::find_pattern_back(byteptr_t pStart, const char (&pattern)[size]) const +{ + return m_pattern.find_back(pStart, m_size, (byteptr_t)pattern, size - 1); +} + +template +byteptr_t CSysModule::find_pattern(const char (&pattern)[size]) const +{ + return m_pattern.find(m_base, m_size, (byteptr_t)pattern, size - 1); +} + +template +size_t CSysModule::GetFunc(byteptr_t addr, TMethod *(*method)) +{ + auto ptr = (size_t)addr + *(size_t *)(addr + 1) + 5; + if (method) + { + *method = reinterpret_cast(ptr); + } + + return ptr; +} + +template +size_t CSysModule::GetFunc(byteptr_t addr, TMethod *(T::*method)) +{ + auto ptr = (size_t)addr + *(size_t *)(addr + 1) + 5; + if (method) + { + *method = reinterpret_cast(ptr); + } + + return ptr; +} \ No newline at end of file diff --git a/hitboxtracker/client/msvc/client.vcxproj b/hitboxtracker/client/msvc/client.vcxproj new file mode 100644 index 0000000..aa50c5d --- /dev/null +++ b/hitboxtracker/client/msvc/client.vcxproj @@ -0,0 +1,253 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {0635BDCF-8622-4483-BEAE-0646D8184654} + Win32Proj + DrawHitBox + 8.1 + + + + DynamicLibrary + true + v140 + MultiByte + + + DynamicLibrary + false + v140 + true + MultiByte + + + + + + + + + + + + + + + true + .dll + hitboxtracker + + + false + .dll + hitboxtracker + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\dlls;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\game_shared;$(ProjectDir)..\..\..\dep\hlsdk\pm_shared;$(ProjectDir)..\..\..\dep\hlsdk\public;$(ProjectDir)..\..\..\dep;$(ProjectDir)..\src;%(AdditionalIncludeDirectories) + precompiled.h + + + Windows + true + psapi.lib;%(AdditionalDependencies) + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + + + Force build to run Pre-Build event + build.always.run + build.always.run + + + + + Level3 + Use + MinSpace + true + true + WIN32;NDEBUG;_WINDOWS;USE_QSTRING;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\dlls;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\game_shared;$(ProjectDir)..\..\..\dep\hlsdk\pm_shared;$(ProjectDir)..\..\..\dep\hlsdk\public;$(ProjectDir)..\..\..\dep;$(ProjectDir)..\src;%(AdditionalIncludeDirectories) + precompiled.h + true + NoExtensions + + + Windows + true + true + true + psapi.lib;%(AdditionalDependencies) + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + + + Force build to run Pre-Build event + build.always.run + build.always.run + + + + + + + + + + + + + + + Use + precompiled.h + Use + precompiled.h + + + + Use + precompiled.h + Use + precompiled.h + + + + + Create + precompiled.h + Create + precompiled.h + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hitboxtracker/client/msvc/client.vcxproj.filters b/hitboxtracker/client/msvc/client.vcxproj.filters new file mode 100644 index 0000000..5767b22 --- /dev/null +++ b/hitboxtracker/client/msvc/client.vcxproj.filters @@ -0,0 +1,360 @@ + + + + + {cb05ca5a-94d8-4be6-9598-5e9c882c08b6} + + + {71b828b1-d7d5-4adf-b47c-7bc585bba060} + + + {47ea399f-1dc0-47bb-801e-d09fb9249795} + + + {f5f66008-df2d-4345-9d8f-bbef2a67994c} + + + {c9ed0f09-0d6d-4d4b-84a1-0341a518ea2c} + + + {4552757d-fc3b-472a-bb65-8fd277268439} + + + {f00fbba2-4fcf-466a-a1e4-4430deb33ddd} + + + {6001fbc3-e98a-442b-8e9b-29970869a2b2} + + + {258cd6d9-699d-4d0b-8991-0d6532c4d206} + + + + + src + + + src + + + src + + + hlsdk\common + + + src\studio + + + src\studio + + + src\studio + + + src + + + src + + + src + + + public + + + hlsdk\public + + + src\modules + + + src\modules + + + hlsdk\engine + + + hlsdk\public + + + + + src + + + src + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\dlls + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + src\studio + + + src\studio + + + src\studio + + + src + + + src + + + public + + + hlsdk\public + + + src\modules + + + src\modules + + + hlsdk\public + + + \ No newline at end of file diff --git a/hitboxtracker/client/src/cdll_int.cpp b/hitboxtracker/client/src/cdll_int.cpp new file mode 100644 index 0000000..275e2c5 --- /dev/null +++ b/hitboxtracker/client/src/cdll_int.cpp @@ -0,0 +1,91 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +float g_lastFOV; +bool g_bHoldingKnife; +bool g_bHoldingShield; + +int Initialize(cl_enginefunc_t *pEnginefuncs, int iVersion) +{ + g_pEngfuncs = pEnginefuncs; + Q_memcpy(&gEngfuncs, pEnginefuncs, sizeof(gEngfuncs)); + + g_pClientfuncs->pHudInitFunc = HUD_Init; + + return gClientfuncs.pInitFunc(pEnginefuncs, iVersion); +} + +void HUD_Init() +{ + g_pClientfuncs->pPostRunCmd = HUD_PostRunCmd; + g_pClientfuncs->pProcessPlayerState = HUD_ProcessPlayerState; + g_pClientfuncs->pStudioInterface = HUD_GetStudioModelInterface; + + gClientfuncs.pHudInitFunc(); + gHUD.Init(); +} + +void HUD_WeaponsPostThink(local_state_t *from, local_state_t *to, usercmd_t *cmd, double time, unsigned int random_seed) +{ + int flags = from->client.iuser3; + + g_bHoldingKnife = (from->client.m_iId == WEAPON_KNIFE); + g_bHoldingShield = (flags & PLAYER_HOLDING_SHIELD) != 0; +} + +void HUD_ProcessPlayerState(entity_state_t *dst, entity_state_t *src) +{ + // save current values of fields from server-side + auto &sync = g_PlayerSyncInfo[src->number]; + + sync.yaw = src->vuser1[0]; + sync.gaityaw = src->vuser1[1]; + sync.gaitframe = src->vuser1[2]; + + sync.gaitmovement = src->vuser2[0]; + sync.gaitsequence = src->vuser2[1]; + sync.pitch = src->vuser2[2]; + + sync.prevgaitorigin[0] = src->maxs[0]; + sync.prevgaitorigin[1] = src->maxs[1]; + sync.prevgaitorigin[2] = src->maxs[2]; + + sync.time = src->mins[0]; // m_clTime + sync.oldtime = src->mins[1]; // m_clOldTime + sync.frametime = src->mins[2]; // m_clTime - m_clOldTime? + + gClientfuncs.pProcessPlayerState(dst, src); +} + +void R_ForceCVars(qboolean multiplayer) +{ + // nothing to do here + // block +} diff --git a/hitboxtracker/client/src/cstrike_util.cpp b/hitboxtracker/client/src/cstrike_util.cpp new file mode 100644 index 0000000..1f76c1a --- /dev/null +++ b/hitboxtracker/client/src/cstrike_util.cpp @@ -0,0 +1,129 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +int g_runfuncs; +int g_rseq, g_gaitseq; +Vector g_clorg, g_clang; + +const char *sPlayerModelFiles[] = +{ + "models/player.mdl", + "models/player/leet/leet.mdl", + "models/player/gign/gign.mdl", + "models/player/vip/vip.mdl", + "models/player/gsg9/gsg9.mdl", + "models/player/guerilla/guerilla.mdl", + "models/player/arctic/arctic.mdl", + "models/player/sas/sas.mdl", + "models/player/terror/terror.mdl", + "models/player/urban/urban.mdl", + "models/player/spetsnaz/spetsnaz.mdl", // CZ + "models/player/militia/militia.mdl" // CZ +}; + +void HUD_PostRunCmd(local_state_t *from, local_state_t *to, usercmd_t *cmd, int runfuncs, double time, unsigned int random_seed) +{ + g_runfuncs = runfuncs; + gClientfuncs.pPostRunCmd(from, to, cmd, runfuncs, time, random_seed); + + if (to->client.fov != g_lastFOV) + { + g_lastFOV = to->client.fov; + } + + HUD_WeaponsPostThink(from, to, cmd, time, random_seed); + + if (runfuncs) + { + g_gaitseq = to->playerstate.gaitsequence; + g_rseq = to->playerstate.sequence; + + g_clorg = to->playerstate.origin; + g_clang = cmd->viewangles; + } +} + +void CounterStrike_GetSequence(int *seq, int *gaitseq) +{ + *seq = g_rseq; + *gaitseq = g_gaitseq; +} + +void CounterStrike_SetSequence(int seq, int gaitseq) +{ + g_rseq = seq; + g_gaitseq = gaitseq; +} + +void CounterStrike_SetOrientation(Vector *p_o, Vector *p_a) +{ + g_clorg = *p_o; + g_clang = *p_a; +} + +void CounterStrike_GetOrientation(float *o, float *a) +{ + *(Vector *)o = g_clorg; + *(Vector *)a = g_clang; +} + +bool IsValidCTModelIndex(int modelType) +{ + switch (static_cast(modelType)) + { + case CS_GIGN: + case CS_GSG9: + case CS_SAS: + case CS_URBAN: + case CS_SPETSNAZ: + return true; + default: + break; + } + + return false; +} + +bool IsValidTModelIndex(int modelType) +{ + switch (static_cast(modelType)) + { + case CS_LEET: + case CS_GUERILLA: + case CS_ARCTIC: + case CS_TERROR: + case CS_MILITIA: + return true; + default: + break; + } + + return false; +} diff --git a/hitboxtracker/client/src/cstrike_util.h b/hitboxtracker/client/src/cstrike_util.h new file mode 100644 index 0000000..b61e5b5 --- /dev/null +++ b/hitboxtracker/client/src/cstrike_util.h @@ -0,0 +1,55 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +enum ModelType_e +{ + CS_DEFAULT, + CS_LEET, + CS_GIGN, + CS_VIP, + CS_GSG9, + CS_GUERILLA, + CS_ARCTIC, + CS_SAS, + CS_TERROR, + CS_URBAN, + CS_SPETSNAZ, + CS_MILITIA, +}; + +bool IsValidCTModelIndex(int modelType); +bool IsValidTModelIndex(int modelType); + +void CounterStrike_GetSequence(int *seq, int *gaitseq); +void CounterStrike_SetSequence(int seq, int gaitseq); +void CounterStrike_SetOrientation(Vector *p_o, Vector *p_a); +void CounterStrike_GetOrientation(float *o, float *a); + +extern const char *sPlayerModelFiles[]; diff --git a/hitboxtracker/client/src/hud.cpp b/hitboxtracker/client/src/hud.cpp new file mode 100644 index 0000000..bc6b586 --- /dev/null +++ b/hitboxtracker/client/src/hud.cpp @@ -0,0 +1,154 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +CHud gHUD; + +cvar_t *cl_lw; +cvar_t *cl_min_t; +cvar_t *cl_min_ct; +cvar_t *cl_shadows; +cvar_t *cl_righthand; +cvar_t *cl_minmodels; + +cvar_t *default_fov; +cvar_t *sensitivity; + +player_sync_t g_PlayerSyncInfo [MAX_PLAYERS + 1]; +extra_player_info_t g_PlayerExtraInfo[MAX_PLAYERS + 1]; // additional player info sent directly to the client dll + +GHUD_DECLARE_MESSAGE(SetFOV) +GHUD_DECLARE_MESSAGE(ShadowIdx) +GHUD_DECLARE_MESSAGE(ResetHUD) + +CHud::CHud() : m_iFOV(0), + m_flMouseSensitivity(0), + m_Client(nullptr) +{ + +} + +bool CHud::Init() +{ + m_Client = new CClient(); + + if (!m_Client->Init("client.dll", "client.log")) { + return false; + } + + cl_lw = gEngfuncs.pfnGetCvarPointer("cl_lw"); + cl_min_t = gEngfuncs.pfnGetCvarPointer("cl_min_t"); + cl_min_ct = gEngfuncs.pfnGetCvarPointer("cl_min_ct"); + cl_shadows = gEngfuncs.pfnGetCvarPointer("cl_shadows"); + cl_righthand = gEngfuncs.pfnGetCvarPointer("cl_righthand"); + cl_minmodels = gEngfuncs.pfnGetCvarPointer("cl_minmodels"); + default_fov = gEngfuncs.pfnGetCvarPointer("default_fov"); + sensitivity = gEngfuncs.pfnGetCvarPointer("sensitivity"); + + HOOK_MESSAGE(SetFOV); + HOOK_MESSAGE(ShadowIdx); + HOOK_MESSAGE(ResetHUD); + + return true; +} + +void CHud::ShutDown() +{ + if (m_Client) { + delete m_Client; + m_Client = nullptr; + } +} + +int CHud::MsgFunc_SetFOV(const char *pszName, int iSize, void *pbuf) +{ + BEGIN_READ(pbuf, iSize); + + int newfov = READ_BYTE(); + int def_fov = default_fov->value; + + // Weapon prediction already takes care of changing the fog. (g_lastFOV). + //if (IsGame("tfc") && cl_lw && cl_lw->value) + // return 1; + + g_lastFOV = newfov; + + if (newfov == 0) + { + m_iFOV = def_fov; + } + else + { + m_iFOV = newfov; + } + + // the clients fov is actually set in the client data update section of the hud + + // Set a new sensitivity + if (m_iFOV == def_fov) + { + // reset to saved sensitivity + m_flMouseSensitivity = 0; + } + else + { + // set a new sensitivity that is proportional to the change from the FOV default + m_flMouseSensitivity = sensitivity->value * ((float)newfov / (float)def_fov) * gEngfuncs.pfnGetCvarFloat("zoom_sensitivity_ratio"); + } + + return g_ClientUserMsgsMap[pszName](pszName, iSize, pbuf); +} + +int CHud::MsgFunc_ShadowIdx(const char *pszName, int iSize, void *pbuf) +{ + BEGIN_READ(pbuf, iSize); + + int idx = READ_LONG(); + g_StudioRenderer.StudioSetShadowSprite(idx); + return g_ClientUserMsgsMap[pszName](pszName, iSize, pbuf); +} + +int CHud::MsgFunc_ResetHUD(const char *pszName, int iSize, void *pbuf) +{ + m_flMouseSensitivity = 0; + + return g_ClientUserMsgsMap[pszName](pszName, iSize, pbuf); +} + +bool CHud::IsGame(const char *game) const +{ + const char *gamedir = gEngfuncs.pfnGetGameDirectory(); + if (!gamedir || gamedir[0] == '\0') { + return false; + } + + char gd[1024]; + COM_FileBase(gamedir, gd); + return Q_stricmp(gd, game) == 0 ? true : false; +} diff --git a/hitboxtracker/client/src/hud.h b/hitboxtracker/client/src/hud.h new file mode 100644 index 0000000..81ff557 --- /dev/null +++ b/hitboxtracker/client/src/hud.h @@ -0,0 +1,126 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define g_PlayerExtraInfo (*pg_PlayerExtraInfo) + +enum +{ + MAX_PLAYERS = 64, + MAX_TEAMS = 64, + MAX_TEAM_NAME = 16, +}; + +struct player_sync_t +{ + float yaw; + float pitch; + float gaityaw; + float gaitframe; + float gaitmovement; + int gaitsequence; + float time; + float oldtime; + float frametime; + Vector prevgaitorigin; +}; + +struct extra_player_info_t +{ + short frags; + short deaths; + short team_id; + int has_c4; + int vip; + Vector origin; + float radarflash; + int radarflashon; + int radarflashes; + short playerclass; + short teamnumber; + char teamname[MAX_TEAM_NAME]; + bool dead; + float showhealth; + int health; + char location[32]; +}; + +// Macros to hook function calls into the HUD object +#define HOOK_MESSAGE(x) HookUserMsg(#x, __MsgFunc_##x) + +#define DECLARE_MESSAGE(y, x)\ +int __MsgFunc_##x(const char *pszName, int iSize, void *pbuf)\ +{\ + return gHUD.y.MsgFunc_##x(pszName, iSize, pbuf);\ +} + +#define GHUD_DECLARE_MESSAGE(x)\ +int __MsgFunc_##x(const char *pszName, int iSize, void *pbuf)\ +{\ + return gHUD.MsgFunc_##x(pszName, iSize, pbuf);\ +} + +#define DECLARE_MESSAGE_FUNC(x)\ +int MsgFunc_##x(const char *pszName, int iSize, void *buf); + +class CClient; +class CHud +{ +public: + CHud(); + + bool Init(); + void ShutDown(); + bool IsGame(const char *game) const; + +public: + DECLARE_MESSAGE_FUNC(SetFOV); + DECLARE_MESSAGE_FUNC(ShadowIdx); + DECLARE_MESSAGE_FUNC(ResetHUD); + + int m_iFOV; + float m_flMouseSensitivity; + +private: + CClient *m_Client; +}; + +extern CHud gHUD; + +extern player_sync_t g_PlayerSyncInfo [MAX_PLAYERS + 1]; +extern extra_player_info_t g_PlayerExtraInfo[MAX_PLAYERS + 1]; + +extern cvar_t *cl_lw; +extern cvar_t *cl_min_t; +extern cvar_t *cl_min_ct; +extern cvar_t *cl_shadows; +extern cvar_t *cl_righthand; +extern cvar_t *cl_minmodels; +extern cvar_t *default_fov; +extern cvar_t *sensitivity; diff --git a/hitboxtracker/client/src/main.cpp b/hitboxtracker/client/src/main.cpp new file mode 100644 index 0000000..b4c2321 --- /dev/null +++ b/hitboxtracker/client/src/main.cpp @@ -0,0 +1,125 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#define CLDLL_ENTRY(field, name) { offsetof(cldll_func_t, field), #name } +#define CLDLL_ENTRY_H(name) { #name, name } + +struct cldll_table_t +{ + size_t offset; + const char *name; +} g_cldllapi_info[] = +{ + CLDLL_ENTRY(pInitFunc, Initialize), + CLDLL_ENTRY(pHudInitFunc, HUD_Init), + CLDLL_ENTRY(pHudVidInitFunc, HUD_VidInit), + CLDLL_ENTRY(pHudRedrawFunc, HUD_Redraw), + CLDLL_ENTRY(pHudUpdateClientDataFunc, HUD_UpdateClientData), + CLDLL_ENTRY(pHudResetFunc, HUD_Reset), + CLDLL_ENTRY(pClientMove, HUD_PlayerMove), + CLDLL_ENTRY(pClientMoveInit, HUD_PlayerMoveInit), + CLDLL_ENTRY(pClientTextureType, HUD_PlayerMoveTexture), + CLDLL_ENTRY(pIN_ActivateMouse, IN_ActivateMouse), + CLDLL_ENTRY(pIN_DeactivateMouse, IN_DeactivateMouse), + CLDLL_ENTRY(pIN_MouseEvent, IN_MouseEvent), + CLDLL_ENTRY(pIN_ClearStates, IN_ClearStates), + CLDLL_ENTRY(pIN_Accumulate, IN_Accumulate), + CLDLL_ENTRY(pCL_CreateMove, CL_CreateMove), + CLDLL_ENTRY(pCL_IsThirdPerson, CL_IsThirdPerson), + CLDLL_ENTRY(pCL_GetCameraOffsets, CL_CameraOffset), + CLDLL_ENTRY(pFindKey, KB_Find), + CLDLL_ENTRY(pCamThink, CAM_Think), + CLDLL_ENTRY(pCalcRefdef, V_CalcRefdef), + CLDLL_ENTRY(pAddEntity, HUD_AddEntity), + CLDLL_ENTRY(pCreateEntities, HUD_CreateEntities), + CLDLL_ENTRY(pDrawNormalTriangles, HUD_DrawNormalTriangles), + CLDLL_ENTRY(pDrawTransparentTriangles, HUD_DrawTransparentTriangles), + CLDLL_ENTRY(pStudioEvent, HUD_StudioEvent), + CLDLL_ENTRY(pPostRunCmd, HUD_PostRunCmd), + CLDLL_ENTRY(pShutdown, HUD_Shutdown), + CLDLL_ENTRY(pTxferLocalOverrides, HUD_TxferLocalOverrides), + CLDLL_ENTRY(pProcessPlayerState, HUD_ProcessPlayerState), + CLDLL_ENTRY(pTxferPredictionData, HUD_TxferPredictionData), + CLDLL_ENTRY(pReadDemoBuffer, Demo_ReadBuffer), + CLDLL_ENTRY(pConnectionlessPacket, HUD_ConnectionlessPacket), + CLDLL_ENTRY(pGetHullBounds, HUD_GetHullBounds), + CLDLL_ENTRY(pHudFrame, HUD_Frame), + CLDLL_ENTRY(pKeyEvent, HUD_Key_Event), + CLDLL_ENTRY(pTempEntUpdate, HUD_TempEntUpdate), + CLDLL_ENTRY(pGetUserEntity, HUD_GetUserEntity), + CLDLL_ENTRY(pVoiceStatus, HUD_VoiceStatus), + CLDLL_ENTRY(pDirectorMessage, HUD_DirectorMessage), + CLDLL_ENTRY(pStudioInterface, HUD_GetStudioModelInterface), + CLDLL_ENTRY(pChatInputPosition, HUD_ChatInputPosition), + CLDLL_ENTRY(pGetPlayerTeam, HUD_GetPlayerTeam), + CLDLL_ENTRY(pClientFactory, ClientFactory), +}; + +BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD type, LPVOID lpReserved) +{ + if (type == DLL_PROCESS_ATTACH) + { + g_EngineLib = new CEngine(); + + const char *engine = registry->ReadString("EngineDLL", ENGINE_CLIENT_LIB); + if (!g_EngineLib->Init(engine, "engine.log")) { + return FALSE; + } + } + else if (type == DLL_PROCESS_DETACH) + { + delete g_EngineLib; + } + + return TRUE; +} + +void *WINAPI _GetProcAddress(HMODULE hModule, LPCSTR lpProcName) +{ + auto res = GetProcAddress(hModule, lpProcName); + for (auto &func : g_cldllapi_info) + { + if (Q_strcmp(func.name, lpProcName) != 0) + continue; + + *(size_t *)(size_t(&gClientfuncs) + func.offset) = size_t(res); + } + + if (!Q_strcmp(lpProcName, "Initialize")) { + return &Initialize; + } + + return res; +} + +BOOL LoadSecureClient(char *pszDllName) +{ + return FALSE; +} diff --git a/hitboxtracker/client/src/main.h b/hitboxtracker/client/src/main.h new file mode 100644 index 0000000..37b8736 --- /dev/null +++ b/hitboxtracker/client/src/main.h @@ -0,0 +1,35 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "iregistry.h" + +void R_ForceCVars(qboolean multiplayer); +void * WINAPI _GetProcAddress(HMODULE hModule, LPCSTR lpProcName); +BOOL LoadSecureClient(char *pszDllName); diff --git a/hitboxtracker/client/src/modules/client.cpp b/hitboxtracker/client/src/modules/client.cpp new file mode 100644 index 0000000..01dc969 --- /dev/null +++ b/hitboxtracker/client/src/modules/client.cpp @@ -0,0 +1,66 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +CClient::CClient() +{ +} + +CClient::~CClient() +{ +} + +bool CClient::Init(const char *szModuleName, const char *pszFile) +{ + if (!CSysModule::Init(szModuleName, pszFile)) + return false; + + if (!(pg_PlayerExtraInfo = (extra_player_info_t (*)[65])FindPlayerExtraInfo())) + { + TraceLog("> %s: Not found global g_PlayerExtraInfo\n", __FUNCTION__); + return false; + } + + return true; +} + +extra_player_info_t **CClient::FindPlayerExtraInfo() +{ + auto pos = getsym("HUD_GetPlayerTeam"); + if (!pos) { + return nullptr; + } + + pos = find_pattern(pos, 32, "\x0F\xBF\x04\x2A\x2A\x2A\x2A\x2A\xC3"); + if (!pos) { + return nullptr; + } + + return (extra_player_info_t **)(*(byteptr_t *)(pos + 4) - offsetof(extra_player_info_t, team_id)); +} diff --git a/hitboxtracker/client/src/modules/client.h b/hitboxtracker/client/src/modules/client.h new file mode 100644 index 0000000..c4025e8 --- /dev/null +++ b/hitboxtracker/client/src/modules/client.h @@ -0,0 +1,41 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CClient: public virtual CSysModule +{ +public: + CClient(); + ~CClient(); + + bool Init(const char *szModuleName, const char *pszFile); + +protected: + extra_player_info_t **FindPlayerExtraInfo(); +}; diff --git a/hitboxtracker/client/src/modules/engine.cpp b/hitboxtracker/client/src/modules/engine.cpp new file mode 100644 index 0000000..01fa784 --- /dev/null +++ b/hitboxtracker/client/src/modules/engine.cpp @@ -0,0 +1,242 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +CEngine *g_EngineLib; + +svc_func_t *g_pSVCfuncs; +cl_enginefunc_t *g_pEngfuncs; +cldll_func_t *g_pClientfuncs; + +svc_func_t gSVCfuncs; +cl_enginefunc_t gEngfuncs; +cldll_func_t gClientfuncs; +StudioLighting_t pfnR_StudioLighting; + +CEngine::CEngine() +{ + registry->Init(); +} + +CEngine::~CEngine() +{ + registry->Shutdown(); + gHUD.ShutDown(); +} + +hook_t CEngine::m_LoadSecureClient(OP_JUMP, LoadSecureClient); +bool CEngine::LoadSecureClient_Init() +{ + byteptr_t pos; + if (!(pos = find_pattern("\x55\x8B\xEC\x8B\x45\x08\x6A\x01\x68"))) { + pos = find_pattern("\x8B\x44\x24\x04\x6A\x00\x68"); + } + + return SetHook(pos, &m_LoadSecureClient); +} + +bool CEngine::LoadInSecureClient_Init() +{ + auto pos = find_string("could not link client.dll function Initialize\n", OP_PUSH); + if (!pos) + { + return false; + } + + pos = find_pattern_back(pos, "\x8B\x2A\x2A\x2A\x2A\x2A\x68"); + if (!pos) + { + return false; + } + + static auto refproc = &_GetProcAddress; + + // 8B 35 14 A1 E1 01 mov esi, ds:GetProcAddress + // -> + // BE XX XX XX XX mov esi, _GetProcAddress + // 90 + + char bytes[6]; + bytes[0] = '\xBE'; + Q_memcpy(&bytes[1], &refproc, sizeof(refproc)); + bytes[5] = '\x90'; + + return patch(pos, &bytes, sizeof(bytes)); +} + +bool CEngine::Init(const char *szModuleName, const char *pszFile) +{ + if (!CSysModule::Init(szModuleName, pszFile)) + return false; + + m_Software = !Q_stricmp(szModuleName, ENGINE_CLIENT_SOFT_LIB) ? true : false; + + if (!LoadSecureClient_Init() || !LoadInSecureClient_Init()) + { + TraceLog("> %s: Not found ClientFuncs\n", __FUNCTION__); + return false; + } + + if (!(g_pClientfuncs = FindClientFuncs())) + { + TraceLog("> %s: Not found ClientFuncs\n", __FUNCTION__); + return false; + } + + if (!(g_pSVCfuncs = FindSVCFuncs())) + { + TraceLog("> %s: Not found SVCFuncs\n", __FUNCTION__); + return false; + } + + if (!(pg_pClientUserMsgs = FindClientUserMsgs())) + { + TraceLog("> %s: Not found UserMsg\n", __FUNCTION__); + return false; + } + + // Find R_ForceCVars and block + if (!FindForceCVars()) + { + TraceLog("> %s: Not found function R_ForceCVars\n", __FUNCTION__); + } + + return true; +} + +hook_t CEngine::m_ForceCVars(OP_JUMP, &R_ForceCVars); +bool CEngine::FindForceCVars() +{ + if (m_Software) { + return true; + } + + byteptr_t pos; + if (!(pos = find_pattern("\x8B\x2A\x2A\x2A\x85\xC0\x0F\x2A\x2A\x2A\x2A\x2A\xD9\x2A\x2A\x2A\x2A\x2A\xD8"))) { + pos = find_pattern("\x55\x8B\xEC\x8B\x45\x08\x85\xC0\x0F\x2A\x2A\x2A\x2A\x2A\xD9"); + } + + if (!pos) { + return false; + } + + return SetHook(pos, &m_ForceCVars); +} + +svc_func_t *CEngine::FindSVCFuncs() +{ + auto pos = find_string("svc_bad"); + if (!pos) { + return nullptr; + } + + auto pSVC = (svc_func_t *)(pos - offsetof(svc_func_t, pszName) + 1); + Q_memcpy(&gSVCfuncs, pSVC, sizeof(gSVCfuncs)); + return pSVC; +} + +cl_enginefunc_t *CEngine::FindEngineFuncs() +{ + auto pos = find_string("ScreenFade", OP_PUSH); + if (!pos) { + return nullptr; + } + + pos = find_pattern(pos + 1, 16, "\x68"); + if (!pos) { + return nullptr; + } + + auto pEngine = *(cl_enginefunc_t **)(pos + 1); + Q_memcpy(&gEngfuncs, pEngine, sizeof(gEngfuncs)); + return pEngine; +} + +cldll_func_t *CEngine::FindClientFuncs() +{ + auto pos = find_string("ScreenFade", OP_PUSH); + if (!pos) { + return nullptr; + } + + pos = find_pattern(pos, 32, "\xFF\x2A\x2A\x2A\x2A\x2A\x68"); + if (!pos) { + return nullptr; + } + + auto pClient = *(cldll_func_t **)(pos + 2); + Q_memcpy(&gClientfuncs, pClient, sizeof(gClientfuncs)); + return pClient; +} + +UserMsg **CEngine::FindClientUserMsgs() +{ + auto pos = find_string("UserMsg: Not Present on Client %d\n", OP_PUSH); + if (!pos) { + return nullptr; + } + + pos = find_pattern(pos - 32, 32, "\x8B\x2A\x2A\x2A\x2A\x2A\x85\xF6\x74\x0B"); + if (!pos) { + return nullptr; + } + + auto pClientUserMsgs = *(UserMsg ***)(pos + 2); + return pClientUserMsgs; +} + +bool CEngine::StudioLightingInit() +{ + auto pos = find_pattern("\x55\x8B\xEC\x51\xDB\x2A\x2A\x2A\x2A\x2A\x8A\x2A\x2A\xB8"); + if (!pos) { + pos = find_pattern("\x51\xDB\x2A\x2A\x2A\x2A\x2A\x8A\x2A\x2A\x2A\xB8"); + } + + if (!pos) { + TraceLog("> %s: Not found function StudioLightingInit #2\n", __FUNCTION__); + return false; + } + + pfnR_StudioLighting = StudioLighting_t(pos); + return true; +} + +void R_StudioLighting(float *lv, int bone, int flags, const vec_t *normal) +{ + if (!pfnR_StudioLighting) { + *lv = 0.75f; + return; + } + + pfnR_StudioLighting(lv, bone, flags, normal); + + if (g_EngineLib->IsSoftware()) { + *lv = *lv / (USHRT_MAX + 1); + } +} diff --git a/hitboxtracker/client/src/modules/engine.h b/hitboxtracker/client/src/modules/engine.h new file mode 100644 index 0000000..ed8b1c3 --- /dev/null +++ b/hitboxtracker/client/src/modules/engine.h @@ -0,0 +1,76 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "net.h" + +class CEngine: virtual public CSysModule +{ +public: + CEngine(); + ~CEngine(); + + bool Init(const char *szModuleName, const char *pszFile); + bool StudioLightingInit(); + bool IsSoftware() const { return m_Software; } + +protected: + bool m_Software; + + bool FindForceCVars(); + bool LoadSecureClient_Init(); + bool LoadInSecureClient_Init(); + + svc_func_t *FindSVCFuncs(); + cl_enginefunc_t *FindEngineFuncs(); + cldll_func_t *FindClientFuncs(); + UserMsg **FindClientUserMsgs(); + + static hook_t m_ForceCVars; + static hook_t m_GetProcAddress; + static hook_t m_LoadSecureClient; +}; + +extern CEngine *g_EngineLib; +extern svc_func_t *g_pSVCfuncs; +extern cl_enginefunc_t *g_pEngfuncs; +extern cldll_func_t *g_pClientfuncs; + +extern svc_func_t gSVCfuncs; +extern cl_enginefunc_t gEngfuncs; +extern cldll_func_t gClientfuncs; + +#define TRACE_LOG(fmt, ...)\ + g_EngineLib->TraceLog("> %s: " fmt, __FUNCTION__, __VA_ARGS__) + +#define TRACE_LOG2(fmt, ...)\ + g_EngineLib->TraceLog(fmt, __VA_ARGS__) + +using StudioLighting_t = void (*)(float *lv, int bone, int flags, const vec_t *normal); +void R_StudioLighting(float *lv, int bone, int flags, const vec_t *normal); diff --git a/hitboxtracker/client/src/precompiled.cpp b/hitboxtracker/client/src/precompiled.cpp new file mode 100644 index 0000000..82b5132 --- /dev/null +++ b/hitboxtracker/client/src/precompiled.cpp @@ -0,0 +1,29 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" diff --git a/hitboxtracker/client/src/precompiled.h b/hitboxtracker/client/src/precompiled.h new file mode 100644 index 0000000..244fe59 --- /dev/null +++ b/hitboxtracker/client/src/precompiled.h @@ -0,0 +1,62 @@ +#pragma once + +//#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "maintypes.h" +#include "strtools.h" +#include "vector.h" +#include "const.h" +#include "edict.h" +#include "eiface.h" +#include "const.h" +#include "vmodes.h" +#include "usermsg.h" +#include "APIProxy.h" +#include "r_studioint.h" +#include "cl_entity.h" +#include "triangleapi.h" +#include "pmtrace.h" +#include "pm_defs.h" +#include "pm_info.h" +#include "cvardef.h" +#include "studio.h" +#include "event_args.h" +#include "event_flags.h" +#include "keydefs.h" +#include "kbutton.h" +#include "com_model.h" +#include "ref_params.h" +#include "studio_event.h" +#include "net_api.h" +#include "r_efx.h" +#include "parsemsg.h" +#include "event_api.h" +#include "screenfade.h" +#include "engine_launcher_api.h" +#include "entity_types.h" +#include "cdll_int.h" +#include "cdll_dll.h" +#include "client.h" + +#include "main.h" +#include "hud.h" +#include "sys_module.h" +#include "cstrike_util.h" +#include "studio/GameStudioModelRenderer.h" + +// Modules +#include "modules/engine.h" // Handle hw.dll +#include "modules/client.h" // Handle client.dll diff --git a/hitboxtracker/client/src/studio/GameStudioModelRenderer.cpp b/hitboxtracker/client/src/studio/GameStudioModelRenderer.cpp new file mode 100644 index 0000000..9eb42ed --- /dev/null +++ b/hitboxtracker/client/src/studio/GameStudioModelRenderer.cpp @@ -0,0 +1,1258 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +float g_flStartScaleTime; +int g_iPrevRenderState; +qboolean g_iRenderStateChanged; + +typedef struct +{ + vec3_t origin; + vec3_t angles; + + vec3_t realangles; + + float animtime; + float frame; + int sequence; + int gaitsequence; + float framerate; + + qboolean m_fSequenceLoops; + qboolean m_fSequenceFinished; + + byte controller[4]; + byte blending[2]; + latchedvars_t lv; + +} client_anim_state_t; + +static client_anim_state_t g_state; +static client_anim_state_t g_clientstate; + +// The renderer object, created on the stack. +CGameStudioModelRenderer g_StudioRenderer; + +CGameStudioModelRenderer::CGameStudioModelRenderer() +{ + // If you want to predict animations locally, set this to TRUE + // NOTE: The animation code is somewhat broken, but gives you a sense for how + // to do client side animation of the predicted player in a third person game. + m_bLocal = false; +} + +void CGameStudioModelRenderer::StudioSetupBones() +{ + double f; + + mstudiobone_t *pbones; + mstudioseqdesc_t *pseqdesc; + mstudioanim_t *panim; + + static float pos[MAXSTUDIOBONES][3]; + static vec4_t q[MAXSTUDIOBONES]; + float bonematrix[3][4]; + + static float pos2[MAXSTUDIOBONES][3]; + static vec4_t q2[MAXSTUDIOBONES]; + static float pos3[MAXSTUDIOBONES][3]; + static vec4_t q3[MAXSTUDIOBONES]; + static float pos4[MAXSTUDIOBONES][3]; + static vec4_t q4[MAXSTUDIOBONES]; + + // Use default bone setup for nonplayers + if (!m_pCurrentEntity->player) + { + CStudioModelRenderer::StudioSetupBones(); + return; + } + + // Bound sequence number + if (m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq || m_pCurrentEntity->curstate.sequence < 0) + { + m_pCurrentEntity->curstate.sequence = 0; + } + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + + if (m_pPlayerInfo) + { + int playerNum = m_pCurrentEntity->index - 1; + if (m_nPlayerGaitSequences[playerNum] != ANIM_JUMP_SEQUENCE && m_pPlayerInfo->gaitsequence == ANIM_JUMP_SEQUENCE) + { + m_pPlayerInfo->gaitframe = 0; + } + + m_nPlayerGaitSequences[playerNum] = m_pPlayerInfo->gaitsequence; + } + + f = StudioEstimateFrame(pseqdesc); + + if (m_pPlayerInfo->gaitsequence == ANIM_WALK_SEQUENCE) + { + if (m_pCurrentEntity->curstate.blending[0] > 26) + { + m_pCurrentEntity->curstate.blending[0] -= 26; + } + else + { + m_pCurrentEntity->curstate.blending[0] = 0; + } + + m_pCurrentEntity->latched.prevseqblending[0] = m_pCurrentEntity->curstate.blending[0]; + } + + // This game knows how to do three way blending + if (pseqdesc->numblends != NUM_BLENDING) + { + StudioCalcRotations(pos, q, pseqdesc, panim, f); + } + else + { + float s = m_pCurrentEntity->curstate.blending[0]; + float t = m_pCurrentEntity->curstate.blending[1]; + + // Blending is 0-127 == Left to Middle, 128 to 255 == Middle to right + if (s <= 127.0f) + { + // Scale 0-127 blending up to 0-255 + s = (s * 2.0f); + + if (t <= 127.0f) + { + t = (t * 2.0f); + + StudioCalcRotations(pos, q, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 1); + StudioCalcRotations(pos2, q2, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 3); + StudioCalcRotations(pos3, q3, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos4, q4, pseqdesc, panim, f); + } + else + { + t = 2.0f * (t - 127.0f); + + panim = LookupAnimation(pseqdesc, 3); + StudioCalcRotations(pos, q, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos2, q2, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 6); + StudioCalcRotations(pos3, q3, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 7); + StudioCalcRotations(pos4, q4, pseqdesc, panim, f); + } + } + else + { + // Scale 127-255 blending up to 0-255 + s = 2.0f * (s - 127.0f); + + if (t <= 127.0f) + { + t = (t * 2.0f); + + panim = LookupAnimation(pseqdesc, 1); + StudioCalcRotations(pos, q, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 2); + StudioCalcRotations(pos2, q2, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos3, q3, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 5); + StudioCalcRotations(pos4, q4, pseqdesc, panim, f); + } + else + { + t = 2.0f * (t - 127.0f); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos, q, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 5); + StudioCalcRotations(pos2, q2, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 7); + StudioCalcRotations(pos3, q3, pseqdesc, panim, f); + + panim = LookupAnimation(pseqdesc, 8); + StudioCalcRotations(pos4, q4, pseqdesc, panim, f); + } + } + + // Normalize interpolant + s /= 255.0f; + t /= 255.0f; + + // Spherically interpolate the bones + StudioSlerpBones(q, pos, q2, pos2, s); + StudioSlerpBones(q3, pos3, q4, pos4, s); + StudioSlerpBones(q, pos, q3, pos3, t); + } + + // Are we in the process of transitioning from one sequence to another. + if (m_fDoInterp && + m_pCurrentEntity->latched.sequencetime && + (m_pCurrentEntity->latched.sequencetime + 0.2 > m_clTime) && + (m_pCurrentEntity->latched.prevsequence < m_pStudioHeader->numseq)) + { + // blend from last sequence + static float pos1b[MAXSTUDIOBONES][3]; + static vec4_t q1b[MAXSTUDIOBONES]; + + float s = m_pCurrentEntity->latched.prevseqblending[0]; + float t = m_pCurrentEntity->latched.prevseqblending[1]; + + // Point at previous sequenece + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->latched.prevsequence; + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + + // Know how to do three way blends + if (pseqdesc->numblends != 9) + { + // clip prevframe + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + } + else + { + // Blending is 0-127 == Left to Middle, 128 to 255 == Middle to right + if (s <= 127.0f) + { + // Scale 0-127 blending up to 0-255 + s = (s * 2.0f); + + if (t <= 127.0f) + { + t = (t * 2.0f); + + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 1); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 3); + StudioCalcRotations(pos3, q3, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos4, q4, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + } + else + { + t = 2.0f * (t - 127.0f); + + panim = LookupAnimation(pseqdesc, 3); + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 6); + StudioCalcRotations(pos3, q3, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 7); + StudioCalcRotations(pos4, q4, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + } + } + else + { + // Scale 127-255 blending up to 0-255 + s = 2.0f * (s - 127.0f); + + if (t <= 127.0f) + { + t = (t * 2.0f); + + panim = LookupAnimation(pseqdesc, 1); + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 2); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos3, q3, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 5); + StudioCalcRotations(pos4, q4, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + } + else + { + t = 2.0f * (t - 127.0f); + + panim = LookupAnimation(pseqdesc, 4); + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 5); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 7); + StudioCalcRotations(pos3, q3, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim = LookupAnimation(pseqdesc, 8); + StudioCalcRotations(pos4, q4, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + } + } + + // Normalize interpolant + s /= 255.0f; + t /= 255.0f; + + // Spherically interpolate the bones + StudioSlerpBones(q1b, pos1b, q2, pos2, s); + StudioSlerpBones(q3, pos3, q4, pos4, s); + StudioSlerpBones(q1b, pos1b, q3, pos3, t); + } + + // Now blend last frame of previous sequence with current sequence. + s = 1.0 - (m_clTime - m_pCurrentEntity->latched.sequencetime) / 0.2; + StudioSlerpBones(q, pos, q1b, pos1b, s); + } + else + { + m_pCurrentEntity->latched.prevframe = f; + } + + // Now convert quaternions and bone positions into matrices + pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + if (m_pPlayerInfo + && m_pCurrentEntity->curstate.sequence < ANIM_FIRST_DEATH_SEQUENCE + && m_pCurrentEntity->curstate.sequence != ANIM_SWIM_1 + && m_pCurrentEntity->curstate.sequence != ANIM_SWIM_2) + { + bool bCopy = true; + + if (m_pPlayerInfo->gaitsequence >= m_pStudioHeader->numseq || m_pPlayerInfo->gaitsequence < 0) + m_pPlayerInfo->gaitsequence = 0; + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex ) + m_pPlayerInfo->gaitsequence; + + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pPlayerInfo->gaitframe); + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + if (!Q_strcmp(pbones[i].name, "Bip01 Spine")) + bCopy = false; + else if (!Q_strcmp(pbones[pbones[i].parent].name, "Bip01 Pelvis")) + bCopy = true; + + if (bCopy) + { + Q_memcpy(pos[i], pos2[i], sizeof(pos[i])); + Q_memcpy(q[i], q2[i], sizeof(q[i])); + } + } + } + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + QuaternionMatrix(q[i], bonematrix); + + bonematrix[0][3] = pos[i][0]; + bonematrix[1][3] = pos[i][1]; + bonematrix[2][3] = pos[i][2]; + + if (pbones[i].parent == -1) + { + if (IEngineStudio.IsHardware()) + { + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_pbonetransform)[i]); + MatrixCopy((*m_pbonetransform)[i], (*m_plighttransform)[i]); + } + else + { + ConcatTransforms((*m_paliastransform), bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]); + } + + // Apply client-side effects to the transformation matrix + StudioFxTransform(m_pCurrentEntity, (*m_pbonetransform)[i]); + } + else + { + ConcatTransforms((*m_pbonetransform)[pbones[i].parent], bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_plighttransform)[pbones[i].parent], bonematrix, (*m_plighttransform)[i]); + } + } +} + +void CGameStudioModelRenderer::StudioEstimateGait(entity_state_t *pplayer) +{ + float dt; + if (m_pPlayerSync) + { + dt = clamp(m_pPlayerSync->time - m_pPlayerSync->oldtime, 0.0f, 1.0f); + } + else + { + dt = clamp(m_clTime - m_clOldTime, 0.0, 1.0); + } + + if (dt == 0 || m_pPlayerInfo->renderframe == m_nFrameCount) + { + m_flGaitMovement = 0; + return; + } + + vec3_t est_velocity; + if (m_fGaitEstimation) + { + VectorSubtract(m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin, est_velocity); + VectorCopy(m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin); + m_flGaitMovement = Length(est_velocity); + if (dt <= 0 || m_flGaitMovement / dt < 5) + { + m_flGaitMovement = 0; + est_velocity[0] = 0; + est_velocity[1] = 0; + } + } + else + { + VectorCopy(pplayer->velocity, est_velocity); + m_flGaitMovement = Length(est_velocity) * dt; + } + + float flYaw = m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw; + if (m_pCurrentEntity->curstate.sequence > 100) + { + m_pPlayerInfo->gaityaw += flYaw; + return; + } + + if (est_velocity[1] == 0 && est_velocity[0] == 0) + { + float flYawDiff = flYaw - (int)(flYaw / 360) * 360; + + if (flYawDiff > 180) + flYawDiff -= 360; + + if (flYawDiff < -180) + flYawDiff += 360; + + flYaw = fmod(flYaw, 360.0); + + if (flYaw < -180) + flYaw += 360; + + else if (flYaw > 180) + flYaw -= 360; + + if (flYaw > -5.0 && flYaw < 5.0) + m_pCurrentEntity->baseline.fuser1 = 0.05; + + if (flYaw < -90.0 || flYaw > 90.0) + m_pCurrentEntity->baseline.fuser1 = 3.5; + + if (dt < 0.25) + flYawDiff *= dt * m_pCurrentEntity->baseline.fuser1; + else + flYawDiff *= dt; + + if (abs(flYawDiff) < 0.1) + flYawDiff = 0.0; + + m_pPlayerInfo->gaityaw += flYawDiff; + m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw - (int)(m_pPlayerInfo->gaityaw / 360) * 360; + m_flGaitMovement = 0; + } + else + { + m_pPlayerInfo->gaityaw = (atan2(est_velocity[1], est_velocity[0]) * (180 / M_PI)); + + if (m_pPlayerInfo->gaityaw > 180) + m_pPlayerInfo->gaityaw = 180; + + if (m_pPlayerInfo->gaityaw < -180) + m_pPlayerInfo->gaityaw = -180; + } +} + +void CGameStudioModelRenderer::StudioProcessGait(entity_state_t *pplayer) +{ + CalculateYawBlend(pplayer); + CalculatePitchBlend(pplayer); + + float dt; + if (m_pPlayerSync) + { + dt = clamp(m_pPlayerSync->time - m_pPlayerSync->oldtime, 0.0f, 1.0f); + } + else + { + dt = clamp(m_clTime - m_clOldTime, 0.0, 1.0); + } + + mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + pplayer->gaitsequence; + + if (pseqdesc->linearmovement[0] > 0) + m_pPlayerInfo->gaitframe += (m_flGaitMovement / pseqdesc->linearmovement[0]) * pseqdesc->numframes; + else + m_pPlayerInfo->gaitframe += pseqdesc->fps * dt * m_pCurrentEntity->curstate.framerate; + + m_pPlayerInfo->gaitframe = m_pPlayerInfo->gaitframe - (int)(m_pPlayerInfo->gaitframe / pseqdesc->numframes) * pseqdesc->numframes; + + if (m_pPlayerInfo->gaitframe < 0) + m_pPlayerInfo->gaitframe += pseqdesc->numframes; +} + +// For local player, in third person, we need to store real +// render data and then setup for with fake/client side animation data +void CGameStudioModelRenderer::SavePlayerState(entity_state_t *pplayer) +{ + cl_entity_t *ent = IEngineStudio.GetCurrentEntity(); + + if (!ent) + return; + + client_anim_state_t *st = &g_state; + + st->angles = ent->curstate.angles; + st->origin = ent->curstate.origin; + st->realangles = ent->angles; + + st->sequence = ent->curstate.sequence; + st->gaitsequence = pplayer->gaitsequence; + st->animtime = ent->curstate.animtime; + st->frame = ent->curstate.frame; + st->framerate = ent->curstate.framerate; + + Q_memcpy(st->blending, ent->curstate.blending, sizeof(st->blending)); + Q_memcpy(st->controller, ent->curstate.controller, sizeof(st->controller)); + + st->lv = ent->latched; +} + +mstudioanim_t *CGameStudioModelRenderer::LookupAnimation(mstudioseqdesc_t *pseqdesc, int index) +{ + mstudioanim_t *panim = StudioGetAnim(m_pRenderModel, pseqdesc); + if (index >= 0 && index <= (pseqdesc->numblends - 1)) + { + panim += index * m_pStudioHeader->numbones; + } + + return panim; +} + +const char *CGameStudioModelRenderer::m_boneNames[] = +{ + "Bip01 Head", + "Bip01 Pelvis", + "Bip01 Spine1", + "Bip01 Spine2", + "Bip01 Spine3" +}; + +void CGameStudioModelRenderer::CachePlayerBoneIndices() +{ + if (m_isBoneCacheValid) + return; + + mstudiobone_t *pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + for (int cacheIdx = 0; cacheIdx < ARRAYSIZE(m_boneNames); cacheIdx++) + { + for (int boneIdx = 0; boneIdx < m_pStudioHeader->numbones; boneIdx++) + { + if (!Q_strcmp(pbones[boneIdx].name, m_boneNames[cacheIdx])) + { + m_boneIndexCache[cacheIdx] = boneIdx; + break; + } + } + } + + m_isBoneCacheValid = true; +} + +int CGameStudioModelRenderer::GetPlayerBoneIndex(BoneIndex whichBone) +{ + return m_boneIndexCache[whichBone]; +} + +bool CGameStudioModelRenderer::GetPlayerBoneWorldPosition(BoneIndex whichBone, Vector &pos) +{ + CachePlayerBoneIndices(); + + int boneIdx = GetPlayerBoneIndex(whichBone); + if (boneIdx < 0 || m_pStudioHeader->numbones <= boneIdx) + return false; + + pos.x = m_rgCachedBoneTransform[boneIdx][0][3]; + pos.y = m_rgCachedBoneTransform[boneIdx][1][3]; + pos.z = m_rgCachedBoneTransform[boneIdx][2][3]; + + return true; +} + +void GetSequenceInfo(void *pmodel, client_anim_state_t *pev, float *pflFrameRate, float *pflGroundSpeed) +{ + studiohdr_t *pstudiohdr = (studiohdr_t *)pmodel; + if (!pstudiohdr) + return; + + if (pev->sequence >= pstudiohdr->numseq || pev->sequence < 0) + { + *pflFrameRate = 0.0; + *pflGroundSpeed = 0.0; + return; + } + + mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; + + if (pseqdesc->numframes > 1) + { + *pflFrameRate = 256 * pseqdesc->fps / (pseqdesc->numframes - 1); + *pflGroundSpeed = pseqdesc->linearmovement.Length(); + *pflGroundSpeed = *pflGroundSpeed * pseqdesc->fps / (pseqdesc->numframes - 1); + } + else + { + *pflFrameRate = 256.0; + *pflGroundSpeed = 0.0; + } +} + +int GetSequenceFlags(void *pmodel, client_anim_state_t *pev) +{ + studiohdr_t *pstudiohdr = (studiohdr_t *)pmodel; + if (!pstudiohdr || pev->sequence >= pstudiohdr->numseq || pev->sequence < 0) + return 0; + + mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; + return pseqdesc->flags; +} + +float StudioFrameAdvance(client_anim_state_t *st, float framerate, float flInterval) +{ + if (flInterval == 0.0) + { + flInterval = (gEngfuncs.GetClientTime() - st->animtime); + if (flInterval <= 0.001) + { + st->animtime = gEngfuncs.GetClientTime(); + return 0.0; + } + } + + if (!st->animtime) + flInterval = 0.0; + + st->frame += flInterval * framerate * st->framerate; + st->animtime = gEngfuncs.GetClientTime(); + + if (st->frame < 0.0 || st->frame >= 256.0) + { + if (st->m_fSequenceLoops) + st->frame -= (int)(st->frame / 256.0) * 256.0; + else + st->frame = (st->frame < 0.0) ? 0 : 255; + st->m_fSequenceFinished = TRUE; // just in case it wasn't caught in GetEvents + } + + return flInterval; +} + +// Called to set up local player's animation values +void CGameStudioModelRenderer::SetupClientAnimation(entity_state_t *pplayer) +{ + static double oldtime; + double curtime, dt; + + client_anim_state_t *st; + float fr, gs; + + cl_entity_t *ent = IEngineStudio.GetCurrentEntity(); + + if (!ent) + return; + + curtime = gEngfuncs.GetClientTime(); + dt = clamp(curtime - oldtime, 0.0, 1.0); + + oldtime = curtime; + st = &g_clientstate; + + st->framerate = 1.0; + + int oldseq = st->sequence; + CounterStrike_GetSequence(&st->sequence, &st->gaitsequence); + CounterStrike_GetOrientation((float *)&st->origin, (float *)&st->angles); + st->realangles = st->angles; + + if (st->sequence != oldseq) + { + st->frame = 0.0; + st->lv.prevsequence = oldseq; + st->lv.sequencetime = st->animtime; + + Q_memcpy(st->lv.prevseqblending, st->blending, sizeof(st->lv.prevseqblending)); + Q_memcpy(st->lv.prevcontroller, st->controller, sizeof(st->lv.prevcontroller)); + } + + studiohdr_t *pmodel = (studiohdr_t *)IEngineStudio.Mod_Extradata(ent->model); + + GetSequenceInfo(pmodel, st, &fr, &gs); + st->m_fSequenceLoops = ((GetSequenceFlags(pmodel, st) & STUDIO_LOOPING) != 0) ? TRUE : FALSE; + StudioFrameAdvance(st, fr, dt); + + // gEngfuncs.Con_Printf("gs %i frame %f\n", st->gaitsequence, st->frame); + + ent->angles = st->realangles; + ent->curstate.angles = st->angles; + ent->curstate.origin = st->origin; + ent->curstate.sequence = st->sequence; + pplayer->gaitsequence = st->gaitsequence; + ent->curstate.animtime = st->animtime; + ent->curstate.frame = st->frame; + ent->curstate.framerate = st->framerate; + + Q_memcpy(ent->curstate.blending, st->blending, sizeof(ent->curstate.blending)); + Q_memcpy(ent->curstate.controller, st->controller, sizeof(ent->curstate.controller)); + + ent->latched = st->lv; +} + +// Called to restore original player state information +void CGameStudioModelRenderer::RestorePlayerState(entity_state_t *pplayer) +{ + cl_entity_t *ent = IEngineStudio.GetCurrentEntity(); + + if (!ent) + return; + + client_anim_state_t *st = &g_clientstate; + + st->angles = ent->curstate.angles; + st->origin = ent->curstate.origin; + st->realangles = ent->angles; + st->sequence = ent->curstate.sequence; + st->gaitsequence = pplayer->gaitsequence; + st->animtime = ent->curstate.animtime; + st->frame = ent->curstate.frame; + st->framerate = ent->curstate.framerate; + + Q_memcpy(st->blending, ent->curstate.blending, sizeof(st->blending)); + Q_memcpy(st->controller, ent->curstate.controller, sizeof(st->controller)); + + st->lv = ent->latched; + + st = &g_state; + + ent->curstate.angles = st->angles; + ent->curstate.origin = st->origin; + ent->angles = st->realangles; + + ent->curstate.sequence = st->sequence; + pplayer->gaitsequence = st->gaitsequence; + ent->curstate.animtime = st->animtime; + ent->curstate.frame = st->frame; + ent->curstate.framerate = st->framerate; + + Q_memcpy(ent->curstate.blending, st->blending, sizeof(ent->curstate.blending)); + Q_memcpy(ent->curstate.controller, st->controller, sizeof(ent->curstate.controller)); + + ent->latched = st->lv; +} + +int CGameStudioModelRenderer::StudioDrawPlayer(int flags, entity_state_t *pplayer) +{ + bool isLocalPlayer = false; + + // Set up for client? + if (m_bLocal && IEngineStudio.GetCurrentEntity() == gEngfuncs.GetLocalPlayer()) + { + isLocalPlayer = true; + } + + if (isLocalPlayer) + { + SavePlayerState(pplayer); // Store original data + SetupClientAnimation(pplayer); // Copy in client side animation data + } + + // Call real draw function + int iret = _StudioDrawPlayer(flags, pplayer); + if (iret && m_pCvarDrawEntities->value == 6) + { + m_pPlayerSync = &g_PlayerSyncInfo[pplayer->number]; + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + + // save + player_info_t saveplayer = *m_pPlayerInfo; + cl_entity_t saveent = *m_pCurrentEntity; + + float gaitmovement = m_flGaitMovement; + m_flGaitMovement = m_pPlayerSync->gaitmovement; + + VectorCopy(m_pPlayerSync->prevgaitorigin, m_pPlayerInfo->prevgaitorigin); + + m_pPlayerInfo->gaitsequence = m_pPlayerSync->gaitsequence; + m_pPlayerInfo->gaityaw = m_pPlayerSync->gaityaw; + m_pPlayerInfo->gaitframe = m_pPlayerSync->gaitframe; + m_pPlayerInfo = nullptr; + + _StudioDrawPlayer(flags, pplayer); + + // restore + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + *m_pPlayerInfo = saveplayer; + *m_pCurrentEntity = saveent; + m_flGaitMovement = gaitmovement; + m_pPlayerInfo = nullptr; + m_pPlayerSync = nullptr; + } + + // Restore for client? + if (isLocalPlayer) + { + // Restore the original data for the player + RestorePlayerState(pplayer); + } + + return iret; +} + +bool WeaponHasAttachments(entity_state_t *pplayer) +{ + if (!pplayer) + return false; + + model_t *pweaponmodel = IEngineStudio.GetModelByIndex(pplayer->weaponmodel); + studiohdr_t *modelheader = (studiohdr_t *)IEngineStudio.Mod_Extradata(pweaponmodel); + + return (modelheader->numattachments != 0); +} + +int CGameStudioModelRenderer::_StudioDrawPlayer(int flags, entity_state_t *pplayer) +{ + m_pCurrentEntity = IEngineStudio.GetCurrentEntity(); + + IEngineStudio.GetTimes(&m_nFrameCount, &m_clTime, &m_clOldTime); + IEngineStudio.GetViewInfo(m_vRenderOrigin, m_vUp, m_vRight, m_vNormal); + IEngineStudio.GetAliasScale(&m_fSoftwareXScale, &m_fSoftwareYScale); + + m_nPlayerIndex = pplayer->number - 1; + + if (m_nPlayerIndex < 0 || m_nPlayerIndex >= gEngfuncs.GetMaxClients()) + return 0; + + if (cl_minmodels && cl_minmodels->value) + { + if (g_PlayerExtraInfo[pplayer->number].teamnumber == TEAM_CT) + { + int modelindex = (cl_min_t && IsValidCTModelIndex(cl_min_t->value)) ? cl_min_t->value : CS_LEET; + m_pRenderModel = gEngfuncs.CL_LoadModel(sPlayerModelFiles[modelindex], nullptr); + } + else if (g_PlayerExtraInfo[pplayer->number].teamnumber == TEAM_CT) + { + if (g_PlayerExtraInfo[pplayer->number].vip) + { + m_pRenderModel = gEngfuncs.CL_LoadModel(sPlayerModelFiles[CS_VIP], nullptr); + } + else + { + int modelindex = (cl_min_ct && IsValidCTModelIndex(cl_min_ct->value)) ? cl_min_ct->value : CS_GIGN; + m_pRenderModel = gEngfuncs.CL_LoadModel(sPlayerModelFiles[modelindex], nullptr); + } + } + } + else + { + m_pRenderModel = IEngineStudio.SetupPlayerModel(m_nPlayerIndex); + } + + if (!m_pRenderModel) + return 0; + + m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata(m_pRenderModel); + IEngineStudio.StudioSetHeader(m_pStudioHeader); + IEngineStudio.SetRenderModel(m_pRenderModel); + + // Check sequence index of bounds + if (m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq || m_pCurrentEntity->curstate.sequence < 0) + m_pCurrentEntity->curstate.sequence = 0; + + if (pplayer->sequence >= m_pStudioHeader->numseq || pplayer->sequence < 0) + pplayer->sequence = 0; + + if (m_pCurrentEntity->curstate.gaitsequence >= m_pStudioHeader->numseq || m_pCurrentEntity->curstate.gaitsequence < 0) + m_pCurrentEntity->curstate.gaitsequence = 0; + + if (pplayer->gaitsequence >= m_pStudioHeader->numseq || pplayer->gaitsequence < 0) + pplayer->gaitsequence = 0; + + if (pplayer->gaitsequence) + { + vec3_t orig_angles; + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + + VectorCopy(m_pCurrentEntity->angles, orig_angles); + + StudioProcessGait(pplayer); + + m_pPlayerInfo->gaitsequence = pplayer->gaitsequence; + m_pPlayerInfo = nullptr; + + StudioSetUpTransform(0); + VectorCopy(orig_angles, m_pCurrentEntity->angles); + } + else + { + m_pCurrentEntity->curstate.controller[0] = 127; + m_pCurrentEntity->curstate.controller[1] = 127; + m_pCurrentEntity->curstate.controller[2] = 127; + m_pCurrentEntity->curstate.controller[3] = 127; + + m_pCurrentEntity->latched.prevcontroller[0] = m_pCurrentEntity->curstate.controller[0]; + m_pCurrentEntity->latched.prevcontroller[1] = m_pCurrentEntity->curstate.controller[1]; + m_pCurrentEntity->latched.prevcontroller[2] = m_pCurrentEntity->curstate.controller[2]; + m_pCurrentEntity->latched.prevcontroller[3] = m_pCurrentEntity->curstate.controller[3]; + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + CalculatePitchBlend(pplayer); + CalculateYawBlend(pplayer); + m_pPlayerInfo->gaitsequence = 0; + + StudioSetUpTransform(0); + } + + if (flags & STUDIO_RENDER) + { + // see if the bounding box lets us trivially reject, also sets + if (!IEngineStudio.StudioCheckBBox()) + return 0; + + (*m_pModelsDrawn)++; + (*m_pStudioModelCount)++; // render data cache cookie + + if (m_pStudioHeader->numbodyparts == 0) + return 1; + } + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + StudioSetupBones(); + StudioSaveBones(); + + m_pPlayerInfo->renderframe = m_nFrameCount; + m_pPlayerInfo = nullptr; + + if ((flags & STUDIO_EVENTS) && (!(flags & STUDIO_RENDER) || !pplayer->weaponmodel || !WeaponHasAttachments(pplayer))) + { + StudioCalcAttachments(); + IEngineStudio.StudioClientEvents(); + + // copy attachments into global entity array + if (m_pCurrentEntity->index > 0) + { + cl_entity_t *ent = gEngfuncs.GetEntityByIndex(m_pCurrentEntity->index); + + Q_memcpy(ent->attachment, m_pCurrentEntity->attachment, sizeof(ent->attachment)); + } + } + + if (flags & STUDIO_RENDER) + { + //if (m_pCvarHiModels->value && m_pRenderModel != m_pCurrentEntity->model) + //{ + // // show highest resolution multiplayer model + // m_pCurrentEntity->curstate.body = 255; + //} + + //if (!(m_pCvarDeveloper->value == 0 && gEngfuncs.GetMaxClients() == 1) && (m_pRenderModel == m_pCurrentEntity->model)) + //{ + // m_pCurrentEntity->curstate.body = 1; // force helmet + //} + + vec3_t dir; + alight_t lighting; + lighting.plightvec = dir; + IEngineStudio.StudioDynamicLight(m_pCurrentEntity, &lighting); + IEngineStudio.StudioEntityLight(&lighting); + IEngineStudio.StudioSetupLighting(&lighting); // model and frame independant + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + + // get remap colors + m_nTopColor = m_pPlayerInfo->topcolor; + if (m_nTopColor < 0) + m_nTopColor = 0; + + if (m_nTopColor > 360) + m_nTopColor = 360; + + m_nBottomColor = m_pPlayerInfo->bottomcolor; + if (m_nBottomColor < 0) + m_nBottomColor = 0; + + if (m_nBottomColor > 360) + m_nBottomColor = 360; + + IEngineStudio.StudioSetRemapColors(m_nTopColor, m_nBottomColor); + + StudioRenderModel(); + m_pPlayerInfo = nullptr; + + if (pplayer->weaponmodel) + { + studiohdr_t *saveheader = m_pStudioHeader; + cl_entity_t saveent = *m_pCurrentEntity; + + model_t *pweaponmodel = IEngineStudio.GetModelByIndex(pplayer->weaponmodel); + + m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata(pweaponmodel); + IEngineStudio.StudioSetHeader(m_pStudioHeader); + + StudioMergeBones(pweaponmodel); + IEngineStudio.StudioSetupLighting(&lighting); + + // no draw weaponmodel only the player + if (!m_pPlayerSync) + { + StudioRenderModel(); + } + + StudioCalcAttachments(); + + if (m_pCurrentEntity->index > 0) + { + Q_memcpy(saveent.attachment, m_pCurrentEntity->attachment, m_pStudioHeader->numattachments * sizeof(vec3_t)); + } + + *m_pCurrentEntity = saveent; + m_pStudioHeader = saveheader; + + IEngineStudio.StudioSetHeader(m_pStudioHeader); + + if (flags & STUDIO_EVENTS) + { + IEngineStudio.StudioClientEvents(); + } + } + + if (cl_shadows && cl_shadows->value) + { + Vector start; + if (GetPlayerBoneWorldPosition(BONE_PELVIS, start)) + { + StudioDrawShadow(start, 20); + } + } + } + + return 1; +} + +void CGameStudioModelRenderer::StudioFxTransform(cl_entity_t *ent, float transform[3][4]) +{ + switch (ent->curstate.renderfx) + { + case kRenderFxDistort: + case kRenderFxHologram: + { + if (gEngfuncs.pfnRandomLong(0, 49) == 0) + { + int axis = gEngfuncs.pfnRandomLong(0, 1); + if (axis == 1) // Choose between x & z + axis = 2; + + VectorScale(transform[axis], gEngfuncs.pfnRandomFloat(1, 1.484), transform[axis]); + } + else if (gEngfuncs.pfnRandomLong(0, 49) == 0) + { + float offset; + int axis = gEngfuncs.pfnRandomLong(0, 1); + if (axis == 1) // Choose between x & z + axis = 2; + + offset = gEngfuncs.pfnRandomFloat(-10, 10); + transform[gEngfuncs.pfnRandomLong(0, 2)][3] += offset; + } + break; + } + case kRenderFxExplode: + { + if (g_iRenderStateChanged) + { + g_flStartScaleTime = m_clTime; + g_iRenderStateChanged = FALSE; + } + + // Make the Model continue to shrink + float flTimeDelta = m_clTime - g_flStartScaleTime; + if (flTimeDelta > 0) + { + float flScale = 0.001; + // Goes almost all away + if (flTimeDelta <= 2.0) + flScale = 1.0 - (flTimeDelta / 2.0); + + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + transform[i][j] *= flScale; + } + } + break; + } + } +} + +void CGameStudioModelRenderer::StudioPlayerBlend(mstudioseqdesc_t *pseqdesc, int *pBlend, float *pPitch) +{ + float range = 45.0; + + *pBlend = (*pPitch * 3); + + if (*pBlend <= -range) + *pBlend = 255; + else if (*pBlend >= range) + *pBlend = 0; + else + *pBlend = 255 * (range - *pBlend) / (2 * range); + + *pPitch = 0; +} + +void CGameStudioModelRenderer::CalculatePitchBlend(entity_state_t *pplayer) +{ + int iBlend; + mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + + StudioPlayerBlend(pseqdesc, &iBlend, &m_pCurrentEntity->angles[PITCH]); + + m_pCurrentEntity->latched.prevangles[PITCH] = m_pCurrentEntity->angles[PITCH]; + m_pCurrentEntity->curstate.blending[1] = iBlend; + m_pCurrentEntity->latched.prevblending[1] = m_pCurrentEntity->curstate.blending[1]; + m_pCurrentEntity->latched.prevseqblending[1] = m_pCurrentEntity->curstate.blending[1]; +} + +void CGameStudioModelRenderer::CalculateYawBlend(entity_state_t *pplayer) +{ + StudioEstimateGait(pplayer); + + // calc side to side turning + float flYaw = fmod(m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw, 360.0f); + + if (flYaw < -180) + flYaw += 360; + else if (flYaw > 180) + flYaw -= 360; + + if (m_flGaitMovement) + { + float maxyaw = 120.0; + if (flYaw > maxyaw) + { + flYaw -= 180; + m_pPlayerInfo->gaityaw -= 180; + m_flGaitMovement = -m_flGaitMovement; + } + else if (flYaw < -maxyaw) + { + flYaw += 180; + m_pPlayerInfo->gaityaw += 180; + m_flGaitMovement = -m_flGaitMovement; + } + } + + float blend_yaw = (flYaw / 90.0) * 128.0 + 127.0; + blend_yaw = clamp(blend_yaw, 0.0f, 255.0f); + blend_yaw = 255.0 - blend_yaw; + + m_pCurrentEntity->curstate.blending[0] = (int)(blend_yaw); + m_pCurrentEntity->latched.prevblending[0] = m_pCurrentEntity->curstate.blending[0]; + m_pCurrentEntity->latched.prevseqblending[0] = m_pCurrentEntity->curstate.blending[0]; + m_pCurrentEntity->angles[YAW] = m_pPlayerInfo->gaityaw; + + if (m_pCurrentEntity->angles[YAW] < 0) + m_pCurrentEntity->angles[YAW] += 360; + + m_pCurrentEntity->latched.prevangles[YAW] = m_pCurrentEntity->angles[YAW]; +} + +// Hooks to class implementation +int R_StudioDrawPlayer(int flags, entity_state_t *pplayer) +{ + return g_StudioRenderer.StudioDrawPlayer(flags, pplayer); +} + +int R_StudioDrawModel(int flags) +{ + return g_StudioRenderer.StudioDrawModel(flags); +} + +void R_StudioInit() +{ + g_StudioRenderer.Init(); +} + +// The simple drawing interface we'll pass back to the engine +r_studio_interface_t studio = +{ + STUDIO_INTERFACE_VERSION, + R_StudioDrawModel, + R_StudioDrawPlayer, +}; + +// Export this function for the engine to use the studio renderer class to render objects. +int HUD_GetStudioModelInterface(int version, r_studio_interface_t **ppinterface, engine_studio_api_t *pstudio) +{ + if (version != STUDIO_INTERFACE_VERSION) + return 0; + + gClientfuncs.pStudioInterface(version, ppinterface, pstudio); + + // Point the engine to our callbacks + *ppinterface = &studio; + + // Copy in engine helper functions + Q_memcpy(&IEngineStudio, pstudio, sizeof(IEngineStudio)); + + // Initialize local variables, etc. + R_StudioInit(); + + if (!g_EngineLib->StudioLightingInit()) + { + g_EngineLib->TraceLog("> %s: not found R_StudioLighting\n", __FUNCTION__); + } + + // Success + return 1; +} diff --git a/hitboxtracker/client/src/studio/GameStudioModelRenderer.h b/hitboxtracker/client/src/studio/GameStudioModelRenderer.h new file mode 100644 index 0000000..e8aaf01 --- /dev/null +++ b/hitboxtracker/client/src/studio/GameStudioModelRenderer.h @@ -0,0 +1,102 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "studio_util.h" +#include "studio/StudioModelRenderer.h" + +#define NUM_BLENDING 9 + +#define ANIM_WALK_SEQUENCE 3 +#define ANIM_JUMP_SEQUENCE 6 +#define ANIM_SWIM_1 8 +#define ANIM_SWIM_2 9 +#define ANIM_FIRST_DEATH_SEQUENCE 101 + +enum BoneIndex +{ + BONE_HEAD = 0, + BONE_PELVIS, + BONE_SPINE1, + BONE_SPINE2, + BONE_SPINE3, + + BONE_MAX, +}; + +class CGameStudioModelRenderer: public CStudioModelRenderer +{ +public: + CGameStudioModelRenderer(); + + // Set up model bone positions + virtual void StudioSetupBones(); + + // Estimate gait frame for player + virtual void StudioEstimateGait(entity_state_t *pplayer); + + // Process movement of player + virtual void StudioProcessGait(entity_state_t *pplayer); + + // Player drawing code + virtual int StudioDrawPlayer(int flags, entity_state_t *pplayer); + virtual int _StudioDrawPlayer(int flags, entity_state_t *pplayer); + + // Apply special effects to transform matrix + virtual void StudioFxTransform(cl_entity_t *ent, float transform[3][4]); + + // Player specific data + // Determine pitch and blending amounts for players + virtual void StudioPlayerBlend(mstudioseqdesc_t *pseqdesc, int *pBlend, float *pPitch); + virtual void CalculateYawBlend(entity_state_t *pplayer); + virtual void CalculatePitchBlend(entity_state_t *pplayer); + +private: + // For local player, in third person, we need to store real render + // data and then setup for with fake/client side animation data + void SavePlayerState(entity_state_t *pplayer); + void SetupClientAnimation(entity_state_t *pplayer); // Called to set up local player's animation values + void RestorePlayerState(entity_state_t *pplayer); // Called to restore original player state information + + bool GetPlayerBoneWorldPosition(BoneIndex whichBone, Vector &pos); + mstudioanim_t *LookupAnimation(mstudioseqdesc_t *pseqdesc, int index); + void CachePlayerBoneIndices(); + int GetPlayerBoneIndex(BoneIndex whichBone); + +private: + static const char *m_boneNames[]; + + // Private data + int m_nPlayerGaitSequences[MAX_CLIENTS]; + bool m_bLocal; + int m_boneIndexCache[BONE_MAX]; + bool m_isBoneCacheValid; +}; + +extern CGameStudioModelRenderer g_StudioRenderer; diff --git a/hitboxtracker/client/src/studio/StudioModelRenderer.cpp b/hitboxtracker/client/src/studio/StudioModelRenderer.cpp new file mode 100644 index 0000000..f27d0c6 --- /dev/null +++ b/hitboxtracker/client/src/studio/StudioModelRenderer.cpp @@ -0,0 +1,1836 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +int g_bIsCZ = -1; +int g_iRightHandValue; + +// Global engine <-> studio model rendering code interface +engine_studio_api_t IEngineStudio; + +int CStudioModelRenderer::m_boxpnt[6][4] = +{ + { 0, 4, 6, 2 }, + { 0, 1, 5, 4 }, + { 0, 2, 3, 1 }, + { 7, 5, 1, 3 }, + { 7, 3, 2, 6 }, + { 7, 6, 4, 5 }, +}; + +vec3_t CStudioModelRenderer::m_hullcolor[8] = +{ + { 1.0, 1.0, 1.0 }, + { 1.0, 0.5, 0.5 }, + { 0.5, 1.0, 0.5 }, + { 1.0, 1.0, 0.5 }, + { 0.5, 0.5, 1.0 }, + { 1.0, 0.5, 1.0 }, + { 0.5, 1.0, 1.0 }, + { 1.0, 1.0, 1.0 }, +}; + +void CStudioModelRenderer::Init() +{ + // Set up some variables shared with engine + m_pCvarHiModels = IEngineStudio.GetCvar("cl_himodels"); + m_pCvarDeveloper = IEngineStudio.GetCvar("developer"); + m_pCvarDrawEntities = IEngineStudio.GetCvar("r_drawentities"); + m_pChromeSprite = IEngineStudio.GetChromeSprite(); + m_pWhiteSprite = IEngineStudio.Mod_ForName("sprites/white.spr", 1); + + IEngineStudio.GetModelCounters(&m_pStudioModelCount, &m_pModelsDrawn); + + // Get pointers to engine data structures + m_pbonetransform = (float (*)[MAXSTUDIOBONES][3][4])IEngineStudio.StudioGetBoneTransform(); + m_plighttransform = (float (*)[MAXSTUDIOBONES][3][4])IEngineStudio.StudioGetLightTransform(); + m_paliastransform = (float (*)[3][4])IEngineStudio.StudioGetAliasTransform(); + m_protationmatrix = (float (*)[3][4])IEngineStudio.StudioGetRotationMatrix(); +} + +CStudioModelRenderer::CStudioModelRenderer() +{ + m_fGaitEstimation = TRUE; + m_fDoInterp = TRUE; + + m_pCurrentEntity = nullptr; + m_pCvarHiModels = nullptr; + m_pCvarDeveloper = nullptr; + m_pCvarDrawEntities = nullptr; + m_pChromeSprite = nullptr; + m_pStudioModelCount = nullptr; + m_pModelsDrawn = nullptr; + m_protationmatrix = nullptr; + m_paliastransform = nullptr; + m_pbonetransform = nullptr; + m_plighttransform = nullptr; + m_pStudioHeader = nullptr; + m_pBodyPart = nullptr; + m_pSubModel = nullptr; + m_pPlayerInfo = nullptr; + m_pRenderModel = nullptr; +} + +CStudioModelRenderer::~CStudioModelRenderer() +{ +} + +void CStudioModelRenderer::StudioCalcBoneAdj(float dadt, float *adj, const byte *pcontroller1, const byte *pcontroller2, byte mouthopen) +{ + int i, j; + float value; + mstudiobonecontroller_t *pbonecontroller; + + pbonecontroller = (mstudiobonecontroller_t *)((byte *)m_pStudioHeader + m_pStudioHeader->bonecontrollerindex); + + for (j = 0; j < m_pStudioHeader->numbonecontrollers; j++) + { + i = pbonecontroller[j].index; + if (i >= STUDIO_MOUTH) + { + // mouth hardcoded at controller 4 + value = mouthopen / 64.0; + if (value > 1.0) + value = 1.0; + + value = (1.0 - value) * pbonecontroller[j].start + value * pbonecontroller[j].end; + //Con_DPrintf("%d %f\n", mouthopen, value); + } + else + { + // check for 360% wrapping + if (pbonecontroller[j].type & STUDIO_RLOOP) + { + if (abs(pcontroller1[i] - pcontroller2[i]) > 128) + { + int a, b; + a = (pcontroller1[j] + 128) % 256; + b = (pcontroller2[j] + 128) % 256; + value = ((a * dadt) + (b * (1 - dadt)) - 128) * (360.0 / 256.0) + pbonecontroller[j].start; + } + else + { + value = ((pcontroller1[i] * dadt + (pcontroller2[i]) * (1.0 - dadt))) * (360.0 / 256.0) + pbonecontroller[j].start; + } + } + else + { + value = (pcontroller1[i] * dadt + pcontroller2[i] * (1.0 - dadt)) / 255.0; + value = clamp(value, 0.0f, 1.0f); + value = (1.0 - value) * pbonecontroller[j].start + value * pbonecontroller[j].end; + } + + //Con_DPrintf("%d %d %f : %f\n", m_pCurrentEntity->curstate.controller[j], m_pCurrentEntity->latched.prevcontroller[j], value, dadt); + } + + switch (pbonecontroller[j].type & STUDIO_TYPES) + { + case STUDIO_XR: + case STUDIO_YR: + case STUDIO_ZR: + adj[j] = value * (M_PI / 180.0); + break; + case STUDIO_X: + case STUDIO_Y: + case STUDIO_Z: + adj[j] = value; + break; + } + } +} + +void CStudioModelRenderer::StudioCalcBoneQuaterion(int frame, float s, mstudiobone_t *pbone, mstudioanim_t *panim, float *adj, float *q) +{ + int j, k; + vec4_t q1, q2; + vec3_t angle1, angle2; + mstudioanimvalue_t *panimvalue; + + for (j = 0; j < 3; j++) + { + if (panim->offset[j + 3] == 0) + { + angle2[j] = angle1[j] = pbone->value[j + 3]; // default; + } + else + { + panimvalue = (mstudioanimvalue_t *)((byte *)panim + panim->offset[j + 3]); + + // DEBUG + k = frame; + if (panimvalue->num.total < panimvalue->num.valid) + k = 0; + + while (panimvalue->num.total <= k) + { + k -= panimvalue->num.total; + panimvalue += panimvalue->num.valid + 1; + + // DEBUG + if (panimvalue->num.total < panimvalue->num.valid) + k = 0; + } + + // Bah, missing blend! + if (panimvalue->num.valid > k) + { + angle1[j] = panimvalue[k + 1].value; + + if (panimvalue->num.valid > k + 1) + { + angle2[j] = panimvalue[k + 2].value; + } + else + { + if (panimvalue->num.total > k + 1) + angle2[j] = angle1[j]; + else + angle2[j] = panimvalue[panimvalue->num.valid + 2].value; + } + } + else + { + angle1[j] = panimvalue[panimvalue->num.valid].value; + + if (panimvalue->num.total > k + 1) + { + angle2[j] = angle1[j]; + } + else + { + angle2[j] = panimvalue[panimvalue->num.valid + 2].value; + } + } + + angle1[j] = pbone->value[j + 3] + angle1[j] * pbone->scale[j + 3]; + angle2[j] = pbone->value[j + 3] + angle2[j] * pbone->scale[j + 3]; + } + + if (pbone->bonecontroller[j + 3] != -1) + { + angle1[j] += adj[pbone->bonecontroller[j + 3]]; + angle2[j] += adj[pbone->bonecontroller[j + 3]]; + } + } + + if (!VectorCompare(angle1, angle2)) + { + AngleQuaternion(angle1, q1); + AngleQuaternion(angle2, q2); + QuaternionSlerp(q1, q2, s, q); + } + else + { + AngleQuaternion(angle1, q); + } +} + +void CStudioModelRenderer::StudioCalcBonePosition(int frame, float s, mstudiobone_t *pbone, mstudioanim_t *panim, float *adj, float *pos) +{ + int j, k; + mstudioanimvalue_t *panimvalue; + + for (j = 0; j < 3; j++) + { + pos[j] = pbone->value[j]; // default; + + if (panim->offset[j] != 0) + { + panimvalue = (mstudioanimvalue_t *)((byte *)panim + panim->offset[j]); + + //if (i == 0 && j == 0) + // Con_DPrintf("%d %d:%d %f\n", frame, panimvalue->num.valid, panimvalue->num.total, s); + + // DEBUG + k = frame; + if (panimvalue->num.total < panimvalue->num.valid) + k = 0; + + // find span of values that includes the frame we want + while (panimvalue->num.total <= k) + { + k -= panimvalue->num.total; + panimvalue += panimvalue->num.valid + 1; + + // DEBUG + if (panimvalue->num.total < panimvalue->num.valid) + k = 0; + } + + // if we're inside the span + if (panimvalue->num.valid > k) + { + // and there's more data in the span + if (panimvalue->num.valid > k + 1) + { + pos[j] += (panimvalue[k + 1].value * (1.0 - s) + s * panimvalue[k + 2].value) * pbone->scale[j]; + } + else + { + pos[j] += panimvalue[k + 1].value * pbone->scale[j]; + } + } + else + { + // are we at the end of the repeating values section and there's another section with data? + if (panimvalue->num.total <= k + 1) + { + pos[j] += (panimvalue[panimvalue->num.valid].value * (1.0 - s) + s * panimvalue[panimvalue->num.valid + 2].value) * pbone->scale[j]; + } + else + { + pos[j] += panimvalue[panimvalue->num.valid].value * pbone->scale[j]; + } + } + } + + if (pbone->bonecontroller[j] != -1 && adj) + { + pos[j] += adj[pbone->bonecontroller[j]]; + } + } +} + +void CStudioModelRenderer::StudioSlerpBones(vec4_t q1[], float pos1[][3], vec4_t q2[], float pos2[][3], float s) +{ + vec4_t q3; + float s1; + + s = clamp(s, 0.0f, 1.0f); + s1 = 1.0 - s; + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + QuaternionSlerp(q1[i], q2[i], s, q3); + + q1[i][0] = q3[0]; + q1[i][1] = q3[1]; + q1[i][2] = q3[2]; + q1[i][3] = q3[3]; + + pos1[i][0] = pos1[i][0] * s1 + pos2[i][0] * s; + pos1[i][1] = pos1[i][1] * s1 + pos2[i][1] * s; + pos1[i][2] = pos1[i][2] * s1 + pos2[i][2] * s; + } +} + +mstudioanim_t *CStudioModelRenderer::StudioGetAnim(model_t *psubmodel, mstudioseqdesc_t *pseqdesc) +{ + mstudioseqgroup_t *pseqgroup; + cache_user_t *paSequences; + + pseqgroup = (mstudioseqgroup_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqgroupindex) + pseqdesc->seqgroup; + + if (pseqdesc->seqgroup == 0) + { + return (mstudioanim_t *)((byte *)m_pStudioHeader + pseqdesc->animindex); + } + + paSequences = (cache_user_t *)psubmodel->submodels; + + if (!paSequences) + { + paSequences = (cache_user_t *)IEngineStudio.Mem_Calloc(MAXSTUDIOGROUPS, sizeof(cache_user_t)); // UNDONE: leak! + psubmodel->submodels = (dmodel_t *)paSequences; + } + + if (!IEngineStudio.Cache_Check((struct cache_user_s *)&(paSequences[pseqdesc->seqgroup]))) + { + gEngfuncs.Con_DPrintf("loading %s\n", pseqgroup->name); + IEngineStudio.LoadCacheFile(pseqgroup->name, (struct cache_user_s *)&paSequences[pseqdesc->seqgroup]); + } + + return (mstudioanim_t *)((byte *)paSequences[pseqdesc->seqgroup].data + pseqdesc->animindex); +} + +void CStudioModelRenderer::StudioPlayerBlend(mstudioseqdesc_t *pseqdesc, int *pBlend, float *pPitch) +{ + // calc up/down pointing + *pBlend = (*pPitch * 3); + if (*pBlend < pseqdesc->blendstart[0]) + { + *pPitch -= pseqdesc->blendstart[0] / 3.0; + *pBlend = 0; + } + else if (*pBlend > pseqdesc->blendend[0]) + { + *pPitch -= pseqdesc->blendend[0] / 3.0; + *pBlend = 255; + } + else + { + if (pseqdesc->blendend[0] - pseqdesc->blendstart[0] < 0.1) // catch qc error + *pBlend = 127; + else + *pBlend = 255 * (*pBlend - pseqdesc->blendstart[0]) / (pseqdesc->blendend[0] - pseqdesc->blendstart[0]); + *pPitch = 0; + } +} + +void CStudioModelRenderer::StudioSetUpTransform(int trivial_accept) +{ + vec3_t angles, modelpos; + + VectorCopy(m_pCurrentEntity->origin, modelpos); + + // TODO: should really be stored with the entity instead of being reconstructed + // TODO: should use a look-up table + // TODO: could cache lazily, stored in the entity + angles[ROLL] = m_pCurrentEntity->curstate.angles[ROLL]; + angles[PITCH] = m_pCurrentEntity->curstate.angles[PITCH]; + angles[YAW] = m_pCurrentEntity->curstate.angles[YAW]; + + if (m_pCurrentEntity->curstate.movetype != MOVETYPE_NONE) + { + VectorCopy(m_pCurrentEntity->angles, angles); + } + + angles[PITCH] = -angles[PITCH]; + AngleMatrix(angles, (*m_protationmatrix)); + + if (!IEngineStudio.IsHardware()) + { + static float viewmatrix[3][4]; + + VectorCopy(m_vRight, viewmatrix[0]); + VectorCopy(m_vUp, viewmatrix[1]); + VectorInverse(viewmatrix[1]); + VectorCopy(m_vNormal, viewmatrix[2]); + + (*m_protationmatrix)[0][3] = modelpos[0] - m_vRenderOrigin[0]; + (*m_protationmatrix)[1][3] = modelpos[1] - m_vRenderOrigin[1]; + (*m_protationmatrix)[2][3] = modelpos[2] - m_vRenderOrigin[2]; + + ConcatTransforms(viewmatrix, (*m_protationmatrix), (*m_paliastransform)); + + // do the scaling up of x and y to screen coordinates as part of the transform + // for the unclipped case (it would mess up clipping in the clipped case). + // Also scale down z, so 1/z is scaled 31 bits for free, and scale down x and y + // correspondingly so the projected x and y come out right + // FIXME: make this work for clipped case too? + if (trivial_accept) + { + for (int i = 0; i < 4; i++) + { + (*m_paliastransform)[0][i] *= m_fSoftwareXScale * (1.0 / (ZISCALE * 0x10000)); + (*m_paliastransform)[1][i] *= m_fSoftwareYScale * (1.0 / (ZISCALE * 0x10000)); + (*m_paliastransform)[2][i] *= 1.0 / (ZISCALE * 0x10000); + + } + } + } + + (*m_protationmatrix)[0][3] = modelpos[0]; + (*m_protationmatrix)[1][3] = modelpos[1]; + (*m_protationmatrix)[2][3] = modelpos[2]; +} + +float CStudioModelRenderer::StudioEstimateInterpolant() +{ + float dadt = 1.0; + if (m_fDoInterp && (m_pCurrentEntity->curstate.animtime >= m_pCurrentEntity->latched.prevanimtime + 0.01)) + { + dadt = (m_clTime - m_pCurrentEntity->curstate.animtime) / 0.1; + if (dadt > 2.0) + { + dadt = 2.0; + } + } + + return dadt; +} + +void CStudioModelRenderer::StudioCalcRotations(float pos[][3], vec4_t *q, mstudioseqdesc_t *pseqdesc, mstudioanim_t *panim, float f) +{ + int frame; + mstudiobone_t *pbone; + + float s; + float adj[MAXSTUDIOCONTROLLERS]; + float dadt; + + if (f > pseqdesc->numframes - 1) + { + f = 0; // bah, fix this bug with changing sequences too fast + } + + // BUG (somewhere else) but this code should validate this data. + // This could cause a crash if the frame # is negative, so we'll go ahead + // and clamp it here + else if (f < -0.01) + { + f = -0.01; + } + + frame = (int)f; + + //Con_DPrintf("%d %.4f %.4f %.4f %.4f %d\n", m_pCurrentEntity->curstate.sequence, m_clTime, m_pCurrentEntity->animtime, m_pCurrentEntity->frame, f, frame); + //Con_DPrintf("%f %f %f\n", m_pCurrentEntity->angles[ROLL], m_pCurrentEntity->angles[PITCH], m_pCurrentEntity->angles[YAW]); + //Con_DPrintf("frame %d %d\n", frame1, frame2); + + dadt = StudioEstimateInterpolant(); + s = (f - frame); + + // add in programtic controllers + pbone = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + StudioCalcBoneAdj(dadt, adj, m_pCurrentEntity->curstate.controller, m_pCurrentEntity->latched.prevcontroller, m_pCurrentEntity->mouth.mouthopen); + + for (int i = 0; i < m_pStudioHeader->numbones; i++, pbone++, panim++) + { + StudioCalcBoneQuaterion(frame, s, pbone, panim, adj, q[i]); + StudioCalcBonePosition(frame, s, pbone, panim, adj, pos[i]); + + //if (0 && i == 0) + // Con_DPrintf("%d %d %d %d\n", m_pCurrentEntity->curstate.sequence, frame, j, k); + } + + if (pseqdesc->motiontype & STUDIO_X) + { + pos[pseqdesc->motionbone][0] = 0.0; + } + if (pseqdesc->motiontype & STUDIO_Y) + { + pos[pseqdesc->motionbone][1] = 0.0; + } + if (pseqdesc->motiontype & STUDIO_Z) + { + pos[pseqdesc->motionbone][2] = 0.0; + } + + s = 0 * ((1.0 - (f - (int)(f))) / (pseqdesc->numframes)) * m_pCurrentEntity->curstate.framerate; + + if (pseqdesc->motiontype & STUDIO_LX) + { + pos[pseqdesc->motionbone][0] += s * pseqdesc->linearmovement[0]; + } + if (pseqdesc->motiontype & STUDIO_LY) + { + pos[pseqdesc->motionbone][1] += s * pseqdesc->linearmovement[1]; + } + if (pseqdesc->motiontype & STUDIO_LZ) + { + pos[pseqdesc->motionbone][2] += s * pseqdesc->linearmovement[2]; + } +} + +void CStudioModelRenderer::StudioFxTransform(cl_entity_t *ent, float transform[3][4]) +{ + switch (ent->curstate.renderfx) + { + case kRenderFxDistort: + case kRenderFxHologram: + { + if (gEngfuncs.pfnRandomLong(0, 49) == 0) + { + int axis = gEngfuncs.pfnRandomLong(0, 1); + if (axis == 1) // Choose between x & z + axis = 2; + + VectorScale(transform[axis], gEngfuncs.pfnRandomFloat(1, 1.484), transform[axis]); + } + else if (gEngfuncs.pfnRandomLong(0, 49) == 0) + { + float offset; + int axis = gEngfuncs.pfnRandomLong(0, 1); + if (axis == 1) // Choose between x & z + axis = 2; + + offset = gEngfuncs.pfnRandomFloat(-10, 10); + transform[gEngfuncs.pfnRandomLong(0, 2)][3] += offset; + } + break; + } + case kRenderFxExplode: + { + float scale = 1.0 + (m_clTime - ent->curstate.animtime) * 10.0; + if (scale > 2) // Don't blow up more than 200% + scale = 2; + + transform[0][1] *= scale; + transform[1][1] *= scale; + transform[2][1] *= scale; + break; + } + } +} + +float CStudioModelRenderer::StudioEstimateFrame(mstudioseqdesc_t *pseqdesc) +{ + double dfdt, f; + + if (m_fDoInterp) + { + if (m_clTime < m_pCurrentEntity->curstate.animtime) + { + dfdt = 0; + } + else + { + dfdt = (m_clTime - m_pCurrentEntity->curstate.animtime) * m_pCurrentEntity->curstate.framerate * pseqdesc->fps; + } + } + else + { + dfdt = 0; + } + + if (pseqdesc->numframes <= 1) + { + f = 0; + } + else + { + f = (m_pCurrentEntity->curstate.frame * (pseqdesc->numframes - 1)) / 256.0; + } + + f += dfdt; + + if (pseqdesc->flags & STUDIO_LOOPING) + { + if (pseqdesc->numframes > 1) + { + f -= (int)(f / (pseqdesc->numframes - 1)) * (pseqdesc->numframes - 1); + } + + if (f < 0) + { + f += (pseqdesc->numframes - 1); + } + } + else + { + if (f >= pseqdesc->numframes - 1.001) + { + f = pseqdesc->numframes - 1.001; + } + + if (f < 0.0) + { + f = 0.0; + } + } + + return f; +} + +void CStudioModelRenderer::StudioSetupBones() +{ + double f; + + mstudiobone_t *pbones; + mstudioseqdesc_t *pseqdesc; + mstudioanim_t *panim; + + static float pos[MAXSTUDIOBONES][3]; + static vec4_t q[MAXSTUDIOBONES]; + float bonematrix[3][4]; + + static float pos2[MAXSTUDIOBONES][3]; + static vec4_t q2[MAXSTUDIOBONES]; + static float pos3[MAXSTUDIOBONES][3]; + static vec4_t q3[MAXSTUDIOBONES]; + static float pos4[MAXSTUDIOBONES][3]; + static vec4_t q4[MAXSTUDIOBONES]; + + if (m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq || m_pCurrentEntity->curstate.sequence < 0) + { + m_pCurrentEntity->curstate.sequence = 0; + } + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + + // always want new gait sequences to start on frame zero +/* if (m_pPlayerInfo) + { + int playerNum = m_pCurrentEntity->index - 1; + + // new jump gaitsequence? start from frame zero + if (m_nPlayerGaitSequences[playerNum] != m_pPlayerInfo->gaitsequence) + { + //m_pPlayerInfo->gaitframe = 0.0; + gEngfuncs.Con_Printf("Setting gaitframe to 0\n"); + } + + m_nPlayerGaitSequences[playerNum] = m_pPlayerInfo->gaitsequence; + //gEngfuncs.Con_Printf("index: %d gaitsequence: %d\n",playerNum, m_pPlayerInfo->gaitsequence); + } +*/ + f = StudioEstimateFrame(pseqdesc); + + if (m_pCurrentEntity->latched.prevframe > f) + { + //Con_DPrintf("%f %f\n", m_pCurrentEntity->prevframe, f); + } + + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + StudioCalcRotations(pos, q, pseqdesc, panim, (int)f); // TODO: CHECK ME cast from float to int and to float + + if (pseqdesc->numblends > 1) + { + float s; + float dadt; + + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos2, q2, pseqdesc, panim, f); + + dadt = StudioEstimateInterpolant(); + s = (m_pCurrentEntity->curstate.blending[0] * dadt + m_pCurrentEntity->latched.prevblending[0] * (1.0 - dadt)) / 255.0; + + StudioSlerpBones(q, pos, q2, pos2, s); + + if (pseqdesc->numblends == 4) + { + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos3, q3, pseqdesc, panim, f); + + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos4, q4, pseqdesc, panim, f); + + s = (m_pCurrentEntity->curstate.blending[0] * dadt + m_pCurrentEntity->latched.prevblending[0] * (1.0 - dadt)) / 255.0; + StudioSlerpBones(q3, pos3, q4, pos4, s); + + s = (m_pCurrentEntity->curstate.blending[1] * dadt + m_pCurrentEntity->latched.prevblending[1] * (1.0 - dadt)) / 255.0; + StudioSlerpBones(q, pos, q3, pos3, s); + } + } + + if (m_fDoInterp && + m_pCurrentEntity->latched.sequencetime && + (m_pCurrentEntity->latched.sequencetime + 0.2 > m_clTime) && + (m_pCurrentEntity->latched.prevsequence < m_pStudioHeader->numseq)) + { + // blend from last sequence + static float pos1b[MAXSTUDIOBONES][3]; + static vec4_t q1b[MAXSTUDIOBONES]; + float s; + + //if (m_pCurrentEntity->latched.prevsequence >= m_pStudioHeader->numseq) + //{ + // m_pCurrentEntity->latched.prevsequence = 0; + //} + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->latched.prevsequence; + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + + // clip prevframe + StudioCalcRotations(pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + if (pseqdesc->numblends > 1) + { + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + s = (m_pCurrentEntity->latched.prevseqblending[0]) / 255.0; + StudioSlerpBones(q1b, pos1b, q2, pos2, s); + + if (pseqdesc->numblends == 4) + { + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos3, q3, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + panim += m_pStudioHeader->numbones; + StudioCalcRotations(pos4, q4, pseqdesc, panim, m_pCurrentEntity->latched.prevframe); + + s = (m_pCurrentEntity->latched.prevseqblending[0]) / 255.0; + StudioSlerpBones(q3, pos3, q4, pos4, s); + + s = (m_pCurrentEntity->latched.prevseqblending[1]) / 255.0; + StudioSlerpBones(q1b, pos1b, q3, pos3, s); + } + } + + s = 1.0 - (m_clTime - m_pCurrentEntity->latched.sequencetime) / 0.2; + StudioSlerpBones(q, pos, q1b, pos1b, s); + } + else + { + //Con_DPrintf("prevframe = %4.2f\n", f); + m_pCurrentEntity->latched.prevframe = f; + } + + pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + // bounds checking + //if (m_pPlayerInfo) + //{ + // if (m_pPlayerInfo->gaitsequence >= m_pStudioHeader->numseq) + // { + // m_pPlayerInfo->gaitsequence = 0; + // } + //} + + // calc gait animation + if (m_pPlayerInfo && m_pPlayerInfo->gaitsequence != 0) + { + //if (m_pPlayerInfo->gaitsequence >= m_pStudioHeader->numseq) + //{ + // m_pPlayerInfo->gaitsequence = 0; + //} + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pPlayerInfo->gaitsequence; + + panim = StudioGetAnim(m_pRenderModel, pseqdesc); + StudioCalcRotations(pos2, q2, pseqdesc, panim, m_pPlayerInfo->gaitframe); + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + if (!Q_strcmp(pbones[i].name, "Bip01 Spine")) + break; + + Q_memcpy(pos[i], pos2[i], sizeof(pos[i])); + Q_memcpy(q[i], q2[i], sizeof(q[i])); + } + } + + cl_entity_t *pViewModel = gEngfuncs.GetViewModel(); + bool bIsViewModel = (pViewModel && pViewModel == m_pCurrentEntity) ? true : false; + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + QuaternionMatrix(q[i], bonematrix); + + bonematrix[0][3] = pos[i][0]; + bonematrix[1][3] = pos[i][1]; + bonematrix[2][3] = pos[i][2]; + + if (pbones[i].parent == -1) + { + if ((cl_righthand && cl_righthand->value && bIsViewModel && IEngineStudio.IsHardware() && !g_bHoldingShield) + || (g_bIsCZ && bIsViewModel && IEngineStudio.IsHardware() && g_bHoldingShield)) + { + bonematrix[1][0] = bonematrix[1][0] * -1.0; + bonematrix[1][1] = bonematrix[1][1] * -1.0; + bonematrix[1][2] = bonematrix[1][2] * -1.0; + bonematrix[1][3] = bonematrix[1][3] * -1.0; + } + + if (IEngineStudio.IsHardware()) + { + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_pbonetransform)[i]); + + // MatrixCopy should be faster... + //ConcatTransforms((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]); + MatrixCopy((*m_pbonetransform)[i], (*m_plighttransform)[i]); + } + else + { + ConcatTransforms((*m_paliastransform), bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]); + } + + // Apply client-side effects to the transformation matrix + StudioFxTransform(m_pCurrentEntity, (*m_pbonetransform)[i]); + } + else + { + ConcatTransforms((*m_pbonetransform)[pbones[i].parent], bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_plighttransform)[pbones[i].parent], bonematrix, (*m_plighttransform)[i]); + } + } +} + +void CStudioModelRenderer::StudioSaveBones() +{ + mstudiobone_t *pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + m_nCachedBones = m_pStudioHeader->numbones; + + for (int i = 0; i < m_pStudioHeader->numbones; i++) + { + Q_strlcpy(m_nCachedBoneNames[i], pbones[i].name); + MatrixCopy((*m_pbonetransform)[i], m_rgCachedBoneTransform[i]); + MatrixCopy((*m_plighttransform)[i], m_rgCachedLightTransform[i]); + } +} + +void CStudioModelRenderer::StudioMergeBones(model_t *psubmodel) +{ + int i, j; + double f; + int do_hunt = true; + + mstudiobone_t *pbones; + mstudioseqdesc_t *pseqdesc; + mstudioanim_t *panim; + + static float pos[MAXSTUDIOBONES][3]; + float bonematrix[3][4]; + static vec4_t q[MAXSTUDIOBONES]; + + if (m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq || m_pCurrentEntity->curstate.sequence < 0) + { + m_pCurrentEntity->curstate.sequence = 0; + } + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + + f = StudioEstimateFrame(pseqdesc); + + if (m_pCurrentEntity->latched.prevframe > f) + { + // Con_DPrintf("%f %f\n", m_pCurrentEntity->prevframe, f); + } + + panim = StudioGetAnim(psubmodel, pseqdesc); + StudioCalcRotations(pos, q, pseqdesc, panim, f); + + pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + for (i = 0; i < m_pStudioHeader->numbones; i++) + { + for (j = 0; j < m_nCachedBones; j++) + { + if (Q_stricmp(pbones[i].name, m_nCachedBoneNames[j]) == 0) + { + MatrixCopy(m_rgCachedBoneTransform[j], (*m_pbonetransform)[i]); + MatrixCopy(m_rgCachedLightTransform[j], (*m_plighttransform)[i]); + break; + } + } + + if (j >= m_nCachedBones) + { + QuaternionMatrix(q[i], bonematrix); + + bonematrix[0][3] = pos[i][0]; + bonematrix[1][3] = pos[i][1]; + bonematrix[2][3] = pos[i][2]; + + if (pbones[i].parent == -1) + { + if (IEngineStudio.IsHardware()) + { + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_pbonetransform)[i]); + + // MatrixCopy should be faster... + //ConcatTransforms((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]); + MatrixCopy((*m_pbonetransform)[i], (*m_plighttransform)[i]); + } + else + { + ConcatTransforms((*m_paliastransform), bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]); + } + + // Apply client-side effects to the transformation matrix + StudioFxTransform(m_pCurrentEntity, (*m_pbonetransform)[i]); + } + else + { + ConcatTransforms((*m_pbonetransform)[pbones[i].parent], bonematrix, (*m_pbonetransform)[i]); + ConcatTransforms((*m_plighttransform)[pbones[i].parent], bonematrix, (*m_plighttransform)[i]); + } + } + } +} + +int CStudioModelRenderer::StudioDrawModel(int flags) +{ + cl_entity_t *pViewModel = gEngfuncs.GetViewModel(); + m_pCurrentEntity = IEngineStudio.GetCurrentEntity(); + + bool changedRighthand = false; + bool bIsViewModel = (pViewModel && pViewModel == m_pCurrentEntity) ? true : false; + + if (g_bIsCZ == -1) + { + g_bIsCZ = gHUD.IsGame("czero") ? 1 : 0; + } + + if (flags & STUDIO_RENDER) + { + if (g_bIsCZ) + { + if (g_bHoldingShield && bIsViewModel) + { + g_iRightHandValue = cl_righthand->value; + + cl_righthand->value = 1; + changedRighthand = true; + } + } + else + { + if (g_bHoldingKnife && bIsViewModel) + { + g_iRightHandValue = cl_righthand->value; + cl_righthand->value = g_iRightHandValue ? 0 : 1; + changedRighthand = true; + } + } + } + + if (gHUD.m_iFOV < 90) + { + if (Q_strstr(m_pCurrentEntity->model->name, "v_awp") + || Q_strstr(m_pCurrentEntity->model->name, "v_scout") + || Q_strstr(m_pCurrentEntity->model->name, "v_g3sg1") + || Q_strstr(m_pCurrentEntity->model->name, "v_sg550")) + { + return 0; + } + } + + IEngineStudio.GetTimes(&m_nFrameCount, &m_clTime, &m_clOldTime); + IEngineStudio.GetViewInfo(m_vRenderOrigin, m_vUp, m_vRight, m_vNormal); + IEngineStudio.GetAliasScale(&m_fSoftwareXScale, &m_fSoftwareYScale); + + if (m_pCurrentEntity->curstate.renderfx == kRenderFxDeadPlayer) + { + if (m_pCurrentEntity->curstate.renderamt <= 0 || m_pCurrentEntity->curstate.renderamt > gEngfuncs.GetMaxClients()) + return 0; + + // get copy of player + entity_state_t deadplayer = *(IEngineStudio.GetPlayerState(m_pCurrentEntity->curstate.renderamt - 1)); // cl.frames[cl.parsecount & CL_UPDATE_MASK].playerstate[m_pCurrentEntity->curstate.renderamt - 1]; + + // clear weapon, movement state + deadplayer.number = m_pCurrentEntity->curstate.renderamt; + deadplayer.weaponmodel = 0; + deadplayer.gaitsequence = 0; + deadplayer.movetype = MOVETYPE_NONE; + + VectorCopy(m_pCurrentEntity->curstate.angles, deadplayer.angles); + VectorCopy(m_pCurrentEntity->curstate.origin, deadplayer.origin); + + qboolean save_interp = m_fDoInterp; + m_fDoInterp = FALSE; + + // draw as though it were a player + int result = StudioDrawPlayer(flags, &deadplayer); + + m_fDoInterp = save_interp; + return result; + } + + m_pRenderModel = m_pCurrentEntity->model; + m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata(m_pRenderModel); + IEngineStudio.StudioSetHeader(m_pStudioHeader); + IEngineStudio.SetRenderModel(m_pRenderModel); + + StudioSetUpTransform(0); + + if (flags & STUDIO_RENDER) + { + // see if the bounding box lets us trivially reject, also sets + if (!IEngineStudio.StudioCheckBBox()) + return 0; + + (*m_pModelsDrawn)++; + (*m_pStudioModelCount)++; // render data cache cookie + + if (m_pStudioHeader->numbodyparts == 0) + return 1; + } + + if (m_pCurrentEntity->curstate.movetype == MOVETYPE_FOLLOW) + { + StudioMergeBones(m_pRenderModel); + } + else + { + StudioSetupBones(); + } + + StudioSaveBones(); + + if (flags & STUDIO_EVENTS) + { + StudioCalcAttachments(); + IEngineStudio.StudioClientEvents(); + + // copy attachments into global entity array + if (m_pCurrentEntity->index > 0) + { + cl_entity_t *ent = gEngfuncs.GetEntityByIndex(m_pCurrentEntity->index); + Q_memcpy(ent->attachment, m_pCurrentEntity->attachment, sizeof(ent->attachment)); + } + } + + if (flags & STUDIO_RENDER) + { + vec3_t dir; + alight_t lighting; + + lighting.plightvec = dir; + IEngineStudio.StudioDynamicLight(m_pCurrentEntity, &lighting); + IEngineStudio.StudioEntityLight(&lighting); + IEngineStudio.StudioSetupLighting(&lighting); // model and frame independant + + // get remap colors + m_nTopColor = (m_pCurrentEntity->curstate.colormap & 0xFF); + m_nBottomColor = (m_pCurrentEntity->curstate.colormap & 0xFF00) >> 8; + + IEngineStudio.StudioSetRemapColors(m_nTopColor, m_nBottomColor); + StudioRenderModel(); + + if (cl_shadows->value > 0 && (Q_strstr(m_pCurrentEntity->model->name, "hostage") || Q_strstr(m_pCurrentEntity->model->name, "scientist"))) + { + StudioDrawShadow(m_pCurrentEntity->origin, 12); + } + } + + if (changedRighthand) + { + cl_righthand->value = (float)g_iRightHandValue; + } + + return 1; +} + +void CStudioModelRenderer::StudioEstimateGait(entity_state_t *pplayer) +{ + float dt = clamp(m_clTime - m_clOldTime, 0.0, 1.0); + if (dt == 0 || m_pPlayerInfo->renderframe == m_nFrameCount) + { + m_flGaitMovement = 0; + return; + } + + vec3_t est_velocity; + if (m_fGaitEstimation) + { + VectorSubtract(m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin, est_velocity); + VectorCopy(m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin); + m_flGaitMovement = Length(est_velocity); + if (dt <= 0 || m_flGaitMovement / dt < 5) + { + m_flGaitMovement = 0; + est_velocity[0] = 0; + est_velocity[1] = 0; + } + } + else + { + VectorCopy(pplayer->velocity, est_velocity); + m_flGaitMovement = Length(est_velocity) * dt; + } + + if (est_velocity[1] == 0 && est_velocity[0] == 0) + { + float flYawDiff = m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw; + flYawDiff = flYawDiff - (int)(flYawDiff / 360) * 360; + + if (flYawDiff > 180) + flYawDiff -= 360; + + if (flYawDiff < -180) + flYawDiff += 360; + + if (dt < 0.25) + flYawDiff *= dt * 4; + else + flYawDiff *= dt; + + m_pPlayerInfo->gaityaw += flYawDiff; + m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw - (int)(m_pPlayerInfo->gaityaw / 360) * 360; + m_flGaitMovement = 0; + } + else + { + m_pPlayerInfo->gaityaw = (atan2(est_velocity[1], est_velocity[0]) * 180 / M_PI); + + if (m_pPlayerInfo->gaityaw > 180) + m_pPlayerInfo->gaityaw = 180; + + if (m_pPlayerInfo->gaityaw < -180) + m_pPlayerInfo->gaityaw = -180; + } +} + +void CStudioModelRenderer::StudioProcessGait(entity_state_t *pplayer) +{ + mstudioseqdesc_t *pseqdesc; + float dt; + int iBlend; + float flYaw; // view direction relative to movement + + //if (m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq) + //{ + // m_pCurrentEntity->curstate.sequence = 0; + //} + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + + StudioPlayerBlend(pseqdesc, &iBlend, &m_pCurrentEntity->angles[PITCH]); + + m_pCurrentEntity->latched.prevangles[PITCH] = m_pCurrentEntity->angles[PITCH]; + m_pCurrentEntity->curstate.blending[0] = iBlend; + m_pCurrentEntity->latched.prevblending[0] = m_pCurrentEntity->curstate.blending[0]; + m_pCurrentEntity->latched.prevseqblending[0] = m_pCurrentEntity->curstate.blending[0]; + + //Con_DPrintf("%f %d\n", m_pCurrentEntity->angles[PITCH], m_pCurrentEntity->blending[0]); + + dt = clamp(m_clTime - m_clOldTime, 0.0, 1.0); + StudioEstimateGait(pplayer); + + //Con_DPrintf("%f %f\n", m_pCurrentEntity->angles[YAW], m_pPlayerInfo->gaityaw); + + // calc side to side turning + flYaw = m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw; + flYaw = flYaw - (int)(flYaw / 360) * 360; + + if (flYaw < -180) + flYaw = flYaw + 360; + + if (flYaw > 180) + flYaw = flYaw - 360; + + if (flYaw > 120) + { + m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw - 180; + m_flGaitMovement = -m_flGaitMovement; + flYaw = flYaw - 180; + } + else if (flYaw < -120) + { + m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw + 180; + m_flGaitMovement = -m_flGaitMovement; + flYaw = flYaw + 180; + } + + // adjust torso + m_pCurrentEntity->curstate.controller[0] = ((flYaw / 4.0) + 30) / (60.0 / 255.0); + m_pCurrentEntity->curstate.controller[1] = ((flYaw / 4.0) + 30) / (60.0 / 255.0); + m_pCurrentEntity->curstate.controller[2] = ((flYaw / 4.0) + 30) / (60.0 / 255.0); + m_pCurrentEntity->curstate.controller[3] = ((flYaw / 4.0) + 30) / (60.0 / 255.0); + + m_pCurrentEntity->latched.prevcontroller[0] = m_pCurrentEntity->curstate.controller[0]; + m_pCurrentEntity->latched.prevcontroller[1] = m_pCurrentEntity->curstate.controller[1]; + m_pCurrentEntity->latched.prevcontroller[2] = m_pCurrentEntity->curstate.controller[2]; + m_pCurrentEntity->latched.prevcontroller[3] = m_pCurrentEntity->curstate.controller[3]; + + m_pCurrentEntity->angles[YAW] = m_pPlayerInfo->gaityaw; + if (m_pCurrentEntity->angles[YAW] < -0) + m_pCurrentEntity->angles[YAW] += 360; + + m_pCurrentEntity->latched.prevangles[YAW] = m_pCurrentEntity->angles[YAW]; + + if (pplayer->gaitsequence >= m_pStudioHeader->numseq) + { + pplayer->gaitsequence = 0; + } + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + pplayer->gaitsequence; + + // calc gait frame + if (pseqdesc->linearmovement[0] > 0) + { + m_pPlayerInfo->gaitframe += (m_flGaitMovement / pseqdesc->linearmovement[0]) * pseqdesc->numframes; + } + else + { + m_pPlayerInfo->gaitframe += pseqdesc->fps * dt; + } + + // do modulo + m_pPlayerInfo->gaitframe = m_pPlayerInfo->gaitframe - (int)(m_pPlayerInfo->gaitframe / pseqdesc->numframes) * pseqdesc->numframes; + + if (m_pPlayerInfo->gaitframe < 0) + m_pPlayerInfo->gaitframe += pseqdesc->numframes; +} + +int CStudioModelRenderer::m_iShadowSprite; +void CStudioModelRenderer::StudioSetShadowSprite(int iSprite) +{ + m_iShadowSprite = iSprite; +} + +void CStudioModelRenderer::StudioDrawShadow(Vector &origin, float scale) +{ + Vector p1, p2, p3, p4; + pmtrace_t pmtrace; + + gEngfuncs.pEventAPI->EV_SetTraceHull(2); + gEngfuncs.pEventAPI->EV_PlayerTrace(origin, origin - Vector(0, 0, 150), PM_STUDIO_BOX | PM_WORLD_ONLY, -1, &pmtrace); + + if (pmtrace.startsolid) + return; + + if (pmtrace.fraction >= 1.0f) + return; + + pmtrace.plane.normal = pmtrace.plane.normal.Normalize(); + + if (pmtrace.plane.normal.z <= 0.7f) + return; + + pmtrace.plane.normal = pmtrace.plane.normal * scale * (1.0f - pmtrace.fraction); + + // add 2.0f to Z, for avoid Z-fighting + p1.x = pmtrace.endpos.x - pmtrace.plane.normal.z; + p1.y = pmtrace.endpos.y + pmtrace.plane.normal.z; + p1.z = pmtrace.endpos.z + 1.0f + pmtrace.plane.normal.x - pmtrace.plane.normal.y; + + p2.x = pmtrace.endpos.x + pmtrace.plane.normal.z; + p2.y = pmtrace.endpos.y + pmtrace.plane.normal.z; + p2.z = pmtrace.endpos.z + 1.0f - pmtrace.plane.normal.x - pmtrace.plane.normal.y; + + p3.x = pmtrace.endpos.x + pmtrace.plane.normal.z; + p3.y = pmtrace.endpos.y - pmtrace.plane.normal.z; + p3.z = pmtrace.endpos.z + 1.0f - pmtrace.plane.normal.x + pmtrace.plane.normal.y; + + p4.x = pmtrace.endpos.x - pmtrace.plane.normal.z; + p4.y = pmtrace.endpos.y - pmtrace.plane.normal.z; + p4.z = pmtrace.endpos.z + 1.0f + pmtrace.plane.normal.x + pmtrace.plane.normal.y; + + IEngineStudio.StudioRenderShadow(m_iShadowSprite, p1, p2, p3, p4); +} + +int CStudioModelRenderer::StudioDrawPlayer(int flags, entity_state_t *pplayer) +{ + m_pCurrentEntity = IEngineStudio.GetCurrentEntity(); + + IEngineStudio.GetTimes(&m_nFrameCount, &m_clTime, &m_clOldTime); + IEngineStudio.GetViewInfo(m_vRenderOrigin, m_vUp, m_vRight, m_vNormal); + IEngineStudio.GetAliasScale(&m_fSoftwareXScale, &m_fSoftwareYScale); + + m_nPlayerIndex = pplayer->number - 1; + + if (m_nPlayerIndex < 0 || m_nPlayerIndex >= gEngfuncs.GetMaxClients()) + return 0; + + m_pRenderModel = IEngineStudio.SetupPlayerModel(m_nPlayerIndex); + if (!m_pRenderModel) + return 0; + + m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata(m_pRenderModel); + IEngineStudio.StudioSetHeader(m_pStudioHeader); + IEngineStudio.SetRenderModel(m_pRenderModel); + + if (pplayer->gaitsequence) + { + vec3_t orig_angles; + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + + VectorCopy(m_pCurrentEntity->angles, orig_angles); + + StudioProcessGait(pplayer); + + m_pPlayerInfo->gaitsequence = pplayer->gaitsequence; + m_pPlayerInfo = nullptr; + + StudioSetUpTransform(0); + VectorCopy(orig_angles, m_pCurrentEntity->angles); + } + else + { + m_pCurrentEntity->curstate.controller[0] = 127; + m_pCurrentEntity->curstate.controller[1] = 127; + m_pCurrentEntity->curstate.controller[2] = 127; + m_pCurrentEntity->curstate.controller[3] = 127; + + m_pCurrentEntity->latched.prevcontroller[0] = m_pCurrentEntity->curstate.controller[0]; + m_pCurrentEntity->latched.prevcontroller[1] = m_pCurrentEntity->curstate.controller[1]; + m_pCurrentEntity->latched.prevcontroller[2] = m_pCurrentEntity->curstate.controller[2]; + m_pCurrentEntity->latched.prevcontroller[3] = m_pCurrentEntity->curstate.controller[3]; + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + m_pPlayerInfo->gaitsequence = 0; + + StudioSetUpTransform(0); + } + + if (flags & STUDIO_RENDER) + { + // see if the bounding box lets us trivially reject, also sets + if (!IEngineStudio.StudioCheckBBox()) + return 0; + + (*m_pModelsDrawn)++; + (*m_pStudioModelCount)++; // render data cache cookie + + if (m_pStudioHeader->numbodyparts == 0) + return 1; + } + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + StudioSetupBones(); + StudioSaveBones(); + m_pPlayerInfo->renderframe = m_nFrameCount; + m_pPlayerInfo = nullptr; + + if (flags & STUDIO_EVENTS) + { + StudioCalcAttachments(); + IEngineStudio.StudioClientEvents(); + + // copy attachments into global entity array + if (m_pCurrentEntity->index > 0) + { + cl_entity_t *ent = gEngfuncs.GetEntityByIndex(m_pCurrentEntity->index); + Q_memcpy(ent->attachment, m_pCurrentEntity->attachment, sizeof(ent->attachment)); + } + } + + if (flags & STUDIO_RENDER) + { + if (m_pCvarHiModels->value && m_pRenderModel != m_pCurrentEntity->model) + { + // show highest resolution multiplayer model + m_pCurrentEntity->curstate.body = 255; + } + + if (!(m_pCvarDeveloper->value == 0 && gEngfuncs.GetMaxClients() == 1) && (m_pRenderModel == m_pCurrentEntity->model)) + { + m_pCurrentEntity->curstate.body = 1; // force helmet + } + + vec3_t dir; + alight_t lighting; + lighting.plightvec = dir; + IEngineStudio.StudioDynamicLight(m_pCurrentEntity, &lighting); + IEngineStudio.StudioEntityLight(&lighting); + IEngineStudio.StudioSetupLighting(&lighting); // model and frame independant + + m_pPlayerInfo = IEngineStudio.PlayerInfo(m_nPlayerIndex); + + // get remap colors + m_nTopColor = m_pPlayerInfo->topcolor; + m_nBottomColor = m_pPlayerInfo->bottomcolor; + + // bounds check + if (m_nTopColor < 0) + m_nTopColor = 0; + + if (m_nTopColor > 360) + m_nTopColor = 360; + + if (m_nBottomColor < 0) + m_nBottomColor = 0; + + if (m_nBottomColor > 360) + m_nBottomColor = 360; + + IEngineStudio.StudioSetRemapColors(m_nTopColor, m_nBottomColor); + + StudioRenderModel(); + m_pPlayerInfo = nullptr; + + if (pplayer->weaponmodel) + { + cl_entity_t saveent = *m_pCurrentEntity; + + model_t *pweaponmodel = IEngineStudio.GetModelByIndex(pplayer->weaponmodel); + + m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata(pweaponmodel); + IEngineStudio.StudioSetHeader(m_pStudioHeader); + + StudioMergeBones(pweaponmodel); + IEngineStudio.StudioSetupLighting(&lighting); + + StudioRenderModel(); + StudioCalcAttachments(); + + *m_pCurrentEntity = saveent; + } + } + + return 1; +} + +const int MAX_NUM_ATTACHMENTS = 4; + +void CStudioModelRenderer::StudioCalcAttachments() +{ + if (m_pStudioHeader->numattachments > MAX_NUM_ATTACHMENTS) + { + gEngfuncs.Con_DPrintf("Too many attachments on %s\n", m_pCurrentEntity->model->name); + exit(-1); + } + + // calculate attachment points + mstudioattachment_t *pattachment = (mstudioattachment_t *)((byte *)m_pStudioHeader + m_pStudioHeader->attachmentindex); + for (int i = 0; i < m_pStudioHeader->numattachments; i++) + { + VectorTransform(pattachment[i].org, (*m_plighttransform)[pattachment[i].bone], m_pCurrentEntity->attachment[i]); + } +} + +void CStudioModelRenderer::StudioRenderModel() +{ + IEngineStudio.SetChromeOrigin(); + IEngineStudio.SetForceFaceFlags(0); + + if (m_pCurrentEntity->curstate.renderfx == kRenderFxGlowShell) + { + m_pCurrentEntity->curstate.renderfx = kRenderFxNone; + StudioRenderFinal(); + + if (!IEngineStudio.IsHardware()) + { + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + } + + IEngineStudio.SetForceFaceFlags(STUDIO_NF_CHROME); + + gEngfuncs.pTriAPI->SpriteTexture(m_pChromeSprite, 0); + m_pCurrentEntity->curstate.renderfx = kRenderFxGlowShell; + + StudioRenderFinal(); + + if (!IEngineStudio.IsHardware()) + { + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); + } + } + else + { + StudioRenderFinal(); + } +} + +void CStudioModelRenderer::StudioDrawBones() +{ + int i, j, k; + float lv; + vec3_t tmp; + vec3_t p[8]; + vec3_t up, right, forward; + vec3_t a1; + mstudiobone_t *pbones; + + pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex); + + gEngfuncs.pTriAPI->SpriteTexture(m_pWhiteSprite, 0); + + for (i = 0; i < m_pStudioHeader->numbones; i++) + { + if (pbones[i].parent == -1) + continue; + + k = pbones[i].parent; + + a1[0] = a1[1] = a1[2] = 1.0f; + up[0] = (*m_plighttransform)[i][0][3] - (*m_plighttransform)[k][0][3]; + up[1] = (*m_plighttransform)[i][1][3] - (*m_plighttransform)[k][1][3]; + up[2] = (*m_plighttransform)[i][2][3] - (*m_plighttransform)[k][2][3]; + + if (up[0] > up[1]) + { + if (up[0] > up[2]) + a1[0] = 0.0f; + else + a1[2] = 0.0f; + } + else + { + if (up[1] > up[2]) + a1[1] = 0.0f; + else + a1[2] = 0.0f; + } + + CrossProduct(up, a1, right); + VectorNormalize(right); + CrossProduct(up, right, forward); + VectorNormalize(forward); + VectorScale(right, 2.0f, right); + VectorScale(forward, 2.0f, forward); + + for (j = 0; j < 8; j++) + { + p[j][0] = (*m_plighttransform)[k][0][3]; + p[j][1] = (*m_plighttransform)[k][1][3]; + p[j][2] = (*m_plighttransform)[k][2][3]; + + if (j & 1) + { + VectorSubtract(p[j], right, p[j]); + } + else + { + VectorAdd(p[j], right, p[j]); + } + + if (j & 2) + { + VectorSubtract(p[j], forward, p[j]); + } + else + { + VectorAdd(p[j], forward, p[j]); + } + + if (j & 4) + { + } + else + { + VectorAdd(p[j], up, p[j]); + } + } + + VectorNormalize(up); + VectorNormalize(right); + VectorNormalize(forward); + + gEngfuncs.pTriAPI->Begin(TRI_QUADS); + gEngfuncs.pTriAPI->Color4f(1.0f, 1.0f, 1.0f, 1.0f); + gEngfuncs.pTriAPI->TexCoord2f(0.0f, 0.0f); + + for (j = 0; j < 6; j++) + { + switch (j) + { + case 0: VectorCopy (right, tmp); break; + case 1: VectorCopy (forward, tmp); break; + case 2: VectorCopy (up, tmp); break; + case 3: VectorScale(right, -1, tmp); break; + case 4: VectorScale(forward, -1, tmp); break; + case 5: VectorScale(up, -1, tmp); break; + } + + R_StudioLighting(&lv, -1, 0, tmp); + + gEngfuncs.pTriAPI->Brightness(lv); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][0]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][1]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][2]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][3]]); + } + + gEngfuncs.pTriAPI->End(); + } +} + +void CStudioModelRenderer::StudioDrawHulls() +{ + int i, j; + float lv; + vec3_t tmp; + vec3_t p[8]; + vec3_t pos; + + mstudiobbox_t *pbbox = (mstudiobbox_t *)((char *)m_pStudioHeader + m_pStudioHeader->hitboxindex); + + gEngfuncs.pTriAPI->SpriteTexture(m_pWhiteSprite, 0); + + for (i = 0; i < m_pStudioHeader->numhitboxes; i++) + { + // skip shield + if (i == 20) + continue; + + for (j = 0; j < 8; j++) + { + tmp[0] = (j & 1) ? pbbox[i].bbmin[0] : pbbox[i].bbmax[0]; + tmp[1] = (j & 2) ? pbbox[i].bbmin[1] : pbbox[i].bbmax[1]; + tmp[2] = (j & 4) ? pbbox[i].bbmin[2] : pbbox[i].bbmax[2]; + + VectorTransform(tmp, (*m_plighttransform)[pbbox[i].bone], p[j]); + } + + j = (pbbox[i].group % 8); + + gEngfuncs.pTriAPI->Begin(TRI_QUADS); + gEngfuncs.pTriAPI->Color4f(m_hullcolor[j][0], m_hullcolor[j][1], m_hullcolor[j][2], 1.0f); + gEngfuncs.pTriAPI->TexCoord2f(0.0f, 0.0f); + + for (j = 0; j < ARRAYSIZE(m_boxpnt); j++) + { + tmp[0] = tmp[1] = tmp[2] = 0; + tmp[j % 3] = (j < 3) ? 1.0 : -1.0; + + R_StudioLighting(&lv, pbbox[i].bone, 0, tmp); + + gEngfuncs.pTriAPI->Brightness(lv); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][0]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][1]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][2]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][3]]); + } + + gEngfuncs.pTriAPI->End(); + } +} + +void CStudioModelRenderer::StudioDrawAbsBBox() +{ + int j; + float lv; + vec3_t tmp; + vec3_t p[8]; + mstudioseqdesc_t *pseqdesc; + + pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence; + + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + gEngfuncs.pTriAPI->SpriteTexture(m_pWhiteSprite, 0); + + for (j = 0; j < ARRAYSIZE(p); j++) + { + p[j][0] = ((j & 1) ? pseqdesc->bbmin[0] : pseqdesc->bbmax[0]) + m_pCurrentEntity->origin[0]; + p[j][1] = ((j & 2) ? pseqdesc->bbmin[1] : pseqdesc->bbmax[1]) + m_pCurrentEntity->origin[1]; + p[j][2] = ((j & 4) ? pseqdesc->bbmin[2] : pseqdesc->bbmax[2]) + m_pCurrentEntity->origin[2]; + } + + gEngfuncs.pTriAPI->Begin(TRI_QUADS); + gEngfuncs.pTriAPI->Color4f(0.5f, 0.5f, 1.0f, 1.0f); + //gEngfuncs.pTriAPI->TexCoord2f(0.0f, 0.0f); + + for (j = 0; j < ARRAYSIZE(m_boxpnt); j++) + { + tmp[0] = tmp[1] = tmp[2] = 0; + tmp[j % 3] = (j < 3) ? 1.0 : -1.0; + + R_StudioLighting(&lv, -1, 0, tmp); + + gEngfuncs.pTriAPI->Brightness(lv); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][0]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][1]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][2]]); + gEngfuncs.pTriAPI->Vertex3fv(p[m_boxpnt[j][3]]); + } + + gEngfuncs.pTriAPI->End(); + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); +} + +void CStudioModelRenderer::StudioRenderFinal_Software() +{ + // Note, rendermode set here has effect in SW + IEngineStudio.SetupRenderer(kRenderNormal); + + if (m_pCvarDrawEntities->value == 2) + { + //IEngineStudio.StudioDrawBones(); + StudioDrawBones(); // IEngineStudio.StudioDrawBones(); + } + else if (m_pCvarDrawEntities->value == 3) + { + StudioDrawHulls(); // IEngineStudio.StudioDrawHulls(); + } + else + { + if (m_pPlayerSync) + { + if (m_pCurrentEntity->player && m_pCvarDrawEntities->value == 6) + { + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + StudioDrawHulls(); + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); + } + } + else + { + // Draw mesh model + for (int i = 0; i < m_pStudioHeader->numbodyparts; i++) + { + IEngineStudio.StudioSetupModel(i, (void **)&m_pBodyPart, (void **)&m_pSubModel); + IEngineStudio.StudioDrawPoints(); + } + } + } + + if (m_pCvarDrawEntities->value == 4) + { + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + StudioDrawHulls(); // IEngineStudio.StudioDrawHulls(); + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); + } + + if (m_pCvarDrawEntities->value == 5) + { + StudioDrawAbsBBox(); // IEngineStudio.StudioDrawAbsBBox(); + } + + IEngineStudio.RestoreRenderer(); +} + +void CStudioModelRenderer::StudioRenderFinal_Hardware() +{ + int rendermode = IEngineStudio.GetForceFaceFlags() ? kRenderTransAdd : m_pCurrentEntity->curstate.rendermode; + IEngineStudio.SetupRenderer(rendermode); + + if (m_pCvarDrawEntities->value == 2) + { + StudioDrawBones(); // IEngineStudio.StudioDrawBones(); + } + else if (m_pCvarDrawEntities->value == 3) + { + StudioDrawHulls(); // IEngineStudio.StudioDrawHulls(); + } + else + { + if (m_pPlayerSync) + { + if (m_pCurrentEntity->player && m_pCvarDrawEntities->value == 6) + { + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + StudioDrawHulls(); + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); + } + } + else + { + // Draw mesh model + for (int i = 0; i < m_pStudioHeader->numbodyparts; i++) + { + IEngineStudio.StudioSetupModel(i, (void **)&m_pBodyPart, (void **)&m_pSubModel); + + if (m_fDoInterp) + { + // interpolation messes up bounding boxes. + m_pCurrentEntity->trivial_accept = 0; + } + + IEngineStudio.GL_SetRenderMode(rendermode); + IEngineStudio.StudioDrawPoints(); + IEngineStudio.GL_StudioDrawShadow(); + } + } + } + + if (m_pCvarDrawEntities->value == 4) + { + gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); + StudioDrawHulls(); // IEngineStudio.StudioDrawHulls(); + gEngfuncs.pTriAPI->RenderMode(kRenderNormal); + } + + if (m_pCvarDrawEntities->value == 5) + { + StudioDrawAbsBBox(); // IEngineStudio.StudioDrawAbsBBox(); + } + + IEngineStudio.RestoreRenderer(); +} + +void CStudioModelRenderer::StudioRenderFinal() +{ + if (IEngineStudio.IsHardware()) + { + StudioRenderFinal_Hardware(); + } + else + { + StudioRenderFinal_Software(); + } +} diff --git a/hitboxtracker/client/src/studio/StudioModelRenderer.h b/hitboxtracker/client/src/studio/StudioModelRenderer.h new file mode 100644 index 0000000..0f83059 --- /dev/null +++ b/hitboxtracker/client/src/studio/StudioModelRenderer.h @@ -0,0 +1,185 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class CStudioModelRenderer +{ +public: + // Construction/Destruction + CStudioModelRenderer(); + virtual ~CStudioModelRenderer(); + + // Initialization + virtual void Init(); + +public: + // Public Interfaces + virtual int StudioDrawModel(int flags); + virtual int StudioDrawPlayer(int flags, struct entity_state_s *pplayer); + +public: + // Local interfaces + void StudioSetShadowSprite(int iSprite); + + // Look up animation data for sequence + virtual mstudioanim_t *StudioGetAnim(model_t *psubmodel, mstudioseqdesc_t *pseqdesc); + + // Interpolate model position and angles and set up matrices + virtual void StudioSetUpTransform(int trivial_accept); + + // Set up model bone positions + virtual void StudioSetupBones(); + + // Find final attachment points + virtual void StudioCalcAttachments(); + + // Save bone matrices and names + virtual void StudioSaveBones(); + + // Merge cached bones with current bones for model + virtual void StudioMergeBones(model_t *psubmodel); + + // Determine interpolation fraction + virtual float StudioEstimateInterpolant(); + + // Determine current frame for rendering + virtual float StudioEstimateFrame(mstudioseqdesc_t *pseqdesc); + + // Apply special effects to transform matrix + virtual void StudioFxTransform(cl_entity_t *ent, float transform[3][4]); + + // Spherical interpolation of bones + virtual void StudioSlerpBones(vec4_t q1[], float pos1[][3], vec4_t q2[], float pos2[][3], float s); + + // Compute bone adjustments(bone controllers) + virtual void StudioCalcBoneAdj(float dadt, float *adj, const byte *pcontroller1, const byte *pcontroller2, byte mouthopen); + + // Get bone quaternions + virtual void StudioCalcBoneQuaterion(int frame, float s, mstudiobone_t *pbone, mstudioanim_t *panim, float *adj, float *q); + + // Get bone positions + virtual void StudioCalcBonePosition(int frame, float s, mstudiobone_t *pbone, mstudioanim_t *panim, float *adj, float *pos); + + // Compute rotations + virtual void StudioCalcRotations(float pos[][3], vec4_t *q, mstudioseqdesc_t *pseqdesc, mstudioanim_t *panim, float f); + + // Send bones and verts to renderer + virtual void StudioRenderModel(); + + // Finalize rendering + virtual void StudioRenderFinal(); + + // GL&D3D vs. Software renderer finishing functions + virtual void StudioRenderFinal_Software(); + virtual void StudioRenderFinal_Hardware(); + + // Player specific data + // Determine pitch and blending amounts for players + virtual void StudioPlayerBlend(mstudioseqdesc_t *pseqdesc, int *pBlend, float *pPitch); + + // Estimate gait frame for player + virtual void StudioEstimateGait(entity_state_t *pplayer); + + // Process movement of player + virtual void StudioProcessGait(entity_state_t *pplayer); + + void StudioDrawShadow(Vector &origin, float scale); + + void StudioDrawBones(); + void StudioDrawHulls(); + void StudioDrawAbsBBox(); + +public: + static int m_iShadowSprite; + static int m_boxpnt[6][4]; + static vec3_t m_hullcolor[8]; + + double m_clTime; // Client clock + double m_clOldTime; // Old Client clock + qboolean m_fDoInterp; // Do interpolation? + qboolean m_fGaitEstimation; // Do gait estimation? + int m_nFrameCount; // Current render frame # + + // Cvars that studio model code needs to reference + cvar_t *m_pCvarHiModels; // Use high quality models? + cvar_t *m_pCvarDeveloper; // Developer debug output desired? + cvar_t *m_pCvarDrawEntities; // Draw entities bone hit boxes, etc? + + cl_entity_t *m_pCurrentEntity; // The entity which we are currently rendering. + model_t *m_pRenderModel; // The model for the entity being rendered + player_info_t *m_pPlayerInfo; // Player info for current player, if drawing a player + player_sync_t *m_pPlayerSync; // Player synchronized info from the server for current player, if drawing a player + + int m_nPlayerIndex; // The index of the player being drawn + float m_flGaitMovement; // The player's gait movement + + studiohdr_t *m_pStudioHeader; // Pointer to header block for studio model data + mstudiobodyparts_t *m_pBodyPart; // Pointers to current body part and submodel + mstudiomodel_t *m_pSubModel; + + // Palette substition for top and bottom of model + int m_nTopColor; + int m_nBottomColor; + + model_t *m_pChromeSprite; // Sprite model used for drawing studio model chrome + model_t *m_pWhiteSprite; // Sprite model used for drawing studio model hulls + + // Caching + int m_nCachedBones; // Number of bones in bone cache + char m_nCachedBoneNames[MAXSTUDIOBONES][32]; // Names of cached bones + + // Cached bone & light transformation matrices + float m_rgCachedBoneTransform [MAXSTUDIOBONES][3][4]; + float m_rgCachedLightTransform[MAXSTUDIOBONES][3][4]; + + // Software renderer scale factors + float m_fSoftwareXScale, m_fSoftwareYScale; + + // Current view vectors and render origin + float m_vUp[3]; + float m_vRight[3]; + float m_vNormal[3]; + + float m_vRenderOrigin[3]; + + // Model render counters(from engine) + int *m_pStudioModelCount; + int *m_pModelsDrawn; + + // Matrices + // Model to world transformation + float (*m_protationmatrix)[3][4]; // Model to world transformation + float (*m_paliastransform)[3][4]; // Model to view transformation + + // Concatenated bone and light transforms + float (*m_pbonetransform) [MAXSTUDIOBONES][3][4]; + float (*m_plighttransform)[MAXSTUDIOBONES][3][4]; +}; + +extern engine_studio_api_t IEngineStudio; diff --git a/hitboxtracker/client/src/studio/studio_util.cpp b/hitboxtracker/client/src/studio/studio_util.cpp new file mode 100644 index 0000000..db3c960 --- /dev/null +++ b/hitboxtracker/client/src/studio/studio_util.cpp @@ -0,0 +1,234 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +float Length(const vec_t *v) +{ + return Q_sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); +} + +void AngleMatrix(const float *angles, float (*matrix)[4]) +{ + float angle; + float sr, sp, sy, cr, cp, cy; + + angle = angles[YAW] * (M_PI * 2 / 360); + sy = sin(angle); + cy = cos(angle); + angle = angles[PITCH] * (M_PI * 2 / 360); + sp = sin(angle); + cp = cos(angle); + angle = angles[ROLL] * (M_PI * 2 / 360); + sr = sin(angle); + cr = cos(angle); + + // matrix = (YAW * PITCH) * ROLL + matrix[0][0] = cp * cy; + matrix[1][0] = cp * sy; + matrix[2][0] = -sp; + matrix[0][1] = sr * sp * cy + cr * -sy; + matrix[1][1] = sr * sp * sy + cr * cy; + matrix[2][1] = sr * cp; + matrix[0][2] = (cr * sp * cy + -sr * -sy); + matrix[1][2] = (cr * sp * sy + -sr * cy); + matrix[2][2] = cr * cp; + matrix[0][3] = 0.0; + matrix[1][3] = 0.0; + matrix[2][3] = 0.0; +} + +int VectorCompare(const float *v1, const float *v2) +{ + for (int i = 0; i < 3; i++) + { + if (v1[i] != v2[i]) + return 0; + } + + return 1; +} + +void CrossProduct(const float *v1, const float *v2, float *cross) +{ + cross[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross[2] = v1[0] * v2[1] - v1[1] * v2[0]; +} + +float VectorNormalize(vec_t *v) +{ + float length = Length(v); + if (length) + { + float ilength = 1.0 / length; + + v[0] *= ilength; + v[1] *= ilength; + v[2] *= ilength; + } + + return length; +} + +void VectorTransform(const float *in1, float in2[3][4], float *out) +{ + out[0] = DotProduct(in1, in2[0]) + in2[0][3]; + out[1] = DotProduct(in1, in2[1]) + in2[1][3]; + out[2] = DotProduct(in1, in2[2]) + in2[2][3]; +} + +void ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]) +{ + out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + + in1[0][2] * in2[2][0]; + out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + + in1[0][2] * in2[2][1]; + out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + + in1[0][2] * in2[2][2]; + out[0][3] = in1[0][0] * in2[0][3] + in1[0][1] * in2[1][3] + + in1[0][2] * in2[2][3] + in1[0][3]; + out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + + in1[1][2] * in2[2][0]; + out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + + in1[1][2] * in2[2][1]; + out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + + in1[1][2] * in2[2][2]; + out[1][3] = in1[1][0] * in2[0][3] + in1[1][1] * in2[1][3] + + in1[1][2] * in2[2][3] + in1[1][3]; + out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + + in1[2][2] * in2[2][0]; + out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + + in1[2][2] * in2[2][1]; + out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + + in1[2][2] * in2[2][2]; + out[2][3] = in1[2][0] * in2[0][3] + in1[2][1] * in2[1][3] + + in1[2][2] * in2[2][3] + in1[2][3]; +} + +// angles index are not the same as ROLL, PITCH, YAW +void AngleQuaternion(float *angles, vec4_t quaternion) +{ + float angle; + float sr, sp, sy, cr, cp, cy; + + // FIXME: rescale the inputs to 1/2 angle + angle = angles[2] * 0.5; + sy = sin(angle); + cy = cos(angle); + angle = angles[1] * 0.5; + sp = sin(angle); + cp = cos(angle); + angle = angles[0] * 0.5; + sr = sin(angle); + cr = cos(angle); + + quaternion[0] = sr * cp * cy - cr * sp * sy; // X + quaternion[1] = cr * sp * cy + sr * cp * sy; // Y + quaternion[2] = cr * cp * sy - sr * sp * cy; // Z + quaternion[3] = cr * cp * cy + sr * sp * sy; // W +} + +void QuaternionSlerp(vec4_t p, vec4_t q, float t, vec4_t qt) +{ + int i; + float omega, cosom, sinom, sclp, sclq; + + // decide if one of the quaternions is backwards + float a = 0; + float b = 0; + + for (i = 0; i < 4; i++) + { + a += (p[i] - q[i]) * (p[i] - q[i]); + b += (p[i] + q[i]) * (p[i] + q[i]); + } + if (a > b) + { + for (i = 0; i < 4; i++) + { + q[i] = -q[i]; + } + } + + cosom = p[0]*q[0] + p[1]*q[1] + p[2]*q[2] + p[3]*q[3]; + + if ((1.0 + cosom) > 0.000001) + { + if ((1.0 - cosom) > 0.000001) + { + omega = acos(cosom); + sinom = sin(omega); + sclp = sin((1.0 - t) * omega) / sinom; + sclq = sin(t * omega) / sinom; + } + else + { + sclp = 1.0 - t; + sclq = t; + } + + for (i = 0; i < 4; i++) + { + qt[i] = sclp * p[i] + sclq * q[i]; + } + } + else + { + qt[0] = -q[1]; + qt[1] = q[0]; + qt[2] = -q[3]; + qt[3] = q[2]; + sclp = sin((1.0 - t) * (0.5 * M_PI)); + sclq = sin(t * (0.5 * M_PI)); + for (i = 0; i < 3; i++) + { + qt[i] = sclp * p[i] + sclq * qt[i]; + } + } +} + +void QuaternionMatrix(vec4_t quaternion, float (*matrix)[4]) +{ + matrix[0][0] = 1.0 - 2.0 * quaternion[1] * quaternion[1] - 2.0 * quaternion[2] * quaternion[2]; + matrix[1][0] = 2.0 * quaternion[0] * quaternion[1] + 2.0 * quaternion[3] * quaternion[2]; + matrix[2][0] = 2.0 * quaternion[0] * quaternion[2] - 2.0 * quaternion[3] * quaternion[1]; + + matrix[0][1] = 2.0 * quaternion[0] * quaternion[1] - 2.0 * quaternion[3] * quaternion[2]; + matrix[1][1] = 1.0 - 2.0 * quaternion[0] * quaternion[0] - 2.0 * quaternion[2] * quaternion[2]; + matrix[2][1] = 2.0 * quaternion[1] * quaternion[2] + 2.0 * quaternion[3] * quaternion[0]; + + matrix[0][2] = 2.0 * quaternion[0] * quaternion[2] + 2.0 * quaternion[3] * quaternion[1]; + matrix[1][2] = 2.0 * quaternion[1] * quaternion[2] - 2.0 * quaternion[3] * quaternion[0]; + matrix[2][2] = 1.0 - 2.0 * quaternion[0] * quaternion[0] - 2.0 * quaternion[1] * quaternion[1]; +} + +void MatrixCopy(float in[3][4], float out[3][4]) +{ + Q_memcpy(out, in, sizeof(float) * 3 * 4); +} diff --git a/hitboxtracker/client/src/studio/studio_util.h b/hitboxtracker/client/src/studio/studio_util.h new file mode 100644 index 0000000..0595225 --- /dev/null +++ b/hitboxtracker/client/src/studio/studio_util.h @@ -0,0 +1,49 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#ifndef M_PI +#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h +#endif + +#define PITCH 0 // up / down +#define YAW 1 // left / right +#define ROLL 2 // fall over + +float Length(const vec_t *v); +void AngleMatrix(const float *angles, float (*matrix)[4]); +int VectorCompare(const float *v1, const float *v2); +void CrossProduct(const float *v1, const float *v2, float *cross); +void VectorTransform(const float *in1, float in2[3][4], float *out); +float VectorNormalize(vec_t *v); +void ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]); +void MatrixCopy(float in[3][4], float out[3][4]); +void QuaternionMatrix(vec4_t quaternion, float (*matrix)[4]); +void QuaternionSlerp(vec4_t p, vec4_t q, float t, vec4_t qt); +void AngleQuaternion(float *angles, vec4_t quaternion); diff --git a/hitboxtracker/client/src/usermsg.cpp b/hitboxtracker/client/src/usermsg.cpp new file mode 100644 index 0000000..db2bc22 --- /dev/null +++ b/hitboxtracker/client/src/usermsg.cpp @@ -0,0 +1,50 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +UserMsg *g_pClientUserMsgs; +std::map g_ClientUserMsgsMap; + +bool HookUserMsg(char *pszMsgName, pfnUserMsgHook pfn) +{ + auto pClientUserMsgs = g_pClientUserMsgs; + while (pClientUserMsgs) + { + if (!Q_strcmp(pClientUserMsgs->szName, pszMsgName)) + { + g_ClientUserMsgsMap[pszMsgName] = pClientUserMsgs->pfn; + pClientUserMsgs->pfn = pfn; + return true; + } + + pClientUserMsgs = pClientUserMsgs->next; + } + + return false; +} diff --git a/hitboxtracker/launcher/msvc/icon.ico b/hitboxtracker/launcher/msvc/icon.ico new file mode 100644 index 0000000..719ec72 Binary files /dev/null and b/hitboxtracker/launcher/msvc/icon.ico differ diff --git a/hitboxtracker/launcher/msvc/launcher.rc b/hitboxtracker/launcher/msvc/launcher.rc new file mode 100644 index 0000000..36e691a Binary files /dev/null and b/hitboxtracker/launcher/msvc/launcher.rc differ diff --git a/hitboxtracker/launcher/msvc/launcher.vcxproj b/hitboxtracker/launcher/msvc/launcher.vcxproj new file mode 100644 index 0000000..6a98c11 --- /dev/null +++ b/hitboxtracker/launcher/msvc/launcher.vcxproj @@ -0,0 +1,137 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {E324283B-70AB-4A32-BE41-AEF5101F655B} + Win32Proj + launcher + 8.1 + + + + Application + true + v140 + MultiByte + + + Application + false + v140 + true + MultiByte + + + + + + + + + + + + + + + true + cs + + + false + cs + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..\src\;$(ProjectDir)..\..\..\;$(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\public;%(AdditionalIncludeDirectories) + precompiled.h + + + Windows + true + ws2_32.lib;winmm.lib;%(AdditionalDependencies) + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + Force build to run Pre-Build event + build.always.run + build.always.run + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..\src\;$(ProjectDir)..\..\..\;$(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\public;%(AdditionalIncludeDirectories) + precompiled.h + + + Windows + true + true + true + ws2_32.lib;winmm.lib;%(AdditionalDependencies) + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + Force build to run Pre-Build event + build.always.run + build.always.run + + + + + + + + + + + Use + precompiled.h + Use + precompiled.h + + + Create + precompiled.h + Create + precompiled.h + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hitboxtracker/launcher/msvc/launcher.vcxproj.filters b/hitboxtracker/launcher/msvc/launcher.vcxproj.filters new file mode 100644 index 0000000..0b3aac6 --- /dev/null +++ b/hitboxtracker/launcher/msvc/launcher.vcxproj.filters @@ -0,0 +1,59 @@ + + + + + {b0a5ec3a-c0e8-453b-875a-79aaefc8057f} + + + {cee0c161-1ccb-4bb8-9835-09397f76eb1c} + + + {a940ddd0-5be3-4fd4-af2d-36961a145293} + + + + + src + + + src + + + src + + + src + + + common + + + common + + + public + + + public + + + + + src + + + common + + + public + + + public + + + + + src + + + \ No newline at end of file diff --git a/hitboxtracker/launcher/msvc/resource.h b/hitboxtracker/launcher/msvc/resource.h new file mode 100644 index 0000000..8a97719 Binary files /dev/null and b/hitboxtracker/launcher/msvc/resource.h differ diff --git a/hitboxtracker/launcher/src/app_linux.cpp b/hitboxtracker/launcher/src/app_linux.cpp new file mode 100644 index 0000000..b6ceedd --- /dev/null +++ b/hitboxtracker/launcher/src/app_linux.cpp @@ -0,0 +1,171 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if !defined(_WIN32) +class CAppLauncher: public IAppLauncher { +public: + bool Init(const char *commandline); + bool Init(int argc, const char *argv[]); + + void ShutDown(); + bool FreeEngine(); + + CSysModule *LoadEngineModule(const char *modulename); + CSysModule *LoadFilesystemModule(const char *modulename); + + bool OnInitVideoMode(); + bool OnVideoModeFailed(); + + void SetEngineDLL(const char **ppEngineDLL); + bool GetExecutableName(char *out, int len); + char *GetBaseDir(); + +private: + char m_BaseDir[MAX_PATH]; + char m_ExeName[MAX_PATH]; +}; + +CAppLauncher g_AppLauncher; +IAppLauncher *applauncher = &g_AppLauncher; + +IAppLauncher *AppLauncher() +{ + return applauncher; +} + +bool CAppLauncher::Init(const char *commandline) +{ + const char en_US[] = "en_US.UTF-8"; + + setenv("LC_ALL", en_US, 1); + setlocale(LC_ALL, en_US); + + const char *pCurrentLocale = setlocale(LC_ALL, nullptr); + if (Q_stricmp(pCurrentLocale, en_US) != 0) + { + fprintf(stderr, "WARNING: setlocale('%s') failed, using locale:'%s'. International characters may not work.\n", en_US, pCurrentLocale); + } + + Q_snprintf(m_ExeName, sizeof(m_ExeName), "%s", argv[0]); + Q_snprintf(m_BaseDir, sizeof(m_BaseDir), "%s", argv[0]); + + // strip out the exe name + char *slash = Q_strrchr(m_BaseDir, CORRECT_PATH_SEPARATOR); + if (slash) + { + *slash = '\0'; + } + + return true; +} + +bool CAppLauncher::Init(int argc, const char *argv[]) +{ + CommandLine()->CreateCmdLine(argc, argv); + return true; +} + +void CAppLauncher::ShutDown() +{ + ; +} + +bool CAppLauncher::FreeEngine() +{ + int maxref = 0; + void *engine = dlopen(ENGINE_CLIENT_LIB, RTLD_NOLOAD); + while (engine && maxref < 9) + { + maxref++; + dlclose(engine); + engine = dlopen(ENGINE_CLIENT_LIB, RTLD_NOLOAD); + } + + // failed to release engine + if (engine) { + fprintf(stderr, "Failed to unload engine on exit (%s).", ENGINE_CLIENT_LIB); + return false; + } + + return true; +} + +CSysModule *CAppLauncher::LoadEngineModule(const char *modulename) +{ + CSysModule *engineModule = Sys_LoadModule(modulename); + if (engineModule) { + return engineModule; + } + + fprintf(stderr, "Could not load %s.\nPlease try again at a later time.", modulename); + return nullptr; +} + +CSysModule *CAppLauncher::LoadFilesystemModule(const char *modulename) +{ + CSysModule *filesystemModule = Sys_LoadModule(modulename); + if (filesystemModule) { + return filesystemModule; + } + + const char message[] = "Failed to load filesystem library, exiting...\n"; + fwrite(message, sizeof(char), sizeof(message) - 1, stderr); + return nullptr; +} + +void CAppLauncher::SetEngineDLL(const char **ppEngineDLL) +{ + *ppEngineDLL = ENGINE_CLIENT_LIB; +} + +bool CAppLauncher::GetExecutableName(char *dest, size_t len) +{ + Q_strnlcpy(out, m_ExeName, len); + return true; +} + +bool CAppLauncher::OnInitVideoMode() +{ + true; +} + +bool CAppLauncher::OnVideoModeFailed() +{ + const char message[] = "The specified video mode is not supported.\nThe game will now exit.\n"; + fwrite(message, sizeof(char), sizeof(message) - 1, stderr); + return false; +} + +char *CAppLauncher::GetBaseDir() +{ + return m_BaseDir; +} + +#endif // !defined(_WIN32) diff --git a/hitboxtracker/launcher/src/app_windows.cpp b/hitboxtracker/launcher/src/app_windows.cpp new file mode 100644 index 0000000..aaac3bf --- /dev/null +++ b/hitboxtracker/launcher/src/app_windows.cpp @@ -0,0 +1,287 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if defined(_WIN32) +class CAppLauncher: public IAppLauncher { +public: + bool Init(const char *commandline); + bool Init(int argc, const char *argv[]); + + void ShutDown(); + bool FreeEngine(); + + CSysModule *LoadEngineModule(const char *modulename); + CSysModule *LoadFilesystemModule(const char *modulename); + + bool OnInitVideoMode(); + bool OnVideoModeFailed(); + + void SetEngineDLL(const char **ppEngineDLL); + bool GetExecutableName(char *dest, size_t len); + char *GetBaseDir(); + + enum + { + DEFAULT_BPP = 16, + DEFAULT_HEIGHT = 640, + DEFAULT_WIDTH = 480, + }; + +private: + char m_BaseDir[MAX_PATH]; + HANDLE m_Handle; + CSysModule *m_HitboxTrackerModule; +}; + +CAppLauncher g_AppLauncher; +IAppLauncher *applauncher = &g_AppLauncher; + +IAppLauncher *AppLauncher() +{ + return &g_AppLauncher; +} + +bool CAppLauncher::Init(const char *commandline) +{ + if (ShouldLaunchAppViaSteam(commandline, STDIO_FILESYSTEM_LIB, STDIO_FILESYSTEM_LIB)) + return false; + + /*m_Handle = CreateMutex(nullptr, FALSE, "ValveHalfLifeLauncherMutex"); + + DWORD event = WaitForSingleObject(m_Handle, 0L); + if (event && event != WAIT_ABANDONED) + { + MessageBox(nullptr, "Could not launch game.", "Error", MB_OK | MB_ICONERROR); + return false; + }*/ + + // Startup winock + WORD version = MAKEWORD(2, 0); + WSADATA wsaData; + WSAStartup(version, &wsaData); + + registry->Init(); + CommandLine()->CreateCmdLine(GetCommandLine()); + + return true; +} + +bool CAppLauncher::Init(int argc, const char *argv[]) +{ + return false; +} + +void CAppLauncher::ShutDown() +{ + registry->Shutdown(); + + if (m_Handle) + { + ReleaseMutex(m_Handle); + CloseHandle(m_Handle); + + m_Handle = nullptr; + } + + if (m_HitboxTrackerModule) + { + Sys_UnloadModule(m_HitboxTrackerModule); + m_HitboxTrackerModule = nullptr; + } + + // shutdown winsock + WSACleanup(); +} + +bool CAppLauncher::FreeEngine() +{ + return true; +} + +CSysModule *CAppLauncher::LoadEngineModule(const char *modulename) +{ + CSysModule *engineModule = Sys_LoadModule(modulename); + if (!engineModule) + { + char error[512]; + Q_sprintf(error, "Could not load %s.\nPlease try again at a later time.", modulename); + MessageBox(nullptr, error, "Fatal Error", MB_OK | MB_ICONERROR); + return nullptr; + } + + // Load 3rd-party + m_HitboxTrackerModule = Sys_LoadModule("hitboxtracker.dll"); + return engineModule; +} + +CSysModule *CAppLauncher::LoadFilesystemModule(const char *modulename) +{ + CSysModule *filesystemModule = Sys_LoadModule(modulename); + if (filesystemModule) { + return filesystemModule; + } + + if (Q_strchr(modulename, ';')) { + MessageBox(nullptr, "Game cannot be run from directories containing the semicolon character (';').", "Fatal Error", MB_OK | MB_ICONERROR); + return nullptr; + } + + _finddata_t data; + intptr_t handle = _findfirst(modulename, &data); + if (handle == -1) { + MessageBox(nullptr, "Could not find filesystem dll to load.", "Fatal Error", MB_OK | MB_ICONERROR); + return nullptr; + } + + MessageBox(nullptr, "Could not load filesystem dll.\nFileSystem crashed during construction.", "Fatal Error", MB_OK | MB_ICONERROR); + _findclose(handle); + return nullptr; +} + +void CAppLauncher::SetEngineDLL(const char **ppEngineDLL) +{ + *ppEngineDLL = ENGINE_CLIENT_LIB; + + const char *key = registry->ReadString("EngineDLL", ENGINE_CLIENT_LIB); + if (!Q_stricmp(key, ENGINE_CLIENT_LIB)) { + *ppEngineDLL = ENGINE_CLIENT_LIB; + } + else if (!Q_stricmp(key, ENGINE_CLIENT_SOFT_LIB)) { + *ppEngineDLL = ENGINE_CLIENT_SOFT_LIB; + } + + if (CommandLine()->CheckParm("-soft") || CommandLine()->CheckParm("-software")) { + *ppEngineDLL = ENGINE_CLIENT_SOFT_LIB; + } + else if (CommandLine()->CheckParm("-gl") || CommandLine()->CheckParm("-d3d")) { + *ppEngineDLL = ENGINE_CLIENT_LIB; + } + + registry->WriteString("EngineDLL", *ppEngineDLL); +} + +bool CAppLauncher::GetExecutableName(char *dest, size_t len) +{ + if (!GetModuleFileName((HINSTANCE)GetModuleHandle(nullptr), dest, len)) { + return false; + } + + return true; +} + +bool CAppLauncher::OnInitVideoMode() +{ + if (!registry->ReadInt("CrashInitializingVideoMode")) { + return true; + } + + registry->WriteInt("CrashInitializingVideoMode", 0); + + if (Q_stricmp(registry->ReadString("EngineDLL", ENGINE_CLIENT_LIB), ENGINE_CLIENT_LIB) != 0) { + return true; + } + + if (registry->ReadInt("EngineD3D") == 1) + { + registry->WriteInt("EngineD3D", 0); + + if (MessageBox(nullptr, + "The game has detected that the previous attempt to start in D3D video mode failed.\n" + "The game will now run attempt to run in openGL mode.", + "Video mode change failure", (MB_OK | MB_OKCANCEL | MB_ICONERROR | MB_ICONEXCLAMATION)) != 1) + { + return false; + } + } + else + { + registry->WriteString("EngineDLL", ENGINE_CLIENT_LIB); + + if (MessageBox(nullptr, + "The game has detected that the previous attempt to start in openGL video mode failed.\n" + "The game will now run in software mode.", + "Video mode change failure", (MB_OK | MB_OKCANCEL | MB_ICONERROR | MB_ICONEXCLAMATION)) != 1) + { + return false; + } + } + + registry->WriteInt("ScreenBPP", DEFAULT_BPP); + registry->WriteInt("ScreenHeight", DEFAULT_HEIGHT); + registry->WriteInt("ScreenWidth", DEFAULT_WIDTH); + return true; +} + +bool CAppLauncher::OnVideoModeFailed() +{ + registry->WriteInt ("ScreenBPP", DEFAULT_BPP); + registry->WriteInt ("ScreenHeight", DEFAULT_HEIGHT); + registry->WriteInt ("ScreenWidth", DEFAULT_WIDTH); + registry->WriteString("EngineDLL", ENGINE_CLIENT_LIB); + + if (MessageBox(nullptr, + "The specified video mode is not supported.\n" + "The game will now run in gl mode.", + "Video mode change failure", (MB_OK | MB_OKCANCEL | MB_ICONERROR | MB_ICONEXCLAMATION)) == 1) + { + return true; + } + + return false; +} + +char *CAppLauncher::GetBaseDir() +{ + m_BaseDir[0] = '\0'; + + char basedir[MAX_PATH]; + if (!GetModuleFileName(nullptr, basedir, sizeof(basedir))) { + return m_BaseDir; + } + + GetLongPathName(basedir, m_BaseDir, sizeof(m_BaseDir)); + + char *pBuffer = Q_strrchr(m_BaseDir, '\\'); + if (pBuffer) { + *(pBuffer + 1) = '\0'; + } + + int j = Q_strlen(m_BaseDir); + if (j > 0) + { + if (m_BaseDir[j - 1] == '\\' || m_BaseDir[j - 1] == '/') { + m_BaseDir[j - 1] = '\0'; + } + } + + return m_BaseDir; +} + +#endif // defined(_WIN32) diff --git a/hitboxtracker/launcher/src/iapp_launcher.h b/hitboxtracker/launcher/src/iapp_launcher.h new file mode 100644 index 0000000..bd01054 --- /dev/null +++ b/hitboxtracker/launcher/src/iapp_launcher.h @@ -0,0 +1,57 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#if defined (_WIN32) + #define LAUNCHER_NAME "hl.exe" +#else + #define LAUNCHER_NAME "hl_linux" +#endif // _WIN32 + +// Interface to launcher app +class IAppLauncher { +public: + virtual bool Init(const char *commandline) = 0; + virtual bool Init(int argc, const char *argv[]) = 0; + + virtual void ShutDown() = 0; + virtual bool FreeEngine() = 0; + + virtual CSysModule *LoadEngineModule(const char *modulename) = 0; + virtual CSysModule *LoadFilesystemModule(const char *modulename) = 0; + + virtual bool OnInitVideoMode() = 0; + virtual bool OnVideoModeFailed() = 0; + + virtual void SetEngineDLL(const char **ppEngineDLL) = 0; + virtual bool GetExecutableName(char *dest, size_t len) = 0; + virtual char *GetBaseDir() = 0; +}; + +IAppLauncher *AppLauncher(); diff --git a/hitboxtracker/launcher/src/launcher.h b/hitboxtracker/launcher/src/launcher.h new file mode 100644 index 0000000..3f59c93 --- /dev/null +++ b/hitboxtracker/launcher/src/launcher.h @@ -0,0 +1,2 @@ +#pragma once + diff --git a/hitboxtracker/launcher/src/main.cpp b/hitboxtracker/launcher/src/main.cpp new file mode 100644 index 0000000..6a0b1ac --- /dev/null +++ b/hitboxtracker/launcher/src/main.cpp @@ -0,0 +1,171 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +IFileSystem *g_pFileSystem; + +enum { + ENGINE_RESULT_NONE, + ENGINE_RESULT_RESTART, + ENGINE_RESULT_UNSUPPORTEDVIDEO, +}; + +#ifdef _WIN32 +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) +#else +#define hInstance nullptr +int main(int argc, char *argv[]) +#endif +{ + static char szNewCommandParams[2048]; + +#ifdef _WIN32 + if (!AppLauncher()->Init(lpCmdLine)) + return 0; +#else + if (!AppLauncher()->Init(argc, argv)) + return 0; +#endif + + bool bRunningSteam = CommandLine()->CheckParm("-steam") ? true : false; + + // calculate the details of our launch + //char exename[256]; + //AppLauncher()->GetExecutableName(exename, sizeof(exename)); + + // strip out the exe name + //char *mod = Q_strrchr(exename, CORRECT_PATH_SEPARATOR) + 1; + //if (Q_stricmp(mod, LAUNCHER_NAME) != 0 && !CommandLine()->CheckParm("-game")) + //{ + // mod[Q_strlen(mod) - 4] = '\0'; + // CommandLine()->AppendParm("-game", mod); + //} + + CommandLine()->AppendParm("-game", "cstrike"); + +#ifdef _WIN32 + _unlink("mssv29.asi"); + _unlink("mssv12.asi"); + _unlink("mp3dec.asi"); + _unlink("opengl32.dll"); +#endif + + if (!AppLauncher()->OnInitVideoMode()) + return 0; + + bool restart = true; + const char *enginedll; + + while (restart) + { + CSysModule *filesystemModule = AppLauncher()->LoadFilesystemModule(STDIO_FILESYSTEM_LIB); + if (!filesystemModule) { + break; + } + + // Get FileSystem interface + CreateInterfaceFn filesystemFactoryFn = Sys_GetFactory(filesystemModule); + g_pFileSystem = (IFileSystem *)filesystemFactoryFn(FILESYSTEM_INTERFACE_VERSION, nullptr); + g_pFileSystem->Mount(); + g_pFileSystem->AddSearchPath(AppLauncher()->GetBaseDir(), "ROOT"); + + szNewCommandParams[0] = '\0'; + AppLauncher()->SetEngineDLL(&enginedll); + + int engineResult = ENGINE_RESULT_NONE; + CSysModule *engineModule = AppLauncher()->LoadEngineModule(enginedll); + if (!engineModule) { + break; + } + + CreateInterfaceFn engineFactory = Sys_GetFactory(engineModule); + if (engineFactory) + { + IEngineAPI *engineAPI = (IEngineAPI *)engineFactory(VENGINE_LAUNCHER_API_VERSION, nullptr); + if (engineAPI) + { + engineResult = engineAPI->Run(hInstance, AppLauncher()->GetBaseDir(), (char *)CommandLine()->GetCmdLine(), szNewCommandParams, Sys_GetFactoryThis(), filesystemFactoryFn); + } + } + + Sys_UnloadModule(engineModule); + + switch (engineResult) + { + case ENGINE_RESULT_NONE: + restart = false; + break; + case ENGINE_RESULT_RESTART: + { + if (!AppLauncher()->FreeEngine()) { + break; + } + + restart = true; + break; + } + case ENGINE_RESULT_UNSUPPORTEDVIDEO: + restart = AppLauncher()->OnVideoModeFailed(); + break; + } + + // Remove any overrides in case settings changed + CommandLine()->RemoveParm("-sw"); + CommandLine()->RemoveParm("-startwindowed"); + CommandLine()->RemoveParm("-windowed"); + CommandLine()->RemoveParm("-window"); + CommandLine()->RemoveParm("-full"); + CommandLine()->RemoveParm("-fullscreen"); + CommandLine()->RemoveParm("-soft"); + CommandLine()->RemoveParm("-software"); + CommandLine()->RemoveParm("-gl"); + CommandLine()->RemoveParm("-d3d"); + CommandLine()->RemoveParm("-w"); + CommandLine()->RemoveParm("-width"); + CommandLine()->RemoveParm("-h"); + CommandLine()->RemoveParm("-height"); + CommandLine()->RemoveParm("+connect"); + CommandLine()->SetParm ("-novid", 0); + + if (Q_strstr(szNewCommandParams, "-game")) { + CommandLine()->RemoveParm("-game"); + } + + if (Q_strstr(szNewCommandParams, "+load")) { + CommandLine()->RemoveParm("+load"); + } + + CommandLine()->AppendParm(szNewCommandParams, nullptr); + g_pFileSystem->Unmount(); + Sys_UnloadModule(filesystemModule); + } + + AppLauncher()->ShutDown(); + return 0; +} diff --git a/hitboxtracker/launcher/src/precompiled.cpp b/hitboxtracker/launcher/src/precompiled.cpp new file mode 100644 index 0000000..82b5132 --- /dev/null +++ b/hitboxtracker/launcher/src/precompiled.cpp @@ -0,0 +1,29 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" diff --git a/hitboxtracker/launcher/src/precompiled.h b/hitboxtracker/launcher/src/precompiled.h new file mode 100644 index 0000000..8b0f679 --- /dev/null +++ b/hitboxtracker/launcher/src/precompiled.h @@ -0,0 +1,48 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#ifdef _WIN32 +#include +#include + +#include +#include +#endif // _WIN32 + +#include + +#include "strtools.h" +#include "interface.h" +#include "FileSystem.h" +#include "iregistry.h" +#include "icommandline.h" +#include "iapp_launcher.h" +#include "SteamAppStartUp.h" +#include "engine_launcher_api.h" diff --git a/hitboxtracker/server/msvc/server.def b/hitboxtracker/server/msvc/server.def new file mode 100644 index 0000000..41f9a0c --- /dev/null +++ b/hitboxtracker/server/msvc/server.def @@ -0,0 +1,5 @@ +LIBRARY hitboxtracker_mm +EXPORTS + GiveFnptrsToDll @1 +SECTIONS + .data READ WRITE diff --git a/hitboxtracker/server/msvc/server.vcxproj b/hitboxtracker/server/msvc/server.vcxproj new file mode 100644 index 0000000..fdad1c0 --- /dev/null +++ b/hitboxtracker/server/msvc/server.vcxproj @@ -0,0 +1,334 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {3A8F89BA-AA33-4C31-ABF8-C6FF243049D2} + Win32Proj + server + 8.1 + + + + DynamicLibrary + true + v140 + MultiByte + + + DynamicLibrary + false + v140 + true + MultiByte + + + + + + + + + + + + + + + true + hitboxtracker_mm + + + false + hitboxtracker_mm + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;USE_QSTRING;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + precompiled.h + $(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\dlls;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\game_shared;$(ProjectDir)..\..\..\dep\hlsdk\pm_shared;$(ProjectDir)..\..\..\dep\hlsdk\public;$(ProjectDir)..\..\..\dep\metamod;$(ProjectDir)..\..\..\dep;%(AdditionalIncludeDirectories) + MultiThreadedDebug + + + Windows + true + server.def + psapi.lib;%(AdditionalDependencies) + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + build.always.run + build.always.run + Force build to run Pre-Build event + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;USE_QSTRING;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + precompiled.h + $(ProjectDir)..\..\..\dep\hlsdk\common;$(ProjectDir)..\..\..\dep\hlsdk\dlls;$(ProjectDir)..\..\..\dep\hlsdk\engine;$(ProjectDir)..\..\..\dep\hlsdk\game_shared;$(ProjectDir)..\..\..\dep\hlsdk\pm_shared;$(ProjectDir)..\..\..\dep\hlsdk\public;$(ProjectDir)..\..\..\dep\metamod;$(ProjectDir)..\..\..\dep;%(AdditionalIncludeDirectories) + MultiThreaded + + + Windows + true + true + true + psapi.lib;%(AdditionalDependencies) + server.def + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + echo Empty Action + build.always.run + build.always.run + Force build to run Pre-Build event + + + + + true + true + + + true + true + + + true + true + + + true + true + + + true + true + + + true + true + + + true + true + + + true + true + + + Use + precompiled.h + Use + precompiled.h + + + Use + precompiled.h + Use + precompiled.h + + + Use + precompiled.h + Use + precompiled.h + + + Create + precompiled.h + Create + precompiled.h + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + + + + + + + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hitboxtracker/server/msvc/server.vcxproj.filters b/hitboxtracker/server/msvc/server.vcxproj.filters new file mode 100644 index 0000000..e4e2193 --- /dev/null +++ b/hitboxtracker/server/msvc/server.vcxproj.filters @@ -0,0 +1,519 @@ + + + + + {1572150b-28fe-42a8-8420-3c642ef04d06} + + + {72e8eef1-f0da-438a-8ff7-b0d9b59cdee5} + + + {0b883166-2fca-4f13-9b08-ea02ab968aa6} + + + {c4daba54-6270-42fd-9a16-ae7de7512823} + + + {5afa6150-5113-431c-9548-df0fdb3ce205} + + + {87436033-5a0c-4dea-a224-7c69a0eb7282} + + + {77eb27a0-64a3-4be5-b2ec-2d0538c41c23} + + + {4193f746-d784-4acc-b3f5-7d5c45964294} + + + {823a9c6f-59ef-4694-8ba6-d96bbcf3c1e6} + + + {34edf5f5-a612-49e9-a360-aef9409d9395} + + + + + src + + + src + + + src + + + src + + + hlsdk\common + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + src + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + + + src + + + metamod + + + metamod + + + metamod + + + metamod + + + metamod + + + metamod + + + metamod + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\common + + + hlsdk\dlls + + + hlsdk\dlls + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\game_shared\bot + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\public + + + hlsdk\pm_shared + + + hlsdk\pm_shared + + + hlsdk\pm_shared + + + hlsdk\pm_shared + + + hlsdk\pm_shared + + + hlsdk\pm_shared + + + hlsdk\public + + + src + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + hlsdk\engine + + + + + + \ No newline at end of file diff --git a/hitboxtracker/server/src/dllapi.cpp b/hitboxtracker/server/src/dllapi.cpp new file mode 100644 index 0000000..a42ee42 --- /dev/null +++ b/hitboxtracker/server/src/dllapi.cpp @@ -0,0 +1,74 @@ +#include "precompiled.h" + +DLL_FUNCTIONS g_DllFunctionTable_Post = +{ + NULL, // pfnGameInit + NULL, // pfnSpawn + NULL, // pfnThink + NULL, // pfnUse + NULL, // pfnTouch + NULL, // pfnBlocked + NULL, // pfnKeyValue + NULL, // pfnSave + NULL, // pfnRestore + NULL, // pfnSetAbsBox + NULL, // pfnSaveWriteFields + NULL, // pfnSaveReadFields + NULL, // pfnSaveGlobalState + NULL, // pfnRestoreGlobalState + NULL, // pfnResetGlobalState + NULL, // pfnClientConnect + NULL, // pfnClientDisconnect + NULL, // pfnClientKill + NULL, // pfnClientPutInServer + NULL, // pfnClientCommand + NULL, // pfnClientUserInfoChanged + &ServerActivate_Post, // pfnServerActivate + NULL, // pfnServerDeactivate + NULL, // pfnPlayerPreThink + NULL, // pfnPlayerPostThink + NULL, // pfnStartFrame + NULL, // pfnParmsNewLevel + NULL, // pfnParmsChangeLevel + NULL, // pfnGetGameDescription + NULL, // pfnPlayerCustomization + NULL, // pfnSpectatorConnect + NULL, // pfnSpectatorDisconnect + NULL, // pfnSpectatorThink + NULL, // pfnSys_Error + NULL, // pfnPM_Move + NULL, // pfnPM_Init + NULL, // pfnPM_FindTextureType + NULL, // pfnSetupVisibility + NULL, // pfnUpdateClientData + &AddToFullPack_Post, // pfnAddToFullPack + NULL, // pfnCreateBaseline + NULL, // pfnRegisterEncoders + NULL, // pfnGetWeaponData + NULL, // pfnCmdStart + NULL, // pfnCmdEnd + NULL, // pfnConnectionlessPacket + NULL, // pfnGetHullBounds + NULL, // pfnCreateInstancedBaselines + NULL, // pfnInconsistentFile + NULL, // pfnAllowLagCompensation +}; + +C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion) +{ + if (!pFunctionTable) + { + ALERT(at_logged, "%s called with null pFunctionTable", __FUNCTION__); + return FALSE; + } + + if (*interfaceVersion != INTERFACE_VERSION) + { + ALERT(at_logged, "%s version mismatch; requested=%d ours=%d", __FUNCTION__, *interfaceVersion, INTERFACE_VERSION); + *interfaceVersion = INTERFACE_VERSION; + return FALSE; + } + + Q_memcpy(pFunctionTable, &g_DllFunctionTable_Post, sizeof(DLL_FUNCTIONS)); + return TRUE; +} diff --git a/hitboxtracker/server/src/h_export.cpp b/hitboxtracker/server/src/h_export.cpp new file mode 100644 index 0000000..d1ed560 --- /dev/null +++ b/hitboxtracker/server/src/h_export.cpp @@ -0,0 +1,13 @@ +#include "precompiled.h" + +enginefuncs_t g_engfuncs; +globalvars_t *gpGlobals; + +// Receive engine function table from engine. +// This appears to be the _first_ DLL routine called by the engine, so we +// do some setup operations here. +C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t *pengfuncsFromEngine, globalvars_t *pGlobals) +{ + Q_memcpy(&g_engfuncs, pengfuncsFromEngine, sizeof(enginefuncs_t)); + gpGlobals = pGlobals; +} diff --git a/hitboxtracker/server/src/main.cpp b/hitboxtracker/server/src/main.cpp new file mode 100644 index 0000000..48346d1 --- /dev/null +++ b/hitboxtracker/server/src/main.cpp @@ -0,0 +1,73 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +server_t *sv; + +int AddToFullPack_Post(entity_state_t *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet) +{ + if (ent->v.modelindex <= 0 || ent->v.modelindex >= MAX_MODELS) + { + RETURN_META_VALUE(MRES_IGNORED, 0); + } + + // we need to call every time SV_StudioSetupBones + // to keep gaityaw and other synced on client-side + TraceResult tr; + TRACE_LINE(ent->v.origin - Vector(1, 1, 1), host->v.origin + Vector(1, 1, 1), 0, nullptr, &tr); + + CBasePlayer *plr = UTIL_PlayerByIndexSafe(e); + if (plr) + { + state->vuser1[0] = plr->m_flYaw; + state->vuser1[1] = plr->m_flGaityaw; + state->vuser1[2] = plr->m_flGaitframe; + + state->vuser2[0] = plr->m_flGaitMovement; + state->vuser2[1] = plr->m_iGaitsequence; + state->vuser2[2] = plr->m_flPitch; + + state->maxs[0] = plr->m_prevgaitorigin[0]; + state->maxs[1] = plr->m_prevgaitorigin[0]; + state->maxs[2] = plr->m_prevgaitorigin[0]; + + state->mins[0] = sv->time; + state->mins[1] = sv->oldtime; + state->mins[2] = gpGlobals->frametime; + } + + RETURN_META_VALUE(MRES_IGNORED, 0); +} + +void ServerActivate_Post(edict_t *pEdictList, int edictCount, int clientMax) +{ + // HACK HACK, we need sv.oldtime, sv.time + sv = (server_t *)((const char *)((size_t)gpGlobals->mapname + (size_t)gpGlobals->pStringBase) - offsetof(server_t, name)); + RETURN_META(MRES_IGNORED); +} diff --git a/hitboxtracker/server/src/main.h b/hitboxtracker/server/src/main.h new file mode 100644 index 0000000..11b5659 --- /dev/null +++ b/hitboxtracker/server/src/main.h @@ -0,0 +1,34 @@ +/* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "entity_state.h" + +int AddToFullPack_Post(entity_state_t *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet); +void ServerActivate_Post(edict_t *pEdictList, int edictCount, int clientMax); diff --git a/hitboxtracker/server/src/meta_api.cpp b/hitboxtracker/server/src/meta_api.cpp new file mode 100644 index 0000000..093f135 --- /dev/null +++ b/hitboxtracker/server/src/meta_api.cpp @@ -0,0 +1,117 @@ +// meta_api.cpp - minimal implementation of metamod's plugin interface + +// This is intended to illustrate the (more or less) bare minimum code +// required for a valid metamod plugin, and is targeted at those who want +// to port existing HL/SDK DLL code to run as a metamod plugin. + +/* + * Copyright (c) 2001-2003 Will Day + * + * This file is part of Metamod. + * + * Metamod is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * Metamod is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Metamod; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, the author gives permission to + * link the code of this program with the Half-Life Game Engine ("HL + * Engine") and Modified Game Libraries ("MODs") developed by Valve, + * L.L.C ("Valve"). You must obey the GNU General Public License in all + * respects for all of the code used other than the HL Engine and MODs + * from Valve. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. + * + */ + +#include "precompiled.h" + +// Description of plugin +plugin_info_t Plugin_info = { + META_INTERFACE_VERSION, // ifvers + "HitboxTracker", // name + "1.0", // version + __DATE__, // date + "s1lent", // author + "https://github.com/s1lentq/hitboxtracker", // url + "HITBOXTRACKER", // logtag, all caps please + PT_STARTUP, // (when) loadable + PT_NEVER, // (when) unloadable +}; + +// Global vars from metamod: +meta_globals_t *gpMetaGlobals; // metamod globals +gamedll_funcs_t *gpGamedllFuncs; // gameDLL function tables +mutil_funcs_t *gpMetaUtilFuncs; // metamod utility functions + +// Metamod requesting info about this plugin: +// ifvers (given) interface_version metamod is using +// pPlugInfo (requested) struct with info about plugin +// pMetaUtilFuncs (given) table of utility functions provided by metamod +C_DLLEXPORT int Meta_Query(char *ifvers, plugin_info_t **pPlugInfo, mutil_funcs_t *pMetaUtilFuncs) +{ + // Give metamod our plugin_info struct + *pPlugInfo = &Plugin_info; + + // Get metamod utility function table. + gpMetaUtilFuncs = pMetaUtilFuncs; + return TRUE; +} + +// Must provide at least one of these.. +static META_FUNCTIONS gMetaFunctionTable = { + NULL, // pfnGetEntityAPI HL SDK; called before game DLL + NULL, // pfnGetEntityAPI_Post META; called after game DLL + NULL, // pfnGetEntityAPI2 HL SDK2; called before game DLL + &GetEntityAPI2_Post, // pfnGetEntityAPI2_Post META; called after game DLL + NULL, // pfnGetNewDLLFunctions HL SDK2; called before game DLL + NULL, // pfnGetNewDLLFunctions_Post META; called after game DLL + NULL, // pfnGetEngineFunctions META; called before HL engine + NULL, // pfnGetEngineFunctions_Post META; called after HL engine +}; + +// Metamod attaching plugin to the server. +// now (given) current phase, ie during map, during changelevel, or at startup +// pFunctionTable (requested) table of function tables this plugin catches +// pMGlobals (given) global vars from metamod +// pGamedllFuncs (given) copy of function tables from game dll +C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs) +{ + if (!pMGlobals) + { + LOG_ERROR(PLID, "Meta_Attach called with null pMGlobals"); + return FALSE; + } + + gpMetaGlobals = pMGlobals; + + if (!pFunctionTable) + { + LOG_ERROR(PLID, "Meta_Attach called with null pFunctionTable"); + return FALSE; + } + + Q_memcpy(pFunctionTable, &gMetaFunctionTable, sizeof(META_FUNCTIONS)); + gpGamedllFuncs = pGamedllFuncs; + + return TRUE; +} + +// Metamod detaching plugin from the server. +// now (given) current phase, ie during map, etc +// reason (given) why detaching (refresh, console unload, forced unload, etc) +C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) +{ + return TRUE; +} diff --git a/hitboxtracker/server/src/precompiled.cpp b/hitboxtracker/server/src/precompiled.cpp new file mode 100644 index 0000000..5f656a4 --- /dev/null +++ b/hitboxtracker/server/src/precompiled.cpp @@ -0,0 +1 @@ +#include "precompiled.h" diff --git a/hitboxtracker/server/src/precompiled.h b/hitboxtracker/server/src/precompiled.h new file mode 100644 index 0000000..3b22cb7 --- /dev/null +++ b/hitboxtracker/server/src/precompiled.h @@ -0,0 +1,9 @@ +#pragma once + +#include "osconfig.h" +#include "extdll.h" +#include "cbase.h" +#include "server.h" + +#include "meta_api.h" +#include "main.h" diff --git a/msvc/hitboxtracker.sln b/msvc/hitboxtracker.sln new file mode 100644 index 0000000..9e7f52d --- /dev/null +++ b/msvc/hitboxtracker.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "client", "..\hitboxtracker\client\msvc\client.vcxproj", "{0635BDCF-8622-4483-BEAE-0646D8184654}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "server", "..\hitboxtracker\server\msvc\server.vcxproj", "{3A8F89BA-AA33-4C31-ABF8-C6FF243049D2}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "launcher", "..\hitboxtracker\launcher\msvc\launcher.vcxproj", "{E324283B-70AB-4A32-BE41-AEF5101F655B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0635BDCF-8622-4483-BEAE-0646D8184654}.Debug|Win32.ActiveCfg = Debug|Win32 + {0635BDCF-8622-4483-BEAE-0646D8184654}.Debug|Win32.Build.0 = Debug|Win32 + {0635BDCF-8622-4483-BEAE-0646D8184654}.Release|Win32.ActiveCfg = Release|Win32 + {0635BDCF-8622-4483-BEAE-0646D8184654}.Release|Win32.Build.0 = Release|Win32 + {3A8F89BA-AA33-4C31-ABF8-C6FF243049D2}.Debug|Win32.ActiveCfg = Debug|Win32 + {3A8F89BA-AA33-4C31-ABF8-C6FF243049D2}.Debug|Win32.Build.0 = Debug|Win32 + {3A8F89BA-AA33-4C31-ABF8-C6FF243049D2}.Release|Win32.ActiveCfg = Release|Win32 + {3A8F89BA-AA33-4C31-ABF8-C6FF243049D2}.Release|Win32.Build.0 = Release|Win32 + {E324283B-70AB-4A32-BE41-AEF5101F655B}.Debug|Win32.ActiveCfg = Debug|Win32 + {E324283B-70AB-4A32-BE41-AEF5101F655B}.Debug|Win32.Build.0 = Debug|Win32 + {E324283B-70AB-4A32-BE41-AEF5101F655B}.Release|Win32.ActiveCfg = Release|Win32 + {E324283B-70AB-4A32-BE41-AEF5101F655B}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal