From 3f46c8d63548a740e9b18f3c1301bc82bbd5ab17 Mon Sep 17 00:00:00 2001 From: Arthurnashh Date: Mon, 23 Nov 2026 19:18:28 -0300 Subject: [PATCH 1/3] Sync source: Steamworks, movement/prediction, UI and network fixes - Add Steamworks client/server integration and test AppID config - Update local movement, action map, stance and player prediction code - Update network queue/server, inventory, zombie, vehicle and UI code - Update DX9 x64 project and runtime configuration - Source only: no build artifacts or binaries --- El/DataSignatures/dataSignatures.cpp | 8 + El/ParamFile/paramFile.cpp | 34 +- El/QStream/qbStream.hpp | 125 ++ .../src/Physics/enf_physicsbulletmanager.cpp | 11 +- cfg/Bin/cfgVehicles.hpp | 1 + extern/Steamworks/isteamapps.h | 149 +++ extern/Steamworks/isteamappticket.h | 28 + extern/Steamworks/isteamclient.h | 361 ++++++ extern/Steamworks/isteamcontroller.h | 62 + extern/Steamworks/isteamfriends.h | 609 +++++++++ extern/Steamworks/isteamgamecoordinator.h | 75 ++ extern/Steamworks/isteamgameserver.h | 452 +++++++ extern/Steamworks/isteamgameserverstats.h | 99 ++ extern/Steamworks/isteamhttp.h | 176 +++ extern/Steamworks/isteammasterserverupdater.h | 1 + extern/Steamworks/isteammatchmaking.h | 731 +++++++++++ extern/Steamworks/isteamnetworking.h | 306 +++++ extern/Steamworks/isteamps3overlayrenderer.h | 91 ++ extern/Steamworks/isteamremotestorage.h | 649 ++++++++++ extern/Steamworks/isteamscreenshots.h | 96 ++ extern/Steamworks/isteamugc.h | 192 +++ extern/Steamworks/isteamunifiedmessages.h | 63 + extern/Steamworks/isteamuser.h | 351 ++++++ extern/Steamworks/isteamuserstats.h | 463 +++++++ extern/Steamworks/isteamutils.h | 304 +++++ extern/Steamworks/matchmakingtypes.h | 249 ++++ extern/Steamworks/steam_api.h | 539 ++++++++ extern/Steamworks/steam_appid.test.txt | 1 + extern/Steamworks/steam_gameserver.h | 163 +++ extern/Steamworks/steamclientpublic.h | 1093 +++++++++++++++++ extern/Steamworks/steamencryptedappticket.h | 32 + extern/Steamworks/steamhttpenums.h | 94 ++ extern/Steamworks/steamps3params.h | 112 ++ extern/Steamworks/steamtypes.h | 151 +++ extern/Steamworks/steamuniverse.h | 27 + lib/Inventory/inventory.cpp | 73 +- lib/Inventory/inventory.hpp | 14 +- lib/Marina/matrixA_old.hpp | 46 +- lib/Network/network.cpp | 113 +- lib/Network/network.hpp | 12 +- lib/Network/networkClient.cpp | 77 +- lib/Network/networkImpl.hpp | 66 +- lib/Network/networkServer.cpp | 403 +++++- lib/Shape/material.cpp | 1 + lib/Shape/shape.cpp | 1 + lib/UI/displayUI.cpp | 241 +++- lib/UI/displayUI.hpp | 19 + lib/UI/optionsUI.cpp | 1 + lib/UI/uiContainers.cpp | 13 + lib/UI/uiMap.cpp | 313 +++-- lib/UI/uiMap.hpp | 1 + lib/d3d9/txtD3D9.cpp | 4 +- lib/gameStateExt.cpp | 9 + lib/helicopter.cpp | 13 +- lib/lib.vcxproj | 26 +- lib/main.cpp | 210 +++- lib/person.cpp | 34 +- lib/person.hpp | 2 + lib/proxyWeapon.hpp | 1 + lib/retailConfig.h | 24 +- lib/serverConfig.h | 19 + lib/simul.cpp | 20 +- lib/soldierOld.cpp | 289 ++++- lib/soldierOld.hpp | 6 + lib/transport.cpp | 22 +- lib/vehicleAI.cpp | 20 +- lib/world.cpp | 20 + lib/zombie.cpp | 139 ++- lib/zombie.hpp | 4 + release-assets/physics/materials.h | 3 + release-assets/server/serverDZ.cfg | 2 + 71 files changed, 9914 insertions(+), 245 deletions(-) create mode 100644 extern/Steamworks/isteamapps.h create mode 100644 extern/Steamworks/isteamappticket.h create mode 100644 extern/Steamworks/isteamclient.h create mode 100644 extern/Steamworks/isteamcontroller.h create mode 100644 extern/Steamworks/isteamfriends.h create mode 100644 extern/Steamworks/isteamgamecoordinator.h create mode 100644 extern/Steamworks/isteamgameserver.h create mode 100644 extern/Steamworks/isteamgameserverstats.h create mode 100644 extern/Steamworks/isteamhttp.h create mode 100644 extern/Steamworks/isteammasterserverupdater.h create mode 100644 extern/Steamworks/isteammatchmaking.h create mode 100644 extern/Steamworks/isteamnetworking.h create mode 100644 extern/Steamworks/isteamps3overlayrenderer.h create mode 100644 extern/Steamworks/isteamremotestorage.h create mode 100644 extern/Steamworks/isteamscreenshots.h create mode 100644 extern/Steamworks/isteamugc.h create mode 100644 extern/Steamworks/isteamunifiedmessages.h create mode 100644 extern/Steamworks/isteamuser.h create mode 100644 extern/Steamworks/isteamuserstats.h create mode 100644 extern/Steamworks/isteamutils.h create mode 100644 extern/Steamworks/matchmakingtypes.h create mode 100644 extern/Steamworks/steam_api.h create mode 100644 extern/Steamworks/steam_appid.test.txt create mode 100644 extern/Steamworks/steam_gameserver.h create mode 100644 extern/Steamworks/steamclientpublic.h create mode 100644 extern/Steamworks/steamencryptedappticket.h create mode 100644 extern/Steamworks/steamhttpenums.h create mode 100644 extern/Steamworks/steamps3params.h create mode 100644 extern/Steamworks/steamtypes.h create mode 100644 extern/Steamworks/steamuniverse.h create mode 100644 release-assets/physics/materials.h diff --git a/El/DataSignatures/dataSignatures.cpp b/El/DataSignatures/dataSignatures.cpp index e3234cdd..075e1423 100644 --- a/El/DataSignatures/dataSignatures.cpp +++ b/El/DataSignatures/dataSignatures.cpp @@ -406,6 +406,11 @@ bool DataSignatures::VerifySignature(const DSHash &hash, const DSSignature &sign } } break; + case 3: + RSADecrypt((unsigned char *)calculatedHash.Data(), + (const unsigned char *)signature._content3.Data(), signature._content3.Size(), + keyData, keySize); + break; } Temp revHash; revHash.Realloc(hash._content.Size()); for (int i=0, siz=hash._content.Size()-1; i<=siz; i++) @@ -458,6 +463,9 @@ bool DataSignatures::VerifySignature(const DSHash &hash, const DSSignature &sign } } break; + case 3: + ok = CryptVerifySignature(handle, (BYTE *)signature._content3.Data(), signature._content3.Size(), key, NULL, 0) == TRUE; + break; } } diff --git a/El/ParamFile/paramFile.cpp b/El/ParamFile/paramFile.cpp index afe4d7fb..5927b8b0 100644 --- a/El/ParamFile/paramFile.cpp +++ b/El/ParamFile/paramFile.cpp @@ -5938,7 +5938,12 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(const char *name, IParamClassSource * SerializeBinStream f(&in); SerializeBin(f, source, context); - if (f.GetError() != SerializeBinStream::EOK) return f.GetError(); + if (f.GetError() != SerializeBinStream::EOK) + { + RptF("Config binary load failed: file=%s error=%d offset=%d version=%d", + name, (int)f.GetError(), f.TellG(), f.GetVersion()); + return f.GetError(); + } SetFile(this); //SetSource(new ParamClassOwnerNoUnload("",name)); @@ -5947,6 +5952,9 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(const char *name, IParamClassSource * // load variables LoadVariables(f, parentVariables, globalVariables); + if (f.GetError() != SerializeBinStream::EOK) + RptF("Config variable load failed: file=%s error=%d offset=%d version=%d", + name, (int)f.GetError(), f.TellG(), f.GetVersion()); #if DIAG_OPEN if (_entries.Size() > 0) @@ -5968,7 +5976,13 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(QIStream &in, IParamClassSource *sour SerializeBinStream f(&in); SerializeBin(f, source, context); - if (f.GetError() != SerializeBinStream::EOK) return f.GetError(); + if (f.GetError() != SerializeBinStream::EOK) + { + RString sourceName = source ? source->GetOwnerDebugName() : RString(""); + RptF("Config binary stream load failed: source=%s error=%d offset=%d version=%d", + (const char *)sourceName, (int)f.GetError(), f.TellG(), f.GetVersion()); + return f.GetError(); + } SetFile(this); //SetSource(new ParamClassOwnerNoUnload("",name)); @@ -5977,6 +5991,12 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(QIStream &in, IParamClassSource *sour // load variables LoadVariables(f, parentVariables, globalVariables); + if (f.GetError() != SerializeBinStream::EOK) + { + RString sourceName = source ? source->GetOwnerDebugName() : RString(""); + RptF("Config variable stream load failed: source=%s error=%d offset=%d version=%d", + (const char *)sourceName, (int)f.GetError(), f.TellG(), f.GetVersion()); + } #if DIAG_OPEN if (_entries.Size() > 0) @@ -6020,7 +6040,12 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(QFBank &bank, const char *name, IEval //context._fullLoad = false; SerializeBin(f, source, context); - if (f.GetError() != SerializeBinStream::EOK) return f.GetError(); + if (f.GetError() != SerializeBinStream::EOK) + { + RptF("Config bank load failed: file=%s error=%d offset=%d version=%d", + name, (int)f.GetError(), f.TellG(), f.GetVersion()); + return f.GetError(); + } SetFile(this); //SetSource(new ParamClassOwnerFilename("",name)); @@ -6028,6 +6053,9 @@ ParamFile::ErrorCode ParamFile::ParseBinEx(QFBank &bank, const char *name, IEval //Assert(CheckIntegrity()); LoadVariables(f, parentVariables, globalVariables); + if (f.GetError() != SerializeBinStream::EOK) + RptF("Config bank variable load failed: file=%s error=%d offset=%d version=%d", + name, (int)f.GetError(), f.TellG(), f.GetVersion()); #if DIAG_OPEN if (_entries.Size() > 0) diff --git a/El/QStream/qbStream.hpp b/El/QStream/qbStream.hpp index e726e36d..085ae979 100644 --- a/El/QStream/qbStream.hpp +++ b/El/QStream/qbStream.hpp @@ -325,6 +325,65 @@ struct AddNonDataFile return false; } }; + +// DayZ signature version 3 hashes selected script/config payloads, together +// with the normalized file list and PBO prefix. Binary assets are deliberately +// excluded by the DayZ v3 policy. +struct DayZV3File +{ + unsigned long startOffset; + unsigned long length; + RString name; + DayZV3File() : startOffset(0), length(0) {} + DayZV3File(unsigned long offset, unsigned long len, RString fileName) + : startOffset(offset), length(len), name(fileName) {} + ClassIsMovable(DayZV3File); +}; + +struct AddDayZV3File +{ + AutoArray &_files; + AddDayZV3File(AutoArray &files) : _files(files) {} + bool operator ()(const FileInfoO &info, const FileBankType *container) + { + if (info.length > 0) + { + const char *ext = GetFileExt(info.name); + if (ext && *ext == '.' && + (!stricmp(ext+1,"bikb") || !stricmp(ext+1,"c") || !stricmp(ext+1,"ext") || + !stricmp(ext+1,"hpp") || !stricmp(ext+1,"cfg") || !stricmp(ext+1,"h") || + !stricmp(ext+1,"inc"))) + _files.Add(DayZV3File(info.startOffset, info.length, info.name)); + } + return false; + } +}; + +struct AddDayZV3Name +{ + AutoArray &_names; + AddDayZV3Name(AutoArray &names) : _names(names) {} + bool operator ()(const FileInfoO &info, const FileBankType *container) + { + if (info.length > 0) + { + RString name = info.name; + name.Lower(); + _names.Add(name); + } + return false; + } +}; + +static int CmpDayZV3Files(const DayZV3File *a, const DayZV3File *b) +{ + return a->startOffset < b->startOffset ? -1 : (a->startOffset > b->startOffset ? 1 : 0); +} + +static int CmpDayZV3Names(const RString *a, const RString *b) +{ + return strcmp(*a, *b); +} //@} NonDataFileHash calculation #define MT_SAFE 0 @@ -609,6 +668,72 @@ class QFBank: public RefCount //break; //unreachable code } } + return false; + case 3: + { + // BISign v3 selects the DayZ script/config file hash (hash3). + AutoArray files; + _files.ForEachF(AddDayZV3File(files)); + QSort(files.Data(), files.Size(), CmpDayZV3Files); + + HashCalculator fileCalculator; + if (files.Size() > 0) + { + QIStreamDataSource in; + in.AttachSource(_fileAccess); + for (int i = 0; i < files.Size(); i++) + { + in.seekg(files[i].startOffset); + int remaining = files[i].length; + char buffer[16*1024]; + while (remaining > 0) + { + int chunk = remaining > (int)sizeof(buffer) ? (int)sizeof(buffer) : remaining; + size_t read = in.read(buffer, chunk); + if (read == 0 || in.fail()) return false; + fileCalculator.Add(buffer, read); + remaining -= (int)read; + } + } + } + else + { + // DayZ v3 uses the reversed sentinel when no files match its allowlist. + fileCalculator.Add("gnihton", 7); + } + AutoArray fileHash; + if (!fileCalculator.GetResult(fileHash)) return false; + + AutoArray names; + _files.ForEachF(AddDayZV3Name(names)); + QSort(names.Data(), names.Size(), CmpDayZV3Names); + HashCalculator nameCalculator; + const char *previous = NULL; + for (int i = 0; i < names.Size(); i++) + { + if (!previous || strcmp(previous, names[i]) != 0) + { + nameCalculator.Add(names[i].Data(), names[i].GetLength()); + previous = names[i]; + } + } + AutoArray nameHash; + if (!nameCalculator.GetResult(nameHash)) return false; + + HashCalculator finalCalculator; + finalCalculator.Add(fileHash.Data(), fileHash.Size()); + finalCalculator.Add(nameHash.Data(), nameHash.Size()); + if (GetPrefix().GetLength() > 0) + { + finalCalculator.Add(GetPrefix().Data(), GetPrefix().GetLength()); + if (GetPrefix()[GetPrefix().GetLength()-1] != '\\') + finalCalculator.Add("\\", 1); + } + AutoArray finalHash; + if (!finalCalculator.GetResult(finalHash)) return false; + hash.Realloc(finalHash.Data(), finalHash.Size()); + return true; + } } return false; } diff --git a/Enfusion/src/Physics/enf_physicsbulletmanager.cpp b/Enfusion/src/Physics/enf_physicsbulletmanager.cpp index 05cc3ad3..1d5ea427 100644 --- a/Enfusion/src/Physics/enf_physicsbulletmanager.cpp +++ b/Enfusion/src/Physics/enf_physicsbulletmanager.cpp @@ -731,13 +731,18 @@ bool BulletManager::LoadMaterials(const char* name) GameDataNamespace globals(NULL, RString(), false); // TODO: parsing namespace if access to globals needed ParamFile matFile; - matFile.ParseBinOrTxt(name, NULL, NULL, &globals); + const bool physicsMaterialsInVfs = QFBankQueryFunctions::FileExists(name); + const bool physicsMaterialsOnDisk = QIFileFunctions::FileExists(name); + const bool physicsMaterialsParsed = matFile.ParseBinOrTxt(name, NULL, NULL, &globals); + RptF("PhysicsMaterialsDiagnostic file=%s vfs=%d disk=%d parsed=%d entries=%d", + cc_cast(name), physicsMaterialsInVfs, physicsMaterialsOnDisk, + physicsMaterialsParsed, matFile.GetEntryCount()); BulletPhysicsMaterial* mat = new BulletPhysicsMaterial(name); - if (matFile.GetEntryCount()==0) + if (!physicsMaterialsParsed || matFile.GetEntryCount()==0) { - RptF("Cannot load material file %s",cc_cast(name)); + RptF("Physics material file is present but invalid: %s",cc_cast(name)); return 0; } else diff --git a/cfg/Bin/cfgVehicles.hpp b/cfg/Bin/cfgVehicles.hpp index b112946d..e7aa3f3b 100644 --- a/cfg/Bin/cfgVehicles.hpp +++ b/cfg/Bin/cfgVehicles.hpp @@ -2779,6 +2779,7 @@ class CfgVehicles emptyGloves = ""; emptyBack = ""; emptyShoulder = ""; + emptyShoulder2 = ""; // optional second large-weapon slot emptyMelee = ""; emptyMask = ""; }; diff --git a/extern/Steamworks/isteamapps.h b/extern/Steamworks/isteamapps.h new file mode 100644 index 00000000..7070e2e9 --- /dev/null +++ b/extern/Steamworks/isteamapps.h @@ -0,0 +1,149 @@ +//====== Copyright © 1996-2008, 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( AppId_t appID, 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; + virtual bool BIsAppInstalled( AppId_t appID ) = 0; // returns true if that app is installed (not necessarily owned) + + virtual CSteamID GetAppOwner() = 0; // returns the SteamID of the original owner. If different from current user, it's borrowed + + // Returns the associated launch param if the game is run via steam://run///?param1=value1;param2=value2;param3=value3 etc. + // Parameter names starting with the character '@' are reserved for internal use and will always return and empty string. + // Parameter names starting with an underscore '_' are reserved for steam features -- they can be queried by the game, + // but it is advised that you not param names beginning with an underscore for your own features. + virtual const char *GetLaunchQueryParam( const char *pchKey ) = 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_VERSION006" + +// 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 ]; +}; + +//--------------------------------------------------------------------------------- +// Purpose: posted after the user gains executes a steam url with query parameters +// such as steam://run///?param1=value1;param2=value2;param3=value3; etc +// while the game is already running. The new params can be queried +// with GetLaunchQueryParam. +//--------------------------------------------------------------------------------- +struct NewLaunchQueryParameters_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 14 }; +}; + + +#pragma pack( pop ) +#endif // ISTEAMAPPS_H diff --git a/extern/Steamworks/isteamappticket.h b/extern/Steamworks/isteamappticket.h new file mode 100644 index 00000000..21fb9e13 --- /dev/null +++ b/extern/Steamworks/isteamappticket.h @@ -0,0 +1,28 @@ +//====== Copyright 1996-2008, Valve Corporation, All rights reserved. ======= +// +// Purpose: a private, but well versioned, interface to get at critical bits +// of a steam3 appticket - consumed by the simple drm wrapper to let it +// ask about ownership with greater confidence. +// +//============================================================================= + +#ifndef ISTEAMAPPTICKET_H +#define ISTEAMAPPTICKET_H +#pragma once + +//----------------------------------------------------------------------------- +// Purpose: hand out a reasonable "future proof" view of an app ownership ticket +// the raw (signed) buffer, and indices into that buffer where the appid and +// steamid are located. the sizes of the appid and steamid are implicit in +// (each version of) the interface - currently uin32 appid and uint64 steamid +//----------------------------------------------------------------------------- +class ISteamAppTicket +{ +public: + virtual uint32 GetAppOwnershipTicketData( uint32 nAppID, void *pvBuffer, uint32 cbBufferLength, uint32 *piAppId, uint32 *piSteamId, uint32 *piSignature, uint32 *pcbSignature ) = 0; +}; + +#define STEAMAPPTICKET_INTERFACE_VERSION "STEAMAPPTICKET_INTERFACE_VERSION001" + + +#endif // ISTEAMAPPTICKET_H diff --git a/extern/Steamworks/isteamclient.h b/extern/Steamworks/isteamclient.h new file mode 100644 index 00000000..f0b52e41 --- /dev/null +++ b/extern/Steamworks/isteamclient.h @@ -0,0 +1,361 @@ +//====== Copyright � 1996-2008, 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; +class ISteamController; +class ISteamUGC; + +//----------------------------------------------------------------------------- +// 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; + + // Exposes the ISteamController interface + virtual ISteamController *GetISteamController( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // Exposes the ISteamUGC interface + virtual ISteamUGC *GetISteamUGC( 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 }; +enum { k_iClientMusicCallbacks = 3200 }; +enum { k_iClientRemoteClientManagerCallbacks = 3300 }; +enum { k_iClientUGCCallbacks = 3400 }; +enum { k_iSteamStreamClientCallbacks = 3500 }; +enum { k_IClientProductBuilderCallbacks = 3600 }; + + +//----------------------------------------------------------------------------- +// 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/extern/Steamworks/isteamcontroller.h b/extern/Steamworks/isteamcontroller.h new file mode 100644 index 00000000..e7ef50d9 --- /dev/null +++ b/extern/Steamworks/isteamcontroller.h @@ -0,0 +1,62 @@ +//====== Copyright 1996-2013, 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/extern/Steamworks/isteamfriends.h b/extern/Steamworks/isteamfriends.h new file mode 100644 index 00000000..6dc6da65 --- /dev/null +++ b/extern/Steamworks/isteamfriends.h @@ -0,0 +1,609 @@ +//====== Copyright (C) 1996-2008, 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 nickname the current user has set for the specified player. Returns NULL if the no nickname has been set for that player. + virtual const char *GetPlayerNickname( CSteamID steamIDPlayer ) = 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 PersonaStateChange_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 *peChatEntryType, CSteamID *psteamidChatter ) = 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 "SteamFriends014" + +// 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/extern/Steamworks/isteamgamecoordinator.h b/extern/Steamworks/isteamgamecoordinator.h new file mode 100644 index 00000000..5ab0637f --- /dev/null +++ b/extern/Steamworks/isteamgamecoordinator.h @@ -0,0 +1,75 @@ +//====== Copyright ©, Valve Corporation, All rights reserved. ======= +// +// Purpose: interface to the game coordinator for this application +// +//============================================================================= + +#ifndef ISTEAMGAMECOORDINATOR +#define ISTEAMGAMECOORDINATOR +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" + + +// list of possible return values from the ISteamGameCoordinator API +enum EGCResults +{ + k_EGCResultOK = 0, + k_EGCResultNoMessage = 1, // There is no message in the queue + k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message + k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam + k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage +}; + + +//----------------------------------------------------------------------------- +// Purpose: Functions for sending and receiving messages from the Game Coordinator +// for this application +//----------------------------------------------------------------------------- +class ISteamGameCoordinator +{ +public: + + // sends a message to the Game Coordinator + virtual EGCResults SendMessage( uint32 unMsgType, const void *pubData, uint32 cubData ) = 0; + + // returns true if there is a message waiting from the game coordinator + virtual bool IsMessageAvailable( uint32 *pcubMsgSize ) = 0; + + // fills the provided buffer with the first message in the queue and returns k_EGCResultOK or + // returns k_EGCResultNoMessage if there is no message waiting. pcubMsgSize is filled with the message size. + // If the provided buffer is not large enough to fit the entire message, k_EGCResultBufferTooSmall is returned + // and the message remains at the head of the queue. + virtual EGCResults RetrieveMessage( uint32 *punMsgType, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize ) = 0; + +}; +#define STEAMGAMECOORDINATOR_INTERFACE_VERSION "SteamGameCoordinator001" + +// 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 new message is available for reading from the message queue +struct GCMessageAvailable_t +{ + enum { k_iCallback = k_iSteamGameCoordinatorCallbacks + 1 }; + uint32 m_nMessageSize; +}; + +// callback notification - A message failed to make it to the GC. It may be down temporarily +struct GCMessageFailed_t +{ + enum { k_iCallback = k_iSteamGameCoordinatorCallbacks + 2 }; +}; + +#pragma pack( pop ) + +#endif // ISTEAMGAMECOORDINATOR diff --git a/extern/Steamworks/isteamgameserver.h b/extern/Steamworks/isteamgameserver.h new file mode 100644 index 00000000..d616e215 --- /dev/null +++ b/extern/Steamworks/isteamgameserver.h @@ -0,0 +1,452 @@ +//====== Copyright (c) 1996-2008, 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 +//----------------------------------------------------------------------------- +#if defined(_WIN64) +// The x64 compatibility runtime shipped with this port exposes SteamGameServer015. +// Keep this vtable in the SDK order; the legacy x86 build continues using v011 below. +class ISteamGameServer +{ +public: + // Steamworks v015 retains this private API as its first vtable slot. + virtual bool InitGameServer(uint32 unIP, uint16 usGamePort, uint16 usQueryPort, uint32 unFlags, AppId_t nGameAppId, const char *pchVersionString) = 0; + virtual void SetProduct(const char *pszProduct) = 0; + virtual void SetGameDescription(const char *pszGameDescription) = 0; + virtual void SetModDir(const char *pszModDir) = 0; + virtual void SetDedicatedServer(bool bDedicated) = 0; + virtual void LogOn(const char *pszToken) = 0; + virtual void LogOnAnonymous() = 0; + virtual void LogOff() = 0; + virtual bool BLoggedOn() = 0; + virtual bool BSecure() = 0; + virtual CSteamID GetSteamID() = 0; + virtual bool WasRestartRequested() = 0; + virtual void SetMaxPlayerCount(int cPlayersMax) = 0; + virtual void SetBotPlayerCount(int cBotplayers) = 0; + virtual void SetServerName(const char *pszServerName) = 0; + virtual void SetMapName(const char *pszMapName) = 0; + virtual void SetPasswordProtected(bool bPasswordProtected) = 0; + virtual void SetSpectatorPort(uint16 unSpectatorPort) = 0; + virtual void SetSpectatorServerName(const char *pszSpectatorServerName) = 0; + virtual void ClearAllKeyValues() = 0; + virtual void SetKeyValue(const char *pKey, const char *pValue) = 0; + virtual void SetGameTags(const char *pchGameTags) = 0; + virtual void SetGameData(const char *pchGameData) = 0; + virtual void SetRegion(const char *pszRegion) = 0; + virtual void SetAdvertiseServerActive(bool bActive) = 0; + void EnableHeartbeats(bool bActive) { SetAdvertiseServerActive(bActive); } + virtual HAuthTicket GetAuthSessionTicket(void *pTicket, int cbMaxTicket, uint32 *pcbTicket, const void *pSnid) = 0; + virtual EBeginAuthSessionResult BeginAuthSession(const void *pAuthTicket, int cbAuthTicket, CSteamID steamID) = 0; + virtual void EndAuthSession(CSteamID steamID) = 0; + virtual void CancelAuthTicket(HAuthTicket hAuthTicket) = 0; + virtual EUserHasLicenseForAppResult UserHasLicenseForApp(CSteamID steamID, AppId_t appID) = 0; + virtual bool RequestUserGroupStatus(CSteamID steamIDUser, CSteamID steamIDGroup) = 0; + virtual void GetGameplayStats() = 0; + virtual SteamAPICall_t GetServerReputation() = 0; + virtual uint64 GetPublicIP() = 0; + virtual bool HandleIncomingPacket(const void *pData, int cbData, uint32 srcIP, uint16 srcPort) = 0; + virtual int GetNextOutgoingPacket(void *pOut, int cbMaxOut, uint32 *pNetAdr, uint16 *pPort) = 0; + virtual SteamAPICall_t AssociateWithClan(CSteamID steamIDClan) = 0; + virtual SteamAPICall_t ComputeNewPlayerCompatibility(CSteamID steamIDNewPlayer) = 0; + virtual bool SendUserConnectAndAuthenticate(uint32 unIPClient, const void *pvAuthBlob, uint32 cubAuthBlobSize, CSteamID *pSteamIDUser) = 0; + virtual CSteamID CreateUnauthenticatedUserConnection() = 0; + virtual void SendUserDisconnect(CSteamID steamIDUser) = 0; + virtual bool BUpdateUserData(CSteamID steamIDUser, const char *pchPlayerName, uint32 uScore) = 0; + virtual void SetHeartbeatIntervalDeprecated(int iHeartbeatInterval) = 0; + virtual void ForceHeartbeatDeprecated() = 0; +}; +#else +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; + +}; + +#endif // _WIN64 + +#if defined(_WIN64) +#define STEAMGAMESERVER_INTERFACE_VERSION "SteamGameServer015" +#else +#define STEAMGAMESERVER_INTERFACE_VERSION "SteamGameServer011" +#endif + +// 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; // SteamID of approved player + CSteamID m_OwnerSteamID; // SteamID of original owner for game license +}; + + +// 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/extern/Steamworks/isteamgameserverstats.h b/extern/Steamworks/isteamgameserverstats.h new file mode 100644 index 00000000..0facf433 --- /dev/null +++ b/extern/Steamworks/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/extern/Steamworks/isteamhttp.h b/extern/Steamworks/isteamhttp.h new file mode 100644 index 00000000..9ac550aa --- /dev/null +++ b/extern/Steamworks/isteamhttp.h @@ -0,0 +1,176 @@ +//====== Copyright © 1996-2009, 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 \ No newline at end of file diff --git a/extern/Steamworks/isteammasterserverupdater.h b/extern/Steamworks/isteammasterserverupdater.h new file mode 100644 index 00000000..4be0ca5c --- /dev/null +++ b/extern/Steamworks/isteammasterserverupdater.h @@ -0,0 +1 @@ +#error "This file isn't used any more" diff --git a/extern/Steamworks/isteammatchmaking.h b/extern/Steamworks/isteammatchmaking.h new file mode 100644 index 00000000..b6f349ab --- /dev/null +++ b/extern/Steamworks/isteammatchmaking.h @@ -0,0 +1,731 @@ +//====== Copyright © 1996-2008, 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/extern/Steamworks/isteamnetworking.h b/extern/Steamworks/isteamnetworking.h new file mode 100644 index 00000000..8f70819d --- /dev/null +++ b/extern/Steamworks/isteamnetworking.h @@ -0,0 +1,306 @@ +//====== Copyright © 1996-2008, 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/extern/Steamworks/isteamps3overlayrenderer.h b/extern/Steamworks/isteamps3overlayrenderer.h new file mode 100644 index 00000000..4e07d4a1 --- /dev/null +++ b/extern/Steamworks/isteamps3overlayrenderer.h @@ -0,0 +1,91 @@ +//====== Copyright © 1996-2010, Valve Corporation, All rights reserved. ======= +// +// Purpose: interface the game must provide Steam with on PS3 in order for the +// Steam overlay to render. +// +//============================================================================= + +#ifndef ISTEAMPS3OVERLAYRENDERER_H +#define ISTEAMPS3OVERLAYRENDERER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "cell/pad.h" + +//----------------------------------------------------------------------------- +// Purpose: Enum for supported gradient directions +//----------------------------------------------------------------------------- +enum EOverlayGradientDirection +{ + k_EOverlayGradientHorizontal = 1, + k_EOverlayGradientVertical = 2, + k_EOverlayGradientNone = 3, +}; + +// Helpers for fetching individual color components from ARGB packed DWORD colors Steam PS3 overlay renderer uses. +#define STEAM_COLOR_RED( color ) \ + (int)(((color)>>16)&0xff) + +#define STEAM_COLOR_GREEN( color ) \ + (int)(((color)>>8)&0xff) + +#define STEAM_COLOR_BLUE( color ) \ + (int)((color)&0xff) + +#define STEAM_COLOR_ALPHA( color ) \ + (int)(((color)>>24)&0xff) + + +//----------------------------------------------------------------------------- +// Purpose: Interface the game must expose to Steam for rendering +//----------------------------------------------------------------------------- +class ISteamPS3OverlayRenderHost +{ +public: + + // Interface for game engine to implement which Steam requires to render. + + // Draw a textured rect. This may use only part of the texture and will pass texture coords, it will also possibly request a gradient and will specify colors for vertexes. + virtual void DrawTexturedRect( int x0, int y0, int x1, int y1, float u0, float v0, float u1, float v1, int32 iTextureID, DWORD colorStart, DWORD colorEnd, EOverlayGradientDirection eDirection ) = 0; + + // Load a RGBA texture for Steam, or update a previously loaded one. Updates may be partial. You must not evict or remove this texture once Steam has uploaded it. + virtual void LoadOrUpdateTexture( int32 iTextureID, bool bIsFullTexture, int x0, int y0, uint32 uWidth, uint32 uHeight, int32 iBytes, char *pData ) = 0; + + // Delete a texture Steam previously uploaded + virtual void DeleteTexture( int32 iTextureID ) = 0; + + // Delete all previously uploaded textures + virtual void DeleteAllTextures() = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Interface Steam exposes for the game to tell it when to render, etc. +//----------------------------------------------------------------------------- +class ISteamPS3OverlayRender +{ +public: + + // Call once at startup to initialize the Steam overlay and pass it your host interface ptr + virtual bool BHostInitialize( uint32 unScreenWidth, uint32 unScreenHeight, uint32 unRefreshRate, ISteamPS3OverlayRenderHost *pRenderHost, void *CellFontLib ) = 0; + + // Call this once a frame when you are ready for the Steam overlay to render (ie, right before flipping buffers, after all your rendering) + virtual void Render() = 0; + + // Call this everytime you read input on PS3. + // + // If this returns true, then the overlay is active and has consumed the input, your game + // should then ignore all the input until BHandleCellPadData once again returns false, which + // will mean the overlay is deactivated. + virtual bool BHandleCellPadData( const CellPadData &padData ) = 0; + + // Call this if you detect no controllers connected or that the XMB is intercepting input + // + // This is important to clear input state for the overlay, so keys left down during XMB activation + // are not continued to be processed. + virtual bool BResetInputState() = 0; +}; + + +#endif // ISTEAMPS3OVERLAYRENDERER_H \ No newline at end of file diff --git a/extern/Steamworks/isteamremotestorage.h b/extern/Steamworks/isteamremotestorage.h new file mode 100644 index 00000000..3f9aa4c2 --- /dev/null +++ b/extern/Steamworks/isteamremotestorage.h @@ -0,0 +1,649 @@ +//====== Copyright � 1996-2008, 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, + k_EWorkshopFileTypeControllerBinding = 12, + k_EWorkshopFileTypeSteamworksAccessInvite = 13, + + // Update k_EWorkshopFileTypeMax if you add values + k_EWorkshopFileTypeMax = 14 + +}; + +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 +}; + +enum +{ + k_WorkshopForceLoadPublishedFileDetailsFromCache = -1 +}; + +enum EUGCReadAction +{ + // Keeps the file handle open unless the last byte is read. You can use this when reading large files (over 100MB) in sequential chunks. + // If the last byte is read, this will behave the same as k_EUGCRead_Close. Otherwise, it behaves the same as k_EUGCRead_ContinueReading. + // This value maintains the same behavior as before the EUGCReadAction parameter was introduced. + k_EUGCRead_ContinueReadingUntilFinished = 0, + + // Keeps the file handle open. Use this when using UGCRead to seek to different parts of the file. + // When you are done seeking around the file, make a final call with k_EUGCRead_Close to close it. + k_EUGCRead_ContinueReading = 1, + + // Frees the file handle. Use this when you're done reading the content. + // To read the file from Steam again you will need to call UGCDownload again. + k_EUGCRead_Close = 2, +}; + + +//----------------------------------------------------------------------------- +// 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, EUGCReadAction eAction ) = 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 k_WorkshopForceLoadPublishedFileDetailsFromCache 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_VERSION012" + + +// 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 + bool m_bAcceptedForUse; // developer has specifically flagged this item as accepted in the Workshop +}; + + +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 ]; + AppId_t m_nAppId; + uint32 m_unStartIndex; +}; + + +//----------------------------------------------------------------------------- +// 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; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Called when the content for a published file is updated +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileUpdated_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 30 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. + UGCHandle_t m_hFile; // The new content +}; + + + +#pragma pack( pop ) + + +#endif // ISTEAMREMOTESTORAGE_H diff --git a/extern/Steamworks/isteamscreenshots.h b/extern/Steamworks/isteamscreenshots.h new file mode 100644 index 00000000..cfa72114 --- /dev/null +++ b/extern/Steamworks/isteamscreenshots.h @@ -0,0 +1,96 @@ +//====== Copyright � 1996-2008, 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/extern/Steamworks/isteamugc.h b/extern/Steamworks/isteamugc.h new file mode 100644 index 00000000..b4a178fc --- /dev/null +++ b/extern/Steamworks/isteamugc.h @@ -0,0 +1,192 @@ +//====== Copyright 1996-2013, Valve Corporation, All rights reserved. ======= +// +// Purpose: interface to steam ugc +// +//============================================================================= + +#ifndef ISTEAMUGC_H +#define ISTEAMUGC_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 + + +typedef uint64 UGCQueryHandle_t; + +const UGCQueryHandle_t k_UGCQueryHandleInvalid = 0xffffffffffffffffull; + +// Matching UGC types for queries +enum EUGCMatchingUGCType +{ + k_EUGCMatchingUGCType_Items = 0, // both mtx items and ready-to-use items + k_EUGCMatchingUGCType_Items_Mtx = 1, + k_EUGCMatchingUGCType_Items_ReadyToUse = 2, + k_EUGCMatchingUGCType_Collections = 3, + k_EUGCMatchingUGCType_Artwork = 4, + k_EUGCMatchingUGCType_Videos = 5, + k_EUGCMatchingUGCType_Screenshots = 6, + k_EUGCMatchingUGCType_AllGuides = 7, // both web guides and integrated guides + k_EUGCMatchingUGCType_WebGuides = 8, + k_EUGCMatchingUGCType_IntegratedGuides = 9, + k_EUGCMatchingUGCType_UsableInGame = 10, // ready-to-use items and integrated guides + k_EUGCMatchingUGCType_ControllerBindings = 11, +}; + +// Different lists of published UGC for a user. +// If the current logged in user is different than the specified user, then some options may not be allowed. +enum EUserUGCList +{ + k_EUserUGCList_Published, + k_EUserUGCList_VotedOn, + k_EUserUGCList_VotedUp, + k_EUserUGCList_VotedDown, + k_EUserUGCList_WillVoteLater, + k_EUserUGCList_Favorited, + k_EUserUGCList_Subscribed, + k_EUserUGCList_UsedOrPlayed, + k_EUserUGCList_Followed, +}; + +// Sort order for user published UGC lists (defaults to creation order descending) +enum EUserUGCListSortOrder +{ + k_EUserUGCListSortOrder_CreationOrderDesc, + k_EUserUGCListSortOrder_CreationOrderAsc, + k_EUserUGCListSortOrder_TitleAsc, + k_EUserUGCListSortOrder_LastUpdatedDesc, + k_EUserUGCListSortOrder_SubscriptionDateDesc, + k_EUserUGCListSortOrder_VoteScoreDesc, + k_EUserUGCListSortOrder_ForModeration, +}; + +// Combination of sorting and filtering for queries across all UGC +enum EUGCQuery +{ + k_EUGCQuery_RankedByVote = 0, + k_EUGCQuery_RankedByPublicationDate = 1, + k_EUGCQuery_AcceptedForGameRankedByAcceptanceDate = 2, + k_EUGCQuery_RankedByTrend = 3, + k_EUGCQuery_FavoritedByFriendsRankedByPublicationDate = 4, + k_EUGCQuery_CreatedByFriendsRankedByPublicationDate = 5, + k_EUGCQuery_RankedByNumTimesReported = 6, + k_EUGCQuery_CreatedByFollowedUsersRankedByPublicationDate = 7, + k_EUGCQuery_NotYetRated = 8, + k_EUGCQuery_RankedByTotalVotesAsc = 9, + k_EUGCQuery_RankedByVotesUp = 10, + k_EUGCQuery_RankedByTextSearch = 11, +}; + + +const uint32 kNumUGCResultsPerPage = 50; + +// Details for a single published file/UGC +struct SteamUGCDetails_t +{ + PublishedFileId_t m_nPublishedFileId; + EResult m_eResult; // The result of the operation. + EWorkshopFileType m_eFileType; // Type of the file + 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 + 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 + uint32 m_rtimeAddedToUserList; // time when the user added the published file to their list (not always applicable) + ERemoteStoragePublishedFileVisibility m_eVisibility; // visibility + bool m_bBanned; // whether the file was banned + bool m_bAcceptedForUse; // developer has specifically flagged this item as accepted in the Workshop + bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer + char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file + // file/url information + UGCHandle_t m_hFile; // The handle of the primary file + UGCHandle_t m_hPreviewFile; // The handle of the preview file + char m_pchFileName[k_cchFilenameMax]; // The cloud filename 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) + // voting information + uint32 m_unVotesUp; // number of votes up + uint32 m_unVotesDown; // number of votes down + float m_flScore; // calculated score +}; + +//----------------------------------------------------------------------------- +// Purpose: Steam UGC support API +//----------------------------------------------------------------------------- +class ISteamUGC +{ +public: + + // Query UGC associated with a user. Creator app id or consumer app id must be valid and be set to the current running app. + virtual UGCQueryHandle_t CreateQueryUserUGCRequest( AccountID_t unAccountID, EUserUGCList eListType, EUGCMatchingUGCType eMatchingUGCType, EUserUGCListSortOrder eSortOrder, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0; + + // Query for all matching UGC. Creator app id or consumer app id must be valid and be set to the current running app. + virtual UGCQueryHandle_t CreateQueryAllUGCRequest( EUGCQuery eQueryType, EUGCMatchingUGCType eMatchingeMatchingUGCTypeFileType, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0; + + // Send the query to Steam + virtual SteamAPICall_t SendQueryUGCRequest( UGCQueryHandle_t handle ) = 0; + + // Retrieve an individual result after receiving the callback for querying UGC + virtual bool GetQueryUGCResult( UGCQueryHandle_t handle, uint32 index, SteamUGCDetails_t *pDetails ) = 0; + + // Release the request to free up memory, after retrieving results + virtual bool ReleaseQueryUGCRequest( UGCQueryHandle_t handle ) = 0; + + // Options to set for querying UGC + virtual bool AddRequiredTag( UGCQueryHandle_t handle, const char *pTagName ) = 0; + virtual bool AddExcludedTag( UGCQueryHandle_t handle, const char *pTagName ) = 0; + virtual bool SetReturnLongDescription( UGCQueryHandle_t handle, bool bReturnLongDescription ) = 0; + virtual bool SetReturnTotalOnly( UGCQueryHandle_t handle, bool bReturnTotalOnly ) = 0; + + // Options only for querying user UGC + virtual bool SetCloudFileNameFilter( UGCQueryHandle_t handle, const char *pMatchCloudFileName ) = 0; + + // Options only for querying all UGC + virtual bool SetMatchAnyTag( UGCQueryHandle_t handle, bool bMatchAnyTag ) = 0; + virtual bool SetSearchText( UGCQueryHandle_t handle, const char *pSearchText ) = 0; + virtual bool SetRankedByTrendDays( UGCQueryHandle_t handle, uint32 unDays ) = 0; + + // Request full details for one piece of UGC + virtual SteamAPICall_t RequestUGCDetails( PublishedFileId_t nPublishedFileID ) = 0; + +}; + +#define STEAMUGC_INTERFACE_VERSION "STEAMUGC_INTERFACE_VERSION001" + +//----------------------------------------------------------------------------- +// Purpose: Callback for querying UGC +//----------------------------------------------------------------------------- +struct SteamUGCQueryCompleted_t +{ + enum { k_iCallback = k_iClientUGCCallbacks + 1 }; + UGCQueryHandle_t m_handle; + EResult m_eResult; + uint32 m_unNumResultsReturned; + uint32 m_unTotalMatchingResults; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback for requesting details on one piece of UGC +//----------------------------------------------------------------------------- +struct SteamUGCRequestUGCDetailsResult_t +{ + enum { k_iCallback = k_iClientUGCCallbacks + 2 }; + SteamUGCDetails_t m_details; +}; + +#pragma pack( pop ) + +#endif // ISTEAMUGC_H diff --git a/extern/Steamworks/isteamunifiedmessages.h b/extern/Steamworks/isteamunifiedmessages.h new file mode 100644 index 00000000..684f4e87 --- /dev/null +++ b/extern/Steamworks/isteamunifiedmessages.h @@ -0,0 +1,63 @@ +//====== Copyright � 1996-2007, 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/extern/Steamworks/isteamuser.h b/extern/Steamworks/isteamuser.h new file mode 100644 index 00000000..c4d39e4a --- /dev/null +++ b/extern/Steamworks/isteamuser.h @@ -0,0 +1,351 @@ +//====== Copyright (c) 1996-2008, 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" + +// Added to the current SteamUser interface for targeted auth tickets. +struct SteamNetworkingIdentity; + +// 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, const SteamNetworkingIdentity *pIdentityRemote = NULL ) = 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; + + // Trading Card badges data access + // if you only have one set of cards, the series will be 1 + // the user has can have two different badges for a series; the regular (max level 5) and the foil (max level 1) + virtual int GetGameBadgeLevel( int nSeries, bool bFoil ) = 0; + + // gets the Steam Level of the user, as shown on their profile + virtual int GetPlayerSteamLevel() = 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 "SteamUser023" + + +// 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; + CSteamID m_OwnerSteamID; // different from m_SteamID if borrowed +}; + + +//----------------------------------------------------------------------------- +// 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/extern/Steamworks/isteamuserstats.h b/extern/Steamworks/isteamuserstats.h new file mode 100644 index 00000000..1fae9bc3 --- /dev/null +++ b/extern/Steamworks/isteamuserstats.h @@ -0,0 +1,463 @@ +//====== Copyright � 1996-2009, 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/extern/Steamworks/isteamutils.h b/extern/Steamworks/isteamutils.h new file mode 100644 index 00000000..e3f462d2 --- /dev/null +++ b/extern/Steamworks/isteamutils.h @@ -0,0 +1,304 @@ +//====== Copyright � 1996-2008, 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_t status, uint64_t 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/extern/Steamworks/matchmakingtypes.h b/extern/Steamworks/matchmakingtypes.h new file mode 100644 index 00000000..c5d81d8c --- /dev/null +++ b/extern/Steamworks/matchmakingtypes.h @@ -0,0 +1,249 @@ +//========= Copyright � 1996-2008, Valve LLC, 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 + +// +// 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; + +/// Store key/value pair used in matchmaking queries. +/// +/// Actually, the name Key/Value is a bit misleading. The "key" is better +/// understood as "filter operation code" and the "value" is the operand to this +/// filter operation. The meaning of the operand depends upon the filter. +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 ); +#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; +} + +#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 + _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 + _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/extern/Steamworks/steam_api.h b/extern/Steamworks/steam_api.h new file mode 100644 index 00000000..38307ed3 --- /dev/null +++ b/extern/Steamworks/steam_api.h @@ -0,0 +1,539 @@ +//====== Copyright 1996-2008, 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" +#include "isteamugc.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 + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// 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 S_CALLTYPE SteamAPI_Shutdown(); + +// checks if a local Steam client is running +S_API bool S_CALLTYPE 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 S_CALLTYPE SteamAPI_RestartAppIfNecessary( uint32 unOwnAppID ); + +// crash dump recording functions +S_API void S_CALLTYPE SteamAPI_WriteMiniDump( uint32 uStructuredExceptionCode, void* pvExceptionInfo, uint32 uBuildID ); +S_API void S_CALLTYPE SteamAPI_SetMiniDumpComment( const char *pchMsg ); + +// interface pointers, configured by SteamAPI_Init() +S_API ISteamClient *S_CALLTYPE 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 S_CALLTYPE SteamAPI_InitSafe(); +#else + +#if defined(_PS3) +S_API bool S_CALLTYPE SteamAPI_Init( SteamPS3Params_t *pParams ); +#else +S_API bool S_CALLTYPE SteamAPI_Init(); +#endif + +S_API ISteamUser *S_CALLTYPE SteamUser(); +S_API ISteamFriends *S_CALLTYPE SteamFriends(); +S_API ISteamUtils *S_CALLTYPE SteamUtils(); +S_API ISteamMatchmaking *S_CALLTYPE SteamMatchmaking(); +S_API ISteamUserStats *S_CALLTYPE SteamUserStats(); +S_API ISteamApps *S_CALLTYPE SteamApps(); +S_API ISteamNetworking *S_CALLTYPE SteamNetworking(); +S_API ISteamMatchmakingServers *S_CALLTYPE SteamMatchmakingServers(); +S_API ISteamRemoteStorage *S_CALLTYPE SteamRemoteStorage(); +S_API ISteamScreenshots *S_CALLTYPE SteamScreenshots(); +S_API ISteamHTTP *S_CALLTYPE SteamHTTP(); +S_API ISteamUnifiedMessages *S_CALLTYPE SteamUnifiedMessages(); +S_API ISteamController *S_CALLTYPE SteamController(); +#ifdef _PS3 +S_API ISteamPS3OverlayRender *S_CALLTYPE 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 S_CALLTYPE SteamAPI_RunCallbacks(); + + + +// functions used by the utility CCallback objects to receive callbacks +S_API void S_CALLTYPE SteamAPI_RegisterCallback( class CCallbackBase *pCallback, int iCallback ); +S_API void S_CALLTYPE SteamAPI_UnregisterCallback( class CCallbackBase *pCallback ); +// functions used by the utility CCallResult objects to receive async call results +S_API void S_CALLTYPE SteamAPI_RegisterCallResult( class CCallbackBase *pCallback, SteamAPICall_t hAPICall ); +S_API void S_CALLTYPE 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; + +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 + SteamAPI_RegisterCallback( this, P::k_iCallback ); + } + + void Unregister() + { + // SteamAPI_UnregisterCallback removes k_ECallbackFlagsRegistered + SteamAPI_UnregisterCallback( this ); + } + + 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; } + ISteamController* SteamController() { return m_pController; } + ISteamUGC* SteamUGC() { return m_pSteamUGC; } +#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; + ISteamUGC *m_pSteamUGC; +#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; + m_pController = NULL; + m_pSteamUGC = 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; + + m_pController = SteamClient()->GetISteamController( hSteamUser, hSteamPipe, STEAMCONTROLLER_INTERFACE_VERSION ); + if ( !m_pController ) + return false; + + m_pSteamUGC = SteamClient()->GetISteamUGC( hSteamUser, hSteamPipe, STEAMUGC_INTERFACE_VERSION ); + if ( !m_pSteamUGC ) + 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 S_CALLTYPE SteamAPI_UseBreakpadCrashHandler( char const *pchVersion, char const *pchDate, char const *pchTime, bool bFullMemoryDumps, void *pvContext, PFNPreMinidumpCallback m_pfnPreMinidumpCallback ); +S_API void S_CALLTYPE SteamAPI_SetBreakpadAppID( uint32 unAppID ); +#endif + +#endif // STEAM_API_H diff --git a/extern/Steamworks/steam_appid.test.txt b/extern/Steamworks/steam_appid.test.txt new file mode 100644 index 00000000..36e08261 --- /dev/null +++ b/extern/Steamworks/steam_appid.test.txt @@ -0,0 +1 @@ +480 diff --git a/extern/Steamworks/steam_gameserver.h b/extern/Steamworks/steam_gameserver.h new file mode 100644 index 00000000..3a106263 --- /dev/null +++ b/extern/Steamworks/steam_gameserver.h @@ -0,0 +1,163 @@ +//====== Copyright © 1996-2008, 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/extern/Steamworks/steamclientpublic.h b/extern/Steamworks/steamclientpublic.h new file mode 100644 index 00000000..abbad418 --- /dev/null +++ b/extern/Steamworks/steamclientpublic.h @@ -0,0 +1,1093 @@ +//========= Copyright � 1996-2008, Valve LLC, 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" +#include "steamuniverse.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 + k_EResultUnexpectedError = 79, // something happened that we didn't expect to ever happen + k_EResultDisabled = 80, // The requested service has been configured to be unavailable + k_EResultInvalidCEGSubmission = 81, // The set of files submitted to the CEG server are not valid ! + k_EResultRestrictedDevice = 82, // The device being used is not allowed to perform this action +}; + +// 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 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_SharedLicense = 32, // license was granted by authorized local device + k_EAppOwernshipFlags_FreeWeekend = 64, // owned by a free weekend licenses + k_EAppOwernshipFlags_LicenseLocked = 128, // shared license is locked (in use) by other user +}; + + +//----------------------------------------------------------------------------- +// 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_Config = 0x100, // hidden app used to config Steam features (backpack, sales, 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 ); + } +#ifdef INT64_DIFFERENT_FROM_INT64_T + CSteamID( uint64_t ulSteamID ) + { + SetFromUint64( (uint64)ulSteamID ); + } +#endif + + + //----------------------------------------------------------------------------- + // 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; + } +#ifdef INT64_DIFFERENT_FROM_INT64_T + CGameID( uint64_t ulGameID ) + { + m_ulGameID = (uint64)ulGameID; + } +#endif + + 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/extern/Steamworks/steamencryptedappticket.h b/extern/Steamworks/steamencryptedappticket.h new file mode 100644 index 00000000..48c63b47 --- /dev/null +++ b/extern/Steamworks/steamencryptedappticket.h @@ -0,0 +1,32 @@ +//========= Copyright © 1996-2010, Valve LLC, All rights reserved. ============ +// +// Purpose: utilities to decode/decrypt a ticket from the +// ISteamUser::RequestEncryptedAppTicket, ISteamUser::GetEncryptedAppTicket API +// +// To use: declare CSteamEncryptedAppTicket, then call BDecryptTicket +// if BDecryptTicket returns true, other accessors are valid +// +//============================================================================= + +#include "steam_api.h" + +static const int k_nSteamEncryptedAppTicketSymmetricKeyLen = 32; + + +S_API bool SteamEncryptedAppTicket_BDecryptTicket( const uint8 *rgubTicketEncrypted, uint32 cubTicketEncrypted, + uint8 *rgubTicketDecrypted, uint32 *pcubTicketDecrypted, + const uint8 rgubKey[k_nSteamEncryptedAppTicketSymmetricKeyLen], int cubKey ); + +S_API bool SteamEncryptedAppTicket_BIsTicketForApp( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted, AppId_t nAppID ); + +S_API RTime32 SteamEncryptedAppTicket_GetTicketIssueTime( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted ); + +S_API void SteamEncryptedAppTicket_GetTicketSteamID( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted, CSteamID *psteamID ); + +S_API AppId_t SteamEncryptedAppTicket_GetTicketAppID( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted ); + +S_API bool SteamEncryptedAppTicket_BUserOwnsAppInTicket( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted, AppId_t nAppID ); + +S_API bool SteamEncryptedAppTicket_BUserIsVacBanned( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted ); + +S_API const uint8 *SteamEncryptedAppTicket_GetUserVariableData( uint8 *rgubTicketDecrypted, uint32 cubTicketDecrypted, uint32 *pcubUserData ); \ No newline at end of file diff --git a/extern/Steamworks/steamhttpenums.h b/extern/Steamworks/steamhttpenums.h new file mode 100644 index 00000000..9ac2eeaf --- /dev/null +++ b/extern/Steamworks/steamhttpenums.h @@ -0,0 +1,94 @@ +//====== Copyright © 1996-2010, 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, + k_EHTTPMethodPUT, + k_EHTTPMethodDELETE, + k_EHTTPMethodOPTIONS, + + // 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_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 \ No newline at end of file diff --git a/extern/Steamworks/steamps3params.h b/extern/Steamworks/steamps3params.h new file mode 100644 index 00000000..c0741b4b --- /dev/null +++ b/extern/Steamworks/steamps3params.h @@ -0,0 +1,112 @@ +//====== Copyright 1996-2008, Valve Corporation, All rights reserved. ======= +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMPS3PARAMS_H +#define STEAMPS3PARAMS_H +#ifdef _WIN32 +#pragma once +#endif + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// PlayStation 3 initialization parameters +// +// The following structure must be passed to when loading steam_api_ps3.prx +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +#define STEAM_PS3_PATH_MAX 1055 +#define STEAM_PS3_SERVICE_ID_MAX 32 +#define STEAM_PS3_COMMUNICATION_ID_MAX 10 +#define STEAM_PS3_COMMUNICATION_SIG_MAX 160 +#define STEAM_PS3_LANGUAGE_MAX 64 +#define STEAM_PS3_REGION_CODE_MAX 16 +#define STEAM_PS3_CURRENT_PARAMS_VER 2 +struct SteamPS3Params_t +{ + uint32 m_unVersion; // set to STEAM_PS3_CURRENT_PARAMS_VER + + void *pReserved; + uint32 m_nAppId; // set to your game's appid + + char m_rgchInstallationPath[ STEAM_PS3_PATH_MAX ]; // directory containing latest steam prx's and sdata. Can be read only (BDVD) + char m_rgchSystemCache[ STEAM_PS3_PATH_MAX ]; // temp working cache, not persistent + char m_rgchGameData[ STEAM_PS3_PATH_MAX ]; // persistent game data path for storing user data + char m_rgchNpServiceID[ STEAM_PS3_SERVICE_ID_MAX ]; + char m_rgchNpCommunicationID[ STEAM_PS3_COMMUNICATION_ID_MAX ]; + char m_rgchNpCommunicationSig[ STEAM_PS3_COMMUNICATION_SIG_MAX ]; + + // Language should be one of the following. must be zero terminated + // danish + // dutch + // english + // finnish + // french + // german + // italian + // korean + // norwegian + // polish + // portuguese + // russian + // schinese + // spanish + // swedish + // tchinese + char m_rgchSteamLanguage[ STEAM_PS3_LANGUAGE_MAX ]; + + // region codes are "SCEA", "SCEE", "SCEJ". must be zero terminated + char m_rgchRegionCode[ STEAM_PS3_REGION_CODE_MAX ]; + + // Should be SYS_TTYP3 through SYS_TTYP10, if it's 0 then Steam won't spawn a + // thread to read console input at all. Using this let's you use Steam console commands + // like: profile_on, profile_off, profile_dump, mem_stats, mem_validate. + unsigned int m_cSteamInputTTY; + + struct Ps3netInit_t + { + bool m_bNeedInit; + void *m_pMemory; + int m_nMemorySize; + int m_flags; + } m_sysNetInitInfo; + + struct Ps3jpgInit_t + { + bool m_bNeedInit; + } m_sysJpgInitInfo; + + struct Ps3pngInit_t + { + bool m_bNeedInit; + } m_sysPngInitInfo; + + struct Ps3sysutilUserInfo_t + { + bool m_bNeedInit; + } m_sysSysUtilUserInfo; + + bool m_bIncludeNewsPage; +}; + + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// PlayStation 3 memory structure +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +#define STEAMPS3_MALLOC_INUSE 0x53D04A51 +#define STEAMPS3_MALLOC_SYSTEM 0x0D102C48 +#define STEAMPS3_MALLOC_OK 0xFFD04A51 +struct SteamPS3Memory_t +{ + bool m_bSingleAllocation; // If true, Steam will request one 6MB allocation and use the returned memory for all future allocations + // If false, Steam will make call malloc for each allocation + + // required function pointers + void* (*m_pfMalloc)(size_t); + void* (*m_pfRealloc)(void *, size_t); + void (*m_pfFree)(void *); + size_t (*m_pUsable_size)(void*); +}; + + +#endif // STEAMPS3PARAMS_H diff --git a/extern/Steamworks/steamtypes.h b/extern/Steamworks/steamtypes.h new file mode 100644 index 00000000..b26990da --- /dev/null +++ b/extern/Steamworks/steamtypes.h @@ -0,0 +1,151 @@ +//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMTYPES_H +#define STEAMTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#define S_CALLTYPE __cdecl + +// 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 + +typedef unsigned char uint8; +typedef signed char int8; + +#if defined( _WIN32 ) + +typedef __int16 int16; +typedef unsigned __int16 uint16; +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; + +typedef int64 lint64; +typedef uint64 ulint64; + +#ifdef X64BITS +typedef __int64 intp; // 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 + +typedef short int16; +typedef unsigned short uint16; +typedef int int32; +typedef unsigned int uint32; +typedef long long int64; +typedef unsigned long long uint64; + +// [u]int64 are actually defined as 'long long' and gcc 64-bit +// doesn't automatically consider them the same as 'long int'. +// Changing the types for [u]int64 is complicated by +// there being many definitions, so we just +// define a 'long int' here and use it in places that would +// otherwise confuse the compiler. +typedef long int lint64; +typedef unsigned long int ulint64; + +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif // 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/extern/Steamworks/steamuniverse.h b/extern/Steamworks/steamuniverse.h new file mode 100644 index 00000000..dd384dcc --- /dev/null +++ b/extern/Steamworks/steamuniverse.h @@ -0,0 +1,27 @@ +//========= Copyright � 1996-2008, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMUNIVERSE_H +#define STEAMUNIVERSE_H +#ifdef _WIN32 +#pragma once +#endif + + +// 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 +}; + + +#endif // STEAMUNIVERSE_H diff --git a/lib/Inventory/inventory.cpp b/lib/Inventory/inventory.cpp index dadef72a..45b9f6bd 100644 --- a/lib/Inventory/inventory.cpp +++ b/lib/Inventory/inventory.cpp @@ -377,7 +377,7 @@ Texture *InventoryItemType::GetAttachmentIcon(int i) const } InventoryItem::InventoryItem(const EntityAIType *type, bool fullCreate) - : base(type, fullCreate), _ui(false), _opened(true), _animationsEnabled(true), _isWorldAttached(false) + : base(type, fullCreate), _ui(false), _inventoryRotated(false), _opened(true), _animationsEnabled(true), _isWorldAttached(false) { int n = Type()->_attachments.Size(); _attachments.Realloc(n); _attachments.Resize(n); @@ -400,6 +400,35 @@ int InventoryItem::GetObjSpecial(int shapeSpecial) const return _ui ? shapeSpecial | DisableSun : shapeSpecial; } +int InventoryItem::GetInventoryWidth() const +{ + const InventoryItemType *type = Type(); + if (!type) return 0; + return _inventoryRotated ? type->GetItemHeight() : type->GetItemWidth(); +} + +int InventoryItem::GetInventoryHeight() const +{ + const InventoryItemType *type = Type(); + if (!type) return 0; + return _inventoryRotated ? type->GetItemWidth() : type->GetItemHeight(); +} + +bool InventoryItem::CanRotateInInventory() const +{ + if (!Type() || GetInventoryWidth() == GetInventoryHeight()) return false; + EntityAI *parent = dyn_cast(GetHierarchyParent()); + if (!parent || !parent->GetSupply()) return false; + return parent->GetSupply()->GetItemsCargo().CanRotateItem(this); +} + +bool InventoryItem::RotateInInventory() +{ + if (!CanRotateInInventory()) return false; + _inventoryRotated = !_inventoryRotated; + return true; +} + bool InventoryItem::CheckAttachmentCondition(const InventoryItem *attachment) const { const InventoryItemType *type = attachment->Type(); @@ -735,7 +764,7 @@ void InventoryItem::GetActions(const std::function UIAction action(new ActionBasic(ATTakeItem, this)); add(action); } - else if (Type() && Type()->_handheld && !person->GetItemInHands()) + if (Type() && !person->GetItemInHands()) { //has no room, take into hands (prototype) DoAssert(!person->GetInSlot(ISHands)); @@ -806,7 +835,7 @@ bool InventoryItem::UseFromInventory(Person *owner) if (Type() && Type()->IsHandheld()) { const InventoryItem *inHands = owner->GetItemInHands(); - if (inHands && inHands->Type() == Type()) + if (inHands == this) { // remove the item owner->TakeItemToHands(NULL); @@ -2178,6 +2207,7 @@ LSError InventoryItem::Serialize(ParamArchive &ar) { CHECK(base::Serialize(ar)); CHECK(ar.SerializeRefs("Attachments", _attachments, 1)); + CHECK(ar.Serialize("inventoryRotated", _inventoryRotated, 1, false)); return LSOK; } @@ -2223,6 +2253,10 @@ TMError InventoryItem::TransferMsg(NetworkMessageContext &ctx) { PREPARE_TRANSFER(UpdateInventoryItem) + bool inventoryRotated = _inventoryRotated; + TRANSF_EX(inventoryRotated, inventoryRotated); + if (!ctx.IsSending()) _inventoryRotated = inventoryRotated; + if (ctx.IsSending()) { TRANSF_REFS(attachments) @@ -2265,6 +2299,7 @@ float InventoryItem::CalculateError(NetworkMessageContextWithError &ctx) PREPARE_TRANSFER(UpdateInventoryItem) if (message->_inLandscape != IsInLandscape()) error += ERR_COEF_IMMEDIATE; + if (message->_inventoryRotated != _inventoryRotated) error += ERR_COEF_IMMEDIATE; // items int count = intMin(message->_attachments.Size(), _attachments.Size()); @@ -2424,8 +2459,8 @@ int InventoryStorage::ItemOn(int row, int col) const const InventoryItemType *type = item->Type(); if (!type) continue; - int w = type->GetItemWidth(); - int h = type->GetItemHeight(); + int w = item->GetInventoryWidth(); + int h = item->GetInventoryHeight(); DoAssert(c + w <= _width); DoAssert(r + h <= _height); if (c + w > col && r + h > row) return i - 1; // i was already incremented @@ -2452,8 +2487,8 @@ void InventoryStorage::Render(StaticArrayAuto &image, const InventoryItem const InventoryItemType *type = item->Type(); if (!type) continue; - int w = type->GetItemWidth(); - int h = type->GetItemHeight(); + int w = item->GetInventoryWidth(); + int h = item->GetInventoryHeight(); DoAssert(col + w <= _width); DoAssert(row + h <= _height); // render the item @@ -2472,10 +2507,10 @@ void InventoryStorage::Render(StaticArrayAuto &image, const InventoryItem } } -int InventoryStorage::FitsInto(const Array &image, const InventoryItemType *type, int index) const +int InventoryStorage::FitsInto(const Array &image, const InventoryItemType *type, int index, bool rotated) const { - int h = type->GetItemHeight(); - int w = type->GetItemWidth(); + int h = rotated ? type->GetItemWidth() : type->GetItemHeight(); + int w = rotated ? type->GetItemHeight() : type->GetItemWidth(); if (index >= 0) { // check the given space @@ -2543,7 +2578,19 @@ int InventoryStorage::CanAddItem(const InventoryItem *item, int index) const AUTO_STATIC_ARRAY(bool, image, 256); Render(image, item); - return FitsInto(image, type, index); + return FitsInto(image, type, index, item->IsInventoryRotated()); +} + +bool InventoryStorage::CanRotateItem(const InventoryItem *item) const +{ + if (!item || !item->Type() || _width <= 0 || _height <= 0) return false; + if (item->GetInventoryWidth() == item->GetInventoryHeight()) return false; + int index = _items.Find(item); + if (index < 0) return false; + + AUTO_STATIC_ARRAY(bool, image, 256); + Render(image, item); + return FitsInto(image, item->Type(), index, !item->IsInventoryRotated()) == index; } int InventoryStorage::CanReplaceItem(const InventoryItem *oldItem, const InventoryItem *newItem) const @@ -2559,10 +2606,10 @@ int InventoryStorage::CanReplaceItem(const InventoryItem *oldItem, const Invento Render(image, oldItem); // check if the newItem fits on the same place - if (FitsInto(image, type, index) == index) return index; + if (FitsInto(image, type, index, newItem->IsInventoryRotated()) == index) return index; // try to find different place in the container - return FitsInto(image, type, -1); + return FitsInto(image, type, -1, newItem->IsInventoryRotated()); } bool InventoryStorage::AddItem(EntityAI *owner, InventoryItem *item, int index) diff --git a/lib/Inventory/inventory.hpp b/lib/Inventory/inventory.hpp index 0ae3b20e..ff2daf4b 100644 --- a/lib/Inventory/inventory.hpp +++ b/lib/Inventory/inventory.hpp @@ -159,6 +159,7 @@ TypeIsSimple(InventorySlotId) #define UPDATE_INVENTORY_ITEM_MSG(MessageName, XX) \ XX(MessageName, bool, isOn, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG("Device switched on"), TRANSF, ET_NOT_EQUAL, ERR_COEF_STRUCTURE) \ XX(MessageName, RefArray, attachments, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("Attachments"), TRANSF_REFS, ET_NOT_EQUAL_COUNT, ERR_COEF_MODE) \ + XX(MessageName, bool, inventoryRotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Item rotated in inventory grid"), TRANSF, ET_NOT_EQUAL, ERR_COEF_IMMEDIATE) \ XX(MessageName, bool, inLandscape, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Item is in landscape"), TRANSF, ET_NOT_EQUAL, ERR_COEF_IMMEDIATE) \ DECLARE_NET_INDICES_EX_ERR(UpdateInventoryItem, UpdateVehicleAI, UPDATE_INVENTORY_ITEM_MSG) @@ -174,6 +175,9 @@ class InventoryItem : public PoweredItem // during drawing in UI, different special flags are used bool _ui; + // Item footprint is rotated 90 degrees in a cargo grid. + bool _inventoryRotated; + // content of the container is accessible from the Inventory UI bool _opened; @@ -235,6 +239,13 @@ class InventoryItem : public PoweredItem //! Perform default action for item in the inventory virtual bool UseFromInventory(Person *owner); + bool IsInventoryRotated() const {return _inventoryRotated;} + void SetInventoryRotated(bool rotated) {_inventoryRotated = rotated;} + int GetInventoryWidth() const; + int GetInventoryHeight() const; + bool CanRotateInInventory() const; + bool RotateInInventory(); + // cast optimization virtual Weapon *GetWeapon() {return NULL;} virtual const Weapon *GetWeapon() const {return NULL;} @@ -406,6 +417,7 @@ class InventoryStorage // check if item fits into container, find the place if not given int CanAddItem(const InventoryItem *item, int index = -1) const; int CanReplaceItem(const InventoryItem *oldItem, const InventoryItem *newItem) const; + bool CanRotateItem(const InventoryItem *item) const; bool AddItem(EntityAI *owner, InventoryItem *item, int index); bool RemoveItem(EntityAI *owner, InventoryItem *item); @@ -432,7 +444,7 @@ class InventoryStorage private: // check the space for the item - int FitsInto(const Array &image, const InventoryItemType *type, int index) const; + int FitsInto(const Array &image, const InventoryItemType *type, int index, bool rotated = false) const; }; // Watch classes diff --git a/lib/Marina/matrixA_old.hpp b/lib/Marina/matrixA_old.hpp index 586598a9..c1272d90 100644 --- a/lib/Marina/matrixA_old.hpp +++ b/lib/Marina/matrixA_old.hpp @@ -329,12 +329,18 @@ void Matrix::CombinateColumns(unsigned int iDestColumn, unsigned int iSour { ASSERT(iDestColumn < _nDim); ASSERT(iSourceColumn < _nDim); + if (iDestColumn >= _nDim || iSourceColumn >= _nDim) return; - Type * pTemp = _pMatrix + iDestColumn; + // Use two independent pointers. The previous code indexed with + // (iSourceColumn - iDestColumn), which underflows when the source + // column comes before the destination and caused an access violation. + Type * pDest = _pMatrix + iDestColumn; + Type * pSource = _pMatrix + iSourceColumn; for(unsigned int iRows = 0; iRows < _nDim; iRows++) { - *pTemp += fCoef * pTemp[iSourceColumn - iDestColumn]; - pTemp += _nDim; + *pDest += fCoef * (*pSource); + pDest += _nDim; + pSource += _nDim; } } @@ -345,33 +351,37 @@ void Matrix::CombineCoordinates(unsigned int iCoord1, { ASSERT(iCoord1 < _nDim); ASSERT(iCoord2 < _nDim); + if (iCoord1 >= _nDim || iCoord2 >= _nDim || iCoord1 == iCoord2) return; ASSERT(IsNumericalZero(pfCombMatrix[0] * pfCombMatrix[2] + pfCombMatrix[1] * pfCombMatrix[3]));// must be unitary - // Columns - Type * pTemp = _pMatrix + iCoord1; + // Columns. Use one pointer per coordinate: the old pTemp[iCoord2 - iCoord1] + // underflows when iCoord2 < iCoord1 and reads out of bounds (crash in the + // vehicle collision solver when friction axes are combined in that order). + Type * pColumn1 = _pMatrix + iCoord1; + Type * pColumn2 = _pMatrix + iCoord2; Type * pTempEnd = _pMatrix + _nDim * _nDim; Type In1, In2; - for(; pTemp < pTempEnd; pTemp += _nDim) + for(; pColumn1 < pTempEnd; pColumn1 += _nDim, pColumn2 += _nDim) { - In1 = (*pTemp); - In2 = pTemp[iCoord2 - iCoord1]; - (*pTemp) = pfCombMatrix[0] * In1 + pfCombMatrix[1] * In2; - pTemp[iCoord2 - iCoord1] = pfCombMatrix[2] * In1 + pfCombMatrix[3] * In2; + In1 = (*pColumn1); + In2 = (*pColumn2); + (*pColumn1) = pfCombMatrix[0] * In1 + pfCombMatrix[1] * In2; + (*pColumn2) = pfCombMatrix[2] * In1 + pfCombMatrix[3] * In2; } // Rows - pTemp = _pMatrix + iCoord1 * _nDim; - pTempEnd = pTemp + _nDim; - Type * pTemp2 = _pMatrix + iCoord2 * _nDim; + Type * pRow1 = _pMatrix + iCoord1 * _nDim; + pTempEnd = pRow1 + _nDim; + Type * pRow2 = _pMatrix + iCoord2 * _nDim; - for(; pTemp < pTempEnd; pTemp++,pTemp2++) + for(; pRow1 < pTempEnd; pRow1++,pRow2++) { - In1 = (*pTemp); - In2 = (*pTemp2); + In1 = (*pRow1); + In2 = (*pRow2); - (*pTemp) = pfCombMatrix[0] * In1 + pfCombMatrix[1] * In2; - (*pTemp2) = pfCombMatrix[2] * In1 + pfCombMatrix[3] * In2; + (*pRow1) = pfCombMatrix[0] * In1 + pfCombMatrix[1] * In2; + (*pRow2) = pfCombMatrix[2] * In1 + pfCombMatrix[3] * In2; } } diff --git a/lib/Network/network.cpp b/lib/Network/network.cpp index 9abcaccd..5c3ab5e9 100644 --- a/lib/Network/network.cpp +++ b/lib/Network/network.cpp @@ -1,5 +1,9 @@ #include "../wpch.hpp" #include "networkImpl.hpp" +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +#include +#include +#endif #include "../global.hpp" //#include "strIncl.hpp" #ifdef _WIN32 @@ -1848,6 +1852,7 @@ DEFINE_NET_MESSAGE(InventoryMenuAttachment, INVENTORY_MENU_ATTACHMENT_MSG) DEFINE_NET_MESSAGE(AskForThrowItem, ASK_FOR_THROW_ITEM_MSG) DEFINE_NET_MESSAGE(AskForDropItem, ASK_FOR_DROP_ITEM_MSG) DEFINE_NET_MESSAGE(AskForMoveItem, ASK_FOR_MOVE_ITEM_MSG) +DEFINE_NET_MESSAGE(AskForRotateInventoryItem, ASK_FOR_ROTATE_INVENTORY_ITEM_MSG) DEFINE_NET_MESSAGE(AskForTakeItemToHands, ASK_FOR_TAKE_ITEM_TO_HANDS_MSG) DEFINE_NET_MESSAGE(AskForSwapItems, ASK_FOR_SWAP_ITEMS_MSG) DEFINE_NET_MESSAGE(AskForPlayerAction, ASK_FOR_PLAYER_ACTION_MSG) @@ -1973,9 +1978,18 @@ bool IsUserIdMatch(const char *id, const char *match) #else +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +#define LOGIN_STEAM_IDENTITY_MSG(MessageName, XX) \ + XX(MessageName, NetInt64, steamID, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Steam user ID"), TRANSF) \ + XX(MessageName, AutoArray, steamSessionTicket, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Steam authentication ticket"), TRANSF) +#else +#define LOGIN_STEAM_IDENTITY_MSG(MessageName, XX) +#endif + #define LOGIN_MSG(MessageName, XX) \ XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) ID"), TRANSF) \ XX(MessageName, int, playerid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID unique in session (shorter than dpnid)"), TRANSF) \ + LOGIN_STEAM_IDENTITY_MSG(MessageName, XX) \ XX(MessageName, int, inaddr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("IP address"), TRANSF) \ XX(MessageName, RString, id, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Unique id of player (derivated from CD key)"), TRANSF) \ XX(MessageName, AutoArray, certificate, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("User sigining certificate"), TRANSF) \ @@ -2006,6 +2020,9 @@ DEFINE_NET_INDICES_ERR(PlayerUpdate, PLAYER_UPDATE_MSG, NoErrorInitialFunc) PlayerIdentity::PlayerIdentity() { +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + _steamID = 0; +#endif _minPing = 0,_avgPing = 0 ,_maxPing = 0; _minBandwidth = 0, _avgBandwidth = 0 , _maxBandwidth =0; _desync = 0; @@ -2083,6 +2100,10 @@ TMError PlayerIdentity::TransferMsg(NetworkMessageContext &ctx) TRANSF_EX(isVoice, voiceOn) TRANSF_EX(privateSlot, privateSlot) TRANSF_EX(rating, rating) +#endif +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + TRANSF(steamID) + TRANSF(steamSessionTicket) #endif TRANSF_EX(id, id) TRANSF_EX(certificate, certificate) @@ -2160,6 +2181,85 @@ RString PlayerIdentity::GetDebugId() const return id; } +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +SteamValidation::SteamValidation() +: _steamId(0), _server(NULL), _dpid(0), _started(false), _authPending(false), _ticksStarted(0), + _callbackGSAuthTicketResponse(NULL, NULL) +{ +} + +SteamValidation::~SteamValidation() +{ + if (_started && SteamGameServer()) + SteamGameServer()->EndAuthSession(CSteamID(_steamId)); +} + +void SteamValidation::Start(PlayerIdentity &identity, NetworkServer *server) +{ + _server = server; + _steamId = identity._steamID; + _steamSessionTicket = identity._steamSessionTicket; + _name = identity.GetName(); + _dpid = identity.dpnid; + _started = false; + _authPending = false; + _ticksStarted = GlobalTickCount(); + _callbackGSAuthTicketResponse.Register(this, &SteamValidation::OnValidateAuthTicketResponse); + + ISteamGameServer *steamServer = SteamGameServer(); + RString expectedSteamId = Format("%I64u", (unsigned __int64)_steamId); + if (!_steamId || strcmpi(identity.id, expectedSteamId) != 0 || + _steamSessionTicket.Size() == 0 || !steamServer || !steamServer->BLoggedOn()) + { + _started = false; + _server->KickOff(_dpid, KOROther, "Steam identity or authentication unavailable"); + return; + } + + EBeginAuthSessionResult result = steamServer->BeginAuthSession( + _steamSessionTicket.Data(), _steamSessionTicket.Size(), CSteamID(_steamId)); + if (result != k_EBeginAuthSessionResultOK) + { + _server->KickOff(_dpid, KOROther, "Steam authentication failed"); + LogF("Steam auth ticket rejected for player %s (reason %d)", cc_cast(_name), result); + } + else + { + _started = true; + _authPending = true; + } +} + +void SteamValidation::HandleTimeout() +{ + if (_authPending && GlobalTickCount() > _ticksStarted + 60000) + { + _authPending = false; + _server->KickOff(_dpid, KORAuthTimeOut); + } +} + +void SteamValidation::OnValidateAuthTicketResponse(ValidateAuthTicketResponse_t *response) +{ + if (!_authPending || !response || response->m_SteamID.ConvertToUint64() != _steamId) return; + + if (response->m_eAuthSessionResponse == k_EAuthSessionResponseOK) + { +#if _USE_BATTL_EYE_SERVER + _server->PlayerGUIDReceived(_dpid, CSteamID(_steamId)); + _server->PlayerGUIDIsValid(_dpid, CSteamID(_steamId)); +#endif + LogF("Steam authenticated player %s (SteamID %I64u)", cc_cast(_name), (unsigned __int64)_steamId); + } + else + { + _server->KickOff(_dpid, KOROther, "Steam authentication rejected"); + LogF("Steam auth failed for player %s (response %d)", cc_cast(_name), response->m_eAuthSessionResponse); + } + _authPending = false; +} +#endif + #define LOCAL_PLAYER_INFO_MSG(MessageName, XX) \ XX(MessageName, NetInt64, xuid, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Xbox user id"), TRANSF) \ @@ -5688,9 +5788,9 @@ void NetworkManager::LoadIsland(RString islandName) #endif //_VBS3 -void NetworkManager::AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type) +void NetworkManager::AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) { - if (_client) _client->AskForSetItemShortcut(person, index, type); + if (_client) _client->AskForSetItemShortcut(person, index, type, item); } void NetworkManager::AskInventoryMenu(AIBrain *unit, InventoryItem *item1, InventoryItem *item2) @@ -5709,9 +5809,14 @@ void NetworkManager::AskForDropItem(Person *person, InventoryItem *item) if (_client) _client->AskForDropItem(person, item); } -void NetworkManager::AskForMoveItem(EntityAI *target, int index, InventoryItem *item) +void NetworkManager::AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) +{ + if (_client) _client->AskForMoveItem(target, index, item, rotated); +} + +void NetworkManager::AskForRotateInventoryItem(Person *person, InventoryItem *item) { - if (_client) _client->AskForMoveItem(target, index, item); + if (_client) _client->AskForRotateInventoryItem(person, item); } void NetworkManager::AskForTakeItemToHands(Person *person, InventoryItem *item) diff --git a/lib/Network/network.hpp b/lib/Network/network.hpp index b7d178f6..093cdbd9 100644 --- a/lib/Network/network.hpp +++ b/lib/Network/network.hpp @@ -1081,10 +1081,11 @@ class INetworkManager virtual void LoadIsland(RString islandName) = 0; #endif - virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type) = 0; + virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) = 0; virtual void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir) = 0; virtual void AskForDropItem(Person *person, InventoryItem *item) = 0; - virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item) = 0; + virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) = 0; + virtual void AskForRotateInventoryItem(Person *person, InventoryItem *item) = 0; virtual void AskForTakeItemToHands(Person *person, InventoryItem *item) = 0; virtual void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) = 0; @@ -1402,6 +1403,7 @@ DEFINE_ENUM_END(TMError) XX(FORMAT_UPDATE, ItemShortcut, UpdateItemShortcut, " Item shortcut in ClientOutput", Update) \ XX(FORMAT_UPDATE, InventoryItem, UpdateInventoryItem, "Generic update of InventoryItem (: EntityAI).", Update) \ XX(FORMAT_SIMPLE, Dummy, AskForMoveItem, "Ask owner for Inventory UI action.", Ask) \ + XX(FORMAT_SIMPLE, Dummy, AskForRotateInventoryItem, "Ask server to rotate inventory item.", Ask) \ XX(FORMAT_SIMPLE, Dummy, AskForThrowItem, "Ask owner for throwing UI action.", Ask) \ XX(FORMAT_SIMPLE, Dummy, AskForDropItem, "Ask owner for Inventory UI action.", Ask) \ XX(FORMAT_SIMPLE, Dummy, AskForSetItemShortcut, "Ask owner for Inventory UI action.", Ask) \ @@ -2697,6 +2699,12 @@ struct PlayerIdentity : public NetworkSimpleObject LocalPlayerInfoList localPlayerInfoList; +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + /// Steam identity and authentication ticket, verified by the dedicated server. + NetInt64 _steamID; + AutoArray _steamSessionTicket; +#endif + //! address for peer-to-peer voice transition sockaddr_in _voiceAddress; diff --git a/lib/Network/networkClient.cpp b/lib/Network/networkClient.cpp index c7dea7e1..86d453a8 100644 --- a/lib/Network/networkClient.cpp +++ b/lib/Network/networkClient.cpp @@ -1,5 +1,8 @@ #include "../wpch.hpp" #include "networkImpl.hpp" +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +#include +#endif #include "../global.hpp" //#include "strIncl.hpp" #include "../stringtableExt.hpp" @@ -3243,6 +3246,26 @@ void NetworkClient::OnMessage(int from, NetworkMessage *msg, NetworkMessageType BankList::ReadAccess banks(GFileBanks); identity.filesCount = banks.Size() + _additionalSignedFiles.Size(); +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + if (SteamUser()) + { + identity._steamID = SteamUser()->GetSteamID().ConvertToUint64(); + char steamTicket[1024]; + uint32 steamTicketSize = 0; + memset(steamTicket, 0, sizeof(steamTicket)); + SteamUser()->GetAuthSessionTicket(steamTicket, sizeof(steamTicket), &steamTicketSize, NULL); + if (identity._steamID != 0 && steamTicketSize > 0 && steamTicketSize <= sizeof(steamTicket)) + { + identity._steamSessionTicket.Copy(steamTicket, steamTicketSize); + identity.id = Format("%I64u", (unsigned __int64)identity._steamID); + } + else + { + identity._steamID = 0; + } + } +#endif + GameDataNamespace globals(NULL, RString(), false); // save - no global namespace @@ -4404,7 +4427,10 @@ void NetworkClient::OnMessage(int from, NetworkMessage *msg, NetworkMessageType { Ref type; if (!ask._itemType.IsEmpty()) type = dynamic_cast(VehicleTypes.New(ask._itemType)); - ask._person->SetItemShortcut(ask._index, type); + if (ask._item && ask._person->FindItem(ask._item)) + ask._person->SetItemShortcutInstance(ask._index, ask._item); + else + ask._person->SetItemShortcut(ask._index, type); } } break; @@ -4488,20 +4514,43 @@ void NetworkClient::OnMessage(int from, NetworkMessage *msg, NetworkMessageType { AskForMoveItemMessage ask; TMSGCHECK(ask.TransferMsg(ctx)) - if (ask._target && ask._item && ask._target->CanMoveItem(ask._index, ask._item)) + if (ask._target && ask._item) { - Entity *parent = ask._item->GetHierarchyParent(); - if (parent) parent->RemoveOwnedItem(ask._item); - - ask._target->MoveItem(ask._index, ask._item); + const bool oldRotation = ask._item->IsInventoryRotated(); + ask._item->SetInventoryRotated(ask._rotated); + if (ask._target->CanMoveItem(ask._index, ask._item)) + { + Entity *parent = ask._item->GetHierarchyParent(); + Person *handsOwner = dyn_cast(parent); + const bool movedFromHands = handsOwner && handsOwner->GetItemInHands() == ask._item; + if (parent) parent->RemoveOwnedItem(ask._item); + + ask._target->MoveItem(ask._index, ask._item); + if (movedFromHands) + UpdateObject(handsOwner, NMCUpdateGeneric, NMFGuaranteed); + if (oldRotation != ask._rotated) + UpdateObject(ask._item, NMCUpdateGeneric, NMFGuaranteed); + } + else + ask._item->SetInventoryRotated(oldRotation); } } break; + case NMTAskForRotateInventoryItem: + { + AskForRotateInventoryItemMessage ask; + TMSGCHECK(ask.TransferMsg(ctx)) + if (GetNetworkManager().IsServerOwner() && ask._person && ask._item && + ask._person->FindItem(ask._item) && ask._item->RotateInInventory()) + UpdateObject(ask._item, NMCUpdateGeneric, NMFGuaranteed); + } + break; case NMTAskForTakeItemToHands: { AskForTakeItemToHandsMessage ask; TMSGCHECK(ask.TransferMsg(ctx)) - if (ask._person && ask._item && ask._person->FindItem(ask._item)) + if (ask._person && ask._item && + (ask._person->FindItem(ask._item) || ask._item->IsInLandscape())) { ask._person->TakeItemToHands(ask._item); } @@ -7586,11 +7635,12 @@ void NetworkClient::AskCommanderOverride(Turret *turret, Turret *overriddenByTur #endif //_VBS3 -void NetworkClient::AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type) +void NetworkClient::AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) { AskForSetItemShortcutMessage msg; msg._person = person; msg._index = index; + msg._item = item; msg._itemType = type ? type->GetName() : RString(); SendMsg(&msg, NMFGuaranteed); } @@ -7622,12 +7672,21 @@ void NetworkClient::AskForDropItem(Person *person, InventoryItem *item) SendMsg(&msg, NMFGuaranteed); } -void NetworkClient::AskForMoveItem(EntityAI *target, int index, InventoryItem *item) +void NetworkClient::AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) { AskForMoveItemMessage msg; msg._target = target; msg._index = index; msg._item = item; + msg._rotated = rotated; + SendMsg(&msg, NMFGuaranteed); +} + +void NetworkClient::AskForRotateInventoryItem(Person *person, InventoryItem *item) +{ + AskForRotateInventoryItemMessage msg; + msg._person = person; + msg._item = item; SendMsg(&msg, NMFGuaranteed); } diff --git a/lib/Network/networkImpl.hpp b/lib/Network/networkImpl.hpp index d9799220..11701f72 100644 --- a/lib/Network/networkImpl.hpp +++ b/lib/Network/networkImpl.hpp @@ -9,6 +9,9 @@ #include "netTransport.hpp" #include "network.hpp" #include "../versionNo.h" +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +#include +#endif #include #include "../memHeap.hpp" @@ -66,6 +69,27 @@ RString GetMsgTypeName(NetworkMessageType type); // extern const char *NetworkMessageTypeNames[]; struct NetworkPlayerInfo; +class NetworkServer; + +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +class SteamValidation +{ + uint64 _steamId; + NetworkServer *_server; + int _dpid; + bool _started; + bool _authPending; + unsigned long _ticksStarted; + RString _name; + AutoArray _steamSessionTicket; +public: + SteamValidation(); + ~SteamValidation(); + void Start(PlayerIdentity &identity, NetworkServer *server); + void HandleTimeout(); + STEAM_GAMESERVER_CALLBACK(SteamValidation, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t, _callbackGSAuthTicketResponse); +}; +#endif ////////////////////////////////////////////////////////////////////////////// // Network Messages @@ -326,6 +350,7 @@ DECLARE_NET_MESSAGE(AskCommanderOverride, ASKCOMMANDEROVERRIDE_MSG) #define ASK_FOR_SET_ITEM_SHORTCUT_MSG(MessageName, XX) \ XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player person"), TRANSF_REF) \ XX(MessageName, int, index, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Shortcut index"), TRANSF)\ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Bound inventory item"), TRANSF_REF) \ XX(MessageName, RString, itemType, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of the item type"), TRANSF) \ DECLARE_NET_MESSAGE(AskForSetItemShortcut, ASK_FOR_SET_ITEM_SHORTCUT_MSG) @@ -355,9 +380,16 @@ DECLARE_NET_MESSAGE(AskForDropItem, ASK_FOR_DROP_ITEM_MSG) XX(MessageName, OLinkPermO(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("New owner of the item"), TRANSF_REF) \ XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Slot index"), TRANSF)\ XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moved item"), TRANSF_REF) \ + XX(MessageName, bool, rotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Requested inventory orientation"), TRANSF) \ DECLARE_NET_MESSAGE(AskForMoveItem, ASK_FOR_MOVE_ITEM_MSG) +#define ASK_FOR_ROTATE_INVENTORY_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player requesting item rotation"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item to rotate in cargo"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForRotateInventoryItem, ASK_FOR_ROTATE_INVENTORY_ITEM_MSG) + #define ASK_FOR_TAKE_ITEM_TO_HANDS_MSG(MessageName, XX) \ XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person holding the item"), TRANSF_REF) \ XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Held item"), TRANSF_REF) \ @@ -2822,10 +2854,11 @@ class NetworkClient : public NetworkComponent */ void AskForDeleteVehicle(Entity *veh); - void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type); + void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item); void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir); void AskForDropItem(Person *person, InventoryItem *item); - void AskForMoveItem(EntityAI *target, int index, InventoryItem *item); + void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated); + void AskForRotateInventoryItem(Person *person, InventoryItem *item); void AskForTakeItemToHands(Person *person, InventoryItem *item); void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner); @@ -3985,6 +4018,9 @@ struct NetworkPlayerInfo : public AsyncDBStorage, public RefCount, private NoCop /// Hashes collected during initial signature test CollectedHashes hashes; +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + SteamValidation _steamValidate; +#endif /// CDKey check @@ -4513,6 +4549,10 @@ class NetworkServer : public NetworkComponent //! BEServer.ReceivedPlayerGUID() will be called as soon as the GameSpy cd-key hash is received from the client (after connecting). void PlayerGUIDReceived(int player); void PlayerGUIDIsValid(int player); +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + void PlayerGUIDReceived(int player, const CSteamID &id); + void PlayerGUIDIsValid(int player, const CSteamID &ownerId); +#endif #define BE_WRAP_CALLBACK(Name, ...) bool __cdecl Name##Callback(int player, __VA_ARGS__); BE_CALLBACKS(BE_WRAP_CALLBACK) @@ -4759,6 +4799,9 @@ class NetworkServer : public NetworkComponent GameState _evaluator; /// global variables for _evaluator GameDataNamespace _globals; + AutoArray _sqfExecQueue; + AutoArray _sqfExecFrom; + bool _sqfExecBusy; //! event handlers RString _eventHandlers[NServerEvent]; @@ -4930,6 +4973,8 @@ class NetworkServer : public NetworkComponent /// add specific server scripting commands to the _evaluator void InitEvaluator(); + void QueueExec(int from, RString expression); + void ProcessQueuedExec(); void ProfileAnswer(const RString &output); #endif @@ -5010,6 +5055,18 @@ class NetworkServer : public NetworkComponent _beIntegration.PlayerGUIDIsValid(player); #endif }; +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + void PlayerGUIDReceived(int player, const CSteamID &id) { +#if _USE_BATTL_EYE_SERVER + _beIntegration.PlayerGUIDReceived(player, id); +#endif + } + void PlayerGUIDIsValid(int player, const CSteamID &ownerId) { +#if _USE_BATTL_EYE_SERVER + _beIntegration.PlayerGUIDIsValid(player, ownerId); +#endif + } +#endif //! The output format is "creator:id friendlyName" RString NetworkIdToNetIdFriendly(const NetworkId &id); @@ -5867,10 +5924,11 @@ friend class NetworkComponent; void PauseSimulation(bool pause); #endif - virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type) override; + virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) override; virtual void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir) override; virtual void AskForDropItem(Person *person, InventoryItem *item) override; - virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item) override; + virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) override; + virtual void AskForRotateInventoryItem(Person *person, InventoryItem *item) override; virtual void AskForTakeItemToHands(Person *person, InventoryItem *item) override; virtual void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) override; diff --git a/lib/Network/networkServer.cpp b/lib/Network/networkServer.cpp index 14f15d02..af8bfbd4 100644 --- a/lib/Network/networkServer.cpp +++ b/lib/Network/networkServer.cpp @@ -33,6 +33,10 @@ #include #include +#if _ENABLE_STEAM && defined(_WIN64) +bool SteamOnlineServerStart(int gamePort, int steamPort, int queryPort, const char *serverName, int maxPlayers, bool passwordProtected); +#endif + #include #include @@ -48,6 +52,8 @@ #include #include +#include +#include #include "../saveGame.hpp" #include "../saveVersion.hpp" @@ -716,7 +722,7 @@ bool NetworkServer::BattlEye::Run(const NetworkServer *server) } // add all players -#if _VERIFY_CLIENT_KEY +#if _VERIFY_CLIENT_KEY || (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) const AutoArray *identities = server->GetIdentities(); if (identities) { @@ -726,7 +732,14 @@ bool NetworkServer::BattlEye::Run(const NetworkServer *server) sockaddr_in address; server->_server->GetClientAddress(identity.dpnid, address); AddPlayer(identity.dpnid, address.sin_addr.s_addr, address.sin_port, identity.name); +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + if (identity._steamID != 0) + PlayerGUIDReceived(identity.dpnid, CSteamID((uint64)identity._steamID)); + else + PlayerGUIDReceived(identity.dpnid); +#else PlayerGUIDReceived(identity.dpnid); +#endif if (identity.clientState == NCSPlaying) PlayerGoesInGame(identity.dpnid); //else PlayerGoesInLobby(identity.dpnid); //<- assumed as default after AddPlayer @@ -773,10 +786,32 @@ void NetworkServer::BattlEye::PlayerGUIDReceived(int player) } } +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +void NetworkServer::BattlEye::PlayerGUIDReceived(int player, const CSteamID &id) +{ + if (_callbacks._receivedPlayerGUID) + { + uint64 steamId = id.ConvertToUint64(); + (*_callbacks._receivedPlayerGUID)(player, &steamId, sizeof(steamId)); + } +} +#endif + void NetworkServer::BattlEye::PlayerGUIDIsValid(int player) { } +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +void NetworkServer::BattlEye::PlayerGUIDIsValid(int player, const CSteamID &ownerId) +{ + if (_callbacks._playerGUIDIsValid) + { + uint64 steamId = ownerId.ConvertToUint64(); + (*_callbacks._playerGUIDIsValid)(player, &steamId, sizeof(steamId)); + } +} +#endif + bool NetworkServer::BattlEye::UpdatePositionCallback(int player, const char *netId, float x, float y, float z, float dirX, float dirY, float dirZ, float upX, float upY, float upZ, float asideX, float asideY, float asideZ) { @@ -867,9 +902,233 @@ void NetworkServer::BattlEye::KickPlayer(int player, const char *reason) } } +#if _ENABLE_DEDICATED_SERVER +// Large SQF files travel as several ordinary BattlEye commands. Reassemble and +// validate the complete script before putting it on the game-thread queue. +struct SDZBeSqfTransfer +{ + std::string id; + unsigned int expectedParts; + unsigned int expectedCrc; + unsigned int receivedParts; + unsigned int receivedBytes; + DWORD startedAt; + std::vector parts; + std::vector received; + + SDZBeSqfTransfer() : expectedParts(0), expectedCrc(0), receivedParts(0), receivedBytes(0), startedAt(0) {} + void Reset() + { + id.clear(); expectedParts = expectedCrc = receivedParts = receivedBytes = 0; startedAt = 0; + parts.clear(); received.clear(); + } +}; + +static SDZBeSqfTransfer SDZBeTransfer; + +static unsigned int SDZBeCrc32(const char *data, unsigned int length) +{ + unsigned int crc = 0xFFFFFFFF; + for (unsigned int i = 0; i < length; i++) + { + crc ^= (unsigned char)data[i]; + for (int bit = 0; bit < 8; bit++) + crc = (crc & 1) ? ((crc >> 1) ^ 0xEDB88320) : (crc >> 1); + } + return ~crc; +} + +static const char *SDZSkipSpaces(const char *text) +{ + while (*text == ' ' || *text == '\t') text++; + return text; +} + +static bool SDZReadToken(const char **cursor, std::string &token) +{ + const char *start = SDZSkipSpaces(*cursor); + if (!*start) return false; + const char *end = start; + while (*end && *end != ' ' && *end != '\t') end++; + token.assign(start, end - start); + *cursor = end; + return true; +} + +static bool SDZValidTransferId(const std::string &id) +{ + if (id.length() != 32) return false; + for (size_t i = 0; i < id.length(); i++) + if (!((id[i] >= '0' && id[i] <= '9') || (id[i] >= 'a' && id[i] <= 'f') || (id[i] >= 'A' && id[i] <= 'F'))) return false; + return true; +} + +static bool SDZHandleRconSqfTransfer(NetworkServer *server, const char *command) +{ + static const char beginPrefix[] = "#exec __SDZ_BEGIN__ "; + static const char partPrefix[] = "#exec __SDZ_PART__ "; + static const char endPrefix[] = "#exec __SDZ_END__ "; + if (!strnicmp(command, beginPrefix, sizeof(beginPrefix) - 1)) + { + SDZBeTransfer.Reset(); + const char *cursor = command + sizeof(beginPrefix) - 1; + std::string id, countText, crcText, extra; + if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, countText) || !SDZReadToken(&cursor, crcText) || + SDZReadToken(&cursor, extra) || !SDZValidTransferId(id)) + { + RptF("SDZ_BE_RCON: invalid large-SQF begin frame"); + return true; + } + char *parseEnd = NULL; + unsigned long count = strtoul(countText.c_str(), &parseEnd, 10); + if (!parseEnd || *parseEnd || count == 0 || count > 2048) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid part count"); + return true; + } + parseEnd = NULL; + unsigned long crc = strtoul(crcText.c_str(), &parseEnd, 16); + if (!parseEnd || *parseEnd || crc > 0xFFFFFFFFUL) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid checksum"); + return true; + } + SDZBeTransfer.id = id; + SDZBeTransfer.expectedParts = (unsigned int)count; + SDZBeTransfer.expectedCrc = (unsigned int)crc; + SDZBeTransfer.startedAt = GetTickCount(); + SDZBeTransfer.parts.resize(count); + SDZBeTransfer.received.resize(count, 0); + RptF("SDZ_BE_RCON: large-SQF transfer started (%u parts)", (unsigned int)count); + return true; + } + + if (!strnicmp(command, partPrefix, sizeof(partPrefix) - 1)) + { + if (SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected large-SQF part without an active transfer"); + return true; + } + const char *cursor = command + sizeof(partPrefix) - 1; + std::string id, indexText; + if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, indexText) || id != SDZBeTransfer.id) + { + RptF("SDZ_BE_RCON: rejected large-SQF part with invalid transfer id"); + return true; + } + char *parseEnd = NULL; + unsigned long index = strtoul(indexText.c_str(), &parseEnd, 10); + if (!parseEnd || *parseEnd || index >= SDZBeTransfer.expectedParts || *cursor != ' ') + { + RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); + return true; + } + const char *chunk = cursor + 1; + size_t chunkLength = strlen(chunk); + if (chunkLength == 0 || chunkLength > 900) + { + RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); + return true; + } + if (SDZBeTransfer.received[index]) + { + const std::string &receivedChunk = SDZBeTransfer.parts[index]; + if (receivedChunk.size() != chunkLength || receivedChunk.compare(0, receivedChunk.size(), chunk, chunkLength) != 0) + RptF("SDZ_BE_RCON: conflicting duplicate large-SQF part"); + return true; + } + if (SDZBeTransfer.receivedBytes + chunkLength > 1048576) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected SQF script larger than 1 MiB"); + return true; + } + SDZBeTransfer.parts[index].assign(chunk, chunkLength); + SDZBeTransfer.received[index] = 1; + SDZBeTransfer.receivedParts++; + SDZBeTransfer.receivedBytes += (unsigned int)chunkLength; + return true; + } + + if (!strnicmp(command, endPrefix, sizeof(endPrefix) - 1)) + { + const char *cursor = command + sizeof(endPrefix) - 1; + std::string id, extra; + if (!SDZReadToken(&cursor, id) || SDZReadToken(&cursor, extra) || id != SDZBeTransfer.id || + SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected invalid or expired large-SQF end frame"); + return true; + } + if (SDZBeTransfer.receivedParts != SDZBeTransfer.expectedParts) + { + RptF("SDZ_BE_RCON: incomplete large-SQF transfer (%u/%u parts)", SDZBeTransfer.receivedParts, SDZBeTransfer.expectedParts); + SDZBeTransfer.Reset(); + return true; + } + std::string script; + script.reserve(SDZBeTransfer.receivedBytes); + for (unsigned int i = 0; i < SDZBeTransfer.expectedParts; i++) script += SDZBeTransfer.parts[i]; + unsigned int expectedCrc = SDZBeTransfer.expectedCrc; + unsigned int receivedBytes = (unsigned int)script.length(); + SDZBeTransfer.Reset(); + if (SDZBeCrc32(script.c_str(), receivedBytes) != expectedCrc) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with checksum mismatch"); + return true; + } + if (!server || script.empty()) + { + RptF("SDZ_BE_RCON: rejected empty large-SQF script or unavailable server"); + return true; + } + server->QueueExec(BOT_CLIENT, RString(script.c_str())); + RptF("SDZ_BE_RCON: queued reassembled SQF (%u bytes)", receivedBytes); + return true; + } + return false; +} +#endif + void NetworkServer::BattlEye::ExecuteCommand(const char *command) { #if _ENABLE_DEDICATED_SERVER + // BattlEye invokes this callback on the dedicated server. There is normally + // no local NetworkClient there, so forwarding #exec through the client drops + // the command. Queue it for the regular server simulation thread instead. + if (!command || !*command) return; + + if (strlen(command) > 1000) + { + RptF("SDZ_BE_RCON: rejected BattlEye command longer than 1000 bytes"); + return; + } + + NetworkServer *server = GNetworkManager.GetServer(); + if (SDZHandleRconSqfTransfer(server, command)) return; + + if (strnicmp(command, "#exec", 5) == 0 && (command[5] == 0 || command[5] == ' ' || command[5] == '\t')) + { + const char *expression = command + 5; + while (*expression == ' ' || *expression == '\t') expression++; + if (!*expression) + { + RptF("SDZ_BE_RCON: rejected empty #exec command"); + return; + } + if (!server) + { + RptF("SDZ_BE_RCON: rejected #exec because the server is unavailable"); + return; + } + server->QueueExec(BOT_CLIENT, RString(expression)); + RptF("SDZ_BE_RCON: queued #exec (%d bytes)", (int)strlen(expression)); + return; + } + NetworkClient *client = GNetworkManager.GetClient(); if (client) { @@ -1010,6 +1269,9 @@ NetworkServer::NetworkServer(NetworkManager *parent, RString name, RString passw _serverState = NSSSelectingMission; _serverStateTime = GlobalTickCount(); _serverTimeOutSent = INT_MAX; +#if _ENABLE_DEDICATED_SERVER + _sqfExecBusy = false; +#endif _connectionDesync = CDGood; _desyncTotalUpdateNext = GlobalTickCount(); _desyncTotalAvg = 0; @@ -3917,6 +4179,10 @@ void NetworkServer::OnSimulate() ReceiveUserMessages(); } +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) ProcessQueuedExec(); +#endif + PerformIntegrityInvestigations(); #if _ENABLE_MP @@ -6086,6 +6352,16 @@ LogF(" sending to %x", pl._player); _squadChecks.Add(new CheckSquadObject(identity, _proxy, this)); +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid != from) continue; + info._steamValidate.Start(identity, this); + break; + } +#endif + //} // send server time to player just connected @@ -6246,6 +6522,15 @@ LogF(" sending to %x", pl._player); case NMTAskForSwapItems: SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); break; + case NMTAskForRotateInventoryItem: + { + AskForRotateInventoryItemMessage ask; + TMError err = ask.TransferMsg(ctx); + if ((err == TMOK || err == TMNotFound) && ask._person && ask._item && + ask._person->GetRemotePlayer() == from && ask._person->FindItem(ask._item)) + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); + } + break; case NMTAskInventoryMenu: { PREPARE_TRANSFER(AskInventoryMenu) @@ -7598,19 +7883,7 @@ LogF(" sending to %x", pl._player); if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) { RString expression = cmd._content.ReadString(); - - GameVarSpace local(false); - int gshandle = _evaluator.BeginContext(&local); - GameValue result = _evaluator.EvaluateMultiple(expression, GameState::EvalContext::_default, &_globals); // server namespace - _evaluator.EndContext(gshandle); - - if (!result.GetNil()) - { - NetworkCommandMessage msg; - msg._type = NCMTExecResult; - msg._content.WriteString(result.GetText()); - SendMsg(from, &msg, NMFGuaranteed); - } + if (expression.GetLength() > 0) QueueExec(from, expression); } } break; @@ -8192,6 +8465,7 @@ void NetworkServer::CheckItemOwner(const NetworkId &id, int newOwner) */ void NetworkServer::OnHackedData(HackType type, int dpid, RString filename) { + RptF("NetworkHackedData type=%d player=%d file=%s", (int)type, dpid, cc_cast(filename)); const PlayerIdentity *identity = FindIdentity(dpid); if (!identity) return; @@ -11258,6 +11532,10 @@ static void LogError */ void NetworkServer::CheckFadeOut() { +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + for (int i=0; i<_players.Size(); i++) + _players[i]->_steamValidate.HandleTimeout(); +#endif if (_serverState == NSSPlaying) { @@ -13057,6 +13335,18 @@ bool CreateDedicatedServer(SessionType sessionType, RString config) if (entry) maxPlayers = *entry; maxPlayers += 1; // dedicated server occupy single slot + RString steamServerName("SourceDayZ Community Server"); + entry = serverCfg.FindEntry("hostname"); + if (entry) steamServerName = *entry; + + int steamPort = 8766; + entry = serverCfg.FindEntry("steamPort"); + if (entry) steamPort = *entry; + + int steamQueryPort = 27016; + entry = serverCfg.FindEntry("steamQueryPort"); + if (entry) steamQueryPort = *entry; + int port = GetServerPort(); int rating = 0; @@ -13081,6 +13371,12 @@ bool CreateDedicatedServer(SessionType sessionType, RString config) MyPidFile = true; } } +#if _ENABLE_STEAM && defined(_WIN64) + if (steamPort > 0 && steamPort <= 65535 && steamQueryPort > 0 && steamQueryPort <= 65535) + SteamOnlineServerStart(port, steamPort, steamQueryPort, cc_cast(steamServerName), maxPlayers - 1, !password.IsEmpty()); + else + LogF("Steamworks server-list ports are invalid; use steamPort and steamQueryPort in the dedicated server config"); +#endif return true; } @@ -13841,6 +14137,85 @@ void NetworkServer::ProfileAnswer(const RString &output) SendMsg(_gameMaster, &msg, NMFGuaranteed); } +void NetworkServer::QueueExec(int from, RString expression) +{ + if (expression.GetLength() <= 0) return; + if (_sqfExecQueue.Size() >= 32 || _sqfExecQueue.Size() != _sqfExecFrom.Size()) + { + RptF("SDZ_SQF_EXEC: rejected command because the execution queue is full or inconsistent"); + return; + } + _sqfExecQueue.Add(expression); + _sqfExecFrom.Add(from); +} + +#if defined(_MSC_VER) +// Keep SEH in a helper without C++ objects that have destructors. +static bool SDZ_TryEvaluateSqf(GameState *state, const char *expression, GameDataNamespace *globals, GameValue *result) +{ + __try + { + *result = state->EvaluateMultiple(expression, GameState::EvalContext::_default, globals); + return true; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + RptF("SDZ_SQF_EXEC: exception 0x%08X while evaluating script", (unsigned)GetExceptionCode()); + return false; + } +} +#endif + +void NetworkServer::ProcessQueuedExec() +{ + if (_sqfExecBusy || _sqfExecQueue.Size() <= 0) return; + _sqfExecBusy = true; + + GameState *execState = GWorld ? GWorld->GetGameState() : NULL; + GameDataNamespace *mission = GWorld ? GWorld->GetMissionNamespace() : NULL; + if (!execState || !mission) + { + _sqfExecQueue.Resize(0); + _sqfExecFrom.Resize(0); + _sqfExecBusy = false; + return; + } + + while (_sqfExecQueue.Size() > 0) + { + RString expression = _sqfExecQueue[0]; + int from = _sqfExecFrom[0]; + _sqfExecQueue.Delete(0); + _sqfExecFrom.Delete(0); + + GameVarSpace local(false); + int gshandle = execState->BeginContext(&local); + GameValue result = NOTHING; + bool evaluated = false; +#if defined(_MSC_VER) + evaluated = SDZ_TryEvaluateSqf(execState, expression, mission, &result); +#else + result = execState->EvaluateMultiple(expression, GameState::EvalContext::_default, mission); + evaluated = true; +#endif + RString answer; + if (evaluated && !result.GetNil()) answer = result.GetText(); + if (from == BOT_CLIENT) + RptF("SDZ_BE_RCON: SQF evaluation %s", evaluated ? "completed" : "failed (see preceding exception)"); + result = NOTHING; + execState->EndContext(gshandle); + + if (from != BOT_CLIENT && answer.GetLength() > 0) + { + NetworkCommandMessage msg; + msg._type = NCMTExecResult; + msg._content.WriteString(answer); + SendMsg(from, &msg, NMFGuaranteed); + } + } + _sqfExecBusy = false; +} + #endif // _ENABLE_DEDICATED_SERVER void ServerQueueItem::SetFence(const RefR &resultMsg) diff --git a/lib/Shape/material.cpp b/lib/Shape/material.cpp index 93218e70..48b34813 100644 --- a/lib/Shape/material.cpp +++ b/lib/Shape/material.cpp @@ -1231,6 +1231,7 @@ void TexMaterial::RequestData() in.AutoOpen(_name); if (in.fail()) { + RptF("MissingResource category=material path=%s", cc_cast(_name)); ErrorMessage(EMMissingData, "Cannot load material file %s.", cc_cast(_name)); RptF("Cannot load material file %s",cc_cast(_name)); Init(); diff --git a/lib/Shape/shape.cpp b/lib/Shape/shape.cpp index 11b3fc4f..77955087 100644 --- a/lib/Shape/shape.cpp +++ b/lib/Shape/shape.cpp @@ -8579,6 +8579,7 @@ bool LODShape::Load(const char *name, bool reversed, const ModelTarget &mt, cons // make sure the shape is named, even when not loaded // otherwise shape caching may be confused _name = nameTemp; + RptF("MissingResource category=object path=%s", (const char *)nameTemp); ErrorMessage(EMMissingData, "Cannot open object %s",(const char *)nameTemp); return false; } diff --git a/lib/UI/displayUI.cpp b/lib/UI/displayUI.cpp index 4dfb55c6..2b812e05 100644 --- a/lib/UI/displayUI.cpp +++ b/lib/UI/displayUI.cpp @@ -55,6 +55,85 @@ #include "../dynSound.hpp" #include "displayUI.hpp" +#if _ENABLE_STEAM && defined(_WIN64) +#include + +bool IsSteamClientInitialized(); + +class SteamServerListBridge : public ISteamMatchmakingServerListResponse +{ + DisplayMultiplayer *_owner; + HServerListRequest _request; + bool _complete; + MatchMakingKeyValuePair_t _tagFilter; + +public: + SteamServerListBridge(DisplayMultiplayer *owner) + : _owner(owner), _request(NULL), _complete(false), _tagFilter("gametagsand", "sourcedayz") + { + } + + ~SteamServerListBridge() + { + _owner = NULL; + Stop(); + } + + void Stop() + { + if (!_request) return; + HServerListRequest request = _request; + bool cancelRequest = !_complete; + // Invalidate the callback target before calling Steam. CancelQuery may + // complete a callback synchronously while the display is being destroyed. + _request = NULL; + _complete = false; + ISteamMatchmakingServers *servers = SteamMatchmakingServers(); + if (servers) + { + if (cancelRequest) servers->CancelQuery(request); + servers->ReleaseRequest(request); + } + } + + bool Start() + { + Stop(); + if (!IsSteamClientInitialized()) return false; + ISteamMatchmakingServers *servers = SteamMatchmakingServers(); + if (!servers) return false; + MatchMakingKeyValuePair_t *filters[] = { &_tagFilter }; + _complete = false; + _request = servers->RequestInternetServerList(480, filters, 1, this); + return _request != NULL; + } + + void ServerResponded(HServerListRequest request, int serverIndex) override + { + if (!_owner || request != _request) return; + ISteamMatchmakingServers *servers = SteamMatchmakingServers(); + if (!servers) return; + gameserveritem_t *server = servers->GetServerDetails(request, serverIndex); + if (server) _owner->AddSteamServer(*server); + } + + void ServerFailedToRespond(HServerListRequest request, int serverIndex) override + { + (void)request; + (void)serverIndex; + } + + void RefreshComplete(HServerListRequest request, EMatchMakingServerResponse response) override + { + if (!_owner || request != _request) return; + _complete = true; + _owner->FinishSteamServerList(); + if (response == eNoServersListedOnMasterServer) + RptF("Steamworks server browser returned no SourceDayZ servers"); + } +}; +#endif + #include "../Protect/selectProtection.h" #include "../mbcs.hpp" @@ -7259,6 +7338,9 @@ struct UpdateSBCallback : public INetworkUpdateCallback */ DisplayMultiplayer::DisplayMultiplayer(ControlsContainer *parent) : Display(parent) +#if _ENABLE_STEAM && defined(_WIN64) + , _steamServerList(NULL) +#endif { _enableSimulation = false; _sessions = NULL; @@ -7270,6 +7352,10 @@ DisplayMultiplayer::DisplayMultiplayer(ControlsContainer *parent) Load("RscDisplayMultiplayer"); LoadParams(); +#if _ENABLE_STEAM && defined(_WIN64) + _steamServerList = new SteamServerListBridge(this); +#endif + _refresh = true; #if _ENABLE_GAMESPY @@ -7323,7 +7409,11 @@ DisplayMultiplayer::DisplayMultiplayer(ControlsContainer *parent) ProgressFinish(p); #endif // _ENABLE_MP - if (_source == BSInternet && !_serverBrowser) _source = BSLAN; + if (_source == BSInternet && !_serverBrowser +#if _ENABLE_STEAM && defined(_WIN64) + && !_steamServerList +#endif + ) _source = BSLAN; } #endif // _ENABLE_GAMESPY @@ -7361,18 +7451,24 @@ DisplayMultiplayer::DisplayMultiplayer(ControlsContainer *parent) SetSource(source, false); +#if _ENABLE_STEAM && defined(_WIN64) + if (_source == BSInternet) UpdateSteamServerList(); + else +#endif + { #if _ENABLE_GAMESPY - // need to be called to obtain my public IP address - UpdateServerList(); - if (_source != BSInternet) UpdateSessions(); + // need to be called to obtain my public IP address + UpdateServerList(); + if (_source != BSInternet) UpdateSessions(); #else - UpdateSessions(); + UpdateSessions(); #endif + } OnSessionChanged(true); -#if _ENABLE_GAMESPY +#if _ENABLE_GAMESPY || (_ENABLE_STEAM && defined(_WIN64)) if (_source == BSInternet) { ShowFilterIcons(true); @@ -7393,7 +7489,110 @@ DisplayMultiplayer::~DisplayMultiplayer() if (_serverBrowser) ServerBrowserFree(_serverBrowser); #endif +#if _ENABLE_STEAM && defined(_WIN64) + delete _steamServerList; + _steamServerList = NULL; +#endif +} + +#if _ENABLE_STEAM && defined(_WIN64) +void DisplayMultiplayer::UpdateSteamServerList() +{ + if (!_sessions || !_steamServerList || !_refresh) return; + + SetProgress(0); + _sessions->_sessions.Resize(0); + _sessions->_indices.Resize(0); + _sessions->SelectSession(0); + _sessionSelected = false; + _refresh = false; + + if (!_steamServerList->Start()) + { + RptF("Steamworks Internet server list could not be started; verify Steam is running and online"); + SetProgress(100); + } +} + +void DisplayMultiplayer::AddSteamServer(const gameserveritem_t &server) +{ + if (!_sessions || !server.m_bHadSuccessfulResponse) return; + + const char *address = server.m_NetAdr.GetConnectionAddressString(); + if (!address || !address[0]) return; + RString guid(address); + + if (_filter.maxPing > 0 && server.m_nPing > _filter.maxPing) return; + if (!_filter.passwordedServers && server.m_bPassword) return; + if (!_filter.fullServers && server.m_nMaxPlayers > 0 && server.m_nPlayers >= server.m_nMaxPlayers) return; + if (_filter.minPlayers > 0 && server.m_nPlayers < _filter.minPlayers) return; + if (_filter.maxPlayers > 0 && server.m_nPlayers > _filter.maxPlayers) return; + + int index = -1; + for (int i = 0; i < _sessions->_sessions.Size(); i++) + { + if (_sessions->_sessions[i].guid == guid) + { + index = i; + break; + } + } + if (index < 0) + { + index = _sessions->_sessions.Add(); + _sessions->_indices.Add(index); + } + + SessionInfo &session = _sessions->_sessions[index]; + session.guid = guid; + session.name = server.GetName(); + session.gameType = "DayZ"; + session.mission = server.m_szMap; + session.island = server.m_szMap; + session.lastTime = 0xFFFFFFFF; + session.actualVersion = APP_VERSION_NUM; + session.actualBuildNo = BUILD_NO; + session.requiredVersion = APP_VERSION_NUM; + session.requiredBuildNo = 0; + session.password = server.m_bPassword; + session.lock = false; + session.badActualVersion = false; + session.badRequiredVersion = false; + session.badMod = false; + session.badAdditionalMods = false; + session.badSignatures = false; + session.serverState = NSSPlaying; + session.ping = server.m_nPing; + session.playersPublic = server.m_nPlayers; + session.slotsPublic = server.m_nMaxPlayers; + session.friends = 0; + session.favorite = false; + session.timeleft = 0; + session.platform = "W"; + session.mod = "SourceDayZ"; + session.equalModRequired = false; + session.dedicated = true; + session.language = 0x10009; + session.difficulty = Glob.config.diffDefault; + session.country = RString(); + session.region = 0; + session.battleEye = 0; + session.timeOfDay = RString(); + session.disable3rdPerson = 0; + session.environmentTimeMul = 1.0f; + session.privateHive = 0; + session.longitude = INT_MAX; + session.latitude = INT_MAX; +} + +void DisplayMultiplayer::FinishSteamServerList() +{ + if (!_sessions) return; + _sessions->Sort(_sort, _ascending, _sessionSelected); + SetProgress(100); + OnSessionChanged(false); } +#endif Control *DisplayMultiplayer::OnCreateCtrl(int type, int idc, ParamEntryPar cls) { @@ -7421,6 +7620,14 @@ Control *DisplayMultiplayer::OnCreateCtrl(int type, int idc, ParamEntryPar cls) void DisplayMultiplayer::OnSimulateBasic() { +#if _ENABLE_STEAM && defined(_WIN64) + if (_source == BSInternet && _steamServerList) + { + UpdateSteamServerList(); + } + else +#endif + { #if _ENABLE_GAMESPY UpdateServerList(); if (_listUpdateRunning==StageDone) @@ -7449,6 +7656,7 @@ void DisplayMultiplayer::OnSimulateBasic() #else UpdateSessions(); #endif + } OnSessionChanged(false); } @@ -7507,9 +7715,17 @@ void DisplayMultiplayer::SetSource(BrowsingSource source, bool save) _source = source; if (save) SaveParams(); +#if _ENABLE_GAMESPY || (_ENABLE_STEAM && defined(_WIN64)) + bool internet = source == BSInternet; +#else bool internet = false; +#endif +#if _ENABLE_GAMESPY if (GetCtrl(IDC_MULTI_GAMESPY)) GetCtrl(IDC_MULTI_GAMESPY)->ShowCtrl(internet); +#else + if (GetCtrl(IDC_MULTI_GAMESPY)) GetCtrl(IDC_MULTI_GAMESPY)->ShowCtrl(false); +#endif if (GetCtrl(IDC_MULTI_PROGRESS)) GetCtrl(IDC_MULTI_PROGRESS)->ShowCtrl(internet); if (GetCtrl(IDC_MULTI_REFRESH)) GetCtrl(IDC_MULTI_REFRESH)->ShowCtrl(true); if (GetCtrl(IDC_MULTI_FILTER)) GetCtrl(IDC_MULTI_FILTER)->ShowCtrl(internet); @@ -7893,8 +8109,17 @@ void DisplayMultiplayer::OnButtonClicked(int idc) switch (idc) { #ifndef _XBOX + case IDC_MULTI_TAB_INTERNET: +#if _ENABLE_GAMESPY || (_ENABLE_STEAM && defined(_WIN64)) + SetSource(BSInternet, true); + SetTab(MPTabInternet); + ShowFilterIcons(true); + _refresh = true; +#endif + break; case IDC_MULTI_TAB_LAN: SetTab(MPTabLAN); + ShowFilterIcons(false); UpdateAddress("", _portLocal); break; case IDC_MULTI_TAB_REMOTE: @@ -9276,7 +9501,11 @@ void DisplayMultiplayer::LoadParams() ParamArchiveLoad ar; if (!ParseUserParamsArchive(ar, &globals)) return; +#if _ENABLE_STEAM && defined(_WIN64) + BrowsingSource defaultSource = BSInternet; +#else BrowsingSource defaultSource = BSLAN; +#endif ar.SerializeEnum("browsingSource", _source, 1, defaultSource); #if _ENABLE_GAMESPY diff --git a/lib/UI/displayUI.hpp b/lib/UI/displayUI.hpp index 72b62c62..47b86a89 100644 --- a/lib/UI/displayUI.hpp +++ b/lib/UI/displayUI.hpp @@ -785,6 +785,11 @@ class C2DSessions : public CListBox, public CSessionsContainer XX(type, prefix, LAN) \ XX(type, prefix, Internet) \ XX(type, prefix, Remote) +#elif _ENABLE_STEAM && defined(_WIN64) +#define BROWSING_SOURCE_ENUM(type, prefix, XX) \ + XX(type, prefix, LAN) \ + XX(type, prefix, Remote) \ + XX(type, prefix, Internet) #else #define BROWSING_SOURCE_ENUM(type, prefix, XX) \ XX(type, prefix, LAN) \ @@ -833,6 +838,9 @@ enum MPTabs { MPTabInternet, MPTabFavorite, MPTabHistory, MPTabFriends, MPTabLAN, MPTabRemote, MP_TABS_COUNT }; +class SteamServerListBridge; +class gameserveritem_t; + class DisplayMultiplayer : public Display { protected: @@ -864,6 +872,13 @@ class DisplayMultiplayer : public Display #endif +#if _ENABLE_STEAM && defined(_WIN64) + friend class SteamServerListBridge; + SteamServerListBridge *_steamServerList; + void AddSteamServer(const gameserveritem_t &server); + void FinishSteamServerList(); +#endif + MPTabs _activeTab; //! which sessions are listed @@ -955,6 +970,10 @@ class DisplayMultiplayer : public Display //! remove a server void RemoveServer(SBServer server); +#endif +#if _ENABLE_STEAM && defined(_WIN64) + //! updates public sessions from the Steam game-server master list + void UpdateSteamServerList(); #endif //! update display when other session was selected void OnSessionChanged(bool changed); diff --git a/lib/UI/optionsUI.cpp b/lib/UI/optionsUI.cpp index 16f61b4b..1bf929eb 100644 --- a/lib/UI/optionsUI.cpp +++ b/lib/UI/optionsUI.cpp @@ -1608,6 +1608,7 @@ RString FindPicture(RString name) RString fullname = GetPictureName(name); if (QFBankQueryFunctions::FileExists(fullname)) return fullname; + RptF("MissingResource category=picture requested=%s resolved=%s", (const char *)name, (const char *)fullname); ErrorMessage(EMMissingData, "Picture %s not found", (const char *)name); return ""; } diff --git a/lib/UI/uiContainers.cpp b/lib/UI/uiContainers.cpp index 900c825c..7ae01487 100644 --- a/lib/UI/uiContainers.cpp +++ b/lib/UI/uiContainers.cpp @@ -34,6 +34,10 @@ #include "uiMap.hpp" +extern bool HandleInventorySpaceKey(); +extern void ReleaseInventorySpaceKey(); +extern bool IsInventoryOpened(); + // #pragma optimize("", off) /*! @@ -1955,6 +1959,9 @@ static int dikCodeShortcutFirst[] = {INPUT_DEVICE_XINPUT + XBOX_Start}; bool ControlsContainer::OnKeyDown(int dikCode) { + if (dikCode == DIK_SPACE && HandleInventorySpaceKey()) + return true; + bool ok = false; bool enableCtrlProcessing = EnableDefaultKeysProcessing(); bool shift = GInput.keys[DIK_LSHIFT] || GInput.keys[DIK_RSHIFT]; @@ -2155,6 +2162,12 @@ bool ControlsContainer::OnKeyDown(int dikCode) bool ControlsContainer::OnKeyUp(int dikCode) { + if (dikCode == DIK_SPACE) + { + ReleaseInventorySpaceKey(); + if (IsInventoryOpened()) return true; + } + bool ok = false; bool enableCtrlProcessing = EnableDefaultKeysProcessing(); bool shift = GInput.keys[DIK_LSHIFT] || GInput.keys[DIK_RSHIFT]; (void)shift; diff --git a/lib/UI/uiMap.cpp b/lib/UI/uiMap.cpp index cc8332be..8ae0c54a 100644 --- a/lib/UI/uiMap.cpp +++ b/lib/UI/uiMap.cpp @@ -6345,6 +6345,7 @@ class DisplayInventory : public Display // drag & drop info OLinkPermO(InventoryItem) _dragItem; + bool _dragRotated; float _dragOffsetX, _dragOffsetY; float _dragGridW, _dragGridH; float _dragZ; @@ -6439,6 +6440,7 @@ class DisplayInventory : public Display virtual void OnDrag(IControl *ctrl) override; virtual unsigned char OnDragging(IControl *draggCtrl, IControl *dropCtrl, float x, float y) override; virtual bool OnDrop(IControl *draggCtrl, IControl *dropCtrl, float x, float y) override; + virtual bool OnKeyDown(int dikCode) override; virtual void DrawDragInfo(float x, float y, unsigned char enabled, Ref dragFont, float dragSize) override; @@ -6464,9 +6466,9 @@ void CItemBase::SetItemShortcut(int index, const InventoryItem *item) const InventoryItemType *type = item ? item->Type() : NULL; if (!GetNetworkManager().IsServerOwner()) // BOT client have to handle it - GetNetworkManager().AskForSetItemShortcut(player, index, type); + GetNetworkManager().AskForSetItemShortcut(player, index, type, const_cast(item)); else - player->SetItemShortcut(index, type); + player->SetItemShortcutInstance(index, const_cast(item)); } void CItemBase::DropItem(Person *owner, InventoryItem *item) @@ -6510,7 +6512,7 @@ void CItemBase::MoveItem(EntityAI *target, int index, InventoryItem *item) if (!GetNetworkManager().IsServerOwner()) // BOT client have to handle it - GetNetworkManager().AskForMoveItem(target, index, item); + GetNetworkManager().AskForMoveItem(target, index, item, item->IsInventoryRotated()); else { Entity *parent = item->GetHierarchyParent(); @@ -6525,6 +6527,17 @@ bool CItemBase::CanMoveItem(EntityAI *target, int index, const InventoryItem *it return target->CanMoveItem(index, item); } +void CItemBase::RotateInventoryItem(Person *person, InventoryItem *item) +{ + // Items in the hands slot are manipulated by dragging them out of the slot, + // never by changing their inventory orientation in place. + if (!item || (person && person->GetItemInHands() == item)) return; + if (!GetNetworkManager().IsServerOwner()) + GetNetworkManager().AskForRotateInventoryItem(person, item); + else if (item->RotateInInventory()) + GetNetworkManager().UpdateObject(item, NMCUpdateGeneric); +} + void CItemBase::TakeItemToHands(Person *person, InventoryItem *item) { if (!GetNetworkManager().IsServerOwner()) @@ -7249,8 +7262,8 @@ bool ContainerUI::DrawObjects(ControlsContainer *parent, CItemBase *ctrl, Invent const InventoryItemType *type = item->Type(); if (type) { - int w = type->GetItemWidth(); - int h = type->GetItemHeight(); + int w = item->GetInventoryWidth(); + int h = item->GetInventoryHeight(); if (top + h * _gridH <= bottom) /* better not to draw part of object */ { Color color(0, 0, 0, -1.0f); @@ -7284,7 +7297,7 @@ static RString GetSpaceText(const InventoryStorage &cargo) if (item) { const InventoryItemType *type = item->Type(); - if (type) count += type->GetItemWidth() * type->GetItemHeight(); + if (type) count += item->GetInventoryWidth() * item->GetInventoryHeight(); } } return Format("%d/%d", count, cargo.GetWidth() * cargo.GetHeight()); @@ -7438,7 +7451,7 @@ bool ContainerUI::DrawForeground(CItemBase *ctrl, UIViewport *vp, InventoryItem if (text) { SetTextAttribute(text, "shadow", "1"); - Rect2DFloat rect(0, 0, type->GetItemWidth() * _gridW, type->GetItemHeight() * _gridH); + Rect2DFloat rect(0, 0, item->GetInventoryWidth() * _gridW, item->GetInventoryHeight() * _gridH); float h = GetTextHeight(text, rect, _size); float w = GetTextWidthFloat(text, _size); rect.x = x + rect.w - w; rect.y = y + rect.h - h; @@ -7625,14 +7638,14 @@ bool ContainerUI::DrawBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem const float heat = item->GetTemperature(); pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorItemBackground")); } - vp->Draw2D(pars, Rect2DPixel(cx, cy, CW(type->GetItemWidth() * _gridW), CH(type->GetItemHeight() * _gridH)), clipRect); - for (int k=i; kGetItemHeight(); k++) - for (int l=j; lGetItemWidth(); l++) + vp->Draw2D(pars, Rect2DPixel(cx, cy, CW(item->GetInventoryWidth() * _gridW), CH(item->GetInventoryHeight() * _gridH)), clipRect); + for (int k=i; kGetInventoryHeight(); k++) + for (int l=j; lGetInventoryWidth(); l++) { int ii = k * cargo->GetWidth() + l; handled[ii] = true; } - if (inHands) vp->Draw2D(hand, Rect2DPixel(CX(x + type->GetItemWidth() * _gridW) - hh, CY(y + type->GetItemHeight() * _gridH) - hh, hh, hh), clipRect); + if (inHands) vp->Draw2D(hand, Rect2DPixel(CX(x + item->GetInventoryWidth() * _gridW) - hh, CY(y + item->GetInventoryHeight() * _gridH) - hh, hh, hh), clipRect); } else { @@ -7663,15 +7676,15 @@ bool ContainerUI::DrawBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem const InventoryItemType *type = item ? item->Type() : nullptr; if (type) { - float ww = CW(type->GetItemWidth() * _gridW); - float hh = CH(type->GetItemHeight() * _gridH); + float ww = CW(item->GetInventoryWidth() * _gridW); + float hh = CH(item->GetInventoryHeight() * _gridH); vp->DrawLine(Line2DPixel(cx, cy, cx + ww, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); vp->DrawLine(Line2DPixel(cx + ww, cy, cx + ww, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); vp->DrawLine(Line2DPixel(cx + ww, cy + hh, cx, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); vp->DrawLine(Line2DPixel(cx, cy + hh, cx, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - for (int k=i; kGetItemHeight(); k++) - for (int l=j; lGetItemWidth(); l++) + for (int k=i; kGetInventoryHeight(); k++) + for (int l=j; lGetInventoryWidth(); l++) { int ii = k * cargo->GetWidth() + l; handled[ii] = true; @@ -8428,8 +8441,12 @@ bool CItemContent::ForEachSlot( int columns = toIntFloor(_w / _titleW); int col = 0; float left = _x; - for (int j=0; j ISShoulder + 1 && order <= ISShoulder2 ? order - 1 : order); InventoryItem *item = _person->GetInSlot((InventorySlotId)j); if (!item) continue; @@ -8460,8 +8477,10 @@ bool CItemContent::ForEachSlot( if (first-- <= 0) top += _titleH + vSpace; } // containers then - for (int j=0; j ISShoulder + 1 && order <= ISShoulder2 ? order - 1 : order); InventoryItem *container = _person->GetInSlot((InventorySlotId)j); if (!container) continue; @@ -8755,11 +8774,6 @@ class CItemInHands : public CItemBase PackedColor _bgNoItemColor; PackedColor _bgItemColor; - float _rotateX; // position of mouse when rotation started - float _rotation; // total rotation - - bool _rotating; - public: CItemInHands(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person); @@ -8774,10 +8788,6 @@ class CItemInHands : public CItemBase virtual float GetGridW() override; virtual float GetGridH() override; virtual bool IsContained(InventoryItem *item) override; - - virtual void OnLButtonDown(float x, float y) override; - virtual void OnLButtonUp(float x, float y) override; - virtual void OnMouseMove(float x, float y, bool active = true) override; }; CItemInHands::CItemInHands(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person) @@ -8792,9 +8802,6 @@ CItemInHands::CItemInHands(ControlsContainer *parent, int idc, ParamEntryPar cls _bgNoItemColor = GetPackedColor(cls >> "colorNoItemBackground"); _bgItemColor = GetPackedColor(cls >> "colorItemBackground"); - - _rotating = false; - _rotation = 0; } void CItemInHands::OnDraw(float alpha) @@ -8802,8 +8809,6 @@ void CItemInHands::OnDraw(float alpha) InventoryItem *item = _person ? _person->GetItemInHands() : NULL; if (item) { - Matrix3 rot(MRotationY, _rotation); - float height = _h - _gridH; DisplayInventory *display = dynamic_cast(_parent.GetLink()); @@ -8815,7 +8820,7 @@ void CItemInHands::OnDraw(float alpha) else if (display->GetSwappedItem() == item) color = ColorItemSwapped; } - DrawItem(item, _x, _y, _w, height, _z, alpha, color, &rot); + DrawItem(item, _x, _y, _w, height, _z, alpha, color); float top = _y + height; int columns = toIntFloor(_w / _gridW); @@ -9089,8 +9094,8 @@ bool CItemInHands::CanAddItem(InventoryItem *newItem, float x, float y) if (m && m->IsOnAnyLadder()) return false; - // only items already owned can be in hands - if (!_person->FindItem(newItem)) return false; + // Ground items can be dragged directly into empty hands as well. + if (!_person->FindItem(newItem) && !newItem->IsInLandscape()) return false; float top = _y + _h - _gridH; @@ -9098,14 +9103,12 @@ bool CItemInHands::CanAddItem(InventoryItem *newItem, float x, float y) InventoryItem *oldItem = _person->GetItemInHands(); if (!oldItem) { - const InventoryItemType *type = newItem->Type(); - return type && type->IsHandheld(); + return true; } if (y < top) { - const InventoryItemType *type = newItem->Type(); - if (type && type->IsHandheld()) return true; // directly to hands + if (newItem->Type()) return true; // directly to hands return CanMoveItem(oldItem, -1, newItem); // as an attachment } @@ -9133,8 +9136,7 @@ void CItemInHands::AddItem(InventoryItem *newItem, float x, float y) { if (!_person) return; - // only items already owned can be in hands - if (!_person->FindItem(newItem)) return; + if (!_person->FindItem(newItem) && !newItem->IsInLandscape()) return; float top = _y + _h - _gridH; @@ -9142,18 +9144,13 @@ void CItemInHands::AddItem(InventoryItem *newItem, float x, float y) InventoryItem *oldItem = _person->GetItemInHands(); if (!oldItem) { - const InventoryItemType *type = newItem->Type(); - if (type && type->IsHandheld()) TakeItemToHands(_person, newItem); + TakeItemToHands(_person, newItem); return; } if (y < top) { - const InventoryItemType *type = newItem->Type(); - if (type && type->IsHandheld()) - TakeItemToHands(_person, newItem); // directly to hands - else - MoveItem(oldItem, -1, newItem); // as an attachment + TakeItemToHands(_person, newItem); return; } @@ -9185,46 +9182,6 @@ float CItemInHands::GetGridH() return _gridH; } -void CItemInHands::OnLButtonDown(float x, float y) -{ - float top = _y + _h - _gridH; - if (y < top) - { - // rotate the container model - _rotating = true; - _rotateX = x; - } - else base::OnLButtonDown(x, y); -} - -void CItemInHands::OnLButtonUp(float x, float y) -{ - if (_rotating) - { - _rotating = false; - } - else base::OnLButtonUp(x, y); -} - -void CItemInHands::OnMouseMove(float x, float y, bool active) -{ - if (_rotating) - { - // rotation speed - static const float speed = 8.0f; - - // hotfix when OnLButtonUp was not called - if (!GInput.mouseL) return; // maybe drag & drop cancel reaction would be needed - - float diff = x - _rotateX; - _rotation += speed * diff; - if (_rotation > H_PI) _rotation -= H_2PI; - else if (_rotation < -H_PI) _rotation += H_2PI; - _rotateX = x; - } - else base::OnMouseMove(x, y, active); -} - class CPlayerPreview : public ControlObject { private: @@ -9432,6 +9389,9 @@ void CPlayerPreview::OnDraw(float alpha) Matrix4 pTransform = proxyObj->RenderVisualState().Transform(); SkeletonIndex boneIndex = _proxies.GetProxyBoneForLevel(_shape, level, i); AnimateMatrix(pTransform, boneIndex); + // Pose anchor in the paperdoll model space. The second shoulder weapon + // below uses the very same composition as the world rendering. + Matrix4 animatedProxy = pTransform; pTransform = GetFrameBase() * pTransform; if (shape->Remarks() & ShapeReversed) @@ -9481,6 +9441,66 @@ void CPlayerPreview::OnDraw(float alpha) ctrl->AnimateMatrix(matrix, boneIndex); return true; }); + + // The character model has a single shoulder proxy, so as in the world + // rendering the second shoulder weapon must be drawn manually at the + // same proxy, mirrored to the right half of the back. + if (proxyType->GetInventorySlot() == ISShoulder) + { + InventoryItem *secondItem = _person->GetInSlot(ISShoulder2); + LODShape *secondShape = secondItem ? secondItem->GetShape() : NULL; + if (secondShape && secondItem != item) + { + // Same composition as Man::PrepareProxiesForDrawing: the offset is + // applied to the pose anchor in model space, then the paperdoll + // frame places the result. + Matrix4 oppositeSide(MTranslation, Vector3(+0.32f, 0.0f, -0.10f)); + Matrix4 secondTransform = GetFrameBase() * oppositeSide * animatedProxy; + + if (secondShape->Remarks() & ShapeReversed) + { + Matrix4 swapM(MScale, -1, +1, -1); + secondTransform = secondTransform * swapM; + } + + Ref oi2 = new SortObject(); + oi2->SetObject(secondItem); + oi2->SetRootObject(this); + if (GetShape() && secondShape->GetSkeletonSource() == GetShape()->GetSkeletonSource()) + oi2->SetParentObject(this); + + secondItem->InsideUIDraw(true); + + Color color(1.0f, 1.0f, 1.0f, 1.0f); + DisplayInventory *display = dynamic_cast(_parent.GetLink()); + if (display) + { + if (display->GetDraggedItem() == secondItem) color = ColorItemDragged; + else if (display->GetSwappedItem() == secondItem) color = ColorItemSwapped; + } + color.SetA(alpha * color.A()); + GEngine->SetInstanceInfo(-1, color, 1.0f); + + secondItem->Draw(-1, pLevel, ClipAll, DrawParameters::_noShadow, InstanceParameters::_default, dist2, secondTransform, oi2 +#if _HELISIM_RENDER_TO_TEXTURE + , GScene->GetDrawObjectIndex() +#endif + ); + + secondItem->InsideUIDraw(false); + GEngine->SetInstanceInfo(-1, HWhite, 1); + + Object *parentObject2 = oi2->GetParentObject(); + secondItem->DrawProxies(pLevel, dist2, secondTransform, [&parentObject2](Matrix4 &matrix, SkeletonIndex boneIndex) -> bool + { + if (!parentObject2) return false; + + CPlayerPreview *ctrl = static_cast(parentObject2); + ctrl->AnimateMatrix(matrix, boneIndex); + return true; + }); + } + } } } } @@ -9796,9 +9816,11 @@ ControlObject *DisplayInspect::OnCreateObject(int type, int idc, ParamEntryPar c } int DisplayInventory::_instances = 0; +static DisplayInventory *GActiveInventoryDisplay = NULL; +static bool GInventorySpaceKeyDown = false; DisplayInventory::DisplayInventory(ControlsContainer *parent, AIBrain *me, EntityAI *source) - : Display(parent), _unit(me), _targetContainer(source) + : Display(parent), _unit(me), _targetContainer(source), _dragRotated(false) { Load("RscDisplayInventory"); @@ -9834,16 +9856,76 @@ DisplayInventory::DisplayInventory(ControlsContainer *parent, AIBrain *me, Entit // OnUnitChanged(); _instances++; + GActiveInventoryDisplay = this; } DisplayInventory::~DisplayInventory() { _instances--; + if (GActiveInventoryDisplay == this) + { + GActiveInventoryDisplay = NULL; + GInventorySpaceKeyDown = false; + } + _dragItem = nullptr; + _swapItem = nullptr; + _dragRotated = false; +} + +bool DisplayInventory::OnKeyDown(int dikCode) +{ + if (dikCode != DIK_SPACE) return Display::OnKeyDown(dikCode); + + InventoryItem *item = _dragItem; + Person *person = _unit ? _unit->GetPerson() : NULL; + if (!item) + { + const float x = 0.5f + GInput.cursorX * 0.5f; + const float y = 0.5f + GInput.cursorY * 0.5f; + const int itemControls[] = {IDC_INVENTORY_HANDS, IDC_INVENTORY_CONTAINER, IDC_INVENTORY_CONTENT}; + for (int i = 0; i < lenof(itemControls) && !item; i++) + { + CItemBase *control = dynamic_cast(GetCtrl(itemControls[i])); + if (control && control->IsInside(x, y)) + { + item = control->GetItemInfo(x, y)._item; + } + } + } + const bool itemInHands = person && item && person->GetItemInHands() == item; + if (_dragItem) + { + if (!itemInHands && _dragItem->Type() && _dragItem->Type()->GetItemWidth() != _dragItem->Type()->GetItemHeight()) + _dragRotated = !_dragRotated; + } + else if (!itemInHands && item && item->Type() && item->GetInventoryWidth() != item->GetInventoryHeight()) + CItemBase::RotateInventoryItem(person, item); + return true; +} + +bool HandleInventorySpaceKey() +{ + if (GActiveInventoryDisplay == NULL || !DisplayInventory::IsOpened()) return false; + if (!GInventorySpaceKeyDown) + { + GInventorySpaceKeyDown = true; + GActiveInventoryDisplay->OnKeyDown(DIK_SPACE); + } + return true; +} + +void ReleaseInventorySpaceKey() +{ + GInventorySpaceKeyDown = false; } Control *DisplayInventory::OnCreateCtrl(int type, int idc, ParamEntryPar cls) { + // Ignore the legacy hands-drop button and its red background control. + // Dropping the hands item is handled by inventory drag-and-drop instead. + if (idc == 198 || stricmp(cls.GetName(), "ButtonBackground2") == 0) return NULL; + Control *ctrl = Display::OnCreateCtrl(type, idc, cls); switch (idc) { @@ -10029,15 +10111,20 @@ void DisplayInventory::OnDrag(IControl *ctrl) _dragItem = nullptr; _swapItem = nullptr; + _dragRotated = false; CItemBase *src = dynamic_cast(ctrl); if (src) { // object to be dragged DragItemInfo info = src->GetDragItemInfo(); - if (info._item && CanRemoveItem(info._item)) + Person *person = _unit ? _unit->GetPerson() : NULL; + const bool isHandsItem = src->IDC() == IDC_INVENTORY_HANDS && person && + person->GetItemInHands() == info._item; + if (info._item && (CanRemoveItem(info._item) || isHandsItem)) { _dragItem = info._item; + _dragRotated = info._item->IsInventoryRotated(); //_dragOffsetX = info._offsetX; //_dragOffsetY = info._offsetY; // always drag the top left corner @@ -10127,6 +10214,26 @@ bool SwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) return true; } +class InventoryRotationPreviewScope +{ +private: + InventoryItem *_item; + bool _original; + Entity *_originalParent; +public: + InventoryRotationPreviewScope(InventoryItem *item, bool rotated) + : _item(item), _original(item ? item->IsInventoryRotated() : false), + _originalParent(item ? item->GetHierarchyParent() : NULL) + { + if (_item) _item->SetInventoryRotated(rotated); + } + ~InventoryRotationPreviewScope() + { + if (_item && _item->GetHierarchyParent() == _originalParent) + _item->SetInventoryRotated(_original); + } +}; + unsigned char DisplayInventory::OnDragging(IControl *dragCtrl, IControl *dropCtrl, float x, float y) { _swapItem = nullptr; // set it when swapping @@ -10138,8 +10245,16 @@ unsigned char DisplayInventory::OnDragging(IControl *dragCtrl, IControl *dropCt CItemBase *dst = dynamic_cast(dropCtrl); if (!src) return DANone; + InventoryRotationPreviewScope rotationPreview(item, _dragRotated); + Person *person = _unit ? _unit->GetPerson() : NULL; - bool canRemove = !person || person->GetItemInHands() != item; // item in hands cannot be removed + const bool handsToVicinity = src->IDC() == IDC_INVENTORY_HANDS && + dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTAINER; + const bool handsToInventory = src->IDC() == IDC_INVENTORY_HANDS && + ((dst && dst->IDC() == IDC_INVENTORY_CONTENT) || + (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER)); + const bool handsToGround = src->IDC() == IDC_INVENTORY_HANDS && dropCtrl == NULL; + bool canRemove = !person || person->GetItemInHands() != item || handsToInventory || handsToVicinity || handsToGround; int srcShortcut = src->GetShortcutIndex(); @@ -10276,8 +10391,16 @@ bool DisplayInventory::OnDrop(IControl *dragCtrl, IControl *dropCtrl, float x, f CItemBase *dst = dynamic_cast(dropCtrl); if (!src || !src->IsContained(item)) return false; // check if item still present in the source + InventoryRotationPreviewScope rotationPreview(item, _dragRotated); + Person *person = _unit ? _unit->GetPerson() : NULL; - bool canRemove = !person || person->GetItemInHands() != item; // item in hands cannot be removed + const bool handsToVicinity = src->IDC() == IDC_INVENTORY_HANDS && + dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTAINER; + const bool handsToInventory = src->IDC() == IDC_INVENTORY_HANDS && + ((dst && dst->IDC() == IDC_INVENTORY_CONTENT) || + (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER)); + const bool handsToGround = src->IDC() == IDC_INVENTORY_HANDS && dropCtrl == NULL; + bool canRemove = !person || person->GetItemInHands() != item || handsToInventory || handsToVicinity || handsToGround; int srcShortcut = src->GetShortcutIndex(); @@ -10323,7 +10446,7 @@ bool DisplayInventory::OnDrop(IControl *dragCtrl, IControl *dropCtrl, float x, f if (canAddOwnedItem) { if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForMoveItem(info._item, -1, item); // ask server to execute the action + GetNetworkManager().AskForMoveItem(info._item, -1, item, item->IsInventoryRotated()); // ask server to execute the action else { // remove from the old owner @@ -10453,8 +10576,8 @@ void DisplayInventory::DrawDragInfo(float x, float y, unsigned char enabled, Ref float dragX = x - _dragOffsetX; float dragY = y - _dragOffsetY; - float dragW = type->GetItemWidth() * _dragGridW; - float dragH = type->GetItemHeight() * _dragGridH; + float dragW = (_dragRotated ? type->GetItemHeight() : type->GetItemWidth()) * _dragGridW; + float dragH = (_dragRotated ? type->GetItemWidth() : type->GetItemHeight()) * _dragGridH; PackedColor dragColor; switch (enabled) @@ -10610,7 +10733,7 @@ void DisplayInventory::MenuItemAddItem::Invoke(AIBrain *unit) if (!_item2->CanAddOwnedItem(_item1)) return; if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForMoveItem(_item2, -1, _item1); // ask server to execute the action + GetNetworkManager().AskForMoveItem(_item2, -1, _item1, _item1->IsInventoryRotated()); // ask server to execute the action else { // remove from the old owner diff --git a/lib/UI/uiMap.hpp b/lib/UI/uiMap.hpp index 79f13d6d..2a104cb6 100644 --- a/lib/UI/uiMap.hpp +++ b/lib/UI/uiMap.hpp @@ -189,6 +189,7 @@ class CItemBase : public ControlObject static void SetItemShortcut(int index, const InventoryItem *item); static void DropItem(Person *owner, InventoryItem *item); static void MoveItem(EntityAI *target, int index, InventoryItem *item); + static void RotateInventoryItem(Person *person, InventoryItem *item); static void TakeItemToHands(Person *person, InventoryItem *item); // test if MoveItem will succeed diff --git a/lib/d3d9/txtD3D9.cpp b/lib/d3d9/txtD3D9.cpp index b911637a..cbe279b8 100644 --- a/lib/d3d9/txtD3D9.cpp +++ b/lib/d3d9/txtD3D9.cpp @@ -1459,7 +1459,9 @@ int TextureD3D9::Init(const char *name, bool caseSensitive) ITextureSourceFactory *factory = SelectTextureSourceFactory(name); if (!factory || !factory->Check(name)) { - ErrorMessage(EMMissingData, "Cannot load texture %s.",(const char *)GetName()); + RptF("MissingResource category=texture path=%s", (const char *)GetName()); + RptF("MissingResource category=texture path=%s", (const char *)GetName()); + ErrorMessage(EMMissingData, "Cannot load texture %s.",(const char *)GetName()); _nMipmaps=0; _levelLoaded = _levelActive = _smallLevel = _largestUsed = _nMipmaps; return -1; diff --git a/lib/gameStateExt.cpp b/lib/gameStateExt.cpp index 2836827e..e37139dd 100644 --- a/lib/gameStateExt.cpp +++ b/lib/gameStateExt.cpp @@ -18241,6 +18241,14 @@ int DBGetItemCount( void ) //----------------------------------------------------------------------------- GameValue DBLoadHost( const GameState *state ) { + // The dedicated server package ships a local persistence service. Keep the + // server's character/world requests on loopback instead of the retired BI + // Hive endpoint; clients still use the host configured by the mission. +#if defined(_SERVER) + ServletCharacter = "http://127.0.0.1:28100/lud0/"; + ServletWorld = "http://127.0.0.1:28100/world/"; + RptF( "DBLoadHost local persistence: %s", ServletCharacter.Data() ); +#else const char s_sCONFIGSERVER[] = {"CfgServerHost"}; RString locName = "adress"; @@ -18267,6 +18275,7 @@ GameValue DBLoadHost( const GameState *state ) }; /**/ RptF( "DBLoadHost host: %s", ServletCharacter.Data() ); +#endif return NOTHING; } diff --git a/lib/helicopter.cpp b/lib/helicopter.cpp index 3b5eb845..81744ed6 100644 --- a/lib/helicopter.cpp +++ b/lib/helicopter.cpp @@ -2063,8 +2063,11 @@ void HelicopterAuto::EngineOn() } void HelicopterAuto::EngineOff() { - //base::EngineOff(); - //_rotorSpeedWanted=0; + // Explicit engine stop (SQF "engineOn false", user action or damage). + // Transport::EngineOff only toggles the flag; the rotor has to be told to + // spin down as well, otherwise the helicopter stays airborne. + _rotorSpeedWanted=0; + base::EngineOff(); } void HelicopterAuto::EngineOffAction() { @@ -4094,6 +4097,9 @@ void HelicopterAuto::KeyboardPilot(AIBrain *unit, float deltaT ) // reset the older input - input methods are not compatible, only one must be used at any given time _pilotVSpeedHelper = _analogueThrottleTime<=_thrustHelperTime; + // Q (collective raise) starts the engine. EngineOn() latches + // _rotorSpeedWanted = 1, so after the key is released the engine keeps + // running; holding Q only controls the climb and Z controls the descent. if (forward>0 || throttleDirect>0) { #if _HELISIM_ROTORLIB @@ -4102,6 +4108,9 @@ void HelicopterAuto::KeyboardPilot(AIBrain *unit, float deltaT ) if (!EngineIsOn()) EngineOn(); #endif } + // Keep transport engine state (sound/HUD/SQF isEngineOn) in sync with the + // latched rotor. Only an explicit engine-off action clears the latch. + if (EngineIsOn() && _engineOff) Transport::EngineOn(); if (!_pilotVSpeedHelper) diff --git a/lib/lib.vcxproj b/lib/lib.vcxproj index 2e96c9dd..c08b03d9 100644 --- a/lib/lib.vcxproj +++ b/lib/lib.vcxproj @@ -82,7 +82,7 @@ Size true $(SolutionDir)extern\Botan\build\include;$(SolutionDir);$(SolutionDir)PhysicalLibs\RigidBody\ODE;$(SolutionDir)extern;$(WindowsSdkDir)Include\$(WindowsTargetPlatformVersion)\ucrt;$(SolutionDir)extern\dxsdk\include;%(AdditionalIncludeDirectories);$(SolutionDir)extern\SimulWeather;$(SolutionDir)extern\bullet2.76\src;$(SolutionDir)Enfusion\include - _ENABLE_PHYSICS=1;_RELEASE=1;NDEBUG;WIN32;_WINDOWS;_SUPER_RELEASE=1;_ENABLE_PBO_PROTECTION=1;DAYZ_PRIVATE_SERVER=1;%(PreprocessorDefinitions) + _ENABLE_PHYSICS=1;_RELEASE=1;NDEBUG;WIN32;_WINDOWS;_SUPER_RELEASE=1;_ENABLE_PBO_PROTECTION=1;%(PreprocessorDefinitions) true false MultiThreaded @@ -109,12 +109,12 @@ /LTCG %(AdditionalOptions) - d3d9.lib;d3dx9.lib;shcore.lib;Delayimp.lib;ddraw.lib;Iphlpapi.lib;libvorbisfile_static.lib;libvorbis_static.lib;libogg.lib;winmm.lib;dxguid.lib;version.lib;rsa_x64.lib;libspeexMt.lib;libspeexdspMt.lib;libbulletcollision.lib;libbulletdynamics.lib;libbulletmath.lib;$(VCToolsInstallDir)lib\x64\legacy_stdio_definitions.lib;%(AdditionalDependencies);libtheora_static.lib + d3d9.lib;d3dx9.lib;shcore.lib;Delayimp.lib;ddraw.lib;Iphlpapi.lib;libvorbisfile_static.lib;libvorbis_static.lib;libogg.lib;winmm.lib;dxguid.lib;version.lib;rsa_x64.lib;libspeexMt.lib;libspeexdspMt.lib;libbulletcollision.lib;libbulletdynamics.lib;libbulletmath.lib;$(VCToolsInstallDir)lib\x64\legacy_stdio_definitions.lib;%(AdditionalDependencies);libtheora_static.lib;steam_api64.lib $(OutDir)$(TargetName)$(TargetExt) true - $(SolutionDir)extern\DXSDK\Lib\x64;$(WindowsSdkDir)Lib\$(WindowsTargetPlatformVersion)\um\x64;$(SolutionDir)build\port-x64\RSA;$(SolutionDir)build\port-x64\audio;$(SolutionDir)build\port-x64\BulletCollision\;$(SolutionDir)build\port-x64\BulletDynamics\;$(SolutionDir)build\port-x64\LinearMath\;$(SolutionDir)extern;%(AdditionalLibraryDirectories);$(SolutionDir)build\port-x64\SimulWeather + $(SolutionDir)extern\DXSDK\Lib\x64;$(WindowsSdkDir)Lib\$(WindowsTargetPlatformVersion)\um\x64;$(SolutionDir)build\port-x64\RSA;$(SolutionDir)build\port-x64\audio;$(SolutionDir)build\port-x64\BulletCollision\;$(SolutionDir)build\port-x64\BulletDynamics\;$(SolutionDir)build\port-x64\LinearMath\;$(SolutionDir)build\port-x64\bin;$(SolutionDir)extern;%(AdditionalLibraryDirectories);$(SolutionDir)build\port-x64\SimulWeather libc.lib;wsock32.lib;%(IgnoreSpecificDefaultLibraries) - %(DelayLoadDLLs) + steam_api64.dll;%(DelayLoadDLLs) true true $(TargetDir)$(TargetName).map @@ -131,8 +131,8 @@ true - - + Copy Steamworks test runtime (AppID 480) + copy /Y "$(SolutionDir)extern\Steamworks\bin\steam_api64.dll" "$(OutDir)steam_api64_real.dll" && copy /Y "$(SolutionDir)extern\Steamworks\bin\steam_api64_compat.dll" "$(OutDir)steam_api64.dll" && copy /Y "$(SolutionDir)extern\Steamworks\steam_appid.test.txt" "$(OutDir)steam_appid.txt" @@ -154,7 +154,7 @@ Size true $(SolutionDir)extern\Botan\build\include;$(SolutionDir);$(SolutionDir)PhysicalLibs\RigidBody\ODE;$(SolutionDir)extern;$(WindowsSdkDir)Include\$(WindowsTargetPlatformVersion)\ucrt;$(SolutionDir)extern\dxsdk\include;%(AdditionalIncludeDirectories);$(SolutionDir)extern\SimulWeather;$(SolutionDir)extern\bullet2.76\src;$(SolutionDir)Enfusion\include - _ENABLE_PHYSICS=1;_RELEASE=1;NDEBUG;WIN32;_WINDOWS;_SUPER_RELEASE=1;_SERVER=1;_ENABLE_PBO_PROTECTION=1;DAYZ_PRIVATE_SERVER=1;%(PreprocessorDefinitions) + _ENABLE_PHYSICS=1;_RELEASE=1;NDEBUG;WIN32;_WINDOWS;_SUPER_RELEASE=1;_SERVER=1;_ENABLE_STEAM=1;_ENABLE_PBO_PROTECTION=1;%(PreprocessorDefinitions) true false MultiThreaded @@ -181,12 +181,12 @@ /LTCG %(AdditionalOptions) - d3d9.lib;d3dx9.lib;shcore.lib;Delayimp.lib;ddraw.lib;Iphlpapi.lib;libvorbisfile_static.lib;libvorbis_static.lib;libogg.lib;winmm.lib;dxguid.lib;version.lib;rsa_x64.lib;libspeexMt.lib;libspeexdspMt.lib;libbulletcollision.lib;libbulletdynamics.lib;libbulletmath.lib;$(VCToolsInstallDir)lib\x64\legacy_stdio_definitions.lib;%(AdditionalDependencies);libtheora_static.lib + d3d9.lib;d3dx9.lib;shcore.lib;Delayimp.lib;ddraw.lib;Iphlpapi.lib;libvorbisfile_static.lib;libvorbis_static.lib;libogg.lib;winmm.lib;dxguid.lib;version.lib;rsa_x64.lib;libspeexMt.lib;libspeexdspMt.lib;libbulletcollision.lib;libbulletdynamics.lib;libbulletmath.lib;$(VCToolsInstallDir)lib\x64\legacy_stdio_definitions.lib;%(AdditionalDependencies);libtheora_static.lib;steam_api64.lib $(OutDir)$(TargetName)$(TargetExt) true - $(SolutionDir)extern\DXSDK\Lib\x64;$(WindowsSdkDir)Lib\$(WindowsTargetPlatformVersion)\um\x64;$(SolutionDir)build\port-x64\RSA;$(SolutionDir)build\port-x64\audio;$(SolutionDir)build\port-x64\BulletCollision\;$(SolutionDir)build\port-x64\BulletDynamics\;$(SolutionDir)build\port-x64\LinearMath\;$(SolutionDir)extern;%(AdditionalLibraryDirectories) + $(SolutionDir)extern\DXSDK\Lib\x64;$(WindowsSdkDir)Lib\$(WindowsTargetPlatformVersion)\um\x64;$(SolutionDir)build\port-x64\RSA;$(SolutionDir)build\port-x64\audio;$(SolutionDir)build\port-x64\BulletCollision\;$(SolutionDir)build\port-x64\BulletDynamics\;$(SolutionDir)build\port-x64\LinearMath\;$(SolutionDir)build\port-x64\bin;$(SolutionDir)extern;%(AdditionalLibraryDirectories) libc.lib;wsock32.lib;%(IgnoreSpecificDefaultLibraries) - %(DelayLoadDLLs) + steam_api64.dll;%(DelayLoadDLLs) true true $(TargetDir)$(TargetName).map @@ -203,8 +203,8 @@ true - - + Copy Steamworks server runtime (AppID 480) + copy /Y "$(SolutionDir)extern\Steamworks\bin\steam_api64.dll" "$(OutDir)steam_api64_real.dll" && copy /Y "$(SolutionDir)extern\Steamworks\bin\steam_api64_compat.dll" "$(OutDir)steam_api64.dll" && copy /Y "$(SolutionDir)extern\Steamworks\steam_appid.test.txt" "$(OutDir)steam_appid.txt" @@ -1927,4 +1927,4 @@ - \ No newline at end of file + diff --git a/lib/main.cpp b/lib/main.cpp index 128ff288..2ff34ec7 100644 --- a/lib/main.cpp +++ b/lib/main.cpp @@ -91,6 +91,20 @@ Basic win32 framework, application init and message handling. #include "jvmInit.hpp" +#if _ENABLE_STEAM && defined(_WIN64) +#include +#include +static bool GSteamInitialized = false; +static bool GSteamGameServerInitialized = false; +static bool GSteamGameServerAdvertised = false; +static bool GSteamGameServerLoginWarning = false; +static bool GSteamServerOfficial = false; +static DWORD GSteamGameServerNextUpdate = 0; +static DWORD GSteamGameServerLoginStarted = 0; +static int GSteamGameServerMaxPlayers = 0; +static RString GSteamGameServerName; +#endif + #include "system/enf_timer.h" #if !defined(_WIN64) #include "d3d9/engdd9.hpp" @@ -4130,6 +4144,15 @@ static void SingleArgument( const char *beg, const char *end ) { if (SAFinish.Process(beg, end)) return; if( end==beg ) return; +#if _ENABLE_STEAM && defined(_WIN64) + static const char officialFlag[]="official="; + // Accept both official=1 and -official=1 in the server launch command. + if (IsOptionWArgs(beg,officialFlag)) + { + GSteamServerOfficial = atoi(beg + strlen(officialFlag)) != 0; + return; + } +#endif if( *beg=='-' || *beg=='/' || *beg=='+' ) { beg++; @@ -4410,6 +4433,12 @@ static void SingleArgument( const char *beg, const char *end ) NetworkPort = atoi(beg + strlen(port)); ServerPort = NetworkPort; } +#if _ENABLE_STEAM && defined(_WIN64) + else if( IsOptionWArgs(beg,officialFlag) ) + { + GSteamServerOfficial = atoi(beg + strlen(officialFlag)) != 0; + } +#endif else if ( IsOptionWArgs(beg,ip) ) { bindIPAddress = inet_addr(beg + strlen(ip)); @@ -5927,6 +5956,7 @@ bool SynchronousSignatureChecker::Process() #endif #if !_SERVER + bool AppIdle() { @@ -6099,6 +6129,9 @@ bool AppIdle() //if( ( focused || ForceRender && LandEditor ) && CanRender ) +#if _ENABLE_STEAM && defined(_WIN64) + if (GSteamInitialized) SteamAPI_RunCallbacks(); +#endif ProcessPipeCommands(); if( CanRender ) { @@ -6634,6 +6667,21 @@ void DDTerm() GlobPreloadedTexturesClear(); DestroyEngine(); +#if _ENABLE_STEAM && defined(_WIN64) + if (GSteamGameServerInitialized) + { + ISteamGameServer *steamServer = SteamGameServer(); + if (steamServer && GSteamGameServerAdvertised) steamServer->SetAdvertiseServerActive(false); + SteamGameServer_Shutdown(); + GSteamGameServerInitialized = false; + GSteamGameServerAdvertised = false; + } + if (GSteamInitialized) + { + SteamAPI_Shutdown(); + GSteamInitialized = false; + } +#endif #if _GAMES_FOR_WINDOWS XOnlineCleanup(); XLiveUnInitialize(); @@ -9364,6 +9412,41 @@ static void DedicatedServerLoop() */ #endif AppServerLoop(); +#if _ENABLE_STEAM && defined(_WIN64) + if (GSteamGameServerInitialized) + { + SteamGameServer_RunCallbacks(); + ISteamGameServer *steamServer = SteamGameServer(); + if (steamServer && steamServer->BLoggedOn()) + { + if (!GSteamGameServerAdvertised) + { + steamServer->SetAdvertiseServerActive(true); + GSteamGameServerAdvertised = true; + LogF("Steamworks dedicated server is listed (AppID 480, official=%d)", GSteamServerOfficial ? 1 : 0); + ConsoleF("Connected to Steam (AppID 480)"); + ConsoleF("Steam policy status (VAC secure: %s)", steamServer->BSecure() ? "yes" : "no"); + } + DWORD now = GlobalTickCount(); + if (now >= GSteamGameServerNextUpdate) + { + AutoArray steamListedPlayers; + GetNetworkManager().GetPlayers(steamListedPlayers); + steamServer->SetServerName(cc_cast(GSteamGameServerName)); + steamServer->SetMaxPlayerCount(GSteamGameServerMaxPlayers); + steamServer->SetBotPlayerCount(steamListedPlayers.Size()); + steamServer->SetGameTags(GSteamServerOfficial ? "sourcedayz,dayz,official=1" : "sourcedayz,dayz"); + GSteamGameServerNextUpdate = now + 5000; + } + } + else if (!GSteamGameServerLoginWarning && GSteamGameServerLoginStarted != 0 && + GlobalTickCount() - GSteamGameServerLoginStarted > 30000) + { + GSteamGameServerLoginWarning = true; + ConsoleF("Steam Game Server has not confirmed login after 30 seconds; check Steamworks/RPT logs"); + } + } +#endif I_AM_ALIVE(); PROFILE_SCOPE_EX(MSGLP, *) @@ -10352,6 +10435,95 @@ static bool InitGamesForWindows(RString language) #endif +#if _ENABLE_STEAM && defined(_WIN64) +extern "C" void __cdecl SteamAPIDebugTextHook(int severity, const char *text) +{ + (void)severity; + if (text) LogF("STEAMWORKS: %s", text); +} + +static bool InitSteam() +{ + if (GSteamInitialized) return true; + + // Spacewar (AppID 480) is used only as the local Steamworks test identity. + // No Steam purchase or ownership checks are enabled by this configuration. + _putenv("SteamAppId=480"); + + // Steamworks provides the test identity; the game's existing online multiplayer + // transport remains separate from this API initialization. + HMODULE steamApi = LoadLibraryA("steam_api64.dll"); + if (!steamApi) + { + LogF("Steamworks test API unavailable (steam_api64.dll, error %lu); native multiplayer transport is unchanged", GetLastError()); + return false; + } + FreeLibrary(steamApi); + + if (!SteamAPI_Init()) + { + LogF("Steamworks test API initialization failed; native multiplayer transport is unchanged"); + return false; + } + + GSteamInitialized = true; + if (SteamUtils()) SteamUtils()->SetWarningMessageHook(&SteamAPIDebugTextHook); + LogF("Steamworks test API initialized (AppID 480)"); + return true; +} + +bool IsSteamClientInitialized() +{ + return GSteamInitialized; +} + +bool SteamOnlineServerStart(int gamePort, int steamPort, int queryPort, const char *serverName, int maxPlayers, bool passwordProtected) +{ + if (GSteamGameServerInitialized) return true; + + _putenv("SteamAppId=480"); + ConsoleF("Connecting dedicated server to Steam (AppID 480)..."); + if (!SteamGameServer_Init(0, (uint16)steamPort, (uint16)gamePort, (uint16)queryPort, eServerModeAuthentication, APP_VERSION_TEXT)) + { + LogF("Steamworks game-server initialization failed; native multiplayer remains available through direct IP"); + ConsoleF("Steam Game Server initialization failed (AppID 480); see the server RPT for details"); + return false; + } + + ISteamGameServer *steamServer = SteamGameServer(); + if (!steamServer) + { + SteamGameServer_Shutdown(); + LogF("Steamworks game-server interface is unavailable; native multiplayer remains available through direct IP"); + ConsoleF("Steam Game Server interface is unavailable"); + return false; + } + + GSteamGameServerInitialized = true; + GSteamGameServerName = serverName && serverName[0] ? serverName : "SourceDayZ Community Server"; + GSteamGameServerMaxPlayers = maxPlayers > 0 ? maxPlayers : MAX_PLAYERS_DS; + GSteamGameServerNextUpdate = 0; + GSteamGameServerLoginStarted = GlobalTickCount(); + GSteamGameServerLoginWarning = false; + GSteamGameServerAdvertised = false; + + steamServer->SetProduct("spacewar"); + steamServer->SetGameDescription("SourceDayZ multiplayer test"); + steamServer->SetModDir("sourcedayz"); + steamServer->SetDedicatedServer(true); + steamServer->SetServerName(cc_cast(GSteamGameServerName)); + steamServer->SetMaxPlayerCount(GSteamGameServerMaxPlayers); + steamServer->SetBotPlayerCount(0); + steamServer->SetPasswordProtected(passwordProtected); + steamServer->SetGameTags(GSteamServerOfficial ? "sourcedayz,dayz,official=1" : "sourcedayz,dayz"); + steamServer->LogOnAnonymous(); + LogF("Steamworks game-server login started (AppID 480, game port %d, query port %d)", gamePort, queryPort); + ConsoleF("SourceDayZ server classification: official=%d", GSteamServerOfficial ? 1 : 0); + ConsoleF("Steam anonymous login requested (AppID 480)"); + return true; +} +#endif + /// scan a subclass of ArmA2.par file for arguments template void ScanArguments(ParamEntryPar args, Function func) @@ -11983,6 +12155,11 @@ it sometimes caused false warnings and premature server termination. // handle -showScriptErrors option GGameState.ShowScriptErrors(ShowScriptErrors); +#if _ENABLE_STEAM && defined(_WIN64) + if (!GenerateShaders && !IsDedicatedServer() && !InitSteam()) + LogF("Steamworks not available; existing online multiplayer networking remains unchanged"); +#endif + // after processing -cpuCount GJobManager.Init(); @@ -12270,11 +12447,15 @@ it sometimes caused false warnings and premature server termination. QFBank &bank = banks[i]; DSSignature signature; DSHash hash; - if ( - !DataSignatures::FindSignature(signature, bank.GetOpenName(), keys, acceptedKeysCount) || - !bank.GetHash(hash._content, signature.Version(), 0) || - !DataSignatures::VerifySignature(hash, signature)) - { + const bool signatureFound = DataSignatures::FindSignature(signature, bank.GetOpenName(), keys, acceptedKeysCount); + const bool bankHashRead = signatureFound && bank.GetHash(hash._content, signature.Version(), 0); + const bool signatureValid = bankHashRead && DataSignatures::VerifySignature(hash, signature); + if (!signatureValid) + { + RptF("PboSignatureRejected file=%s signatureFound=%d bankHashRead=%d trustedKey=%s keyVersion=%d", + cc_cast(bank.GetOpenName()), signatureFound, bankHashRead, + signatureFound ? cc_cast(signature._key._name) : "", + signatureFound ? signature.Version() : 0); #if SIGNATURES_TEST_ONLY LogF("Warning: Signature of %s is wrong.", cc_cast(bank.GetOpenName())); #else @@ -12288,6 +12469,11 @@ it sometimes caused false warnings and premature server termination. ErrorMessage(LocalizeString(IDS_HASH_WRONG)); #endif } + else if (!stricmp(signature._key._name, "SourceDayZShoulder2")) + { + RptF("PboSignatureAccepted file=%s key=%s version=%d", + cc_cast(bank.GetOpenName()), cc_cast(signature._key._name), signature.Version()); + } } static const char *additionalSignedFiles[] = ADDITIONAL_SIGNED_FILES; for (int i=0; i buf; vsprintf( buf, format, argptr ); +#if defined(_WIN32) + // Keep the caller chain in the RPT so generic fatal messages can be mapped + // back to the exact source location with this build's PDB. + void *errorStack[16]; + typedef USHORT (WINAPI *CaptureStackBackTraceFn)(ULONG, ULONG, PVOID *, PULONG); + HMODULE kernelModule = GetModuleHandleA("kernel32.dll"); + CaptureStackBackTraceFn captureStack = kernelModule ? (CaptureStackBackTraceFn)GetProcAddress(kernelModule, "RtlCaptureStackBackTrace") : NULL; + if (!captureStack && kernelModule) + captureStack = (CaptureStackBackTraceFn)GetProcAddress(kernelModule, "CaptureStackBackTrace"); + USHORT errorStackSize = captureStack ? captureStack(1, 16, errorStack, NULL) : 0; + for (USHORT errorStackIndex = 0; errorStackIndex < errorStackSize; errorStackIndex++) + ::ErrF("ErrorMessageStack[%u]=%p", (unsigned)errorStackIndex, errorStack[errorStackIndex]); +#endif + // kill direct draw #ifdef _WIN32 GDebugExceptionTrap.SaveContext("ErrorMessage"); diff --git a/lib/person.cpp b/lib/person.cpp index 59130353..daa917ae 100644 --- a/lib/person.cpp +++ b/lib/person.cpp @@ -625,6 +625,13 @@ float Person::CalculateError(NetworkMessageContextWithError &ctx) error += base::CalculateError(ctx); break; } + + // The player's own position drives remote AI (including zombie attacks). + // The generic time-only position error can otherwise leave the server with + // a stale player position for several seconds while the player is moving. + if (ctx.GetClass() == NMCUpdatePosition && GWorld && this == GWorld->GetRealPlayer()) + error *= 20.0f; + return error; } @@ -994,6 +1001,8 @@ bool Person::AddOwnedItem(InventoryItem *item) if (type) { int slot = type->GetInventorySlot(); + if (slot == ISShoulder && _inventorySlots[ISShoulder] && !_inventorySlots[ISShoulder2]) + slot = ISShoulder2; if (slot >= 0 && slot < NInventorySlotId && _inventorySlots[slot] == NULL) { // move in world @@ -1014,6 +1023,8 @@ bool Person::CanAddOwnedItem(const InventoryItem *item) const if (type) { int slot = type->GetInventorySlot(); + if (slot == ISShoulder && _inventorySlots[ISShoulder] && !_inventorySlots[ISShoulder2]) + slot = ISShoulder2; return slot >= 0 && slot < NInventorySlotId && _inventorySlots[slot] == NULL; } @@ -1028,6 +1039,8 @@ int Person::CanReplaceOwnedItem(const InventoryItem *oldItem, const InventoryIte if (type) { int slot = type->GetInventorySlot(); + if (slot == ISShoulder && _inventorySlots[ISShoulder2] == oldItem) + return ISShoulder2; if (slot >= 0 && slot < NInventorySlotId && _inventorySlots[slot] == oldItem) return slot; } @@ -1056,7 +1069,8 @@ bool Person::CanMoveItem(int index, const InventoryItem *item) const // item fits into this slot const InventoryItemType *type = item->Type(); - return type && type->GetInventorySlot() == index; + return type && (type->GetInventorySlot() == index || + (index == ISShoulder2 && type->GetInventorySlot() == ISShoulder)); } else { @@ -1224,6 +1238,7 @@ bool Person::CanAddItem(const InventoryItem *item) const { int slot = type->GetInventorySlot(); if (slot >= 0 && slot < NInventorySlotId && _inventorySlots[slot] == NULL) return true; + if (slot == ISShoulder && _inventorySlots[ISShoulder2] == NULL) return true; } // then check owned containers @@ -1247,6 +1262,8 @@ bool Person::AddItem(InventoryItem *item) if (type) { int slot = type->GetInventorySlot(); + if (slot == ISShoulder && _inventorySlots[ISShoulder] && !_inventorySlots[ISShoulder2]) + slot = ISShoulder2; if (slot >= 0 && slot < NInventorySlotId && _inventorySlots[slot] == NULL) { // move in world @@ -1721,6 +1738,12 @@ void Person::SimulateWeaponInputs(InputInterface *input, AIBrain *unit, const Tu const InventoryItemType *type = GetItemShortcut(index); if (type) { + InventoryItem *bound = _shortcutItems[index]; + if (bound && FindItem(bound) && bound->Type() == type) + { + bound->UseFromInventory(this); + continue; + } // find item of this type ForEachItem([this, type](InventoryItem *item) -> bool { @@ -1750,6 +1773,7 @@ const InventoryItemType *Person::GetItemShortcut(int index) const void Person::SetItemShortcut(int index, const InventoryItemType *itemType) { void ShowShortcuts(); + if (index >= 0 && index < NItemShortcuts) _shortcutItems[index] = NULL; if (index<0) { @@ -1787,6 +1811,14 @@ void Person::SetItemShortcut(int index, const InventoryItemType *itemType) } } +void Person::SetItemShortcutInstance(int index, InventoryItem *item) +{ + if (index < 0 || index >= NItemShortcuts) return; + if (item && !FindItem(item)) return; + SetItemShortcut(index, item ? item->Type() : NULL); + _shortcutItems[index] = item; +} + int Person::FindItemShortcutIndex(const InventoryItemType *itemType) { for( int i = 0; i < NItemShortcuts; ++i ) diff --git a/lib/person.hpp b/lib/person.hpp index e85a9c7b..147780c0 100644 --- a/lib/person.hpp +++ b/lib/person.hpp @@ -147,6 +147,7 @@ class Person: public EntityAIFull, public IWeaponsHolder, public CountInstances< // shortcuts to inventory items Ref _itemShortcuts[NItemShortcuts]; + OLinkPermO(InventoryItem) _shortcutItems[NItemShortcuts]; /// currently using item OLinkPermO(InventoryItem) _itemInHands; @@ -561,6 +562,7 @@ class Person: public EntityAIFull, public IWeaponsHolder, public CountInstances< /// Shortcuts to inventory items const InventoryItemType *GetItemShortcut(int index) const; void SetItemShortcut(int index, const InventoryItemType *itemType); + void SetItemShortcutInstance(int index, InventoryItem *item); int FindItemShortcutIndex(const InventoryItemType *itemType); InventoryItem *GetItemShortcutObject(int index) const; void RemoveItemShortcut(InventoryItem *item); diff --git a/lib/proxyWeapon.hpp b/lib/proxyWeapon.hpp index a89b5b29..dca43c54 100644 --- a/lib/proxyWeapon.hpp +++ b/lib/proxyWeapon.hpp @@ -51,6 +51,7 @@ class ProxySubpart : public Vehicle XX(type, prefix, Gloves) \ XX(type, prefix, Back) \ XX(type, prefix, Hands) /* temporary slot for the item in hands not fitting into inventory */ \ + XX(type, prefix, Shoulder2) /* second large weapon carried across the back */ \ #ifndef DECL_ENUM_INVENTORY_SLOT_ID #define DECL_ENUM_INVENTORY_SLOT_ID diff --git a/lib/retailConfig.h b/lib/retailConfig.h index 0e7b7c6b..8d340da0 100644 --- a/lib/retailConfig.h +++ b/lib/retailConfig.h @@ -1,3 +1,8 @@ +// Steam AppID 480 identity/authentication for the multiplayer test build. +// Steam account authentication is enabled; paid-app ownership is not required. +#define _ENABLE_STEAM 1 +#define _ENABLE_STEAM_IDENTITY 1 + // Configuration parameters for Armed Assault super release #define _VERIFY_KEY 0 #define _VERIFY_CLIENT_KEY 0 // server is checking the CD key of clients on GameSpy @@ -185,7 +190,7 @@ enum DistributionId // ------------------------------------------------------------- // Testing of initial signatures test -#define _ACCEPT_ONLY_SIGNED_DATA 1 +#define _ACCEPT_ONLY_SIGNED_DATA 0 // Accepted public keys #define ACCEPTED_KEYS { \ { \ @@ -201,6 +206,23 @@ enum DistributionId 0xf0, 0xeb, 0x42, 0xaa, 0x6c, 0xd2, 0x4f, 0xd0, 0xb0, 0xc4, 0xf1, 0xa2, 0x24, 0xee, 0x0a, 0x1a, \ 0x42, 0xfc, 0x6e, 0xe2, 0x6f, 0x94, 0x34, 0x1e, 0x96, 0xb9, 0x59, 0x27, 0xac, 0x5d, 0xd5, 0xb3, \ 0x00, 0x8e, 0x69, 0x21, 0xa9, 0x93, 0x68, 0xca} \ + }, \ + { \ + "SourceDayZShoulder2", \ + { \ + 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, \ + 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xe5, 0xf7, 0x4b, 0x88, \ + 0xef, 0xc9, 0x70, 0x1f, 0x7c, 0x20, 0xf9, 0x65, 0x62, 0x63, 0xa3, 0x59, \ + 0xb9, 0x21, 0x92, 0x42, 0x6e, 0x8e, 0x90, 0xff, 0xc5, 0x61, 0xc2, 0xed, \ + 0xb9, 0xef, 0x54, 0x53, 0xf9, 0x4c, 0xf8, 0x45, 0xc5, 0xdd, 0xa1, 0x71, \ + 0xab, 0x9d, 0x26, 0x59, 0xb0, 0x31, 0x37, 0xd8, 0x2b, 0xdb, 0xef, 0x37, \ + 0x86, 0x42, 0x2e, 0x34, 0x2b, 0x96, 0xe3, 0x90, 0x1f, 0x1d, 0x94, 0xb6, \ + 0xc7, 0xdd, 0x42, 0x5a, 0x09, 0x78, 0x38, 0x36, 0x9c, 0x19, 0x60, 0x42, \ + 0x69, 0x27, 0x74, 0x6a, 0xcd, 0x84, 0xdb, 0x6b, 0x6a, 0x2e, 0x61, 0x87, \ + 0x35, 0x61, 0xcc, 0x4f, 0x33, 0x69, 0x46, 0xa0, 0xae, 0xbe, 0xa4, 0xbf, \ + 0xbf, 0x67, 0x04, 0x45, 0xc7, 0x98, 0xc9, 0xeb, 0x7d, 0xdb, 0x56, 0x08, \ + 0x62, 0xce, 0xb2, 0x8f, 0xf4, 0x76, 0xdf, 0x30, 0x23, 0x66, 0x20, 0x0a, \ + 0x6c, 0x21, 0x10, 0xd4} \ } \ } diff --git a/lib/serverConfig.h b/lib/serverConfig.h index 71bd2eeb..0bc3ebca 100644 --- a/lib/serverConfig.h +++ b/lib/serverConfig.h @@ -1,4 +1,6 @@ // Configuration parameters for super release +#define _ENABLE_STEAM 1 +#define _ENABLE_STEAM_IDENTITY 1 #define _VERIFY_KEY 0 #define _VERIFY_CLIENT_KEY 0 // server is checking the CD key of clients on GameSpy #define _VERIFY_BLACKLIST 0 @@ -152,6 +154,23 @@ 0xf0, 0xeb, 0x42, 0xaa, 0x6c, 0xd2, 0x4f, 0xd0, 0xb0, 0xc4, 0xf1, 0xa2, 0x24, 0xee, 0x0a, 0x1a, \ 0x42, 0xfc, 0x6e, 0xe2, 0x6f, 0x94, 0x34, 0x1e, 0x96, 0xb9, 0x59, 0x27, 0xac, 0x5d, 0xd5, 0xb3, \ 0x00, 0x8e, 0x69, 0x21, 0xa9, 0x93, 0x68, 0xca} \ + }, \ + { \ + "SourceDayZShoulder2", \ + { \ + 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, \ + 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xe5, 0xf7, 0x4b, 0x88, \ + 0xef, 0xc9, 0x70, 0x1f, 0x7c, 0x20, 0xf9, 0x65, 0x62, 0x63, 0xa3, 0x59, \ + 0xb9, 0x21, 0x92, 0x42, 0x6e, 0x8e, 0x90, 0xff, 0xc5, 0x61, 0xc2, 0xed, \ + 0xb9, 0xef, 0x54, 0x53, 0xf9, 0x4c, 0xf8, 0x45, 0xc5, 0xdd, 0xa1, 0x71, \ + 0xab, 0x9d, 0x26, 0x59, 0xb0, 0x31, 0x37, 0xd8, 0x2b, 0xdb, 0xef, 0x37, \ + 0x86, 0x42, 0x2e, 0x34, 0x2b, 0x96, 0xe3, 0x90, 0x1f, 0x1d, 0x94, 0xb6, \ + 0xc7, 0xdd, 0x42, 0x5a, 0x09, 0x78, 0x38, 0x36, 0x9c, 0x19, 0x60, 0x42, \ + 0x69, 0x27, 0x74, 0x6a, 0xcd, 0x84, 0xdb, 0x6b, 0x6a, 0x2e, 0x61, 0x87, \ + 0x35, 0x61, 0xcc, 0x4f, 0x33, 0x69, 0x46, 0xa0, 0xae, 0xbe, 0xa4, 0xbf, \ + 0xbf, 0x67, 0x04, 0x45, 0xc7, 0x98, 0xc9, 0xeb, 0x7d, 0xdb, 0x56, 0x08, \ + 0x62, 0xce, 0xb2, 0x8f, 0xf4, 0x76, 0xdf, 0x30, 0x23, 0x66, 0x20, 0x0a, \ + 0x6c, 0x21, 0x10, 0xd4} \ } \ } diff --git a/lib/simul.cpp b/lib/simul.cpp index 70f8d120..8fbd82f3 100644 --- a/lib/simul.cpp +++ b/lib/simul.cpp @@ -469,6 +469,15 @@ void Entity::ApplyRemoteStateAdjustSpeed(float deltaT, VisualState &moveTrans) { if (_remoteState) { + // The locally controlled player predicts its own movement. Applying an + // older server snapshot here runs after CreatePotentialState and replaces + // the freshly computed step with the previous position (walk animation in + // place). Spawn/teleport cuts are applied directly by TransferMsg. + if (GetNetworkManager().IsClient() && GWorld && this == GWorld->GetRealPlayer()) + { + _remoteState.Free(); + return; + } ApplyRemoteState(deltaT,moveTrans); FutureVisualState()._speed = moveTrans._speed; } @@ -5704,6 +5713,7 @@ TMError Entity::TransferMsg(NetworkMessageContext &ctx) { bool isFirstReceived = Glob.time>=_maxPredictionTime; // first, or first after a freeze bool positionValid = false; + bool ignoreLocalPosition = false; TMCHECK(base::TransferMsg(ctx)) PREPARE_TRANSFER(UpdatePositionVehicle) if (ctx.IsSending()) @@ -5729,6 +5739,8 @@ TMError Entity::TransferMsg(NetworkMessageContext &ctx) VisualCut(); } positionValid = (posFlags & SimulatePosValid) != 0; + ignoreLocalPosition = GetNetworkManager().IsClient() && GWorld && + this == GWorld->GetRealPlayer() && !(posFlags & SimulatePosCut); } if (ctx.IsSending()) { @@ -5772,7 +5784,13 @@ TMError Entity::TransferMsg(NetworkMessageContext &ctx) remoteState.orientOffset = M3Zero; #endif - if (positionValid && IsInLandscape()) // positionValid is IsInLandscape() on the sender side + // Read every field above before ignoring an ordinary server snapshot + // for the owner. Returning early would leave the message stream unread. + if (ignoreLocalPosition) + { + _remoteState.Free(); + } + else if (positionValid && IsInLandscape()) // positionValid is IsInLandscape() on the sender side { VisualState &vs = FutureVisualState(); #if _VBS2 diff --git a/lib/soldierOld.cpp b/lib/soldierOld.cpp index b01bd210..7ab63755 100644 --- a/lib/soldierOld.cpp +++ b/lib/soldierOld.cpp @@ -34,6 +34,7 @@ Implementation file for Man and Soldier classes #include #include #include +#include #include "move_actions.hpp" #include "integrity.hpp" @@ -41,6 +42,16 @@ Implementation file for Man and Soldier classes #include #include "gameDirs.hpp" +// Match animation-state fragments without depending on their letter casing. +static bool MoveNameHas(const char *name, const char *part) +{ + if (!name || !part || !*part) return false; + const size_t len = strlen(part); + for (const char *p = name; *p; ++p) + if (_strnicmp(p, part, len) == 0) return true; + return false; +} + #include "dikCodes.h" #include "Network/network.hpp" @@ -1738,6 +1749,7 @@ _vegCollisionTime(TIME_MIN), _metabolismFactor(1.0f), _showPrimaryWeapon(true), _showSecondaryWeapon(true), _showHead(true), + _secondShoulderOffsetLocal(VZero), _secondShoulderOffsetValid(false), _manScale(1), _coverGrassHeight(0.0f), @@ -2979,6 +2991,15 @@ void Man::TakeInHandsAction(InventoryItem *item) { HandleItemInHands(item); + // Hands are an inventory location, not a second reference to a slot item. + // Transfer the item only after the previous hands item has been put away. + if (item && GetInSlot(ISHands) != item) + { + Entity *previousOwner = item->GetHierarchyParent(); + if (previousOwner) previousOwner->RemoveOwnedItem(item); + if (!GetInSlot(ISHands)) PutInSlot(ISHands, item); + } + _itemInHands = item; // TODO: weapon will tell us what action to play @@ -4874,6 +4895,7 @@ bool Man::SimulateAnimations(float &turn, float &moveX, float &moveZ, float delt } } } + DoAssert(fabs(moveX)<100); DoAssert(fabs(moveZ)<100); @@ -6192,6 +6214,17 @@ bool Man::CreatePotentialStateFreeFall(ManVisualState & moveTrans, Vector3& fric moveTrans.SetPosition(FutureVisualState().Position() + diffPos); } + else if (QIsManual() && !_swimming && (!Brain() || !Brain()->GetVehicleIn())) + { + // Free-fall normally preserves momentum but discards locomotion root steps. + // Keep limited horizontal control for the local player so a missing ground + // contact cannot permanently lock movement and yaw after the fall timeout. + Vector3 airStep; + FutureVisualState().DirectionModelToWorld(airStep, Vector3(moveX, 0, moveZ)); + airStep[1] = 0; + airStep *= 0.25f; + moveTrans.SetPosition(moveTrans.Position() + airStep); + } // Friction with air. Vector3Val speed=FutureVisualState().ModelSpeed(); @@ -6417,6 +6450,7 @@ bool Man::CreatePotentialState(ManVisualState & moveTrans, float& turn, float de float moveX,moveZ; bool change = SimulateAnimations(turn,moveX,moveZ,deltaT,prec); + if (_objectContact) change = true; @@ -7518,6 +7552,34 @@ void Man::Simulate( float deltaT, SimulationImportance prec ) return; } + // Local player jump: apply a short upward impulse and play the matching + // animation state for the weapon currently held. + if (this == GWorld->GetRealPlayer() && !_swimming && !IsDead() && Brain() && !Brain()->GetVehicleIn()) + { + RStringB curName = GetMovesType()->GetMoveName(_moves.GetPrimaryMove(FutureVisualState()._moves).id); + const char *moveName = cc_cast(curName); + if (GInput.GetKeyToDo(DIK_SPACE) && _landContact && !_freeFall) + { + FutureVisualState()._speed[1] = 4.6f; + _landContact = false; + _freeFallStartTime = TIME_MAX; + FreeFall(1.2f); + + RStringB jumpMove = "AmovPercMjmpSnonWnonDf"; + if (MoveNameHas(moveName, "Wrfl")) + jumpMove = "AmovPercMjmpSlowWrflDf"; + else if (MoveNameHas(moveName, "Wmel")) + jumpMove = "AmovPercMjmpSlowWmelDf"; + if (!PlayMoveNow(jumpMove)) + { + RStringB fallbackMove = "AovrPercMrunSnonWnonDf"; + if (MoveNameHas(moveName, "Wrfl")) fallbackMove = "AovrPercMrunSlowWrflDf"; + else if (MoveNameHas(moveName, "Wmel")) fallbackMove = "AovrPercMrunSlowWmelDf"; + PlayMoveNow(fallbackMove); + } + } + } + if (!IsControlled() && CheckPredictionFrozen()) { float timeOffset = AI_MAX_SIM_TIME; @@ -8101,6 +8163,7 @@ void Man::Simulate( float deltaT, SimulationImportance prec ) if (ValidatePotentialState(moveTrans) > 0) _ignoreCollisionIfStuck = true; } + } } // if( _freeFall ) @@ -10822,6 +10885,66 @@ void Man::PrepareProxiesForDrawing( ReleaseProxyInfo(info,false); } + // The second long weapon uses the existing shoulder proxy as a pose anchor. + // Offset it across the back so it remains visible without requiring a new + // character-model proxy in every survivor P3D. + InventoryItem *secondShoulderWeapon = GetInSlot(ISShoulder2); + if (_showPrimaryWeapon && secondShoulderWeapon && secondShoulderWeapon != _itemInHands && secondShoulderWeapon->GetShape()) + { + int shoulderProxyIndex = -1; + for (int i=0; iGetProxyCountForLevel(level); i++) + { + const ProxyObjectTyped &proxy = type->GetProxyForLevel(level, i); + Object *proxyObj = proxy.obj; + const EntityType *proxyType = proxyObj ? proxyObj->GetEntityType() : NULL; + if (proxyType && proxyType->GetInventorySlot() == ISShoulder) + { + shoulderProxyIndex = i; + break; + } + } + + if (shoulderProxyIndex >= 0) + { + Weapon *secondWeapon = secondShoulderWeapon->GetWeapon(); + if (secondWeapon) secondWeapon->UpdateShape(); + + LODShape *secondShape = secondShoulderWeapon->GetShape(); + int secondLevel = GScene->LevelFromDistance2(secondShape, dist2, transform.position.Scale()); + if (secondLevel == LOD_INVISIBLE && secondShoulderWeapon->GetFeatureSize() > 0) + secondLevel = secondShape->FindSimplestLevel(); + + if (secondLevel != LOD_INVISIBLE && secondLevel >= 0) + { + const ProxyObjectTyped &shoulderProxy = type->GetProxyForLevel(level, shoulderProxyIndex); + SkeletonIndex boneIndex = type->GetProxyBoneForLevel(level, shoulderProxyIndex); + Matrix4 anchor = AnimateProxyMatrix(RenderVisualState(), level, shoulderProxy.GetTransform(), boneIndex); + + const ManVisualState &mvs = RenderVisualState().cast(); + const Vector3 approvedShift(+0.32f, 0.0f, -0.10f); + // While standing still (and not leaning) the offset is recalibrated so + // the placement stays exactly the tuned one in character space. While + // moving the last calibrated vector is kept, which makes the weapon + // follow the shoulder bone rigidly (no sliding off the back). + if ((mvs._modelSpeed.SquareSize() < 0.25f && mvs._leaningTransIdent) || !_secondShoulderOffsetValid) + { + _secondShoulderOffsetLocal = anchor.Orientation().InverseGeneral() * approvedShift; + _secondShoulderOffsetValid = true; + } + Matrix4 oppositeSide(MTranslation, _secondShoulderOffsetLocal); + PositionRender secondTransform = transform * anchor * oppositeSide; + + if (secondShape->Remarks() & ShapeReversed) + { + Matrix4 swapM(MScale, -1, +1, -1); + secondTransform = secondTransform * swapM; + } + + GScene->ProxyForDrawing(secondShoulderWeapon, rootObj, secondLevel, rootLevel, clipFlags, dist2, secondTransform); + } + } + } + base::PrepareProxiesForDrawing(rootObj, rootLevel, animContext, transform, level, clipFlags, so); if (parent) @@ -11652,14 +11775,14 @@ void Man::ShowWeapons(bool showPrimary, bool showSecondary) _showSecondaryWeapon = showSecondary; } -const float MaxStandSlope = 0.9f; -const float MinStandSlope = -0.9f; +const float MaxStandSlope = 1.0f; +const float MinStandSlope = -1.0f; -const float MaxRunSlope = 0.4f; -const float MinRunSlope = -0.7f; +const float MaxRunSlope = 1.0f; +const float MinRunSlope = -1.0f; -const float MaxSprintSlope = 0.2f; -const float MinSprintSlope = -0.5f; +const float MaxSprintSlope = 0.9f; +const float MinSprintSlope = -0.9f; inline bool CanSprint(float gradFwd, float gradAside, float dirFwd, float dirAside) { @@ -13558,7 +13681,12 @@ void ManType::Load(ParamEntryPar par, const char *shape) for (int i=0; i> (RString("empty") + InventorySlotTypes.GetName(i)); + RString emptySlotName = RString("empty") + InventorySlotTypes.GetName(i); + // Older config.bin files do not define the new optional Shoulder2 slot. + // Do not ask ParamEntry for a missing key: that emits a fatal config + // warning during SurvivorMale initialization and can abort startup. + RString typeName; + if (par.CheckIfEntryExists(emptySlotName)) typeName = par >> emptySlotName; if (!typeName.IsEmpty()) _emptySlots[i] = dynamic_cast(VehicleTypes.New(typeName)); } @@ -15151,7 +15279,10 @@ static const ManAction SelectManActionRaised[3][3][3]= void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) { - if (KeyboardUsedInFrame()) return; + if (KeyboardUsedInFrame()) + { + return; + } TurretContextEx context; context._turret = NULL; @@ -15219,13 +15350,11 @@ void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) if (zoom) { CameraType camType = GWorld->GetCameraType(); - zoom->_zoomInsteadOfOptics = ( - input->GetAction(UALockTarget) -#if _VBS2 //no zooming with RMB when having 2D optics - && !(GetOpticsModel(this) && camType == CamGunner) -#endif - && (camType == CamInternal || camType == CamExternal || camType == CamGunner) - ); + // Right mouse button (UALockTarget) = hold-to-zoom. This must be + // re-evaluated every frame, otherwise releasing the button leaves the + // camera stuck at the maximum zoom level. + zoom->_zoomInsteadOfOptics = input->GetAction(UALockTarget) && + (camType == CamInternal || camType == CamExternal || camType == CamGunner); RenderVisualStateScope(true),zoom->Update(input,deltaT,this); // Zoom update may call RenderVisualState to check if optics are enabled WeaponModePtr ptr = _weaponsState.ValidatedCurrentWeapon(); @@ -15291,9 +15420,20 @@ void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) bool suspendMovement = false; if ((!_landContact || _freeFall) && _freeFallStartTimeGetActionWithCurveExclusive(InputInterface::CurveFovMouse, UAAimHeadRight, UAAimHeadLeft); float lookY = input->GetActionWithCurveExclusive(InputInterface::CurveFovMouse, UAAimHeadUp, UAAimHeadDown); + // Some 0.45 input profiles only bind the horizontal mouse to UAAimRight/ + // UAAimLeft. Preserve free-look yaw in those profiles when the dedicated + // head-yaw pair has no binding or was already consumed by another view. + if (fabs(lookX) < 1e-6f) + lookX = input->GetActionWithCurve(InputInterface::CurveFovMouse, UAAimRight, UAAimLeft); float rotXWanted = (ironSight ? _gunXRotWanted : _lookXRotWanted) + lookY*deltaT; float rotYWanted = (ironSight ? _gunYRotWanted : _lookYRotWanted) - lookX*deltaT; @@ -15448,7 +15593,7 @@ void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) } } - if ((!_landContact || _freeFall) && _freeFallStartTimeGetUseFastMove()) + if (fastForwardAct<+0.1f && map && map->GetUseFastMove()) fastFlag = true; int rlFlag = 0, fbFlag = 0; if (fabs(rlWanted)>+1.5f) @@ -15640,9 +15785,8 @@ void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) float maxSpeed = Type()->GetMaxSpeedMs(); float limitSpeed = floatMin(1.2f - GetEncumbrance(), 1.0f) * maxSpeed; - if (fabs(_leanZRot)+fabs(_leanZRotWanted)>0.5f) - // if there is any significant leaning, limit movement speed to walking - limitSpeed = floatMin(limitSpeed,2.5f); + // Lean is an additive pose overlay; it does not force the character back + // to walking. The normal run, sprint, weight, slope and water limits apply. if (_waterDepth>0.6) { if (_waterDepth>1.0) @@ -15761,11 +15905,26 @@ void Soldier::KeyboardPilot(float deltaT, SimulationImportance prec) } - MoveId moveWanted = map ? Type()->GetMove(map, selAction) : GetDefaultMove(); + MoveId moveWanted = map ? Type()->GetMove(map, selAction) : MoveIdNone; + // Resolve the requested action through the active ActionMap first. If the + // current state has no map or does not define this action, use the map for + // the decoded posture before falling back to an idle/default move. + if (moveWanted == MoveIdNone) + { + const MoveIdExt &postureMove = GetMovesType()->GetMove(GetActUpDegree(FutureVisualState()), selAction); + if (postureMove.id != MoveIdNone) + { + moveWanted = postureMove.id; + } + } + if (moveWanted == MoveIdNone) + moveWanted = GetDefaultMove(); if (!IsLocal() && _targetMoveWanted!=MoveIdNone) { ActionMap *targetMap = Type()->GetActionMap(_targetMoveWanted, AnimSubIx()); - if (map!=targetMap && Type()->GetMove(map, ManActStop)!=Type()->GetMove(targetMap, ManActStop)) + MoveId currentStop = map ? Type()->GetMove(map, ManActStop) : GetDefaultMove(); + MoveId targetStop = targetMap ? Type()->GetMove(targetMap, ManActStop) : GetDefaultMove(); + if (map!=targetMap && currentStop!=targetStop) { moveWanted = _targetMoveWanted; } @@ -15864,7 +16023,24 @@ int Man::GetAutoUpDegree() const MoveId Man::GetDefaultMove() const { int deg = GetAutoUpDegree(); - return GetMovesType()->GetDefaultMove(deg); + MoveId move = GetMovesType()->GetDefaultMove(deg); + if (move != MoveIdNone) + return move; + + // Some imported survivor animation configs leave the posture's Default + // action unmapped. MotionPath::PatchNoMove then receives MoveIdNone and the + // character stays in bind pose with no movement actions. Recover a living, + // upright character to the known base idle state so the normal action map + // can drive walking and running again. + if (!_isDead && !IsDown()) + { + MoveId fallbackMove = GetMovesType()->GetMoveId("AidlPercMstpSnonWnonDnon"); + if (fallbackMove == MoveIdNone) + fallbackMove = GetMovesType()->GetMoveId("AmovPercMstpSnonWnonDnon"); + if (fallbackMove != MoveIdNone) + return fallbackMove; + } + return move; } MoveId Man::GetDefaultMove(ManAction action) const @@ -17196,17 +17372,43 @@ void Man::RecalcLeaningTransform() float leanRotAngle; float leanShift; ActionMap *map = type->GetActionMap(_moves.GetPrimaryMove(vs->_moves).id, AnimSubIx()); + ActionMap *leanMap = map; if (map) { if (_leanZRot >= 0) { - leanRotAngle = map->GetLeanRRot(); - leanShift = map->GetLeanRShift(); + leanRotAngle = leanMap->GetLeanRRot(); + leanShift = leanMap->GetLeanRShift(); } else { - leanRotAngle = map->GetLeanLRot(); - leanShift = map->GetLeanLShift(); + leanRotAngle = leanMap->GetLeanLRot(); + leanShift = leanMap->GetLeanLShift(); + } + + // Some fast and strafe action maps omit lean offsets. Reuse the stop + // animation map from the same movement family while the player runs. + if (fabs(leanRotAngle) < 1e-6f && fabs(leanShift) < 1e-6f) + { + const MoveIdExt &stopMove = type->GetMove(map, ManActStop); + if (stopMove.id != MoveIdNone) + { + ActionMap *stopMap = type->GetActionMap(stopMove.id, AnimSubIx()); + if (stopMap && stopMap != map) + { + leanMap = stopMap; + if (_leanZRot >= 0) + { + leanRotAngle = leanMap->GetLeanRRot(); + leanShift = leanMap->GetLeanRShift(); + } + else + { + leanRotAngle = leanMap->GetLeanLRot(); + leanShift = leanMap->GetLeanLShift(); + } + } + } } } else @@ -17216,6 +17418,8 @@ void Man::RecalcLeaningTransform() } float leaningFactor = ValueTest(vs,&MoveInfoMan::LeaningFactor); + if (fabs(_leanZRot) > 0.01f && leaningFactor < 1e-4f) + leaningFactor = 1.0f; float leaningAngle = -_leanZRot * leanRotAngle * leaningFactor; float leaningShift = _leanZRot * leanShift * leaningFactor; if (fabs(leaningAngle) > 1e-6f || fabs(leaningShift) > 1e-6f) @@ -19962,6 +20166,33 @@ bool Soldier::ProcessFireWeapon(const TurretContext &context, const WeaponModePt if (QIsManual()) { + // In iron sights the camera and the muzzle have different origins. + // Aim the projectile from the muzzle at the surface under the sight, + // otherwise the two rays remain parallel and miss sideways nearby. + if (GWorld->GetCameraType() == CamGunner && GWorld->CameraOn() == this && + GScene && GScene->GetCamera()) + { + const Camera *camera = GScene->GetCamera(); + Vector3 cameraPos = camera->Position(); + Vector3 cameraDir = camera->Direction().Normalized(); + const float maxAimDistance = 500.0f; + float aimDistance = GLandscape->IntersectWithGroundOrSea( + NULL, cameraPos, cameraDir, 0, maxAimDistance); + if (aimDistance <= 0 || aimDistance > maxAimDistance) + aimDistance = maxAimDistance; + + CollisionBuffer hits; + GLandscape->ObjectCollisionLine(GetRenderVisualStateAge(), hits, + Landscape::FilterIgnoreOne(this), cameraPos, + cameraPos + cameraDir * aimDistance, 0, + ObjIntersectView, ObjIntersectFire, CF_NEAREST_CONTACT); + Vector3 sightTarget = hits.Size() > 0 ? hits[0].pos : + cameraPos + cameraDir * aimDistance; + Vector3 muzzleWorld = vs->PositionModelToWorld(pos); + Vector3 muzzleToTarget = sightTarget - muzzleWorld; + if (muzzleToTarget.SquareSize() > 1.0f) + dir = vs->DirectionWorldToModel(muzzleToTarget.Normalized()); + } // get fov from the current camera settings GWorld->GetCameraType(); //float fov = GScene->GetCamera()->Left(); diff --git a/lib/soldierOld.hpp b/lib/soldierOld.hpp index 1c62f838..2a125765 100644 --- a/lib/soldierOld.hpp +++ b/lib/soldierOld.hpp @@ -1274,6 +1274,12 @@ class Man: public Person bool _showPrimaryWeapon; bool _showSecondaryWeapon; bool _showHead; + + /// Second shoulder weapon offset expressed in the shoulder proxy's local + /// space. Calibrated while the man stands still so the tuned placement is + /// kept, while locomotion still carries the weapon with the shoulder bone. + Vector3 _secondShoulderOffsetLocal; + bool _secondShoulderOffsetValid; //@{ variables used while climbing ladder OLinkO(Building) _ladderBuilding; diff --git a/lib/transport.cpp b/lib/transport.cpp index c06b388f..ef295bbc 100644 --- a/lib/transport.cpp +++ b/lib/transport.cpp @@ -12164,19 +12164,22 @@ void Transport::LookAround(float aimX, float aimY, float deltaT, const ViewPars void Transport::UpdateZoom(AIBrain *unit) { Person *player = unit->GetPerson(); -// static bool doIt = false; -// if (GetZoom() && doIt) GetZoom()->_zoomInsteadOfOptics=false; //patch zoomInsteadOfOptics + // The zoom flag must reflect the current button state every frame. Setting + // it only when zooming in left the camera stuck at maximum zoom after the + // button was released (the "infinite zoom" bug in vehicles). + bool zoomInsteadOfOptics = false; if (player && GInput.GetAction(UALockTarget) && (GWorld->IsCameraActive(CamInternal) || GWorld->IsCameraActive(CamExternal))) { // EntityAIFull *veh = FocusOn()->GetVehicle(); // Assert(veh); - //which turret? + // Turret gunners keep using RMB for lock-on weapons; everybody else + // (pilot, copilot, cargo) gets hold-to-zoom on the right mouse button. + bool allowZoom = true; TurretContext context; // if (veh->GetPrimaryGunnerTurret(context)) if (FindTurret(player, context)) { WeaponModePtr curPtr = context._weapons->ValidatedCurrentWeapon(); - bool allowZoom = true; if (curPtr.IsValid()) { const MuzzleType *muzzle = curPtr.GetMuzzleType(); @@ -12185,15 +12188,12 @@ void Transport::UpdateZoom(AIBrain *unit) muzzle->_canBeLocked == 1 && Glob.config.IsEnabled(DTAutoGuideAT); if (canLock) allowZoom = false; } - if( allowZoom ) - { - // zoom in -// forcedZoom=true; - if (GetZoom()) - GetZoom()->_zoomInsteadOfOptics=true; - } } + if (allowZoom) zoomInsteadOfOptics = true; } + // Use the zoom of the unit being updated (driver or gunner), not the + // currently focused one, so the flag is always applied to the right camera. + if (GetZoom(unit)) GetZoom(unit)->_zoomInsteadOfOptics = zoomInsteadOfOptics; } Object::Zoom *Transport::GetZoom(const AIBrain *unit) diff --git a/lib/vehicleAI.cpp b/lib/vehicleAI.cpp index c66d7c1b..a48cb667 100644 --- a/lib/vehicleAI.cpp +++ b/lib/vehicleAI.cpp @@ -9554,8 +9554,15 @@ bool EntityAIFull::FireMGun(const TurretContext &context, const WeaponModePtr &p } gaussX*=2.0/gausPassNum; gaussY*=2.0/gausPassNum; - float randomX=(gaussX-1)*(ptr.SumDispersionModifiers(this)); - float randomY=(gaussY-1)*(ptr.SumDispersionModifiers(this)); + const float configuredDispersion = ptr.SumDispersionModifiers(this); + float effectiveDispersion = configuredDispersion; + // Some old rifle configs have a base dispersion near 0.1 radians even for + // a player using iron sights. Keep a small spread for bullets, while + // preserving the separate pellet spread of shotguns. + if (QIsManual() && type->_simulation == AmmoShotBullet) + saturateMin(effectiveDispersion, 0.003f); + float randomX=(gaussX-1)*effectiveDispersion; + float randomY=(gaussY-1)*effectiveDispersion; if( !QIsManual() ) { AIBrain *unit = context._gunner ? context._gunner->Brain() : NULL; @@ -9575,6 +9582,15 @@ bool EntityAIFull::FireMGun(const TurretContext &context, const WeaponModePtr &p } } + if (QIsManual() && GWorld && this == GWorld->GetRealPlayer()) + { + static int shotDispersionDiagnostics = 0; + if (shotDispersionDiagnostics++ < 32) + RptF("ShotDispersion base=%g attachments=%g effective=%g randomX=%g randomY=%g fade=%d", + mode->_dispersion, configuredDispersion - mode->_dispersion, + effectiveDispersion, randomX, randomY, DoFade ? 1 : 0); + } + Vector3 dir(randomX,randomY,1); svs.DirectionModelToWorld(dir,dir); diff --git a/lib/world.cpp b/lib/world.cpp index 6dad4709..a445b40b 100644 --- a/lib/world.cpp +++ b/lib/world.cpp @@ -53,6 +53,10 @@ #include "scripts.hpp" #include #include + +extern bool IsInventoryOpened(); +extern bool HandleInventorySpaceKey(); +extern void ReleaseInventorySpaceKey(); #include "txtPreload.hpp" #include "Shape/material.hpp" #include "Protect/selectProtection.h" @@ -12979,6 +12983,10 @@ if (_playerOn) DoAssert(_checkHashQueue.Size() > 0); if (!_checkingHash->IsValid()) { + RptF("BankHashMismatch bank=%d path=%s reason=%d", + _checkHashQueue[0]._bankIndex, + cc_cast(banks[_checkHashQueue[0]._bankIndex].GetOpenName()), + (int)_checkHashQueue[0]._reason); #if SIGNATURES_TEST_ONLY LogF("Warning: Hash of %s is wrong.", cc_cast(banks[_checkHashQueue[0]._bankIndex].GetOpenName())); #else @@ -16847,6 +16855,12 @@ bool World::DoKeyDown(int dikCode) return false; #endif + if (dikCode == DIK_SPACE && HandleInventorySpaceKey()) + { + GInput.DisableKey(dikCode); + return true; + } + #if _VBS3 // key bindings for (int i=0; i<_boundkeys.Size(); i++) { @@ -16930,6 +16944,12 @@ bool World::DoKeyDown(int dikCode) bool World::DoKeyUp(int dikCode) { + if (dikCode == DIK_SPACE) + { + ReleaseInventorySpaceKey(); + if (IsInventoryOpened()) return true; + } + if (!IsUserInputEnabled() #if _VBS3 && dikCode != DIK_ESCAPE diff --git a/lib/zombie.cpp b/lib/zombie.cpp index 971944db..f38280d8 100644 --- a/lib/zombie.cpp +++ b/lib/zombie.cpp @@ -220,7 +220,9 @@ void Dummy(LightAI* context) LightAI::LightAI(const EntityAIType *name, bool fullCreate): Man(name, fullCreate), _nearestPlayer(0), _checkAttack(0), _attackAction(0), _tiredFactor(0), - _tiredFactorHysteresis(0) + _tiredFactorHysteresis(0), + _nextPathOptimization(TIME_MIN), _nextObstacleCheckTime(TIME_MIN), + _lastAttackTime(TIME_MIN) { } @@ -465,6 +467,15 @@ void LightAI::Simulate( float deltaT, SimulationImportance prec ) if (IsSimulationDisabled()) return; + const bool isZombie = dynamic_cast(this) != NULL; + if (isZombie && _ignoreCollisionIfStuck) + { + // The inherited stuck recovery disables Geometry collision. Keep zombie + // collision active so a blocked zombie cannot escape through a wall. + _ignoreCollisionIfStuck = false; + _stuckStarted = TIME_MAX; + } + _toSafeSpot.AddWaypoint(FutureVisualState().Position()); float deltaT0 = deltaT; @@ -567,6 +578,7 @@ void LightAI::Simulate( float deltaT, SimulationImportance prec ) bool bChange = false; ManVisualState moveTrans = FutureVisualState(); // store old position + Vector3 prevPos = moveTrans.Position(); if(Brain()->GetLifeState() == LifeStateUnconscious) { @@ -641,7 +653,9 @@ void LightAI::Simulate( float deltaT, SimulationImportance prec ) } else { - if(_attackAction && Type()->GetAttackAction(_attackAction - 1)._canWalk) + if (isZombie) + _staticCollision = true; // route checks can miss obstacles; keep physical fallback enabled + else if(_attackAction && Type()->GetAttackAction(_attackAction - 1)._canWalk) _staticCollision = true; //avoid jumping into wall else { @@ -669,6 +683,42 @@ void LightAI::Simulate( float deltaT, SimulationImportance prec ) _objectContactNonStatic = false; + // Validate long zombie moves at short intervals using the animated body + // collision shape, preventing a fast simulation step from tunneling + // through a thin wall when both endpoints are clear. + if (isZombie && prec <= SimulateVisibleFar && !_useAudioTimeForMoves) + { + static const float zombieCollisionSubdiv = 0.2f; + const float moveDist = prevPos.Distance(moveTrans.Position()); + if (moveDist > zombieCollisionSubdiv + 0.01f) + { + const Time backupVegCollisionTime = _vegCollisionTime; + const bool backupHighPriorityContact = _highPriorityContact; + const bool backupPurePersonContact = _purePersonContact; + const bool backupObjectContact = _objectContact; + ManVisualState collisionTest(moveTrans); + int lastClearStep = 0; + const int stepCount = intMax((int)ceilf(moveDist / zombieCollisionSubdiv), 2); + const Vector3 endPos = moveTrans.Position(); + for (int step = 0; step < stepCount; step++) + { + collisionTest.SetPosition(prevPos.Lerp(endPos, (float)step / (stepCount - 1))); + const float collisionVolume = ValidatePotentialState(collisionTest); + _vegCollisionTime = backupVegCollisionTime; + _highPriorityContact = backupHighPriorityContact; + _purePersonContact = backupPurePersonContact; + _objectContact = backupObjectContact; + if (collisionVolume > 0.0f) break; + lastClearStep = step; + } + if (lastClearStep < 2) + lastClearStep = intMin(lastClearStep + 1, stepCount - 1); + const float moveRatio = (float)lastClearStep / (stepCount - 1); + moveTrans.SetPosition(prevPos.Lerp(endPos, moveRatio)); + deltaT *= moveRatio; + } + } + const bool farCollision = false; if (prec<=SimulateVisibleFar) { @@ -902,9 +952,48 @@ void LightAI::Simulate( float deltaT, SimulationImportance prec ) { _stuckStarted = TIME_MAX; _ignoreCollisionIfStuck = false; - if (ValidatePotentialState(moveTrans) > 0) + if (!isZombie && ValidatePotentialState(moveTrans) > 0) _ignoreCollisionIfStuck = true; } + + // Endpoint capsule checks alone can miss a thin wall or fence when the + // zombie's simulated move crosses the whole obstacle in one frame. + if (deltaT > 0 && (prec <= SimulateVisibleNear || (isZombie && prec <= SimulateVisibleFar))) + { + const Vector3 oldPos = FutureVisualState().Position() + ZombieRayTestOffset; + const Vector3 newPos = moveTrans.Position() + ZombieRayTestOffset; + CollisionBuffer collision; + if (newPos.Distance2(oldPos) > Square(0.1f) && !_ignoreCollisionIfStuck) + GLandscape->ObjectCollisionLine(GetFutureVisualStateAge(), collision, + Landscape::FilterIgnoreOne(this), oldPos, newPos, ZombieRayTestRadius, ObjIntersectGeom); + + float firstHit = 1e10f; + for (int i = 0; i < collision.Size(); i++) + { + const CollisionInfo &info = collision[i]; + Object *obj = info.object; + if (!obj) continue; + const bool zombieStaticWorldBlock = isZombie && obj->Static(); + if (obj->IsPassable() && !zombieStaticWorldBlock) continue; + _objectContact = true; + _objectContactNonStatic = _objectContactNonStatic || !obj->Static(); + // ObjectCollisionLine reports entry=false when the segment begins + // inside (or touching) this expanded geometry. That is not a usable + // impact fraction; leave the overlap to the animated body solver. + if (!info.entry) continue; + if (info.under < firstHit) firstHit = info.under; + } + if (firstHit < 1.0f) + { + // Stop just before the first outside-to-inside contact. Do not + // impose a minimum forward step, which would push short moves into + // the same wall and produce an overlap on every following frame. + firstHit = floatMax(firstHit - 0.005f, 0.0f); + const Vector3 collisionPos = FutureVisualState().Position() * (1 - firstHit) + moveTrans.Position() * firstHit; + repairMove += collisionPos - moveTrans.Position(); + moveTrans.SetPosition(collisionPos); + } + } } } // if( _freeFall ) @@ -2149,7 +2238,7 @@ void LightAI::AIPathPilot(SteerInfo& info, float deltaT) const VisualState& vs = FutureVisualState(); const FSM::State fsmState = _fsm->GetState(); - if( _walkTarget && _walkTarget->_trail.Size() && CanWalk() ) + if( _walkTarget && (_walkTarget->_trail.Size() || _walkTarget->_pathBlocked) && CanWalk() ) { Vector3 position = vs.Position(); Vector3 dir = vs.Direction(); @@ -2183,10 +2272,46 @@ void LightAI::AIPathPilot(SteerInfo& info, float deltaT) } } - if( Glob.time > _nextObstacleCheckTime ) + // A multi-waypoint trail already came from the obstacle-aware pathfinder. + // Rebuilding a path to the moving target every second for every zombie + // creates a large server-side spike (especially on dense servers) and + // makes remote player positions appear stale. Recheck only direct/finished + // trails, where there is no alternate route to follow, or a blocked path. + if (_walkTarget->_target && + (_walkTarget->_trail.Size() <= 1 || _walkTarget->_pathBlocked) && + Glob.time >= _nextObstacleCheckTime) + { + _nextObstacleCheckTime = Glob.time + 1.0f; + const Vector3 targetPos = _walkTarget->_target->FutureVisualState().Position(); + const float targetDist2 = targetPos.Distance2(position); + const bool pathFound = InitPathToTarget(_walkTarget, ZombieRayTestOffset, ZombieRayTestRadius, 100); + if (!pathFound && targetDist2 <= Square(100.0f)) + { + _walkTarget->_pathBlocked = true; + _walkTarget->_trail.Clear(); + } + else + _walkTarget->_pathBlocked = false; + + if (_walkTarget->_pathBlocked) + { + info.speedWanted = 0; + info.sideSpeedWanted = 0; + info.headChange = 0; + info.turnPredict = 0; + _walkTarget = NULL; + return; + } + } + + if (_walkTarget->_pathBlocked) { - // FindPathAroundObstacles(_walkTarget->_trail, _walkTarget->_target); - _nextObstacleCheckTime = Glob.time + 1; + info.speedWanted = 0; + info.sideSpeedWanted = 0; + info.headChange = 0; + info.turnPredict = 0; + _walkTarget = NULL; + return; } Vector3 walkPos = _walkTarget->_trail[0]._pos; diff --git a/lib/zombie.hpp b/lib/zombie.hpp index 37a9b945..c9e987e6 100644 --- a/lib/zombie.hpp +++ b/lib/zombie.hpp @@ -98,12 +98,16 @@ class ChaseTarget: public RefCount public: Ref _target; AutoArray _trail; + bool _pathBlocked; + + ChaseTarget() : _pathBlocked(false) {} void AddWaypoint(Vector3Par pos); float Age() const; void Clear() { _trail.Clear(); + _pathBlocked = false; } ChaseTarget* CreateReversed() const; bool ReachedGoal(Vector3Par pos) const; diff --git a/release-assets/physics/materials.h b/release-assets/physics/materials.h new file mode 100644 index 00000000..2e6b0220 --- /dev/null +++ b/release-assets/physics/materials.h @@ -0,0 +1,3 @@ +class Materials +{ +}; diff --git a/release-assets/server/serverDZ.cfg b/release-assets/server/serverDZ.cfg index 7e4232f7..5f3dfb9e 100644 --- a/release-assets/server/serverDZ.cfg +++ b/release-assets/server/serverDZ.cfg @@ -1,6 +1,8 @@ hostname = "Private DayZ Server"; password = ""; maxPlayers = 10; +steamPort = 8766; +steamQueryPort = 27016; verifySignatures = 2; reportingIP = "noreport"; voteMissionPlayers = 1; From 08510f21752f3bfa11633a94a8c4cea1d3a1878b Mon Sep 17 00:00:00 2001 From: Gabriel Stoltemberg Date: Mon, 23 Nov 2026 21:43:19 -0300 Subject: [PATCH 2/3] Reconcile inventory rotation and Steam declarations --- lib/Inventory/inventory.cpp | 3 --- lib/Inventory/inventory.hpp | 1 - lib/Network/networkImpl.hpp | 4 ++-- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/Inventory/inventory.cpp b/lib/Inventory/inventory.cpp index e27b1328..c2bce05a 100644 --- a/lib/Inventory/inventory.cpp +++ b/lib/Inventory/inventory.cpp @@ -2265,7 +2265,6 @@ TMError InventoryItem::TransferMsg(NetworkMessageContext &ctx) TRANSF_EX(inLandscape, inLandscape); bool isOn = IsOn(); TRANSF_EX(isOn, isOn); - TRANSF_EX(inventoryRotated, _inventoryRotated); } else { @@ -2288,7 +2287,6 @@ TMError InventoryItem::TransferMsg(NetworkMessageContext &ctx) if (item) item->ItemMoveOut(this); } - TRANSF_EX(inventoryRotated, _inventoryRotated); } } @@ -2322,7 +2320,6 @@ float InventoryItem::CalculateError(NetworkMessageContextWithError &ctx) error += ERR_COEF_MODE * dif; if ( message->_isOn!=IsOn() ) error += ERR_COEF_STRUCTURE; - if ( message->_inventoryRotated != _inventoryRotated ) error += ERR_COEF_MODE; } return error; } diff --git a/lib/Inventory/inventory.hpp b/lib/Inventory/inventory.hpp index 51eb4a86..3ee5c3fe 100644 --- a/lib/Inventory/inventory.hpp +++ b/lib/Inventory/inventory.hpp @@ -161,7 +161,6 @@ TypeIsSimple(InventorySlotId) XX(MessageName, RefArray, attachments, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("Attachments"), TRANSF_REFS, ET_NOT_EQUAL_COUNT, ERR_COEF_MODE) \ XX(MessageName, bool, inventoryRotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Item rotated in inventory grid"), TRANSF, ET_NOT_EQUAL, ERR_COEF_IMMEDIATE) \ XX(MessageName, bool, inLandscape, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Item is in landscape"), TRANSF, ET_NOT_EQUAL, ERR_COEF_IMMEDIATE) \ - XX(MessageName, bool, inventoryRotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Item is rotated in the inventory grid"), TRANSF, ET_NOT_EQUAL, ERR_COEF_MODE) \ DECLARE_NET_INDICES_EX_ERR(UpdateInventoryItem, UpdateVehicleAI, UPDATE_INVENTORY_ITEM_MSG) diff --git a/lib/Network/networkImpl.hpp b/lib/Network/networkImpl.hpp index abda070c..498e46e5 100644 --- a/lib/Network/networkImpl.hpp +++ b/lib/Network/networkImpl.hpp @@ -3929,7 +3929,7 @@ struct AsyncDBStorage void DBCheckLoaded(); }; -#if _ENABLE_STEAM_MATCHMAKING +#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) class SteamValidation { /// Steam authentication is completed (need not wait for it) @@ -4065,7 +4065,7 @@ struct NetworkPlayerInfo : public AsyncDBStorage, public RefCount, private NoCop SteamValidation _steamValidate; #endif -#if _ENABLE_STEAM_MATCHMAKING +#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) SteamValidation _steamValidate; #endif From 55c6d91e0ef5bad906af3d4702af39bad49c8f1b Mon Sep 17 00:00:00 2001 From: Gabriel Stoltemberg Date: Mon, 23 Nov 2026 21:44:25 -0300 Subject: [PATCH 3/3] Preserve Steam identity and resolve UI declaration --- lib/UI/uiMap.cpp | 1 - lib/retailConfig.h | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/UI/uiMap.cpp b/lib/UI/uiMap.cpp index 27226c5f..2f27ca34 100644 --- a/lib/UI/uiMap.cpp +++ b/lib/UI/uiMap.cpp @@ -6430,7 +6430,6 @@ class DisplayInventory : public Display Control *OnCreateCtrl(int type, int idc, ParamEntryPar cls); ControlObject *OnCreateObject(int type, int idc, ParamEntryPar cls); void OnSimulate(EntityAI *vehicle); - virtual bool OnKeyDown(int dikCode) override; void DestroyHUD(int exit) { GWorld->DestroyUserDialog(); diff --git a/lib/retailConfig.h b/lib/retailConfig.h index e7c67c8b..10ffdbc6 100644 --- a/lib/retailConfig.h +++ b/lib/retailConfig.h @@ -57,9 +57,8 @@ #define _ENABLE_DX10 0 #define _USE_BATTL_EYE_SERVER 1 #define _USE_BATTL_EYE_CLIENT 1 -// Steamworks SDK is not available in this tree; keep all Steam integration disabled. +// Ownership and matchmaking are configured independently of Steam identity. #define _ENABLE_STEAM_OWNERSHIP 0 -#define _ENABLE_STEAM 0 #define _ENABLE_STEAM_MATCHMAKING 0 #define _ENABLE_SEND_UDP_MESSAGE 0 #define _ENABLE_TEXTURE_HEADERS 1 //if reading texture headers from texture headers file is enabled