From 0bac9f0de8a28b5d125689d32839347bfd1c14b4 Mon Sep 17 00:00:00 2001 From: def Date: Fri, 25 Sep 2020 18:11:59 +0200 Subject: [PATCH 1/7] Manual preparation for cleaner clang-format Also include what you use explicitly --- .clang-format | 6 +- src/antibot/antibot_data.h | 6 +- src/antibot/antibot_null.cpp | 26 ++--- src/base/system.c | 5 +- src/engine/client/backend_sdl.cpp | 2 +- src/engine/client/client.cpp | 14 +-- src/engine/client/demoedit.h | 2 + src/engine/client/graphics_threaded.cpp | 3 +- src/engine/demo.h | 7 +- src/engine/external/.clang-format | 3 + src/engine/kernel.h | 7 -- src/engine/server/databases/connection.cpp | 86 +++++++------- src/engine/server/register.h | 1 + src/game/client/animstate.h | 2 + src/game/client/components/ghost.h | 1 + src/game/extrainfo.h | 2 + src/game/server/entities/gun.cpp | 6 +- src/game/server/entities/projectile.h | 2 + src/game/server/gamecontext.h | 2 + src/game/server/score.cpp | 126 ++++++++++----------- src/game/server/teehistorian.cpp | 27 +++-- src/test/teehistorian.cpp | 12 +- src/tools/crapnet.cpp | 2 +- 23 files changed, 178 insertions(+), 172 deletions(-) create mode 100644 src/engine/external/.clang-format diff --git a/.clang-format b/.clang-format index 86a3a921d..0e478c288 100644 --- a/.clang-format +++ b/.clang-format @@ -2,12 +2,16 @@ Language: Cpp AccessModifierOffset: -8 AlignAfterOpenBracket: DontAlign +AlignEscapedNewlines: DontAlign AlignTrailingComments: false -AllowShortFunctionsOnASingleLine: Inline +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All AlwaysBreakTemplateDeclarations: true BasedOnStyle: LLVM BreakBeforeBraces: Custom BreakBeforeTernaryOperators: false +BreakConstructorInitializers: AfterColon BreakStringLiterals: true BraceWrapping: AfterCaseLabel: true diff --git a/src/antibot/antibot_data.h b/src/antibot/antibot_data.h index 811210502..02d9b3978 100644 --- a/src/antibot/antibot_data.h +++ b/src/antibot/antibot_data.h @@ -30,9 +30,9 @@ struct CAntibotInputData // Defined by the network protocol, unlikely to change. //enum //{ - //TEAM_SPECTATORS=-1, - //TEAM_RED=0, - //TEAM_BLUE=1, +// TEAM_SPECTATORS=-1, +// TEAM_RED=0, +// TEAM_BLUE=1, //}; struct CAntibotCharacterData diff --git a/src/antibot/antibot_null.cpp b/src/antibot/antibot_null.cpp index aa8ffef2c..00d3cde43 100644 --- a/src/antibot/antibot_null.cpp +++ b/src/antibot/antibot_null.cpp @@ -22,18 +22,18 @@ void AntibotDump(void) { g_pData->m_pfnLog("null antibot", g_pData->m_pUser); } -void AntibotOnPlayerInit(int ClientID) { (void)ClientID; } -void AntibotOnPlayerDestroy(int ClientID) { (void)ClientID; } -void AntibotOnSpawn(int ClientID) { (void)ClientID; } -void AntibotOnHammerFireReloading(int ClientID) { (void)ClientID; } -void AntibotOnHammerFire(int ClientID) { (void)ClientID; } -void AntibotOnHammerHit(int ClientID) { (void)ClientID; } -void AntibotOnDirectInput(int ClientID) { (void)ClientID; } -void AntibotOnCharacterTick(int ClientID) { (void)ClientID; } -void AntibotOnHookAttach(int ClientID, bool Player) { (void)ClientID; (void)Player; } -void AntibotOnEngineTick(void) { } -void AntibotOnEngineClientJoin(int ClientID, bool Sixup) { (void)ClientID; (void)Sixup; } -void AntibotOnEngineClientDrop(int ClientID, const char *pReason) { (void)ClientID; (void)pReason; } -void AntibotOnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) { (void)ClientID; (void)pData; (void)Size; (void)Flags; } +void AntibotOnPlayerInit(int /*ClientID*/) {} +void AntibotOnPlayerDestroy(int /*ClientID*/) {} +void AntibotOnSpawn(int /*ClientID*/) {} +void AntibotOnHammerFireReloading(int /*ClientID*/) {} +void AntibotOnHammerFire(int /*ClientID*/) {} +void AntibotOnHammerHit(int /*ClientID*/) {} +void AntibotOnDirectInput(int /*ClientID*/) {} +void AntibotOnCharacterTick(int /*ClientID*/) {} +void AntibotOnHookAttach(int /*ClientID*/, bool /*Player*/) {} +void AntibotOnEngineTick(void) {} +void AntibotOnEngineClientJoin(int /*ClientID*/, bool /*Sixup*/) {} +void AntibotOnEngineClientDrop(int /*ClientID*/, const char * /*pReason*/) {} +void AntibotOnEngineClientMessage(int /*ClientID*/, const void * /*pData*/, int /*Size*/, int /*Flags*/) {} } diff --git a/src/base/system.c b/src/base/system.c index 48d693c90..b9f9908bb 100644 --- a/src/base/system.c +++ b/src/base/system.c @@ -52,6 +52,7 @@ #include #include #include + #include #include #include @@ -3335,8 +3336,8 @@ int os_is_winxp_or_lower(void) mem_zero(&ver, sizeof(OSVERSIONINFO)); ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&ver); - return ver.dwMajorVersion < WINXP_MAJOR - || (ver.dwMajorVersion == WINXP_MAJOR && ver.dwMinorVersion <= WINXP_MINOR); + return ver.dwMajorVersion < WINXP_MAJOR || + (ver.dwMajorVersion == WINXP_MAJOR && ver.dwMinorVersion <= WINXP_MINOR); #else return 0; #endif diff --git a/src/engine/client/backend_sdl.cpp b/src/engine/client/backend_sdl.cpp index 1f026b474..4ed003d67 100644 --- a/src/engine/client/backend_sdl.cpp +++ b/src/engine/client/backend_sdl.cpp @@ -3651,7 +3651,7 @@ static void ParseVersionString(const GLubyte* pStr, int& VersionMajor, int& Vers char aCurNumberStr[32]; size_t CurNumberStrLen = 0; size_t TotalNumbersPassed = 0; - int aNumbers[3] = { 0, }; + int aNumbers[3] = { 0 }; bool LastWasNumber = false; while(*pStr && TotalNumbersPassed < 3) { diff --git a/src/engine/client/client.cpp b/src/engine/client/client.cpp index 80bf2b907..f39e16f60 100644 --- a/src/engine/client/client.cpp +++ b/src/engine/client/client.cpp @@ -1380,8 +1380,8 @@ void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, CServerInfo Info = {0}; int SavedType = SavedServerInfoType(RawType); - if((SavedType == SERVERINFO_64_LEGACY || SavedType == SERVERINFO_EXTENDED) - && pEntry && pEntry->m_GotInfo && SavedType == pEntry->m_Info.m_Type) + if((SavedType == SERVERINFO_64_LEGACY || SavedType == SERVERINFO_EXTENDED) && + pEntry && pEntry->m_GotInfo && SavedType == pEntry->m_Info.m_Type) { Info = pEntry->m_Info; } @@ -2527,8 +2527,8 @@ void CClient::PumpNetwork() m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); } - if(State() != IClient::STATE_OFFLINE && State() < IClient::STATE_QUITING && m_DummyConnected - && m_NetClient[CLIENT_DUMMY].State() == NETSTATE_OFFLINE) + if(State() != IClient::STATE_OFFLINE && State() < IClient::STATE_QUITING && m_DummyConnected && + m_NetClient[CLIENT_DUMMY].State() == NETSTATE_OFFLINE) { DummyDisconnect(0); char aBuf[256]; @@ -3219,9 +3219,9 @@ void CClient::Run() bool IsRenderActive = (g_Config.m_GfxBackgroundRender || m_pGraphics->WindowOpen()); - if(IsRenderActive - && (!g_Config.m_GfxAsyncRenderOld || m_pGraphics->IsIdle()) - && (!g_Config.m_GfxRefreshRate || (time_freq() / (int64)g_Config.m_GfxRefreshRate) <= Now - LastRenderTime)) + if(IsRenderActive && + (!g_Config.m_GfxAsyncRenderOld || m_pGraphics->IsIdle()) && + (!g_Config.m_GfxRefreshRate || (time_freq() / (int64)g_Config.m_GfxRefreshRate) <= Now - LastRenderTime)) { m_RenderFrames++; diff --git a/src/engine/client/demoedit.h b/src/engine/client/demoedit.h index 8838f73c4..9eb91caca 100644 --- a/src/engine/client/demoedit.h +++ b/src/engine/client/demoedit.h @@ -2,6 +2,8 @@ #define ENGINE_CLIENT_DEMOEDIT_H #include +#include +#include #define CONNECTLINK "ddnet:" diff --git a/src/engine/client/graphics_threaded.cpp b/src/engine/client/graphics_threaded.cpp index 60039ae9f..a8478ddcb 100644 --- a/src/engine/client/graphics_threaded.cpp +++ b/src/engine/client/graphics_threaded.cpp @@ -2091,8 +2091,7 @@ int CGraphics_Threaded::Init() 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, - 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, - }; + 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff}; m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,s_aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); return 0; diff --git a/src/engine/demo.h b/src/engine/demo.h index 721155aeb..015ec6e89 100644 --- a/src/engine/demo.h +++ b/src/engine/demo.h @@ -18,12 +18,11 @@ const double g_aSpeeds[] = {0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, typedef bool (*DEMOFUNC_FILTER)(const void *pData, int DataSize, void *pUser); // TODO: Properly extend demo format using uuids +// "6be6da4a-cebd-380c-9b5b-1289c842d780" +// "demoitem-sha256@ddnet.tw" static const CUuid SHA256_EXTENSION = {{ - // "6be6da4a-cebd-380c-9b5b-1289c842d780" - // "demoitem-sha256@ddnet.tw" 0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c, - 0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80 -}}; + 0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80}}; struct CDemoHeader { diff --git a/src/engine/external/.clang-format b/src/engine/external/.clang-format new file mode 100644 index 000000000..259fe7fbe --- /dev/null +++ b/src/engine/external/.clang-format @@ -0,0 +1,3 @@ +DisableFormat: true +# clang-format bug: still sorts includes even if disabled +SortIncludes: false diff --git a/src/engine/kernel.h b/src/engine/kernel.h index 235ccb945..736f27719 100644 --- a/src/engine/kernel.h +++ b/src/engine/kernel.h @@ -18,9 +18,6 @@ protected: public: IInterface() : m_pKernel(0) {} virtual ~IInterface() {} - - //virtual unsigned InterfaceID() = 0; - //virtual const char *InterfaceName() = 0; }; #define MACRO_INTERFACE(Name, ver) \ @@ -28,10 +25,6 @@ public: static const char *InterfaceName() { return Name; } \ private: - //virtual unsigned InterfaceID() { return INTERFACE_ID; } - //virtual const char *InterfaceName() { return name; } - - // This kernel thingie makes the structure very flat and basiclly singletons. // I'm not sure if this is a good idea but it works for now. class IKernel diff --git a/src/engine/server/databases/connection.cpp b/src/engine/server/databases/connection.cpp index e94ec9904..b7a95caf9 100644 --- a/src/engine/server/databases/connection.cpp +++ b/src/engine/server/databases/connection.cpp @@ -6,23 +6,23 @@ void IDbConnection::FormatCreateRace(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, "CREATE TABLE IF NOT EXISTS %s_race (" - "Map VARCHAR(128) COLLATE %s NOT NULL, " - "Name VARCHAR(%d) COLLATE %s NOT NULL, " - "Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - "Time FLOAT DEFAULT 0, " - "Server CHAR(4), " - "cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, " - "cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, " - "cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, " - "cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, " - "cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, " - "cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, " - "cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, " - "cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, " - "cp25 FLOAT DEFAULT 0, " - "GameID VARCHAR(64), " - "DDNet7 BOOL DEFAULT FALSE, " - "PRIMARY KEY (Map, Name, Time, Timestamp, Server)" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Time FLOAT DEFAULT 0, " + " Server CHAR(4), " + " cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, " + " cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, " + " cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, " + " cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, " + " cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, " + " cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, " + " cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, " + " cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, " + " cp25 FLOAT DEFAULT 0, " + " GameID VARCHAR(64), " + " DDNet7 BOOL DEFAULT FALSE, " + " PRIMARY KEY (Map, Name, Time, Timestamp, Server)" ");", GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate()); } @@ -31,14 +31,14 @@ void IDbConnection::FormatCreateTeamrace(char *aBuf, unsigned int BufferSize, co { str_format(aBuf, BufferSize, "CREATE TABLE IF NOT EXISTS %s_teamrace (" - "Map VARCHAR(128) COLLATE %s NOT NULL, " - "Name VARCHAR(%d) COLLATE %s NOT NULL, " - "Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - "Time FLOAT DEFAULT 0, " - "ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite - "GameID VARCHAR(64), " - "DDNet7 BOOL DEFAULT FALSE, " - "PRIMARY KEY (ID, Name)" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Time FLOAT DEFAULT 0, " + " ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite + " GameID VARCHAR(64), " + " DDNet7 BOOL DEFAULT FALSE, " + " PRIMARY KEY (ID, Name)" ");", GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate(), pIdType); } @@ -47,13 +47,13 @@ void IDbConnection::FormatCreateMaps(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, "CREATE TABLE IF NOT EXISTS %s_maps (" - "Map VARCHAR(128) COLLATE %s NOT NULL, " - "Server VARCHAR(32) COLLATE %s NOT NULL, " - "Mapper VARCHAR(128) COLLATE %s NOT NULL, " - "Points INT DEFAULT 0, " - "Stars INT DEFAULT 0, " - "Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " - "PRIMARY KEY (Map)" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Server VARCHAR(32) COLLATE %s NOT NULL, " + " Mapper VARCHAR(128) COLLATE %s NOT NULL, " + " Points INT DEFAULT 0, " + " Stars INT DEFAULT 0, " + " Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " + " PRIMARY KEY (Map)" ");", GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); } @@ -62,14 +62,14 @@ void IDbConnection::FormatCreateSaves(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, "CREATE TABLE IF NOT EXISTS %s_saves (" - "Savegame TEXT COLLATE %s NOT NULL, " - "Map VARCHAR(128) COLLATE %s NOT NULL, " - "Code VARCHAR(128) COLLATE %s NOT NULL, " - "Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - "Server CHAR(4), " - "DDNet7 BOOL DEFAULT FALSE, " - "SaveID VARCHAR(36) DEFAULT NULL, " - "PRIMARY KEY (Map, Code)" + " Savegame TEXT COLLATE %s NOT NULL, " + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Code VARCHAR(128) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Server CHAR(4), " + " DDNet7 BOOL DEFAULT FALSE, " + " SaveID VARCHAR(36) DEFAULT NULL, " + " PRIMARY KEY (Map, Code)" ");", GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); } @@ -78,9 +78,9 @@ void IDbConnection::FormatCreatePoints(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, "CREATE TABLE IF NOT EXISTS %s_points (" - "Name VARCHAR(%d) COLLATE %s NOT NULL, " - "Points INT DEFAULT 0, " - "PRIMARY KEY (Name)" + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Points INT DEFAULT 0, " + " PRIMARY KEY (Name)" ");", GetPrefix(), MAX_NAME_LENGTH, BinaryCollate()); } diff --git a/src/engine/server/register.h b/src/engine/server/register.h index a75547ba7..86af0c93c 100644 --- a/src/engine/server/register.h +++ b/src/engine/server/register.h @@ -4,6 +4,7 @@ #define ENGINE_SERVER_REGISTER_H #include +#include class CRegister { diff --git a/src/game/client/animstate.h b/src/game/client/animstate.h index fbc0a2f8e..730fff989 100644 --- a/src/game/client/animstate.h +++ b/src/game/client/animstate.h @@ -3,6 +3,8 @@ #ifndef GAME_CLIENT_ANIMSTATE_H #define GAME_CLIENT_ANIMSTATE_H +#include + class CAnimState { CAnimKeyframe m_Body; diff --git a/src/game/client/components/ghost.h b/src/game/client/components/ghost.h index b1e134c04..617b54f96 100644 --- a/src/game/client/components/ghost.h +++ b/src/game/client/components/ghost.h @@ -4,6 +4,7 @@ #define GAME_CLIENT_COMPONENTS_GHOST_H #include +#include enum { diff --git a/src/game/extrainfo.h b/src/game/extrainfo.h index fd3877011..c89b2ab1d 100644 --- a/src/game/extrainfo.h +++ b/src/game/extrainfo.h @@ -3,6 +3,8 @@ #ifndef GAME_EXTRAINFO_H #define GAME_EXTRAINFO_H +#include + #include bool UseExtraInfo(const CNetObj_Projectile *pProj); diff --git a/src/game/server/entities/gun.cpp b/src/game/server/entities/gun.cpp index c805f3210..ade1c8ea2 100644 --- a/src/game/server/entities/gun.cpp +++ b/src/game/server/entities/gun.cpp @@ -117,9 +117,9 @@ void CGun::Snap(int SnappingClient) CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 - || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) - && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || + GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && + GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); int Tick = (Server()->Tick()%Server()->TickSpeed())%11; diff --git a/src/game/server/entities/projectile.h b/src/game/server/entities/projectile.h index ad9a63200..f1d596339 100644 --- a/src/game/server/entities/projectile.h +++ b/src/game/server/entities/projectile.h @@ -3,6 +3,8 @@ #ifndef GAME_SERVER_ENTITIES_PROJECTILE_H #define GAME_SERVER_ENTITIES_PROJECTILE_H +#include + class CProjectile : public CEntity { public: diff --git a/src/game/server/gamecontext.h b/src/game/server/gamecontext.h index 86c0f515e..a440623d1 100644 --- a/src/game/server/gamecontext.h +++ b/src/game/server/gamecontext.h @@ -21,6 +21,8 @@ #include "player.h" #include "teehistorian.h" +#include + #ifdef _MSC_VER typedef __int32 int32_t; typedef unsigned __int32 uint32_t; diff --git a/src/game/server/score.cpp b/src/game/server/score.cpp index a32887ff1..74fef7934 100644 --- a/src/game/server/score.cpp +++ b/src/game/server/score.cpp @@ -213,8 +213,8 @@ bool CScore::LoadPlayerDataThread(IDbConnection *pSqlServer, const ISqlData *pGa // get best race time str_format(aBuf, sizeof(aBuf), "SELECT Time, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, " - "cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, " - "cp21, cp22, cp23, cp24, cp25 " + " cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, " + " cp21, cp22, cp23, cp24, cp25 " "FROM %s_race " "WHERE Map = ? AND Name = ? " "ORDER BY Time ASC " @@ -293,9 +293,9 @@ bool CScore::MapVoteThread(IDbConnection *pSqlServer, const ISqlData *pGameData) "FROM %s_maps " "WHERE Map LIKE %s " "ORDER BY " - "CASE WHEN Map = ? THEN 0 ELSE 1 END, " - "CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " - "LENGTH(Map), Map " + " CASE WHEN Map = ? THEN 0 ELSE 1 END, " + " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " + " LENGTH(Map), Map " "LIMIT 1;", pSqlServer->GetPrefix(), pSqlServer->CollateNocase()); pSqlServer->PrepareStatement(aBuf); @@ -354,21 +354,21 @@ bool CScore::MapInfoThread(IDbConnection *pSqlServer, const ISqlData *pGameData) char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "SELECT l.Map, l.Server, Mapper, Points, Stars, " - "(SELECT COUNT(Name) FROM %s_race WHERE Map = l.Map) AS Finishes, " - "(SELECT COUNT(DISTINCT Name) FROM %s_race WHERE Map = l.Map) AS Finishers, " - "(SELECT ROUND(AVG(Time)) FROM %s_race WHERE Map = l.Map) AS Average, " - "%s AS Stamp, " - "%s-%s AS Ago, " - "(SELECT MIN(Time) FROM %s_race WHERE Map = l.Map AND Name = ?) AS OwnTime " + " (SELECT COUNT(Name) FROM %s_race WHERE Map = l.Map) AS Finishes, " + " (SELECT COUNT(DISTINCT Name) FROM %s_race WHERE Map = l.Map) AS Finishers, " + " (SELECT ROUND(AVG(Time)) FROM %s_race WHERE Map = l.Map) AS Average, " + " %s AS Stamp, " + " %s-%s AS Ago, " + " (SELECT MIN(Time) FROM %s_race WHERE Map = l.Map AND Name = ?) AS OwnTime " "FROM (" - "SELECT * FROM %s_maps " - "WHERE Map LIKE %s " - "ORDER BY " - "CASE WHEN Map = ? THEN 0 ELSE 1 END, " - "CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " - "LENGTH(Map), " - "Map " - "LIMIT 1" + " SELECT * FROM %s_maps " + " WHERE Map LIKE %s " + " ORDER BY " + " CASE WHEN Map = ? THEN 0 ELSE 1 END, " + " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " + " LENGTH(Map), " + " Map " + " LIMIT 1" ") as l;", pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), aTimestamp, aCurrentTimestamp, aTimestamp, @@ -579,9 +579,9 @@ bool CScore::SaveTeamScoreThread(IDbConnection *pSqlServer, const ISqlData *pGam str_format(aBuf, sizeof(aBuf), "SELECT l.ID, Name, Time " "FROM (" // preselect teams with first name in team - "SELECT ID " - "FROM %s_teamrace " - "WHERE Map = ? AND Name = ? AND DDNet7 = false" + " SELECT ID " + " FROM %s_teamrace " + " WHERE Map = ? AND Name = ? AND DDNet7 = false" ") as l INNER JOIN %s_teamrace AS r ON l.ID = r.ID " "ORDER BY l.ID, Name COLLATE %s;", pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->BinaryCollate()); @@ -663,11 +663,11 @@ bool CScore::ShowRankThread(IDbConnection *pSqlServer, const ISqlData *pGameData str_format(aBuf, sizeof(aBuf), "SELECT Rank, Name, Time " "FROM (" - "SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " - "FROM %s_race " - "WHERE Map = ? " - "GROUP BY Name " - "WINDOW w AS (ORDER BY Time)" + " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " + " FROM %s_race " + " WHERE Map = ? " + " GROUP BY Name " + " WINDOW w AS (ORDER BY Time)" ") as a " "WHERE Name = ?;", pSqlServer->GetPrefix()); @@ -721,17 +721,17 @@ bool CScore::ShowTeamRankThread(IDbConnection *pSqlServer, const ISqlData *pGame str_format(aBuf, sizeof(aBuf), "SELECT l.ID, Name, Time, Rank " "FROM (" // teamrank score board - "SELECT RANK() OVER w AS Rank, ID " - "FROM %s_teamrace " - "WHERE Map = ? " - "GROUP BY ID " - "WINDOW w AS (ORDER BY Time)" + " SELECT RANK() OVER w AS Rank, ID " + " FROM %s_teamrace " + " WHERE Map = ? " + " GROUP BY ID " + " WINDOW w AS (ORDER BY Time)" ") AS TeamRank INNER JOIN (" // select rank with Name in team - "SELECT ID " - "FROM %s_teamrace " - "WHERE Map = ? AND Name = ? " - "ORDER BY Time " - "LIMIT 1" + " SELECT ID " + " FROM %s_teamrace " + " WHERE Map = ? AND Name = ? " + " ORDER BY Time " + " LIMIT 1" ") AS l ON TeamRank.ID = l.ID " "INNER JOIN %s_teamrace AS r ON l.ID = r.ID ", pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); @@ -799,11 +799,11 @@ bool CScore::ShowTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGameData str_format(aBuf, sizeof(aBuf), "SELECT Name, Time, Rank " "FROM (" - "SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " - "FROM %s_race " - "WHERE Map = ? " - "GROUP BY Name " - "WINDOW w AS (ORDER BY Time)" + " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " + " FROM %s_race " + " WHERE Map = ? " + " GROUP BY Name " + " WINDOW w AS (ORDER BY Time)" ") as a " "ORDER BY Rank %s " "LIMIT %d, 5;", @@ -856,16 +856,16 @@ bool CScore::ShowTeamTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGame str_format(aBuf, sizeof(aBuf), "SELECT Name, Time, Rank, TeamSize " "FROM (" // limit to 5 - "SELECT TeamSize, Rank, ID " - "FROM (" // teamrank score board - "SELECT RANK() OVER w AS Rank, ID, COUNT(*) AS Teamsize " - "FROM %s_teamrace " - "WHERE Map = ? " - "GROUP BY Id " - "WINDOW w AS (ORDER BY Time)" - ") as l1 " - "ORDER BY Rank %s " - "LIMIT %d, 5" + " SELECT TeamSize, Rank, ID " + " FROM (" // teamrank score board + " SELECT RANK() OVER w AS Rank, ID, COUNT(*) AS Teamsize " + " FROM %s_teamrace " + " WHERE Map = ? " + " GROUP BY Id " + " WINDOW w AS (ORDER BY Time)" + " ) as l1 " + " ORDER BY Rank %s " + " LIMIT %d, 5" ") as l2 " "INNER JOIN %s_teamrace as r ON l2.ID = r.ID " "ORDER BY Rank %s, r.ID, Name ASC;", @@ -1045,8 +1045,8 @@ bool CScore::ShowPointsThread(IDbConnection *pSqlServer, const ISqlData *pGameDa char aBuf[512]; str_format(aBuf, sizeof(aBuf), "SELECT (" - "SELECT COUNT(Name) + 1 FROM %s_points WHERE Points > (" - "SELECT points FROM %s_points WHERE Name = ?" + " SELECT COUNT(Name) + 1 FROM %s_points WHERE Points > (" + " SELECT points FROM %s_points WHERE Name = ?" ")) as Rank, Points, Name " "FROM %s_points WHERE Name = ?;", pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); @@ -1094,9 +1094,9 @@ bool CScore::ShowTopPointsThread(IDbConnection *pSqlServer, const ISqlData *pGam str_format(aBuf, sizeof(aBuf), "SELECT Rank, Points, Name " "FROM (" - "SELECT RANK() OVER w AS Rank, Points, Name " - "FROM %s_points " - "WINDOW w as (ORDER BY Points DESC)" + " SELECT RANK() OVER w AS Rank, Points, Name " + " FROM %s_points " + " WINDOW w as (ORDER BY Points DESC)" ") as a " "ORDER BY Rank %s " "LIMIT ?, 5;", @@ -1203,9 +1203,9 @@ bool CScore::RandomUnfinishedMapThread(IDbConnection *pSqlServer, const ISqlData "SELECT Map " "FROM %s_maps " "WHERE Server = ? AND Map != ? AND Stars = ? AND Map NOT IN (" - "SELECT Map " - "FROM %s_race " - "WHERE Name = ?" + " SELECT Map " + " FROM %s_race " + " WHERE Name = ?" ") ORDER BY RAND() " "LIMIT 1;", pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); @@ -1221,9 +1221,9 @@ bool CScore::RandomUnfinishedMapThread(IDbConnection *pSqlServer, const ISqlData "SELECT Map " "FROM %s_maps AS maps " "WHERE Server = ? AND Map != ? AND Map NOT IN (" - "SELECT Map " - "FROM %s_race as race " - "WHERE Name = ?" + " SELECT Map " + " FROM %s_race as race " + " WHERE Name = ?" ") ORDER BY RAND() " "LIMIT 1;", pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); diff --git a/src/game/server/teehistorian.cpp b/src/game/server/teehistorian.cpp index d1c620cc1..6d77d614d 100644 --- a/src/game/server/teehistorian.cpp +++ b/src/game/server/teehistorian.cpp @@ -1,15 +1,15 @@ #include "teehistorian.h" #include -#include #include +#include #include static const char TEEHISTORIAN_NAME[] = "teehistorian@ddnet.tw"; static const CUuid TEEHISTORIAN_UUID = CalculateUuid(TEEHISTORIAN_NAME); static const char TEEHISTORIAN_VERSION[] = "2"; -#define UUID(id, name) static const CUuid UUID_ ## id = CalculateUuid(name); +#define UUID(id, name) static const CUuid UUID_##id = CalculateUuid(name); #include #undef UUID @@ -84,7 +84,7 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) char aJson[2048]; - #define E(buf, str) EscapeJson(buf, sizeof(buf), str) +#define E(buf, str) EscapeJson(buf, sizeof(buf), str) str_format(aJson, sizeof(aJson), "{\"comment\":\"%s\",\"version\":\"%s\",\"game_uuid\":\"%s\",\"server_version\":\"%s\",\"start_time\":\"%s\",\"server_name\":\"%s\",\"server_port\":\"%d\",\"game_type\":\"%s\",\"map_name\":\"%s\",\"map_size\":\"%d\",\"map_sha256\":\"%s\",\"map_crc\":\"%08x\",\"prng_description\":\"%s\",\"config\":{", E(aCommentBuffer, TEEHISTORIAN_NAME), @@ -106,7 +106,7 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) char aBuffer2[1024]; bool First = true; - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ +#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \ if((Flags)&CFGFLAG_SERVER && !((Flags)&CFGFLAG_NONTEEHISTORIC) && pGameInfo->m_pConfig->m_##Name != (Def)) \ { \ str_format(aJson, sizeof(aJson), "%s\"%s\":\"%d\"", \ @@ -117,9 +117,9 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) First = false; \ } - #define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) MACRO_CONFIG_INT(Name,ScriptName,Def,0,0,Save,Desc) +#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) MACRO_CONFIG_INT(Name, ScriptName, Def, 0, 0, Save, Desc) - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ +#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \ if((Flags)&CFGFLAG_SERVER && !((Flags)&CFGFLAG_NONTEEHISTORIC) && str_comp(pGameInfo->m_pConfig->m_##Name, (Def)) != 0) \ { \ str_format(aJson, sizeof(aJson), "%s\"%s\":\"%s\"", \ @@ -130,11 +130,11 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) First = false; \ } - #include +#include - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR str_format(aJson, sizeof(aJson), "},\"tuning\":{"); Write(aJson, str_length(aJson)); @@ -142,7 +142,7 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) First = true; static const float TicksPerSecond = 50.0f; - #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) \ +#define MACRO_TUNING_PARAM(Name, ScriptName, Value, Description) \ if(pGameInfo->m_pTuning->m_##Name.Get() != (int)((Value)*100)) \ { \ str_format(aJson, sizeof(aJson), "%s\"%s\":\"%d\"", \ @@ -152,8 +152,8 @@ void CTeeHistorian::WriteHeader(const CGameInfo *pGameInfo) Write(aJson, str_length(aJson)); \ First = false; \ } - #include - #undef MACRO_TUNING_PARAM +#include +#undef MACRO_TUNING_PARAM str_format(aJson, sizeof(aJson), "},\"uuids\":["); Write(aJson, str_length(aJson)); @@ -184,7 +184,6 @@ void CTeeHistorian::WriteExtra(CUuid Uuid, const void *pData, int DataSize) Write(pData, DataSize); } - void CTeeHistorian::BeginTick(int Tick) { dbg_assert(m_State == STATE_START || m_State == STATE_BEFORE_TICK, "invalid teehistorian state"); diff --git a/src/test/teehistorian.cpp b/src/test/teehistorian.cpp index 14b464a31..412fdb437 100644 --- a/src/test/teehistorian.cpp +++ b/src/test/teehistorian.cpp @@ -49,8 +49,7 @@ protected: 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, - 0x01, 0x23, - }}; + 0x01, 0x23}}; mem_zero(&m_GameInfo, sizeof(m_GameInfo)); @@ -349,8 +348,7 @@ TEST_F(TeeHistorian, DDNetVersion) }; CUuid ConnectionID = { 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, - 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b, - }; + 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b}; m_TH.RecordDDNetVersion(0, ConnectionID, 13010, "DDNet 13.1 (3623f5e4cd184556)"); m_TH.RecordDDNetVersionOld(1, 13010); Finish(); @@ -456,8 +454,7 @@ TEST_F(TeeHistorian, SaveSuccess) CUuid SaveID = { 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, - 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b, - }; + 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b}; const char *pTeamSave = "2\tH.\nll0"; m_TH.RecordTeamSaveSuccess(21, SaveID, pTeamSave); Finish(); @@ -503,8 +500,7 @@ TEST_F(TeeHistorian, LoadSuccess) CUuid SaveID = { 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, - 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b, - }; + 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b}; const char *pTeamSave = "2\tH.\nll0"; m_TH.RecordTeamLoadSuccess(21, SaveID, pTeamSave); Finish(); diff --git a/src/tools/crapnet.cpp b/src/tools/crapnet.cpp index 97b7efb37..0ad63a4f8 100644 --- a/src/tools/crapnet.cpp +++ b/src/tools/crapnet.cpp @@ -31,7 +31,7 @@ struct CPingConfig }; static CPingConfig m_aConfigPings[] = { -// base flux spike loss delay delayfreq + // base flux spike loss delay delayfreq {0, 0, 0, 0, 0, 0}, {40, 20, 100, 0, 0, 0}, {140, 40, 200, 0, 0, 0}, From 2d8a1ee2b73eeec50f8b4badf0a895ff7982b165 Mon Sep 17 00:00:00 2001 From: def Date: Fri, 25 Sep 2020 18:44:40 +0200 Subject: [PATCH 2/7] Make fix_style.py look at files, not lines --- scripts/fix_style.py | 57 +++++++++++++------------------------------- 1 file changed, 16 insertions(+), 41 deletions(-) diff --git a/scripts/fix_style.py b/scripts/fix_style.py index b1e292248..0bc1df8c3 100755 --- a/scripts/fix_style.py +++ b/scripts/fix_style.py @@ -5,42 +5,26 @@ import re import subprocess import sys -RE_POSITION=re.compile(rb"^@@ -[0-9]+,[0-9]+ \+(?P[0-9]+),(?P[0-9]+) @@") -def get_line_ranges(git_diff): - new_filename = None - result = defaultdict(list) - for line in git_diff.splitlines(): - if line.startswith(b"+++ "): - new_filename = line[6:].decode() - continue - match = RE_POSITION.match(line) - if match: - start = int(match.group("start").decode()) - end = start + int(match.group("len").decode()) - 1 - result[new_filename].append((start, end)) - continue - return dict(result) - -def git_get_changed_lines(margin, base): - return get_line_ranges(subprocess.check_output([ +def git_get_changed_files(margin, base): + return subprocess.check_output([ "git", "diff", base, - "--unified={}".format(margin), - ])) + "--name-only", + ]).decode().splitlines() -def filter_cpp(changed_lines): - return {filename: changed_lines[filename] for filename in changed_lines - if any(filename.endswith(ext) for ext in ".c .cpp .h".split())} +def filter_cpp(changed_files): + return [filename for filename in changed_files + if any(filename.endswith(ext) for ext in ".c .cpp .h".split())] -def reformat(changed_lines): - for filename in changed_lines: - subprocess.check_call(["clang-format", "-i"] + ["--lines={}:{}".format(start, end) for start, end in changed_lines[filename]] + [filename]) +def reformat(changed_files): + for filename in changed_files: + subprocess.check_call(["clang-format", "-i", filename]) -def warn(changed_lines): +def warn(changed_files): result = 0 - for filename in changed_lines: - result = subprocess.call(["clang-format", "-Werror", "--dry-run"] + ["--lines={}:{}".format(start, end) for start, end in changed_lines[filename]] + [filename]) or result + for filename in changed_files: + result = subprocess.call(["clang-format", "-Werror", "--dry-run", filename]) or result return result def get_common_base(base): @@ -48,23 +32,14 @@ def get_common_base(base): def main(): import argparse - p = argparse.ArgumentParser(description="Check and fix style of changed lines") + p = argparse.ArgumentParser(description="Check and fix style of changed files") p.add_argument("--base", default="HEAD", help="Revision to compare to") p.add_argument("-n", "--dry-run", action="store_true", help="Don't fix, only warn") args = p.parse_args() if not args.dry_run: - last_ranges = None - ranges = filter_cpp(git_get_changed_lines(1, base=args.base)) - i = 0 - while last_ranges != ranges: - print("Iteration {}".format(i)) - reformat(ranges) - last_ranges = ranges - ranges = filter_cpp(git_get_changed_lines(1, base=args.base)) - i += 1 - print("Done after {} iterations".format(i)) + reformat(filter_cpp(git_get_changed_files(1, base=args.base))) else: - sys.exit(warn(filter_cpp(git_get_changed_lines(1, base=args.base)))) + sys.exit(warn(filter_cpp(git_get_changed_files(1, base=args.base)))) if __name__ == "__main__": main() From 678b2b15c39abd483cfe215cd749ea55e6206159 Mon Sep 17 00:00:00 2001 From: heinrich5991 Date: Sat, 26 Sep 2020 00:58:58 +0200 Subject: [PATCH 3/7] Change fix_style.py script to unconditionally format everything --- .github/workflows/style.yml | 2 +- scripts/fix_style.py | 42 ++++++++++++++++--------------------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index a883caaa3..62d2ba419 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -23,5 +23,5 @@ jobs: - name: Check style run: | clang-format -version - scripts/fix_style.py --dry-run --base origin/master + scripts/fix_style.py --dry-run scripts/check_header_guards.py diff --git a/scripts/fix_style.py b/scripts/fix_style.py index 0bc1df8c3..31dcf66f2 100755 --- a/scripts/fix_style.py +++ b/scripts/fix_style.py @@ -1,45 +1,39 @@ #!/usr/bin/env python3 from collections import defaultdict +import os import re import subprocess import sys -def git_get_changed_files(margin, base): - return subprocess.check_output([ - "git", - "diff", - base, - "--name-only", - ]).decode().splitlines() +os.chdir(os.path.dirname(__file__) + "/..") -def filter_cpp(changed_files): - return [filename for filename in changed_files - if any(filename.endswith(ext) for ext in ".c .cpp .h".split())] - -def reformat(changed_files): - for filename in changed_files: - subprocess.check_call(["clang-format", "-i", filename]) - -def warn(changed_files): - result = 0 - for filename in changed_files: - result = subprocess.call(["clang-format", "-Werror", "--dry-run", filename]) or result +def recursive_file_list(path): + result = [] + for dirpath, dirnames, filenames in os.walk(path): + result += [os.path.join(dirpath, filename) for filename in filenames] return result -def get_common_base(base): - return subprocess.check_output(["git", "merge-base", "HEAD", base]).decode().strip() +def filter_cpp(filenames): + return [filename for filename in filenames + if any(filename.endswith(ext) for ext in ".c .cpp .h".split())] + +def reformat(filenames): + subprocess.check_call(["clang-format", "-i"] + filenames) + +def warn(filenames): + return subprocess.call(["clang-format", "-Werror", "--dry-run"] + filenames) def main(): import argparse p = argparse.ArgumentParser(description="Check and fix style of changed files") - p.add_argument("--base", default="HEAD", help="Revision to compare to") p.add_argument("-n", "--dry-run", action="store_true", help="Don't fix, only warn") args = p.parse_args() + filenames = filter_cpp(recursive_file_list("src")) if not args.dry_run: - reformat(filter_cpp(git_get_changed_files(1, base=args.base))) + reformat(filenames) else: - sys.exit(warn(filter_cpp(git_get_changed_files(1, base=args.base)))) + sys.exit(warn(filenames)) if __name__ == "__main__": main() From 2e8e19290e017179ecec08bea97d3157f3301c61 Mon Sep 17 00:00:00 2001 From: def Date: Sat, 26 Sep 2020 21:49:35 +0200 Subject: [PATCH 4/7] fix_style.py: Ignore generated key headers --- scripts/fix_style.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/fix_style.py b/scripts/fix_style.py index 31dcf66f2..27e69780a 100755 --- a/scripts/fix_style.py +++ b/scripts/fix_style.py @@ -8,10 +8,12 @@ import sys os.chdir(os.path.dirname(__file__) + "/..") +ignore_files = ["src/engine/keys.h", "src/engine/client/keynames.h"] + def recursive_file_list(path): result = [] for dirpath, dirnames, filenames in os.walk(path): - result += [os.path.join(dirpath, filename) for filename in filenames] + result += filter(lambda p: p not in ignore_files, [os.path.join(dirpath, filename) for filename in filenames]) return result def filter_cpp(filenames): From 3be8a592e52a03e555b6aa29a8dea529797bb645 Mon Sep 17 00:00:00 2001 From: def Date: Sat, 26 Sep 2020 21:41:58 +0200 Subject: [PATCH 5/7] Run clang-format Purely automatic change. In case of conflict with this change, apply the other change and rerun the formatting to restore it: $ python scripts/fix_style.py --- src/antibot/antibot_data.h | 27 +- src/antibot/antibot_interface.h | 4 +- src/antibot/antibot_null.cpp | 10 +- src/base/color.h | 60 +- src/base/detect.h | 166 ++- src/base/dynamic.h | 1 - src/base/hash.h | 8 +- src/base/hash_bundled.c | 8 +- src/base/hash_ctxt.h | 8 +- src/base/hash_libtomcrypt.c | 264 ++-- src/base/math.h | 69 +- src/base/system.c | 503 +++---- src/base/system.h | 48 +- src/base/tl/algorithm.h | 18 +- src/base/tl/allocator.h | 6 +- src/base/tl/array.h | 61 +- src/base/tl/base.h | 2 +- src/base/tl/range.h | 120 +- src/base/tl/sorted_array.h | 21 +- src/base/tl/string.h | 25 +- src/base/tl/threading.h | 8 +- src/base/unicode/confusables_data.h | 4 +- src/base/unicode/tolower.c | 20 +- src/base/unicode/tolower_data.h | 2 +- src/base/vmath.h | 276 +++- src/engine/antibot.h | 4 +- src/engine/client.h | 28 +- src/engine/client/backend_sdl.cpp | 676 +++++----- src/engine/client/backend_sdl.h | 136 +- src/engine/client/client.cpp | 397 +++--- src/engine/client/client.h | 17 +- src/engine/client/demoedit.cpp | 2 +- src/engine/client/friends.cpp | 8 +- src/engine/client/graphics_threaded.cpp | 390 +++--- src/engine/client/graphics_threaded.h | 150 ++- src/engine/client/http.cpp | 30 +- src/engine/client/http.h | 15 +- src/engine/client/opengl_sl.cpp | 45 +- src/engine/client/opengl_sl.h | 20 +- src/engine/client/opengl_sl_program.cpp | 27 +- src/engine/client/opengl_sl_program.h | 61 +- src/engine/client/serverbrowser.cpp | 150 ++- src/engine/client/serverbrowser.h | 16 +- src/engine/client/sound.cpp | 194 ++- src/engine/client/steam.cpp | 8 +- src/engine/client/text.cpp | 223 ++-- src/engine/client/updater.cpp | 82 +- src/engine/client/updater.h | 26 +- src/engine/client/video.cpp | 211 ++- src/engine/client/video.h | 77 +- src/engine/console.h | 21 +- src/engine/demo.h | 13 +- src/engine/editor.h | 1 - src/engine/friends.h | 4 +- src/engine/graphics.h | 58 +- src/engine/kernel.h | 13 +- src/engine/map.h | 3 +- src/engine/masterserver.h | 3 +- src/engine/message.h | 3 +- src/engine/server.h | 40 +- src/engine/server/antibot.cpp | 119 +- src/engine/server/antibot.h | 1 + src/engine/server/authmanager.cpp | 2 +- src/engine/server/authmanager.h | 1 + src/engine/server/databases/connection.cpp | 116 +- src/engine/server/databases/connection.h | 2 +- .../server/databases/connection_pool.cpp | 60 +- src/engine/server/databases/connection_pool.h | 18 +- src/engine/server/databases/mysql.cpp | 52 +- src/engine/server/databases/mysql.h | 16 +- src/engine/server/databases/sqlite.cpp | 24 +- src/engine/server/name_ban.h | 4 +- src/engine/server/register.cpp | 24 +- src/engine/server/register.h | 2 +- src/engine/server/server.cpp | 374 +++--- src/engine/server/server.h | 53 +- src/engine/server/sql_string_helpers.cpp | 45 +- src/engine/server/sql_string_helpers.h | 5 +- src/engine/server/upnp.cpp | 17 +- src/engine/server/upnp.h | 2 +- src/engine/serverbrowser.h | 16 +- src/engine/shared/compression.cpp | 39 +- src/engine/shared/config.cpp | 51 +- src/engine/shared/config.h | 38 +- src/engine/shared/console.cpp | 160 ++- src/engine/shared/console.h | 28 +- src/engine/shared/datafile.cpp | 138 +- src/engine/shared/datafile.h | 14 +- src/engine/shared/demo.cpp | 180 ++- src/engine/shared/demo.h | 7 +- src/engine/shared/econ.cpp | 9 +- src/engine/shared/econ.h | 7 +- src/engine/shared/engine.cpp | 15 +- src/engine/shared/fifo.cpp | 12 +- src/engine/shared/filecollection.cpp | 116 +- src/engine/shared/filecollection.h | 4 +- src/engine/shared/ghost.cpp | 40 +- src/engine/shared/ghost.h | 6 +- src/engine/shared/huffman.cpp | 36 +- src/engine/shared/huffman.h | 11 +- src/engine/shared/jobs.cpp | 1 - src/engine/shared/jobs.h | 4 +- src/engine/shared/json.cpp | 44 +- src/engine/shared/json.h | 12 +- src/engine/shared/kernel.cpp | 6 +- src/engine/shared/linereader.cpp | 6 +- src/engine/shared/linereader.h | 3 +- src/engine/shared/masterserver.cpp | 4 +- src/engine/shared/memheap.cpp | 8 +- src/engine/shared/memheap.h | 3 +- src/engine/shared/netban.cpp | 77 +- src/engine/shared/netban.h | 43 +- src/engine/shared/network.cpp | 110 +- src/engine/shared/network.h | 83 +- src/engine/shared/network_client.cpp | 18 +- src/engine/shared/network_conn.cpp | 62 +- src/engine/shared/network_console.cpp | 3 +- src/engine/shared/network_console_conn.cpp | 46 +- src/engine/shared/network_server.cpp | 131 +- src/engine/shared/packer.cpp | 13 +- src/engine/shared/packer.h | 15 +- src/engine/shared/protocol.h | 71 +- src/engine/shared/protocol_ex.cpp | 42 +- src/engine/shared/protocol_ex.h | 22 +- src/engine/shared/protocol_ex_msgs.h | 12 +- src/engine/shared/ringbuffer.cpp | 21 +- src/engine/shared/ringbuffer.h | 17 +- src/engine/shared/serverbrowser.cpp | 31 +- src/engine/shared/snapshot.cpp | 85 +- src/engine/shared/snapshot.h | 29 +- src/engine/shared/storage.cpp | 32 +- src/engine/shared/teehistorian_ex.cpp | 6 +- src/engine/shared/teehistorian_ex.h | 8 +- src/engine/shared/teehistorian_ex_chunks.h | 14 +- src/engine/shared/uuid_manager.cpp | 10 +- src/engine/shared/uuid_manager.h | 7 +- src/engine/shared/video.cpp | 2 +- src/engine/shared/video.h | 8 +- src/engine/sound.h | 20 +- src/engine/storage.h | 3 +- src/engine/textrender.h | 22 +- src/game/bezier.cpp | 9 +- src/game/bezier.h | 1 + src/game/client/animstate.cpp | 17 +- src/game/client/component.h | 34 +- src/game/client/components/background.cpp | 14 +- src/game/client/components/binds.cpp | 35 +- src/game/client/components/binds.h | 5 +- src/game/client/components/broadcast.cpp | 26 +- src/game/client/components/camera.cpp | 6 +- src/game/client/components/camera.h | 1 + src/game/client/components/console.cpp | 4 +- src/game/client/components/console.h | 6 +- src/game/client/components/controls.cpp | 230 ++-- src/game/client/components/controls.h | 2 +- src/game/client/components/countryflags.cpp | 15 +- src/game/client/components/countryflags.h | 8 +- src/game/client/components/damageind.cpp | 24 +- src/game/client/components/damageind.h | 3 +- src/game/client/components/debughud.cpp | 68 +- src/game/client/components/debughud.h | 1 + src/game/client/components/effects.cpp | 94 +- src/game/client/components/effects.h | 1 + src/game/client/components/emoticon.cpp | 64 +- src/game/client/components/flow.cpp | 28 +- src/game/client/components/flow.h | 1 + src/game/client/components/ghost.cpp | 21 +- src/game/client/components/ghost.h | 6 +- src/game/client/components/hud.cpp | 210 ++- src/game/client/components/hud.h | 4 +- src/game/client/components/items.cpp | 127 +- src/game/client/components/items.h | 3 +- src/game/client/components/killmessages.cpp | 45 +- src/game/client/components/killmessages.h | 1 + src/game/client/components/mapimages.cpp | 35 +- src/game/client/components/mapimages.h | 2 +- src/game/client/components/maplayers.cpp | 456 +++---- src/game/client/components/maplayers.h | 46 +- src/game/client/components/mapsounds.cpp | 61 +- src/game/client/components/mapsounds.h | 2 +- .../client/components/menu_background.cpp | 4 +- src/game/client/components/menu_background.h | 4 +- src/game/client/components/menus.h | 32 +- src/game/client/components/menus_browser.cpp | 207 +-- src/game/client/components/menus_demo.cpp | 284 ++-- src/game/client/components/menus_ingame.cpp | 171 ++- src/game/client/components/menus_settings.cpp | 283 ++-- src/game/client/components/motd.cpp | 26 +- src/game/client/components/motd.h | 1 + src/game/client/components/nameplates.cpp | 53 +- src/game/client/components/nameplates.h | 10 +- src/game/client/components/particles.cpp | 40 +- src/game/client/components/particles.h | 10 +- src/game/client/components/players.cpp | 186 ++- src/game/client/components/players.h | 7 +- src/game/client/components/race_demo.cpp | 11 +- src/game/client/components/scoreboard.cpp | 189 +-- src/game/client/components/scoreboard.h | 1 - src/game/client/components/skins.cpp | 49 +- src/game/client/components/sounds.cpp | 22 +- src/game/client/components/sounds.h | 3 +- src/game/client/components/spectator.cpp | 69 +- src/game/client/components/spectator.h | 2 +- src/game/client/components/statboard.cpp | 137 +- src/game/client/components/statboard.h | 40 +- src/game/client/components/voting.cpp | 33 +- src/game/client/components/voting.h | 4 +- src/game/client/gameclient.cpp | 334 +++-- src/game/client/gameclient.h | 35 +- src/game/client/lineinput.cpp | 25 +- src/game/client/lineinput.h | 7 +- .../client/prediction/entities/character.cpp | 435 +++--- .../client/prediction/entities/character.h | 17 +- src/game/client/prediction/entities/laser.cpp | 32 +- src/game/client/prediction/entities/laser.h | 1 + .../client/prediction/entities/pickup.cpp | 100 +- .../client/prediction/entities/projectile.cpp | 126 +- .../client/prediction/entities/projectile.h | 9 +- src/game/client/prediction/entity.cpp | 12 +- src/game/client/prediction/entity.h | 25 +- src/game/client/prediction/gameworld.cpp | 103 +- src/game/client/prediction/gameworld.h | 1 + src/game/client/race.cpp | 14 +- src/game/client/render.cpp | 258 ++-- src/game/client/render.h | 35 +- src/game/client/render_map.cpp | 642 +++++---- src/game/client/ui.cpp | 51 +- src/game/client/ui.h | 38 +- src/game/collision.cpp | 375 +++--- src/game/collision.h | 10 +- src/game/ddracecommands.h | 60 +- src/game/editor/auto_map.cpp | 116 +- src/game/editor/auto_map.h | 13 +- src/game/editor/editor.cpp | 1093 ++++++++------- src/game/editor/editor.h | 99 +- src/game/editor/io.cpp | 202 +-- src/game/editor/layer_game.cpp | 35 +- src/game/editor/layer_quads.cpp | 44 +- src/game/editor/layer_sounds.cpp | 63 +- src/game/editor/layer_tiles.cpp | 1179 ++++++++--------- src/game/editor/popups.cpp | 429 +++--- src/game/extrainfo.cpp | 32 +- src/game/gamecore.cpp | 125 +- src/game/gamecore.h | 98 +- src/game/layers.cpp | 33 +- src/game/layers.h | 1 - src/game/localization.cpp | 2 +- src/game/localization.h | 2 +- src/game/mapbugs.cpp | 12 +- src/game/mapitems.h | 41 +- src/game/mapitems_ex.cpp | 6 +- src/game/mapitems_ex.h | 29 +- src/game/mapitems_ex_types.h | 2 +- src/game/prng.cpp | 1 - src/game/server/ddracechat.cpp | 718 +++++----- src/game/server/ddracechat.h | 24 +- src/game/server/ddracecommands.cpp | 247 ++-- src/game/server/entities/character.cpp | 707 +++++----- src/game/server/entities/character.h | 20 +- src/game/server/entities/door.cpp | 48 +- src/game/server/entities/door.h | 4 +- src/game/server/entities/dragger.cpp | 131 +- src/game/server/entities/dragger.h | 16 +- src/game/server/entities/flag.cpp | 2 +- src/game/server/entities/gun.cpp | 57 +- src/game/server/entities/gun.h | 2 +- src/game/server/entities/laser.cpp | 63 +- src/game/server/entities/light.cpp | 69 +- src/game/server/entities/light.h | 6 +- src/game/server/entities/pickup.cpp | 153 +-- src/game/server/entities/pickup.h | 1 - src/game/server/entities/plasma.cpp | 60 +- src/game/server/entities/plasma.h | 6 +- src/game/server/entities/projectile.cpp | 217 ++- src/game/server/entities/projectile.h | 7 +- src/game/server/entity.cpp | 28 +- src/game/server/entity.h | 26 +- src/game/server/eventhandler.cpp | 2 +- src/game/server/eventhandler.h | 3 +- src/game/server/gamecontext.cpp | 564 ++++---- src/game/server/gamecontext.h | 51 +- src/game/server/gamecontroller.cpp | 169 ++- src/game/server/gamecontroller.h | 4 +- src/game/server/gamemodes/DDRace.cpp | 22 +- src/game/server/gamemodes/DDRace.h | 11 +- src/game/server/gameworld.cpp | 100 +- src/game/server/gameworld.h | 1 - src/game/server/player.cpp | 137 +- src/game/server/player.h | 12 +- src/game/server/save.cpp | 362 +++-- src/game/server/save.h | 31 +- src/game/server/score.cpp | 571 ++++---- src/game/server/score.h | 67 +- src/game/server/teams.cpp | 313 +++-- src/game/server/teams.h | 31 +- src/game/server/teehistorian.h | 2 +- src/game/server/teeinfo.cpp | 38 +- src/game/server/teeinfo.h | 30 +- src/game/teamscore.cpp | 10 +- src/game/teamscore.h | 5 +- src/game/tuning.h | 2 +- src/game/variables.h | 196 +-- src/game/voting.h | 8 +- src/mastersrv/mastersrv.cpp | 95 +- src/mastersrv/mastersrv.h | 3 +- src/steam/steam_api_flat.h | 14 +- src/steam/steam_api_stub.cpp | 4 +- src/test/color.cpp | 32 +- src/test/csv.cpp | 31 +- src/test/hash.cpp | 54 +- src/test/jobs.cpp | 13 +- src/test/packer.cpp | 4 +- src/test/prng.cpp | 7 +- src/test/str.cpp | 46 +- src/test/teehistorian.cpp | 97 +- src/tools/crapnet.cpp | 43 +- src/tools/fake_server.cpp | 42 +- src/tools/map_convert_07.cpp | 18 +- src/tools/map_diff.cpp | 14 +- src/tools/map_extract.cpp | 17 +- src/tools/map_replace_image.cpp | 16 +- src/tools/packetgen.cpp | 9 +- src/twping/twping.cpp | 12 +- 323 files changed, 12202 insertions(+), 11628 deletions(-) mode change 100755 => 100644 src/base/hash_libtomcrypt.c diff --git a/src/antibot/antibot_data.h b/src/antibot/antibot_data.h index 02d9b3978..637c1b5de 100644 --- a/src/antibot/antibot_data.h +++ b/src/antibot/antibot_data.h @@ -6,12 +6,12 @@ enum { - ANTIBOT_ABI_VERSION=3, + ANTIBOT_ABI_VERSION = 3, - ANTIBOT_MSGFLAG_NONVITAL=1, - ANTIBOT_MSGFLAG_FLUSH=2, + ANTIBOT_MSGFLAG_NONVITAL = 1, + ANTIBOT_MSGFLAG_FLUSH = 2, - ANTIBOT_MAX_CLIENTS=64, + ANTIBOT_MAX_CLIENTS = 64, }; struct CAntibotMapData @@ -64,15 +64,16 @@ struct CAntibotVersion int m_SizeRoundData; }; -#define ANTIBOT_VERSION { \ - ANTIBOT_ABI_VERSION, \ - sizeof(CAntibotVersion), \ - sizeof(CAntibotData), \ - sizeof(CAntibotCharacterData), \ - sizeof(CAntibotInputData), \ - sizeof(CAntibotMapData), \ - sizeof(CAntibotRoundData), \ -} +#define ANTIBOT_VERSION \ + { \ + ANTIBOT_ABI_VERSION, \ + sizeof(CAntibotVersion), \ + sizeof(CAntibotData), \ + sizeof(CAntibotCharacterData), \ + sizeof(CAntibotInputData), \ + sizeof(CAntibotMapData), \ + sizeof(CAntibotRoundData), \ + } struct CAntibotData { diff --git a/src/antibot/antibot_interface.h b/src/antibot/antibot_interface.h index 0f9af519a..451a13058 100644 --- a/src/antibot/antibot_interface.h +++ b/src/antibot/antibot_interface.h @@ -2,8 +2,7 @@ #define ANTIBOT_ANTIBOT_INTERFACE_H #include "antibot_data.h" -extern "C" -{ +extern "C" { int AntibotAbiVersion(); void AntibotInit(CAntibotData *pCallbackData); @@ -25,7 +24,6 @@ void AntibotOnEngineTick(void); void AntibotOnEngineClientJoin(int ClientID, bool Sixup); void AntibotOnEngineClientDrop(int ClientID, const char *pReason); void AntibotOnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags); - } #endif // ANTIBOT_ANTIBOT_INTERFACE_H diff --git a/src/antibot/antibot_null.cpp b/src/antibot/antibot_null.cpp index 00d3cde43..fb6b9f1b0 100644 --- a/src/antibot/antibot_null.cpp +++ b/src/antibot/antibot_null.cpp @@ -2,8 +2,7 @@ static CAntibotData *g_pData; -extern "C" -{ +extern "C" { int AntibotAbiVersion() { @@ -14,9 +13,9 @@ void AntibotInit(CAntibotData *pData) g_pData = pData; g_pData->m_pfnLog("null antibot initialized", g_pData->m_pUser); } -void AntibotRoundStart(CAntibotRoundData *pRoundData) { }; -void AntibotRoundEnd(void) { }; -void AntibotUpdateData(void) { } +void AntibotRoundStart(CAntibotRoundData *pRoundData){}; +void AntibotRoundEnd(void){}; +void AntibotUpdateData(void) {} void AntibotDestroy(void) { g_pData = 0; } void AntibotDump(void) { @@ -35,5 +34,4 @@ void AntibotOnEngineTick(void) {} void AntibotOnEngineClientJoin(int /*ClientID*/, bool /*Sixup*/) {} void AntibotOnEngineClientDrop(int /*ClientID*/, const char * /*pReason*/) {} void AntibotOnEngineClientMessage(int /*ClientID*/, const void * /*pData*/, int /*Size*/, int /*Flags*/) {} - } diff --git a/src/base/color.h b/src/base/color.h index dff296861..845ee58a8 100644 --- a/src/base/color.h +++ b/src/base/color.h @@ -33,14 +33,26 @@ inline float RgbToHue(float r, float g, float b) } // Curiously Recurring Template Pattern for type safety -template +template class color4_base { public: - union { float x, r, h; }; - union { float y, g, s; }; - union { float z, b, l, v; }; - union { float w, a; }; + union + { + float x, r, h; + }; + union + { + float y, g, s; + }; + union + { + float z, b, l, v; + }; + union + { + float w, a; + }; color4_base() {} @@ -93,7 +105,7 @@ public: DerivedT WithAlpha(float alpha) { - DerivedT col(static_cast(*this)); + DerivedT col(static_cast(*this)); col.a = alpha; return col; } @@ -103,7 +115,7 @@ class ColorHSLA : public color4_base { public: using color4_base::color4_base; - ColorHSLA() {}; + ColorHSLA(){}; constexpr static const float DARKEST_LGT = 0.5f; @@ -122,7 +134,7 @@ public: unsigned Pack(float Darkest, bool Alpha = false) { ColorHSLA col = *this; - col.l = (l - Darkest)/(1 - Darkest); + col.l = (l - Darkest) / (1 - Darkest); col.l = clamp(col.l, 0.0f, 1.0f); return col.Pack(Alpha); } @@ -132,19 +144,20 @@ class ColorHSVA : public color4_base { public: using color4_base::color4_base; - ColorHSVA() {}; + ColorHSVA(){}; }; class ColorRGBA : public color4_base { public: using color4_base::color4_base; - ColorRGBA() {}; + ColorRGBA(){}; }; -template T color_cast(const F &f) = delete; +template +T color_cast(const F &f) = delete; -template <> +template<> inline ColorHSLA color_cast(const ColorRGBA &rgb) { float Min = minimum(rgb.r, rgb.g, rgb.b); @@ -153,12 +166,12 @@ inline ColorHSLA color_cast(const ColorRGBA &rgb) float c = Max - Min; float h = RgbToHue(rgb.r, rgb.g, rgb.b); float l = 0.5f * (Max + Min); - float s = (Max != 0.0f && Min != 1.0f) ? (c/(1 - (absolute(2 * l - 1)))) : 0; + float s = (Max != 0.0f && Min != 1.0f) ? (c / (1 - (absolute(2 * l - 1)))) : 0; return ColorHSLA(h, s, l, rgb.a); } -template <> +template<> inline ColorRGBA color_cast(const ColorHSLA &hsl) { vec3 rgb = vec3(0, 0, 0); @@ -167,7 +180,8 @@ inline ColorRGBA color_cast(const ColorHSLA &hsl) float c = (1 - absolute(2 * hsl.l - 1)) * hsl.s; float x = c * (1 - absolute(fmod(h1, 2) - 1)); - switch(round_truncate(h1)) { + switch(round_truncate(h1)) + { case 0: rgb.r = c, rgb.g = x; break; @@ -189,43 +203,43 @@ inline ColorRGBA color_cast(const ColorHSLA &hsl) break; } - float m = hsl.l - (c/2); + float m = hsl.l - (c / 2); return ColorRGBA(rgb.r + m, rgb.g + m, rgb.b + m, hsl.a); } -template <> +template<> inline ColorHSLA color_cast(const ColorHSVA &hsv) { float l = hsv.v * (1 - hsv.s * 0.5f); - return ColorHSLA(hsv.h, (l == 0.0f || l == 1.0f) ? 0 : (hsv.v - l)/minimum(l, 1 - l), l); + return ColorHSLA(hsv.h, (l == 0.0f || l == 1.0f) ? 0 : (hsv.v - l) / minimum(l, 1 - l), l); } -template <> +template<> inline ColorHSVA color_cast(const ColorHSLA &hsl) { float v = hsl.l + hsl.s * minimum(hsl.l, 1 - hsl.l); return ColorHSVA(hsl.h, v == 0.0f ? 0 : 2 - (2 * hsl.l / v), v); } -template <> +template<> inline ColorRGBA color_cast(const ColorHSVA &hsv) { return color_cast(color_cast(hsv)); } -template <> +template<> inline ColorHSVA color_cast(const ColorRGBA &rgb) { return color_cast(color_cast(rgb)); } -template +template T color_scale(const T &col, float s) { return T(col.x * s, col.y * s, col.z * s, col.a * s); } -template +template T color_invert(const T &col) { return T(1.0f - col.x, 1.0f - col.y, 1.0f - col.z, 1.0f - col.a); diff --git a/src/base/detect.h b/src/base/detect.h index 48b263ced..9d32094ca 100644 --- a/src/base/detect.h +++ b/src/base/detect.h @@ -12,144 +12,142 @@ /* windows Family */ #if defined(WIN64) || defined(_WIN64) - /* Hmm, is this IA64 or x86-64? */ - #define CONF_FAMILY_WINDOWS 1 - #define CONF_FAMILY_STRING "windows" - #define CONF_PLATFORM_WIN64 1 - #define PLATFORM_STRING "win64" +/* Hmm, is this IA64 or x86-64? */ +#define CONF_FAMILY_WINDOWS 1 +#define CONF_FAMILY_STRING "windows" +#define CONF_PLATFORM_WIN64 1 +#define PLATFORM_STRING "win64" #elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) - #define CONF_FAMILY_WINDOWS 1 - #define CONF_FAMILY_STRING "windows" - #define CONF_PLATFORM_WIN32 1 - #define PLATFORM_STRING "win32" +#define CONF_FAMILY_WINDOWS 1 +#define CONF_FAMILY_STRING "windows" +#define CONF_PLATFORM_WIN32 1 +#define PLATFORM_STRING "win32" #endif /* unix family */ #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_FREEBSD 1 - #define PLATFORM_STRING "freebsd" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_FREEBSD 1 +#define PLATFORM_STRING "freebsd" #endif #if defined(__NetBSD__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_NETBSD 1 - #define PLATFORM_STRING "netbsd" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_NETBSD 1 +#define PLATFORM_STRING "netbsd" #endif #if defined(__OpenBSD__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_OPENBSD 1 - #define PLATFORM_STRING "openbsd" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_OPENBSD 1 +#define PLATFORM_STRING "openbsd" #endif #if defined(__LINUX__) || defined(__linux__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_LINUX 1 - #define PLATFORM_STRING "linux" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_LINUX 1 +#define PLATFORM_STRING "linux" #endif #if defined(__GNU__) || defined(__gnu__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_HURD 1 - #define PLATFORM_STRING "gnu" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_HURD 1 +#define PLATFORM_STRING "gnu" #endif #if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_MACOSX 1 - #define PLATFORM_STRING "macosx" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_MACOSX 1 +#define PLATFORM_STRING "macosx" #endif #if defined(__sun) - #define CONF_FAMILY_UNIX 1 - #define CONF_FAMILY_STRING "unix" - #define CONF_PLATFORM_SOLARIS 1 - #define PLATFORM_STRING "solaris" +#define CONF_FAMILY_UNIX 1 +#define CONF_FAMILY_STRING "unix" +#define CONF_PLATFORM_SOLARIS 1 +#define PLATFORM_STRING "solaris" #endif /* beos family */ #if defined(__BeOS) || defined(__BEOS__) - #define CONF_FAMILY_BEOS 1 - #define CONF_FAMILY_STRING "beos" - #define CONF_PLATFORM_BEOS 1 - #define PLATFORM_STRING "beos" +#define CONF_FAMILY_BEOS 1 +#define CONF_FAMILY_STRING "beos" +#define CONF_PLATFORM_BEOS 1 +#define PLATFORM_STRING "beos" #endif - /* use gcc endianness definitions when available */ #if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun) - #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) - #include - #else - #include - #endif - - #if __BYTE_ORDER == __LITTLE_ENDIAN - #define CONF_ARCH_ENDIAN_LITTLE 1 - #elif __BYTE_ORDER == __BIG_ENDIAN - #define CONF_ARCH_ENDIAN_BIG 1 - #endif +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#include +#else +#include #endif +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define CONF_ARCH_ENDIAN_LITTLE 1 +#elif __BYTE_ORDER == __BIG_ENDIAN +#define CONF_ARCH_ENDIAN_BIG 1 +#endif +#endif /* architectures */ #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32) - #define CONF_ARCH_IA32 1 - #define CONF_ARCH_STRING "ia32" - #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) - #define CONF_ARCH_ENDIAN_LITTLE 1 - #endif +#define CONF_ARCH_IA32 1 +#define CONF_ARCH_STRING "ia32" +#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) +#define CONF_ARCH_ENDIAN_LITTLE 1 +#endif #endif #if defined(__ia64__) || defined(_M_IA64) - #define CONF_ARCH_IA64 1 - #define CONF_ARCH_STRING "ia64" - #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) - #define CONF_ARCH_ENDIAN_LITTLE 1 - #endif +#define CONF_ARCH_IA64 1 +#define CONF_ARCH_STRING "ia64" +#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) +#define CONF_ARCH_ENDIAN_LITTLE 1 +#endif #endif #if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64) - #define CONF_ARCH_AMD64 1 - #define CONF_ARCH_STRING "amd64" - #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) - #define CONF_ARCH_ENDIAN_LITTLE 1 - #endif +#define CONF_ARCH_AMD64 1 +#define CONF_ARCH_STRING "amd64" +#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) +#define CONF_ARCH_ENDIAN_LITTLE 1 +#endif #endif #if defined(__powerpc__) || defined(__ppc__) - #define CONF_ARCH_PPC 1 - #define CONF_ARCH_STRING "ppc" - #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) - #define CONF_ARCH_ENDIAN_BIG 1 - #endif +#define CONF_ARCH_PPC 1 +#define CONF_ARCH_STRING "ppc" +#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) +#define CONF_ARCH_ENDIAN_BIG 1 +#endif #endif #if defined(__sparc__) - #define CONF_ARCH_SPARC 1 - #define CONF_ARCH_STRING "sparc" - #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) - #define CONF_ARCH_ENDIAN_BIG 1 - #endif +#define CONF_ARCH_SPARC 1 +#define CONF_ARCH_STRING "sparc" +#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) +#define CONF_ARCH_ENDIAN_BIG 1 +#endif #endif #if defined(__ARMEB__) - #define CONF_ARCH_ARM 1 - #define CONF_ARCH_STRING "arm" - #define CONF_ARCH_ENDIAN_BIG 1 +#define CONF_ARCH_ARM 1 +#define CONF_ARCH_STRING "arm" +#define CONF_ARCH_ENDIAN_BIG 1 #endif #if defined(__ARMEL__) - #define CONF_ARCH_ARM 1 - #define CONF_ARCH_STRING "arm" - #define CONF_ARCH_ENDIAN_LITTLE 1 +#define CONF_ARCH_ARM 1 +#define CONF_ARCH_STRING "arm" +#define CONF_ARCH_ENDIAN_LITTLE 1 #endif #ifndef CONF_FAMILY_STRING diff --git a/src/base/dynamic.h b/src/base/dynamic.h index 1cb4c60af..7db91ca7c 100644 --- a/src/base/dynamic.h +++ b/src/base/dynamic.h @@ -11,5 +11,4 @@ #define DYNAMIC_IMPORT #endif - #endif // BASE_DYNAMIC_H diff --git a/src/base/hash.h b/src/base/hash.h index 28b098034..b56a89fc6 100644 --- a/src/base/hash.h +++ b/src/base/hash.h @@ -9,10 +9,10 @@ extern "C" { enum { - SHA256_DIGEST_LENGTH=256/8, - SHA256_MAXSTRSIZE=2*SHA256_DIGEST_LENGTH+1, - MD5_DIGEST_LENGTH=128/8, - MD5_MAXSTRSIZE=2*MD5_DIGEST_LENGTH+1, + SHA256_DIGEST_LENGTH = 256 / 8, + SHA256_MAXSTRSIZE = 2 * SHA256_DIGEST_LENGTH + 1, + MD5_DIGEST_LENGTH = 128 / 8, + MD5_MAXSTRSIZE = 2 * MD5_DIGEST_LENGTH + 1, }; typedef struct diff --git a/src/base/hash_bundled.c b/src/base/hash_bundled.c index c24d293e4..c3ebb8285 100644 --- a/src/base/hash_bundled.c +++ b/src/base/hash_bundled.c @@ -6,14 +6,14 @@ void md5_update(MD5_CTX *ctxt, const void *data, size_t data_len) { - md5_append(ctxt, data, data_len); + md5_append(ctxt, data, data_len); } MD5_DIGEST md5_finish(MD5_CTX *ctxt) { - MD5_DIGEST result; - md5_finish_(ctxt, result.data); - return result; + MD5_DIGEST result; + md5_finish_(ctxt, result.data); + return result; } #endif diff --git a/src/base/hash_ctxt.h b/src/base/hash_ctxt.h index 256988832..b12bad2f9 100644 --- a/src/base/hash_ctxt.h +++ b/src/base/hash_ctxt.h @@ -21,10 +21,10 @@ extern "C" { #else typedef struct { - uint64 length; - uint32_t state[8]; - uint32_t curlen; - unsigned char buf[64]; + uint64 length; + uint32_t state[8]; + uint32_t curlen; + unsigned char buf[64]; } SHA256_CTX; typedef md5_state_t MD5_CTX; #endif diff --git a/src/base/hash_libtomcrypt.c b/src/base/hash_libtomcrypt.c old mode 100755 new mode 100644 index b3deafe49..3d37d164e --- a/src/base/hash_libtomcrypt.c +++ b/src/base/hash_libtomcrypt.c @@ -14,189 +14,195 @@ typedef uint64_t u64; typedef SHA256_CTX sha256_state; static const u32 K[64] = -{ - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, - 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, - 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, - 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, - 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, - 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, - 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, - 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, - 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, - 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; + { + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL}; static u32 minimum(u32 x, u32 y) { - return x < y ? x : y; + return x < y ? x : y; } -static u32 load32(const unsigned char* y) +static u32 load32(const unsigned char *y) { - return ((u32)y[0] << 24) | ((u32)y[1] << 16) | ((u32)y[2] << 8) | ((u32)y[3] << 0); + return ((u32)y[0] << 24) | ((u32)y[1] << 16) | ((u32)y[2] << 8) | ((u32)y[3] << 0); } -static void store64(u64 x, unsigned char* y) +static void store64(u64 x, unsigned char *y) { - int i; - for(i = 0; i != 8; ++i) - y[i] = (x >> ((7-i) * 8)) & 255; + int i; + for(i = 0; i != 8; ++i) + y[i] = (x >> ((7 - i) * 8)) & 255; } -static void store32(u32 x, unsigned char* y) +static void store32(u32 x, unsigned char *y) { - int i; - for(i = 0; i != 4; ++i) - y[i] = (x >> ((3-i) * 8)) & 255; + int i; + for(i = 0; i != 4; ++i) + y[i] = (x >> ((3 - i) * 8)) & 255; } -static u32 Ch(u32 x, u32 y, u32 z) { return z ^ (x & (y ^ z)); } +static u32 Ch(u32 x, u32 y, u32 z) { return z ^ (x & (y ^ z)); } static u32 Maj(u32 x, u32 y, u32 z) { return ((x | y) & z) | (x & y); } -static u32 Rot(u32 x, u32 n) { return (x >> (n & 31)) | (x << (32 - (n & 31))); } -static u32 Sh(u32 x, u32 n) { return x >> n; } -static u32 Sigma0(u32 x) { return Rot(x, 2) ^ Rot(x, 13) ^ Rot(x, 22); } -static u32 Sigma1(u32 x) { return Rot(x, 6) ^ Rot(x, 11) ^ Rot(x, 25); } -static u32 Gamma0(u32 x) { return Rot(x, 7) ^ Rot(x, 18) ^ Sh(x, 3); } -static u32 Gamma1(u32 x) { return Rot(x, 17) ^ Rot(x, 19) ^ Sh(x, 10); } +static u32 Rot(u32 x, u32 n) { return (x >> (n & 31)) | (x << (32 - (n & 31))); } +static u32 Sh(u32 x, u32 n) { return x >> n; } +static u32 Sigma0(u32 x) { return Rot(x, 2) ^ Rot(x, 13) ^ Rot(x, 22); } +static u32 Sigma1(u32 x) { return Rot(x, 6) ^ Rot(x, 11) ^ Rot(x, 25); } +static u32 Gamma0(u32 x) { return Rot(x, 7) ^ Rot(x, 18) ^ Sh(x, 3); } +static u32 Gamma1(u32 x) { return Rot(x, 17) ^ Rot(x, 19) ^ Sh(x, 10); } -static void sha_compress(sha256_state* md, const unsigned char* buf) +static void sha_compress(sha256_state *md, const unsigned char *buf) { - u32 S[8], W[64], t0, t1, t; - int i; + u32 S[8], W[64], t0, t1, t; + int i; - // Copy state into S - for(i = 0; i < 8; i++) - S[i] = md->state[i]; + // Copy state into S + for(i = 0; i < 8; i++) + S[i] = md->state[i]; - // Copy the state into 512-bits into W[0..15] - for(i = 0; i < 16; i++) - W[i] = load32(buf + (4*i)); + // Copy the state into 512-bits into W[0..15] + for(i = 0; i < 16; i++) + W[i] = load32(buf + (4 * i)); - // Fill W[16..63] - for(i = 16; i < 64; i++) - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + // Fill W[16..63] + for(i = 16; i < 64; i++) + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; - // Compress - #define RND(a, b, c, d, e, f, g, h, i) \ - { \ - t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ - t1 = Sigma0(a) + Maj(a, b, c); \ - d += t0; \ - h = t0 + t1; \ - } +// Compress +#define RND(a, b, c, d, e, f, g, h, i) \ + { \ + t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ + t1 = Sigma0(a) + Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; \ + } - for(i = 0; i < 64; ++i) - { - RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i); - t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; - S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; - } + for(i = 0; i < 64; ++i) + { + RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i); + t = S[7]; + S[7] = S[6]; + S[6] = S[5]; + S[5] = S[4]; + S[4] = S[3]; + S[3] = S[2]; + S[2] = S[1]; + S[1] = S[0]; + S[0] = t; + } - // Feedback - for(i = 0; i < 8; i++) - md->state[i] = md->state[i] + S[i]; + // Feedback + for(i = 0; i < 8; i++) + md->state[i] = md->state[i] + S[i]; } // Public interface -static void sha_init(sha256_state* md) +static void sha_init(sha256_state *md) { - md->curlen = 0; - md->length = 0; - md->state[0] = 0x6A09E667UL; - md->state[1] = 0xBB67AE85UL; - md->state[2] = 0x3C6EF372UL; - md->state[3] = 0xA54FF53AUL; - md->state[4] = 0x510E527FUL; - md->state[5] = 0x9B05688CUL; - md->state[6] = 0x1F83D9ABUL; - md->state[7] = 0x5BE0CD19UL; + md->curlen = 0; + md->length = 0; + md->state[0] = 0x6A09E667UL; + md->state[1] = 0xBB67AE85UL; + md->state[2] = 0x3C6EF372UL; + md->state[3] = 0xA54FF53AUL; + md->state[4] = 0x510E527FUL; + md->state[5] = 0x9B05688CUL; + md->state[6] = 0x1F83D9ABUL; + md->state[7] = 0x5BE0CD19UL; } -static void sha_process(sha256_state* md, const void* src, u32 inlen) +static void sha_process(sha256_state *md, const void *src, u32 inlen) { - const u32 block_size = 64; - const unsigned char* in = src; + const u32 block_size = 64; + const unsigned char *in = src; - while(inlen > 0) - { - if(md->curlen == 0 && inlen >= block_size) - { - sha_compress(md, in); - md->length += block_size * 8; - in += block_size; - inlen -= block_size; - } - else - { - u32 n = minimum(inlen, (block_size - md->curlen)); - memcpy(md->buf + md->curlen, in, n); - md->curlen += n; - in += n; - inlen -= n; + while(inlen > 0) + { + if(md->curlen == 0 && inlen >= block_size) + { + sha_compress(md, in); + md->length += block_size * 8; + in += block_size; + inlen -= block_size; + } + else + { + u32 n = minimum(inlen, (block_size - md->curlen)); + memcpy(md->buf + md->curlen, in, n); + md->curlen += n; + in += n; + inlen -= n; - if(md->curlen == block_size) - { - sha_compress(md, md->buf); - md->length += 8*block_size; - md->curlen = 0; - } - } - } + if(md->curlen == block_size) + { + sha_compress(md, md->buf); + md->length += 8 * block_size; + md->curlen = 0; + } + } + } } -static void sha_done(sha256_state* md, void* out) +static void sha_done(sha256_state *md, void *out) { - int i; + int i; - // Increase the length of the message - md->length += md->curlen * 8; + // Increase the length of the message + md->length += md->curlen * 8; - // Append the '1' bit - md->buf[md->curlen++] = (unsigned char)0x80; + // Append the '1' bit + md->buf[md->curlen++] = (unsigned char)0x80; - // If the length is currently above 56 bytes we append zeros then compress. - // Then we can fall back to padding zeros and length encoding like normal. - if(md->curlen > 56) - { - while(md->curlen < 64) - md->buf[md->curlen++] = 0; - sha_compress(md, md->buf); - md->curlen = 0; - } + // If the length is currently above 56 bytes we append zeros then compress. + // Then we can fall back to padding zeros and length encoding like normal. + if(md->curlen > 56) + { + while(md->curlen < 64) + md->buf[md->curlen++] = 0; + sha_compress(md, md->buf); + md->curlen = 0; + } - // Pad up to 56 bytes of zeroes - while(md->curlen < 56) - md->buf[md->curlen++] = 0; + // Pad up to 56 bytes of zeroes + while(md->curlen < 56) + md->buf[md->curlen++] = 0; - // Store length - store64(md->length, md->buf+56); - sha_compress(md, md->buf); + // Store length + store64(md->length, md->buf + 56); + sha_compress(md, md->buf); - // Copy output - for(i = 0; i < 8; i++) - store32(md->state[i], (unsigned char *)out+(4*i)); + // Copy output + for(i = 0; i < 8; i++) + store32(md->state[i], (unsigned char *)out + (4 * i)); } void sha256_init(SHA256_CTX *ctxt) { - sha_init(ctxt); + sha_init(ctxt); } void sha256_update(SHA256_CTX *ctxt, const void *data, size_t data_len) { - sha_process(ctxt, data, data_len); + sha_process(ctxt, data, data_len); } SHA256_DIGEST sha256_finish(SHA256_CTX *ctxt) { - SHA256_DIGEST result; - sha_done(ctxt, result.data); - return result; + SHA256_DIGEST result; + sha_done(ctxt, result.data); + return result; } #endif diff --git a/src/base/math.h b/src/base/math.h index f1637be40..4ce286d25 100644 --- a/src/base/math.h +++ b/src/base/math.h @@ -6,7 +6,7 @@ #include #include -template +template constexpr inline T clamp(T val, T min, T max) { return val < min ? min : (val > max ? max : val); @@ -14,7 +14,7 @@ constexpr inline T clamp(T val, T min, T max) constexpr inline float sign(float f) { - return f<0.0f?-1.0f:1.0f; + return f < 0.0f ? -1.0f : 1.0f; } constexpr inline int round_to_int(float f) @@ -35,14 +35,14 @@ inline int round_ceil(float f) template constexpr inline T mix(const T a, const T b, TB amount) { - return a + (b-a)*amount; + return a + (b - a) * amount; } -inline float frandom() { return rand()/(float)(RAND_MAX); } +inline float frandom() { return rand() / (float)(RAND_MAX); } // float to fixed -constexpr inline int f2fx(float v) { return (int)(v*(float)(1<<10)); } -constexpr inline float fx2f(int v) { return v*(1.0f/(1<<10)); } +constexpr inline int f2fx(float v) { return (int)(v * (float)(1 << 10)); } +constexpr inline float fx2f(int v) { return v * (1.0f / (1 << 10)); } // int to fixed inline int i2fx(int v) @@ -68,23 +68,60 @@ inline int gcd(int a, int b) class fxp { int value; + public: void set(int v) { value = v; } int get() const { return value; } - fxp &operator = (int v) { value = v<<10; return *this; } - fxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; } - operator float() const { return value/(float)(1<<10); } + fxp &operator=(int v) + { + value = v << 10; + return *this; + } + fxp &operator=(float v) + { + value = (int)(v * (float)(1 << 10)); + return *this; + } + operator float() const { return value / (float)(1 << 10); } }; constexpr float pi = 3.1415926535897932384626433f; -template constexpr inline T minimum(T a, T b) { return a constexpr inline T minimum(T a, T b, T c) { return minimum(minimum(a, b), c); } -template constexpr inline T maximum(T a, T b) { return a>b?a:b; } -template constexpr inline T maximum(T a, T b, T c) { return maximum(maximum(a, b), c); } -template constexpr inline T absolute(T a) { return a +constexpr inline T minimum(T a, T b) +{ + return a < b ? a : b; +} +template +constexpr inline T minimum(T a, T b, T c) +{ + return minimum(minimum(a, b), c); +} +template +constexpr inline T maximum(T a, T b) +{ + return a > b ? a : b; +} +template +constexpr inline T maximum(T a, T b, T c) +{ + return maximum(maximum(a, b), c); +} +template +constexpr inline T absolute(T a) +{ + return a < T(0) ? -a : a; +} -template constexpr inline T in_range(T a, T lower, T upper) { return lower <= a && a <= upper; } -template constexpr inline T in_range(T a, T upper) { return in_range(a, 0, upper); } +template +constexpr inline T in_range(T a, T lower, T upper) +{ + return lower <= a && a <= upper; +} +template +constexpr inline T in_range(T a, T upper) +{ + return in_range(a, 0, upper); +} #endif // BASE_MATH_H diff --git a/src/base/system.c b/src/base/system.c index b9f9908bb..24dce2e26 100644 --- a/src/base/system.c +++ b/src/base/system.c @@ -1,19 +1,19 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include "system.h" -#include #include +#include #if defined(CONF_WEBSOCKETS) - #include "engine/shared/websockets.h" +#include "engine/shared/websockets.h" #endif #if defined(CONF_FAMILY_UNIX) @@ -46,32 +46,35 @@ #endif #elif defined(CONF_FAMILY_WINDOWS) - #define WIN32_LEAN_AND_MEAN - #undef _WIN32_WINNT - #define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */ - #include - #include - #include +#define WIN32_LEAN_AND_MEAN +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */ +#include +#include +#include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include #else - #error NOT IMPLEMENTED +#error NOT IMPLEMENTED #endif #if defined(CONF_PLATFORM_SOLARIS) - #include +#include #endif #if defined(__cplusplus) extern "C" { #endif -IOHANDLE io_stdin() { return (IOHANDLE)stdin; } +IOHANDLE io_stdin() +{ + return (IOHANDLE)stdin; +} IOHANDLE io_stdout() { return (IOHANDLE)stdout; } IOHANDLE io_stderr() { return (IOHANDLE)stderr; } @@ -105,7 +108,7 @@ void dbg_break_imp(void) #ifdef __GNUC__ __builtin_trap(); #else - *((volatile unsigned*)0) = 0x0; + *((volatile unsigned *)0) = 0x0; #endif } @@ -115,7 +118,7 @@ void dbg_msg(const char *sys, const char *fmt, ...) char *msg; int len; - char str[1024*4]; + char str[1024 * 4]; int i; char timestr[80]; @@ -128,9 +131,9 @@ void dbg_msg(const char *sys, const char *fmt, ...) va_start(args, fmt); #if defined(CONF_FAMILY_WINDOWS) - _vsnprintf(msg, sizeof(str)-len, fmt, args); + _vsnprintf(msg, sizeof(str) - len, fmt, args); #else - vsnprintf(msg, sizeof(str)-len, fmt, args); + vsnprintf(msg, sizeof(str) - len, fmt, args); #endif va_end(args); @@ -147,7 +150,6 @@ static void logger_debugger(const char *line, void *user) } #endif - static void logger_file(const char *line, void *user) { ASYNCIO *logfile = (ASYNCIO *)user; @@ -161,7 +163,7 @@ static void logger_file(const char *line, void *user) static void logger_stdout_sync(const char *line, void *user) { size_t length = strlen(line); - wchar_t *wide = malloc(length * sizeof (*wide)); + wchar_t *wide = malloc(length * sizeof(*wide)); const char *p = line; int wlen = 0; HANDLE console; @@ -251,7 +253,6 @@ void dbg_logger_file(const char *filename) dbg_logger(logger_file, logger_file_finish, aio_new(logfile)); else dbg_msg("dbg/logger", "failed to open '%s' for logging", filename); - } /* */ @@ -265,7 +266,7 @@ void mem_move(void *dest, const void *source, unsigned size) memmove(dest, source, size); } -void mem_zero(void *block,unsigned size) +void mem_zero(void *block, unsigned size) { memset(block, 0, size); } @@ -283,12 +284,12 @@ IOHANDLE io_open(const char *filename, int flags) unsigned io_read(IOHANDLE io, void *buffer, unsigned size) { - return fread(buffer, 1, size, (FILE*)io); + return fread(buffer, 1, size, (FILE *)io); } unsigned io_skip(IOHANDLE io, int size) { - fseek((FILE*)io, size, SEEK_CUR); + fseek((FILE *)io, size, SEEK_CUR); return size; } @@ -311,12 +312,12 @@ int io_seek(IOHANDLE io, int offset, int origin) return -1; } - return fseek((FILE*)io, offset, real_origin); + return fseek((FILE *)io, offset, real_origin); } long int io_tell(IOHANDLE io) { - return ftell((FILE*)io); + return ftell((FILE *)io); } long int io_length(IOHANDLE io) @@ -330,34 +331,33 @@ long int io_length(IOHANDLE io) int io_error(IOHANDLE io) { - return ferror((FILE*)io); + return ferror((FILE *)io); } unsigned io_write(IOHANDLE io, const void *buffer, unsigned size) { - return fwrite(buffer, 1, size, (FILE*)io); + return fwrite(buffer, 1, size, (FILE *)io); } unsigned io_write_newline(IOHANDLE io) { #if defined(CONF_FAMILY_WINDOWS) - return fwrite("\r\n", 1, 2, (FILE*)io); + return fwrite("\r\n", 1, 2, (FILE *)io); #else - return fwrite("\n", 1, 1, (FILE*)io); + return fwrite("\n", 1, 1, (FILE *)io); #endif } int io_close(IOHANDLE io) { - return fclose((FILE*)io) != 0; + return fclose((FILE *)io) != 0; } int io_flush(IOHANDLE io) { - return fflush((FILE*)io); + return fflush((FILE *)io); } - #define ASYNC_BUFSIZE 8 * 1024 #define ASYNC_LOCAL_BUFSIZE 64 * 1024 @@ -709,12 +709,12 @@ void *thread_init(void (*threadfunc)(void *), void *u, const char *name) dbg_msg("thread", "creating %s thread failed: %d", name, result); return 0; } - return (void*)id; + return (void *)id; } #elif defined(CONF_FAMILY_WINDOWS) return CreateThread(NULL, 0, thread_run, data, 0, NULL); #else - #error not implemented +#error not implemented #endif } @@ -728,7 +728,7 @@ void thread_wait(void *thread) WaitForSingleObject((HANDLE)thread, INFINITE); CloseHandle(thread); #else - #error not implemented +#error not implemented #endif } @@ -741,7 +741,7 @@ void thread_yield(void) #elif defined(CONF_FAMILY_WINDOWS) Sleep(0); #else - #error not implemented +#error not implemented #endif } @@ -753,9 +753,9 @@ void thread_sleep(int microseconds) if(result == -1 && errno != EINTR) dbg_msg("thread", "sleep failed: %d", errno); #elif defined(CONF_FAMILY_WINDOWS) - Sleep(microseconds/1000); + Sleep(microseconds / 1000); #else - #error not implemented +#error not implemented #endif } @@ -768,7 +768,7 @@ void thread_detach(void *thread) #elif defined(CONF_FAMILY_WINDOWS) CloseHandle(thread); #else - #error not implemented +#error not implemented #endif } @@ -780,14 +780,12 @@ void *thread_init_and_detach(void (*threadfunc)(void *), void *u, const char *na return thread; } - - #if defined(CONF_FAMILY_UNIX) typedef pthread_mutex_t LOCKINTERNAL; #elif defined(CONF_FAMILY_WINDOWS) typedef CRITICAL_SECTION LOCKINTERNAL; #else - #error not implemented on this platform +#error not implemented on this platform #endif LOCK lock_create(void) @@ -810,7 +808,7 @@ LOCK lock_create(void) #elif defined(CONF_FAMILY_WINDOWS) InitializeCriticalSection((LPCRITICAL_SECTION)lock); #else - #error not implemented on this platform +#error not implemented on this platform #endif return (LOCK)lock; } @@ -824,7 +822,7 @@ void lock_destroy(LOCK lock) #elif defined(CONF_FAMILY_WINDOWS) DeleteCriticalSection((LPCRITICAL_SECTION)lock); #else - #error not implemented on this platform +#error not implemented on this platform #endif free(lock); } @@ -836,7 +834,7 @@ int lock_trylock(LOCK lock) #elif defined(CONF_FAMILY_WINDOWS) return !TryEnterCriticalSection((LPCRITICAL_SECTION)lock); #else - #error not implemented on this platform +#error not implemented on this platform #endif } @@ -849,7 +847,7 @@ void lock_wait(LOCK lock) #elif defined(CONF_FAMILY_WINDOWS) EnterCriticalSection((LPCRITICAL_SECTION)lock); #else - #error not implemented on this platform +#error not implemented on this platform #endif } @@ -862,12 +860,15 @@ void lock_unlock(LOCK lock) #elif defined(CONF_FAMILY_WINDOWS) LeaveCriticalSection((LPCRITICAL_SECTION)lock); #else - #error not implemented on this platform +#error not implemented on this platform #endif } #if defined(CONF_FAMILY_WINDOWS) -void sphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); } +void sphore_init(SEMAPHORE *sem) +{ + *sem = CreateSemaphore(0, 0, 10000, 0); +} void sphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, INFINITE); } void sphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); } void sphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); } @@ -946,17 +947,17 @@ int64 time_get_impl(void) dbg_msg("clock", "gettime failed: %d", errno); return 0; } - last = (int64)spec.tv_sec*(int64)1000000 + (int64)spec.tv_nsec / 1000; + last = (int64)spec.tv_sec * (int64)1000000 + (int64)spec.tv_nsec / 1000; return last; #elif defined(CONF_FAMILY_WINDOWS) int64 t; QueryPerformanceCounter((PLARGE_INTEGER)&t); - if(ttype = NETTYPE_IPV4; - dst->port = htons(((struct sockaddr_in*)src)->sin_port); - mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); + dst->port = htons(((struct sockaddr_in *)src)->sin_port); + mem_copy(dst->ip, &((struct sockaddr_in *)src)->sin_addr.s_addr, 4); } else if(src->sa_family == AF_WEBSOCKET_INET) { mem_zero(dst, sizeof(NETADDR)); dst->type = NETTYPE_WEBSOCKET_IPV4; - dst->port = htons(((struct sockaddr_in*)src)->sin_port); - mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); + dst->port = htons(((struct sockaddr_in *)src)->sin_port); + mem_copy(dst->ip, &((struct sockaddr_in *)src)->sin_addr.s_addr, 4); } else if(src->sa_family == AF_INET6) { mem_zero(dst, sizeof(NETADDR)); dst->type = NETTYPE_IPV6; - dst->port = htons(((struct sockaddr_in6*)src)->sin6_port); - mem_copy(dst->ip, &((struct sockaddr_in6*)src)->sin6_addr.s6_addr, 16); + dst->port = htons(((struct sockaddr_in6 *)src)->sin6_port); + mem_copy(dst->ip, &((struct sockaddr_in6 *)src)->sin6_addr.s6_addr, 16); } else { @@ -1082,13 +1083,13 @@ void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_por { if(add_port != 0) str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", - (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], - (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15], + (addr->ip[0] << 8) | addr->ip[1], (addr->ip[2] << 8) | addr->ip[3], (addr->ip[4] << 8) | addr->ip[5], (addr->ip[6] << 8) | addr->ip[7], + (addr->ip[8] << 8) | addr->ip[9], (addr->ip[10] << 8) | addr->ip[11], (addr->ip[12] << 8) | addr->ip[13], (addr->ip[14] << 8) | addr->ip[15], addr->port); else str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]", - (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], - (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15]); + (addr->ip[0] << 8) | addr->ip[1], (addr->ip[2] << 8) | addr->ip[3], (addr->ip[4] << 8) | addr->ip[5], (addr->ip[6] << 8) | addr->ip[7], + (addr->ip[8] << 8) | addr->ip[9], (addr->ip[10] << 8) | addr->ip[11], (addr->ip[12] << 8) | addr->ip[13], (addr->ip[14] << 8) | addr->ip[15]); } else str_format(string, max_length, "unknown type %d", addr->type); @@ -1105,24 +1106,24 @@ static int priv_net_extract(const char *hostname, char *host, int max_host, int { // ipv6 mode for(i = 1; i < max_host && hostname[i] && hostname[i] != ']'; i++) - host[i-1] = hostname[i]; - host[i-1] = 0; + host[i - 1] = hostname[i]; + host[i - 1] = 0; if(hostname[i] != ']') // malformatted return -1; i++; if(hostname[i] == ':') - *port = atol(hostname+i+1); + *port = atol(hostname + i + 1); } else { // generic mode (ipv4, hostname etc) - for(i = 0; i < max_host-1 && hostname[i] && hostname[i] != ':'; i++) + for(i = 0; i < max_host - 1 && hostname[i] && hostname[i] != ':'; i++) host[i] = hostname[i]; host[i] = 0; if(hostname[i] == ':') - *port = atol(hostname+i+1); + *port = atol(hostname + i + 1); } return 0; @@ -1189,7 +1190,7 @@ static int parse_int(int *out, const char **str) return 0; } - i = (i*10) + (**str - '0'); + i = (i * 10) + (**str - '0'); (*str)++; } @@ -1198,7 +1199,8 @@ static int parse_int(int *out, const char **str) static int parse_char(char c, const char **str) { - if(**str != c) return -1; + if(**str != c) + return -1; (*str)++; return 0; } @@ -1206,8 +1208,10 @@ static int parse_char(char c, const char **str) static int parse_uint8(unsigned char *out, const char **str) { int i; - if(parse_int(&i, str) != 0) return -1; - if(i < 0 || i > 0xff) return -1; + if(parse_int(&i, str) != 0) + return -1; + if(i < 0 || i > 0xff) + return -1; *out = i; return 0; } @@ -1215,8 +1219,10 @@ static int parse_uint8(unsigned char *out, const char **str) static int parse_uint16(unsigned short *out, const char **str) { int i; - if(parse_int(&i, str) != 0) return -1; - if(i < 0 || i > 0xffff) return -1; + if(parse_int(&i, str) != 0) + return -1; + if(i < 0 || i > 0xffff) + return -1; *out = i; return 0; } @@ -1271,17 +1277,25 @@ int net_addr_from_str(NETADDR *addr, const char *string) else { /* ipv4 */ - if(parse_uint8(&addr->ip[0], &str)) return -1; - if(parse_char('.', &str)) return -1; - if(parse_uint8(&addr->ip[1], &str)) return -1; - if(parse_char('.', &str)) return -1; - if(parse_uint8(&addr->ip[2], &str)) return -1; - if(parse_char('.', &str)) return -1; - if(parse_uint8(&addr->ip[3], &str)) return -1; + if(parse_uint8(&addr->ip[0], &str)) + return -1; + if(parse_char('.', &str)) + return -1; + if(parse_uint8(&addr->ip[1], &str)) + return -1; + if(parse_char('.', &str)) + return -1; + if(parse_uint8(&addr->ip[2], &str)) + return -1; + if(parse_char('.', &str)) + return -1; + if(parse_uint8(&addr->ip[3], &str)) + return -1; if(*str == ':') { str++; - if(parse_uint16(&addr->port, &str)) return -1; + if(parse_uint16(&addr->port, &str)) + return -1; } addr->type = NETTYPE_IPV4; @@ -1341,7 +1355,7 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i #if defined(CONF_FAMILY_WINDOWS) char buf[128]; int error = WSAGetLastError(); - if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) + if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) buf[0] = 0; dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, error, buf); #else @@ -1353,7 +1367,7 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i #if defined(CONF_FAMILY_UNIX) /* on tcp sockets set SO_REUSEADDR to fix port rebind on restart */ - if (domain == AF_INET && type == SOCK_STREAM) + if(domain == AF_INET && type == SOCK_STREAM) { int option = 1; if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) != 0) @@ -1362,11 +1376,11 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i #endif /* set to IPv6 only if that's what we are creating */ -#if defined(IPV6_V6ONLY) /* windows sdk 6.1 and higher */ +#if defined(IPV6_V6ONLY) /* windows sdk 6.1 and higher */ if(domain == AF_INET6) { int ipv6only = 1; - if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6only, sizeof(ipv6only)) != 0) + if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&ipv6only, sizeof(ipv6only)) != 0) dbg_msg("socket", "Setting V6ONLY failed: %d", errno); } #endif @@ -1378,7 +1392,7 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i #if defined(CONF_FAMILY_WINDOWS) char buf[128]; int error = WSAGetLastError(); - if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) + if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) buf[0] = 0; dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, error, buf); #else @@ -1398,7 +1412,7 @@ NETSOCKET net_udp_create(NETADDR bindaddr) NETADDR tmpbindaddr = bindaddr; int broadcast = 1; - if(bindaddr.type&NETTYPE_IPV4) + if(bindaddr.type & NETTYPE_IPV4) { struct sockaddr_in addr; int socket = -1; @@ -1413,21 +1427,21 @@ NETSOCKET net_udp_create(NETADDR bindaddr) sock.ipv4sock = socket; /* set broadcast */ - if(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)) != 0) + if(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char *)&broadcast, sizeof(broadcast)) != 0) dbg_msg("socket", "Setting BROADCAST on ipv4 failed: %d", errno); { /* set DSCP/TOS */ int iptos = 0x10 /* IPTOS_LOWDELAY */; //int iptos = 46; /* High Priority */ - if(setsockopt(socket, IPPROTO_IP, IP_TOS, (char*)&iptos, sizeof(iptos)) != 0) + if(setsockopt(socket, IPPROTO_IP, IP_TOS, (char *)&iptos, sizeof(iptos)) != 0) dbg_msg("socket", "Setting TOS on ipv4 failed: %d", errno); } } } #if defined(CONF_WEBSOCKETS) - if(bindaddr.type&NETTYPE_WEBSOCKET_IPV4) + if(bindaddr.type & NETTYPE_WEBSOCKET_IPV4) { int socket = -1; char addr_str[NETADDR_MAXSTRSIZE]; @@ -1438,14 +1452,15 @@ NETSOCKET net_udp_create(NETADDR bindaddr) net_addr_str(&tmpbindaddr, addr_str, sizeof(addr_str), 0); socket = websocket_create(addr_str, tmpbindaddr.port); - if (socket >= 0) { + if(socket >= 0) + { sock.type |= NETTYPE_WEBSOCKET_IPV4; sock.web_ipv4sock = socket; } } #endif - if(bindaddr.type&NETTYPE_IPV6) + if(bindaddr.type & NETTYPE_IPV6) { struct sockaddr_in6 addr; int socket = -1; @@ -1460,14 +1475,14 @@ NETSOCKET net_udp_create(NETADDR bindaddr) sock.ipv6sock = socket; /* set broadcast */ - if(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)) != 0) - dbg_msg("socket", "Setting BROADCAST on ipv6 failed: %d", errno); + if(setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char *)&broadcast, sizeof(broadcast)) != 0) + dbg_msg("socket", "Setting BROADCAST on ipv6 failed: %d", errno); { /* set DSCP/TOS */ int iptos = 0x10 /* IPTOS_LOWDELAY */; //int iptos = 46; /* High Priority */ - if(setsockopt(socket, IPPROTO_IP, IP_TOS, (char*)&iptos, sizeof(iptos)) != 0) + if(setsockopt(socket, IPPROTO_IP, IP_TOS, (char *)&iptos, sizeof(iptos)) != 0) dbg_msg("socket", "Setting TOS on ipv6 failed: %d", errno); } } @@ -1484,12 +1499,12 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size { int d = -1; - if(addr->type&NETTYPE_IPV4) + if(addr->type & NETTYPE_IPV4) { if(sock.ipv4sock >= 0) { struct sockaddr_in sa; - if(addr->type&NETTYPE_LINK_BROADCAST) + if(addr->type & NETTYPE_LINK_BROADCAST) { mem_zero(&sa, sizeof(sa)); sa.sin_port = htons(addr->port); @@ -1499,7 +1514,7 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size else netaddr_to_sockaddr_in(addr, &sa); - d = sendto((int)sock.ipv4sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + d = sendto((int)sock.ipv4sock, (const char *)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); } else dbg_msg("net", "can't send ipv4 traffic to this socket"); @@ -1520,12 +1535,12 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size } #endif - if(addr->type&NETTYPE_IPV6) + if(addr->type & NETTYPE_IPV6) { if(sock.ipv6sock >= 0) { struct sockaddr_in6 sa; - if(addr->type&NETTYPE_LINK_BROADCAST) + if(addr->type & NETTYPE_LINK_BROADCAST) { mem_zero(&sa, sizeof(sa)); sa.sin6_port = htons(addr->port); @@ -1537,7 +1552,7 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size else netaddr_to_sockaddr_in6(addr, &sa); - d = sendto((int)sock.ipv6sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + d = sendto((int)sock.ipv6sock, (const char *)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); } else dbg_msg("net", "can't send ipv6 traffic to this socket"); @@ -1563,7 +1578,7 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size return d; } -void net_init_mmsgs(MMSGS* m) +void net_init_mmsgs(MMSGS *m) { #if defined(CONF_PLATFORM_LINUX) int i; @@ -1584,7 +1599,7 @@ void net_init_mmsgs(MMSGS* m) #endif } -int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS* m, unsigned char **data) +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS *m, unsigned char **data) { char sockaddrbuf[128]; int bytes = 0; @@ -1615,7 +1630,7 @@ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS //network_stats.recv_bytes += bytes; //network_stats.recv_packets++; bytes = m->msgs[m->pos].msg_len; - *data = (unsigned char*)m->bufs[m->pos]; + *data = (unsigned char *)m->bufs[m->pos]; m->pos++; return bytes; } @@ -1623,14 +1638,14 @@ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS if(bytes == 0 && sock.ipv4sock >= 0) { socklen_t fromlen = sizeof(struct sockaddr_in); - bytes = recvfrom(sock.ipv4sock, (char*)buffer, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + bytes = recvfrom(sock.ipv4sock, (char *)buffer, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); *data = buffer; } if(bytes <= 0 && sock.ipv6sock >= 0) { socklen_t fromlen = sizeof(struct sockaddr_in6); - bytes = recvfrom(sock.ipv6sock, (char*)buffer, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + bytes = recvfrom(sock.ipv6sock, (char *)buffer, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); *data = buffer; } #endif @@ -1668,7 +1683,7 @@ NETSOCKET net_tcp_create(NETADDR bindaddr) NETSOCKET sock = invalid_socket; NETADDR tmpbindaddr = bindaddr; - if(bindaddr.type&NETTYPE_IPV4) + if(bindaddr.type & NETTYPE_IPV4) { struct sockaddr_in addr; int socket = -1; @@ -1684,7 +1699,7 @@ NETSOCKET net_tcp_create(NETADDR bindaddr) } } - if(bindaddr.type&NETTYPE_IPV6) + if(bindaddr.type & NETTYPE_IPV6) { struct sockaddr_in6 addr; int socket = -1; @@ -1780,7 +1795,7 @@ int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) s = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len); - if (s != -1) + if(s != -1) { sockaddr_to_netaddr((const struct sockaddr *)&addr, a); new_sock->type = NETTYPE_IPV4; @@ -1796,7 +1811,7 @@ int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) s = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len); - if (s != -1) + if(s != -1) { sockaddr_to_netaddr((const struct sockaddr *)&addr, a); new_sock->type = NETTYPE_IPV6; @@ -1810,14 +1825,14 @@ int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) int net_tcp_connect(NETSOCKET sock, const NETADDR *a) { - if(a->type&NETTYPE_IPV4) + if(a->type & NETTYPE_IPV4) { struct sockaddr_in addr; netaddr_to_sockaddr_in(a, &addr); return connect(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr)); } - if(a->type&NETTYPE_IPV6) + if(a->type & NETTYPE_IPV6) { struct sockaddr_in6 addr; netaddr_to_sockaddr_in6(a, &addr); @@ -1843,9 +1858,9 @@ int net_tcp_send(NETSOCKET sock, const void *data, int size) int bytes = -1; if(sock.ipv4sock >= 0) - bytes = send((int)sock.ipv4sock, (const char*)data, size, 0); + bytes = send((int)sock.ipv4sock, (const char *)data, size, 0); if(sock.ipv6sock >= 0) - bytes = send((int)sock.ipv6sock, (const char*)data, size, 0); + bytes = send((int)sock.ipv6sock, (const char *)data, size, 0); return bytes; } @@ -1855,9 +1870,9 @@ int net_tcp_recv(NETSOCKET sock, void *data, int maxsize) int bytes = -1; if(sock.ipv4sock >= 0) - bytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0); + bytes = recv((int)sock.ipv4sock, (char *)data, maxsize, 0); if(sock.ipv6sock >= 0) - bytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0); + bytes = recv((int)sock.ipv6sock, (char *)data, maxsize, 0); return bytes; } @@ -1891,7 +1906,7 @@ int net_init(void) WSADATA wsaData; int err = WSAStartup(MAKEWORD(1, 1), &wsaData); dbg_assert(err == 0, "network initialization failed."); - return err==0?0:1; + return err == 0 ? 0 : 1; #endif return 0; @@ -1926,13 +1941,13 @@ int fs_listdir_info(const char *dir, FS_LISTDIR_INFO_CALLBACK cb, int type, void #if defined(CONF_FAMILY_WINDOWS) WIN32_FIND_DATA finddata; HANDLE handle; - char buffer[1024*2]; + char buffer[1024 * 2]; int length; str_format(buffer, sizeof(buffer), "%s/*", dir); handle = FindFirstFileA(buffer, &finddata); - if (handle == INVALID_HANDLE_VALUE) + if(handle == INVALID_HANDLE_VALUE) return 0; str_format(buffer, sizeof(buffer), "%s/", dir); @@ -1941,17 +1956,16 @@ int fs_listdir_info(const char *dir, FS_LISTDIR_INFO_CALLBACK cb, int type, void /* add all the entries */ do { - str_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length); + str_copy(buffer + length, finddata.cFileName, (int)sizeof(buffer) - length); if(cb(finddata.cFileName, fs_getmtime(buffer), fs_is_dir(buffer), type, user)) break; - } - while (FindNextFileA(handle, &finddata)); + } while(FindNextFileA(handle, &finddata)); FindClose(handle); return 0; #else struct dirent *entry; - char buffer[1024*2]; + char buffer[1024 * 2]; int length; DIR *d = opendir(dir); @@ -1963,7 +1977,7 @@ int fs_listdir_info(const char *dir, FS_LISTDIR_INFO_CALLBACK cb, int type, void while((entry = readdir(d)) != NULL) { - str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + str_copy(buffer + length, entry->d_name, (int)sizeof(buffer) - length); if(cb(entry->d_name, fs_getmtime(buffer), fs_is_dir(buffer), type, user)) break; } @@ -1979,13 +1993,13 @@ int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) #if defined(CONF_FAMILY_WINDOWS) WIN32_FIND_DATA finddata; HANDLE handle; - char buffer[1024*2]; + char buffer[1024 * 2]; int length; str_format(buffer, sizeof(buffer), "%s/*", dir); handle = FindFirstFileA(buffer, &finddata); - if (handle == INVALID_HANDLE_VALUE) + if(handle == INVALID_HANDLE_VALUE) return 0; str_format(buffer, sizeof(buffer), "%s/", dir); @@ -1994,17 +2008,16 @@ int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) /* add all the entries */ do { - str_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length); + str_copy(buffer + length, finddata.cFileName, (int)sizeof(buffer) - length); if(cb(finddata.cFileName, fs_is_dir(buffer), type, user)) break; - } - while (FindNextFileA(handle, &finddata)); + } while(FindNextFileA(handle, &finddata)); FindClose(handle); return 0; #else struct dirent *entry; - char buffer[1024*2]; + char buffer[1024 * 2]; int length; DIR *d = opendir(dir); @@ -2016,7 +2029,7 @@ int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) while((entry = readdir(d)) != NULL) { - str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + str_copy(buffer + length, entry->d_name, (int)sizeof(buffer) - length); if(cb(entry->d_name, fs_is_dir(buffer), type, user)) break; } @@ -2047,7 +2060,7 @@ int fs_storage_path(const char *appname, char *path, int max) snprintf(path, max, "%s/Library/Application Support/%s", home, appname); #else snprintf(path, max, "%s/.%s", home, appname); - for(i = strlen(home)+2; path[i]; i++) + for(i = strlen(home) + 2; path[i]; i++) path[i] = tolower(path[i]); #endif @@ -2057,10 +2070,10 @@ int fs_storage_path(const char *appname, char *path, int max) int fs_makedir_rec_for(const char *path) { - char buffer[1024*2]; + char buffer[1024 * 2]; char *p; str_copy(buffer, path, sizeof(buffer)); - for(p = buffer+1; *p != '\0'; p++) + for(p = buffer + 1; *p != '\0'; p++) { if(*p == '/' && *(p + 1) != '\0') { @@ -2077,7 +2090,7 @@ int fs_makedir(const char *path) { #if defined(CONF_FAMILY_WINDOWS) if(_mkdir(path) == 0) - return 0; + return 0; if(errno == EEXIST) return 0; return -1; @@ -2096,20 +2109,20 @@ int fs_is_dir(const char *path) /* TODO: do this smarter */ WIN32_FIND_DATA finddata; HANDLE handle; - char buffer[1024*2]; + char buffer[1024 * 2]; str_format(buffer, sizeof(buffer), "%s/*", path); - if ((handle = FindFirstFileA(buffer, &finddata)) == INVALID_HANDLE_VALUE) + if((handle = FindFirstFileA(buffer, &finddata)) == INVALID_HANDLE_VALUE) return 0; FindClose(handle); return 1; #else struct stat sb; - if (stat(path, &sb) == -1) + if(stat(path, &sb) == -1) return 0; - if (S_ISDIR(sb.st_mode)) + if(S_ISDIR(sb.st_mode)) return 1; else return 0; @@ -2119,7 +2132,7 @@ int fs_is_dir(const char *path) time_t fs_getmtime(const char *path) { struct stat sb; - if (stat(path, &sb) == -1) + if(stat(path, &sb) == -1) return 0; return sb.st_mtime; @@ -2187,12 +2200,12 @@ int fs_rename(const char *oldname, const char *newname) void swap_endian(void *data, unsigned elem_size, unsigned num) { - char *src = (char*) data; + char *src = (char *)data; char *dst = src + (elem_size - 1); while(num) { - unsigned n = elem_size>>1; + unsigned n = elem_size >> 1; char tmp; while(n) { @@ -2205,7 +2218,7 @@ void swap_endian(void *data, unsigned elem_size, unsigned num) n--; } - src = src + (elem_size>>1); + src = src + (elem_size >> 1); dst = src + (elem_size - 1); num--; } @@ -2247,9 +2260,9 @@ int net_socket_read_wait(NETSOCKET sock, int time) /* don't care about writefds and exceptfds */ if(time < 0) - select(sockid+1, &readfds, NULL, NULL, NULL); + select(sockid + 1, &readfds, NULL, NULL, NULL); else - select(sockid+1, &readfds, NULL, NULL, &tv); + select(sockid + 1, &readfds, NULL, NULL, &tv); if(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds)) return 1; @@ -2321,13 +2334,13 @@ void str_append(char *dst, const char *src, int dst_size) i++; } - dst[dst_size-1] = 0; /* assure null termination */ + dst[dst_size - 1] = 0; /* assure null termination */ } void str_copy(char *dst, const char *src, int dst_size) { - strncpy(dst, src, dst_size-1); - dst[dst_size-1] = 0; /* assure null termination */ + strncpy(dst, src, dst_size - 1); + dst[dst_size - 1] = 0; /* assure null termination */ } void str_utf8_truncate(char *dst, int dst_size, const char *src, int truncation_len) @@ -2341,7 +2354,7 @@ void str_utf8_truncate(char *dst, int dst_size, const char *src, int truncation_ cursor = str_utf8_forward(src, cursor); pos++; } - str_copy(dst, src, size+1); + str_copy(dst, src, size + 1); } void str_truncate(char *dst, int dst_size, const char *src, int truncation_len) @@ -2368,7 +2381,7 @@ int str_format(char *buffer, int buffer_size, const char *format, ...) ret = _vsnprintf(buffer, buffer_size, format, ap); va_end(ap); - buffer[buffer_size-1] = 0; /* assure null termination */ + buffer[buffer_size - 1] = 0; /* assure null termination */ /* _vsnprintf is documented to return negative values on truncation, but * in practice we didn't see that. let's handle it anyway just in case. */ @@ -2392,9 +2405,9 @@ int str_format(char *buffer, int buffer_size, const char *format, ...) char *str_trim_words(char *str, int words) { - while (words && *str) + while(words && *str) { - if (isspace(*str) && !isspace(*(str + 1))) + if(isspace(*str) && !isspace(*(str + 1))) words--; str++; } @@ -2513,9 +2526,9 @@ const char *str_skip_whitespaces_const(const char *str) int str_comp_nocase(const char *a, const char *b) { #if defined(CONF_FAMILY_WINDOWS) - return _stricmp(a,b); + return _stricmp(a, b); #else - return strcasecmp(a,b); + return strcasecmp(a, b); #endif } @@ -2551,9 +2564,9 @@ int str_comp_filenames(const char *a, const char *b) { if(!result) result = *a - *b; - ++a; ++b; - } - while(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9'); + ++a; + ++b; + } while(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9'); if(*a >= '0' && *a <= '9') return 1; @@ -2661,8 +2674,7 @@ int str_utf32_dist_buffer(const int *a, int a_len, const int *b, int b_len, int B(i, j) = min3( B(i - 1, j) + 1, B(i, j - 1) + 1, - B(i - 1, j - 1) + subst - ); + B(i - 1, j - 1) + subst); } } return B(a_len, b_len); @@ -2713,7 +2725,6 @@ const char *str_find_nocase(const char *haystack, const char *needle) return 0; } - const char *str_find(const char *haystack, const char *needle) { while(*haystack) /* native implementation */ @@ -2743,43 +2754,43 @@ void str_hex(char *dst, int dst_size, const void *data, int data_size) static const char hex[] = "0123456789ABCDEF"; int b; - for(b = 0; b < data_size && b < dst_size/4-4; b++) + for(b = 0; b < data_size && b < dst_size / 4 - 4; b++) { - dst[b*3] = hex[((const unsigned char *)data)[b]>>4]; - dst[b*3+1] = hex[((const unsigned char *)data)[b]&0xf]; - dst[b*3+2] = ' '; - dst[b*3+3] = 0; + dst[b * 3] = hex[((const unsigned char *)data)[b] >> 4]; + dst[b * 3 + 1] = hex[((const unsigned char *)data)[b] & 0xf]; + dst[b * 3 + 2] = ' '; + dst[b * 3 + 3] = 0; } } static int hexval(char x) { - switch(x) - { - case '0': return 0; - case '1': return 1; - case '2': return 2; - case '3': return 3; - case '4': return 4; - case '5': return 5; - case '6': return 6; - case '7': return 7; - case '8': return 8; - case '9': return 9; - case 'a': - case 'A': return 10; - case 'b': - case 'B': return 11; - case 'c': - case 'C': return 12; - case 'd': - case 'D': return 13; - case 'e': - case 'E': return 14; - case 'f': - case 'F': return 15; - default: return -1; - } + switch(x) + { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + case 'a': + case 'A': return 10; + case 'b': + case 'B': return 11; + case 'c': + case 'C': return 12; + case 'd': + case 'D': return 13; + case 'e': + case 'E': return 14; + case 'f': + case 'F': return 15; + default: return -1; + } } static int byteval(const char *byte, unsigned char *dst) @@ -2821,7 +2832,7 @@ void str_timestamp_ex(time_t time_data, char *buffer, int buffer_size, const cha struct tm *time_info; time_info = localtime(&time_data); strftime(buffer, buffer_size, format, time_info); - buffer[buffer_size-1] = 0; /* assure null termination */ + buffer[buffer_size - 1] = 0; /* assure null termination */ } void str_timestamp_format(char *buffer, int buffer_size, const char *format) @@ -2857,7 +2868,7 @@ void str_escape(char **dst, const char *src, const char *end) int mem_comp(const void *a, const void *b, int size) { - return memcmp(a,b,size); + return memcmp(a, b, size); } void net_stats(NETSTATS *stats_inout) @@ -2870,7 +2881,7 @@ int str_isspace(char c) { return c == ' ' || c == '\n' || c == '\t'; } char str_uppercase(char c) { if(c >= 'a' && c <= 'z') - return 'A' + (c-'a'); + return 'A' + (c - 'a'); return c; } @@ -2954,12 +2965,12 @@ const char *str_utf8_find_nocase(const char *haystack, const char *needle) int str_utf8_isspace(int code) { return code <= 0x0020 || code == 0x0085 || code == 0x00A0 || - code == 0x034F || code == 0x1680 || code == 0x180E || - (code >= 0x2000 && code <= 0x200F) || (code >= 0x2028 && code <= 0x202F) || - (code >= 0x205F && code <= 0x2064) || (code >= 0x206A && code <= 0x206F) || - code == 0x2800 || code == 0x3000 || - (code >= 0xFE00 && code <= 0xFE0F) || code == 0xFEFF || - (code >= 0xFFF9 && code <= 0xFFFC); + code == 0x034F || code == 0x1680 || code == 0x180E || + (code >= 0x2000 && code <= 0x200F) || (code >= 0x2028 && code <= 0x202F) || + (code >= 0x205F && code <= 0x2064) || (code >= 0x206A && code <= 0x206F) || + code == 0x2800 || code == 0x3000 || + (code >= 0xFE00 && code <= 0xFE0F) || code == 0xFEFF || + (code >= 0xFFF9 && code <= 0xFFFC); } const char *str_utf8_skip_whitespaces(const char *str) @@ -3009,7 +3020,7 @@ void str_utf8_trim_right(char *param) int str_utf8_isstart(char c) { - if((c&0xC0) == 0x80) /* 10xxxxxx */ + if((c & 0xC0) == 0x80) /* 10xxxxxx */ return 0; return 1; } @@ -3031,29 +3042,35 @@ int str_utf8_forward(const char *str, int cursor) if(!buf[0]) return cursor; - if((*buf&0x80) == 0x0) /* 0xxxxxxx */ - return cursor+1; - else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ + if((*buf & 0x80) == 0x0) /* 0xxxxxxx */ + return cursor + 1; + else if((*buf & 0xE0) == 0xC0) /* 110xxxxx */ { - if(!buf[1]) return cursor+1; - return cursor+2; + if(!buf[1]) + return cursor + 1; + return cursor + 2; } - else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ + else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ { - if(!buf[1]) return cursor+1; - if(!buf[2]) return cursor+2; - return cursor+3; + if(!buf[1]) + return cursor + 1; + if(!buf[2]) + return cursor + 2; + return cursor + 3; } - else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ + else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ { - if(!buf[1]) return cursor+1; - if(!buf[2]) return cursor+2; - if(!buf[3]) return cursor+3; - return cursor+4; + if(!buf[1]) + return cursor + 1; + if(!buf[2]) + return cursor + 2; + if(!buf[3]) + return cursor + 3; + return cursor + 4; } /* invalid */ - return cursor+1; + return cursor + 1; } int str_utf8_encode(char *ptr, int chr) @@ -3066,23 +3083,23 @@ int str_utf8_encode(char *ptr, int chr) } else if(chr <= 0x7FF) { - ptr[0] = 0xC0|((chr>>6)&0x1F); - ptr[1] = 0x80|(chr&0x3F); + ptr[0] = 0xC0 | ((chr >> 6) & 0x1F); + ptr[1] = 0x80 | (chr & 0x3F); return 2; } else if(chr <= 0xFFFF) { - ptr[0] = 0xE0|((chr>>12)&0x0F); - ptr[1] = 0x80|((chr>>6)&0x3F); - ptr[2] = 0x80|(chr&0x3F); + ptr[0] = 0xE0 | ((chr >> 12) & 0x0F); + ptr[1] = 0x80 | ((chr >> 6) & 0x3F); + ptr[2] = 0x80 | (chr & 0x3F); return 3; } else if(chr <= 0x10FFFF) { - ptr[0] = 0xF0|((chr>>18)&0x07); - ptr[1] = 0x80|((chr>>12)&0x3F); - ptr[2] = 0x80|((chr>>6)&0x3F); - ptr[3] = 0x80|(chr&0x3F); + ptr[0] = 0xF0 | ((chr >> 18) & 0x07); + ptr[1] = 0x80 | ((chr >> 12) & 0x3F); + ptr[2] = 0x80 | ((chr >> 6) & 0x3F); + ptr[3] = 0x80 | (chr & 0x3F); return 4; } @@ -3151,15 +3168,19 @@ int str_utf8_decode(const char **ptr) } else if(0xE0 <= byte && byte <= 0xEF) { - if(byte == 0xE0) utf8_lower_boundary = 0xA0; - if(byte == 0xED) utf8_upper_boundary = 0x9F; + if(byte == 0xE0) + utf8_lower_boundary = 0xA0; + if(byte == 0xED) + utf8_upper_boundary = 0x9F; utf8_bytes_needed = 2; utf8_code_point = byte - 0xE0; } else if(0xF0 <= byte && byte <= 0xF4) { - if(byte == 0xF0) utf8_lower_boundary = 0x90; - if(byte == 0xF4) utf8_upper_boundary = 0x8F; + if(byte == 0xF0) + utf8_lower_boundary = 0x90; + if(byte == 0xF4) + utf8_upper_boundary = 0x8F; utf8_bytes_needed = 3; utf8_code_point = byte - 0xF0; } @@ -3285,7 +3306,7 @@ PROCESS shell_execute(const char *file) #elif defined(CONF_FAMILY_UNIX) char *argv[2]; pid_t pid; - argv[0] = (char*) file; + argv[0] = (char *)file; argv[1] = NULL; pid = fork(); if(pid == -1) @@ -3337,7 +3358,7 @@ int os_is_winxp_or_lower(void) ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&ver); return ver.dwMajorVersion < WINXP_MAJOR || - (ver.dwMajorVersion == WINXP_MAJOR && ver.dwMinorVersion <= WINXP_MINOR); + (ver.dwMajorVersion == WINXP_MAJOR && ver.dwMinorVersion <= WINXP_MINOR); #else return 0; #endif @@ -3353,7 +3374,7 @@ struct SECURE_RANDOM_DATA #endif }; -static struct SECURE_RANDOM_DATA secure_random_data = { 0 }; +static struct SECURE_RANDOM_DATA secure_random_data = {0}; int secure_random_init(void) { @@ -3447,7 +3468,7 @@ int secure_rand(void) { unsigned int i; secure_random_fill(&i, sizeof(i)); - return (int)(i%RAND_MAX); + return (int)(i % RAND_MAX); } #if defined(__cplusplus) diff --git a/src/base/system.h b/src/base/system.h index a59301ae0..89d382c8d 100644 --- a/src/base/system.h +++ b/src/base/system.h @@ -23,8 +23,8 @@ #endif #ifdef CONF_PLATFORM_LINUX -#include #include +#include #endif #ifdef __cplusplus @@ -47,17 +47,16 @@ extern "C" { */ #ifdef CONF_DEBUG -#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) +#define dbg_assert(test, msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) #else -#define dbg_assert(test,msg) +#define dbg_assert(test, msg) #endif void dbg_assert_imp(const char *filename, int line, int test, const char *msg); - #ifdef __clang_analyzer__ #include #undef dbg_assert -#define dbg_assert(test,msg) assert(test) +#define dbg_assert(test, msg) assert(test) #endif #ifdef __GNUC__ @@ -99,7 +98,7 @@ void dbg_break_imp(void); */ void dbg_msg(const char *sys, const char *fmt, ...) -GNUC_ATTRIBUTE((format(printf, 2, 3))); + GNUC_ATTRIBUTE((format(printf, 2, 3))); /* Group: Memory */ @@ -166,7 +165,8 @@ void mem_zero(void *block, unsigned size); int mem_comp(const void *a, const void *b, int size); /* Group: File IO */ -enum { +enum +{ IOFLAG_READ = 1, IOFLAG_WRITE = 2, IOFLAG_RANDOM = 4, @@ -321,7 +321,6 @@ int io_flush(IOHANDLE io); */ int io_error(IOHANDLE io); - /* Function: io_stdin Returns an to the standard input. @@ -532,7 +531,7 @@ void thread_detach(void *thread); void *thread_init_and_detach(void (*threadfunc)(void *), void *user, const char *name); /* Group: Locks */ -typedef void* LOCK; +typedef void *LOCK; LOCK lock_create(void); void lock_destroy(LOCK lock); @@ -541,18 +540,17 @@ int lock_trylock(LOCK lock); void lock_wait(LOCK lock); void lock_unlock(LOCK lock); - /* Group: Semaphores */ #if defined(CONF_FAMILY_WINDOWS) - typedef void* SEMAPHORE; +typedef void *SEMAPHORE; #elif defined(CONF_PLATFORM_MACOSX) - #include - typedef sem_t* SEMAPHORE; +#include +typedef sem_t *SEMAPHORE; #elif defined(CONF_FAMILY_UNIX) - #include - typedef sem_t SEMAPHORE; +#include +typedef sem_t SEMAPHORE; #else - #error not implemented on this platform +#error not implemented on this platform #endif void sphore_init(SEMAPHORE *sem); @@ -663,14 +661,14 @@ typedef struct enum { - NETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX + NETADDR_MAXSTRSIZE = 1 + (8 * 4 + 7) + 1 + 1 + 5 + 1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX NETTYPE_INVALID = 0, NETTYPE_IPV4 = 1, NETTYPE_IPV6 = 2, NETTYPE_LINK_BROADCAST = 4, NETTYPE_WEBSOCKET_IPV4 = 8, - NETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6|NETTYPE_WEBSOCKET_IPV4 + NETTYPE_ALL = NETTYPE_IPV4 | NETTYPE_IPV6 | NETTYPE_WEBSOCKET_IPV4 }; typedef struct @@ -813,7 +811,7 @@ typedef struct #endif } MMSGS; -void net_init_mmsgs(MMSGS* m); +void net_init_mmsgs(MMSGS *m); /* Function: net_udp_recv @@ -830,7 +828,7 @@ void net_init_mmsgs(MMSGS* m); On success it returns the number of bytes received. Returns -1 on error. */ -int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS* m, unsigned char **data); +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS *m, unsigned char **data); /* Function: net_udp_close @@ -844,7 +842,6 @@ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS */ int net_udp_close(NETSOCKET sock); - /* Group: Network TCP */ /* @@ -1086,7 +1083,7 @@ int str_length(const char *str); - Guarantees that dst string will contain zero-termination. */ int str_format(char *buffer, int buffer_size, const char *format, ...) -GNUC_ATTRIBUTE((format(printf, 3, 4))); + GNUC_ATTRIBUTE((format(printf, 3, 4))); /* Function: str_trim_words @@ -1495,9 +1492,9 @@ int str_hex_decode(void *dst, int dst_size, const char *src); */ void str_timestamp(char *buffer, int buffer_size); void str_timestamp_format(char *buffer, int buffer_size, const char *format) -GNUC_ATTRIBUTE((format(strftime, 3, 0))); + GNUC_ATTRIBUTE((format(strftime, 3, 0))); void str_timestamp_ex(time_t time, char *buffer, int buffer_size, const char *format) -GNUC_ATTRIBUTE((format(strftime, 4, 0))); + GNUC_ATTRIBUTE((format(strftime, 4, 0))); #define FORMAT_TIME "%H:%M:%S" #define FORMAT_SPACE "%Y-%m-%d %H:%M:%S" @@ -1660,7 +1657,6 @@ int fs_rename(const char *oldname, const char *newname); Group: Undocumented */ - /* Function: net_tcp_connect_non_blocking @@ -1715,7 +1711,6 @@ int open_link(const char *link); void swap_endian(void *data, unsigned elem_size, unsigned num); - typedef void (*DBG_LOGGER)(const char *line, void *user); typedef void (*DBG_LOGGER_FINISH)(void *user); void dbg_logger(DBG_LOGGER logger, DBG_LOGGER_FINISH finish, void *user); @@ -1732,7 +1727,6 @@ typedef struct int recv_bytes; } NETSTATS; - void net_stats(NETSTATS *stats); int str_toint(const char *str); diff --git a/src/base/tl/algorithm.h b/src/base/tl/algorithm.h index a9136d28a..d90fcc9c9 100644 --- a/src/base/tl/algorithm.h +++ b/src/base/tl/algorithm.h @@ -6,7 +6,6 @@ #include "base/tl/range.h" #include - /* insert 4 v @@ -14,7 +13,6 @@ */ - template R partition_linear(R range, T value) { @@ -30,7 +28,6 @@ R partition_linear(R range, T value) return range; } - template R partition_binary(R range, T value) { @@ -47,11 +44,11 @@ R partition_binary(R range, T value) while(range.size() > 1) { - unsigned pivot = (range.size()-1)/2; + unsigned pivot = (range.size() - 1) / 2; if(range.index(pivot) < value) - range = range.slice(pivot+1, range.size()-1); + range = range.slice(pivot + 1, range.size() - 1); else - range = range.slice(0, pivot+1); + range = range.slice(0, pivot + 1); } return range; } @@ -71,12 +68,13 @@ template R find_binary(R range, T value) { range = partition_linear(range, value); - if(range.empty()) return range; - if(range.front() == value) return range; + if(range.empty()) + return range; + if(range.front() == value) + return range; return R(); } - template void sort_bubble(R range) { @@ -107,14 +105,12 @@ void sort_quick(R range) concept_index::check(range); }*/ - template void sort(R range) { sort_bubble(range); } - template bool sort_verify(R range) { diff --git a/src/base/tl/allocator.h b/src/base/tl/allocator.h index d12347e30..5d04d1192 100644 --- a/src/base/tl/allocator.h +++ b/src/base/tl/allocator.h @@ -3,15 +3,15 @@ #ifndef BASE_TL_ALLOCATOR_H #define BASE_TL_ALLOCATOR_H -template +template class allocator_default { public: static T *alloc() { return new T; } static void free(T *p) { delete p; } - static T *alloc_array(int size) { return new T [size]; } - static void free_array(T *p) { delete [] p; } + static T *alloc_array(int size) { return new T[size]; } + static void free_array(T *p) { delete[] p; } }; #endif // TL_FILE_ALLOCATOR_HPP diff --git a/src/base/tl/array.h b/src/base/tl/array.h index 829a4d789..998b83a10 100644 --- a/src/base/tl/array.h +++ b/src/base/tl/array.h @@ -3,9 +3,8 @@ #ifndef BASE_TL_ARRAY_H #define BASE_TL_ARRAY_H -#include "base/tl/range.h" #include "base/tl/allocator.h" - +#include "base/tl/range.h" /* Class: array @@ -16,7 +15,7 @@ - Use set_size() if you know how many elements - Use optimize() to reduce the needed space. */ -template > +template> class array : private ALLOCATOR { void init() @@ -47,7 +46,6 @@ public: (*this)[i] = other[i]; } - /* Function: array destructor */ @@ -57,7 +55,6 @@ public: list = 0x0; } - /* Function: delete_all @@ -71,7 +68,6 @@ public: clear(); } - /* Function: clear @@ -102,8 +98,8 @@ public: */ void remove_index_fast(int index) { - list[index] = list[num_elements-1]; - set_size(size()-1); + list[index] = list[num_elements - 1]; + set_size(size() - 1); } /* @@ -112,7 +108,7 @@ public: Remarks: - Invalidates ranges */ - void remove_fast(const T& item) + void remove_fast(const T &item) { for(int i = 0; i < size(); i++) if(list[i] == item) @@ -130,10 +126,10 @@ public: */ void remove_index(int index) { - for(int i = index+1; i < num_elements; i++) - list[i-1] = list[i]; + for(int i = index + 1; i < num_elements; i++) + list[i - 1] = list[i]; - set_size(size()-1); + set_size(size() - 1); } /* @@ -142,7 +138,7 @@ public: Remarks: - Invalidates ranges */ - bool remove(const T& item) + bool remove(const T &item) { for(int i = 0; i < size(); i++) if(list[i] == item) @@ -164,12 +160,12 @@ public: - Invalidates ranges - See remarks about how the array grows. */ - int add(const T& item) + int add(const T &item) { incsize(); - set_size(size()+1); - list[num_elements-1] = item; - return num_elements-1; + set_size(size() + 1); + list[num_elements - 1] = item; + return num_elements - 1; } /* @@ -184,27 +180,27 @@ public: - Invalidates ranges - See remarks about how the array grows. */ - int insert(const T& item, range r) + int insert(const T &item, range r) { if(r.empty()) return add(item); - int index = (int)(&r.front()-list); + int index = (int)(&r.front() - list); incsize(); - set_size(size()+1); + set_size(size() + 1); - for(int i = num_elements-1; i > index; i--) - list[i] = list[i-1]; + for(int i = num_elements - 1; i > index; i--) + list[i] = list[i - 1]; list[index] = item; - return num_elements-1; + return num_elements - 1; } /* Function: operator[] */ - T& operator[] (int index) + T &operator[](int index) { return list[index]; } @@ -212,7 +208,7 @@ public: /* Function: const operator[] */ - const T& operator[] (int index) const + const T &operator[](int index) const { return list[index]; } @@ -242,7 +238,7 @@ public: */ void set_size(int new_size) { - if(list_size < new_size) + if(list_size < new_size) alloc(new_size); num_elements = new_size; } @@ -265,7 +261,6 @@ public: alloc(hint); } - /* Function: optimize Removes unnecessary data, returns how many bytes was earned. @@ -286,7 +281,7 @@ public: */ int memusage() { - return sizeof(array) + sizeof(T)*list_size; + return sizeof(array) + sizeof(T) * list_size; } /* @@ -295,7 +290,7 @@ public: Remarks: - Invalidates ranges */ - array &operator = (const array &other) + array &operator=(const array &other) { set_size(other.size()); for(int i = 0; i < size(); i++) @@ -307,17 +302,17 @@ public: Function: all Returns a range that contains the whole array. */ - range all() { return range(list, list+num_elements); } -protected: + range all() { return range(list, list + num_elements); } +protected: void incsize() { if(num_elements == list_size) { if(list_size < 2) - alloc(list_size+1); + alloc(list_size + 1); else - alloc(list_size+list_size/2); + alloc(list_size + list_size / 2); } } diff --git a/src/base/tl/base.h b/src/base/tl/base.h index 71d5e4aa9..f64f35078 100644 --- a/src/base/tl/base.h +++ b/src/base/tl/base.h @@ -3,8 +3,8 @@ #ifndef BASE_TL_BASE_H #define BASE_TL_BASE_H -#include #include +#include #include using std::swap; diff --git a/src/base/tl/range.h b/src/base/tl/range.h index 6947cc4b3..fc63530f9 100644 --- a/src/base/tl/range.h +++ b/src/base/tl/range.h @@ -20,7 +20,12 @@ */ struct concept_empty { - template static void check(T &t) { if(0) t.empty(); } + template + static void check(T &t) + { + if(0) + t.empty(); + } }; /* @@ -34,7 +39,12 @@ struct concept_empty */ struct concept_index { - template static void check(T &t) { if(0) t.index(0); } + template + static void check(T &t) + { + if(0) + t.index(0); + } }; /* @@ -48,7 +58,12 @@ struct concept_index */ struct concept_size { - template static void check(T &t) { if(0) t.size(); } + template + static void check(T &t) + { + if(0) + t.size(); + } }; /* @@ -62,7 +77,12 @@ struct concept_size */ struct concept_slice { - template static void check(T &t) { if(0) t.slice(0, 0); } + template + static void check(T &t) + { + if(0) + t.slice(0, 0); + } }; /* @@ -76,7 +96,12 @@ struct concept_slice */ struct concept_sorted { - template static void check(T &t) { if(0) t.sorted(); } + template + static void check(T &t) + { + if(0) + t.sorted(); + } }; /* @@ -92,7 +117,15 @@ struct concept_sorted */ struct concept_forwarditeration { - template static void check(T &t) { if(0) { t.front(); t.pop_front(); } } + template + static void check(T &t) + { + if(0) + { + t.front(); + t.pop_front(); + } + } }; /* @@ -108,15 +141,21 @@ struct concept_forwarditeration */ struct concept_backwarditeration { - template static void check(T &t) { if(0) { t.back(); t.pop_back(); } } + template + static void check(T &t) + { + if(0) + { + t.back(); + t.pop_back(); + } + } }; - /* Group: Range classes */ - /* Class: plain_range @@ -145,15 +184,35 @@ public: } bool empty() const { return begin >= end; } - void pop_front() { tl_assert(!empty()); begin++; } - void pop_back() { tl_assert(!empty()); end--; } - T& front() { tl_assert(!empty()); return *begin; } - T& back() { tl_assert(!empty()); return *(end-1); } - T& index(unsigned i) { tl_assert(i < (unsigned)(end-begin)); return begin[i]; } - unsigned size() const { return (unsigned)(end-begin); } + void pop_front() + { + tl_assert(!empty()); + begin++; + } + void pop_back() + { + tl_assert(!empty()); + end--; + } + T &front() + { + tl_assert(!empty()); + return *begin; + } + T &back() + { + tl_assert(!empty()); + return *(end - 1); + } + T &index(unsigned i) + { + tl_assert(i < (unsigned)(end - begin)); + return begin[i]; + } + unsigned size() const { return (unsigned)(end - begin); } plain_range slice(unsigned startindex, unsigned endindex) { - return plain_range(begin+startindex, begin+endindex); + return plain_range(begin + startindex, begin + endindex); } protected: @@ -172,20 +231,23 @@ template class plain_range_sorted : public plain_range { typedef plain_range parent; + public: /* sorted concept */ - void sorted() const { } + void sorted() const {} plain_range_sorted() - {} + { + } - plain_range_sorted(T *b, T *e) - : parent(b, e) - {} + plain_range_sorted(T *b, T *e) : + parent(b, e) + { + } plain_range_sorted slice(unsigned start, unsigned count) { - return plain_range_sorted(parent::begin+start, parent::begin+start+count); + return plain_range_sorted(parent::begin + start, parent::begin + start + count); } }; @@ -194,6 +256,7 @@ class reverse_range { private: reverse_range() {} + public: typedef typename R::type type; @@ -204,20 +267,23 @@ public: reverse_range(const reverse_range &other) { range = other.range; } - bool empty() const { return range.empty(); } void pop_front() { range.pop_back(); } void pop_back() { range.pop_front(); } - type& front() { return range.back(); } - type& back() { return range.front(); } + type &front() { return range.back(); } + type &back() { return range.front(); } R range; }; -template reverse_range reverse(R range) { +template +reverse_range reverse(R range) +{ return reverse_range(range); } -template R reverse(reverse_range range) { +template +R reverse(reverse_range range) +{ return range.range; } diff --git a/src/base/tl/sorted_array.h b/src/base/tl/sorted_array.h index 1bc77e881..f4c1dd95e 100644 --- a/src/base/tl/sorted_array.h +++ b/src/base/tl/sorted_array.h @@ -6,24 +6,32 @@ #include "base/tl/algorithm.h" #include "base/tl/array.h" -template > +template> class sorted_array : public array { typedef array parent; // insert and size is not allowed - int insert(const T& item, typename parent::range r) { dbg_break(); return 0; } - int set_size(int new_size) { dbg_break(); return 0; } + int insert(const T &item, typename parent::range r) + { + dbg_break(); + return 0; + } + int set_size(int new_size) + { + dbg_break(); + return 0; + } public: typedef plain_range_sorted range; - int add(const T& item) + int add(const T &item) { return parent::insert(item, partition_binary(all(), item)); } - int add_unsorted(const T& item) + int add_unsorted(const T &item) { return parent::add(item); } @@ -33,12 +41,11 @@ public: sort(all()); } - /* Function: all Returns a sorted range that contains the whole array. */ - range all() { return range(parent::list, parent::list+parent::num_elements); } + range all() { return range(parent::list, parent::list + parent::num_elements); } }; #endif // TL_FILE_SORTED_ARRAY_HPP diff --git a/src/base/tl/string.h b/src/base/tl/string.h index d93f7581a..3a3c772e3 100644 --- a/src/base/tl/string.h +++ b/src/base/tl/string.h @@ -3,10 +3,10 @@ #ifndef BASE_TL_STRING_H #define BASE_TL_STRING_H -#include "base/tl/base.h" #include "base/tl/allocator.h" +#include "base/tl/base.h" -template +template class string_base : private ALLOCATOR { char *str; @@ -14,7 +14,8 @@ class string_base : private ALLOCATOR void reset() { - str = 0; length = 0; + str = 0; + length = 0; } void free() @@ -26,8 +27,8 @@ class string_base : private ALLOCATOR void copy(const char *other_str, int other_length) { length = other_length; - str = ALLOCATOR::alloc_array(length+1); - mem_copy(str, other_str, length+1); + str = ALLOCATOR::alloc_array(length + 1); + mem_copy(str, other_str, length + 1); } void copy(const string_base &other) @@ -40,10 +41,14 @@ class string_base : private ALLOCATOR public: string_base() { reset(); } string_base(const char *other_str) { copy(other_str, str_length(other_str)); } - string_base(const string_base &other) { reset(); copy(other); } + string_base(const string_base &other) + { + reset(); + copy(other); + } ~string_base() { free(); } - string_base &operator = (const char *other) + string_base &operator=(const char *other) { free(); if(other) @@ -51,20 +56,20 @@ public: return *this; } - string_base &operator = (const string_base &other) + string_base &operator=(const string_base &other) { free(); copy(other); return *this; } - bool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; } + bool operator<(const char *other_str) const { return str_comp(str, other_str) < 0; } operator const char *() const { return str; } const char *cstr() const { return str; } }; /* normal allocated string */ -typedef string_base > string; +typedef string_base> string; #endif // TL_FILE_STRING_HPP diff --git a/src/base/tl/threading.h b/src/base/tl/threading.h index 55b69e3cf..c8ce5a461 100644 --- a/src/base/tl/threading.h +++ b/src/base/tl/threading.h @@ -6,10 +6,11 @@ class semaphore { SEMAPHORE sem; + public: semaphore() { sphore_init(&sem); } ~semaphore() { sphore_destroy(&sem); } - semaphore(const semaphore&) = delete; + semaphore(const semaphore &) = delete; void wait() { sphore_wait(&sem); } void signal() { sphore_signal(&sem); } }; @@ -29,7 +30,7 @@ public: lock_destroy(var); } - lock(const lock&) = delete; + lock(const lock &) = delete; void take() { lock_wait(var); } void release() { lock_unlock(var); } @@ -38,6 +39,7 @@ public: class scope_lock { lock *var; + public: scope_lock(lock *l) { @@ -50,7 +52,7 @@ public: var->release(); } - scope_lock(const scope_lock&) = delete; + scope_lock(const scope_lock &) = delete; }; #endif // BASE_TL_THREADING_H diff --git a/src/base/unicode/confusables_data.h b/src/base/unicode/confusables_data.h index d0868fb6f..0328456d0 100644 --- a/src/base/unicode/confusables_data.h +++ b/src/base/unicode/confusables_data.h @@ -8,8 +8,8 @@ struct DECOMP_SLICE enum { - NUM_DECOMP_LENGTHS=8, - NUM_DECOMPS=9563, + NUM_DECOMP_LENGTHS = 8, + NUM_DECOMPS = 9563, }; static const uint8_t decomp_lengths[NUM_DECOMP_LENGTHS] = { diff --git a/src/base/unicode/tolower.c b/src/base/unicode/tolower.c index 942e326f1..d6db32ad1 100644 --- a/src/base/unicode/tolower.c +++ b/src/base/unicode/tolower.c @@ -4,19 +4,19 @@ static int compul(const void *a, const void *b) { - struct UPPER_LOWER *ul_a = (struct UPPER_LOWER *) a; - struct UPPER_LOWER *ul_b = (struct UPPER_LOWER *) b; - return ul_a->upper - ul_b->upper; + struct UPPER_LOWER *ul_a = (struct UPPER_LOWER *)a; + struct UPPER_LOWER *ul_b = (struct UPPER_LOWER *)b; + return ul_a->upper - ul_b->upper; } int str_utf8_tolower(int code) { - struct UPPER_LOWER key; - struct UPPER_LOWER *res; - key.upper = code; - res = bsearch(&key, tolower, NUM_TOLOWER, sizeof(struct UPPER_LOWER), compul); + struct UPPER_LOWER key; + struct UPPER_LOWER *res; + key.upper = code; + res = bsearch(&key, tolower, NUM_TOLOWER, sizeof(struct UPPER_LOWER), compul); - if(res == NULL) - return code; - return res->lower; + if(res == NULL) + return code; + return res->lower; } diff --git a/src/base/unicode/tolower_data.h b/src/base/unicode/tolower_data.h index 5a0e09e5d..222a5384d 100644 --- a/src/base/unicode/tolower_data.h +++ b/src/base/unicode/tolower_data.h @@ -8,7 +8,7 @@ struct UPPER_LOWER enum { - NUM_TOLOWER=1390, + NUM_TOLOWER = 1390, }; static const struct UPPER_LOWER tolower[] = { diff --git a/src/base/vmath.h b/src/base/vmath.h index 64a51e88c..f50c603ff 100644 --- a/src/base/vmath.h +++ b/src/base/vmath.h @@ -13,8 +13,14 @@ template class vector2_base { public: - union { T x,u; }; - union { T y,v; }; + union + { + T x, u; + }; + union + { + T y, v; + }; vector2_base() {} vector2_base(T nx, T ny) @@ -23,53 +29,82 @@ public: y = ny; } - vector2_base operator -() const { return vector2_base(-x, -y); } - vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); } - vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); } - vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); } - vector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); } - vector2_base operator /(const T v) const { return vector2_base(x/v, y/v); } - vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); } + vector2_base operator-() const { return vector2_base(-x, -y); } + vector2_base operator-(const vector2_base &v) const { return vector2_base(x - v.x, y - v.y); } + vector2_base operator+(const vector2_base &v) const { return vector2_base(x + v.x, y + v.y); } + vector2_base operator*(const T v) const { return vector2_base(x * v, y * v); } + vector2_base operator*(const vector2_base &v) const { return vector2_base(x * v.x, y * v.y); } + vector2_base operator/(const T v) const { return vector2_base(x / v, y / v); } + vector2_base operator/(const vector2_base &v) const { return vector2_base(x / v.x, y / v.y); } - const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; } - const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; } - const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this; } - const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; } - const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this; } - const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; } + const vector2_base &operator+=(const vector2_base &v) + { + x += v.x; + y += v.y; + return *this; + } + const vector2_base &operator-=(const vector2_base &v) + { + x -= v.x; + y -= v.y; + return *this; + } + const vector2_base &operator*=(const T v) + { + x *= v; + y *= v; + return *this; + } + const vector2_base &operator*=(const vector2_base &v) + { + x *= v.x; + y *= v.y; + return *this; + } + const vector2_base &operator/=(const T v) + { + x /= v; + y /= v; + return *this; + } + const vector2_base &operator/=(const vector2_base &v) + { + x /= v.x; + y /= v.y; + return *this; + } - bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead - bool operator !=(const vector2_base &v) const { return x != v.x || y != v.y; } + bool operator==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead + bool operator!=(const vector2_base &v) const { return x != v.x || y != v.y; } - operator const T* () { return &x; } + operator const T *() { return &x; } T &operator[](const int index) { return index ? y : x; } }; - template inline T length(const vector2_base &a) { - return sqrtf(a.x*a.x + a.y*a.y); + return sqrtf(a.x * a.x + a.y * a.y); } template inline T distance(const vector2_base a, const vector2_base &b) { - return length(a-b); + return length(a - b); } template inline T dot(const vector2_base a, const vector2_base &b) { - return a.x*b.x + a.y*b.y; + return a.x * b.x + a.y * b.y; } template inline vector2_base normalize(const vector2_base &v) { - T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y)); - return vector2_base(v.x*l, v.y*l); + T l = (T)(1.0f / sqrtf(v.x * v.x + v.y * v.y)); + return vector2_base(v.x * l, v.y * l); } typedef vector2_base vec2; @@ -82,8 +117,8 @@ inline vector2_base closest_point_on_line(vector2_base line_point0, vector vector2_base c = target_point - line_point0; vector2_base v = (line_point1 - line_point0); v = normalize(v); - T d = length(line_point0-line_point1); - T t = dot(v, c)/d; + T d = length(line_point0 - line_point1); + T t = dot(v, c) / d; return mix(line_point0, line_point1, clamp(t, (T)0, (T)1)); /* if (t < 0) t = 0; @@ -96,9 +131,18 @@ template class vector3_base { public: - union { T x,r,h; }; - union { T y,g,s; }; - union { T z,b,v,l; }; + union + { + T x, r, h; + }; + union + { + T y, g, s; + }; + union + { + T z, b, v, l; + }; vector3_base() {} vector3_base(T nx, T ny, T nz) @@ -108,30 +152,66 @@ public: z = nz; } - vector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); } - vector3_base operator -() const { return vector3_base(-x, -y, -z); } - vector3_base operator +(const vector3_base &v) const { return vector3_base(x+v.x, y+v.y, z+v.z); } - vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); } - vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); } - vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); } - vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); } + vector3_base operator-(const vector3_base &v) const { return vector3_base(x - v.x, y - v.y, z - v.z); } + vector3_base operator-() const { return vector3_base(-x, -y, -z); } + vector3_base operator+(const vector3_base &v) const { return vector3_base(x + v.x, y + v.y, z + v.z); } + vector3_base operator*(const T v) const { return vector3_base(x * v, y * v, z * v); } + vector3_base operator*(const vector3_base &v) const { return vector3_base(x * v.x, y * v.y, z * v.z); } + vector3_base operator/(const T v) const { return vector3_base(x / v, y / v, z / v); } + vector3_base operator/(const vector3_base &v) const { return vector3_base(x / v.x, y / v.y, z / v.z); } - const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; } - const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } - const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this; } - const vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } - const vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this; } - const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } + const vector3_base &operator+=(const vector3_base &v) + { + x += v.x; + y += v.y; + z += v.z; + return *this; + } + const vector3_base &operator-=(const vector3_base &v) + { + x -= v.x; + y -= v.y; + z -= v.z; + return *this; + } + const vector3_base &operator*=(const T v) + { + x *= v; + y *= v; + z *= v; + return *this; + } + const vector3_base &operator*=(const vector3_base &v) + { + x *= v.x; + y *= v.y; + z *= v.z; + return *this; + } + const vector3_base &operator/=(const T v) + { + x /= v; + y /= v; + z /= v; + return *this; + } + const vector3_base &operator/=(const vector3_base &v) + { + x /= v.x; + y /= v.y; + z /= v.z; + return *this; + } - bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead + bool operator==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead - operator const T* () { return &x; } + operator const T *() { return &x; } }; template inline T length(const vector3_base &a) { - return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z); + return sqrtf(a.x * a.x + a.y * a.y + a.z * a.z); } template @@ -146,29 +226,29 @@ inline vector2_base rotate(const vector2_base &a, float angle) template inline T distance(const vector3_base &a, const vector3_base &b) { - return length(a-b); + return length(a - b); } template inline T dot(const vector3_base &a, const vector3_base &b) { - return a.x*b.x + a.y*b.y + a.z*b.z; + return a.x * b.x + a.y * b.y + a.z * b.z; } template inline vector3_base normalize(const vector3_base &v) { - T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y + v.z*v.z)); - return vector3_base(v.x*l, v.y*l, v.z*l); + T l = (T)(1.0f / sqrtf(v.x * v.x + v.y * v.y + v.z * v.z)); + return vector3_base(v.x * l, v.y * l, v.z * l); } template inline vector3_base cross(const vector3_base &a, const vector3_base &b) { return vector3_base( - a.y*b.z - a.z*b.y, - a.z*b.x - a.x*b.z, - a.x*b.y - a.y*b.x); + a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x); } typedef vector3_base vec3; @@ -181,10 +261,22 @@ template class vector4_base { public: - union { T x,r,h; }; - union { T y,g,s; }; - union { T z,b,l; }; - union { T w,a; }; + union + { + T x, r, h; + }; + union + { + T y, g, s; + }; + union + { + T z, b, l; + }; + union + { + T w, a; + }; vector4_base() {} vector4_base(T nx, T ny, T nz, T nw) @@ -195,24 +287,66 @@ public: w = nw; } - vector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); } - vector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); } - vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); } - vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); } - vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); } - vector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); } - vector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); } + vector4_base operator+(const vector4_base &v) const { return vector4_base(x + v.x, y + v.y, z + v.z, w + v.w); } + vector4_base operator-(const vector4_base &v) const { return vector4_base(x - v.x, y - v.y, z - v.z, w - v.w); } + vector4_base operator-() const { return vector4_base(-x, -y, -z, -w); } + vector4_base operator*(const vector4_base &v) const { return vector4_base(x * v.x, y * v.y, z * v.z, w * v.w); } + vector4_base operator*(const T v) const { return vector4_base(x * v, y * v, z * v, w * v); } + vector4_base operator/(const vector4_base &v) const { return vector4_base(x / v.x, y / v.y, z / v.z, w / v.w); } + vector4_base operator/(const T v) const { return vector4_base(x / v, y / v, z / v, w / v); } - const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } - const vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } - const vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this; } - const vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } - const vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this; } - const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } + const vector4_base &operator+=(const vector4_base &v) + { + x += v.x; + y += v.y; + z += v.z; + w += v.w; + return *this; + } + const vector4_base &operator-=(const vector4_base &v) + { + x -= v.x; + y -= v.y; + z -= v.z; + w -= v.w; + return *this; + } + const vector4_base &operator*=(const T v) + { + x *= v; + y *= v; + z *= v; + w *= v; + return *this; + } + const vector4_base &operator*=(const vector4_base &v) + { + x *= v.x; + y *= v.y; + z *= v.z; + w *= v.w; + return *this; + } + const vector4_base &operator/=(const T v) + { + x /= v; + y /= v; + z /= v; + w /= v; + return *this; + } + const vector4_base &operator/=(const vector4_base &v) + { + x /= v.x; + y /= v.y; + z /= v.z; + w /= v.w; + return *this; + } - bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead + bool operator==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead - operator const T* () { return &x; } + operator const T *() { return &x; } }; typedef vector4_base vec4; diff --git a/src/engine/antibot.h b/src/engine/antibot.h index d5d48d116..179aeaf61 100644 --- a/src/engine/antibot.h +++ b/src/engine/antibot.h @@ -24,7 +24,7 @@ public: // Commands virtual void Dump() = 0; - virtual ~IAntibot() { }; + virtual ~IAntibot(){}; }; class IEngineAntibot : public IAntibot @@ -39,7 +39,7 @@ public: virtual void OnEngineClientDrop(int ClientID, const char *pReason) = 0; virtual void OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) = 0; - virtual ~IEngineAntibot() { }; + virtual ~IEngineAntibot(){}; }; #endif //ENGINE_ANTIBOT_H diff --git a/src/engine/client.h b/src/engine/client.h index c8a9161bd..1db21ed87 100644 --- a/src/engine/client.h +++ b/src/engine/client.h @@ -4,17 +4,17 @@ #define ENGINE_CLIENT_H #include "kernel.h" -#include "message.h" #include "graphics.h" +#include "message.h" #include enum { - RECORDER_MANUAL=0, - RECORDER_AUTO=1, - RECORDER_RACE=2, - RECORDER_REPLAYS=3, - RECORDER_MAX=4, + RECORDER_MANUAL = 0, + RECORDER_AUTO = 1, + RECORDER_RACE = 2, + RECORDER_REPLAYS = 3, + RECORDER_MAX = 4, }; typedef bool (*CLIENTFUNC_FILTER)(const void *pData, int DataSize, void *pUser); @@ -41,6 +41,7 @@ protected: int m_GameTickSpeed; float m_FrameTimeAvg; + public: char m_aNews[3000]; int64 m_ReconnectTime; @@ -64,7 +65,7 @@ public: enum { - STATE_OFFLINE=0, + STATE_OFFLINE = 0, STATE_CONNECTING, STATE_LOADING, STATE_ONLINE, @@ -103,9 +104,9 @@ public: virtual void Restart() = 0; virtual void Quit() = 0; virtual const char *DemoPlayer_Play(const char *pFilename, int StorageType) = 0; - #if defined(CONF_VIDEORECORDER) +#if defined(CONF_VIDEORECORDER) virtual const char *DemoPlayer_Render(const char *pFilename, int StorageType, const char *pVideoName, int SpeedIndex) = 0; - #endif +#endif virtual void DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder) = 0; virtual void DemoRecorder_HandleAutoStart() = 0; virtual void DemoRecorder_Stop(int Recorder, bool RemoveFile = false) = 0; @@ -150,8 +151,8 @@ public: enum { - SNAP_CURRENT=0, - SNAP_PREV=1 + SNAP_CURRENT = 0, + SNAP_PREV = 1 }; // TODO: Refactor: should redo this a bit i think, too many virtual calls @@ -164,7 +165,7 @@ public: virtual void SnapSetStaticsize(int ItemType, int Size) = 0; virtual int SendMsg(CMsgPacker *pMsg, int Flags) = 0; - virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient=1) = 0; + virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient = 1) = 0; template int SendPackMsg(T *pMsg, int Flags) @@ -207,10 +208,9 @@ public: virtual void GenerateTimeoutSeed() = 0; - virtual IFriends* Foes() = 0; + virtual IFriends *Foes() = 0; virtual void GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount) = 0; - }; class IGameClient : public IInterface diff --git a/src/engine/client/backend_sdl.cpp b/src/engine/client/backend_sdl.cpp index 4ed003d67..cda1bd912 100644 --- a/src/engine/client/backend_sdl.cpp +++ b/src/engine/client/backend_sdl.cpp @@ -1,25 +1,25 @@ #include #if defined(CONF_FAMILY_WINDOWS) - // For FlashWindowEx, FLASHWINFO, FLASHW_TRAY - #define _WIN32_WINNT 0x0501 - #define WINVER 0x0501 +// For FlashWindowEx, FLASHWINFO, FLASHW_TRAY +#define _WIN32_WINNT 0x0501 +#define WINVER 0x0501 #endif #include #include +#include "SDL.h" +#include "SDL_opengl.h" +#include "SDL_syswm.h" #include #include -#include #include -#include "SDL.h" -#include "SDL_syswm.h" -#include "SDL_opengl.h" +#include #if defined(SDL_VIDEO_DRIVER_X11) - #include - #include +#include +#include #endif #include @@ -27,19 +27,18 @@ #include #if defined(CONF_VIDEORECORDER) - #include "video.h" +#include "video.h" #endif -#include "graphics_threaded.h" #include "backend_sdl.h" +#include "graphics_threaded.h" -#include "opengl_sl_program.h" #include "opengl_sl.h" +#include "opengl_sl_program.h" #ifdef __MINGW32__ -extern "C" -{ - int putenv(const char *); +extern "C" { +int putenv(const char *); } #endif @@ -47,19 +46,19 @@ extern "C" sync_barrier - creates a full hardware fence */ #if defined(__GNUC__) - inline void sync_barrier() - { - __sync_synchronize(); - } +inline void sync_barrier() +{ + __sync_synchronize(); +} #elif defined(_MSC_VER) - #define WIN32_LEAN_AND_MEAN - #include - inline void sync_barrier() - { - MemoryBarrier(); - } +#define WIN32_LEAN_AND_MEAN +#include +inline void sync_barrier() +{ + MemoryBarrier(); +} #else - #error missing atomic implementation for this compiler +#error missing atomic implementation for this compiler #endif // ------------ CGraphicsBackend_Threaded @@ -73,19 +72,19 @@ void CGraphicsBackend_Threaded::ThreadFunc(void *pUser) pThis->m_Activity.wait(); if(pThis->m_pBuffer) { - #ifdef CONF_PLATFORM_MACOSX - CAutoreleasePool AutoreleasePool; - #endif +#ifdef CONF_PLATFORM_MACOSX + CAutoreleasePool AutoreleasePool; +#endif pThis->m_pProcessor->RunBuffer(pThis->m_pBuffer); sync_barrier(); pThis->m_pBuffer = 0x0; pThis->m_BufferDone.signal(); } - #if defined(CONF_VIDEORECORDER) - if (IVideo::Current()) - IVideo::Current()->NextVideoFrameThread(); - #endif +#if defined(CONF_VIDEORECORDER) + if(IVideo::Current()) + IVideo::Current()->NextVideoFrameThread(); +#endif } } @@ -130,7 +129,7 @@ void CGraphicsBackend_Threaded::WaitForIdle() m_BufferDone.wait(); } -static bool Texture2DTo3D(void* pImageBuffer, int ImageWidth, int ImageHeight, int ImageColorChannelCount, int SplitCountWidth, int SplitCountHeight, void* pTarget3DImageData, int& Target3DImageWidth, int& Target3DImageHeight) +static bool Texture2DTo3D(void *pImageBuffer, int ImageWidth, int ImageHeight, int ImageColorChannelCount, int SplitCountWidth, int SplitCountHeight, void *pTarget3DImageData, int &Target3DImageWidth, int &Target3DImageHeight) { Target3DImageWidth = ImageWidth / SplitCountWidth; Target3DImageHeight = ImageHeight / SplitCountHeight; @@ -149,7 +148,7 @@ static bool Texture2DTo3D(void* pImageBuffer, int ImageWidth, int ImageHeight, i size_t TargetImageFullSize = (size_t)(TargetImageFullWidth * (size_t)Target3DImageHeight); ptrdiff_t ImageOffset = (ptrdiff_t)(((size_t)Y * FullImageWidth * (size_t)Target3DImageHeight) + ((size_t)Y3D * FullImageWidth) + ((size_t)X * TargetImageFullWidth)); ptrdiff_t TargetImageOffset = (ptrdiff_t)(TargetImageFullSize * (size_t)DepthIndex + ((size_t)Y3D * TargetImageFullWidth)); - mem_copy(((uint8_t*)pTarget3DImageData) + TargetImageOffset, ((uint8_t*)pImageBuffer) + (ptrdiff_t)(ImageOffset), TargetImageFullWidth); + mem_copy(((uint8_t *)pTarget3DImageData) + TargetImageOffset, ((uint8_t *)pImageBuffer) + (ptrdiff_t)(ImageOffset), TargetImageFullWidth); } } } @@ -164,7 +163,7 @@ void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SComman pCommand->m_pSemaphore->signal(); } -bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) +bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) { switch(pBaseCommand->m_Cmd) { @@ -193,17 +192,23 @@ static int HighestBit(int OfVar) int CCommandProcessorFragment_OpenGL::TexFormatToOpenGLFormat(int TexFormat) { - if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB; - if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_ALPHA; - if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) + return GL_RGB; + if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) + return GL_ALPHA; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) + return GL_RGBA; return GL_RGBA; } int CCommandProcessorFragment_OpenGL::TexFormatToImageColorChannelCount(int TexFormat) { - if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return 3; - if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return 1; - if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return 4; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) + return 3; + if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) + return 1; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) + return 4; return 4; } @@ -217,18 +222,18 @@ static float CubicHermite(float A, float B, float C, float D, float t) return (a * t * t * t) + (b * t * t) + (c * t) + d; } -static void GetPixelClamped(uint8_t* pSourceImage, int x, int y, uint32_t W, uint32_t H, size_t BPP, uint8_t aTmp[]) +static void GetPixelClamped(uint8_t *pSourceImage, int x, int y, uint32_t W, uint32_t H, size_t BPP, uint8_t aTmp[]) { x = clamp(x, 0, (int)W - 1); y = clamp(y, 0, (int)H - 1); - for (size_t i = 0; i < BPP; i++) + for(size_t i = 0; i < BPP; i++) { aTmp[i] = pSourceImage[x * BPP + (W * BPP * y) + i]; } } -static void SampleBicubic(uint8_t* pSourceImage, float u, float v, uint32_t W, uint32_t H, size_t BPP, uint8_t aSample[]) +static void SampleBicubic(uint8_t *pSourceImage, float u, float v, uint32_t W, uint32_t H, size_t BPP, uint8_t aSample[]) { float X = (u * W) - 0.5f; int xInt = (int)X; @@ -258,7 +263,7 @@ static void SampleBicubic(uint8_t* pSourceImage, float u, float v, uint32_t W, u uint8_t PX23[4]; uint8_t PX33[4]; - GetPixelClamped(pSourceImage, xInt - 1, yInt - 1, W, H, BPP, PX00); + GetPixelClamped(pSourceImage, xInt - 1, yInt - 1, W, H, BPP, PX00); GetPixelClamped(pSourceImage, xInt + 0, yInt - 1, W, H, BPP, PX10); GetPixelClamped(pSourceImage, xInt + 1, yInt - 1, W, H, BPP, PX20); GetPixelClamped(pSourceImage, xInt + 2, yInt - 1, W, H, BPP, PX30); @@ -278,7 +283,7 @@ static void SampleBicubic(uint8_t* pSourceImage, float u, float v, uint32_t W, u GetPixelClamped(pSourceImage, xInt + 1, yInt + 2, W, H, BPP, PX23); GetPixelClamped(pSourceImage, xInt + 2, yInt + 2, W, H, BPP, PX33); - for (size_t i = 0; i < BPP; i++) + for(size_t i = 0; i < BPP; i++) { float Clmn0 = CubicHermite(PX00[i], PX10[i], PX20[i], PX30[i], xFract); float Clmn1 = CubicHermite(PX01[i], PX11[i], PX21[i], PX31[i], xFract); @@ -307,7 +312,7 @@ static void ResizeImage(uint8_t *pSourceImage, uint32_t SW, uint32_t SH, uint8_t float u = (float)x / (float)(W - 1); SampleBicubic(pSourceImage, u, v, SW, SH, BPP, aSample); - for (size_t i = 0; i < BPP; ++i) + for(size_t i = 0; i < BPP; ++i) { pDestinationImage[x * BPP + ((W * BPP) * y) + i] = aSample[i]; } @@ -323,7 +328,7 @@ void *CCommandProcessorFragment_OpenGL::Resize(int Width, int Height, int NewWid pTmpData = (unsigned char *)malloc(NewWidth * NewHeight * Bpp); - ResizeImage((uint8_t*)pData, Width, Height, (uint8_t*)pTmpData, NewWidth, NewHeight, Bpp); + ResizeImage((uint8_t *)pData, Width, Height, (uint8_t *)pTmpData, NewWidth, NewHeight, Bpp); return pTmpData; } @@ -418,7 +423,6 @@ void CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &St { dbg_msg("OpenGL", "Error: this call should not happen."); } - } } @@ -458,7 +462,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Update(const CCommandBuffer:: { glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); - void* pTexData = pCommand->m_pData; + void *pTexData = pCommand->m_pData; int Width = pCommand->m_Width; int Height = pCommand->m_Height; int X = pCommand->m_X; @@ -594,7 +598,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: } while(Width > m_MaxTexSize || Height > m_MaxTexSize); NeedsResize = true; } - else if(pCommand->m_Format != CCommandBuffer::TEXFORMAT_ALPHA && (Width > 16 && Height > 16 && (pCommand->m_Flags&CCommandBuffer::TEXFLAG_QUALITY) == 0)) + else if(pCommand->m_Format != CCommandBuffer::TEXFORMAT_ALPHA && (Width > 16 && Height > 16 && (pCommand->m_Flags & CCommandBuffer::TEXFLAG_QUALITY) == 0)) { Width >>= 1; Height >>= 1; @@ -616,26 +620,26 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: int Oglformat = TexFormatToOpenGLFormat(pCommand->m_Format); int StoreOglformat = TexFormatToOpenGLFormat(pCommand->m_StoreFormat); - if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_COMPRESSED) + if(pCommand->m_Flags & CCommandBuffer::TEXFLAG_COMPRESSED) { switch(StoreOglformat) { - case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB_ARB; break; - case GL_ALPHA: StoreOglformat = GL_COMPRESSED_ALPHA_ARB; break; - case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA_ARB; break; - default: StoreOglformat = GL_COMPRESSED_RGBA_ARB; + case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB_ARB; break; + case GL_ALPHA: StoreOglformat = GL_COMPRESSED_ALPHA_ARB; break; + case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA_ARB; break; + default: StoreOglformat = GL_COMPRESSED_RGBA_ARB; } } - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); } - if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS || !m_HasMipMaps) + if(pCommand->m_Flags & CCommandBuffer::TEXFLAG_NOMIPMAPS || !m_HasMipMaps) { - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -644,7 +648,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: } else { - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); @@ -654,9 +658,9 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: int Flag2DArrayTexture = (CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE | CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER); int Flag3DTexture = (CCommandBuffer::TEXFLAG_TO_3D_TEXTURE | CCommandBuffer::TEXFLAG_TO_3D_TEXTURE_SINGLE_LAYER); - if((pCommand->m_Flags&(Flag2DArrayTexture | Flag3DTexture)) != 0) + if((pCommand->m_Flags & (Flag2DArrayTexture | Flag3DTexture)) != 0) { - bool Is3DTexture = (pCommand->m_Flags&Flag3DTexture) != 0; + bool Is3DTexture = (pCommand->m_Flags & Flag3DTexture) != 0; glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex2DArray); @@ -670,7 +674,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: { Target = m_2DArrayTarget; } - + glBindTexture(Target, m_aTextures[pCommand->m_Slot].m_Tex2DArray); if(IsNewApi()) @@ -693,7 +697,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: if(IsNewApi()) glSamplerParameteri(m_aTextures[pCommand->m_Slot].m_Sampler2DArray, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); } - + glTexParameteri(Target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(Target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(Target, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT); @@ -709,12 +713,12 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: int ImageColorChannels = TexFormatToImageColorChannelCount(pCommand->m_Format); - uint8_t* p3DImageData = NULL; + uint8_t *p3DImageData = NULL; - bool IsSingleLayer = (pCommand->m_Flags& (CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER | CCommandBuffer::TEXFLAG_TO_3D_TEXTURE_SINGLE_LAYER)) != 0; + bool IsSingleLayer = (pCommand->m_Flags & (CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER | CCommandBuffer::TEXFLAG_TO_3D_TEXTURE_SINGLE_LAYER)) != 0; if(!IsSingleLayer) - p3DImageData = (uint8_t*)malloc(ImageColorChannels * Width * Height); + p3DImageData = (uint8_t *)malloc(ImageColorChannels * Width * Height); int Image3DWidth, Image3DHeight; int ConvertWidth = Width; @@ -727,7 +731,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: dbg_msg("gfx", "3D/2D array texture was resized"); int NewWidth = maximum(HighestBit(ConvertWidth), 16); int NewHeight = maximum(HighestBit(ConvertHeight), 16); - uint8_t* pNewTexData = (uint8_t*)Resize(ConvertWidth, ConvertHeight, NewWidth, NewHeight, pCommand->m_Format, (const uint8_t*)pTexData); + uint8_t *pNewTexData = (uint8_t *)Resize(ConvertWidth, ConvertHeight, NewWidth, NewHeight, pCommand->m_Format, (const uint8_t *)pTexData); ConvertWidth = NewWidth; ConvertHeight = NewHeight; @@ -755,7 +759,7 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: glTexParameteriv(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); }*/ } - + if(!IsSingleLayer) free(p3DImageData); } @@ -765,12 +769,12 @@ void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer:: m_aTextures[pCommand->m_Slot].m_LastWrapMode = CCommandBuffer::WRAP_REPEAT; // calculate memory usage - m_aTextures[pCommand->m_Slot].m_MemSize = Width*Height*pCommand->m_PixelSize; + m_aTextures[pCommand->m_Slot].m_MemSize = Width * Height * pCommand->m_PixelSize; while(Width > 2 && Height > 2) { - Width>>=1; - Height>>=1; - m_aTextures[pCommand->m_Slot].m_MemSize += Width*Height*pCommand->m_PixelSize; + Width >>= 1; + Height >>= 1; + m_aTextures[pCommand->m_Slot].m_MemSize += Width * Height * pCommand->m_PixelSize; } m_pTextureMemoryUsage->store(m_pTextureMemoryUsage->load(std::memory_order_relaxed) + m_aTextures[pCommand->m_Slot].m_MemSize, std::memory_order_relaxed); @@ -787,9 +791,9 @@ void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand { SetState(pCommand->m_State); - glVertexPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices); - glTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*2); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*4); + glVertexPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char *)pCommand->m_pVertices); + glTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char *)pCommand->m_pVertices + sizeof(float) * 2); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(CCommandBuffer::SVertex), (char *)pCommand->m_pVertices + sizeof(float) * 4); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); @@ -797,13 +801,13 @@ void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand switch(pCommand->m_PrimType) { case CCommandBuffer::PRIMTYPE_QUADS: - glDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount*4); + glDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount * 4); break; case CCommandBuffer::PRIMTYPE_LINES: - glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2); + glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount * 2); break; case CCommandBuffer::PRIMTYPE_TRIANGLES: - glDrawArrays(GL_TRIANGLES, 0, pCommand->m_PrimCount*3); + glDrawArrays(GL_TRIANGLES, 0, pCommand->m_PrimCount * 3); break; default: dbg_msg("render", "unknown primtype %d\n", pCommand->m_Cmd); @@ -813,29 +817,29 @@ void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand void CCommandProcessorFragment_OpenGL::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand) { // fetch image data - GLint aViewport[4] = {0,0,0,0}; + GLint aViewport[4] = {0, 0, 0, 0}; glGetIntegerv(GL_VIEWPORT, aViewport); int w = aViewport[2]; int h = aViewport[3]; // we allocate one more row to use when we are flipping the texture - unsigned char *pPixelData = (unsigned char *)malloc(w*(h+1)*3); - unsigned char *pTempRow = pPixelData+w*h*3; + unsigned char *pPixelData = (unsigned char *)malloc(w * (h + 1) * 3); + unsigned char *pTempRow = pPixelData + w * h * 3; // fetch the pixels GLint Alignment; glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment); glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); + glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); glPixelStorei(GL_PACK_ALIGNMENT, Alignment); // flip the pixel because opengl works from bottom left corner - for(int y = 0; y < h/2; y++) + for(int y = 0; y < h / 2; y++) { - mem_copy(pTempRow, pPixelData+y*w*3, w*3); - mem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3); - mem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3); + mem_copy(pTempRow, pPixelData + y * w * 3, w * 3); + mem_copy(pPixelData + y * w * 3, pPixelData + (h - y - 1) * w * 3, w * 3); + mem_copy(pPixelData + (h - y - 1) * w * 3, pTempRow, w * 3); } // fill in the information @@ -851,7 +855,7 @@ CCommandProcessorFragment_OpenGL::CCommandProcessorFragment_OpenGL() m_HasShaders = false; } -bool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) +bool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) { switch(pBaseCommand->m_Cmd) { @@ -1038,7 +1042,7 @@ void CCommandProcessorFragment_OpenGL2::SetState(const CCommandBuffer::SState &S glBindTexture(m_2DArrayTarget, m_aTextures[State.m_Texture].m_Tex2DArray); if(IsNewApi()) glBindSampler(Slot, m_aTextures[State.m_Texture].m_Sampler2DArray); - } + } } } if(pProgram->m_LocIsTextured != -1) @@ -1058,7 +1062,7 @@ void CCommandProcessorFragment_OpenGL2::SetState(const CCommandBuffer::SState &S if(m_aTextures[State.m_Texture].m_LastWrapMode != State.m_WrapMode && !Use2DArrayTextures) { - switch (State.m_WrapMode) + switch(State.m_WrapMode) { case CCommandBuffer::WRAP_REPEAT: if(IsNewApi()) @@ -1109,11 +1113,12 @@ void CCommandProcessorFragment_OpenGL2::SetState(const CCommandBuffer::SState &S }; // transpose bcs of column-major order of opengl - glUniformMatrix4x2fv(pProgram->m_LocPos, 1, true, (float*)&m); + glUniformMatrix4x2fv(pProgram->m_LocPos, 1, true, (float *)&m); } } -bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t CheckCount, size_t VerticesCount, uint8_t aFakeTexture[], size_t SingleImageSize) { +bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t CheckCount, size_t VerticesCount, uint8_t aFakeTexture[], size_t SingleImageSize) +{ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int Slot = 0; @@ -1128,17 +1133,16 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check if(StepN == 1) { - float aColor[4] = { 1.f, 1.f, 1.f, 1.f }; - pProgram->SetUniformVec4(((CGLSLTileProgram*)pProgram)->m_LocColor, 1, aColor); + float aColor[4] = {1.f, 1.f, 1.f, 1.f}; + pProgram->SetUniformVec4(((CGLSLTileProgram *)pProgram)->m_LocColor, 1, aColor); } float m[2 * 4] = { 1, 0, 0, 0, - 0, 1, 0, 0 - }; + 0, 1, 0, 0}; // transpose bcs of column-major order of opengl - glUniformMatrix4x2fv(pProgram->m_LocPos, 1, true, (float*)&m); + glUniformMatrix4x2fv(pProgram->m_LocPos, 1, true, (float *)&m); } else { @@ -1146,7 +1150,7 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check glLoadIdentity(); glOrtho(-1, 1, -1, 1, -10.0f, 10.f); } - + GLuint BufferID = 0; if(StepN == 1 && m_HasShaders) { @@ -1157,7 +1161,7 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof((m_aStreamVertices[0])), 0); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 3, GL_FLOAT, false, sizeof((m_aStreamVertices[0])), (GLvoid*)(sizeof(vec4) + sizeof(vec2))); + glVertexAttribPointer(1, 3, GL_FLOAT, false, sizeof((m_aStreamVertices[0])), (GLvoid *)(sizeof(vec4) + sizeof(vec2))); } else { @@ -1166,8 +1170,8 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(m_aStreamVertices[0]), m_aStreamVertices); - glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); - glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); + glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); + glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); } glDrawArrays(GL_QUADS, 0, VerticesCount); @@ -1193,7 +1197,7 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check glFinish(); - GLint aViewport[4] = {0,0,0,0}; + GLint aViewport[4] = {0, 0, 0, 0}; glGetIntegerv(GL_VIEWPORT, aViewport); int w = aViewport[2]; @@ -1210,7 +1214,7 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); glPixelStorei(GL_PACK_ALIGNMENT, Alignment); - + // now analyse the image data bool CheckFailed = false; int WidthTile = w / 16; @@ -1229,8 +1233,8 @@ bool CCommandProcessorFragment_OpenGL2::DoAnalyzeStep(size_t StepN, size_t Check ptrdiff_t OffsetFakeTexture = SingleImageSize * d; OffsetPixelData = clamp(OffsetPixelData, 0, (ptrdiff_t)PixelDataSize); OffsetFakeTexture = clamp(OffsetFakeTexture, 0, (ptrdiff_t)(SingleImageSize * CheckCount)); - uint8_t* pPixel = pPixelData + OffsetPixelData; - uint8_t* pPixelTex = aFakeTexture + OffsetFakeTexture; + uint8_t *pPixel = pPixelData + OffsetPixelData; + uint8_t *pPixelTex = aFakeTexture + OffsetFakeTexture; for(size_t i = 0; i < 3; ++i) { if((pPixel[i] < pPixelTex[i] - 25) || (pPixel[i] > pPixelTex[i] + 25)) @@ -1252,11 +1256,11 @@ bool CCommandProcessorFragment_OpenGL2::IsTileMapAnalysisSucceeded() // create fake texture 1024x1024 const size_t ImageWidth = 1024; const size_t ImageHeight = 1024; - uint8_t* pFakeTexture = (uint8_t*)malloc(sizeof(uint8_t) * ImageWidth * ImageHeight * 4); + uint8_t *pFakeTexture = (uint8_t *)malloc(sizeof(uint8_t) * ImageWidth * ImageHeight * 4); // fill by colors stepping by 50 => (255 / 50 ~ 5) => 5 times 3(color channels) = 5 ^ 3 = 125 possibilities to check size_t CheckCount = 5 * 5 * 5; // always fill 4 pixels of the texture, so the sampling is accurate - int aCurColor[4] = { 25, 25, 25, 255 }; + int aCurColor[4] = {25, 25, 25, 255}; const size_t SingleImageWidth = 64; const size_t SingleImageHeight = 64; size_t SingleImageSize = SingleImageWidth * SingleImageHeight * 4; @@ -1303,7 +1307,7 @@ bool CCommandProcessorFragment_OpenGL2::IsTileMapAnalysisSucceeded() { Target = m_2DArrayTarget; } - + glBindTexture(Target, FakeTexture); glTexParameteri(Target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if(!m_Has2DArrayTextures) @@ -1315,17 +1319,17 @@ bool CCommandProcessorFragment_OpenGL2::IsTileMapAnalysisSucceeded() glTexParameteri(Target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(Target, GL_GENERATE_MIPMAP, GL_TRUE); } - + glTexParameteri(Target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(Target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(Target, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT); - + glTexImage3D(Target, 0, GL_RGBA, ImageWidth / 16, ImageHeight / 16, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, pFakeTexture); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_SCISSOR_TEST); - + glDisable(GL_TEXTURE_2D); if(m_Has3DTextures) glDisable(GL_TEXTURE_3D); @@ -1415,7 +1419,7 @@ bool CCommandProcessorFragment_OpenGL2::IsTileMapAnalysisSucceeded() bool NoError = DoAnalyzeStep(0, CheckCount, VertexCount, pFakeTexture, SingleImageSize); if(NoError && m_HasShaders) NoError &= DoAnalyzeStep(1, CheckCount, VertexCount, pFakeTexture, SingleImageSize); - + glDeleteTextures(1, &FakeTexture); free(pFakeTexture); @@ -1425,7 +1429,7 @@ bool CCommandProcessorFragment_OpenGL2::IsTileMapAnalysisSucceeded() void CCommandProcessorFragment_OpenGL2::Cmd_Init(const SCommand_Init *pCommand) { CCommandProcessorFragment_OpenGL::Cmd_Init(pCommand); - + m_HasShaders = pCommand->m_pCapabilities->m_ShaderSupport; bool HasAllFunc = true; @@ -1657,7 +1661,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CreateBufferObject(const CCommandBuf glBindBuffer(GL_COPY_WRITE_BUFFER, 0); } - SBufferObject& BufferObject = m_BufferObjectIndices[Index]; + SBufferObject &BufferObject = m_BufferObjectIndices[Index]; BufferObject.m_BufferObjectID = VertBufferID; BufferObject.m_DataSize = pCommand->m_DataSize; BufferObject.m_pData = malloc(pCommand->m_DataSize); @@ -1668,7 +1672,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CreateBufferObject(const CCommandBuf void CCommandProcessorFragment_OpenGL2::Cmd_RecreateBufferObject(const CCommandBuffer::SCommand_RecreateBufferObject *pCommand) { int Index = pCommand->m_BufferIndex; - SBufferObject& BufferObject = m_BufferObjectIndices[Index]; + SBufferObject &BufferObject = m_BufferObjectIndices[Index]; if(m_HasShaders) { @@ -1688,7 +1692,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RecreateBufferObject(const CCommandB void CCommandProcessorFragment_OpenGL2::Cmd_UpdateBufferObject(const CCommandBuffer::SCommand_UpdateBufferObject *pCommand) { int Index = pCommand->m_BufferIndex; - SBufferObject& BufferObject = m_BufferObjectIndices[Index]; + SBufferObject &BufferObject = m_BufferObjectIndices[Index]; if(m_HasShaders) { @@ -1698,7 +1702,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_UpdateBufferObject(const CCommandBuf } if(pCommand->m_pUploadData) - mem_copy(((uint8_t*)BufferObject.m_pData) + (ptrdiff_t)pCommand->m_pOffset, pCommand->m_pUploadData, pCommand->m_DataSize); + mem_copy(((uint8_t *)BufferObject.m_pData) + (ptrdiff_t)pCommand->m_pOffset, pCommand->m_pUploadData, pCommand->m_DataSize); } void CCommandProcessorFragment_OpenGL2::Cmd_CopyBufferObject(const CCommandBuffer::SCommand_CopyBufferObject *pCommand) @@ -1706,15 +1710,15 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CopyBufferObject(const CCommandBuffe int WriteIndex = pCommand->m_WriteBufferIndex; int ReadIndex = pCommand->m_ReadBufferIndex; - SBufferObject& ReadBufferObject = m_BufferObjectIndices[ReadIndex]; - SBufferObject& WriteBufferObject = m_BufferObjectIndices[WriteIndex]; + SBufferObject &ReadBufferObject = m_BufferObjectIndices[ReadIndex]; + SBufferObject &WriteBufferObject = m_BufferObjectIndices[WriteIndex]; + + mem_copy(((uint8_t *)WriteBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pWriteOffset, ((uint8_t *)ReadBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pReadOffset, pCommand->m_CopySize); - mem_copy(((uint8_t*)WriteBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pWriteOffset, ((uint8_t*)ReadBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pReadOffset, pCommand->m_CopySize); - if(m_HasShaders) { glBindBuffer(GL_COPY_WRITE_BUFFER, WriteBufferObject.m_BufferObjectID); - glBufferSubData(GL_COPY_WRITE_BUFFER, (GLintptr)(pCommand->m_pWriteOffset), (GLsizeiptr)(pCommand->m_CopySize), ((uint8_t*)WriteBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pWriteOffset); + glBufferSubData(GL_COPY_WRITE_BUFFER, (GLintptr)(pCommand->m_pWriteOffset), (GLsizeiptr)(pCommand->m_CopySize), ((uint8_t *)WriteBufferObject.m_pData) + (ptrdiff_t)pCommand->m_pWriteOffset); glBindBuffer(GL_COPY_WRITE_BUFFER, 0); } } @@ -1722,7 +1726,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CopyBufferObject(const CCommandBuffe void CCommandProcessorFragment_OpenGL2::Cmd_DeleteBufferObject(const CCommandBuffer::SCommand_DeleteBufferObject *pCommand) { int Index = pCommand->m_BufferIndex; - SBufferObject& BufferObject = m_BufferObjectIndices[Index]; + SBufferObject &BufferObject = m_BufferObjectIndices[Index]; if(m_HasShaders) { @@ -1750,11 +1754,11 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CreateBufferContainer(const CCommand } } - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; for(int i = 0; i < pCommand->m_AttrCount; ++i) { - SBufferContainerInfo::SAttribute& Attr = pCommand->m_Attributes[i]; + SBufferContainerInfo::SAttribute &Attr = pCommand->m_Attributes[i]; BufferContainer.m_ContainerInfo.m_Attributes.push_back(Attr); } @@ -1763,12 +1767,13 @@ void CCommandProcessorFragment_OpenGL2::Cmd_CreateBufferContainer(const CCommand void CCommandProcessorFragment_OpenGL2::Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) { - SBufferContainer& BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; + SBufferContainer &BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; BufferContainer.m_ContainerInfo.m_Attributes.clear(); - for(int i = 0; i < pCommand->m_AttrCount; ++i) { - SBufferContainerInfo::SAttribute& Attr = pCommand->m_Attributes[i]; + for(int i = 0; i < pCommand->m_AttrCount; ++i) + { + SBufferContainerInfo::SAttribute &Attr = pCommand->m_Attributes[i]; BufferContainer.m_ContainerInfo.m_Attributes.push_back(Attr); } @@ -1777,7 +1782,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_UpdateBufferContainer(const CCommand void CCommandProcessorFragment_OpenGL2::Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) { - SBufferContainer& BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; + SBufferContainer &BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; if(pCommand->m_DestroyAllBO) { @@ -1789,7 +1794,8 @@ void CCommandProcessorFragment_OpenGL2::Cmd_DeleteBufferContainer(const CCommand for(size_t j = 0; j < BufferContainer.m_ContainerInfo.m_Attributes.size(); ++j) { // set all equal ids to zero to not double delete - if(VertBufferID == BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex) { + if(VertBufferID == BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex) + { BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex = -1; } } @@ -1815,7 +1821,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_IndicesRequiredNumNotify(const CComm { } -void CCommandProcessorFragment_OpenGL2::RenderBorderTileEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int DrawNum, const float* pOffset, const float* pDir, int JumpIndex) +void CCommandProcessorFragment_OpenGL2::RenderBorderTileEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int DrawNum, const float *pOffset, const float *pDir, int JumpIndex) { if(m_HasShaders) { @@ -1835,45 +1841,43 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileEmulation(SBufferContain { CCommandProcessorFragment_OpenGL::SetState(State, true); } - bool IsTextured = BufferContainer.m_ContainerInfo.m_Attributes.size() == 2; - SBufferObject& BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; - + SBufferObject &BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; + glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); if(IsTextured) glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(2, GL_FLOAT, sizeof(m_aStreamVertices[0]), m_aStreamVertices); - glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); + glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); if(IsTextured) - glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); + glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); size_t VertexCount = 0; for(size_t i = 0; i < DrawNum; ++i) { GLint RealOffset = (GLint)((((size_t)(uintptr_t)(pBuffOffset)) / (6 * sizeof(unsigned int))) * 4); size_t SingleVertSize = (sizeof(vec2) + (IsTextured ? sizeof(vec3) : 0)); - size_t CurBufferOffset = (RealOffset) * SingleVertSize; + size_t CurBufferOffset = (RealOffset)*SingleVertSize; for(size_t n = 0; n < 4; ++n) { - int XCount = i - (int(i/JumpIndex) * JumpIndex); - int YCount = (int(i/JumpIndex)); + int XCount = i - (int(i / JumpIndex) * JumpIndex); + int YCount = (int(i / JumpIndex)); ptrdiff_t VertOffset = (ptrdiff_t)(CurBufferOffset + (n * SingleVertSize)); - vec2* pPos = (vec2*)((uint8_t*)BufferObject.m_pData + VertOffset); + vec2 *pPos = (vec2 *)((uint8_t *)BufferObject.m_pData + VertOffset); - GL_SVertexTex3D& Vertex = m_aStreamVertices[VertexCount++]; + GL_SVertexTex3D &Vertex = m_aStreamVertices[VertexCount++]; mem_copy(&Vertex.m_Pos, pPos, sizeof(vec2)); mem_copy(&Vertex.m_Color, pColor, sizeof(vec4)); if(IsTextured) { - vec3* pTex = (vec3*)((uint8_t*)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); + vec3 *pTex = (vec3 *)((uint8_t *)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); mem_copy(&Vertex.m_Tex, pTex, sizeof(vec3)); } @@ -1884,7 +1888,7 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileEmulation(SBufferContain { glDrawArrays(GL_QUADS, 0, VertexCount); VertexCount = 0; - } + } } } if(VertexCount > 0) @@ -1902,7 +1906,7 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileEmulation(SBufferContain } } -void CCommandProcessorFragment_OpenGL2::RenderBorderTileLineEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float* pOffset, const float* pDir) +void CCommandProcessorFragment_OpenGL2::RenderBorderTileLineEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float *pOffset, const float *pDir) { if(m_HasShaders) { @@ -1922,12 +1926,11 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileLineEmulation(SBufferCon { CCommandProcessorFragment_OpenGL::SetState(State, true); } - bool IsTextured = BufferContainer.m_ContainerInfo.m_Attributes.size() == 2; - SBufferObject& BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; - + SBufferObject &BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; + glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); @@ -1935,29 +1938,29 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileLineEmulation(SBufferCon glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(m_aStreamVertices[0]), m_aStreamVertices); - glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); + glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); if(IsTextured) - glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); + glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); size_t VertexCount = 0; for(size_t i = 0; i < DrawNum; ++i) { GLint RealOffset = (GLint)((((size_t)(uintptr_t)(pBuffOffset)) / (6 * sizeof(unsigned int))) * 4); size_t SingleVertSize = (sizeof(vec2) + (IsTextured ? sizeof(vec3) : 0)); - size_t CurBufferOffset = (RealOffset) * SingleVertSize; + size_t CurBufferOffset = (RealOffset)*SingleVertSize; size_t VerticesPerLine = (size_t)IndexDrawNum / 6; for(size_t n = 0; n < 4 * (size_t)VerticesPerLine; ++n) { ptrdiff_t VertOffset = (ptrdiff_t)(CurBufferOffset + (n * SingleVertSize)); - vec2* pPos = (vec2*)((uint8_t*)BufferObject.m_pData + VertOffset); + vec2 *pPos = (vec2 *)((uint8_t *)BufferObject.m_pData + VertOffset); - GL_SVertexTex3D& Vertex = m_aStreamVertices[VertexCount++]; + GL_SVertexTex3D &Vertex = m_aStreamVertices[VertexCount++]; mem_copy(&Vertex.m_Pos, pPos, sizeof(vec2)); mem_copy(&Vertex.m_Color, pColor, sizeof(vec4)); if(IsTextured) { - vec3* pTex = (vec3*)((uint8_t*)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); + vec3 *pTex = (vec3 *)((uint8_t *)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); mem_copy(&Vertex.m_Tex, pTex, sizeof(vec3)); } @@ -1968,7 +1971,7 @@ void CCommandProcessorFragment_OpenGL2::RenderBorderTileLineEmulation(SBufferCon { glDrawArrays(GL_QUADS, 0, VertexCount); VertexCount = 0; - } + } } } if(VertexCount > 0) @@ -1993,9 +1996,9 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderBorderTile(const CCommandBuffe if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; - RenderBorderTileEmulation(BufferContainer, pCommand->m_State, (float*)&pCommand->m_Color, pCommand->m_pIndicesOffset, pCommand->m_DrawNum, pCommand->m_Offset, pCommand->m_Dir, pCommand->m_JumpIndex); + RenderBorderTileEmulation(BufferContainer, pCommand->m_State, (float *)&pCommand->m_Color, pCommand->m_pIndicesOffset, pCommand->m_DrawNum, pCommand->m_Offset, pCommand->m_Dir, pCommand->m_JumpIndex); } void CCommandProcessorFragment_OpenGL2::Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) @@ -2005,9 +2008,9 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderBorderTileLine(const CCommandB if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; - RenderBorderTileLineEmulation(BufferContainer, pCommand->m_State, (float*)&pCommand->m_Color, pCommand->m_pIndicesOffset, pCommand->m_IndexDrawNum, pCommand->m_DrawNum, pCommand->m_Offset, pCommand->m_Dir); + RenderBorderTileLineEmulation(BufferContainer, pCommand->m_State, (float *)&pCommand->m_Color, pCommand->m_pIndicesOffset, pCommand->m_IndexDrawNum, pCommand->m_DrawNum, pCommand->m_Offset, pCommand->m_Dir); } void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) @@ -2017,7 +2020,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(pCommand->m_IndicesDrawNum == 0) { @@ -2037,17 +2040,16 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer UseProgram(pProgram); SetState(pCommand->m_State, pProgram, true); - pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float*)&pCommand->m_Color); + pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float *)&pCommand->m_Color); } else { CCommandProcessorFragment_OpenGL::SetState(pCommand->m_State, true); } - bool IsTextured = BufferContainer.m_ContainerInfo.m_Attributes.size() == 2; - SBufferObject& BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; + SBufferObject &BufferObject = m_BufferObjectIndices[(size_t)BufferContainer.m_ContainerInfo.m_Attributes[0].m_VertBufferBindingIndex]; if(m_HasShaders) glBindBuffer(GL_ARRAY_BUFFER, BufferObject.m_BufferObjectID); @@ -2080,9 +2082,9 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer else { glVertexPointer(2, GL_FLOAT, sizeof(m_aStreamVertices[0]), m_aStreamVertices); - glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); + glColorPointer(4, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2))); if(IsTextured) - glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t*)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); + glTexCoordPointer(3, GL_FLOAT, sizeof(m_aStreamVertices[0]), (uint8_t *)m_aStreamVertices + (ptrdiff_t)(sizeof(vec2) + sizeof(vec4))); size_t VertexCount = 0; for(int i = 0; i < pCommand->m_IndicesDrawNum; ++i) @@ -2095,13 +2097,13 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer for(size_t n = 0; n < RealDrawCount; ++n) { ptrdiff_t VertOffset = (ptrdiff_t)(CurBufferOffset + (n * SingleVertSize)); - vec2* pPos = (vec2*)((uint8_t*)BufferObject.m_pData + VertOffset); - GL_SVertexTex3D& Vertex = m_aStreamVertices[VertexCount++]; + vec2 *pPos = (vec2 *)((uint8_t *)BufferObject.m_pData + VertOffset); + GL_SVertexTex3D &Vertex = m_aStreamVertices[VertexCount++]; mem_copy(&Vertex.m_Pos, pPos, sizeof(vec2)); mem_copy(&Vertex.m_Color, &pCommand->m_Color, sizeof(vec4)); if(IsTextured) { - vec3* pTex = (vec3*)((uint8_t*)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); + vec3 *pTex = (vec3 *)((uint8_t *)BufferObject.m_pData + VertOffset + (ptrdiff_t)sizeof(vec2)); mem_copy(&Vertex.m_Tex, pTex, sizeof(vec3)); } @@ -2109,7 +2111,7 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer { glDrawArrays(GL_QUADS, 0, VertexCount); VertexCount = 0; - } + } } } if(VertexCount > 0) @@ -2137,15 +2139,19 @@ void CCommandProcessorFragment_OpenGL2::Cmd_RenderTileLayer(const CCommandBuffer // ------------ CCommandProcessorFragment_OpenGL3_3 int CCommandProcessorFragment_OpenGL3_3::TexFormatToNewOpenGLFormat(int TexFormat) { - if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB; - if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_RED; - if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) + return GL_RGB; + if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) + return GL_RED; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) + return GL_RGBA; return GL_RGBA; } void CCommandProcessorFragment_OpenGL3_3::UseProgram(CGLSLTWProgram *pProgram) { - if(m_LastProgramID != pProgram->GetProgramID()) { + if(m_LastProgramID != pProgram->GetProgramID()) + { pProgram->UseProgram(); m_LastProgramID = pProgram->GetProgramID(); } @@ -2190,7 +2196,8 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Init(const SCommand_Init *pCommand CGLSLCompiler ShaderCompiler(g_Config.m_GfxOpenGLMajor, g_Config.m_GfxOpenGLMinor, g_Config.m_GfxOpenGLPatch); GLint CapVal; - glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &CapVal);; + glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &CapVal); + ; m_MaxQuadsAtOnce = minimum(((CapVal - 20) / (3 * 4)), m_MaxQuadsPossible); { @@ -2456,7 +2463,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Init(const SCommand_Init *pCommand m_pSpriteProgram->m_LocVertciesColor = m_pSpriteProgram->GetUniformLoc("VerticesColor"); m_pSpriteProgram->SetUniform(m_pSpriteProgram->m_LocRotation, 0); - float Center[2] = { 0.f, 0.f }; + float Center[2] = {0.f, 0.f}; m_pSpriteProgram->SetUniformVec2(m_pSpriteProgram->m_LocCenter, 1, Center); } { @@ -2479,7 +2486,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Init(const SCommand_Init *pCommand m_pSpriteProgramMultiple->m_LocCenter = m_pSpriteProgramMultiple->GetUniformLoc("Center"); m_pSpriteProgramMultiple->m_LocVertciesColor = m_pSpriteProgramMultiple->GetUniformLoc("VerticesColor"); - float Center[2] = { 0.f, 0.f }; + float Center[2] = {0.f, 0.f}; m_pSpriteProgramMultiple->SetUniformVec2(m_pSpriteProgramMultiple->m_LocCenter, 1, Center); } @@ -2501,8 +2508,8 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Init(const SCommand_Init *pCommand glEnableVertexAttribArray(2); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(CCommandBuffer::SVertex), 0); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(CCommandBuffer::SVertex), (void*)(sizeof(float) * 2)); - glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(CCommandBuffer::SVertex), (void*)(sizeof(float) * 4)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(CCommandBuffer::SVertex), (void *)(sizeof(float) * 2)); + glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(CCommandBuffer::SVertex), (void *)(sizeof(float) * 4)); if(m_UsePreinitializedVertexBuffer) glBufferData(GL_ARRAY_BUFFER, sizeof(CCommandBuffer::SVertex) * CCommandBuffer::MAX_VERTICES, NULL, GL_STREAM_DRAW); @@ -2539,21 +2546,21 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Init(const SCommand_Init *pCommand glGenBuffers(1, &m_QuadDrawIndexBufferID); glBindBuffer(GL_COPY_WRITE_BUFFER, m_QuadDrawIndexBufferID); - unsigned int Indices[CCommandBuffer::MAX_VERTICES/4 * 6]; + unsigned int Indices[CCommandBuffer::MAX_VERTICES / 4 * 6]; int Primq = 0; - for(int i = 0; i < CCommandBuffer::MAX_VERTICES/4 * 6; i+=6) + for(int i = 0; i < CCommandBuffer::MAX_VERTICES / 4 * 6; i += 6) { Indices[i] = Primq; - Indices[i+1] = Primq + 1; - Indices[i+2] = Primq + 2; - Indices[i+3] = Primq; - Indices[i+4] = Primq + 2; - Indices[i+5] = Primq + 3; - Primq+=4; + Indices[i + 1] = Primq + 1; + Indices[i + 2] = Primq + 2; + Indices[i + 3] = Primq; + Indices[i + 4] = Primq + 2; + Indices[i + 5] = Primq + 3; + Primq += 4; } - glBufferData(GL_COPY_WRITE_BUFFER, sizeof(unsigned int) * CCommandBuffer::MAX_VERTICES/4 * 6, Indices, GL_STATIC_DRAW); + glBufferData(GL_COPY_WRITE_BUFFER, sizeof(unsigned int) * CCommandBuffer::MAX_VERTICES / 4 * 6, Indices, GL_STATIC_DRAW); - m_CurrentIndicesInBuffer = CCommandBuffer::MAX_VERTICES/4 * 6; + m_CurrentIndicesInBuffer = CCommandBuffer::MAX_VERTICES / 4 * 6; mem_zero(m_aTextures, sizeof(m_aTextures)); @@ -2631,7 +2638,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Update(const CCommandBuffe glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); - void* pTexData = pCommand->m_pData; + void *pTexData = pCommand->m_pData; int Width = pCommand->m_Width; int Height = pCommand->m_Height; int X = pCommand->m_X; @@ -2687,20 +2694,19 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe { do { - Width>>=1; - Height>>=1; + Width >>= 1; + Height >>= 1; ++RescaleCount; - } - while(Width > m_MaxTexSize || Height > m_MaxTexSize); + } while(Width > m_MaxTexSize || Height > m_MaxTexSize); void *pTmpData = Resize(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast(pCommand->m_pData)); free(pTexData); pTexData = pTmpData; } - else if(pCommand->m_Format != CCommandBuffer::TEXFORMAT_ALPHA && (Width > 16 && Height > 16 && (pCommand->m_Flags&CCommandBuffer::TEXFLAG_QUALITY) == 0)) + else if(pCommand->m_Format != CCommandBuffer::TEXFORMAT_ALPHA && (Width > 16 && Height > 16 && (pCommand->m_Flags & CCommandBuffer::TEXFLAG_QUALITY) == 0)) { - Width>>=1; - Height>>=1; + Width >>= 1; + Height >>= 1; ++RescaleCount; void *pTmpData = Resize(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast(pCommand->m_pData)); @@ -2715,15 +2721,15 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe int Oglformat = TexFormatToNewOpenGLFormat(pCommand->m_Format); int StoreOglformat = TexFormatToNewOpenGLFormat(pCommand->m_StoreFormat); - if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_COMPRESSED) + if(pCommand->m_Flags & CCommandBuffer::TEXFLAG_COMPRESSED) { switch(StoreOglformat) { - case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB; break; - // COMPRESSED_ALPHA is deprecated, so use different single channel format. - case GL_RED: StoreOglformat = GL_COMPRESSED_RED; break; - case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA; break; - default: StoreOglformat = GL_COMPRESSED_RGBA; + case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB; break; + // COMPRESSED_ALPHA is deprecated, so use different single channel format. + case GL_RED: StoreOglformat = GL_COMPRESSED_RED; break; + case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA; break; + default: StoreOglformat = GL_COMPRESSED_RGBA; } } int Slot = 0; @@ -2735,7 +2741,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe glActiveTexture(GL_TEXTURE0 + Slot); } - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); @@ -2752,9 +2758,9 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe StoreOglformat = GL_R8; } - if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS) + if(pCommand->m_Flags & CCommandBuffer::TEXFLAG_NOMIPMAPS) { - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -2765,7 +2771,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe } else { - if((pCommand->m_Flags&CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) + if((pCommand->m_Flags & CCommandBuffer::TEXFLAG_NO_2D_TEXTURE) == 0) { glSamplerParameteri(m_aTextures[pCommand->m_Slot].m_Sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glSamplerParameteri(m_aTextures[pCommand->m_Slot].m_Sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); @@ -2779,7 +2785,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe glGenerateMipmap(GL_TEXTURE_2D); } - if((pCommand->m_Flags&(CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE | CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER)) != 0) + if((pCommand->m_Flags & (CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE | CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER)) != 0) { glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex2DArray); glBindTexture(GL_TEXTURE_2D_ARRAY, m_aTextures[pCommand->m_Slot].m_Tex2DArray); @@ -2794,12 +2800,12 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe int ImageColorChannels = TexFormatToImageColorChannelCount(pCommand->m_Format); - uint8_t* p3DImageData = NULL; + uint8_t *p3DImageData = NULL; - bool IsSingleLayer = (pCommand->m_Flags& CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0; + bool IsSingleLayer = (pCommand->m_Flags & CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0; if(!IsSingleLayer) - p3DImageData = (uint8_t*)malloc(ImageColorChannels * Width * Height); + p3DImageData = (uint8_t *)malloc(ImageColorChannels * Width * Height); int Image3DWidth, Image3DHeight; int ConvertWidth = Width; @@ -2812,7 +2818,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe dbg_msg("gfx", "3D/2D array texture was resized"); int NewWidth = maximum(HighestBit(ConvertWidth), 16); int NewHeight = maximum(HighestBit(ConvertHeight), 16); - uint8_t* pNewTexData = (uint8_t*)Resize(ConvertWidth, ConvertHeight, NewWidth, NewHeight, pCommand->m_Format, (const uint8_t*)pTexData); + uint8_t *pNewTexData = (uint8_t *)Resize(ConvertWidth, ConvertHeight, NewWidth, NewHeight, pCommand->m_Format, (const uint8_t *)pTexData); ConvertWidth = NewWidth; ConvertHeight = NewHeight; @@ -2841,7 +2847,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe glTexParameteriv(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } } - + if(!IsSingleLayer) free(p3DImageData); } @@ -2851,12 +2857,12 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Texture_Create(const CCommandBuffe m_aTextures[pCommand->m_Slot].m_LastWrapMode = CCommandBuffer::WRAP_REPEAT; // calculate memory usage - m_aTextures[pCommand->m_Slot].m_MemSize = Width*Height*pCommand->m_PixelSize; + m_aTextures[pCommand->m_Slot].m_MemSize = Width * Height * pCommand->m_PixelSize; while(Width > 2 && Height > 2) { - Width>>=1; - Height>>=1; - m_aTextures[pCommand->m_Slot].m_MemSize += Width*Height*pCommand->m_PixelSize; + Width >>= 1; + Height >>= 1; + m_aTextures[pCommand->m_Slot].m_MemSize += Width * Height * pCommand->m_PixelSize; } m_pTextureMemoryUsage->store(m_pTextureMemoryUsage->load(std::memory_order_relaxed) + m_aTextures[pCommand->m_Slot].m_MemSize, std::memory_order_relaxed); @@ -2876,7 +2882,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Clear(const CCommandBuffer::SComma void CCommandProcessorFragment_OpenGL3_3::UploadStreamBufferData(unsigned int PrimitiveType, const void *pVertices, size_t VertSize, unsigned int PrimitiveCount, bool AsTex3D) { int Count = 0; - switch (PrimitiveType) + switch(PrimitiveType) { case CCommandBuffer::PRIMTYPE_LINES: Count = PrimitiveCount * 2; @@ -2919,7 +2925,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Render(const CCommandBuffer::SComm { // We don't support GL_QUADS due to core profile case CCommandBuffer::PRIMTYPE_LINES: - glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2); + glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount * 2); break; case CCommandBuffer::PRIMTYPE_QUADS: if(m_LastIndexBufferBound[m_LastStreamBuffer] != m_QuadDrawIndexBufferID) @@ -2927,7 +2933,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Render(const CCommandBuffer::SComm glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_QuadDrawIndexBufferID); m_LastIndexBufferBound[m_LastStreamBuffer] = m_QuadDrawIndexBufferID; } - glDrawElements(GL_TRIANGLES, pCommand->m_PrimCount*6, GL_UNSIGNED_INT, 0); + glDrawElements(GL_TRIANGLES, pCommand->m_PrimCount * 6, GL_UNSIGNED_INT, 0); break; default: dbg_msg("render", "unknown primtype %d\n", pCommand->m_Cmd); @@ -2966,29 +2972,29 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderTex3D(const CCommandBuffer:: void CCommandProcessorFragment_OpenGL3_3::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand) { // fetch image data - GLint aViewport[4] = {0,0,0,0}; + GLint aViewport[4] = {0, 0, 0, 0}; glGetIntegerv(GL_VIEWPORT, aViewport); int w = aViewport[2]; int h = aViewport[3]; // we allocate one more row to use when we are flipping the texture - unsigned char *pPixelData = (unsigned char *)malloc(w*(h+1)*3); - unsigned char *pTempRow = pPixelData+w*h*3; + unsigned char *pPixelData = (unsigned char *)malloc(w * (h + 1) * 3); + unsigned char *pTempRow = pPixelData + w * h * 3; // fetch the pixels GLint Alignment; glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment); glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); + glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); glPixelStorei(GL_PACK_ALIGNMENT, Alignment); // flip the pixel because opengl works from bottom left corner - for(int y = 0; y < h/2; y++) + for(int y = 0; y < h / 2; y++) { - mem_copy(pTempRow, pPixelData+y*w*3, w*3); - mem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3); - mem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3); + mem_copy(pTempRow, pPixelData + y * w * 3, w * 3); + mem_copy(pPixelData + y * w * 3, pPixelData + (h - y - 1) * w * 3, w * 3); + mem_copy(pPixelData + (h - y - 1) * w * 3, pTempRow, w * 3); } // fill in the information @@ -3000,7 +3006,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_Screenshot(const CCommandBuffer::S void CCommandProcessorFragment_OpenGL3_3::DestroyBufferContainer(int Index, bool DeleteBOs) { - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID != 0) glDeleteVertexArrays(1, &BufferContainer.m_VertArrayID); @@ -3015,7 +3021,8 @@ void CCommandProcessorFragment_OpenGL3_3::DestroyBufferContainer(int Index, bool for(size_t j = 0; j < BufferContainer.m_ContainerInfo.m_Attributes.size(); ++j) { // set all equal ids to zero to not double delete - if(VertBufferID == BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex) { + if(VertBufferID == BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex) + { BufferContainer.m_ContainerInfo.m_Attributes[j].m_VertBufferBindingIndex = -1; } } @@ -3031,19 +3038,20 @@ void CCommandProcessorFragment_OpenGL3_3::DestroyBufferContainer(int Index, bool void CCommandProcessorFragment_OpenGL3_3::AppendIndices(unsigned int NewIndicesCount) { - if(NewIndicesCount <= m_CurrentIndicesInBuffer) return; + if(NewIndicesCount <= m_CurrentIndicesInBuffer) + return; unsigned int AddCount = NewIndicesCount - m_CurrentIndicesInBuffer; unsigned int *Indices = new unsigned int[AddCount]; - int Primq = (m_CurrentIndicesInBuffer/6) * 4; - for(unsigned int i = 0; i < AddCount; i+=6) + int Primq = (m_CurrentIndicesInBuffer / 6) * 4; + for(unsigned int i = 0; i < AddCount; i += 6) { Indices[i] = Primq; - Indices[i+1] = Primq + 1; - Indices[i+2] = Primq + 2; - Indices[i+3] = Primq; - Indices[i+4] = Primq + 2; - Indices[i+5] = Primq + 3; - Primq+=4; + Indices[i + 1] = Primq + 1; + Indices[i + 2] = Primq + 2; + Indices[i + 3] = Primq; + Indices[i + 4] = Primq + 2; + Indices[i + 5] = Primq + 3; + Primq += 4; } glBindBuffer(GL_COPY_READ_BUFFER, m_QuadDrawIndexBufferID); @@ -3139,7 +3147,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_CreateBufferContainer(const CComma } } - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; glGenVertexArrays(1, &BufferContainer.m_VertArrayID); glBindVertexArray(BufferContainer.m_VertArrayID); @@ -3151,7 +3159,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_CreateBufferContainer(const CComma glBindBuffer(GL_ARRAY_BUFFER, m_BufferObjectIndices[pCommand->m_Attributes[i].m_VertBufferBindingIndex]); - SBufferContainerInfo::SAttribute& Attr = pCommand->m_Attributes[i]; + SBufferContainerInfo::SAttribute &Attr = pCommand->m_Attributes[i]; if(Attr.m_FuncType == 0) glVertexAttribPointer((GLuint)i, Attr.m_DataTypeCount, Attr.m_Type, (GLboolean)Attr.m_Normalized, pCommand->m_Stride, Attr.m_pOffset); @@ -3166,21 +3174,23 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_CreateBufferContainer(const CComma void CCommandProcessorFragment_OpenGL3_3::Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) { - SBufferContainer& BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; + SBufferContainer &BufferContainer = m_BufferContainers[pCommand->m_BufferContainerIndex]; glBindVertexArray(BufferContainer.m_VertArrayID); //disable all old attributes - for(size_t i = 0; i < BufferContainer.m_ContainerInfo.m_Attributes.size(); ++i) { + for(size_t i = 0; i < BufferContainer.m_ContainerInfo.m_Attributes.size(); ++i) + { glDisableVertexAttribArray((GLuint)i); } BufferContainer.m_ContainerInfo.m_Attributes.clear(); - for(int i = 0; i < pCommand->m_AttrCount; ++i) { + for(int i = 0; i < pCommand->m_AttrCount; ++i) + { glEnableVertexAttribArray((GLuint)i); glBindBuffer(GL_ARRAY_BUFFER, m_BufferObjectIndices[pCommand->m_Attributes[i].m_VertBufferBindingIndex]); - SBufferContainerInfo::SAttribute& Attr = pCommand->m_Attributes[i]; + SBufferContainerInfo::SAttribute &Attr = pCommand->m_Attributes[i]; if(Attr.m_FuncType == 0) glVertexAttribPointer((GLuint)i, Attr.m_DataTypeCount, Attr.m_Type, Attr.m_Normalized, pCommand->m_Stride, Attr.m_pOffset); else if(Attr.m_FuncType == 1) @@ -3210,22 +3220,24 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderBorderTile(const CCommandBuf if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; - if(BufferContainer.m_VertArrayID == 0) return; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; + if(BufferContainer.m_VertArrayID == 0) + return; CGLSLTileProgram *pProgram = NULL; if(pCommand->m_State.m_Texture >= 0 && pCommand->m_State.m_Texture < CCommandBuffer::MAX_TEXTURES) { pProgram = m_pBorderTileProgramTextured; } - else pProgram = m_pBorderTileProgram; + else + pProgram = m_pBorderTileProgram; UseProgram(pProgram); SetState(pCommand->m_State, pProgram, true); - pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float*)&pCommand->m_Color); + pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float *)&pCommand->m_Color); - pProgram->SetUniformVec2(pProgram->m_LocOffset, 1, (float*)&pCommand->m_Offset); - pProgram->SetUniformVec2(pProgram->m_LocDir, 1, (float*)&pCommand->m_Dir); + pProgram->SetUniformVec2(pProgram->m_LocOffset, 1, (float *)&pCommand->m_Offset); + pProgram->SetUniformVec2(pProgram->m_LocDir, 1, (float *)&pCommand->m_Dir); pProgram->SetUniform(pProgram->m_LocJumpIndex, (int)pCommand->m_JumpIndex); glBindVertexArray(BufferContainer.m_VertArrayID); @@ -3244,7 +3256,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderBorderTileLine(const CComman if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3253,13 +3265,14 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderBorderTileLine(const CComman { pProgram = m_pBorderTileLineProgramTextured; } - else pProgram = m_pBorderTileLineProgram; + else + pProgram = m_pBorderTileLineProgram; UseProgram(pProgram); SetState(pCommand->m_State, pProgram, true); - pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float*)&pCommand->m_Color); - pProgram->SetUniformVec2(pProgram->m_LocOffset, 1, (float*)&pCommand->m_Offset); - pProgram->SetUniformVec2(pProgram->m_LocDir, 1, (float*)&pCommand->m_Dir); + pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float *)&pCommand->m_Color); + pProgram->SetUniformVec2(pProgram->m_LocOffset, 1, (float *)&pCommand->m_Offset); + pProgram->SetUniformVec2(pProgram->m_LocDir, 1, (float *)&pCommand->m_Dir); glBindVertexArray(BufferContainer.m_VertArrayID); if(BufferContainer.m_LastIndexBufferBound != m_QuadDrawIndexBufferID) @@ -3277,7 +3290,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderTileLayer(const CCommandBuff if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3297,7 +3310,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderTileLayer(const CCommandBuff UseProgram(pProgram); SetState(pCommand->m_State, pProgram, true); - pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float*)&pCommand->m_Color); + pProgram->SetUniformVec4(pProgram->m_LocColor, 1, (float *)&pCommand->m_Color); glBindVertexArray(BufferContainer.m_VertArrayID); if(BufferContainer.m_LastIndexBufferBound != m_QuadDrawIndexBufferID) @@ -3318,7 +3331,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadLayer(const CCommandBuff if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3356,23 +3369,24 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadLayer(const CCommandBuff { int ActualQuadCount = minimum(QuadsLeft, m_MaxQuadsAtOnce); - for(size_t i = 0; i < (size_t)ActualQuadCount; ++i) { + for(size_t i = 0; i < (size_t)ActualQuadCount; ++i) + { mem_copy(&aColors[i], pCommand->m_pQuadInfo[i + QuadOffset].m_aColor, sizeof(vec4)); mem_copy(&aOffsets[i], pCommand->m_pQuadInfo[i + QuadOffset].m_aOffsets, sizeof(vec2)); mem_copy(&aRotations[i], &pCommand->m_pQuadInfo[i + QuadOffset].m_Rotation, sizeof(float)); } - pProgram->SetUniformVec4(pProgram->m_LocColors, ActualQuadCount, (float*)aColors); - pProgram->SetUniformVec2(pProgram->m_LocOffsets, ActualQuadCount, (float*)aOffsets); - pProgram->SetUniform(pProgram->m_LocRotations, ActualQuadCount, (float*)aRotations); - glDrawElements(GL_TRIANGLES, ActualQuadCount * 6, GL_UNSIGNED_INT, (void*)(QuadOffset * 6 * sizeof(unsigned int))); + pProgram->SetUniformVec4(pProgram->m_LocColors, ActualQuadCount, (float *)aColors); + pProgram->SetUniformVec2(pProgram->m_LocOffsets, ActualQuadCount, (float *)aOffsets); + pProgram->SetUniform(pProgram->m_LocRotations, ActualQuadCount, (float *)aRotations); + glDrawElements(GL_TRIANGLES, ActualQuadCount * 6, GL_UNSIGNED_INT, (void *)(QuadOffset * 6 * sizeof(unsigned int))); QuadsLeft -= ActualQuadCount; QuadOffset += (size_t)ActualQuadCount; } } -void CCommandProcessorFragment_OpenGL3_3::RenderText(const CCommandBuffer::SState& State, int DrawNum, int TextTextureIndex, int TextOutlineTextureIndex, int TextureSize, const float* pTextColor, const float* pTextOutlineColor) +void CCommandProcessorFragment_OpenGL3_3::RenderText(const CCommandBuffer::SState &State, int DrawNum, int TextTextureIndex, int TextOutlineTextureIndex, int TextureSize, const float *pTextColor, const float *pTextOutlineColor) { if(DrawNum == 0) { @@ -3438,7 +3452,7 @@ void CCommandProcessorFragment_OpenGL3_3::RenderText(const CCommandBuffer::SStat if(m_pTextProgram->m_LastOutlineColor[0] != pTextOutlineColor[0] || m_pTextProgram->m_LastOutlineColor[1] != pTextOutlineColor[1] || m_pTextProgram->m_LastOutlineColor[2] != pTextOutlineColor[2] || m_pTextProgram->m_LastOutlineColor[3] != pTextOutlineColor[3]) { - m_pTextProgram->SetUniformVec4(m_pTextProgram->m_LocOutlineColor, 1, (float*)pTextOutlineColor); + m_pTextProgram->SetUniformVec4(m_pTextProgram->m_LocOutlineColor, 1, (float *)pTextOutlineColor); m_pTextProgram->m_LastOutlineColor[0] = pTextOutlineColor[0]; m_pTextProgram->m_LastOutlineColor[1] = pTextOutlineColor[1]; m_pTextProgram->m_LastOutlineColor[2] = pTextOutlineColor[2]; @@ -3447,14 +3461,14 @@ void CCommandProcessorFragment_OpenGL3_3::RenderText(const CCommandBuffer::SStat if(m_pTextProgram->m_LastColor[0] != pTextColor[0] || m_pTextProgram->m_LastColor[1] != pTextColor[1] || m_pTextProgram->m_LastColor[2] != pTextColor[2] || m_pTextProgram->m_LastColor[3] != pTextColor[3]) { - m_pTextProgram->SetUniformVec4(m_pTextProgram->m_LocColor, 1, (float*)pTextColor); + m_pTextProgram->SetUniformVec4(m_pTextProgram->m_LocColor, 1, (float *)pTextColor); m_pTextProgram->m_LastColor[0] = pTextColor[0]; m_pTextProgram->m_LastColor[1] = pTextColor[1]; m_pTextProgram->m_LastColor[2] = pTextColor[2]; m_pTextProgram->m_LastColor[3] = pTextColor[3]; } - glDrawElements(GL_TRIANGLES, DrawNum, GL_UNSIGNED_INT, (void*)(0)); + glDrawElements(GL_TRIANGLES, DrawNum, GL_UNSIGNED_INT, (void *)(0)); } void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderText(const CCommandBuffer::SCommand_RenderText *pCommand) @@ -3464,7 +3478,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderText(const CCommandBuffer::S if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3494,7 +3508,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderTextStream(const CCommandBuf m_LastIndexBufferBound[m_LastStreamBuffer] = m_QuadDrawIndexBufferID; } - float aTextColor[4] = { 1.f, 1.f, 1.f, 1.f }; + float aTextColor[4] = {1.f, 1.f, 1.f, 1.f}; RenderText(pCommand->m_State, pCommand->m_PrimCount * 6, pCommand->m_TextTextureIndex, pCommand->m_TextOutlineTextureIndex, pCommand->m_TextureSize, aTextColor, pCommand->m_aTextOutlineColor); @@ -3513,7 +3527,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainer(const CCommand if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3542,7 +3556,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSprite(const if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3558,7 +3572,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSprite(const if(pCommand->m_Rotation != 0.0f && (m_pSpriteProgram->m_LastCenter[0] != pCommand->m_Center.x || m_pSpriteProgram->m_LastCenter[1] != pCommand->m_Center.y)) { - m_pSpriteProgram->SetUniformVec2(m_pSpriteProgram->m_LocCenter, 1, (float*)&pCommand->m_Center); + m_pSpriteProgram->SetUniformVec2(m_pSpriteProgram->m_LocCenter, 1, (float *)&pCommand->m_Center); m_pSpriteProgram->m_LastCenter[0] = pCommand->m_Center.x; m_pSpriteProgram->m_LastCenter[1] = pCommand->m_Center.y; } @@ -3571,7 +3585,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSprite(const if(m_pSpriteProgram->m_LastVertciesColor[0] != pCommand->m_VertexColor.r || m_pSpriteProgram->m_LastVertciesColor[1] != pCommand->m_VertexColor.g || m_pSpriteProgram->m_LastVertciesColor[2] != pCommand->m_VertexColor.b || m_pSpriteProgram->m_LastVertciesColor[3] != pCommand->m_VertexColor.a) { - m_pSpriteProgram->SetUniformVec4(m_pSpriteProgram->m_LocVertciesColor, 1, (float*)&pCommand->m_VertexColor); + m_pSpriteProgram->SetUniformVec4(m_pSpriteProgram->m_LocVertciesColor, 1, (float *)&pCommand->m_VertexColor); m_pSpriteProgram->m_LastVertciesColor[0] = pCommand->m_VertexColor.r; m_pSpriteProgram->m_LastVertciesColor[1] = pCommand->m_VertexColor.g; m_pSpriteProgram->m_LastVertciesColor[2] = pCommand->m_VertexColor.b; @@ -3593,7 +3607,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSpriteMultipl if((size_t)Index >= m_BufferContainers.size()) return; - SBufferContainer& BufferContainer = m_BufferContainers[Index]; + SBufferContainer &BufferContainer = m_BufferContainers[Index]; if(BufferContainer.m_VertArrayID == 0) return; @@ -3609,14 +3623,14 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSpriteMultipl if((m_pSpriteProgramMultiple->m_LastCenter[0] != pCommand->m_Center.x || m_pSpriteProgramMultiple->m_LastCenter[1] != pCommand->m_Center.y)) { - m_pSpriteProgramMultiple->SetUniformVec2(m_pSpriteProgramMultiple->m_LocCenter, 1, (float*)&pCommand->m_Center); + m_pSpriteProgramMultiple->SetUniformVec2(m_pSpriteProgramMultiple->m_LocCenter, 1, (float *)&pCommand->m_Center); m_pSpriteProgramMultiple->m_LastCenter[0] = pCommand->m_Center.x; m_pSpriteProgramMultiple->m_LastCenter[1] = pCommand->m_Center.y; } if(m_pSpriteProgramMultiple->m_LastVertciesColor[0] != pCommand->m_VertexColor.r || m_pSpriteProgramMultiple->m_LastVertciesColor[1] != pCommand->m_VertexColor.g || m_pSpriteProgramMultiple->m_LastVertciesColor[2] != pCommand->m_VertexColor.b || m_pSpriteProgramMultiple->m_LastVertciesColor[3] != pCommand->m_VertexColor.a) { - m_pSpriteProgramMultiple->SetUniformVec4(m_pSpriteProgramMultiple->m_LocVertciesColor, 1, (float*)&pCommand->m_VertexColor); + m_pSpriteProgramMultiple->SetUniformVec4(m_pSpriteProgramMultiple->m_LocVertciesColor, 1, (float *)&pCommand->m_VertexColor); m_pSpriteProgramMultiple->m_LastVertciesColor[0] = pCommand->m_VertexColor.r; m_pSpriteProgramMultiple->m_LastVertciesColor[1] = pCommand->m_VertexColor.g; m_pSpriteProgramMultiple->m_LastVertciesColor[2] = pCommand->m_VertexColor.b; @@ -3633,7 +3647,7 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSpriteMultipl { int UniformCount = (DrawCount > RSPCount ? RSPCount : DrawCount); - m_pSpriteProgramMultiple->SetUniformVec4(m_pSpriteProgramMultiple->m_LocRSP, UniformCount, (float*)(pCommand->m_pRenderInfo + RenderOffset)); + m_pSpriteProgramMultiple->SetUniformVec4(m_pSpriteProgramMultiple->m_LocRSP, UniformCount, (float *)(pCommand->m_pRenderInfo + RenderOffset)); glDrawElementsInstanced(GL_TRIANGLES, pCommand->m_DrawNum, GL_UNSIGNED_INT, pCommand->m_pOffset, UniformCount); @@ -3644,14 +3658,14 @@ void CCommandProcessorFragment_OpenGL3_3::Cmd_RenderQuadContainerAsSpriteMultipl // ------------ CCommandProcessorFragment_SDL -static void ParseVersionString(const GLubyte* pStr, int& VersionMajor, int& VersionMinor, int& VersionPatch) +static void ParseVersionString(const GLubyte *pStr, int &VersionMajor, int &VersionMinor, int &VersionPatch) { if(pStr) { char aCurNumberStr[32]; size_t CurNumberStrLen = 0; size_t TotalNumbersPassed = 0; - int aNumbers[3] = { 0 }; + int aNumbers[3] = {0}; bool LastWasNumber = false; while(*pStr && TotalNumbersPassed < 3) { @@ -3707,8 +3721,8 @@ void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand) glDepthMask(0); // check what this context can do - const GLubyte* pVersionString = glGetString(GL_VERSION); - dbg_msg("OpenGL", "Version string: %s", (const char*)pVersionString); + const GLubyte *pVersionString = glGetString(GL_VERSION); + dbg_msg("OpenGL", "Version string: %s", (const char *)pVersionString); // parse version string ParseVersionString(pVersionString, pCommand->m_pCapabilities->m_ContextMajor, pCommand->m_pCapabilities->m_ContextMinor, pCommand->m_pCapabilities->m_ContextPatch); @@ -3819,7 +3833,7 @@ void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand) if(TextureLayers >= 256) { pCommand->m_pCapabilities->m_2DArrayTextures = true; - pCommand->m_pCapabilities->m_2DArrayTexturesAsExtension = true; + pCommand->m_pCapabilities->m_2DArrayTexturesAsExtension = true; } } @@ -3892,7 +3906,7 @@ void CCommandProcessorFragment_SDL::Cmd_VideoModes(const CCommandBuffer::SComman { SDL_DisplayMode mode; int maxModes = SDL_GetNumDisplayModes(pCommand->m_Screen), - numModes = 0; + numModes = 0; for(int i = 0; i < maxModes; i++) { @@ -3957,7 +3971,7 @@ void CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer) break; if(m_pOpenGL->RunCommand(pBaseCommand)) - continue; + continue; if(m_SDL.RunCommand(pBaseCommand)) continue; @@ -3971,23 +3985,27 @@ void CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer) CCommandProcessor_SDL_OpenGL::CCommandProcessor_SDL_OpenGL(int OpenGLMajor, int OpenGLMinor, int OpenGLPatch) { - if(OpenGLMajor < 2) { + if(OpenGLMajor < 2) + { m_pOpenGL = new CCommandProcessorFragment_OpenGL(); } - if(OpenGLMajor == 2) { + if(OpenGLMajor == 2) + { m_pOpenGL = new CCommandProcessorFragment_OpenGL2(); } - if(OpenGLMajor == 3 && OpenGLMinor == 0) { + if(OpenGLMajor == 3 && OpenGLMinor == 0) + { m_pOpenGL = new CCommandProcessorFragment_OpenGL3(); } - else if((OpenGLMajor == 3 && OpenGLMinor == 3) || OpenGLMajor >= 4) { + else if((OpenGLMajor == 3 && OpenGLMinor == 3) || OpenGLMajor >= 4) + { m_pOpenGL = new CCommandProcessorFragment_OpenGL3_3(); } } // ------------ CGraphicsBackend_SDL_OpenGL -static void GetGlewVersion(int& GlewMajor, int& GlewMinor, int& GlewPatch) +static void GetGlewVersion(int &GlewMajor, int &GlewMinor, int &GlewPatch) { #ifdef GLEW_VERSION_4_6 if(GLEW_VERSION_4_6) @@ -4224,10 +4242,10 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_INIT_FAILED; } - #ifdef CONF_FAMILY_WINDOWS - if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention - putenv("SDL_VIDEO_WINDOW_POS=center"); // ignore_convention - #endif +#ifdef CONF_FAMILY_WINDOWS + if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention + putenv("SDL_VIDEO_WINDOW_POS=center"); // ignore_convention +#endif } SDL_ClearError(); @@ -4353,7 +4371,6 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt dbg_msg("gfx", "unable to retrieve screen information: %s", SDL_GetError()); return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_SCREEN_INFO_REQUEST_FAILED; } - } else { @@ -4380,17 +4397,17 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt // set flags int SdlFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS; - if(Flags&IGraphicsBackend::INITFLAG_HIGHDPI) + if(Flags & IGraphicsBackend::INITFLAG_HIGHDPI) SdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI; #if defined(SDL_VIDEO_DRIVER_X11) - if(Flags&IGraphicsBackend::INITFLAG_RESIZABLE) + if(Flags & IGraphicsBackend::INITFLAG_RESIZABLE) SdlFlags |= SDL_WINDOW_RESIZABLE; #endif #if defined(CONF_PLATFORM_MACOSX) // TODO: remove this when fixed in SDL - if(Flags&IGraphicsBackend::INITFLAG_BORDERLESS) + if(Flags & IGraphicsBackend::INITFLAG_BORDERLESS) SdlFlags |= SDL_WINDOW_BORDERLESS; #endif - if(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN) + if(Flags & IGraphicsBackend::INITFLAG_FULLSCREEN) { // when we are at fullscreen, we really shouldn't allow window sizes, that aren't supported by the driver bool SupportedResolution = false; @@ -4472,7 +4489,7 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt InitError = IsVersionSupportedGlew(g_Config.m_GfxOpenGLMajor, g_Config.m_GfxOpenGLMinor, g_Config.m_GfxOpenGLPatch, GlewMajor, GlewMinor, GlewPatch); SDL_GL_GetDrawableSize(m_pWindow, pCurrentWidth, pCurrentHeight); - SDL_GL_SetSwapInterval(Flags&IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0); + SDL_GL_SetSwapInterval(Flags & IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0); SDL_GL_MakeCurrent(NULL, NULL); if(InitError != 0) @@ -4484,14 +4501,14 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt g_Config.m_GfxOpenGLMajor = GlewMajor; g_Config.m_GfxOpenGLMinor = GlewMinor; g_Config.m_GfxOpenGLPatch = GlewPatch; - + return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_OPENGL_VERSION_FAILED; } // start the command processor m_pProcessor = new CCommandProcessor_SDL_OpenGL(g_Config.m_GfxOpenGLMajor, g_Config.m_GfxOpenGLMinor, g_Config.m_GfxOpenGLPatch); StartProcessor(m_pProcessor); - + // issue init commands for OpenGL and SDL CCommandBuffer CmdBuffer(1024, 512); //run sdl first to have the context in the thread @@ -4568,7 +4585,7 @@ int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Screen, int *pWidt { // query the current displaymode, when running in fullscreen // this is required if DPI scaling is active - if(SdlFlags&SDL_WINDOW_FULLSCREEN) + if(SdlFlags & SDL_WINDOW_FULLSCREEN) { SDL_DisplayMode CurrentDisplayMode; SDL_GetCurrentDisplayMode(g_Config.m_GfxScreen, &CurrentDisplayMode); @@ -4644,7 +4661,7 @@ void CGraphicsBackend_SDL_OpenGL::Maximize() bool CGraphicsBackend_SDL_OpenGL::Fullscreen(bool State) { -#if defined(CONF_PLATFORM_MACOSX) // Todo SDL: remove this when fixed (game freezes when losing focus in fullscreen) +#if defined(CONF_PLATFORM_MACOSX) // Todo SDL: remove this when fixed (game freezes when losing focus in fullscreen) return SDL_SetWindowFullscreen(m_pWindow, State ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0) == 0; #else return SDL_SetWindowFullscreen(m_pWindow, State ? SDL_WINDOW_FULLSCREEN : 0) == 0; @@ -4680,12 +4697,12 @@ int CGraphicsBackend_SDL_OpenGL::GetWindowScreen() int CGraphicsBackend_SDL_OpenGL::WindowActive() { - return SDL_GetWindowFlags(m_pWindow)&SDL_WINDOW_INPUT_FOCUS; + return SDL_GetWindowFlags(m_pWindow) & SDL_WINDOW_INPUT_FOCUS; } int CGraphicsBackend_SDL_OpenGL::WindowOpen() { - return SDL_GetWindowFlags(m_pWindow)&SDL_WINDOW_SHOWN; + return SDL_GetWindowFlags(m_pWindow) & SDL_WINDOW_SHOWN; } void CGraphicsBackend_SDL_OpenGL::SetWindowGrab(bool Grab) @@ -4704,33 +4721,32 @@ void CGraphicsBackend_SDL_OpenGL::NotifyWindow() return; } - #if defined(CONF_FAMILY_WINDOWS) - FLASHWINFO desc; - desc.cbSize = sizeof(desc); - desc.hwnd = info.info.win.window; - desc.dwFlags = FLASHW_TRAY; - desc.uCount = 3; // flash 3 times - desc.dwTimeout = 0; +#if defined(CONF_FAMILY_WINDOWS) + FLASHWINFO desc; + desc.cbSize = sizeof(desc); + desc.hwnd = info.info.win.window; + desc.dwFlags = FLASHW_TRAY; + desc.uCount = 3; // flash 3 times + desc.dwTimeout = 0; - FlashWindowEx(&desc); - #elif defined(SDL_VIDEO_DRIVER_X11) && !defined(CONF_PLATFORM_MACOSX) - Display *dpy = info.info.x11.display; - Window win = info.info.x11.window; + FlashWindowEx(&desc); +#elif defined(SDL_VIDEO_DRIVER_X11) && !defined(CONF_PLATFORM_MACOSX) + Display *dpy = info.info.x11.display; + Window win = info.info.x11.window; - // Old hints - XWMHints *wmhints; - wmhints = XAllocWMHints(); - wmhints->flags = XUrgencyHint; - XSetWMHints(dpy, win, wmhints); - XFree(wmhints); + // Old hints + XWMHints *wmhints; + wmhints = XAllocWMHints(); + wmhints->flags = XUrgencyHint; + XSetWMHints(dpy, win, wmhints); + XFree(wmhints); - // More modern way of notifying - static Atom demandsAttention = XInternAtom(dpy, "_NET_WM_STATE_DEMANDS_ATTENTION", true); - static Atom wmState = XInternAtom(dpy, "_NET_WM_STATE", true); - XChangeProperty(dpy, win, wmState, XA_ATOM, 32, PropModeReplace, - (unsigned char *) &demandsAttention, 1); - #endif + // More modern way of notifying + static Atom demandsAttention = XInternAtom(dpy, "_NET_WM_STATE_DEMANDS_ATTENTION", true); + static Atom wmState = XInternAtom(dpy, "_NET_WM_STATE", true); + XChangeProperty(dpy, win, wmState, XA_ATOM, 32, PropModeReplace, + (unsigned char *)&demandsAttention, 1); +#endif } - IGraphicsBackend *CreateGraphicsBackend() { return new CGraphicsBackend_SDL_OpenGL; } diff --git a/src/engine/client/backend_sdl.h b/src/engine/client/backend_sdl.h index 548f0bbd3..cb0b42653 100644 --- a/src/engine/client/backend_sdl.h +++ b/src/engine/client/backend_sdl.h @@ -7,32 +7,31 @@ #include -# if defined(CONF_PLATFORM_MACOSX) - #include +#if defined(CONF_PLATFORM_MACOSX) +#include - class CAutoreleasePool +class CAutoreleasePool +{ +private: + id m_Pool; + +public: + CAutoreleasePool() { - private: - id m_Pool; + Class NSAutoreleasePoolClass = (Class)objc_getClass("NSAutoreleasePool"); + m_Pool = class_createInstance(NSAutoreleasePoolClass, 0); + SEL selector = sel_registerName("init"); + ((id(*)(id, SEL))objc_msgSend)(m_Pool, selector); + } - public: - CAutoreleasePool() - { - Class NSAutoreleasePoolClass = (Class) objc_getClass("NSAutoreleasePool"); - m_Pool = class_createInstance(NSAutoreleasePoolClass, 0); - SEL selector = sel_registerName("init"); - ((id (*)(id, SEL))objc_msgSend)(m_Pool, selector); - } - - ~CAutoreleasePool() - { - SEL selector = sel_registerName("drain"); - ((id (*)(id, SEL))objc_msgSend)(m_Pool, selector); - } - }; + ~CAutoreleasePool() + { + SEL selector = sel_registerName("drain"); + ((id(*)(id, SEL))objc_msgSend)(m_Pool, selector); + } +}; #endif - // basic threaded backend, abstract, missing init and shutdown functions class CGraphicsBackend_Threaded : public IGraphicsBackend { @@ -57,7 +56,7 @@ protected: private: ICommandProcessor *m_pProcessor; - CCommandBuffer * volatile m_pBuffer; + CCommandBuffer *volatile m_pBuffer; volatile bool m_Shutdown; semaphore m_Activity; semaphore m_BufferDone; @@ -71,10 +70,10 @@ class CCommandProcessorFragment_General { void Cmd_Nop(); void Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand); -public: - bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); -}; +public: + bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); +}; struct SBackendCapabilites { @@ -110,7 +109,8 @@ class CCommandProcessorFragment_OpenGL protected: struct CTexture { - CTexture() : m_Tex(0), m_Tex2DArray(0), m_Sampler(0), m_Sampler2DArray(0) {} + CTexture() : + m_Tex(0), m_Tex2DArray(0), m_Sampler(0), m_Sampler2DArray(0) {} GLuint m_Tex; GLuint m_Tex2DArray; //or 3D texture as fallback GLuint m_Sampler; @@ -140,6 +140,7 @@ protected: bool m_HasShaders; int m_LastBlendMode; //avoid all possible opengl state changes bool m_LastClipEnable; + public: enum { @@ -149,7 +150,8 @@ public: struct SCommand_Init : public CCommandBuffer::SCommand { - SCommand_Init() : SCommand(CMD_INIT) {} + SCommand_Init() : + SCommand(CMD_INIT) {} class IStorage *m_pStorage; std::atomic *m_pTextureMemoryUsage; SBackendCapabilites *m_pCapabilities; @@ -158,7 +160,8 @@ public: struct SCommand_Shutdown : public CCommandBuffer::SCommand { - SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {} + SCommand_Shutdown() : + SCommand(CMD_SHUTDOWN) {} }; protected: @@ -190,7 +193,7 @@ protected: virtual void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) {} virtual void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) {} virtual void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) {} - + virtual void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) {} virtual void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) {} virtual void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) {} @@ -200,13 +203,15 @@ protected: virtual void Cmd_RenderQuadContainer(const CCommandBuffer::SCommand_RenderQuadContainer *pCommand) {} virtual void Cmd_RenderQuadContainerAsSprite(const CCommandBuffer::SCommand_RenderQuadContainerAsSprite *pCommand) {} virtual void Cmd_RenderQuadContainerAsSpriteMultiple(const CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple *pCommand) {} + public: CCommandProcessorFragment_OpenGL(); - bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); + bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); }; -class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenGL { +class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenGL +{ struct SBufferContainer { SBufferContainer() {} @@ -218,13 +223,14 @@ class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenG struct SBufferObject { - SBufferObject(GLuint BufferObjectID) : m_BufferObjectID(BufferObjectID) + SBufferObject(GLuint BufferObjectID) : + m_BufferObjectID(BufferObjectID) { m_pData = NULL; m_DataSize = 0; } GLuint m_BufferObjectID; - void* m_pData; + void *m_pData; size_t m_DataSize; }; @@ -233,10 +239,11 @@ class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenG bool DoAnalyzeStep(size_t StepN, size_t CheckCount, size_t VerticesCount, uint8_t aFakeTexture[], size_t SingleImageSize); bool IsTileMapAnalysisSucceeded(); - void RenderBorderTileEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int DrawNum, const float* pOffset, const float* pDir, int JumpIndex); - void RenderBorderTileLineEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float* pOffset, const float* pDir); + void RenderBorderTileEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int DrawNum, const float *pOffset, const float *pDir, int JumpIndex); + void RenderBorderTileLineEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float *pOffset, const float *pDir); void UseProgram(CGLSLTWProgram *pProgram); + protected: void SetState(const CCommandBuffer::SState &State, CGLSLTWProgram *pProgram, bool Use2DArrayTextures = false); @@ -254,8 +261,8 @@ protected: void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) override; void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) override; void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) override; - - void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override; + + void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override; void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) override; void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) override; @@ -263,24 +270,27 @@ protected: CGLSLTileProgram *m_pTileProgramTextured; CGLSLPrimitiveProgram *m_pPrimitive3DProgram; CGLSLPrimitiveProgram *m_pPrimitive3DProgramTextured; - + bool m_UseMultipleTextureUnits; - + GLint m_MaxTextureUnits; - - struct STextureBound{ + + struct STextureBound + { int m_TextureSlot; bool m_Is2DArray; }; std::vector m_TextureSlotBoundToUnit; //the texture index generated by loadtextureraw is stored in an index calculated by max texture units - + bool IsAndUpdateTextureSlotBound(int IDX, int Slot, bool Is2DArray = false); + public: - CCommandProcessorFragment_OpenGL2() : CCommandProcessorFragment_OpenGL(), m_UseMultipleTextureUnits(false) {} + CCommandProcessorFragment_OpenGL2() : + CCommandProcessorFragment_OpenGL(), m_UseMultipleTextureUnits(false) {} }; -class CCommandProcessorFragment_OpenGL3 : public CCommandProcessorFragment_OpenGL2 { - +class CCommandProcessorFragment_OpenGL3 : public CCommandProcessorFragment_OpenGL2 +{ }; #define MAX_STREAM_BUFFER_COUNT 30 @@ -314,17 +324,18 @@ class CCommandProcessorFragment_OpenGL3_3 : public CCommandProcessorFragment_Ope GLuint m_LastIndexBufferBound[MAX_STREAM_BUFFER_COUNT]; int m_LastStreamBuffer; - + GLuint m_QuadDrawIndexBufferID; unsigned int m_CurrentIndicesInBuffer; void DestroyBufferContainer(int Index, bool DeleteBOs = true); - + void AppendIndices(unsigned int NewIndicesCount); - + struct SBufferContainer { - SBufferContainer() : m_VertArrayID(0), m_LastIndexBufferBound(0) {} + SBufferContainer() : + m_VertArrayID(0), m_LastIndexBufferBound(0) {} GLuint m_VertArrayID; GLuint m_LastIndexBufferBound; SBufferContainerInfo m_ContainerInfo; @@ -332,8 +343,9 @@ class CCommandProcessorFragment_OpenGL3_3 : public CCommandProcessorFragment_Ope std::vector m_BufferContainers; std::vector m_BufferObjectIndices; - + CCommandBuffer::SColorf m_ClearColor; + protected: static int TexFormatToNewOpenGLFormat(int TexFormat); bool IsNewApi() override { return true; } @@ -362,8 +374,8 @@ protected: void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) override; void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) override; void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) override; - - void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override; + + void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override; void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) override; void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) override; void Cmd_RenderQuadLayer(const CCommandBuffer::SCommand_RenderQuadLayer *pCommand) override; @@ -372,6 +384,7 @@ protected: void Cmd_RenderQuadContainer(const CCommandBuffer::SCommand_RenderQuadContainer *pCommand) override; void Cmd_RenderQuadContainerAsSprite(const CCommandBuffer::SCommand_RenderQuadContainerAsSprite *pCommand) override; void Cmd_RenderQuadContainerAsSpriteMultiple(const CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple *pCommand) override; + public: CCommandProcessorFragment_OpenGL3_3() = default; }; @@ -382,6 +395,7 @@ class CCommandProcessorFragment_SDL // SDL stuff SDL_Window *m_pWindow; SDL_GLContext m_GLContext; + public: enum { @@ -392,7 +406,8 @@ public: struct SCommand_Init : public CCommandBuffer::SCommand { - SCommand_Init() : SCommand(CMD_INIT) {} + SCommand_Init() : + SCommand(CMD_INIT) {} SDL_Window *m_pWindow; SDL_GLContext m_GLContext; SBackendCapabilites *m_pCapabilities; @@ -410,7 +425,8 @@ public: struct SCommand_Update_Viewport : public CCommandBuffer::SCommand { - SCommand_Update_Viewport() : SCommand(CMD_UPDATE_VIEWPORT) {} + SCommand_Update_Viewport() : + SCommand(CMD_UPDATE_VIEWPORT) {} int m_X; int m_Y; int m_Width; @@ -419,7 +435,8 @@ public: struct SCommand_Shutdown : public CCommandBuffer::SCommand { - SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {} + SCommand_Shutdown() : + SCommand(CMD_SHUTDOWN) {} }; private: @@ -430,6 +447,7 @@ private: void Cmd_VSync(const CCommandBuffer::SCommand_VSync *pCommand); void Cmd_Resize(const CCommandBuffer::SCommand_Resize *pCommand); void Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand); + public: CCommandProcessorFragment_SDL(); @@ -442,6 +460,7 @@ class CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandP CCommandProcessorFragment_OpenGL *m_pOpenGL; CCommandProcessorFragment_SDL m_SDL; CCommandProcessorFragment_General m_General; + public: CCommandProcessor_SDL_OpenGL(int OpenGLMajor, int OpenGLMinor, int OpenGLPatch); virtual void RunBuffer(CCommandBuffer *pBuffer); @@ -457,8 +476,9 @@ class CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded int m_NumScreens; SBackendCapabilites m_Capabilites; - + bool m_UseNewOpenGL; + public: virtual int Init(const char *pName, int *Screen, int *pWidth, int *pHeight, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight, int *pCurrentWidth, int *pCurrentHeight, class IStorage *pStorage); virtual int Shutdown(); @@ -470,14 +490,14 @@ public: virtual void Minimize(); virtual void Maximize(); virtual bool Fullscreen(bool State); - virtual void SetWindowBordered(bool State); // on=true/off=false + virtual void SetWindowBordered(bool State); // on=true/off=false virtual bool SetWindowScreen(int Index); virtual int GetWindowScreen(); virtual int WindowActive(); virtual int WindowOpen(); virtual void SetWindowGrab(bool Grab); virtual void NotifyWindow(); - + virtual bool IsNewOpenGL() { return m_UseNewOpenGL; } virtual bool HasTileBuffering() { return m_Capabilites.m_TileBuffering; } virtual bool HasQuadBuffering() { return m_Capabilites.m_QuadBuffering; } diff --git a/src/engine/client/client.cpp b/src/engine/client/client.cpp index f39e16f60..0da65a1aa 100644 --- a/src/engine/client/client.cpp +++ b/src/engine/client/client.cpp @@ -5,14 +5,14 @@ #include -#include // qsort #include +#include // qsort #include #include #include -#include #include +#include #include #include @@ -36,10 +36,11 @@ #include #include -#include #include +#include #include #include +#include #include #include #include @@ -49,7 +50,6 @@ #include #include #include -#include #include #include @@ -57,12 +57,12 @@ #include -#include #include +#include #if defined(CONF_FAMILY_WINDOWS) - #define WIN32_LEAN_AND_MEAN - #include +#define WIN32_LEAN_AND_MEAN +#include #endif #include "client.h" @@ -70,7 +70,7 @@ #include "serverbrowser.h" #if defined(CONF_VIDEORECORDER) - #include "video.h" +#include "video.h" #endif #include @@ -111,7 +111,7 @@ void CGraph::ScaleMin() void CGraph::Add(float v, float r, float g, float b) { - m_Index = (m_Index+1)&(MAX_VALUES-1); + m_Index = (m_Index + 1) & (MAX_VALUES - 1); m_aValues[m_Index] = v; m_aColors[m_Index][0] = r; m_aColors[m_Index][1] = g; @@ -122,7 +122,6 @@ void CGraph::Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, { //m_pGraphics->BlendNormal(); - pGraphics->TextureClear(); pGraphics->QuadsBegin(); @@ -133,47 +132,45 @@ void CGraph::Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, pGraphics->LinesBegin(); pGraphics->SetColor(0.95f, 0.95f, 0.95f, 1.00f); - IGraphics::CLineItem LineItem(x, y+h/2, x+w, y+h/2); + IGraphics::CLineItem LineItem(x, y + h / 2, x + w, y + h / 2); pGraphics->LinesDraw(&LineItem, 1); pGraphics->SetColor(0.5f, 0.5f, 0.5f, 0.75f); IGraphics::CLineItem Array[2] = { - IGraphics::CLineItem(x, y+(h*3)/4, x+w, y+(h*3)/4), - IGraphics::CLineItem(x, y+h/4, x+w, y+h/4)}; + IGraphics::CLineItem(x, y + (h * 3) / 4, x + w, y + (h * 3) / 4), + IGraphics::CLineItem(x, y + h / 4, x + w, y + h / 4)}; pGraphics->LinesDraw(Array, 2); for(int i = 1; i < MAX_VALUES; i++) { - float a0 = (i-1)/(float)MAX_VALUES; - float a1 = i/(float)MAX_VALUES; - int i0 = (m_Index+i-1)&(MAX_VALUES-1); - int i1 = (m_Index+i)&(MAX_VALUES-1); + float a0 = (i - 1) / (float)MAX_VALUES; + float a1 = i / (float)MAX_VALUES; + int i0 = (m_Index + i - 1) & (MAX_VALUES - 1); + int i1 = (m_Index + i) & (MAX_VALUES - 1); - float v0 = (m_aValues[i0]-m_Min) / (m_Max-m_Min); - float v1 = (m_aValues[i1]-m_Min) / (m_Max-m_Min); + float v0 = (m_aValues[i0] - m_Min) / (m_Max - m_Min); + float v1 = (m_aValues[i1] - m_Min) / (m_Max - m_Min); IGraphics::CColorVertex Array[2] = { IGraphics::CColorVertex(0, m_aColors[i0][0], m_aColors[i0][1], m_aColors[i0][2], 0.75f), IGraphics::CColorVertex(1, m_aColors[i1][0], m_aColors[i1][1], m_aColors[i1][2], 0.75f)}; pGraphics->SetColorVertex(Array, 2); - IGraphics::CLineItem LineItem(x+a0*w, y+h-v0*h, x+a1*w, y+h-v1*h); + IGraphics::CLineItem LineItem(x + a0 * w, y + h - v0 * h, x + a1 * w, y + h - v1 * h); pGraphics->LinesDraw(&LineItem, 1); - } pGraphics->LinesEnd(); pGraphics->TextureSet(FontTexture); pGraphics->QuadsBegin(); - pGraphics->QuadsText(x+2, y+h-16, 16, pDescription); + pGraphics->QuadsText(x + 2, y + h - 16, 16, pDescription); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%.2f", m_Max); - pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+2, 16, aBuf); + pGraphics->QuadsText(x + w - 8 * str_length(aBuf) - 8, y + 2, 16, aBuf); str_format(aBuf, sizeof(aBuf), "%.2f", m_Min); - pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+h-16, 16, aBuf); + pGraphics->QuadsText(x + w - 8 * str_length(aBuf) - 8, y + h - 16, 16, aBuf); pGraphics->QuadsEnd(); } - void CSmoothTime::Init(int64 Target) { m_Snap = time_get(); @@ -201,13 +198,13 @@ int64 CSmoothTime::Get(int64 Now) if(t > c) AdjustSpeed = m_aAdjustSpeed[1]; - float a = ((Now-m_Snap)/(float)time_freq()) * AdjustSpeed; + float a = ((Now - m_Snap) / (float)time_freq()) * AdjustSpeed; if(a > 1.0f) a = 1.0f; - int64 r = c + (int64)((t-c)*a); + int64 r = c + (int64)((t - c) * a); - m_Graph.Add(a+0.5f,1,1,1); + m_Graph.Add(a + 0.5f, 1, 1, 1); return r; } @@ -240,11 +237,11 @@ void CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustD { // ignore this ping spike UpdateTimer = 0; - pGraph->Add(TimeLeft, 1,1,0); + pGraph->Add(TimeLeft, 1, 1, 0); } else { - pGraph->Add(TimeLeft, 1,0,0); + pGraph->Add(TimeLeft, 1, 0, 0); if(m_aAdjustSpeed[AdjustDirection] < 30.0f) m_aAdjustSpeed[AdjustDirection] *= 2.0f; } @@ -254,7 +251,7 @@ void CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustD if(m_SpikeCounter) m_SpikeCounter--; - pGraph->Add(TimeLeft, 0,1,0); + pGraph->Add(TimeLeft, 0, 1, 0); m_aAdjustSpeed[AdjustDirection] *= 0.95f; if(m_aAdjustSpeed[AdjustDirection] < 2.0f) @@ -265,10 +262,10 @@ void CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustD UpdateInt(Target); } - -CClient::CClient() : m_DemoPlayer(&m_SnapshotDelta) +CClient::CClient() : + m_DemoPlayer(&m_SnapshotDelta) { - for (int i = 0; i < RECORDER_MAX; i++) + for(int i = 0; i < RECORDER_MAX; i++) m_DemoRecorder[i] = CDemoRecorder(&m_SnapshotDelta); m_pEditor = 0; @@ -371,11 +368,11 @@ static inline bool RepackMsg(const CMsgPacker *pMsg, CPacker &Packer) Packer.Reset(); if(pMsg->m_MsgID < OFFSET_UUID) { - Packer.AddInt((pMsg->m_MsgID<<1)|(pMsg->m_System?1:0)); + Packer.AddInt((pMsg->m_MsgID << 1) | (pMsg->m_System ? 1 : 0)); } else { - Packer.AddInt((0<<1)|(pMsg->m_System?1:0)); // NETMSG_EX, NETMSGTYPE_EX + Packer.AddInt((0 << 1) | (pMsg->m_System ? 1 : 0)); // NETMSG_EX, NETMSGTYPE_EX g_UuidManager.PackUuid(pMsg->m_MsgID, &Packer); } Packer.AddRaw(pMsg->Data(), pMsg->Size()); @@ -400,19 +397,19 @@ int CClient::SendMsg(CMsgPacker *pMsg, int Flags) Packet.m_pData = Pack.Data(); Packet.m_DataSize = Pack.Size(); - if(Flags&MSGFLAG_VITAL) + if(Flags & MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; - if(Flags&MSGFLAG_FLUSH) + if(Flags & MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; - if(Flags&MSGFLAG_RECORD) + if(Flags & MSGFLAG_RECORD) { for(int i = 0; i < RECORDER_MAX; i++) if(m_DemoRecorder[i].IsRecording()) m_DemoRecorder[i].RecordMessage(Packet.m_pData, Packet.m_DataSize); } - if(!(Flags&MSGFLAG_NOSEND)) + if(!(Flags & MSGFLAG_NOSEND)) { m_NetClient[g_Config.m_ClDummy].Send(&Packet); } @@ -431,20 +428,19 @@ void CClient::SendInfo() CMsgPacker Msg(NETMSG_INFO, true); Msg.AddString(GameClient()->NetVersion(), 128); Msg.AddString(m_Password, 128); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH); } - void CClient::SendEnterGame() { CMsgPacker Msg(NETMSG_ENTERGAME, true); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH); } void CClient::SendReady() { CMsgPacker Msg(NETMSG_READY, true); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH); } void CClient::SendMapRequest() @@ -454,7 +450,7 @@ void CClient::SendMapRequest() m_MapdownloadFile = Storage()->OpenFile(m_aMapdownloadFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true); Msg.AddInt(m_MapdownloadChunk); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH); } void CClient::RconAuth(const char *pName, const char *pPassword) @@ -491,7 +487,7 @@ void CClient::DirectInput(int *pInput, int Size) Msg.AddInt(m_PredTick[g_Config.m_ClDummy]); Msg.AddInt(Size); - for(int i = 0; i < Size/4; i++) + for(int i = 0; i < Size / 4; i++) Msg.AddInt(pInput[i]); SendMsg(&Msg, 0); @@ -528,7 +524,7 @@ void CClient::SendInput() m_aInputs[i][m_CurrentInput[i]].m_Time = Now; // pack it - for(int k = 0; k < Size/4; k++) + for(int k = 0; k < Size / 4; k++) Msg.AddInt(m_aInputs[i][m_CurrentInput[i]].m_aData[k]); m_CurrentInput[i]++; @@ -762,7 +758,7 @@ void CClient::Connect(const char *pAddress, const char *pPassword) void CClient::DisconnectWithReason(const char *pReason) { char aBuf[512]; - str_format(aBuf, sizeof(aBuf), "disconnecting. reason='%s'", pReason?pReason:"unknown"); + str_format(aBuf, sizeof(aBuf), "disconnecting. reason='%s'", pReason ? pReason : "unknown"); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); // stop demo playback and recorder @@ -889,9 +885,9 @@ int CClient::SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient) Packet.m_pData = Pack.Data(); Packet.m_DataSize = Pack.Size(); - if(Flags&MSGFLAG_VITAL) + if(Flags & MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; - if(Flags&MSGFLAG_FLUSH) + if(Flags & MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; m_NetClient[NetClient].Send(&Packet); @@ -982,7 +978,6 @@ void CClient::SnapSetStaticsize(int ItemType, int Size) m_SnapshotDelta.SetStaticsize(ItemType, Size); } - void CClient::DebugRender() { static NETSTATS Prev, Current; @@ -995,10 +990,10 @@ void CClient::DebugRender() //m_pGraphics->BlendNormal(); Graphics()->TextureSet(m_DebugFont); - Graphics()->MapScreen(0,0,Graphics()->ScreenWidth(),Graphics()->ScreenHeight()); + Graphics()->MapScreen(0, 0, Graphics()->ScreenWidth(), Graphics()->ScreenHeight()); Graphics()->QuadsBegin(); - if(time_get()-LastSnap > time_freq()) + if(time_get() - LastSnap > time_freq()) { LastSnap = time_get(); Prev = Current; @@ -1011,27 +1006,28 @@ void CClient::DebugRender() udp = 8 total = 42 */ - FrameTimeAvg = FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f; + FrameTimeAvg = FrameTimeAvg * 0.9f + m_RenderFrameTime * 0.1f; str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d gfxmem: %dk fps: %3d", m_CurGameTick[g_Config.m_ClDummy], m_PredTick[g_Config.m_ClDummy], - Graphics()->MemoryUsage()/1024, - (int)(1.0f/FrameTimeAvg + 0.5f)); + Graphics()->MemoryUsage() / 1024, + (int)(1.0f / FrameTimeAvg + 0.5f)); Graphics()->QuadsText(2, 2, 16, aBuffer); - { - int SendPackets = (Current.sent_packets-Prev.sent_packets); - int SendBytes = (Current.sent_bytes-Prev.sent_bytes); - int SendTotal = SendBytes + SendPackets*42; - int RecvPackets = (Current.recv_packets-Prev.recv_packets); - int RecvBytes = (Current.recv_bytes-Prev.recv_bytes); - int RecvTotal = RecvBytes + RecvPackets*42; + int SendPackets = (Current.sent_packets - Prev.sent_packets); + int SendBytes = (Current.sent_bytes - Prev.sent_bytes); + int SendTotal = SendBytes + SendPackets * 42; + int RecvPackets = (Current.recv_packets - Prev.recv_packets); + int RecvBytes = (Current.recv_bytes - Prev.recv_bytes); + int RecvTotal = RecvBytes + RecvPackets * 42; - if(!SendPackets) SendPackets++; - if(!RecvPackets) RecvPackets++; + if(!SendPackets) + SendPackets++; + if(!RecvPackets) + RecvPackets++; str_format(aBuffer, sizeof(aBuffer), "send: %3d %5d+%4d=%5d (%3d kbps) avg: %5d\nrecv: %3d %5d+%4d=%5d (%3d kbps) avg: %5d", - SendPackets, SendBytes, SendPackets*42, SendTotal, (SendTotal*8)/1024, SendBytes/SendPackets, - RecvPackets, RecvBytes, RecvPackets*42, RecvTotal, (RecvTotal*8)/1024, RecvBytes/RecvPackets); + SendPackets, SendBytes, SendPackets * 42, SendTotal, (SendTotal * 8) / 1024, SendBytes / SendPackets, + RecvPackets, RecvBytes, RecvPackets * 42, RecvTotal, (RecvTotal * 8) / 1024, RecvBytes / RecvPackets); Graphics()->QuadsText(2, 14, 16, aBuffer); } @@ -1043,9 +1039,9 @@ void CClient::DebugRender() { if(m_SnapshotDelta.GetDataRate(i)) { - str_format(aBuffer, sizeof(aBuffer), "%4d %20s: %8d %8d %8d", i, GameClient()->GetItemName(i), m_SnapshotDelta.GetDataRate(i)/8, m_SnapshotDelta.GetDataUpdates(i), - (m_SnapshotDelta.GetDataRate(i)/m_SnapshotDelta.GetDataUpdates(i))/8); - Graphics()->QuadsText(2, 100+y*12, 16, aBuffer); + str_format(aBuffer, sizeof(aBuffer), "%4d %20s: %8d %8d %8d", i, GameClient()->GetItemName(i), m_SnapshotDelta.GetDataRate(i) / 8, m_SnapshotDelta.GetDataUpdates(i), + (m_SnapshotDelta.GetDataRate(i) / m_SnapshotDelta.GetDataUpdates(i)) / 8); + Graphics()->QuadsText(2, 100 + y * 12, 16, aBuffer); y++; } } @@ -1059,16 +1055,16 @@ void CClient::DebugRender() if(g_Config.m_DbgGraphs) { //Graphics()->MapScreen(0,0,400.0f,300.0f); - float w = Graphics()->ScreenWidth()/4.0f; - float h = Graphics()->ScreenHeight()/6.0f; - float sp = Graphics()->ScreenWidth()/100.0f; - float x = Graphics()->ScreenWidth()-w-sp; + float w = Graphics()->ScreenWidth() / 4.0f; + float h = Graphics()->ScreenHeight() / 6.0f; + float sp = Graphics()->ScreenWidth() / 100.0f; + float x = Graphics()->ScreenWidth() - w - sp; m_FpsGraph.ScaleMax(); m_FpsGraph.ScaleMin(); - m_FpsGraph.Render(Graphics(), m_DebugFont, x, sp*5, w, h, "FPS"); - m_InputtimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp, w, h, "Prediction Margin"); - m_GametimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp+h+sp, w, h, "Gametime Margin"); + m_FpsGraph.Render(Graphics(), m_DebugFont, x, sp * 5, w, h, "FPS"); + m_InputtimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp * 5 + h + sp, w, h, "Prediction Margin"); + m_GametimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp * 5 + h + sp + h + sp, w, h, "Gametime Margin"); } } @@ -1142,7 +1138,7 @@ void CClient::Render() if(State() == IClient::STATE_ONLINE && g_Config.m_ClAntiPingLimit) { int64 Now = time_get(); - g_Config.m_ClAntiPing = (m_PredictedTime.Get(Now)-m_GameTime[g_Config.m_ClDummy].Get(Now))*1000/(float)time_freq() > g_Config.m_ClAntiPingLimit; + g_Config.m_ClAntiPing = (m_PredictedTime.Get(Now) - m_GameTime[g_Config.m_ClDummy].Get(Now)) * 1000 / (float)time_freq() > g_Config.m_ClAntiPingLimit; } } @@ -1271,9 +1267,9 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) //server count from master server if(pPacket->m_DataSize == (int)sizeof(SERVERBROWSE_COUNT) + 2 && mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) { - unsigned char *pP = (unsigned char*) pPacket->m_pData; + unsigned char *pP = (unsigned char *)pPacket->m_pData; pP += sizeof(SERVERBROWSE_COUNT); - int ServerCount = ((*pP)<<8) | *(pP+1); + int ServerCount = ((*pP) << 8) | *(pP + 1); int ServerID = -1; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { @@ -1314,14 +1310,14 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) if(!Valid) return; - int Size = pPacket->m_DataSize-sizeof(SERVERBROWSE_LIST); - int Num = Size/sizeof(CMastersrvAddr); - CMastersrvAddr *pAddrs = (CMastersrvAddr *)((char*)pPacket->m_pData+sizeof(SERVERBROWSE_LIST)); + int Size = pPacket->m_DataSize - sizeof(SERVERBROWSE_LIST); + int Num = Size / sizeof(CMastersrvAddr); + CMastersrvAddr *pAddrs = (CMastersrvAddr *)((char *)pPacket->m_pData + sizeof(SERVERBROWSE_LIST)); for(int i = 0; i < Num; i++) { NETADDR Addr; - static unsigned char s_IPV4Mapping[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF }; + static unsigned char s_IPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}; // copy address if(!mem_comp(s_IPV4Mapping, pAddrs[i].m_aIp, sizeof(s_IPV4Mapping))) @@ -1338,7 +1334,7 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) Addr.type = NETTYPE_IPV6; mem_copy(Addr.ip, pAddrs[i].m_aIp, sizeof(Addr.ip)); } - Addr.port = (pAddrs[i].m_aPort[0]<<8) | pAddrs[i].m_aPort[1]; + Addr.port = (pAddrs[i].m_aPort[0] << 8) | pAddrs[i].m_aPort[1]; m_ServerBrowser.Set(Addr, IServerBrowser::SET_MASTER_ADD, -1, 0x0); } @@ -1393,8 +1389,8 @@ void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, CUnpacker Up; Up.Reset(pData, DataSize); - #define GET_STRING(array) str_copy(array, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(array)) - #define GET_INT(integer) (integer) = str_toint(Up.GetString()) +#define GET_STRING(array) str_copy(array, Up.GetString(CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES), sizeof(array)) +#define GET_INT(integer) (integer) = str_toint(Up.GetString()) int Offset = 0; // Only used for SavedType == SERVERINFO_64_LEGACY int Token; @@ -1478,7 +1474,7 @@ void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, Up.GetString(); // extra info, reserved uint64 Flag = (uint64)1 << PacketNo; - DuplicatedPacket = Info.m_ReceivedPackets&Flag; + DuplicatedPacket = Info.m_ReceivedPackets & Flag; Info.m_ReceivedPackets |= Flag; } @@ -1507,7 +1503,7 @@ void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, if(SavedType == SERVERINFO_64_LEGACY) { uint64 Flag = (uint64)1 << i; - if(!(Info.m_ReceivedPackets&Flag)) + if(!(Info.m_ReceivedPackets & Flag)) { Info.m_ReceivedPackets |= Flag; Info.m_NumReceivedClients++; @@ -1558,8 +1554,8 @@ void CClient::ProcessServerInfo(int RawType, NETADDR *pFrom, const void *pData, } } - #undef GET_STRING - #undef GET_INT +#undef GET_STRING +#undef GET_INT } bool CClient::ShouldSendChatTimeoutCodeHeuristic() @@ -1604,12 +1600,12 @@ static CServerCapabilities GetServerCapabilities(int Version, int Flags) bool DDNet = false; if(Version >= 1) { - DDNet = Flags&SERVERCAPFLAG_DDNET; + DDNet = Flags & SERVERCAPFLAG_DDNET; } Result.m_ChatTimeoutCode = DDNet; if(Version >= 1) { - Result.m_ChatTimeoutCode = Flags&SERVERCAPFLAG_CHATTIMEOUTCODE; + Result.m_ChatTimeoutCode = Flags & SERVERCAPFLAG_CHATTIMEOUTCODE; } return Result; } @@ -1638,9 +1634,9 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) if(Sys) { // system message - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_DETAILS) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_DETAILS) { - const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES); + const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES); SHA256_DIGEST *pMapSha256 = (SHA256_DIGEST *)Unpacker.GetRaw(sizeof(*pMapSha256)); int MapCrc = Unpacker.GetInt(); @@ -1654,7 +1650,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) m_MapDetailsSha256 = *pMapSha256; m_MapDetailsCrc = MapCrc; } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CAPABILITIES) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CAPABILITIES) { if(!m_CanReceiveServerCapabilities) { @@ -1670,7 +1666,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) m_CanReceiveServerCapabilities = false; m_ServerSentCapabilities = true; } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_CHANGE) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_CHANGE) { if(m_CanReceiveServerCapabilities) { @@ -1680,7 +1676,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) bool MapDetailsWerePresent = m_MapDetailsPresent; m_MapDetailsPresent = false; - const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES); + const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC | CUnpacker::SKIP_START_WHITESPACES); int MapCrc = Unpacker.GetInt(); int MapSize = Unpacker.GetInt(); const char *pError = 0; @@ -1788,7 +1784,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true); Msg.AddInt(m_MapdownloadChunk); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH); if(g_Config.m_Debug) { @@ -1798,7 +1794,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) } } } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CON_READY) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CON_READY) { GameClient()->OnConnected(); } @@ -1807,7 +1803,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) CMsgPacker Msg(NETMSG_PING_REPLY, true); SendMsg(&Msg, 0); } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_ADD) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_ADD) { const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); const char *pHelp = Unpacker.GetString(CUnpacker::SANITIZE_CC); @@ -1815,13 +1811,13 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) if(Unpacker.Error() == 0) m_pConsole->RegisterTemp(pName, pParams, CFGFLAG_SERVER, pHelp); } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_REM) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_REM) { const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(Unpacker.Error() == 0) m_pConsole->DeregisterTemp(pName); } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_AUTH_STATUS) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_AUTH_STATUS) { int Result = Unpacker.GetInt(); if(Unpacker.Error() == 0) @@ -1833,7 +1829,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) if(Old != 0 && m_UseTempRconCommands == 0) m_pConsole->DeregisterTempAll(); } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_LINE) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_LINE) { const char *pLine = Unpacker.GetString(); if(Unpacker.Error() == 0) @@ -1842,7 +1838,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) else if(Msg == NETMSG_PING_REPLY) { char aBuf[256]; - str_format(aBuf, sizeof(aBuf), "latency %.2f", (time_get() - m_PingStartTime)*1000 / (float)time_freq()); + str_format(aBuf, sizeof(aBuf), "latency %.2f", (time_get() - m_PingStartTime) * 1000 / (float)time_freq()); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client/network", aBuf); } else if(Msg == NETMSG_INPUTTIMING) @@ -1858,7 +1854,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) if(m_aInputs[g_Config.m_ClDummy][k].m_Tick == InputPredTick) { Target = m_aInputs[g_Config.m_ClDummy][k].m_PredictedTime + (Now - m_aInputs[g_Config.m_ClDummy][k].m_Time); - Target = Target - (int64)(((TimeLeft-PREDICTION_MARGIN)/1000.0f)*time_freq()); + Target = Target - (int64)(((TimeLeft - PREDICTION_MARGIN) / 1000.0f) * time_freq()); break; } } @@ -1871,7 +1867,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) int NumParts = 1; int Part = 0; int GameTick = Unpacker.GetInt(); - int DeltaTick = GameTick-Unpacker.GetInt(); + int DeltaTick = GameTick - Unpacker.GetInt(); int PartSize = 0; int Crc = 0; int CompleteSize = 0; @@ -1910,10 +1906,10 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) m_CurrentRecvTick[g_Config.m_ClDummy] = GameTick; } - mem_copy((char*)m_aSnapshotIncomingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, clamp(PartSize, 0, (int)sizeof(m_aSnapshotIncomingData) - Part*MAX_SNAPSHOT_PACKSIZE)); - m_SnapshotParts[g_Config.m_ClDummy] |= 1< 2) { int64 Now = m_GameTime[g_Config.m_ClDummy].Get(time_get()); - int64 TickStart = GameTick*time_freq()/50; - int64 TimeLeft = (TickStart-Now)*1000 / time_freq(); - m_GameTime[g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0); + int64 TickStart = GameTick * time_freq() / 50; + int64 TimeLeft = (TickStart - Now) * 1000 / time_freq(); + m_GameTime[g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick - 1) * time_freq() / 50, TimeLeft, 0); } if(m_ReceivedSnapshots[g_Config.m_ClDummy] > 50 && !m_aTimeoutCodeSent[g_Config.m_ClDummy]) @@ -2091,7 +2087,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) } else { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 || Msg == NETMSGTYPE_SV_EXTRAPROJECTILE) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 || Msg == NETMSGTYPE_SV_EXTRAPROJECTILE) { // game message for(int i = 0; i < RECORDER_MAX; i++) @@ -2139,7 +2135,7 @@ void CClient::ProcessServerPacketDummy(CNetChunk *pPacket) int NumParts = 1; int Part = 0; int GameTick = Unpacker.GetInt(); - int DeltaTick = GameTick-Unpacker.GetInt(); + int DeltaTick = GameTick - Unpacker.GetInt(); int PartSize = 0; int Crc = 0; int CompleteSize = 0; @@ -2178,10 +2174,10 @@ void CClient::ProcessServerPacketDummy(CNetChunk *pPacket) m_CurrentRecvTick[!g_Config.m_ClDummy] = GameTick; } - mem_copy((char*)m_aSnapshotIncomingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, clamp(PartSize, 0, (int)sizeof(m_aSnapshotIncomingData) - Part*MAX_SNAPSHOT_PACKSIZE)); - m_SnapshotParts[!g_Config.m_ClDummy] |= 1< 2) { int64 Now = m_GameTime[!g_Config.m_ClDummy].Get(time_get()); - int64 TickStart = GameTick*time_freq()/50; - int64 TimeLeft = (TickStart-Now)*1000 / time_freq(); - m_GameTime[!g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0); + int64 TickStart = GameTick * time_freq() / 50; + int64 TimeLeft = (TickStart - Now) * 1000 / time_freq(); + m_GameTime[!g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick - 1) * time_freq() / 50, TimeLeft, 0); } // ack snapshot @@ -2418,8 +2414,7 @@ bool CClient::IsDDNetInfoChanged() io_close(OldFile); return true; } - } - while(OldBytes > 0); + } while(OldBytes > 0); io_close(NewFile); } @@ -2510,7 +2505,7 @@ void CClient::LoadDDNetInfo() void CClient::PumpNetwork() { - for(int i=0; i>= 1; if(Unpacker.Error()) @@ -2645,13 +2640,12 @@ void CClient::Update() { if(State() == IClient::STATE_DEMOPLAYBACK) { - #if defined(CONF_VIDEORECORDER) - if (m_DemoPlayer.IsPlaying() && IVideo::Current()) + if(m_DemoPlayer.IsPlaying() && IVideo::Current()) { - if (IVideo::Current()->FrameRendered()) + if(IVideo::Current()->FrameRendered()) IVideo::Current()->NextVideoFrame(); - if (IVideo::Current()->AudioFrameRendered()) + if(IVideo::Current()->AudioFrameRendered()) IVideo::Current()->NextAudioFrameTimeline(); } else if(m_ButtonRender) @@ -2691,7 +2685,7 @@ void CClient::Update() while(1) { CSnapshotStorage::CHolder *pCur = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]; - int64 TickStart = (pCur->m_Tick)*time_freq()/50; + int64 TickStart = (pCur->m_Tick) * time_freq() / 50; if(TickStart < Now) { @@ -2731,7 +2725,7 @@ void CClient::Update() while(1) { CSnapshotStorage::CHolder *pCur = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]; - int64 TickStart = (pCur->m_Tick)*time_freq()/50; + int64 TickStart = (pCur->m_Tick) * time_freq() / 50; if(TickStart < Now) { @@ -2758,25 +2752,24 @@ void CClient::Update() break; } - if(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] && m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]) { - int64 CurtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick)*time_freq()/50; - int64 PrevtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick)*time_freq()/50; - int PrevPredTick = (int)(PredNow*50/time_freq()); - int NewPredTick = PrevPredTick+1; + int64 CurtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick) * time_freq() / 50; + int64 PrevtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick) * time_freq() / 50; + int PrevPredTick = (int)(PredNow * 50 / time_freq()); + int NewPredTick = PrevPredTick + 1; - m_GameIntraTick[g_Config.m_ClDummy] = (Now - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + m_GameIntraTick[g_Config.m_ClDummy] = (Now - PrevtickStart) / (float)(CurtickStart - PrevtickStart); m_GameTickTime[g_Config.m_ClDummy] = (Now - PrevtickStart) / (float)Freq; //(float)SERVER_TICK_SPEED); - CurtickStart = NewPredTick*time_freq()/50; - PrevtickStart = PrevPredTick*time_freq()/50; - m_PredIntraTick[g_Config.m_ClDummy] = (PredNow - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + CurtickStart = NewPredTick * time_freq() / 50; + PrevtickStart = PrevPredTick * time_freq() / 50; + m_PredIntraTick[g_Config.m_ClDummy] = (PredNow - PrevtickStart) / (float)(CurtickStart - PrevtickStart); - if(NewPredTick < m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick-SERVER_TICK_SPEED || NewPredTick > m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick+SERVER_TICK_SPEED) + if(NewPredTick < m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick - SERVER_TICK_SPEED || NewPredTick > m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick + SERVER_TICK_SPEED) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "prediction time reset!"); - m_PredictedTime.Init(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick*time_freq()/50); + m_PredictedTime.Init(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick * time_freq() / 50); } if(NewPredTick > m_PredTick[g_Config.m_ClDummy]) @@ -2792,7 +2785,7 @@ void CClient::Update() // only do sane predictions if(Repredict) { - if(m_PredTick[g_Config.m_ClDummy] > m_CurGameTick[g_Config.m_ClDummy] && m_PredTick[g_Config.m_ClDummy] < m_CurGameTick[g_Config.m_ClDummy]+50) + if(m_PredTick[g_Config.m_ClDummy] > m_CurGameTick[g_Config.m_ClDummy] && m_PredTick[g_Config.m_ClDummy] < m_CurGameTick[g_Config.m_ClDummy] + 50) GameClient()->OnPredict(); } @@ -2802,7 +2795,7 @@ void CClient::Update() time_get() > m_CurrentServerInfoRequestTime) { m_ServerBrowser.RequestCurrentServer(m_ServerAddress); - m_CurrentServerInfoRequestTime = time_get()+time_freq()*2; + m_CurrentServerInfoRequestTime = time_get() + time_freq() * 2; } } @@ -2817,7 +2810,7 @@ void CClient::Update() int64 Now = time_get(); if(State() == IClient::STATE_OFFLINE) { - if(Now > ActionTaken+time_freq()*2) + if(Now > ActionTaken + time_freq() * 2) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "reconnecting!"); Connect(g_Config.m_DbgStressServer); @@ -2826,7 +2819,7 @@ void CClient::Update() } else { - if(Now > ActionTaken+time_freq()*(10+g_Config.m_DbgStress)) + if(Now > ActionTaken + time_freq() * (10 + g_Config.m_DbgStress)) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "disconnecting!"); Disconnect(); @@ -2919,16 +2912,16 @@ void CClient::Update() void CClient::RegisterInterfaces() { - Kernel()->RegisterInterface(static_cast(&m_DemoRecorder[RECORDER_MANUAL]), false); - Kernel()->RegisterInterface(static_cast(&m_DemoPlayer), false); - Kernel()->RegisterInterface(static_cast(&m_GhostRecorder), false); - Kernel()->RegisterInterface(static_cast(&m_GhostLoader), false); - Kernel()->RegisterInterface(static_cast(&m_ServerBrowser), false); + Kernel()->RegisterInterface(static_cast(&m_DemoRecorder[RECORDER_MANUAL]), false); + Kernel()->RegisterInterface(static_cast(&m_DemoPlayer), false); + Kernel()->RegisterInterface(static_cast(&m_GhostRecorder), false); + Kernel()->RegisterInterface(static_cast(&m_GhostLoader), false); + Kernel()->RegisterInterface(static_cast(&m_ServerBrowser), false); #if defined(CONF_AUTOUPDATE) - Kernel()->RegisterInterface(static_cast(&m_Updater), false); + Kernel()->RegisterInterface(static_cast(&m_Updater), false); #endif - Kernel()->RegisterInterface(static_cast(&m_Friends), false); - Kernel()->ReregisterInterface(static_cast(&m_Foes)); + Kernel()->RegisterInterface(static_cast(&m_Friends), false); + Kernel()->ReregisterInterface(static_cast(&m_Foes)); } void CClient::InitInterfaces() @@ -3005,7 +2998,7 @@ void CClient::Run() bool RegisterFail = false; RegisterFail = RegisterFail || !Kernel()->RegisterInterface(m_pGraphics); // IEngineGraphics - RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast(m_pGraphics), false); + RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast(m_pGraphics), false); if(RegisterFail || m_pGraphics->Init() != 0) { @@ -3040,8 +3033,7 @@ void CClient::Run() do { BindAddr.port = (secure_rand() % 64511) + 1024; - } - while(!m_NetClient[i].Open(BindAddr, 0)); + } while(!m_NetClient[i].Open(BindAddr, 0)); } } @@ -3159,26 +3151,26 @@ void CClient::Run() CMsgPacker MsgInfo(NETMSG_INFO, true); MsgInfo.AddString(GameClient()->NetVersion(), 128); MsgInfo.AddString(m_Password, 128); - SendMsgY(&MsgInfo, MSGFLAG_VITAL|MSGFLAG_FLUSH, 1); + SendMsgY(&MsgInfo, MSGFLAG_VITAL | MSGFLAG_FLUSH, 1); // update netclient m_NetClient[CLIENT_DUMMY].Update(); // send ready CMsgPacker MsgReady(NETMSG_READY, true); - SendMsgY(&MsgReady, MSGFLAG_VITAL|MSGFLAG_FLUSH, 1); + SendMsgY(&MsgReady, MSGFLAG_VITAL | MSGFLAG_FLUSH, 1); // startinfo GameClient()->SendDummyInfo(true); // send enter game an finish the connection CMsgPacker MsgEnter(NETMSG_ENTERGAME, true); - SendMsgY(&MsgEnter, MSGFLAG_VITAL|MSGFLAG_FLUSH, 1); + SendMsgY(&MsgEnter, MSGFLAG_VITAL | MSGFLAG_FLUSH, 1); } // update input if(Input()->Update()) - break; // SDL_QUIT + break; // SDL_QUIT #if defined(CONF_AUTOUPDATE) Updater()->Update(); #endif @@ -3194,7 +3186,7 @@ void CClient::Run() if(CtrlShiftKey(KEY_E, LastE)) { - g_Config.m_ClEditor = g_Config.m_ClEditor^1; + g_Config.m_ClEditor = g_Config.m_ClEditor ^ 1; Input()->MouseModeRelative(); Input()->SetIMEState(true); } @@ -3231,9 +3223,9 @@ void CClient::Run() m_RenderFrameTimeLow = m_RenderFrameTime; if(m_RenderFrameTime > m_RenderFrameTimeHigh) m_RenderFrameTimeHigh = m_RenderFrameTime; - m_FpsGraph.Add(1.0f/m_RenderFrameTime, 1,1,1); + m_FpsGraph.Add(1.0f / m_RenderFrameTime, 1, 1, 1); - m_FrameTimeAvg = m_FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f; + m_FrameTimeAvg = m_FrameTimeAvg * 0.9f + m_RenderFrameTime * 0.1f; // keep the overflow time - it's used to make sure the gfx refreshrate is reached int64 AdditionalTime = g_Config.m_GfxRefreshRate ? ((Now - LastRenderTime) - (time_freq() / (int64)g_Config.m_GfxRefreshRate)) : 0; @@ -3246,7 +3238,7 @@ void CClient::Run() #ifdef CONF_DEBUG if(g_Config.m_DbgStress) { - if((m_RenderFrames%10) == 0) + if((m_RenderFrames % 10) == 0) { if(!m_EditorActive) Render(); @@ -3341,12 +3333,12 @@ void CClient::Run() if(g_Config.m_DbgHitch) { - thread_sleep(g_Config.m_DbgHitch*1000); + thread_sleep(g_Config.m_DbgHitch * 1000); g_Config.m_DbgHitch = 0; } // update local time - m_LocalTime = (time_get()-m_LocalStartTime)/(float)time_freq(); + m_LocalTime = (time_get() - m_LocalStartTime) / (float)time_freq(); } #if defined(CONF_FAMILY_UNIX) @@ -3501,12 +3493,12 @@ void CClient::Con_StartVideo(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; - if (pSelf->State() != IClient::STATE_DEMOPLAYBACK) + if(pSelf->State() != IClient::STATE_DEMOPLAYBACK) pSelf->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "videorecorder", "Can not start videorecorder outside of demoplayer."); - if (!IVideo::Current()) + if(!IVideo::Current()) { - new CVideo((CGraphics_Threaded*)pSelf->m_pGraphics, pSelf->Storage(), pSelf->m_pConsole, pSelf->Graphics()->ScreenWidth(), pSelf->Graphics()->ScreenHeight(), ""); + new CVideo((CGraphics_Threaded *)pSelf->m_pGraphics, pSelf->Storage(), pSelf->m_pConsole, pSelf->Graphics()->ScreenWidth(), pSelf->Graphics()->ScreenHeight(), ""); IVideo::Current()->Start(); bool paused = pSelf->m_DemoPlayer.Info()->m_Info.m_Paused; if(paused) @@ -3520,13 +3512,13 @@ void CClient::StartVideo(IConsole::IResult *pResult, void *pUserData, const char { CClient *pSelf = (CClient *)pUserData; - if (pSelf->State() != IClient::STATE_DEMOPLAYBACK) + if(pSelf->State() != IClient::STATE_DEMOPLAYBACK) pSelf->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "videorecorder", "Can not start videorecorder outside of demoplayer."); pSelf->m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "demo_render", pVideoName); - if (!IVideo::Current()) + if(!IVideo::Current()) { - new CVideo((CGraphics_Threaded*)pSelf->m_pGraphics, pSelf->Storage(), pSelf->m_pConsole, pSelf->Graphics()->ScreenWidth(), pSelf->Graphics()->ScreenHeight(), pVideoName); + new CVideo((CGraphics_Threaded *)pSelf->m_pGraphics, pSelf->Storage(), pSelf->m_pConsole, pSelf->Graphics()->ScreenWidth(), pSelf->Graphics()->ScreenHeight(), pVideoName); IVideo::Current()->Start(); } else @@ -3535,7 +3527,7 @@ void CClient::StartVideo(IConsole::IResult *pResult, void *pUserData, const char void CClient::Con_StopVideo(IConsole::IResult *pResult, void *pUserData) { - if (IVideo::Current()) + if(IVideo::Current()) IVideo::Current()->Stop(); } @@ -3653,7 +3645,6 @@ void CClient::SaveReplay(const int Length) // And we restart the recorder DemoRecorder_StartReplayRecorder(); } - } void CClient::DemoSlice(const char *pDstPath, CLIENTFUNC_FILTER pfnFilter, void *pUser) @@ -3908,7 +3899,7 @@ void CClient::ConchainWindowScreen(IConsole::IResult *pResult, void *pUserData, void CClient::ToggleFullscreen() { - if(Graphics()->Fullscreen(g_Config.m_GfxFullscreen^1)) + if(Graphics()->Fullscreen(g_Config.m_GfxFullscreen ^ 1)) g_Config.m_GfxFullscreen ^= 1; } @@ -3944,7 +3935,7 @@ void CClient::ConchainWindowBordered(IConsole::IResult *pResult, void *pUserData void CClient::ToggleWindowVSync() { - if(Graphics()->SetVSync(g_Config.m_GfxVsync^1)) + if(Graphics()->SetVSync(g_Config.m_GfxVsync ^ 1)) g_Config.m_GfxVsync ^= 1; } @@ -4061,9 +4052,9 @@ void CClient::RegisterCommands() m_pConsole->Register("dummy_connect", "", CFGFLAG_CLIENT, Con_DummyConnect, this, "connect dummy"); m_pConsole->Register("dummy_disconnect", "", CFGFLAG_CLIENT, Con_DummyDisconnect, this, "disconnect dummy"); - m_pConsole->Register("quit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); - m_pConsole->Register("exit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); - m_pConsole->Register("minimize", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Minimize, this, "Minimize Teeworlds"); + m_pConsole->Register("quit", "", CFGFLAG_CLIENT | CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); + m_pConsole->Register("exit", "", CFGFLAG_CLIENT | CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); + m_pConsole->Register("minimize", "", CFGFLAG_CLIENT | CFGFLAG_STORE, Con_Minimize, this, "Minimize Teeworlds"); m_pConsole->Register("connect", "s[host|ip]", CFGFLAG_CLIENT, Con_Connect, this, "Connect to the specified host/ip"); m_pConsole->Register("disconnect", "", CFGFLAG_CLIENT, Con_Disconnect, this, "Disconnect from the server"); m_pConsole->Register("ping", "", CFGFLAG_CLIENT, Con_Ping, this, "Ping the current server"); @@ -4077,7 +4068,7 @@ void CClient::RegisterCommands() m_pConsole->Register("rcon", "r[rcon-command]", CFGFLAG_CLIENT, Con_Rcon, this, "Send specified command to rcon"); m_pConsole->Register("rcon_auth", "s[password]", CFGFLAG_CLIENT, Con_RconAuth, this, "Authenticate to rcon"); m_pConsole->Register("rcon_login", "s[username] r[password]", CFGFLAG_CLIENT, Con_RconLogin, this, "Authenticate to rcon with a username"); - m_pConsole->Register("play", "r[file]", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Play, this, "Play the file specified"); + m_pConsole->Register("play", "r[file]", CFGFLAG_CLIENT | CFGFLAG_STORE, Con_Play, this, "Play the file specified"); m_pConsole->Register("record", "?s[file]", CFGFLAG_CLIENT, Con_Record, this, "Record to the file"); m_pConsole->Register("stoprecord", "", CFGFLAG_CLIENT, Con_StopRecord, this, "Stop recording"); m_pConsole->Register("add_demomarker", "", CFGFLAG_CLIENT, Con_AddDemoMarker, this, "Add demo timeline marker"); @@ -4107,9 +4098,8 @@ void CClient::RegisterCommands() // DDRace - - #define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, 0, 0, help); - #include +#define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, 0, 0, help); +#include } static CClient *CreateClient() @@ -4210,19 +4200,19 @@ int main(int argc, const char **argv) // ignore_convention RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineSound); // IEngineSound - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineSound), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineSound), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineInput); // IEngineInput - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineInput), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineInput), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineTextRender); // IEngineTextRender - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineTextRender), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineTextRender), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineMap); // IEngineMap - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineMasterServer); // IEngineMasterServer - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateEditor(), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateGameClient(), false); @@ -4290,7 +4280,7 @@ int main(int argc, const char **argv) // ignore_convention else if(argc == 2 && str_endswith(argv[1], ".map")) pClient->HandleMapPath(argv[1]); else if(argc > 1) // ignore_convention - pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + pConsole->ParseArguments(argc - 1, &argv[1]); // ignore_convention if(pSteam->GetConnectAddress()) { @@ -4368,7 +4358,6 @@ bool CClient::RaceRecord_IsRecording() return m_DemoRecorder[RECORDER_RACE].IsRecording(); } - void CClient::RequestDDNetInfo() { char aUrl[256]; @@ -4393,7 +4382,7 @@ void CClient::RequestDDNetInfo() int CClient::GetPredictionTime() { int64 Now = time_get(); - return (int)((m_PredictedTime.Get(Now)-m_GameTime[g_Config.m_ClDummy].Get(Now))*1000/(float)time_freq()); + return (int)((m_PredictedTime.Get(Now) - m_GameTime[g_Config.m_ClDummy].Get(Now)) * 1000 / (float)time_freq()); } void CClient::GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount) @@ -4402,6 +4391,6 @@ void CClient::GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float Mix int64 PredTime = m_PredictedTime.Get(time_get()); int64 SmoothTime = clamp(GameTime + (int64)(MixAmount * (PredTime - GameTime)), GameTime, PredTime); - *pSmoothTick = (int)(SmoothTime*50/time_freq())+1; - *pSmoothIntraTick = (SmoothTime - (*pSmoothTick-1)*time_freq()/50) / (float)(time_freq()/50); + *pSmoothTick = (int)(SmoothTime * 50 / time_freq()) + 1; + *pSmoothIntraTick = (SmoothTime - (*pSmoothTick - 1) * time_freq() / 50) / (float)(time_freq() / 50); } diff --git a/src/engine/client/client.h b/src/engine/client/client.h index ca7247bad..4b1d289ca 100644 --- a/src/engine/client/client.h +++ b/src/engine/client/client.h @@ -18,7 +18,7 @@ public: enum { // restrictions: Must be power of two - MAX_VALUES=128, + MAX_VALUES = 128, }; float m_Min, m_Max; @@ -35,7 +35,6 @@ public: void Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription); }; - class CSmoothTime { int64 m_Snap; @@ -81,8 +80,8 @@ class CClient : public IClient, public CDemoPlayer::IListener enum { - NUM_SNAPSHOT_TYPES=2, - PREDICTION_MARGIN=1000/50/2, // magic network prediction value + NUM_SNAPSHOT_TYPES = 2, + PREDICTION_MARGIN = 1000 / 50 / 2, // magic network prediction value }; enum @@ -135,7 +134,7 @@ class CClient : public IClient, public CDemoPlayer::IListener int m_UseTempRconCommands; char m_Password[32]; bool m_SendPassword; - bool m_ButtonRender=false; + bool m_ButtonRender = false; // version-checking char m_aVersionStr[10]; @@ -228,7 +227,7 @@ class CClient : public IClient, public CDemoPlayer::IListener { enum { - STATE_INIT=0, + STATE_INIT = 0, STATE_START, STATE_READY, }; @@ -238,7 +237,7 @@ class CClient : public IClient, public CDemoPlayer::IListener } m_VersionInfo; volatile int m_GfxState; - static void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); } + static void GraphicsThreadProxy(void *pThis) { ((CClient *)pThis)->GraphicsThread(); } void GraphicsThread(); #if defined(CONF_FAMILY_UNIX) @@ -260,7 +259,7 @@ public: // ----- send functions ----- virtual int SendMsg(CMsgPacker *pMsg, int Flags); - virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient=1); + virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient = 1); void SendInfo(); void SendEnterGame(); @@ -465,7 +464,7 @@ public: bool EditorHasUnsavedData() { return m_pEditor->HasUnsavedData(); } - virtual IFriends* Foes() { return &m_Foes; } + virtual IFriends *Foes() { return &m_Foes; } void GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount); }; diff --git a/src/engine/client/demoedit.cpp b/src/engine/client/demoedit.cpp index 92932f3fe..a65b2d4c9 100644 --- a/src/engine/client/demoedit.cpp +++ b/src/engine/client/demoedit.cpp @@ -1,5 +1,5 @@ -#include #include "demoedit.h" +#include CDemoEdit::CDemoEdit(const char *pNetVersion, class CSnapshotDelta *pSnapshotDelta, IStorage *pStorage, const char *pDemo, const char *pDst, int StartTick, int EndTick) : m_SnapshotDelta(*pSnapshotDelta), diff --git a/src/engine/client/friends.cpp b/src/engine/client/friends.cpp index 4836323a6..ca07aee11 100644 --- a/src/engine/client/friends.cpp +++ b/src/engine/client/friends.cpp @@ -62,7 +62,7 @@ void CFriends::Init(bool Foes) const CFriendInfo *CFriends::GetFriend(int Index) const { - return &m_aFriends[maximum(0, Index%m_NumFriends)]; + return &m_aFriends[maximum(0, Index % m_NumFriends)]; } int CFriends::GetFriendState(const char *pName, const char *pClan) const @@ -139,7 +139,7 @@ void CFriends::RemoveFriend(int Index) { if(Index >= 0 && Index < m_NumFriends) { - mem_move(&m_aFriends[Index], &m_aFriends[Index+1], sizeof(CFriendInfo)*(m_NumFriends-(Index+1))); + mem_move(&m_aFriends[Index], &m_aFriends[Index + 1], sizeof(CFriendInfo) * (m_NumFriends - (Index + 1))); --m_NumFriends; } } @@ -153,7 +153,7 @@ void CFriends::Friends() for(int i = 0; i < m_NumFriends; ++i) { str_format(aBuf, sizeof(aBuf), "Name: %s, Clan: %s", m_aFriends[i].m_aName, m_aFriends[i].m_aClan); - pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_Foes?"foes":"friends", aBuf, true); + pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_Foes ? "foes" : "friends", aBuf, true); } } } @@ -162,7 +162,7 @@ void CFriends::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CFriends *pSelf = (CFriends *)pUserData; char aBuf[128]; - const char *pEnd = aBuf+sizeof(aBuf)-4; + const char *pEnd = aBuf + sizeof(aBuf) - 4; for(int i = 0; i < pSelf->m_NumFriends; ++i) { str_copy(aBuf, pSelf->m_Foes ? "add_foe " : "add_friend ", sizeof(aBuf)); diff --git a/src/engine/client/graphics_threaded.cpp b/src/engine/client/graphics_threaded.cpp index a8478ddcb..d74d4c4ef 100644 --- a/src/engine/client/graphics_threaded.cpp +++ b/src/engine/client/graphics_threaded.cpp @@ -13,44 +13,43 @@ #include -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include // cosf, sinf, log2f #if defined(CONF_VIDEORECORDER) - #include "video.h" +#include "video.h" #endif #include "graphics_threaded.h" static CVideoMode g_aFakeModes[] = { - {320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8}, - {720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8}, - {1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8}, - {1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8}, - {1280,1024,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8}, - {1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,1000,8,8,8}, - {1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8}, - {1800,1440,8,8,8}, {1856,1392,8,8,8}, {1920,1080,8,8,8}, - {1920,1200,8,8,8}, {1920,1440,8,8,8}, {1920,2400,8,8,8}, - {2048,1536,8,8,8}, + {320, 240, 8, 8, 8}, {400, 300, 8, 8, 8}, {640, 480, 8, 8, 8}, + {720, 400, 8, 8, 8}, {768, 576, 8, 8, 8}, {800, 600, 8, 8, 8}, + {1024, 600, 8, 8, 8}, {1024, 768, 8, 8, 8}, {1152, 864, 8, 8, 8}, + {1280, 768, 8, 8, 8}, {1280, 800, 8, 8, 8}, {1280, 960, 8, 8, 8}, + {1280, 1024, 8, 8, 8}, {1368, 768, 8, 8, 8}, {1400, 1050, 8, 8, 8}, + {1440, 900, 8, 8, 8}, {1440, 1050, 8, 8, 8}, {1600, 1000, 8, 8, 8}, + {1600, 1200, 8, 8, 8}, {1680, 1050, 8, 8, 8}, {1792, 1344, 8, 8, 8}, + {1800, 1440, 8, 8, 8}, {1856, 1392, 8, 8, 8}, {1920, 1080, 8, 8, 8}, + {1920, 1200, 8, 8, 8}, {1920, 1440, 8, 8, 8}, {1920, 2400, 8, 8, 8}, + {2048, 1536, 8, 8, 8}, - {320,240,5,6,5}, {400,300,5,6,5}, {640,480,5,6,5}, - {720,400,5,6,5}, {768,576,5,6,5}, {800,600,5,6,5}, - {1024,600,5,6,5}, {1024,768,5,6,5}, {1152,864,5,6,5}, - {1280,768,5,6,5}, {1280,800,5,6,5}, {1280,960,5,6,5}, - {1280,1024,5,6,5}, {1368,768,5,6,5}, {1400,1050,5,6,5}, - {1440,900,5,6,5}, {1440,1050,5,6,5}, {1600,1000,5,6,5}, - {1600,1200,5,6,5}, {1680,1050,5,6,5}, {1792,1344,5,6,5}, - {1800,1440,5,6,5}, {1856,1392,5,6,5}, {1920,1080,5,6,5}, - {1920,1200,5,6,5}, {1920,1440,5,6,5}, {1920,2400,5,6,5}, - {2048,1536,5,6,5} -}; + {320, 240, 5, 6, 5}, {400, 300, 5, 6, 5}, {640, 480, 5, 6, 5}, + {720, 400, 5, 6, 5}, {768, 576, 5, 6, 5}, {800, 600, 5, 6, 5}, + {1024, 600, 5, 6, 5}, {1024, 768, 5, 6, 5}, {1152, 864, 5, 6, 5}, + {1280, 768, 5, 6, 5}, {1280, 800, 5, 6, 5}, {1280, 960, 5, 6, 5}, + {1280, 1024, 5, 6, 5}, {1368, 768, 5, 6, 5}, {1400, 1050, 5, 6, 5}, + {1440, 900, 5, 6, 5}, {1440, 1050, 5, 6, 5}, {1600, 1000, 5, 6, 5}, + {1600, 1200, 5, 6, 5}, {1680, 1050, 5, 6, 5}, {1792, 1344, 5, 6, 5}, + {1800, 1440, 5, 6, 5}, {1856, 1392, 5, 6, 5}, {1920, 1080, 5, 6, 5}, + {1920, 1200, 5, 6, 5}, {1920, 1440, 5, 6, 5}, {1920, 2400, 5, 6, 5}, + {2048, 1536, 5, 6, 5}}; void CGraphics_Threaded::FlushVertices(bool KeepVertices) { @@ -65,7 +64,7 @@ void CGraphics_Threaded::FlushVertices(bool KeepVertices) } } -void CGraphics_Threaded::FlushTextVertices(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float* pOutlineTextColor) +void CGraphics_Threaded::FlushTextVertices(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float *pOutlineTextColor) { CCommandBuffer::SCommand_RenderTextStream Cmd; int PrimType, PrimCount, NumVerts; @@ -158,12 +157,12 @@ void CGraphics_Threaded::ClipEnable(int x, int y, int w, int h) x = clamp(x, 0, ScreenWidth()); y = clamp(y, 0, ScreenHeight()); - w = clamp(w, 0, ScreenWidth()-x); - h = clamp(h, 0, ScreenHeight()-y); + w = clamp(w, 0, ScreenWidth() - x); + h = clamp(h, 0, ScreenHeight() - y); m_State.m_ClipEnable = true; m_State.m_ClipX = x; - m_State.m_ClipY = ScreenHeight()-(y+h); + m_State.m_ClipY = ScreenHeight() - (y + h); m_State.m_ClipW = w; m_State.m_ClipH = h; } @@ -223,7 +222,7 @@ void CGraphics_Threaded::LinesBegin() { dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice"); m_Drawing = DRAWING_LINES; - SetColor(1,1,1,1); + SetColor(1, 1, 1, 1); } void CGraphics_Threaded::LinesEnd() @@ -239,18 +238,18 @@ void CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num) for(int i = 0; i < Num; ++i) { - m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0; - m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0; - m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0]; - SetColor(&m_aVertices[m_NumVertices + 2*i], 0); + m_aVertices[m_NumVertices + 2 * i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 2 * i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 2 * i].m_Tex = m_aTexture[0]; + SetColor(&m_aVertices[m_NumVertices + 2 * i], 0); - m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1; - m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1; - m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1]; - SetColor(&m_aVertices[m_NumVertices + 2*i + 1], 1); + m_aVertices[m_NumVertices + 2 * i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 2 * i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 2 * i + 1].m_Tex = m_aTexture[1]; + SetColor(&m_aVertices[m_NumVertices + 2 * i + 1], 1); } - AddVertices(2*Num); + AddVertices(2 * Num); } int CGraphics_Threaded::UnloadTexture(CTextureHandle Index) @@ -272,9 +271,12 @@ int CGraphics_Threaded::UnloadTexture(CTextureHandle Index) static int ImageFormatToTexFormat(int Format) { - if(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB; - if(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA; - if(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA; + if(Format == CImageInfo::FORMAT_RGB) + return CCommandBuffer::TEXFORMAT_RGB; + if(Format == CImageInfo::FORMAT_RGBA) + return CCommandBuffer::TEXFORMAT_RGBA; + if(Format == CImageInfo::FORMAT_ALPHA) + return CCommandBuffer::TEXFORMAT_ALPHA; return CCommandBuffer::TEXFORMAT_RGBA; } @@ -288,7 +290,6 @@ static int ImageFormatToPixelSize(int Format) } } - int CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData) { CCommandBuffer::SCommand_Texture_Update Cmd; @@ -300,7 +301,7 @@ int CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y Cmd.m_Format = ImageFormatToTexFormat(Format); // calculate memory usage - int MemSize = Width*Height*ImageFormatToPixelSize(Format); + int MemSize = Width * Height * ImageFormatToPixelSize(Format); // copy texture data void *pTmpData = malloc(MemSize); @@ -360,25 +361,25 @@ IGraphics::CTextureHandle CGraphics_Threaded::LoadTextureRaw(int Width, int Heig // flags Cmd.m_Flags = 0; - if(Flags&IGraphics::TEXLOAD_NOMIPMAPS) + if(Flags & IGraphics::TEXLOAD_NOMIPMAPS) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS; if(g_Config.m_GfxTextureCompressionOld && ((Flags & IGraphics::TEXLOAD_NO_COMPRESSION) == 0)) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_COMPRESSED; if(g_Config.m_GfxTextureQualityOld || Flags & TEXLOAD_NORESAMPLE) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_QUALITY; - if((Flags&IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE) != 0) + if((Flags & IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE) != 0) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE; - if((Flags&IGraphics::TEXLOAD_TO_3D_TEXTURE) != 0) + if((Flags & IGraphics::TEXLOAD_TO_3D_TEXTURE) != 0) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_3D_TEXTURE; - if((Flags&IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0) + if((Flags & IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER; - if((Flags&IGraphics::TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER) != 0) + if((Flags & IGraphics::TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER) != 0) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_3D_TEXTURE_SINGLE_LAYER; - if((Flags&IGraphics::TEXLOAD_NO_2D_TEXTURE) != 0) + if((Flags & IGraphics::TEXLOAD_NO_2D_TEXTURE) != 0) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NO_2D_TEXTURE; // copy texture data - int MemSize = Width*Height*Cmd.m_PixelSize; + int MemSize = Width * Height * Cmd.m_PixelSize; void *pTmpData = malloc(MemSize); mem_copy(pTmpData, pData, MemSize); Cmd.m_pData = pTmpData; @@ -425,7 +426,7 @@ int CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int Sto png_t Png; // ignore_convention // open file for reading - png_init(0,0); // ignore_convention + png_init(0, 0); // ignore_convention IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename)); if(File) @@ -560,7 +561,7 @@ void CGraphics_Threaded::TextQuadsBegin() QuadsBegin(); } -void CGraphics_Threaded::TextQuadsEnd(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float* pOutlineTextColor) +void CGraphics_Threaded::TextQuadsEnd(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float *pOutlineTextColor) { dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->TextQuadsEnd without begin"); FlushTextVertices(TextureSize, TextTextureIndex, TextOutlineTextureIndex, pOutlineTextColor); @@ -598,10 +599,12 @@ void CGraphics_Threaded::QuadsSetRotation(float Angle) m_Rotation = Angle; } -inline void clampf(float& Value, float Min, float Max) +inline void clampf(float &Value, float Min, float Max) { - if(Value > Max) Value = Max; - else if(Value < Min) Value = Min; + if(Value > Max) + Value = Max; + else if(Value < Min) + Value = Min; } void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num) @@ -615,10 +618,10 @@ void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num) clampf(g, 0.f, 1.f); clampf(b, 0.f, 1.f); clampf(a, 0.f, 1.f); - m_aColor[pArray[i].m_Index].r = (unsigned char)(r*255.f); - m_aColor[pArray[i].m_Index].g = (unsigned char)(g*255.f); - m_aColor[pArray[i].m_Index].b = (unsigned char)(b*255.f); - m_aColor[pArray[i].m_Index].a = (unsigned char)(a*255.f); + m_aColor[pArray[i].m_Index].r = (unsigned char)(r * 255.f); + m_aColor[pArray[i].m_Index].g = (unsigned char)(g * 255.f); + m_aColor[pArray[i].m_Index].b = (unsigned char)(b * 255.f); + m_aColor[pArray[i].m_Index].a = (unsigned char)(a * 255.f); } } @@ -664,10 +667,10 @@ void CGraphics_Threaded::ChangeColorOfCurrentQuadVertices(float r, float g, floa clampf(g, 0.f, 1.f); clampf(b, 0.f, 1.f); clampf(a, 0.f, 1.f); - m_aColor[0].r = (unsigned char)(r*255.f); - m_aColor[0].g = (unsigned char)(g*255.f); - m_aColor[0].b = (unsigned char)(b*255.f); - m_aColor[0].a = (unsigned char)(a*255.f); + m_aColor[0].r = (unsigned char)(r * 255.f); + m_aColor[0].g = (unsigned char)(g * 255.f); + m_aColor[0].b = (unsigned char)(b * 255.f); + m_aColor[0].a = (unsigned char)(a * 255.f); for(int i = 0; i < m_NumVertices; ++i) { @@ -735,11 +738,15 @@ void CGraphics_Threaded::ChangeColorOfQuadVertices(int QuadOffset, unsigned char void CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV) { - m_aTexture[0].u = TlU; m_aTexture[1].u = BrU; - m_aTexture[0].v = TlV; m_aTexture[1].v = TlV; + m_aTexture[0].u = TlU; + m_aTexture[1].u = BrU; + m_aTexture[0].v = TlV; + m_aTexture[1].v = TlV; - m_aTexture[3].u = TlU; m_aTexture[2].u = BrU; - m_aTexture[3].v = BrV; m_aTexture[2].v = BrV; + m_aTexture[3].u = TlU; + m_aTexture[2].u = BrU; + m_aTexture[3].v = BrV; + m_aTexture[2].v = BrV; } void CGraphics_Threaded::QuadsSetSubsetFree( @@ -761,8 +768,8 @@ void CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num) { for(int i = 0; i < Num; ++i) { - pArray[i].m_X -= pArray[i].m_Width/2; - pArray[i].m_Y -= pArray[i].m_Height/2; + pArray[i].m_X -= pArray[i].m_Width / 2; + pArray[i].m_Y -= pArray[i].m_Height / 2; } QuadsDrawTL(pArray, Num); @@ -809,65 +816,65 @@ void CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) { for(int i = 0; i < Num; ++i) { - m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X0; - m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y0; - m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0]; - SetColor(&m_aVertices[m_NumVertices + 6*i], 0); + m_aVertices[m_NumVertices + 6 * i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6 * i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6 * i].m_Tex = m_aTexture[0]; + SetColor(&m_aVertices[m_NumVertices + 6 * i], 0); - m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X1; - m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y1; - m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1]; - SetColor(&m_aVertices[m_NumVertices + 6*i + 1], 1); + m_aVertices[m_NumVertices + 6 * i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 6 * i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 6 * i + 1].m_Tex = m_aTexture[1]; + SetColor(&m_aVertices[m_NumVertices + 6 * i + 1], 1); - m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X3; - m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y3; - m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[3]; - SetColor(&m_aVertices[m_NumVertices + 6*i + 2], 3); + m_aVertices[m_NumVertices + 6 * i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6 * i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6 * i + 2].m_Tex = m_aTexture[3]; + SetColor(&m_aVertices[m_NumVertices + 6 * i + 2], 3); - m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X0; - m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y0; - m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0]; - SetColor(&m_aVertices[m_NumVertices + 6*i + 3], 0); + m_aVertices[m_NumVertices + 6 * i + 3].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6 * i + 3].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6 * i + 3].m_Tex = m_aTexture[0]; + SetColor(&m_aVertices[m_NumVertices + 6 * i + 3], 0); - m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X3; - m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y3; - m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[3]; - SetColor(&m_aVertices[m_NumVertices + 6*i + 4], 3); + m_aVertices[m_NumVertices + 6 * i + 4].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6 * i + 4].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6 * i + 4].m_Tex = m_aTexture[3]; + SetColor(&m_aVertices[m_NumVertices + 6 * i + 4], 3); - m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X2; - m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y2; - m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[2]; - SetColor(&m_aVertices[m_NumVertices + 6*i + 5], 2); + m_aVertices[m_NumVertices + 6 * i + 5].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 6 * i + 5].m_Pos.y = pArray[i].m_Y2; + m_aVertices[m_NumVertices + 6 * i + 5].m_Tex = m_aTexture[2]; + SetColor(&m_aVertices[m_NumVertices + 6 * i + 5], 2); } - AddVertices(3*2*Num); + AddVertices(3 * 2 * Num); } else { for(int i = 0; i < Num; ++i) { - m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0; - m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0; - m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; - SetColor(&m_aVertices[m_NumVertices + 4*i], 0); + m_aVertices[m_NumVertices + 4 * i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 4 * i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 4 * i].m_Tex = m_aTexture[0]; + SetColor(&m_aVertices[m_NumVertices + 4 * i], 0); - m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1; - m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1; - m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; - SetColor(&m_aVertices[m_NumVertices + 4*i + 1], 1); + m_aVertices[m_NumVertices + 4 * i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 4 * i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 4 * i + 1].m_Tex = m_aTexture[1]; + SetColor(&m_aVertices[m_NumVertices + 4 * i + 1], 1); - m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3; - m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3; - m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3]; - SetColor(&m_aVertices[m_NumVertices + 4*i + 2], 3); + m_aVertices[m_NumVertices + 4 * i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 4 * i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 4 * i + 2].m_Tex = m_aTexture[3]; + SetColor(&m_aVertices[m_NumVertices + 4 * i + 2], 3); - m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2; - m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2; - m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2]; - SetColor(&m_aVertices[m_NumVertices + 4*i + 3], 2); + m_aVertices[m_NumVertices + 4 * i + 3].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 4 * i + 3].m_Pos.y = pArray[i].m_Y2; + m_aVertices[m_NumVertices + 4 * i + 3].m_Tex = m_aTexture[2]; + SetColor(&m_aVertices[m_NumVertices + 4 * i + 3], 2); } - AddVertices(4*Num); + AddVertices(4 * Num); } } @@ -888,19 +895,19 @@ void CGraphics_Threaded::QuadsText(float x, float y, float Size, const char *pTe else { QuadsSetSubset( - (c%16)/16.0f, - (c/16)/16.0f, - (c%16)/16.0f+1.0f/16.0f, - (c/16)/16.0f+1.0f/16.0f); + (c % 16) / 16.0f, + (c / 16) / 16.0f, + (c % 16) / 16.0f + 1.0f / 16.0f, + (c / 16) / 16.0f + 1.0f / 16.0f); CQuadItem QuadItem(x, y, Size, Size); QuadsDrawTL(&QuadItem, 1); - x += Size/2; + x += Size / 2; } } } -void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor, char** pOffsets, unsigned int *IndicedVertexDrawNum, size_t NumIndicesOffet) +void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor, char **pOffsets, unsigned int *IndicedVertexDrawNum, size_t NumIndicesOffet) { if(NumIndicesOffet == 0) return; @@ -912,21 +919,21 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor Cmd.m_BufferContainerIndex = BufferContainerIndex; mem_copy(&Cmd.m_Color, pColor, sizeof(Cmd.m_Color)); - void *Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet); + void *Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet); if(Data == 0x0) { // kick command buffer and try again KickCommandBuffer(); - void *Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet); + void *Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet); if(Data == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } } - Cmd.m_pIndicesOffsets = (char**)Data; - Cmd.m_pDrawCount = (unsigned int*)(((char*)Data) + (sizeof(char*)*NumIndicesOffet)); + Cmd.m_pIndicesOffsets = (char **)Data; + Cmd.m_pDrawCount = (unsigned int *)(((char *)Data) + (sizeof(char *) * NumIndicesOffet)); // check if we have enough free memory in the commandbuffer if(!m_pCommandBuffer->AddCommand(Cmd)) @@ -934,14 +941,14 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor // kick command buffer and try again KickCommandBuffer(); - Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet); + Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet); if(Data == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } - Cmd.m_pIndicesOffsets = (char**)Data; - Cmd.m_pDrawCount = (unsigned int*)(((char*)Data) + (sizeof(char*)*NumIndicesOffet)); + Cmd.m_pIndicesOffsets = (char **)Data; + Cmd.m_pDrawCount = (unsigned int *)(((char *)Data) + (sizeof(char *) * NumIndicesOffet)); if(!m_pCommandBuffer->AddCommand(Cmd)) { @@ -950,9 +957,8 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor } } - - mem_copy(Cmd.m_pIndicesOffsets, pOffsets, sizeof(char*)*NumIndicesOffet); - mem_copy(Cmd.m_pDrawCount, IndicedVertexDrawNum, sizeof(unsigned int)*NumIndicesOffet); + mem_copy(Cmd.m_pIndicesOffsets, pOffsets, sizeof(char *) * NumIndicesOffet); + mem_copy(Cmd.m_pDrawCount, IndicedVertexDrawNum, sizeof(unsigned int) * NumIndicesOffet); //todo max indices group check!! } @@ -1023,7 +1029,7 @@ void CGraphics_Threaded::RenderBorderTileLines(int BufferContainerIndex, float * } } -void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderInfo* pQuadInfo, int QuadNum) +void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderInfo *pQuadInfo, int QuadNum) { if(QuadNum == 0) return; @@ -1034,7 +1040,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn Cmd.m_QuadNum = QuadNum; Cmd.m_BufferContainerIndex = BufferContainerIndex; - Cmd.m_pQuadInfo = (SQuadRenderInfo*)AllocCommandBufferData(QuadNum * sizeof(SQuadRenderInfo)); + Cmd.m_pQuadInfo = (SQuadRenderInfo *)AllocCommandBufferData(QuadNum * sizeof(SQuadRenderInfo)); if(Cmd.m_pQuadInfo == 0x0) return; @@ -1044,7 +1050,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn // kick command buffer and try again KickCommandBuffer(); - Cmd.m_pQuadInfo = (SQuadRenderInfo*)m_pCommandBuffer->AllocData(QuadNum * sizeof(SQuadRenderInfo)); + Cmd.m_pQuadInfo = (SQuadRenderInfo *)m_pCommandBuffer->AllocData(QuadNum * sizeof(SQuadRenderInfo)); if(Cmd.m_pQuadInfo == 0x0) { dbg_msg("graphics", "failed to allocate data for the quad info"); @@ -1061,7 +1067,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn mem_copy(Cmd.m_pQuadInfo, pQuadInfo, sizeof(SQuadRenderInfo) * QuadNum); } -void CGraphics_Threaded::RenderText(int BufferContainerIndex, int TextQuadNum, int TextureSize, int TextureTextIndex, int TextureTextOutlineIndex, float* pTextColor, float* pTextoutlineColor) +void CGraphics_Threaded::RenderText(int BufferContainerIndex, int TextQuadNum, int TextureSize, int TextureTextIndex, int TextureTextOutlineIndex, float *pTextColor, float *pTextoutlineColor) { if(BufferContainerIndex == -1) return; @@ -1112,7 +1118,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex) { if(IsQuadContainerBufferingEnabled()) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if(Container.m_Quads.size() > 0) { if(Container.m_QuadBufferObjectIndex == -1) @@ -1132,7 +1138,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex) Info.m_Stride = sizeof(CCommandBuffer::SVertex); Info.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); - SBufferContainerInfo::SAttribute* pAttr = &Info.m_Attributes.back(); + SBufferContainerInfo::SAttribute *pAttr = &Info.m_Attributes.back(); pAttr->m_DataTypeCount = 2; pAttr->m_FuncType = 0; pAttr->m_Normalized = false; @@ -1144,7 +1150,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex) pAttr->m_DataTypeCount = 2; pAttr->m_FuncType = 0; pAttr->m_Normalized = false; - pAttr->m_pOffset = (void*)(sizeof(float) * 2); + pAttr->m_pOffset = (void *)(sizeof(float) * 2); pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_VertBufferBindingIndex = Container.m_QuadBufferObjectIndex; Info.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); @@ -1152,7 +1158,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex) pAttr->m_DataTypeCount = 4; pAttr->m_FuncType = 0; pAttr->m_Normalized = true; - pAttr->m_pOffset = (void*)(sizeof(float) * 2 + sizeof(float) * 2); + pAttr->m_pOffset = (void *)(sizeof(float) * 2 + sizeof(float) * 2); pAttr->m_Type = GRAPHICS_TYPE_UNSIGNED_BYTE; pAttr->m_VertBufferBindingIndex = Container.m_QuadBufferObjectIndex; @@ -1164,7 +1170,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex) void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pArray, int Num) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if((int)Container.m_Quads.size() > Num + CCommandBuffer::MAX_VERTICES) return; @@ -1172,7 +1178,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pA for(int i = 0; i < Num; ++i) { Container.m_Quads.push_back(SQuadContainer::SQuad()); - SQuadContainer::SQuad& Quad = Container.m_Quads.back(); + SQuadContainer::SQuad &Quad = Container.m_Quads.back(); Quad.m_aVertices[0].m_Pos.x = pArray[i].m_X; Quad.m_aVertices[0].m_Pos.y = pArray[i].m_Y; @@ -1209,7 +1215,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pA void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem *pArray, int Num) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if((int)Container.m_Quads.size() > Num + CCommandBuffer::MAX_VERTICES) return; @@ -1217,7 +1223,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem for(int i = 0; i < Num; ++i) { Container.m_Quads.push_back(SQuadContainer::SQuad()); - SQuadContainer::SQuad& Quad = Container.m_Quads.back(); + SQuadContainer::SQuad &Quad = Container.m_Quads.back(); Quad.m_aVertices[0].m_Pos.x = pArray[i].m_X0; Quad.m_aVertices[0].m_Pos.y = pArray[i].m_Y0; @@ -1245,7 +1251,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem void CGraphics_Threaded::QuadContainerReset(int ContainerIndex) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if(IsQuadContainerBufferingEnabled()) { if(Container.m_QuadBufferContainerIndex != -1) @@ -1271,7 +1277,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadDrawNum void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset, int QuadDrawNum) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if(QuadDrawNum == -1) QuadDrawNum = (int)Container.m_Quads.size() - QuadOffset; @@ -1287,7 +1293,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset, CCommandBuffer::SCommand_RenderQuadContainer Cmd; Cmd.m_State = m_State; Cmd.m_DrawNum = (unsigned int)QuadDrawNum * 6; - Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int)); + Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int)); Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex; // check if we have enough free memory in the commandbuffer @@ -1309,7 +1315,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset, { for(int i = 0; i < QuadDrawNum; ++i) { - SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset + i]; + SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset + i]; m_aVertices[i * 6] = Quad.m_aVertices[0]; m_aVertices[i * 6 + 1] = Quad.m_aVertices[1]; m_aVertices[i * 6 + 2] = Quad.m_aVertices[2]; @@ -1332,7 +1338,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset, void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int QuadOffset, float X, float Y, float ScaleX, float ScaleY) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if((int)Container.m_Quads.size() < QuadOffset + 1) return; @@ -1342,7 +1348,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua if(Container.m_QuadBufferContainerIndex == -1) return; - SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset]; + SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset]; CCommandBuffer::SCommand_RenderQuadContainerAsSprite Cmd; float ScreenX0, ScreenY0, ScreenX1, ScreenY1; @@ -1352,7 +1358,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); Cmd.m_DrawNum = 1 * 6; - Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int)); + Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int)); Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex; Cmd.m_VertexColor.r = (float)m_aColor[0].r / 255.f; @@ -1383,7 +1389,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua { if(g_Config.m_GfxQuadAsTriangle) { - SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset]; + SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset]; m_aVertices[0] = Quad.m_aVertices[0]; m_aVertices[1] = Quad.m_aVertices[1]; m_aVertices[2] = Quad.m_aVertices[2]; @@ -1458,7 +1464,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex, int QuadOffset, int DrawCount, SRenderSpriteInfo *pRenderInfo) { - SQuadContainer& Container = m_QuadContainers[ContainerIndex]; + SQuadContainer &Container = m_QuadContainers[ContainerIndex]; if(DrawCount == 0) return; @@ -1468,14 +1474,14 @@ void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex, if(Container.m_QuadBufferContainerIndex == -1) return; - SQuadContainer::SQuad& Quad = Container.m_Quads[0]; + SQuadContainer::SQuad &Quad = Container.m_Quads[0]; CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple Cmd; Cmd.m_State = m_State; Cmd.m_DrawNum = 1 * 6; Cmd.m_DrawCount = DrawCount; - Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int)); + Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int)); Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex; Cmd.m_VertexColor.r = (float)m_aColor[0].r / 255.f; @@ -1533,9 +1539,9 @@ void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex, } } -void* CGraphics_Threaded::AllocCommandBufferData(unsigned AllocSize) +void *CGraphics_Threaded::AllocCommandBufferData(unsigned AllocSize) { - void* pData = m_pCommandBuffer->AllocData(AllocSize); + void *pData = m_pCommandBuffer->AllocData(AllocSize); if(pData == 0x0) { // kick command buffer and try again @@ -1597,7 +1603,8 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD } mem_copy(Cmd.m_pUploadData, pUploadData, UploadDataSize); } - else { + else + { Cmd.m_pUploadData = NULL; // check if we have enough free memory in the commandbuffer if(!m_pCommandBuffer->AddCommand(Cmd)) @@ -1613,10 +1620,11 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD // update the buffer instead size_t UploadDataOffset = 0; - while(UploadDataSize > 0) { + while(UploadDataSize > 0) + { size_t UpdateSize = (UploadDataSize > CMD_BUFFER_DATA_BUFFER_SIZE ? CMD_BUFFER_DATA_BUFFER_SIZE : UploadDataSize); - UpdateBufferObject(Index, UpdateSize, (((char*)pUploadData) + UploadDataOffset), (void*)UploadDataOffset); + UpdateBufferObject(Index, UpdateSize, (((char *)pUploadData) + UploadDataOffset), (void *)UploadDataOffset); UploadDataOffset += UpdateSize; UploadDataSize -= UpdateSize; @@ -1626,7 +1634,7 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD return Index; } -void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadDataSize, void* pUploadData) +void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadDataSize, void *pUploadData) { CCommandBuffer::SCommand_RecreateBufferObject Cmd; Cmd.m_BufferIndex = BufferIndex; @@ -1660,7 +1668,8 @@ void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadData mem_copy(Cmd.m_pUploadData, pUploadData, UploadDataSize); } - else { + else + { Cmd.m_pUploadData = NULL; // check if we have enough free memory in the commandbuffer if(!m_pCommandBuffer->AddCommand(Cmd)) @@ -1676,10 +1685,11 @@ void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadData // update the buffer instead size_t UploadDataOffset = 0; - while(UploadDataSize > 0) { + while(UploadDataSize > 0) + { size_t UpdateSize = (UploadDataSize > CMD_BUFFER_DATA_BUFFER_SIZE ? CMD_BUFFER_DATA_BUFFER_SIZE : UploadDataSize); - UpdateBufferObject(BufferIndex, UpdateSize, (((char*)pUploadData) + UploadDataOffset), (void*)UploadDataOffset); + UpdateBufferObject(BufferIndex, UpdateSize, (((char *)pUploadData) + UploadDataOffset), (void *)UploadDataOffset); UploadDataOffset += UpdateSize; UploadDataSize -= UpdateSize; @@ -1790,7 +1800,7 @@ int CGraphics_Threaded::CreateBufferContainer(SBufferContainerInfo *pContainerIn Cmd.m_AttrCount = (int)pContainerInfo->m_Attributes.size(); Cmd.m_Stride = pContainerInfo->m_Stride; - Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); + Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); if(Cmd.m_Attributes == NULL) return -1; @@ -1800,7 +1810,7 @@ int CGraphics_Threaded::CreateBufferContainer(SBufferContainerInfo *pContainerIn // kick command buffer and try again KickCommandBuffer(); - Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); + Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); if(Cmd.m_Attributes == 0x0) { dbg_msg("graphics", "failed to allocate data for upload data"); @@ -1865,7 +1875,6 @@ void CGraphics_Threaded::DeleteBufferContainer(int ContainerIndex, bool DestroyA } m_VertexArrayInfo[ContainerIndex].m_AssociatedBufferObjectIndices.clear(); - // also clear the buffer object index m_VertexArrayInfo[ContainerIndex].m_FreeIndex = m_FirstFreeVertexArrayInfo; m_FirstFreeVertexArrayInfo = ContainerIndex; @@ -1878,7 +1887,7 @@ void CGraphics_Threaded::UpdateBufferContainer(int ContainerIndex, SBufferContai Cmd.m_AttrCount = (int)pContainerInfo->m_Attributes.size(); Cmd.m_Stride = pContainerInfo->m_Stride; - Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); + Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); if(Cmd.m_Attributes == NULL) return; @@ -1888,7 +1897,7 @@ void CGraphics_Threaded::UpdateBufferContainer(int ContainerIndex, SBufferContai // kick command buffer and try again KickCommandBuffer(); - Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); + Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute)); if(Cmd.m_Attributes == 0x0) { dbg_msg("graphics", "failed to allocate data for upload data"); @@ -1932,11 +1941,16 @@ int CGraphics_Threaded::IssueInit() { int Flags = 0; - if(g_Config.m_GfxBorderless) Flags |= IGraphicsBackend::INITFLAG_BORDERLESS; - if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN; - if(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC; - if(g_Config.m_GfxHighdpi) Flags |= IGraphicsBackend::INITFLAG_HIGHDPI; - if(g_Config.m_GfxResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE; + if(g_Config.m_GfxBorderless) + Flags |= IGraphicsBackend::INITFLAG_BORDERLESS; + if(g_Config.m_GfxFullscreen) + Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN; + if(g_Config.m_GfxVsync) + Flags |= IGraphicsBackend::INITFLAG_VSYNC; + if(g_Config.m_GfxHighdpi) + Flags |= IGraphicsBackend::INITFLAG_HIGHDPI; + if(g_Config.m_GfxResizable) + Flags |= IGraphicsBackend::INITFLAG_RESIZABLE; int r = m_pBackend->Init("DDNet Client", &g_Config.m_GfxScreen, &g_Config.m_GfxScreenWidth, &g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags, &m_DesktopScreenWidth, &m_DesktopScreenHeight, &m_ScreenWidth, &m_ScreenHeight, m_pStorage); m_IsNewOpenGL = m_pBackend->IsNewOpenGL(); @@ -2069,9 +2083,9 @@ int CGraphics_Threaded::Init() // init textures m_FirstFreeTexture = 0; - for(int i = 0; i < MAX_TEXTURES-1; i++) - m_aTextureIndices[i] = i+1; - m_aTextureIndices[MAX_TEXTURES-1] = -1; + for(int i = 0; i < MAX_TEXTURES - 1; i++) + m_aTextureIndices[i] = i + 1; + m_aTextureIndices[MAX_TEXTURES - 1] = -1; m_FirstFreeVertexArrayInfo = -1; m_FirstFreeBufferObjectIndex = -1; @@ -2088,12 +2102,12 @@ int CGraphics_Threaded::Init() // create null texture, will get id=0 static const unsigned char s_aNullTextureData[] = { - 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, - 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, - 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, - 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff}; + 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, + 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff}; - m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,s_aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); + m_InvalidTexture = LoadTextureRaw(4, 4, CImageInfo::FORMAT_RGBA, s_aNullTextureData, CImageInfo::FORMAT_RGBA, TEXLOAD_NORESAMPLE); return 0; } @@ -2143,17 +2157,17 @@ bool CGraphics_Threaded::SetWindowScreen(int Index) void CGraphics_Threaded::Resize(int w, int h) { #if defined(CONF_VIDEORECORDER) - if (IVideo::Current() && IVideo::Current()->IsRecording()) + if(IVideo::Current() && IVideo::Current()->IsRecording()) return; #endif if(m_ScreenWidth == w && m_ScreenHeight == h) return; - if(h > 4*w/5) - h = 4*w/5; - if(w > 21*h/9) - w = 21*h/9; + if(h > 4 * w / 5) + h = 4 * w / 5; + if(w > 21 * h / 9) + w = 21 * h / 9; m_ScreenWidth = w; m_ScreenHeight = h; @@ -2206,7 +2220,7 @@ void CGraphics_Threaded::TakeScreenshot(const char *pFilename) // TODO: screenshot support char aDate[20]; str_timestamp(aDate, sizeof(aDate)); - str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate); + str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename ? pFilename : "screenshot", aDate); m_DoScreenshot = true; } @@ -2220,7 +2234,7 @@ void CGraphics_Threaded::Swap() { if(!m_Warnings.empty()) { - SGraphicsWarning* pCurWarning = GetCurWarning(); + SGraphicsWarning *pCurWarning = GetCurWarning(); if(pCurWarning->m_WasShown) { m_Warnings.erase(m_Warnings.begin()); @@ -2286,7 +2300,7 @@ SGraphicsWarning *CGraphics_Threaded::GetCurWarning() return NULL; else { - SGraphicsWarning* pCurWarning = &m_Warnings[0]; + SGraphicsWarning *pCurWarning = &m_Warnings[0]; return pCurWarning; } } @@ -2295,7 +2309,7 @@ int CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes, int Scre { if(g_Config.m_GfxDisplayAllModes) { - int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode); + int Count = sizeof(g_aFakeModes) / sizeof(CVideoMode); mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes)); if(MaxModes < Count) Count = MaxModes; diff --git a/src/engine/client/graphics_threaded.h b/src/engine/client/graphics_threaded.h index e08d570e8..b421ce90a 100644 --- a/src/engine/client/graphics_threaded.h +++ b/src/engine/client/graphics_threaded.h @@ -5,8 +5,8 @@ #include -#define CMD_BUFFER_DATA_BUFFER_SIZE 1024*1024*2 -#define CMD_BUFFER_CMD_BUFFER_SIZE 1024*256 +#define CMD_BUFFER_DATA_BUFFER_SIZE 1024 * 1024 * 2 +#define CMD_BUFFER_CMD_BUFFER_SIZE 1024 * 256 class CCommandBuffer { @@ -15,6 +15,7 @@ class CCommandBuffer unsigned char *m_pData; unsigned m_Size; unsigned m_Used; + public: CBuffer(unsigned BufferSize) { @@ -25,7 +26,7 @@ class CCommandBuffer ~CBuffer() { - delete [] m_pData; + delete[] m_pData; m_pData = 0x0; m_Used = 0; m_Size = 0; @@ -56,8 +57,8 @@ public: enum { - MAX_TEXTURES=1024*4, - MAX_VERTICES=32*1024, + MAX_TEXTURES = 1024 * 4, + MAX_VERTICES = 32 * 1024, }; enum @@ -170,7 +171,8 @@ public: struct SCommand { public: - SCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {} + SCommand(unsigned Cmd) : + m_Cmd(Cmd), m_Size(0) {} unsigned m_Cmd; unsigned m_Size; }; @@ -193,25 +195,29 @@ public: struct SCommand_Clear : public SCommand { - SCommand_Clear() : SCommand(CMD_CLEAR) {} + SCommand_Clear() : + SCommand(CMD_CLEAR) {} SColorf m_Color; }; struct SCommand_Signal : public SCommand { - SCommand_Signal() : SCommand(CMD_SIGNAL) {} + SCommand_Signal() : + SCommand(CMD_SIGNAL) {} semaphore *m_pSemaphore; }; struct SCommand_RunBuffer : public SCommand { - SCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {} + SCommand_RunBuffer() : + SCommand(CMD_RUNBUFFER) {} CCommandBuffer *m_pOtherBuffer; }; struct SCommand_Render : public SCommand { - SCommand_Render() : SCommand(CMD_RENDER) {} + SCommand_Render() : + SCommand(CMD_RENDER) {} SState m_State; unsigned m_PrimType; unsigned m_PrimCount; @@ -220,8 +226,8 @@ public: struct SCommand_RenderTex3D : public SCommand { - SCommand_RenderTex3D() - : SCommand(CMD_RENDER_TEX3D) {} + SCommand_RenderTex3D() : + SCommand(CMD_RENDER_TEX3D) {} SState m_State; unsigned m_PrimType; unsigned m_PrimCount; @@ -230,7 +236,8 @@ public: struct SCommand_CreateBufferObject : public SCommand { - SCommand_CreateBufferObject() : SCommand(CMD_CREATE_BUFFER_OBJECT) {} + SCommand_CreateBufferObject() : + SCommand(CMD_CREATE_BUFFER_OBJECT) {} int m_BufferIndex; @@ -238,10 +245,10 @@ public: size_t m_DataSize; }; - struct SCommand_RecreateBufferObject : public SCommand { - SCommand_RecreateBufferObject() : SCommand(CMD_RECREATE_BUFFER_OBJECT) {} + SCommand_RecreateBufferObject() : + SCommand(CMD_RECREATE_BUFFER_OBJECT) {} int m_BufferIndex; @@ -251,7 +258,8 @@ public: struct SCommand_UpdateBufferObject : public SCommand { - SCommand_UpdateBufferObject() : SCommand(CMD_UPDATE_BUFFER_OBJECT) {} + SCommand_UpdateBufferObject() : + SCommand(CMD_UPDATE_BUFFER_OBJECT) {} int m_BufferIndex; @@ -262,7 +270,8 @@ public: struct SCommand_CopyBufferObject : public SCommand { - SCommand_CopyBufferObject() : SCommand(CMD_COPY_BUFFER_OBJECT) {} + SCommand_CopyBufferObject() : + SCommand(CMD_COPY_BUFFER_OBJECT) {} int m_WriteBufferIndex; int m_ReadBufferIndex; @@ -274,38 +283,42 @@ public: struct SCommand_DeleteBufferObject : public SCommand { - SCommand_DeleteBufferObject() : SCommand(CMD_DELETE_BUFFER_OBJECT) {} + SCommand_DeleteBufferObject() : + SCommand(CMD_DELETE_BUFFER_OBJECT) {} int m_BufferIndex; }; struct SCommand_CreateBufferContainer : public SCommand { - SCommand_CreateBufferContainer() : SCommand(CMD_CREATE_BUFFER_CONTAINER) {} + SCommand_CreateBufferContainer() : + SCommand(CMD_CREATE_BUFFER_CONTAINER) {} int m_BufferContainerIndex; int m_Stride; int m_AttrCount; - SBufferContainerInfo::SAttribute* m_Attributes; + SBufferContainerInfo::SAttribute *m_Attributes; }; struct SCommand_UpdateBufferContainer : public SCommand { - SCommand_UpdateBufferContainer() : SCommand(CMD_UPDATE_BUFFER_CONTAINER) {} + SCommand_UpdateBufferContainer() : + SCommand(CMD_UPDATE_BUFFER_CONTAINER) {} int m_BufferContainerIndex; int m_Stride; int m_AttrCount; - SBufferContainerInfo::SAttribute* m_Attributes; + SBufferContainerInfo::SAttribute *m_Attributes; }; struct SCommand_DeleteBufferContainer : public SCommand { - SCommand_DeleteBufferContainer() : SCommand(CMD_DELETE_BUFFER_CONTAINER) {} + SCommand_DeleteBufferContainer() : + SCommand(CMD_DELETE_BUFFER_CONTAINER) {} int m_BufferContainerIndex; bool m_DestroyAllBO; @@ -313,19 +326,21 @@ public: struct SCommand_IndicesRequiredNumNotify : public SCommand { - SCommand_IndicesRequiredNumNotify() : SCommand(CMD_INDICES_REQUIRED_NUM_NOTIFY) {} + SCommand_IndicesRequiredNumNotify() : + SCommand(CMD_INDICES_REQUIRED_NUM_NOTIFY) {} unsigned int m_RequiredIndicesNum; }; struct SCommand_RenderTileLayer : public SCommand { - SCommand_RenderTileLayer() : SCommand(CMD_RENDER_TILE_LAYER) {} + SCommand_RenderTileLayer() : + SCommand(CMD_RENDER_TILE_LAYER) {} SState m_State; SColorf m_Color; //the color of the whole tilelayer -- already envelopped //the char offset of all indices that should be rendered, and the amount of renders - char** m_pIndicesOffsets; + char **m_pIndicesOffsets; unsigned int *m_pDrawCount; int m_IndicesDrawNum; @@ -334,7 +349,8 @@ public: struct SCommand_RenderBorderTile : public SCommand { - SCommand_RenderBorderTile() : SCommand(CMD_RENDER_BORDER_TILE) {} + SCommand_RenderBorderTile() : + SCommand(CMD_RENDER_BORDER_TILE) {} SState m_State; SColorf m_Color; //the color of the whole tilelayer -- already envelopped char *m_pIndicesOffset; // you should use the command buffer data to allocate vertices for this command @@ -348,7 +364,8 @@ public: struct SCommand_RenderBorderTileLine : public SCommand { - SCommand_RenderBorderTileLine() : SCommand(CMD_RENDER_BORDER_TILE_LINE) {} + SCommand_RenderBorderTileLine() : + SCommand(CMD_RENDER_BORDER_TILE_LINE) {} SState m_State; SColorf m_Color; //the color of the whole tilelayer -- already envelopped char *m_pIndicesOffset; // you should use the command buffer data to allocate vertices for this command @@ -362,17 +379,19 @@ public: struct SCommand_RenderQuadLayer : public SCommand { - SCommand_RenderQuadLayer() : SCommand(CMD_RENDER_QUAD_LAYER) {} + SCommand_RenderQuadLayer() : + SCommand(CMD_RENDER_QUAD_LAYER) {} SState m_State; int m_BufferContainerIndex; - SQuadRenderInfo* m_pQuadInfo; + SQuadRenderInfo *m_pQuadInfo; int m_QuadNum; }; struct SCommand_RenderText : public SCommand { - SCommand_RenderText() : SCommand(CMD_RENDER_TEXT) {} + SCommand_RenderText() : + SCommand(CMD_RENDER_TEXT) {} SState m_State; int m_BufferContainerIndex; @@ -388,7 +407,8 @@ public: struct SCommand_RenderTextStream : public SCommand { - SCommand_RenderTextStream() : SCommand(CMD_RENDER_TEXT_STREAM) {} + SCommand_RenderTextStream() : + SCommand(CMD_RENDER_TEXT_STREAM) {} SState m_State; SVertex *m_pVertices; @@ -405,7 +425,8 @@ public: struct SCommand_RenderQuadContainer : public SCommand { - SCommand_RenderQuadContainer() : SCommand(CMD_RENDER_QUAD_CONTAINER) {} + SCommand_RenderQuadContainer() : + SCommand(CMD_RENDER_QUAD_CONTAINER) {} SState m_State; int m_BufferContainerIndex; @@ -416,7 +437,8 @@ public: struct SCommand_RenderQuadContainerAsSprite : public SCommand { - SCommand_RenderQuadContainerAsSprite() : SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE) {} + SCommand_RenderQuadContainerAsSprite() : + SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE) {} SState m_State; int m_BufferContainerIndex; @@ -432,7 +454,8 @@ public: struct SCommand_RenderQuadContainerAsSpriteMultiple : public SCommand { - SCommand_RenderQuadContainerAsSpriteMultiple() : SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE_MULTIPLE) {} + SCommand_RenderQuadContainerAsSpriteMultiple() : + SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE_MULTIPLE) {} SState m_State; int m_BufferContainerIndex; @@ -449,13 +472,15 @@ public: struct SCommand_Screenshot : public SCommand { - SCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {} + SCommand_Screenshot() : + SCommand(CMD_SCREENSHOT) {} CImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well }; struct SCommand_VideoModes : public SCommand { - SCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {} + SCommand_VideoModes() : + SCommand(CMD_VIDEOMODES) {} CVideoMode *m_pModes; // processor will fill this in int m_MaxModes; // maximum of modes the processor can write to the m_pModes @@ -465,14 +490,16 @@ public: struct SCommand_Swap : public SCommand { - SCommand_Swap() : SCommand(CMD_SWAP) {} + SCommand_Swap() : + SCommand(CMD_SWAP) {} int m_Finish; }; struct SCommand_VSync : public SCommand { - SCommand_VSync() : SCommand(CMD_VSYNC) {} + SCommand_VSync() : + SCommand(CMD_VSYNC) {} int m_VSync; bool *m_pRetOk; @@ -480,7 +507,8 @@ public: struct SCommand_Resize : public SCommand { - SCommand_Resize() : SCommand(CMD_RESIZE) {} + SCommand_Resize() : + SCommand(CMD_RESIZE) {} int m_Width; int m_Height; @@ -488,7 +516,8 @@ public: struct SCommand_Texture_Create : public SCommand { - SCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {} + SCommand_Texture_Create() : + SCommand(CMD_TEXTURE_CREATE) {} // texture information int m_Slot; @@ -504,7 +533,8 @@ public: struct SCommand_Texture_Update : public SCommand { - SCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {} + SCommand_Texture_Update() : + SCommand(CMD_TEXTURE_UPDATE) {} // texture information int m_Slot; @@ -517,18 +547,18 @@ public: void *m_pData; // will be freed by the command processor }; - struct SCommand_Texture_Destroy : public SCommand { - SCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {} + SCommand_Texture_Destroy() : + SCommand(CMD_TEXTURE_DESTROY) {} // texture information int m_Slot; }; // - CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize) - : m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize) + CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize) : + m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize) { } @@ -589,11 +619,11 @@ class IGraphicsBackend public: enum { - INITFLAG_FULLSCREEN = 1<<0, - INITFLAG_VSYNC = 1<<1, - INITFLAG_RESIZABLE = 1<<2, - INITFLAG_BORDERLESS = 1<<3, - INITFLAG_HIGHDPI = 1<<4, + INITFLAG_FULLSCREEN = 1 << 0, + INITFLAG_VSYNC = 1 << 1, + INITFLAG_RESIZABLE = 1 << 2, + INITFLAG_BORDERLESS = 1 << 3, + INITFLAG_HIGHDPI = 1 << 4, }; virtual ~IGraphicsBackend() {} @@ -634,11 +664,11 @@ class CGraphics_Threaded : public IEngineGraphics { NUM_CMDBUFFERS = 2, - MAX_VERTICES = 32*1024, - MAX_TEXTURES = 1024*4, + MAX_VERTICES = 32 * 1024, + MAX_TEXTURES = 1024 * 4, - DRAWING_QUADS=1, - DRAWING_LINES=2 + DRAWING_QUADS = 1, + DRAWING_LINES = 2 }; CCommandBuffer::SState m_State; @@ -684,7 +714,8 @@ class CGraphics_Threaded : public IEngineGraphics struct SVertexArrayInfo { - SVertexArrayInfo() : m_FreeIndex(-1) {} + SVertexArrayInfo() : + m_FreeIndex(-1) {} // keep a reference to them, so we can free their IDs std::vector m_AssociatedBufferObjectIndices; @@ -710,7 +741,6 @@ class CGraphics_Threaded : public IEngineGraphics CCommandBuffer::SVertex m_aVertices[4]; }; - std::vector m_Quads; int m_QuadBufferObjectIndex; @@ -723,13 +753,14 @@ class CGraphics_Threaded : public IEngineGraphics struct SWindowResizeListener { - SWindowResizeListener(WINDOW_RESIZE_FUNC pFunc, void *pUser) : m_pFunc(pFunc), m_pUser(pUser) {} + SWindowResizeListener(WINDOW_RESIZE_FUNC pFunc, void *pUser) : + m_pFunc(pFunc), m_pUser(pUser) {} WINDOW_RESIZE_FUNC m_pFunc; void *m_pUser; }; std::vector m_ResizeListeners; - void* AllocCommandBufferData(unsigned AllocSize); + void *AllocCommandBufferData(unsigned AllocSize); void AddVertices(int Count); void AddVertices(int Count, CCommandBuffer::SVertex *pVertices); @@ -757,6 +788,7 @@ class CGraphics_Threaded : public IEngineGraphics int IssueInit(); int InitWindow(); + public: CGraphics_Threaded(); diff --git a/src/engine/client/http.cpp b/src/engine/client/http.cpp index 2418ecdd7..be8cdc5d5 100644 --- a/src/engine/client/http.cpp +++ b/src/engine/client/http.cpp @@ -13,7 +13,7 @@ // TODO: Non-global pls? static CURLSH *gs_Share; -static LOCK gs_aLocks[CURL_LOCK_DATA_LAST+1]; +static LOCK gs_aLocks[CURL_LOCK_DATA_LAST + 1]; static int GetLockIndex(int Data) { @@ -75,13 +75,13 @@ void EscapeUrl(char *pBuf, int Size, const char *pStr) curl_free(pEsc); } -CRequest::CRequest(const char *pUrl, CTimeout Timeout, bool LogProgress) - : m_Timeout(Timeout), - m_Size(0), - m_Progress(0), - m_LogProgress(LogProgress), - m_State(HTTP_QUEUED), - m_Abort(false) +CRequest::CRequest(const char *pUrl, CTimeout Timeout, bool LogProgress) : + m_Timeout(Timeout), + m_Size(0), + m_Progress(0), + m_LogProgress(LogProgress), + m_State(HTTP_QUEUED), + m_Abort(false) { str_copy(m_aUrl, pUrl, sizeof(m_aUrl)); } @@ -247,11 +247,11 @@ size_t CGet::OnData(char *pData, size_t DataSize) return DataSize; } -CGetFile::CGetFile(IStorage *pStorage, const char *pUrl, const char *pDest, int StorageType, CTimeout Timeout, bool LogProgress) - : CRequest(pUrl, Timeout, LogProgress), - m_pStorage(pStorage), - m_StorageType(StorageType), - m_File(0) +CGetFile::CGetFile(IStorage *pStorage, const char *pUrl, const char *pDest, int StorageType, CTimeout Timeout, bool LogProgress) : + CRequest(pUrl, Timeout, LogProgress), + m_pStorage(pStorage), + m_StorageType(StorageType), + m_File(0) { str_copy(m_aDest, pDest, sizeof(m_aDest)); @@ -298,8 +298,8 @@ int CGetFile::OnCompletion(int State) return State; } -CPostJson::CPostJson(const char *pUrl, CTimeout Timeout, const char *pJson) - : CRequest(pUrl, Timeout) +CPostJson::CPostJson(const char *pUrl, CTimeout Timeout, const char *pJson) : + CRequest(pUrl, Timeout) { str_copy(m_aJson, pJson, sizeof(m_aJson)); } diff --git a/src/engine/client/http.h b/src/engine/client/http.h index 20345b5a7..79ab1f7bb 100644 --- a/src/engine/client/http.h +++ b/src/engine/client/http.h @@ -1,9 +1,9 @@ #ifndef ENGINE_CLIENT_HTTP_H #define ENGINE_CLIENT_HTTP_H +#include #include #include -#include typedef struct _json_value json_value; typedef void CURL; @@ -78,7 +78,17 @@ public: CGet(const char *pUrl, CTimeout Timeout); ~CGet(); - size_t ResultSize() const { if(!Result()) { return 0; } else { return m_BufferSize; } } + size_t ResultSize() const + { + if(!Result()) + { + return 0; + } + else + { + return m_BufferSize; + } + } unsigned char *Result() const; unsigned char *TakeResult(); json_value *ResultJson() const; @@ -105,7 +115,6 @@ public: const char *Dest() const { return m_aDest; } }; - class CPostJson : public CRequest { virtual size_t OnData(char *pData, size_t DataSize) { return DataSize; } diff --git a/src/engine/client/opengl_sl.cpp b/src/engine/client/opengl_sl.cpp index db10a9b0b..31f05e555 100644 --- a/src/engine/client/opengl_sl.cpp +++ b/src/engine/client/opengl_sl.cpp @@ -1,18 +1,18 @@ #include "opengl_sl.h" #include #include -#include #include #include +#include -bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char *pFile, int Type) +bool CGLSL::LoadShader(CGLSLCompiler *pCompiler, IStorage *pStorage, const char *pFile, int Type) { - if (m_IsLoaded) + if(m_IsLoaded) return true; IOHANDLE f = pStorage->OpenFile(pFile, IOFLAG_READ, IStorage::TYPE_ALL); std::vector Lines; - if (f) + if(f) { bool IsNewOpenGL = pCompiler->m_OpenGLVersionMajor >= 4 || (pCompiler->m_OpenGLVersionMajor == 3 && pCompiler->m_OpenGLVersionMinor == 3); //add compiler specific values @@ -38,7 +38,7 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char } } - for(CGLSLCompiler::SGLSLCompilerDefine& Define : pCompiler->m_Defines) + for(CGLSLCompiler::SGLSLCompilerDefine &Define : pCompiler->m_Defines) { Lines.push_back(std::string("#define ") + Define.m_DefineName + std::string(" ") + Define.m_DefineValue + std::string("\r\n")); } @@ -50,8 +50,8 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char CLineReader LineReader; LineReader.Init(f); - char* ReadLine = NULL; - while ((ReadLine = LineReader.Get())) + char *ReadLine = NULL; + while((ReadLine = LineReader.Get())) { std::string Line; pCompiler->ParseLine(Line, ReadLine, Type); @@ -60,9 +60,9 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char } io_close(f); - const char** ShaderCode = new const char*[Lines.size()]; + const char **ShaderCode = new const char *[Lines.size()]; - for (size_t i = 0; i < Lines.size(); ++i) + for(size_t i = 0; i < Lines.size(); ++i) { ShaderCode[i] = Lines[i].c_str(); } @@ -77,7 +77,7 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char int CompilationStatus; glGetShaderiv(shader, GL_COMPILE_STATUS, &CompilationStatus); - if (CompilationStatus == GL_FALSE) + if(CompilationStatus == GL_FALSE) { char buff[3000]; @@ -97,13 +97,14 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char return true; } - else return false; - + else + return false; } void CGLSL::DeleteShader() { - if (!IsLoaded()) return; + if(!IsLoaded()) + return; m_IsLoaded = false; glDeleteShader(m_ShaderID); } @@ -138,12 +139,12 @@ CGLSLCompiler::CGLSLCompiler(int OpenGLVersionMajor, int OpenGLVersionMinor, int m_TextureReplaceType = 0; } -void CGLSLCompiler::AddDefine(const std::string& DefineName, const std::string& DefineValue) +void CGLSLCompiler::AddDefine(const std::string &DefineName, const std::string &DefineValue) { m_Defines.emplace_back(SGLSLCompilerDefine(DefineName, DefineValue)); } -void CGLSLCompiler::AddDefine(const char* pDefineName, const char* pDefineValue) +void CGLSLCompiler::AddDefine(const char *pDefineName, const char *pDefineValue) { AddDefine(std::string(pDefineName), std::string(pDefineValue)); } @@ -153,12 +154,12 @@ void CGLSLCompiler::ClearDefines() m_Defines.clear(); } -void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type) +void CGLSLCompiler::ParseLine(std::string &Line, const char *pReadLine, int Type) { bool IsNewOpenGL = m_OpenGLVersionMajor >= 4 || (m_OpenGLVersionMajor == 3 && m_OpenGLVersionMinor == 3); if(!IsNewOpenGL) { - const char* pBuff = pReadLine; + const char *pBuff = pReadLine; char aTmpStr[1024]; size_t TmpStrSize = 0; while(*pBuff) @@ -168,13 +169,13 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type Line.append(1, *pBuff); ++pBuff; } - + while(*pBuff && !str_isspace(*pBuff) && *pBuff != '(' && *pBuff != '.') { aTmpStr[TmpStrSize++] = *pBuff; ++pBuff; } - + if(TmpStrSize > 0) { aTmpStr[TmpStrSize] = 0; @@ -221,7 +222,7 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type Found = true; } } - + if(!Found) { dbg_msg("Shader compiler", "Fix shader for older OpenGL versions."); @@ -261,9 +262,9 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type else { Line.append(aTmpStr); - } + } } - + if(*pBuff) { Line.append(1, *pBuff); diff --git a/src/engine/client/opengl_sl.h b/src/engine/client/opengl_sl.h index a0e0e96a1..f5f95bd8c 100644 --- a/src/engine/client/opengl_sl.h +++ b/src/engine/client/opengl_sl.h @@ -2,21 +2,23 @@ #define ENGINE_CLIENT_OPENGL_SL_H #include -#include #include +#include class CGLSLCompiler; -class CGLSL { +class CGLSL +{ public: - bool LoadShader(CGLSLCompiler* pCompiler, class IStorage *pStorage, const char *pFile, int Type); + bool LoadShader(CGLSLCompiler *pCompiler, class IStorage *pStorage, const char *pFile, int Type); void DeleteShader(); - + bool IsLoaded(); GLuint GetShaderID(); - + CGLSL(); virtual ~CGLSL(); + private: GLuint m_ShaderID; int m_Type; @@ -30,7 +32,7 @@ private: struct SGLSLCompilerDefine { - SGLSLCompilerDefine(const std::string& DefineName, const std::string& DefineValue) + SGLSLCompilerDefine(const std::string &DefineName, const std::string &DefineValue) { m_DefineName = DefineName; m_DefineValue = DefineValue; @@ -52,11 +54,11 @@ public: void SetHasTextureArray(bool TextureArray) { m_HasTextureArray = TextureArray; } void SetTextureReplaceType(int TextureReplaceType) { m_TextureReplaceType = TextureReplaceType; } - void AddDefine(const std::string& DefineName, const std::string& DefineValue); - void AddDefine(const char* pDefineName, const char* pDefineValue); + void AddDefine(const std::string &DefineName, const std::string &DefineValue); + void AddDefine(const char *pDefineName, const char *pDefineValue); void ClearDefines(); - void ParseLine(std::string& Line, const char* pReadLine, int Type); + void ParseLine(std::string &Line, const char *pReadLine, int Type); enum EGLSLCompilerTextureReplaceType { diff --git a/src/engine/client/opengl_sl_program.cpp b/src/engine/client/opengl_sl_program.cpp index e51598f77..8abc1bb18 100644 --- a/src/engine/client/opengl_sl_program.cpp +++ b/src/engine/client/opengl_sl_program.cpp @@ -9,14 +9,15 @@ void CGLSLProgram::CreateProgram() void CGLSLProgram::DeleteProgram() { - if (!m_IsLinked) return; + if(!m_IsLinked) + return; m_IsLinked = false; glDeleteProgram(m_ProgramID); } -bool CGLSLProgram::AddShader(CGLSL* pShader) +bool CGLSLProgram::AddShader(CGLSL *pShader) { - if (pShader->IsLoaded()) + if(pShader->IsLoaded()) { glAttachShader(m_ProgramID, pShader->GetShaderID()); return true; @@ -24,9 +25,9 @@ bool CGLSLProgram::AddShader(CGLSL* pShader) return false; } -void CGLSLProgram::DetachShader(CGLSL* pShader) +void CGLSLProgram::DetachShader(CGLSL *pShader) { - if (pShader->IsLoaded()) + if(pShader->IsLoaded()) { DetachShaderByID(pShader->GetShaderID()); } @@ -43,7 +44,7 @@ void CGLSLProgram::LinkProgram() int LinkStatus; glGetProgramiv(m_ProgramID, GL_LINK_STATUS, &LinkStatus); m_IsLinked = LinkStatus == GL_TRUE; - if (!m_IsLinked) + if(!m_IsLinked) { char sInfoLog[1024]; char sFinalMessage[1536]; @@ -52,7 +53,7 @@ void CGLSLProgram::LinkProgram() str_format(sFinalMessage, 1536, "Error! Shader program wasn't linked! The linker returned:\n\n%s", sInfoLog); dbg_msg("GLSL Program", "%s", sFinalMessage); } - + //detach all shaders attached to this program DetachAllShaders(); } @@ -64,7 +65,7 @@ void CGLSLProgram::DetachAllShaders() while(1) { glGetAttachedShaders(m_ProgramID, 100, &ReturnedCount, aShaders); - + if(ReturnedCount > 0) { for(GLsizei i = 0; i < ReturnedCount; ++i) @@ -72,8 +73,9 @@ void CGLSLProgram::DetachAllShaders() DetachShaderByID(aShaders[i]); } } - - if(ReturnedCount < 100) break; + + if(ReturnedCount < 100) + break; } } @@ -112,14 +114,15 @@ void CGLSLProgram::SetUniform(int Loc, const bool Value) glUniform1i(Loc, (int)Value); } -int CGLSLProgram::GetUniformLoc(const char* Name) +int CGLSLProgram::GetUniformLoc(const char *Name) { return glGetUniformLocation(m_ProgramID, Name); } void CGLSLProgram::UseProgram() { - if(m_IsLinked) glUseProgram(m_ProgramID); + if(m_IsLinked) + glUseProgram(m_ProgramID); } GLuint CGLSLProgram::GetProgramID() diff --git a/src/engine/client/opengl_sl_program.h b/src/engine/client/opengl_sl_program.h index b54332a54..aacbbbd6b 100644 --- a/src/engine/client/opengl_sl_program.h +++ b/src/engine/client/opengl_sl_program.h @@ -5,22 +5,23 @@ class CGLSL; -class CGLSLProgram { +class CGLSLProgram +{ public: void CreateProgram(); void DeleteProgram(); - - bool AddShader(CGLSL* pShader); - + + bool AddShader(CGLSL *pShader); + void LinkProgram(); void UseProgram(); GLuint GetProgramID(); - - void DetachShader(CGLSL* pShader); + + void DetachShader(CGLSL *pShader); void DetachShaderByID(GLuint ShaderID); void DetachAllShaders(); - - //Support various types + + //Support various types void SetUniformVec2(int Loc, int Count, const float *pValue); void SetUniformVec4(int Loc, int Count, const float *pValue); void SetUniform(int Loc, const int Value); @@ -28,21 +29,23 @@ public: void SetUniform(int Loc, const bool Value); void SetUniform(int Loc, const float Value); void SetUniform(int Loc, int Count, const float *pValues); - + //for performance reason we do not use SetUniform with using strings... save the Locations of the variables instead - int GetUniformLoc(const char* Name); - + int GetUniformLoc(const char *Name); + CGLSLProgram(); virtual ~CGLSLProgram(); - + protected: GLuint m_ProgramID; bool m_IsLinked; }; -class CGLSLTWProgram : public CGLSLProgram { +class CGLSLTWProgram : public CGLSLProgram +{ public: - CGLSLTWProgram() : m_LocPos(-1), m_LocIsTextured(-1), m_LocTextureSampler(-1), m_LastTextureSampler(-1), m_LastIsTextured(-1) + CGLSLTWProgram() : + m_LocPos(-1), m_LocIsTextured(-1), m_LocTextureSampler(-1), m_LastTextureSampler(-1), m_LastIsTextured(-1) { m_LastScreen[0] = m_LastScreen[1] = m_LastScreen[2] = m_LastScreen[3] = -1.f; } @@ -56,9 +59,11 @@ public: float m_LastScreen[4]; }; -class CGLSLTextProgram : public CGLSLTWProgram { +class CGLSLTextProgram : public CGLSLTWProgram +{ public: - CGLSLTextProgram() : CGLSLTWProgram() + CGLSLTextProgram() : + CGLSLTWProgram() { m_LastColor[0] = m_LastColor[1] = m_LastColor[2] = m_LastColor[3] = -1.f; m_LastOutlineColor[0] = m_LastOutlineColor[1] = m_LastOutlineColor[2] = m_LastOutlineColor[3] = -1.f; @@ -79,13 +84,16 @@ public: int m_LastTextureSize; }; -class CGLSLPrimitiveProgram : public CGLSLTWProgram { +class CGLSLPrimitiveProgram : public CGLSLTWProgram +{ public: }; -class CGLSLSpriteProgram : public CGLSLTWProgram { +class CGLSLSpriteProgram : public CGLSLTWProgram +{ public: - CGLSLSpriteProgram() : CGLSLTWProgram() + CGLSLSpriteProgram() : + CGLSLTWProgram() { m_LastRotation = 0.f; m_LastCenter[0] = m_LastCenter[1] = 0.f; @@ -101,9 +109,11 @@ public: float m_LastVertciesColor[4]; }; -class CGLSLSpriteMultipleProgram : public CGLSLTWProgram { +class CGLSLSpriteMultipleProgram : public CGLSLTWProgram +{ public: - CGLSLSpriteMultipleProgram() : CGLSLTWProgram() + CGLSLSpriteMultipleProgram() : + CGLSLTWProgram() { m_LastCenter[0] = m_LastCenter[1] = 0.f; m_LastVertciesColor[0] = m_LastVertciesColor[1] = m_LastVertciesColor[2] = m_LastVertciesColor[3] = -1.f; @@ -117,16 +127,19 @@ public: float m_LastVertciesColor[4]; }; -class CGLSLQuadProgram : public CGLSLTWProgram { +class CGLSLQuadProgram : public CGLSLTWProgram +{ public: int m_LocColors; int m_LocOffsets; int m_LocRotations; }; -class CGLSLTileProgram : public CGLSLTWProgram { +class CGLSLTileProgram : public CGLSLTWProgram +{ public: - CGLSLTileProgram() : m_LocColor(-1), m_LocOffset(-1), m_LocDir(-1), m_LocNum(-1), m_LocJumpIndex(-1) {} + CGLSLTileProgram() : + m_LocColor(-1), m_LocOffset(-1), m_LocDir(-1), m_LocNum(-1), m_LocJumpIndex(-1) {} int m_LocColor; int m_LocOffset; diff --git a/src/engine/client/serverbrowser.cpp b/src/engine/client/serverbrowser.cpp index 7020c0370..c2b46044b 100644 --- a/src/engine/client/serverbrowser.cpp +++ b/src/engine/client/serverbrowser.cpp @@ -28,8 +28,10 @@ class SortWrap typedef bool (CServerBrowser::*SortFunc)(int, int) const; SortFunc m_pfnSort; CServerBrowser *m_pThis; + public: - SortWrap(CServerBrowser *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {} + SortWrap(CServerBrowser *t, SortFunc f) : + m_pfnSort(f), m_pThis(t) {} bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); } }; @@ -117,7 +119,7 @@ bool CServerBrowser::SortCompareName(int Index1, int Index2) const CServerEntry *b = m_ppServerlist[Index2]; // make sure empty entries are listed last return (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp(a->m_Info.m_aName, b->m_Info.m_aName) < 0 : - a->m_GotInfo ? true : false; + a->m_GotInfo ? true : false; } bool CServerBrowser::SortCompareMap(int Index1, int Index2) const @@ -165,7 +167,7 @@ bool CServerBrowser::SortCompareNumPlayersAndPing(int Index1, int Index2) const if(a->m_Info.m_NumFilteredPlayers == 0 || b->m_Info.m_NumFilteredPlayers == 0) return a->m_Info.m_NumFilteredPlayers == 0; else - return a->m_Info.m_NumFilteredPlayers - (a->m_Info.m_Latency/100)*MAX_CLIENTS < b->m_Info.m_NumFilteredPlayers - (b->m_Info.m_Latency/100)*MAX_CLIENTS; + return a->m_Info.m_NumFilteredPlayers - (a->m_Info.m_Latency / 100) * MAX_CLIENTS < b->m_Info.m_NumFilteredPlayers - (b->m_Info.m_Latency / 100) * MAX_CLIENTS; } void CServerBrowser::Filter() @@ -191,7 +193,7 @@ void CServerBrowser::Filter() Filtered = 1; else if(g_Config.m_BrFilterFull && Players(m_ppServerlist[i]->m_Info) == Max(m_ppServerlist[i]->m_Info)) Filtered = 1; - else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags&SERVER_FLAG_PASSWORD) + else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags & SERVER_FLAG_PASSWORD) Filtered = 1; else if(g_Config.m_BrFilterPing && g_Config.m_BrFilterPing < m_ppServerlist[i]->m_Info.m_Latency) Filtered = 1; @@ -320,17 +322,17 @@ int CServerBrowser::SortHash() const void SetFilteredPlayers(const CServerInfo &Item) { - if (g_Config.m_BrFilterSpectators) + if(g_Config.m_BrFilterSpectators) Item.m_NumFilteredPlayers = Item.m_NumPlayers; else Item.m_NumFilteredPlayers = Item.m_NumClients; - if (g_Config.m_BrFilterConnectingPlayers) + if(g_Config.m_BrFilterConnectingPlayers) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { const CServerInfo::CClient &Client = Item.m_aClients[i]; - if (str_comp(Client.m_aName, "(connecting)") == 0 && Client.m_aClan[0] == '\0' && Client.m_Country == -1 && Client.m_Score == 0) + if(str_comp(Client.m_aName, "(connecting)") == 0 && Client.m_aClan[0] == '\0' && Client.m_Country == -1 && Client.m_Score == 0) Item.m_NumFilteredPlayers--; } } @@ -350,18 +352,18 @@ void CServerBrowser::Sort() Filter(); // sort - if(g_Config.m_BrSortOrder == 2 && (g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS ||g_Config.m_BrSort == IServerBrowser::SORT_PING)) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayersAndPing)); + if(g_Config.m_BrSortOrder == 2 && (g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS || g_Config.m_BrSort == IServerBrowser::SORT_PING)) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayersAndPing)); else if(g_Config.m_BrSort == IServerBrowser::SORT_NAME) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName)); + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName)); else if(g_Config.m_BrSort == IServerBrowser::SORT_PING) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing)); + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing)); else if(g_Config.m_BrSort == IServerBrowser::SORT_MAP) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap)); + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap)); else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayers)); + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayers)); else if(g_Config.m_BrSort == IServerBrowser::SORT_GAMETYPE) - std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype)); + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype)); // set indexes for(i = 0; i < m_NumSortedServers; i++) @@ -401,7 +403,7 @@ CServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr) if(net_addr_comp(&pEntry->m_Addr, &Addr) == 0) return pEntry; } - return (CServerEntry*)0; + return (CServerEntry *)0; } void CServerBrowser::QueueRequest(CServerEntry *pEntry) @@ -498,7 +500,7 @@ CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr) CServerEntry **ppNewlist; m_NumServerCapacity += 100; ppNewlist = (CServerEntry **)calloc(m_NumServerCapacity, sizeof(CServerEntry *)); - mem_copy(ppNewlist, m_ppServerlist, m_NumServers*sizeof(CServerEntry*)); + mem_copy(ppNewlist, m_ppServerlist, m_NumServers * sizeof(CServerEntry *)); free(m_ppServerlist); m_ppServerlist = ppNewlist; } @@ -569,12 +571,12 @@ void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServer } pEntry = Find(Addr); - + if(m_ServerlistType == IServerBrowser::TYPE_LAN) { NETADDR Broadcast; mem_zero(&Broadcast, sizeof(Broadcast)); - Broadcast.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST; + Broadcast.type = m_pNetClient->NetType() | NETTYPE_LINK_BROADCAST; int Token = GenerateToken(Broadcast); bool Drop = false; Drop = Drop || BasicToken != GetBasicToken(Token); @@ -602,13 +604,13 @@ void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServer return; } } - + SetInfo(pEntry, *pInfo); - if (m_ServerlistType == IServerBrowser::TYPE_LAN) - pEntry->m_Info.m_Latency = minimum(static_cast((time_get()-m_BroadcastTime)*1000/time_freq()), 999); - else if (pEntry->m_RequestTime > 0) + if(m_ServerlistType == IServerBrowser::TYPE_LAN) + pEntry->m_Info.m_Latency = minimum(static_cast((time_get() - m_BroadcastTime) * 1000 / time_freq()), 999); + else if(pEntry->m_RequestTime > 0) { - pEntry->m_Info.m_Latency = minimum(static_cast((time_get()-pEntry->m_RequestTime)*1000/time_freq()), 999); + pEntry->m_Info.m_Latency = minimum(static_cast((time_get() - pEntry->m_RequestTime) * 1000 / time_freq()), 999); pEntry->m_RequestTime = -1; // Request has been answered } RemoveRequest(pEntry); @@ -635,15 +637,15 @@ void CServerBrowser::Refresh(int Type) if(Type == IServerBrowser::TYPE_LAN) { - unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO) + 1]; CNetChunk Packet; int i; /* do the broadcast version */ Packet.m_ClientID = -1; mem_zero(&Packet, sizeof(Packet)); - Packet.m_Address.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST; - Packet.m_Flags = NETSENDFLAG_CONNLESS|NETSENDFLAG_EXTENDED; + Packet.m_Address.type = m_pNetClient->NetType() | NETTYPE_LINK_BROADCAST; + Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED; Packet.m_DataSize = sizeof(Buffer); Packet.m_pData = Buffer; mem_zero(&Packet.m_aExtraData, sizeof(Packet.m_aExtraData)); @@ -739,7 +741,7 @@ void CServerBrowser::Refresh(int Type) void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const { - unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO) + 1]; CNetChunk Packet; if(g_Config.m_Debug) @@ -747,7 +749,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; - str_format(aBuf, sizeof(aBuf),"requesting server info from %s", aAddrStr); + str_format(aBuf, sizeof(aBuf), "requesting server info from %s", aAddrStr); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); } @@ -758,7 +760,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons Packet.m_ClientID = -1; Packet.m_Address = Addr; - Packet.m_Flags = NETSENDFLAG_CONNLESS|NETSENDFLAG_EXTENDED; + Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED; Packet.m_DataSize = sizeof(Buffer); Packet.m_pData = Buffer; mem_zero(&Packet.m_aExtraData, sizeof(Packet.m_aExtraData)); @@ -773,7 +775,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons void CServerBrowser::RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) const { - unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO_64_LEGACY)+1]; + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO_64_LEGACY) + 1]; CNetChunk Packet; if(g_Config.m_Debug) @@ -781,7 +783,7 @@ void CServerBrowser::RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) co char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; - str_format(aBuf, sizeof(aBuf),"requesting server info 64 from %s", aAddrStr); + str_format(aBuf, sizeof(aBuf), "requesting server info 64 from %s", aAddrStr); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); } @@ -805,7 +807,6 @@ void CServerBrowser::RequestCurrentServer(const NETADDR &Addr) const RequestImpl(Addr, 0); } - void CServerBrowser::Update(bool ForceResort) { int64 Timeout = time_freq(); @@ -849,21 +850,21 @@ void CServerBrowser::Update(bool ForceResort) { m_MasterServerCount = 0; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + int Count = m_pMasterServer->GetCount(i); + if(Count == -1) { - if(!m_pMasterServer->IsValid(i)) - continue; - int Count = m_pMasterServer->GetCount(i); - if(Count == -1) - { /* ignore Server m_MasterServerCount = -1; return; // we don't have the required server information */ - } - else - m_MasterServerCount += Count; } + else + m_MasterServerCount += Count; + } //request Server-List NETADDR Addr; CNetChunk Packet; @@ -892,27 +893,27 @@ void CServerBrowser::Update(bool ForceResort) { m_MasterServerCount = 0; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + int Count = m_pMasterServer->GetCount(i); + if(Count == -1) { - if(!m_pMasterServer->IsValid(i)) - continue; - int Count = m_pMasterServer->GetCount(i); - if(Count == -1) - { /* ignore Server m_MasterServerCount = -1; return; // we don't have the required server information */ - } - else - m_MasterServerCount += Count; } - //if(g_Config.m_Debug) - //{ - // dbg_msg("client_srvbrowse", "ServerCount2: %d", m_MasterServerCount); - //} + else + m_MasterServerCount += Count; + } + //if(g_Config.m_Debug) + //{ + // dbg_msg("client_srvbrowse", "ServerCount2: %d", m_MasterServerCount); + //} } - if(m_MasterServerCount > m_NumRequests + m_LastPacketTick) + if(m_MasterServerCount > m_NumRequests + m_LastPacketTick) { ++m_LastPacketTick; return; //wait for more packets @@ -923,7 +924,7 @@ void CServerBrowser::Update(bool ForceResort) { if(!pEntry) // no more entries break; - if(pEntry->m_RequestTime && pEntry->m_RequestTime+Timeout < Now) + if(pEntry->m_RequestTime && pEntry->m_RequestTime + Timeout < Now) { pEntry = pEntry->m_pNextReq; continue; @@ -934,7 +935,7 @@ void CServerBrowser::Update(bool ForceResort) if(pEntry->m_RequestTime == 0) { - if (pEntry->m_Request64Legacy) + if(pEntry->m_Request64Legacy) RequestImpl64(pEntry->m_Addr, pEntry); else RequestImpl(pEntry->m_Addr, pEntry); @@ -957,7 +958,7 @@ void CServerBrowser::Update(bool ForceResort) } //update max-requests - m_CurrentMaxRequests = m_CurrentMaxRequests/2; + m_CurrentMaxRequests = m_CurrentMaxRequests / 2; if(m_CurrentMaxRequests < 1) m_CurrentMaxRequests = 1; } @@ -969,7 +970,7 @@ void CServerBrowser::Update(bool ForceResort) if(!pEntry) // no more entries break; pNext = pEntry->m_pNextReq; - RemoveRequest(pEntry); //release request + RemoveRequest(pEntry); //release request pEntry = pNext; } } @@ -979,7 +980,6 @@ void CServerBrowser::Update(bool ForceResort) Sort(); } - bool CServerBrowser::IsFavorite(const NETADDR &Addr) const { // search for the address @@ -1031,7 +1031,7 @@ void CServerBrowser::RemoveFavorite(const NETADDR &Addr) { if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0) { - mem_move(&m_aFavoriteServers[i], &m_aFavoriteServers[i+1], sizeof(NETADDR)*(m_NumFavoriteServers-(i+1))); + mem_move(&m_aFavoriteServers[i], &m_aFavoriteServers[i + 1], sizeof(NETADDR) * (m_NumFavoriteServers - (i + 1))); m_NumFavoriteServers--; pEntry = Find(Addr); @@ -1045,24 +1045,24 @@ void CServerBrowser::RemoveFavorite(const NETADDR &Addr) void CServerBrowser::LoadDDNetServers() { - if (!m_pDDNetInfo) + if(!m_pDDNetInfo) return; // reset servers / countries - for (int Network = 0; Network < NUM_NETWORKS; Network++) + for(int Network = 0; Network < NUM_NETWORKS; Network++) { CNetwork *pNet = &m_aNetworks[Network]; // parse JSON const json_value *pServers = json_object_get(m_pDDNetInfo, Network == NETWORK_DDNET ? "servers" : "servers-kog"); - if (!pServers || pServers->type != json_array) + if(!pServers || pServers->type != json_array) return; pNet->m_NumCountries = 0; pNet->m_NumTypes = 0; - for (int i = 0; i < json_array_length(pServers) && pNet->m_NumCountries < MAX_COUNTRIES; i++) + for(int i = 0; i < json_array_length(pServers) && pNet->m_NumCountries < MAX_COUNTRIES; i++) { // pSrv - { name, flagId, servers } const json_value *pSrv = json_array_get(pServers, i); @@ -1070,7 +1070,7 @@ void CServerBrowser::LoadDDNetServers() const json_value *pName = json_object_get(pSrv, "name"); const json_value *pFlagID = json_object_get(pSrv, "flagId"); - if (pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer) + if(pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer) { dbg_msg("client_srvbrowse", "invalid attributes"); continue; @@ -1085,12 +1085,12 @@ void CServerBrowser::LoadDDNetServers() pCntr->m_FlagID = json_int_get(pFlagID); // add country - for (unsigned int t = 0; t < pTypes->u.object.length; t++) + for(unsigned int t = 0; t < pTypes->u.object.length; t++) { const char *pType = pTypes->u.object.values[t].name; const json_value *pAddrs = pTypes->u.object.values[t].value; - if (pAddrs->type != json_array) + if(pAddrs->type != json_array) { dbg_msg("client_srvbrowse", "invalid attributes"); continue; @@ -1113,10 +1113,10 @@ void CServerBrowser::LoadDDNetServers() } // add addresses - for (int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++) + for(int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++) { const json_value *pAddr = json_array_get(pAddrs, g); - if (pAddr->type != json_string) + if(pAddr->type != json_string) { dbg_msg("client_srvbrowse", "invalid attributes"); continue; @@ -1170,7 +1170,7 @@ int CServerBrowser::HasRank(const char *pMap) if(!pDDNetRanks || pDDNetRanks->type != json_array) return -1; - for (int i = 0; i < json_array_length(pDDNetRanks); i++) + for(int i = 0; i < json_array_length(pDDNetRanks); i++) { const json_value *pJson = json_array_get(pDDNetRanks, i); if(!pJson || pJson->type != json_string) @@ -1248,18 +1248,16 @@ bool CServerBrowser::IsRefreshingMasters() const return m_pMasterServer->IsRefreshing(); } - int CServerBrowser::LoadingProgression() const { if(m_NumServers == 0) return 0; int Servers = m_NumServers; - int Loaded = m_NumServers-m_NumRequests; - return 100.0f * Loaded/Servers; + int Loaded = m_NumServers - m_NumRequests; + return 100.0f * Loaded / Servers; } - void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CServerBrowser *pSelf = (CServerBrowser *)pUserData; @@ -1276,7 +1274,7 @@ void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData) void CServerBrowser::DDNetFilterAdd(char *pFilter, const char *pName) { - if (DDNetFiltered(pFilter, pName)) + if(DDNetFiltered(pFilter, pName)) return; char aBuf[128]; @@ -1286,7 +1284,7 @@ void CServerBrowser::DDNetFilterAdd(char *pFilter, const char *pName) void CServerBrowser::DDNetFilterRem(char *pFilter, const char *pName) { - if (!DDNetFiltered(pFilter, pName)) + if(!DDNetFiltered(pFilter, pName)) return; // rewrite exclude/filter list diff --git a/src/engine/client/serverbrowser.h b/src/engine/client/serverbrowser.h index 3947f3920..47740fa5d 100644 --- a/src/engine/client/serverbrowser.h +++ b/src/engine/client/serverbrowser.h @@ -3,9 +3,9 @@ #ifndef ENGINE_CLIENT_SERVERBROWSER_H #define ENGINE_CLIENT_SERVERBROWSER_H +#include #include #include -#include class CServerBrowser : public IServerBrowser { @@ -38,7 +38,12 @@ public: char m_aTypes[MAX_SERVERS][32]; int m_NumServers; - void Reset() { m_NumServers = 0; m_FlagID = -1; m_aName[0] = '\0'; }; + void Reset() + { + m_NumServers = 0; + m_FlagID = -1; + m_aName[0] = '\0'; + }; /*void Add(NETADDR Addr, char* pType) { if (m_NumServers < MAX_SERVERS) { @@ -51,9 +56,9 @@ public: enum { - MAX_FAVORITES=2048, - MAX_COUNTRIES=16, - MAX_TYPES=32, + MAX_FAVORITES = 2048, + MAX_COUNTRIES = 16, + MAX_TYPES = 32, }; struct CNetwork @@ -65,7 +70,6 @@ public: int m_NumTypes; }; - CServerBrowser(); virtual ~CServerBrowser(); diff --git a/src/engine/client/sound.cpp b/src/engine/client/sound.cpp index fa66d2a75..308473161 100644 --- a/src/engine/client/sound.cpp +++ b/src/engine/client/sound.cpp @@ -12,13 +12,12 @@ #include "sound.h" -extern "C" -{ +extern "C" { #if defined(CONF_VIDEORECORDER) - #include +#include #endif - #include - #include +#include +#include } #include @@ -65,9 +64,9 @@ struct CVoice }; }; -static CSample m_aSamples[NUM_SAMPLES] = { {0} }; -static CVoice m_aVoices[NUM_VOICES] = { {0} }; -static CChannel m_aChannels[NUM_CHANNELS] = { {255, 0} }; +static CSample m_aSamples[NUM_SAMPLES] = {{0}}; +static CVoice m_aVoices[NUM_VOICES] = {{0}}; +static CChannel m_aChannels[NUM_CHANNELS] = {{255, 0}}; static LOCK m_SoundLock = 0; @@ -78,7 +77,7 @@ static int m_MixingRate = 48000; static volatile int m_SoundVolume = 100; static int m_NextVoice = 0; -static int *m_pMixBuffer = 0; // buffer only used by the thread callback function +static int *m_pMixBuffer = 0; // buffer only used by the thread callback function static unsigned m_MaxFrames = 0; static const void *s_pWVBuffer = 0x0; @@ -100,7 +99,7 @@ static short Int2Short(int i) static int IntAbs(int i) { - if(i<0) + if(i < 0) return -i; return i; } @@ -108,7 +107,7 @@ static int IntAbs(int i) static void Mix(short *pFinalOut, unsigned Frames) { int MasterVol; - mem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int)); + mem_zero(m_pMixBuffer, m_MaxFrames * 2 * sizeof(int)); Frames = minimum(Frames, m_MaxFrames); // acquire lock while we are mixing @@ -125,13 +124,13 @@ static void Mix(short *pFinalOut, unsigned Frames) int *pOut = m_pMixBuffer; int Step = v->m_pSample->m_Channels; // setup input sources - short *pInL = &v->m_pSample->m_pData[v->m_Tick*Step]; - short *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1]; + short *pInL = &v->m_pSample->m_pData[v->m_Tick * Step]; + short *pInR = &v->m_pSample->m_pData[v->m_Tick * Step + 1]; - unsigned End = v->m_pSample->m_NumFrames-v->m_Tick; + unsigned End = v->m_pSample->m_NumFrames - v->m_Tick; - int Rvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f)); - int Lvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f)); + int Rvol = (int)(v->m_pChannel->m_Vol * (v->m_Vol / 255.0f)); + int Lvol = (int)(v->m_pChannel->m_Vol * (v->m_Vol / 255.0f)); // make sure that we don't go outside the sound data if(Frames < End) @@ -142,7 +141,7 @@ static void Mix(short *pFinalOut, unsigned Frames) pInR = pInL; // volume calculation - if(v->m_Flags&ISound::FLAG_POS && v->m_pChannel->m_Pan) + if(v->m_Flags & ISound::FLAG_POS && v->m_pChannel->m_Pan) { // TODO: we should respect the channel panning value int dx = v->m_X - m_CenterX; @@ -158,65 +157,65 @@ static void Mix(short *pFinalOut, unsigned Frames) switch(v->m_Shape) { case ISound::SHAPE_CIRCLE: + { + float r = v->m_Circle.m_Radius; + RangeX = r; + + int Dist = (int)sqrtf((float)dx * dx + dy * dy); // nasty float + if(Dist < r) { - float r = v->m_Circle.m_Radius; - RangeX = r; + InVoiceField = true; - int Dist = (int)sqrtf((float)dx*dx+dy*dy); // nasty float - if(Dist < r) - { - InVoiceField = true; - - // falloff - int FalloffDistance = r*v->m_Falloff; - if(Dist > FalloffDistance) - FalloffX = FalloffY = (r-Dist)/(r-FalloffDistance); - else - FalloffX = FalloffY = 1.0f; - } + // falloff + int FalloffDistance = r * v->m_Falloff; + if(Dist > FalloffDistance) + FalloffX = FalloffY = (r - Dist) / (r - FalloffDistance); else - InVoiceField = false; - - break; + FalloffX = FalloffY = 1.0f; } + else + InVoiceField = false; + + break; + } case ISound::SHAPE_RECTANGLE: + { + RangeX = v->m_Rectangle.m_Width / 2.0f; + + int abs_dx = abs(dx); + int abs_dy = abs(dy); + + int w = v->m_Rectangle.m_Width / 2.0f; + int h = v->m_Rectangle.m_Height / 2.0f; + + if(abs_dx < w && abs_dy < h) { - RangeX = v->m_Rectangle.m_Width/2.0f; + InVoiceField = true; - int abs_dx = abs(dx); - int abs_dy = abs(dy); + // falloff + int fx = v->m_Falloff * w; + int fy = v->m_Falloff * h; - int w = v->m_Rectangle.m_Width/2.0f; - int h = v->m_Rectangle.m_Height/2.0f; - - if(abs_dx < w && abs_dy < h) - { - InVoiceField = true; - - // falloff - int fx = v->m_Falloff * w; - int fy = v->m_Falloff * h; - - FalloffX = abs_dx > fx ? (float)(w-abs_dx)/(w-fx) : 1.0f; - FalloffY = abs_dy > fy ? (float)(h-abs_dy)/(h-fy) : 1.0f; - } - else - InVoiceField = false; - - break; + FalloffX = abs_dx > fx ? (float)(w - abs_dx) / (w - fx) : 1.0f; + FalloffY = abs_dy > fy ? (float)(h - abs_dy) / (h - fy) : 1.0f; } + else + InVoiceField = false; + + break; + } }; if(InVoiceField) { // panning - if(!(v->m_Flags&ISound::FLAG_NO_PANNING)) + if(!(v->m_Flags & ISound::FLAG_NO_PANNING)) { if(dx > 0) - Lvol = ((RangeX-p)*Lvol)/RangeX; + Lvol = ((RangeX - p) * Lvol) / RangeX; else - Rvol = ((RangeX-p)*Rvol)/RangeX; + Rvol = ((RangeX - p) * Rvol) / RangeX; } { @@ -234,8 +233,8 @@ static void Mix(short *pFinalOut, unsigned Frames) // process all frames for(unsigned s = 0; s < End; s++) { - *pOut++ += (*pInL)*Lvol; - *pOut++ += (*pInR)*Rvol; + *pOut++ += (*pInL) * Lvol; + *pOut++ += (*pInR) * Rvol; pInL += Step; pInR += Step; v->m_Tick++; @@ -244,7 +243,7 @@ static void Mix(short *pFinalOut, unsigned Frames) // free voice if not used any more if(v->m_Tick == v->m_pSample->m_NumFrames) { - if(v->m_Flags&ISound::FLAG_LOOP) + if(v->m_Flags & ISound::FLAG_LOOP) v->m_Tick = 0; else { @@ -255,7 +254,6 @@ static void Mix(short *pFinalOut, unsigned Frames) } } - // release the lock lock_unlock(m_SoundLock); @@ -264,12 +262,12 @@ static void Mix(short *pFinalOut, unsigned Frames) // TODO: this seams slow for(unsigned i = 0; i < Frames; i++) { - int j = i<<1; - int vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8; - int vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8; + int j = i << 1; + int vl = ((m_pMixBuffer[j] * MasterVol) / 101) >> 8; + int vr = ((m_pMixBuffer[j + 1] * MasterVol) / 101) >> 8; pFinalOut[j] = Int2Short(vl); - pFinalOut[j+1] = Int2Short(vr); + pFinalOut[j + 1] = Int2Short(vr); // dbg_msg("sound", "the real shit: %d %d", pFinalOut[j], pFinalOut[j+1]); } @@ -278,23 +276,21 @@ static void Mix(short *pFinalOut, unsigned Frames) #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(pFinalOut, sizeof(short), Frames * 2); #endif - } static void SdlCallback(void *pUnused, Uint8 *pStream, int Len) { (void)pUnused; #if defined(CONF_VIDEORECORDER) - if (!(IVideo::Current() && g_Config.m_ClVideoSndEnable)) - Mix((short *)pStream, Len/2/2); + if(!(IVideo::Current() && g_Config.m_ClVideoSndEnable)) + Mix((short *)pStream, Len / 2 / 2); else IVideo::Current()->NextAudioFrame(Mix); #else - Mix((short *)pStream, Len/2/2); + Mix((short *)pStream, Len / 2 / 2); #endif } - int CSound::Init() { m_SoundEnabled = 0; @@ -327,7 +323,7 @@ int CSound::Init() // Open the audio device and start playing sound! m_Device = SDL_OpenAudioDevice(NULL, 0, &Format, &FormatOut, 0); - if (m_Device == 0) + if(m_Device == 0) { dbg_msg("client/sound", "unable to open audio: %s", SDL_GetError()); return -1; @@ -335,7 +331,7 @@ int CSound::Init() else dbg_msg("client/sound", "sound init successful using audio driver '%s'", SDL_GetCurrentAudioDriver()); - m_MaxFrames = FormatOut.samples*2; + m_MaxFrames = FormatOut.samples * 2; m_pMixBuffer = (int *)calloc(m_MaxFrames * 2, sizeof(int)); SDL_PauseAudioDevice(m_Device, 0); @@ -359,10 +355,10 @@ int CSound::Update() m_SoundVolume = WantedVolume; lock_unlock(m_SoundLock); } -//#if defined(CONF_VIDEORECORDER) -// if(IVideo::Current() && g_Config.m_ClVideoSndEnable) -// IVideo::Current()->NextAudioFrame(Mix); -//#endif + //#if defined(CONF_VIDEORECORDER) + // if(IVideo::Current() && g_Config.m_ClVideoSndEnable) + // IVideo::Current()->NextAudioFrame(Mix); + //#endif return 0; } @@ -404,24 +400,24 @@ void CSound::RateConvert(int SampleID) return; // allocate new data - NumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate); + NumFrames = (int)((pSample->m_NumFrames / (float)pSample->m_Rate) * m_MixingRate); pNewData = (short *)calloc(NumFrames * pSample->m_Channels, sizeof(short)); for(int i = 0; i < NumFrames; i++) { // resample TODO: this should be done better, like linear at least - float a = i/(float)NumFrames; - int f = (int)(a*pSample->m_NumFrames); + float a = i / (float)NumFrames; + int f = (int)(a * pSample->m_NumFrames); if(f >= pSample->m_NumFrames) - f = pSample->m_NumFrames-1; + f = pSample->m_NumFrames - 1; // set new data if(pSample->m_Channels == 1) pNewData[i] = pSample->m_pData[f]; else if(pSample->m_Channels == 2) { - pNewData[i*2] = pSample->m_pData[f*2]; - pNewData[i*2+1] = pSample->m_pData[f*2+1]; + pNewData[i * 2] = pSample->m_pData[f * 2]; + pNewData[i * 2 + 1] = pSample->m_pData[f * 2 + 1]; } } @@ -439,8 +435,8 @@ int CSound::DecodeOpus(int SampleID, const void *pData, unsigned DataSize) CSample *pSample = &m_aSamples[SampleID]; - OggOpusFile *OpusFile = op_open_memory((const unsigned char *) pData, DataSize, NULL); - if (OpusFile) + OggOpusFile *OpusFile = op_open_memory((const unsigned char *)pData, DataSize, NULL); + if(OpusFile) { int NumChannels = op_channel_count(OpusFile, -1); int NumSamples = op_pcm_total(OpusFile, -1); // per channel! @@ -457,9 +453,9 @@ int CSound::DecodeOpus(int SampleID, const void *pData, unsigned DataSize) int Read; int Pos = 0; - while (Pos < NumSamples) + while(Pos < NumSamples) { - Read = op_read(OpusFile, pSample->m_pData + Pos*NumChannels, NumSamples*NumChannels, NULL); + Read = op_read(OpusFile, pSample->m_pData + Pos * NumChannels, NumSamples * NumChannels, NULL); Pos += Read; } @@ -574,11 +570,11 @@ int CSound::DecodeWV(int SampleID, const void *pData, unsigned DataSize) pSample->m_pData = (short *)calloc(NumSamples * NumChannels, sizeof(short)); pDst = pSample->m_pData; - for (i = 0; i < NumSamples*NumChannels; i++) + for(i = 0; i < NumSamples * NumChannels; i++) *pDst++ = (short)*pSrc++; free(pBuffer); -#ifdef CONF_WAVPACK_CLOSE_FILE +#ifdef CONF_WAVPACK_CLOSE_FILE WavpackCloseFile(pContext); #endif @@ -645,7 +641,6 @@ int CSound::LoadOpus(const char *pFilename) return SampleID; } - int CSound::LoadWV(const char *pFilename) { // don't waste memory on sound when we are stress testing @@ -761,7 +756,7 @@ float CSound::GetSampleDuration(int SampleID) if(SampleID == -1 || SampleID >= NUM_SAMPLES) return 0.0f; - return (m_aSamples[SampleID].m_NumFrames/m_aSamples[SampleID].m_Rate); + return (m_aSamples[SampleID].m_NumFrames / m_aSamples[SampleID].m_Rate); } void CSound::SetListenerPos(float x, float y) @@ -781,7 +776,7 @@ void CSound::SetVoiceVolume(CVoiceHandle Voice, float Volume) return; Volume = clamp(Volume, 0.0f, 1.0f); - m_aVoices[VoiceID].m_Vol = (int)(Volume*255.0f); + m_aVoices[VoiceID].m_Vol = (int)(Volume * 255.0f); } void CSound::SetVoiceFalloff(CVoiceHandle Voice, float Falloff) @@ -827,7 +822,7 @@ void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float offset) if(m_aVoices[VoiceID].m_pSample) { int Tick = 0; - bool IsLooping = m_aVoices[VoiceID].m_Flags&ISound::FLAG_LOOP; + bool IsLooping = m_aVoices[VoiceID].m_Flags & ISound::FLAG_LOOP; uint64 TickOffset = m_aVoices[VoiceID].m_pSample->m_Rate * offset; if(m_aVoices[VoiceID].m_pSample->m_NumFrames > 0 && IsLooping) Tick = TickOffset % m_aVoices[VoiceID].m_pSample->m_NumFrames; @@ -836,10 +831,10 @@ void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float offset) // at least 200msec off, else depend on buffer size float Threshold = maximum(0.2f * m_aVoices[VoiceID].m_pSample->m_Rate, (float)m_MaxFrames); - if(abs(m_aVoices[VoiceID].m_Tick-Tick) > Threshold) + if(abs(m_aVoices[VoiceID].m_Tick - Tick) > Threshold) { // take care of looping (modulo!) - if( !(IsLooping && (minimum(m_aVoices[VoiceID].m_Tick, Tick) + m_aVoices[VoiceID].m_pSample->m_NumFrames - maximum(m_aVoices[VoiceID].m_Tick, Tick)) <= Threshold)) + if(!(IsLooping && (minimum(m_aVoices[VoiceID].m_Tick, Tick) + m_aVoices[VoiceID].m_pSample->m_NumFrames - maximum(m_aVoices[VoiceID].m_Tick, Tick)) <= Threshold)) { m_aVoices[VoiceID].m_Tick = Tick; } @@ -880,8 +875,8 @@ void CSound::SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height) void CSound::SetChannel(int ChannelID, float Vol, float Pan) { - m_aChannels[ChannelID].m_Vol = (int)(Vol*255.0f); - m_aChannels[ChannelID].m_Pan = (int)(Pan*255.0f); // TODO: this is only on and off right now + m_aChannels[ChannelID].m_Vol = (int)(Vol * 255.0f); + m_aChannels[ChannelID].m_Pan = (int)(Pan * 255.0f); // TODO: this is only on and off right now } ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float x, float y) @@ -899,7 +894,7 @@ ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float if(!m_aVoices[id].m_pSample) { VoiceID = id; - m_NextVoice = id+1; + m_NextVoice = id + 1; break; } } @@ -929,7 +924,7 @@ ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float ISound::CVoiceHandle CSound::PlayAt(int ChannelID, int SampleID, int Flags, float x, float y) { - return Play(ChannelID, SampleID, Flags|ISound::FLAG_POS, x, y); + return Play(ChannelID, SampleID, Flags | ISound::FLAG_POS, x, y); } ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags) @@ -992,5 +987,4 @@ void CSound::StopVoice(CVoiceHandle Voice) lock_unlock(m_SoundLock); } - IEngineSound *CreateEngineSound() { return new CSound; } diff --git a/src/engine/client/steam.cpp b/src/engine/client/steam.cpp index 6c77a3784..45e473602 100644 --- a/src/engine/client/steam.cpp +++ b/src/engine/client/steam.cpp @@ -129,10 +129,10 @@ class CSteamStub : public ISteam { const char *GetPlayerName() { return 0; } const NETADDR *GetConnectAddress() { return 0; } - void ClearConnectAddress() { } - void Update() { } - void ClearGameInfo() { } - void SetGameInfo(NETADDR ServerAddr, const char *pMapName) { } + void ClearConnectAddress() {} + void Update() {} + void ClearGameInfo() {} + void SetGameInfo(NETADDR ServerAddr, const char *pMapName) {} }; ISteam *CreateSteam() diff --git a/src/engine/client/text.cpp b/src/engine/client/text.cpp index 3d828436f..bfffdb03a 100644 --- a/src/engine/client/text.cpp +++ b/src/engine/client/text.cpp @@ -1,11 +1,11 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include #include -#include #include #include +#include // ft2 texture #include @@ -17,8 +17,8 @@ enum MAX_CHARACTERS = 64, }; -#include #include +#include struct SFontSizeChar { @@ -71,7 +71,6 @@ struct CFontSizeData FT_Face *m_pFace; std::map m_Chars; - }; #define MIN_FONT_SIZE 6 @@ -135,7 +134,7 @@ struct STextContainer { STextContainer() { Reset(); } - CFont* m_pFont; + CFont *m_pFont; int m_FontSize; STextString m_StringInfo; @@ -178,7 +177,6 @@ struct STextContainer } }; - class CTextRender : public IEngineTextRender { IGraphics *m_pGraphics; @@ -192,7 +190,7 @@ class CTextRender : public IEngineTextRender SBufferContainerInfo m_DefaultTextContainerInfo; - std::vector m_Fonts; + std::vector m_Fonts; CFont *m_pCurFont; int GetFreeTextContainerIndex() @@ -218,7 +216,7 @@ class CTextRender : public IEngineTextRender m_FirstFreeTextContainerIndex = Index; } - STextContainer& GetTextContainer(int Index) + STextContainer &GetTextContainer(int Index) { if(Index >= (int)m_TextContainers.size()) { @@ -245,7 +243,7 @@ class CTextRender : public IEngineTextRender if(*pCursor == 0) return Length; if(*pCursor == '\n' || *pCursor == '\t' || *pCursor == ' ') - return Length+1; + return Length + 1; Length = str_utf8_forward(pText, Length); } } @@ -266,22 +264,22 @@ class CTextRender : public IEngineTextRender for(int y = 0; y < h; y++) for(int x = 0; x < w; x++) { - int c = pIn[y*w+x]; + int c = pIn[y * w + x]; for(int sy = -OutlineCount; sy <= OutlineCount; sy++) for(int sx = -OutlineCount; sx <= OutlineCount; sx++) { - int GetX = x+sx; - int GetY = y+sy; + int GetX = x + sx; + int GetY = y + sy; if(GetX >= 0 && GetY >= 0 && GetX < w && GetY < h) { - int Index = GetY*w+GetX; + int Index = GetY * w + GetX; if(pIn[Index] > c) c = pIn[Index]; } } - pOut[y*w+x] = c; + pOut[y * w + x] = c; } } @@ -314,7 +312,7 @@ class CTextRender : public IEngineTextRender { int NewDimensions = pFont->m_CurTextureDimensions[TextureIndex] * 2; - unsigned char *pTmpTexBuffer = new unsigned char[NewDimensions*NewDimensions]; + unsigned char *pTmpTexBuffer = new unsigned char[NewDimensions * NewDimensions]; mem_zero(pTmpTexBuffer, NewDimensions * NewDimensions * sizeof(unsigned char)); for(int y = 0; y < pFont->m_CurTextureDimensions[TextureIndex]; ++y) @@ -355,11 +353,10 @@ class CTextRender : public IEngineTextRender } // 128k * 2 of data used for rendering glyphs - unsigned char ms_aGlyphData[(1024/4) * (1024/4)]; - unsigned char ms_aGlyphDataOutlined[(1024/4) * (1024/4)]; + unsigned char ms_aGlyphData[(1024 / 4) * (1024 / 4)]; + unsigned char ms_aGlyphDataOutlined[(1024 / 4) * (1024 / 4)]; - - bool GetCharacterSpace(CFont *pFont, int TextureIndex, int Width, int Height, int& PosX, int& PosY) + bool GetCharacterSpace(CFont *pFont, int TextureIndex, int Width, int Height, int &PosX, int &PosY) { if(pFont->m_CurTextureDimensions[TextureIndex] < Width) return false; @@ -367,7 +364,7 @@ class CTextRender : public IEngineTextRender return false; // skyline bottom left algorithm - std::vector& SkylineHeights = pFont->m_TextureSkyline[TextureIndex].m_CurHeightOfPixelColumn; + std::vector &SkylineHeights = pFont->m_TextureSkyline[TextureIndex].m_CurHeightOfPixelColumn; // search a fitting area with less pixel loss int SmallestPixelLossAreaX = 0; @@ -453,7 +450,7 @@ class CTextRender : public IEngineTextRender if(GlyphIndex == 0) { - for(CFont::SFontFallBack& FallbackFont : pFont->m_FtFallbackFonts) + for(CFont::SFontFallBack &FallbackFont : pFont->m_FtFallbackFonts) { FtFace = FallbackFont.m_FtFace; FT_Set_Pixel_Sizes(FtFace, 0, pSizeData->m_FontSize); @@ -479,7 +476,7 @@ class CTextRender : public IEngineTextRender } } - if(FT_Load_Glyph(FtFace, GlyphIndex, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP)) + if(FT_Load_Glyph(FtFace, GlyphIndex, FT_LOAD_RENDER | FT_LOAD_NO_BITMAP)) { dbg_msg("pFont", "error loading glyph %d", Chr); return; @@ -500,7 +497,7 @@ class CTextRender : public IEngineTextRender for(py = 0; py < pBitmap->rows; py++) // ignore_convention for(px = 0; px < pBitmap->width; px++) // ignore_convention - ms_aGlyphData[(py+y)*Width+px+x] = pBitmap->buffer[py*pBitmap->width+px]; // ignore_convention + ms_aGlyphData[(py + y) * Width + px + x] = pBitmap->buffer[py * pBitmap->width + px]; // ignore_convention // upload the glyph int X = 0; @@ -530,7 +527,7 @@ class CTextRender : public IEngineTextRender pFontchr->m_Width = Width; pFontchr->m_OffsetX = (FtFace->glyph->metrics.horiBearingX >> 6); // ignore_convention pFontchr->m_OffsetY = -((FtFace->glyph->metrics.height >> 6) - (FtFace->glyph->metrics.horiBearingY >> 6)); - pFontchr->m_AdvanceX = (FtFace->glyph->advance.x>>6); // ignore_convention + pFontchr->m_AdvanceX = (FtFace->glyph->advance.x >> 6); // ignore_convention pFontchr->m_aUVs[0] = X; pFontchr->m_aUVs[1] = Y; @@ -546,7 +543,7 @@ class CTextRender : public IEngineTextRender if(it == pSizeData->m_Chars.end()) { // render and add character - SFontSizeChar& FontSizeChr = pSizeData->m_Chars[Chr]; + SFontSizeChar &FontSizeChr = pSizeData->m_Chars[Chr]; RenderGlyph(pFont, pSizeData, Chr); @@ -560,18 +557,17 @@ class CTextRender : public IEngineTextRender float Kerning(CFont *pFont, FT_UInt GlyphIndexLeft, FT_UInt GlyphIndexRight) { - FT_Vector Kerning = {0,0}; + FT_Vector Kerning = {0, 0}; FT_Get_Kerning(pFont->m_FtFace, GlyphIndexLeft, GlyphIndexRight, FT_KERNING_DEFAULT, &Kerning); - return (Kerning.x>>6); + return (Kerning.x >> 6); } - public: CTextRender() { m_pGraphics = 0; - m_Color = ColorRGBA(1,1,1,1); + m_Color = ColorRGBA(1, 1, 1, 1); m_OutlineColor = ColorRGBA(0, 0, 0, 0.3f); m_pCurFont = 0; @@ -612,7 +608,7 @@ public: m_DefaultTextContainerInfo.m_Stride = sizeof(STextCharQuadVertex); m_DefaultTextContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); - SBufferContainerInfo::SAttribute* pAttr = &m_DefaultTextContainerInfo.m_Attributes.back(); + SBufferContainerInfo::SAttribute *pAttr = &m_DefaultTextContainerInfo.m_Attributes.back(); pAttr->m_DataTypeCount = 2; pAttr->m_FuncType = 0; pAttr->m_Normalized = false; @@ -624,7 +620,7 @@ public: pAttr->m_DataTypeCount = 2; pAttr->m_FuncType = 0; pAttr->m_Normalized = false; - pAttr->m_pOffset = (void*)(sizeof(float) * 2); + pAttr->m_pOffset = (void *)(sizeof(float) * 2); pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_VertBufferBindingIndex = -1; m_DefaultTextContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); @@ -632,7 +628,7 @@ public: pAttr->m_DataTypeCount = 4; pAttr->m_FuncType = 0; pAttr->m_Normalized = true; - pAttr->m_pOffset = (void*)(sizeof(float) * 2 + sizeof(float) * 2); + pAttr->m_pOffset = (void *)(sizeof(float) * 2 + sizeof(float) * 2); pAttr->m_Type = GRAPHICS_TYPE_UNSIGNED_BYTE; pAttr->m_VertBufferBindingIndex = -1; @@ -730,7 +726,7 @@ public: FT_Done_Face(pFont->m_FtFace); - for(CFont::SFontFallBack& FallbackFont : pFont->m_FtFallbackFonts) + for(CFont::SFontFallBack &FallbackFont : pFont->m_FtFallbackFonts) { FT_Done_Face(FallbackFont.m_FtFace); } @@ -873,9 +869,9 @@ public: float UVScale = 1.0f / pFont->m_CurTextureDimensions[0]; const char *pCurrent = (char *)pText; - const char *pEnd = pCurrent+Length; + const char *pEnd = pCurrent + Length; - if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) + if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) { DrawX = pCursor->m_X; DrawY = pCursor->m_Y; @@ -888,7 +884,7 @@ public: LineCount = pCursor->m_LineCount; - if(pCursor->m_Flags&TEXTFLAG_RENDER) + if(pCursor->m_Flags & TEXTFLAG_RENDER) { // make sure there are no vertices Graphics()->FlushVertices(); @@ -903,7 +899,7 @@ public: { Graphics()->TextureSet(pFont->m_aTextures[1]); Graphics()->QuadsBegin(); - Graphics()->SetColor(m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a*m_Color.a); + Graphics()->SetColor(m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a * m_Color.a); } } @@ -914,9 +910,9 @@ public: { int NewLine = 0; const char *pBatchEnd = pEnd; - if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END)) + if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags & TEXTFLAG_STOP_AT_END)) { - int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd-pCurrent)); + int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd - pCurrent)); CTextCursor Compare = *pCursor; Compare.m_X = DrawX; Compare.m_Y = DrawY; @@ -924,7 +920,7 @@ public: Compare.m_LineWidth = -1; TextEx(&Compare, pCurrent, Wlen); - if(Compare.m_X-DrawX > pCursor->m_LineWidth) + if(Compare.m_X - DrawX > pCursor->m_LineWidth) { // word can't be fitted in one line, cut it CTextCursor Cutter = *pCursor; @@ -943,7 +939,7 @@ public: if(WordGlyphs <= 3) // if we can't place 3 chars of the word on this line, take the next Wlen = 0; } - else if(Compare.m_X-pCursor->m_StartX > pCursor->m_LineWidth) + else if(Compare.m_X - pCursor->m_StartX > pCursor->m_LineWidth) { NewLine = 1; Wlen = 0; @@ -956,7 +952,7 @@ public: int NextCharacter = str_utf8_decode(&pTmp); while(pCurrent < pBatchEnd) { - pCursor->m_CharCount += pTmp-pCurrent; + pCursor->m_CharCount += pTmp - pCurrent; int Character = NextCharacter; pCurrent = pTmp; NextCharacter = str_utf8_decode(&pTmp); @@ -968,7 +964,7 @@ public: DrawX = pCursor->m_StartX; DrawY += Size; - if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -982,25 +978,25 @@ public: SFontSizeChar *pChr = GetChar(pFont, pSizeData, Character); if(pChr) { - bool ApplyBearingX = !(((m_RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (m_RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); - float Advance = ((((m_RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale; + bool ApplyBearingX = !(((m_RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (m_RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); + float Advance = ((((m_RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale; float CharKerning = 0.f; - if((m_RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0) - CharKerning = Kerning(pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size; + if((m_RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0) + CharKerning = Kerning(pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size; LastCharGlyphIndex = pChr->m_GlyphIndex; - if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning)+Advance*Size-pCursor->m_StartX > pCursor->m_LineWidth) + if(pCursor->m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth) { // we hit the end of the line, no more to render or count pCurrent = pEnd; break; } - float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size; - float CharWidth = pChr->m_Width*Scale*Size; + float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size; + float CharWidth = pChr->m_Width * Scale * Size; - if(pCursor->m_Flags&TEXTFLAG_RENDER && m_Color.a != 0.f) + if(pCursor->m_Flags & TEXTFLAG_RENDER && m_Color.a != 0.f) { if(Graphics()->IsTextBufferingEnabled()) Graphics()->QuadsSetSubset(pChr->m_aUVs[0], pChr->m_aUVs[3], pChr->m_aUVs[2], pChr->m_aUVs[1]); @@ -1009,22 +1005,22 @@ public: float Y = (DrawY + Size); float BearingY = 0.f; - BearingY = (((m_RenderFlags&TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY*Scale*Size)); + BearingY = (((m_RenderFlags & TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY * Scale * Size)); - if((m_RenderFlags&TEXT_RENDER_FLAG_NO_OVERSIZE) != 0) + if((m_RenderFlags & TEXT_RENDER_FLAG_NO_OVERSIZE) != 0) { - if(pChr->m_Height*Scale*Size + BearingY > Size) - BearingY -= pChr->m_Height*Scale*Size - Size; + if(pChr->m_Height * Scale * Size + BearingY > Size) + BearingY -= pChr->m_Height * Scale * Size - Size; } - IGraphics::CQuadItem QuadItem((DrawX + CharKerning) + BearingX, Y - BearingY, CharWidth, -pChr->m_Height*Scale*Size); + IGraphics::CQuadItem QuadItem((DrawX + CharKerning) + BearingX, Y - BearingY, CharWidth, -pChr->m_Height * Scale * Size); Graphics()->QuadsDrawTL(&QuadItem, 1); } - if(NextCharacter == 0 && (m_RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) + if(NextCharacter == 0 && (m_RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) DrawX += BearingX + CharKerning + CharWidth; else - DrawX += Advance*Size + CharKerning; + DrawX += Advance * Size + CharKerning; pCursor->m_GlyphCount++; ++CharacterCounter; @@ -1035,7 +1031,7 @@ public: { DrawX = pCursor->m_StartX; DrawY += Size; - if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -1045,11 +1041,11 @@ public: } } - if(pCursor->m_Flags&TEXTFLAG_RENDER) + if(pCursor->m_Flags & TEXTFLAG_RENDER) { if(Graphics()->IsTextBufferingEnabled()) { - float OutlineColor[4] = { m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a*m_Color.a }; + float OutlineColor[4] = {m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a * m_Color.a}; Graphics()->TextQuadsEnd(pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], OutlineColor); } else @@ -1083,7 +1079,7 @@ public: return -1; int ContainerIndex = GetFreeTextContainerIndex(); - STextContainer& TextContainer = GetTextContainer(ContainerIndex); + STextContainer &TextContainer = GetTextContainer(ContainerIndex); TextContainer.m_pFont = pFont; CFontSizeData *pSizeData = NULL; @@ -1159,7 +1155,7 @@ public: virtual void AppendTextContainer(CTextCursor *pCursor, int TextContainerIndex, const char *pText) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); CFontSizeData *pSizeData = NULL; @@ -1203,7 +1199,7 @@ public: int RenderFlags = TextContainer.m_RenderFlags; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) { DrawX = pCursor->m_X; DrawY = pCursor->m_Y; @@ -1223,7 +1219,7 @@ public: { int NewLine = 0; const char *pBatchEnd = pEnd; - if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END)) + if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags & TEXTFLAG_STOP_AT_END)) { int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd - pCurrent)); CTextCursor Compare = *pCursor; @@ -1265,7 +1261,7 @@ public: int NextCharacter = str_utf8_decode(&pTmp); while(pCurrent < pBatchEnd) { - TextContainer.m_CharCount += pTmp-pCurrent; + TextContainer.m_CharCount += pTmp - pCurrent; int Character = NextCharacter; pCurrent = pTmp; NextCharacter = str_utf8_decode(&pTmp); @@ -1277,7 +1273,7 @@ public: DrawX = pCursor->m_StartX; DrawY += Size; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -1291,38 +1287,38 @@ public: SFontSizeChar *pChr = GetChar(TextContainer.m_pFont, pSizeData, Character); if(pChr) { - bool ApplyBearingX = !(((RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); - float Advance = ((((RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale; + bool ApplyBearingX = !(((RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); + float Advance = ((((RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale; float CharKerning = 0.f; - if((RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0) - CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size; + if((RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0) + CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size; LastCharGlyphIndex = pChr->m_GlyphIndex; - if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth) + if(pCursor->m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth) { // we hit the end of the line, no more to render or count pCurrent = pEnd; break; } - float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size; - float CharWidth = pChr->m_Width*Scale*Size; + float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size; + float CharWidth = pChr->m_Width * Scale * Size; // don't add text that isn't drawn, the color overwrite is used for that if(m_Color.a != 0.f) { TextContainer.m_StringInfo.m_CharacterQuads.push_back(STextCharQuad()); - STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads.back(); + STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads.back(); float Y = (DrawY + Size); - float BearingY = (((RenderFlags&TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY*Scale*Size)); + float BearingY = (((RenderFlags & TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY * Scale * Size)); - if((RenderFlags&TEXT_RENDER_FLAG_NO_OVERSIZE) != 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_OVERSIZE) != 0) { - if(pChr->m_Height*Scale*Size + BearingY > Size) - BearingY -= pChr->m_Height*Scale*Size - Size; + if(pChr->m_Height * Scale * Size + BearingY > Size) + BearingY -= pChr->m_Height * Scale * Size - Size; } TextCharQuad.m_Vertices[0].m_X = (DrawX + CharKerning) + BearingX; @@ -1344,7 +1340,7 @@ public: TextCharQuad.m_Vertices[1].m_Color.m_A = (unsigned char)(m_Color.a * 255.f); TextCharQuad.m_Vertices[2].m_X = (DrawX + CharKerning) + BearingX + CharWidth; - TextCharQuad.m_Vertices[2].m_Y = Y - BearingY - pChr->m_Height*Scale*Size; + TextCharQuad.m_Vertices[2].m_Y = Y - BearingY - pChr->m_Height * Scale * Size; TextCharQuad.m_Vertices[2].m_U = pChr->m_aUVs[2]; TextCharQuad.m_Vertices[2].m_V = pChr->m_aUVs[1]; TextCharQuad.m_Vertices[2].m_Color.m_R = (unsigned char)(m_Color.r * 255.f); @@ -1353,7 +1349,7 @@ public: TextCharQuad.m_Vertices[2].m_Color.m_A = (unsigned char)(m_Color.a * 255.f); TextCharQuad.m_Vertices[3].m_X = (DrawX + CharKerning) + BearingX; - TextCharQuad.m_Vertices[3].m_Y = Y - BearingY - pChr->m_Height*Scale*Size; + TextCharQuad.m_Vertices[3].m_Y = Y - BearingY - pChr->m_Height * Scale * Size; TextCharQuad.m_Vertices[3].m_U = pChr->m_aUVs[0]; TextCharQuad.m_Vertices[3].m_V = pChr->m_aUVs[1]; TextCharQuad.m_Vertices[3].m_Color.m_R = (unsigned char)(m_Color.r * 255.f); @@ -1362,7 +1358,7 @@ public: TextCharQuad.m_Vertices[3].m_Color.m_A = (unsigned char)(m_Color.a * 255.f); } - if(NextCharacter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) + if(NextCharacter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) DrawX += BearingX + CharKerning + CharWidth; else DrawX += Advance * Size + CharKerning; @@ -1375,7 +1371,7 @@ public: { DrawX = pCursor->m_StartX; DrawY += Size; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -1419,7 +1415,7 @@ public: virtual void RecreateTextContainerSoft(CTextCursor *pCursor, int TextContainerIndex, const char *pText) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); TextContainer.m_StringInfo.m_CharacterQuads.clear(); TextContainer.m_StringInfo.m_QuadNum = 0; // the text buffer gets then recreated by the appended quads @@ -1428,7 +1424,7 @@ public: virtual void SetTextContainerSelection(int TextContainerIndex, const char *pText, int CursorPos, int SelectionStart, int SelectionEnd) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); CFontSizeData *pSizeData = NULL; @@ -1467,7 +1463,7 @@ public: int RenderFlags = TextContainer.m_RenderFlags; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0) { DrawX = TextContainer.m_X; DrawY = TextContainer.m_Y; @@ -1497,7 +1493,7 @@ public: { int NewLine = 0; const char *pBatchEnd = pEnd; - if(TextContainer.m_LineWidth > 0 && !(TextContainer.m_Flags&TEXTFLAG_STOP_AT_END)) + if(TextContainer.m_LineWidth > 0 && !(TextContainer.m_Flags & TEXTFLAG_STOP_AT_END)) { CTextCursor FakeCursor; SetCursor(&FakeCursor, DrawX, DrawY, TextContainer.m_UnscaledFontSize, TextContainer.m_Flags); @@ -1551,7 +1547,7 @@ public: int NextCharacter = str_utf8_decode(&pTmp); while(pCurrent < pBatchEnd) { - TextContainer.m_CharCount += pTmp-pCurrent; + TextContainer.m_CharCount += pTmp - pCurrent; int Character = NextCharacter; pCurrent = pTmp; NextCharacter = str_utf8_decode(&pTmp); @@ -1563,7 +1559,7 @@ public: DrawX = TextContainer.m_StartX; DrawY += Size; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -1577,15 +1573,15 @@ public: SFontSizeChar *pChr = GetChar(TextContainer.m_pFont, pSizeData, Character); if(pChr) { - bool ApplyBearingX = !(((RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); - float Advance = ((((RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + (!ApplyBearingX ? (-pChr->m_OffsetX) : 0.f)))) * Scale; + bool ApplyBearingX = !(((RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0)); + float Advance = ((((RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + (!ApplyBearingX ? (-pChr->m_OffsetX) : 0.f)))) * Scale; float CharKerning = 0.f; - if((RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0) - CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size; + if((RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0) + CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size; LastCharGlyphIndex = pChr->m_GlyphIndex; - if(TextContainer.m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - TextContainer.m_StartX > TextContainer.m_LineWidth) + if(TextContainer.m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - TextContainer.m_StartX > TextContainer.m_LineWidth) { // we hit the end of the line, no more to render or count pCurrent = pEnd; @@ -1604,10 +1600,10 @@ public: SelectionQuads.push_back(IGraphics::CQuadItem((DrawX + CharKerning), DrawY, Advance * Size, MaxRowHeight)); } - float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size; - float CharWidth = pChr->m_Width*Scale*Size; + float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size; + float CharWidth = pChr->m_Width * Scale * Size; - if(NextCharacter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) + if(NextCharacter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0) DrawX += BearingX + CharKerning + CharWidth; else DrawX += Advance * Size + CharKerning; @@ -1622,7 +1618,7 @@ public: { DrawX = TextContainer.m_StartX; DrawY += Size; - if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; @@ -1647,7 +1643,7 @@ public: virtual void DeleteTextContainer(int TextContainerIndex) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); if(Graphics()->IsTextBufferingEnabled()) { if(TextContainer.m_StringInfo.m_QuadBufferContainerIndex != -1) @@ -1660,7 +1656,7 @@ public: virtual void RenderTextContainer(int TextContainerIndex, STextRenderColor *pTextColor, STextRenderColor *pTextOutlineColor) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); CFont *pFont = TextContainer.m_pFont; if(TextContainer.m_StringInfo.m_SelectionQuadContainerIndex != -1) @@ -1680,7 +1676,7 @@ public: { Graphics()->TextureClear(); // render buffered text - Graphics()->RenderText(TextContainer.m_StringInfo.m_QuadBufferContainerIndex, TextContainer.m_StringInfo.m_QuadNum, pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], (float*)pTextColor, (float*)pTextOutlineColor); + Graphics()->RenderText(TextContainer.m_StringInfo.m_QuadBufferContainerIndex, TextContainer.m_StringInfo.m_QuadNum, pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], (float *)pTextColor, (float *)pTextOutlineColor); } else { @@ -1694,7 +1690,7 @@ public: for(size_t i = 0; i < TextContainer.m_StringInfo.m_QuadNum; ++i) { - STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i]; + STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i]; Graphics()->SetColor(TextCharQuad.m_Vertices[0].m_Color.m_R / 255.f * pTextOutlineColor->m_R, TextCharQuad.m_Vertices[0].m_Color.m_G / 255.f * pTextOutlineColor->m_G, TextCharQuad.m_Vertices[0].m_Color.m_B / 255.f * pTextOutlineColor->m_B, TextCharQuad.m_Vertices[0].m_Color.m_A / 255.f * pTextOutlineColor->m_A); @@ -1711,7 +1707,7 @@ public: for(size_t i = 0; i < TextContainer.m_StringInfo.m_QuadNum; ++i) { - STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i]; + STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i]; unsigned char CR = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_R) * pTextColor->m_R); unsigned char CG = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_G) * pTextColor->m_G); unsigned char CB = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_B) * pTextColor->m_B); @@ -1725,7 +1721,6 @@ public: else Graphics()->QuadsEnd(); - // reset Graphics()->SetColor(1.f, 1.f, 1.f, 1.f); } @@ -1733,13 +1728,13 @@ public: virtual void RenderTextContainer(int TextContainerIndex, STextRenderColor *pTextColor, STextRenderColor *pTextOutlineColor, float X, float Y) { - STextContainer& TextContainer = GetTextContainer(TextContainerIndex); + STextContainer &TextContainer = GetTextContainer(TextContainerIndex); // remap the current screen, after render revert the change again float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - if((TextContainer.m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) + if((TextContainer.m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0) { float FakeToScreenX = (Graphics()->ScreenWidth() / (ScreenX1 - ScreenX0)); float FakeToScreenY = (Graphics()->ScreenHeight() / (ScreenY1 - ScreenY0)); @@ -1758,7 +1753,7 @@ public: virtual void UploadEntityLayerText(void *pTexBuff, int ImageColorChannelCount, int TexWidth, int TexHeight, int TexSubWidth, int TexSubHeight, const char *pText, int Length, float x, float y, int FontSize) { - if (FontSize < 1) + if(FontSize < 1) return; const char *pCurrent = (char *)pText; @@ -1778,7 +1773,7 @@ public: FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, FontSize); - if(FT_Load_Char(pFont->m_FtFace, NextCharacter, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP)) + if(FT_Load_Char(pFont->m_FtFace, NextCharacter, FT_LOAD_RENDER | FT_LOAD_NO_BITMAP)) { dbg_msg("pFont", "error loading glyph %d", NextCharacter); pCurrent = pTmp; @@ -1789,7 +1784,7 @@ public: int SlotW = pBitmap->width; int SlotH = pBitmap->rows; - int SlotSize = SlotW*SlotH; + int SlotSize = SlotW * SlotH; // prepare glyph data mem_zero(ms_aGlyphData, SlotSize); @@ -1799,11 +1794,11 @@ public: for(py = 0; py < (unsigned)SlotH; py++) // ignore_convention for(px = 0; px < (unsigned)SlotW; px++) { - ms_aGlyphData[(py)*SlotW + px] = pBitmap->buffer[py*pBitmap->width + px]; // ignore_convention + ms_aGlyphData[(py)*SlotW + px] = pBitmap->buffer[py * pBitmap->width + px]; // ignore_convention } } - uint8_t* pImageBuff = (uint8_t*)pTexBuff; + uint8_t *pImageBuff = (uint8_t *)pTexBuff; for(int OffY = 0; OffY < SlotH; ++OffY) { for(int OffX = 0; OffX < SlotW; ++OffX) @@ -1838,7 +1833,7 @@ public: int FontSize = 100.f / ((float)WidthOfText / (float)MaxWidth); - if (MaxSize > 0 && FontSize > MaxSize) + if(MaxSize > 0 && FontSize > MaxSize) FontSize = MaxSize; return FontSize; @@ -1852,7 +1847,7 @@ public: int WidthOfText = 0; FT_Set_Pixel_Sizes(pFont->m_FtFace, FontWidth, FontHeight); - while (pCurrent < pEnd) + while(pCurrent < pEnd) { const char *pTmp = pCurrent; int NextCharacter = str_utf8_decode(&pTmp); @@ -1886,7 +1881,7 @@ public: for(size_t i = 0; i < m_TextContainers.size(); ++i) if(m_TextContainers[i].m_StringInfo.m_QuadBufferContainerIndex != -1) FoundTextContainer = true; - if (FoundTextContainer) + if(FoundTextContainer) { dbg_msg("text render", "%s", "Found non empty text container"); dbg_assert(false, "text container was not empty"); diff --git a/src/engine/client/updater.cpp b/src/engine/client/updater.cpp index 625fca9d3..0004c85bd 100644 --- a/src/engine/client/updater.cpp +++ b/src/engine/client/updater.cpp @@ -1,16 +1,16 @@ #include "updater.h" #include -#include -#include #include +#include #include #include +#include #include #include // system -using std::string; using std::map; +using std::string; class CUpdaterFetchTask : public CGetFile { @@ -176,14 +176,14 @@ void CUpdater::Update() { switch(m_State) { - case IUpdater::GOT_MANIFEST: - PerformUpdate(); - break; - case IUpdater::MOVE_FILES: - CommitUpdate(); - break; - default: - return; + case IUpdater::GOT_MANIFEST: + PerformUpdate(); + break; + case IUpdater::MOVE_FILES: + CommitUpdate(); + break; + default: + return; } } @@ -206,16 +206,16 @@ bool CUpdater::ReplaceClient() str_format(aPath, sizeof(aPath), "update/%s", m_aClientExecTmp); Success &= m_pStorage->RenameBinaryFile(aPath, PLAT_CLIENT_EXEC); } - #if !defined(CONF_FAMILY_WINDOWS) - m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, aPath, sizeof aPath); - char aBuf[512]; - str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); - if(system(aBuf)) - { - dbg_msg("updater", "ERROR: failed to set client executable bit"); - Success = false; - } - #endif +#if !defined(CONF_FAMILY_WINDOWS) + m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, aPath, sizeof aPath); + char aBuf[512]; + str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); + if(system(aBuf)) + { + dbg_msg("updater", "ERROR: failed to set client executable bit"); + Success = false; + } +#endif return Success; } @@ -230,16 +230,16 @@ bool CUpdater::ReplaceServer() Success &= m_pStorage->RenameBinaryFile(PLAT_SERVER_EXEC, SERVER_EXEC ".old"); str_format(aPath, sizeof(aPath), "update/%s", m_aServerExecTmp); Success &= m_pStorage->RenameBinaryFile(aPath, PLAT_SERVER_EXEC); - #if !defined(CONF_FAMILY_WINDOWS) - m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, aPath, sizeof aPath); - char aBuf[512]; - str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); - if (system(aBuf)) - { - dbg_msg("updater", "ERROR: failed to set server executable bit"); - Success = false; - } - #endif +#if !defined(CONF_FAMILY_WINDOWS) + m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, aPath, sizeof aPath); + char aBuf[512]; + str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); + if(system(aBuf)) + { + dbg_msg("updater", "ERROR: failed to set server executable bit"); + Success = false; + } +#endif return Success; } @@ -391,14 +391,14 @@ void CUpdater::CommitUpdate() void CUpdater::WinXpRestart() { - char aBuf[512]; - IOHANDLE bhFile = io_open(m_pStorage->GetBinaryPath("du.bat", aBuf, sizeof aBuf), IOFLAG_WRITE); - if(!bhFile) - return; - char bBuf[512]; - str_format(bBuf, sizeof(bBuf), ":_R\r\ndel \"" PLAT_CLIENT_EXEC "\"\r\nif exist \"" PLAT_CLIENT_EXEC "\" goto _R\r\n:_T\r\nmove /y \"update\\%s\" \"" PLAT_CLIENT_EXEC "\"\r\nif not exist \"" PLAT_CLIENT_EXEC "\" goto _T\r\nstart " PLAT_CLIENT_EXEC "\r\ndel \"du.bat\"\r\n", m_aClientExecTmp); - io_write(bhFile, bBuf, str_length(bBuf)); - io_close(bhFile); - shell_execute(aBuf); - m_pClient->Quit(); + char aBuf[512]; + IOHANDLE bhFile = io_open(m_pStorage->GetBinaryPath("du.bat", aBuf, sizeof aBuf), IOFLAG_WRITE); + if(!bhFile) + return; + char bBuf[512]; + str_format(bBuf, sizeof(bBuf), ":_R\r\ndel \"" PLAT_CLIENT_EXEC "\"\r\nif exist \"" PLAT_CLIENT_EXEC "\" goto _R\r\n:_T\r\nmove /y \"update\\%s\" \"" PLAT_CLIENT_EXEC "\"\r\nif not exist \"" PLAT_CLIENT_EXEC "\" goto _T\r\nstart " PLAT_CLIENT_EXEC "\r\ndel \"du.bat\"\r\n", m_aClientExecTmp); + io_write(bhFile, bBuf, str_length(bBuf)); + io_close(bhFile); + shell_execute(aBuf); + m_pClient->Quit(); } diff --git a/src/engine/client/updater.h b/src/engine/client/updater.h index 4ae05fddd..5ba3fadbd 100644 --- a/src/engine/client/updater.h +++ b/src/engine/client/updater.h @@ -1,8 +1,8 @@ #ifndef ENGINE_CLIENT_UPDATER_H #define ENGINE_CLIENT_UPDATER_H -#include #include +#include #include #include @@ -10,20 +10,20 @@ #define SERVER_EXEC "DDNet-Server" #if defined(CONF_FAMILY_WINDOWS) - #define PLAT_EXT ".exe" - #define PLAT_NAME CONF_PLATFORM_STRING +#define PLAT_EXT ".exe" +#define PLAT_NAME CONF_PLATFORM_STRING #elif defined(CONF_FAMILY_UNIX) - #define PLAT_EXT "" - #if defined(CONF_ARCH_IA32) - #define PLAT_NAME CONF_PLATFORM_STRING "-x86" - #elif defined(CONF_ARCH_AMD64) - #define PLAT_NAME CONF_PLATFORM_STRING "-x86_64" - #else - #define PLAT_NAME CONF_PLATFORM_STRING "-unsupported" - #endif +#define PLAT_EXT "" +#if defined(CONF_ARCH_IA32) +#define PLAT_NAME CONF_PLATFORM_STRING "-x86" +#elif defined(CONF_ARCH_AMD64) +#define PLAT_NAME CONF_PLATFORM_STRING "-x86_64" #else - #define PLAT_EXT "" - #define PLAT_NAME "unsupported-unsupported" +#define PLAT_NAME CONF_PLATFORM_STRING "-unsupported" +#endif +#else +#define PLAT_EXT "" +#define PLAT_NAME "unsupported-unsupported" #endif #define PLAT_CLIENT_DOWN CLIENT_EXEC "-" PLAT_NAME PLAT_EXT diff --git a/src/engine/client/video.cpp b/src/engine/client/video.cpp index 2c7d63565..97bf7c2dc 100644 --- a/src/engine/client/video.cpp +++ b/src/engine/client/video.cpp @@ -1,8 +1,8 @@ #if defined(CONF_VIDEORECORDER) -#include #include #include +#include #include "video.h" @@ -13,7 +13,7 @@ const size_t FORMAT_NCHANNELS = 3; static LOCK g_WriteLock = 0; -CVideo::CVideo(CGraphics_Threaded* pGraphics, IStorage* pStorage, IConsole *pConsole, int Width, int Height, const char *pName) : +CVideo::CVideo(CGraphics_Threaded *pGraphics, IStorage *pStorage, IConsole *pConsole, int Width, int Height, const char *pName) : m_pGraphics(pGraphics), m_pStorage(pStorage), m_pConsole(pConsole), @@ -47,7 +47,7 @@ CVideo::CVideo(CGraphics_Threaded* pGraphics, IStorage* pStorage, IConsole *pCon // TODO: m_HasAudio = g_Config.m_ClVideoSndEnable; - m_SndBufferSize = g_Config.m_SndBufferSize; + m_SndBufferSize = g_Config.m_SndBufferSize; dbg_assert(ms_pCurrentVideo == 0, "ms_pCurrentVideo is NOT set to NULL while creating a new Video."); @@ -98,7 +98,6 @@ void CVideo::Start() m_pPixels = (uint8_t *)malloc(NVals * sizeof(GLubyte)); m_pRGB = (uint8_t *)malloc(NVals * sizeof(uint8_t)); - /* Add the audio and video streams using the default format codecs * and initialize the codecs. */ if(m_pFormat->video_codec != AV_CODEC_ID_NONE) @@ -152,8 +151,7 @@ void CVideo::Start() m_VideoStream.pSwsCtx, m_VideoStream.pEnc->width, m_VideoStream.pEnc->height, AV_PIX_FMT_RGB24, m_VideoStream.pEnc->width, m_VideoStream.pEnc->height, AV_PIX_FMT_YUV420P, - 0, 0, 0, 0 - ); + 0, 0, 0, 0); } /* Write the stream header, if any. */ @@ -195,7 +193,7 @@ void CVideo::Stop() if(m_HasAudio) CloseStream(&m_AudioStream); - //fclose(m_dbgfile); + //fclose(m_dbgfile); if(!(m_pFormat->flags & AVFMT_NOFILE)) avio_closep(&m_pFormatContext->pb); @@ -252,7 +250,7 @@ void CVideo::NextVideoFrame() //dbg_msg("video_recorder", "called"); ms_Time += ms_TickTime; - ms_LocalTime = (ms_Time-ms_LocalStartTime)/(float)time_freq(); + ms_LocalTime = (ms_Time - ms_LocalStartTime) / (float)time_freq(); m_NextFrame = true; m_Vframe += 1; @@ -268,7 +266,7 @@ void CVideo::NextAudioFrameTimeline() if(m_Recording && m_HasAudio) { //if(m_Vframe * m_AudioStream.pEnc->sample_rate / m_FPS >= m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size) - if(m_VideoStream.pEnc->frame_number * (double)m_AudioStream.pEnc->sample_rate / m_FPS >= (double)m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size) + if(m_VideoStream.pEnc->frame_number * (double)m_AudioStream.pEnc->sample_rate / m_FPS >= (double)m_AudioStream.pEnc->frame_number * m_AudioStream.pEnc->frame_size) { m_NextAudioFrame = true; } @@ -282,7 +280,7 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames)) m_ProcessingAudioFrame = true; //dbg_msg("video recorder", "video_frame: %lf", (double)(m_Vframe/m_FPS)); //if((double)(m_Vframe/m_FPS) < m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size/m_AudioStream.pEnc->sample_rate) - //return; + //return; Mix(m_aBuffer, ALEN); //m_AudioStream.pFrame->pts = m_AudioStream.pEnc->frame_number; //dbg_msg("video_recorder", "aframe: %d", m_AudioStream.pEnc->frame_number); @@ -297,9 +295,9 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames)) int DstNbSamples; av_samples_fill_arrays( - (uint8_t**)m_AudioStream.pTmpFrame->data, + (uint8_t **)m_AudioStream.pTmpFrame->data, 0, // pointer to linesize (int*) - (const uint8_t*)m_aBuffer, + (const uint8_t *)m_aBuffer, 2, // channels m_AudioStream.pTmpFrame->nb_samples, AV_SAMPLE_FMT_S16, @@ -309,17 +307,15 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames)) DstNbSamples = av_rescale_rnd( swr_get_delay( m_AudioStream.pSwrCtx, - m_AudioStream.pEnc->sample_rate - ) + m_AudioStream.pTmpFrame->nb_samples, - + m_AudioStream.pEnc->sample_rate) + + m_AudioStream.pTmpFrame->nb_samples, + m_AudioStream.pEnc->sample_rate, - m_AudioStream.pEnc->sample_rate, AV_ROUND_UP - ); + m_AudioStream.pEnc->sample_rate, AV_ROUND_UP); // dbg_msg("video_recorder", "DstNbSamples: %d", DstNbSamples); // fwrite(m_aBuffer, sizeof(short), 2048, m_dbgfile); - int Ret = av_frame_make_writable(m_AudioStream.pFrame); if(Ret < 0) { @@ -333,8 +329,7 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames)) m_AudioStream.pFrame->data, m_AudioStream.pFrame->nb_samples, (const uint8_t **)m_AudioStream.pTmpFrame->data, - m_AudioStream.pTmpFrame->nb_samples - ); + m_AudioStream.pTmpFrame->nb_samples); if(Ret < 0) { @@ -363,9 +358,9 @@ void CVideo::FillAudioFrame() void CVideo::FillVideoFrame() { - const int InLinesize[1] = { 3 * m_VideoStream.pEnc->width }; - sws_scale(m_VideoStream.pSwsCtx, (const uint8_t * const *)&m_pRGB, InLinesize, 0, - m_VideoStream.pEnc->height, m_VideoStream.pFrame->data, m_VideoStream.pFrame->linesize); + const int InLinesize[1] = {3 * m_VideoStream.pEnc->width}; + sws_scale(m_VideoStream.pSwsCtx, (const uint8_t *const *)&m_pRGB, InLinesize, 0, + m_VideoStream.pEnc->height, m_VideoStream.pFrame->data, m_VideoStream.pFrame->linesize); } void CVideo::ReadRGBFromGL() @@ -389,10 +384,9 @@ void CVideo::ReadRGBFromGL() } } - -AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height) +AVFrame *CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height) { - AVFrame* pPicture; + AVFrame *pPicture; int Ret; pPicture = av_frame_alloc(); @@ -400,7 +394,7 @@ AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height) return NULL; pPicture->format = PixFmt; - pPicture->width = Width; + pPicture->width = Width; pPicture->height = Height; /* allocate the buffers for the frame data */ @@ -414,8 +408,7 @@ AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height) return pPicture; } - -AVFrame* CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples) +AVFrame *CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples) { AVFrame *Frame = av_frame_alloc(); int Ret; @@ -447,8 +440,8 @@ AVFrame* CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLa bool CVideo::OpenVideo() { int Ret; - AVCodecContext* c = m_VideoStream.pEnc; - AVDictionary* opt = 0; + AVCodecContext *c = m_VideoStream.pEnc; + AVDictionary *opt = 0; av_dict_copy(&opt, m_pOptDict, 0); @@ -543,22 +536,22 @@ bool CVideo::OpenAudio() return false; } - /* set options */ - av_opt_set_int(m_AudioStream.pSwrCtx, "in_channel_count", 2, 0); - av_opt_set_int(m_AudioStream.pSwrCtx, "in_sample_rate", g_Config.m_SndRate, 0); - av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0); - av_opt_set_int(m_AudioStream.pSwrCtx, "out_channel_count", c->channels, 0); - av_opt_set_int(m_AudioStream.pSwrCtx, "out_sample_rate", c->sample_rate, 0); - av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "out_sample_fmt", c->sample_fmt, 0); + /* set options */ + av_opt_set_int(m_AudioStream.pSwrCtx, "in_channel_count", 2, 0); + av_opt_set_int(m_AudioStream.pSwrCtx, "in_sample_rate", g_Config.m_SndRate, 0); + av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0); + av_opt_set_int(m_AudioStream.pSwrCtx, "out_channel_count", c->channels, 0); + av_opt_set_int(m_AudioStream.pSwrCtx, "out_sample_rate", c->sample_rate, 0); + av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "out_sample_fmt", c->sample_fmt, 0); - /* initialize the resampling context */ - if((Ret = swr_init(m_AudioStream.pSwrCtx)) < 0) - { - dbg_msg("video_recorder", "Failed to initialize the resampling context"); - return false; - } + /* initialize the resampling context */ + if((Ret = swr_init(m_AudioStream.pSwrCtx)) < 0) + { + dbg_msg("video_recorder", "Failed to initialize the resampling context"); + return false; + } - return true; + return true; } /* Add an output stream. */ @@ -567,7 +560,7 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp AVCodecContext *c; /* find the encoder */ - *ppCodec= avcodec_find_encoder(CodecId); + *ppCodec = avcodec_find_encoder(CodecId); if(!(*ppCodec)) { dbg_msg("video_recorder", "Could not find encoder for '%s'", @@ -581,7 +574,7 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp dbg_msg("video_recorder", "Could not allocate stream"); return false; } - pStream->pSt->id = pOC->nb_streams-1; + pStream->pSt->id = pOC->nb_streams - 1; c = avcodec_alloc_context3(*ppCodec); if(!c) { @@ -590,79 +583,79 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp } pStream->pEnc = c; - switch ((*ppCodec)->type) + switch((*ppCodec)->type) { - case AVMEDIA_TYPE_AUDIO: + case AVMEDIA_TYPE_AUDIO: - // m_MixingRate = g_Config.m_SndRate; - // - // // Set 16-bit stereo audio at 22Khz - // Format.freq = g_Config.m_SndRate; // ignore_convention - // Format.format = AUDIO_S16; // ignore_convention - // Format.channels = 2; // ignore_convention - // Format.samples = g_Config.m_SndBufferSize; // ignore_convention + // m_MixingRate = g_Config.m_SndRate; + // + // // Set 16-bit stereo audio at 22Khz + // Format.freq = g_Config.m_SndRate; // ignore_convention + // Format.format = AUDIO_S16; // ignore_convention + // Format.channels = 2; // ignore_convention + // Format.samples = g_Config.m_SndBufferSize; // ignore_convention - c->sample_fmt = (*ppCodec)->sample_fmts ? (*ppCodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; - c->bit_rate = g_Config.m_SndRate * 2 * 16; - c->frame_size = m_SndBufferSize; - c->sample_rate = g_Config.m_SndRate; - if((*ppCodec)->supported_samplerates) + c->sample_fmt = (*ppCodec)->sample_fmts ? (*ppCodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; + c->bit_rate = g_Config.m_SndRate * 2 * 16; + c->frame_size = m_SndBufferSize; + c->sample_rate = g_Config.m_SndRate; + if((*ppCodec)->supported_samplerates) + { + c->sample_rate = (*ppCodec)->supported_samplerates[0]; + for(int i = 0; (*ppCodec)->supported_samplerates[i]; i++) { - c->sample_rate = (*ppCodec)->supported_samplerates[0]; - for(int i = 0; (*ppCodec)->supported_samplerates[i]; i++) - { - if((*ppCodec)->supported_samplerates[i] == g_Config.m_SndRate) - c->sample_rate = g_Config.m_SndRate; - } + if((*ppCodec)->supported_samplerates[i] == g_Config.m_SndRate) + c->sample_rate = g_Config.m_SndRate; } - c->channels = 2; - c->channel_layout = AV_CH_LAYOUT_STEREO; + } + c->channels = 2; + c->channel_layout = AV_CH_LAYOUT_STEREO; - pStream->pSt->time_base.num = 1; - pStream->pSt->time_base.den = c->sample_rate; - break; + pStream->pSt->time_base.num = 1; + pStream->pSt->time_base.den = c->sample_rate; + break; - case AVMEDIA_TYPE_VIDEO: - c->codec_id = CodecId; + case AVMEDIA_TYPE_VIDEO: + c->codec_id = CodecId; - c->bit_rate = 400000; - /* Resolution must be a multiple of two. */ - c->width = m_Width; - c->height = m_Height%2==0?m_Height:m_Height-1; - /* timebase: This is the fundamental unit of time (in seconds) in terms + c->bit_rate = 400000; + /* Resolution must be a multiple of two. */ + c->width = m_Width; + c->height = m_Height % 2 == 0 ? m_Height : m_Height - 1; + /* timebase: This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. For fixed-fps content, * timebase should be 1/framerate and timestamp increments should be * identical to 1. */ - pStream->pSt->time_base.num = 1; - pStream->pSt->time_base.den = m_FPS; - c->time_base = pStream->pSt->time_base; + pStream->pSt->time_base.num = 1; + pStream->pSt->time_base.den = m_FPS; + c->time_base = pStream->pSt->time_base; - c->gop_size = 12; /* emit one intra frame every twelve frames at most */ - c->pix_fmt = STREAM_PIX_FMT; - if(c->codec_id == AV_CODEC_ID_MPEG2VIDEO) - { - /* just for testing, we also add B-frames */ - c->max_b_frames = 2; - } - if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO) - { - /* Needed to avoid using macroblocks in which some coeffs overflow. + c->gop_size = 12; /* emit one intra frame every twelve frames at most */ + c->pix_fmt = STREAM_PIX_FMT; + if(c->codec_id == AV_CODEC_ID_MPEG2VIDEO) + { + /* just for testing, we also add B-frames */ + c->max_b_frames = 2; + } + if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO) + { + /* Needed to avoid using macroblocks in which some coeffs overflow. * This does not happen with normal video, it just happens here as * the motion of the chroma plane does not match the luma plane. */ - c->mb_decision = 2; - } - if(CodecId == AV_CODEC_ID_H264) - { - const char *presets[10] = {"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo"}; - //av_opt_set(c->priv_data, "preset", "slow", 0); - //av_opt_set_int(c->priv_data, "crf", 22, 0); - av_opt_set(c->priv_data, "preset", presets[g_Config.m_ClVideoX264Preset], 0); - av_opt_set_int(c->priv_data, "crf", g_Config.m_ClVideoX264Crf, 0); - } + c->mb_decision = 2; + } + if(CodecId == AV_CODEC_ID_H264) + { + const char *presets[10] = {"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo"}; + //av_opt_set(c->priv_data, "preset", "slow", 0); + //av_opt_set_int(c->priv_data, "crf", 22, 0); + av_opt_set(c->priv_data, "preset", presets[g_Config.m_ClVideoX264Preset], 0); + av_opt_set_int(c->priv_data, "crf", g_Config.m_ClVideoX264Crf, 0); + } break; - default: - break; + default: + break; } /* Some formats want stream headers to be separate. */ @@ -672,12 +665,12 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp return true; } -void CVideo::WriteFrame(OutputStream* pStream) +void CVideo::WriteFrame(OutputStream *pStream) { //lock_wait(g_WriteLock); int RetRecv = 0; - AVPacket Packet = { 0 }; + AVPacket Packet = {0}; av_init_packet(&Packet); Packet.data = 0; @@ -711,12 +704,12 @@ void CVideo::WriteFrame(OutputStream* pStream) //lock_unlock(g_WriteLock); } -void CVideo::FinishFrames(OutputStream* pStream) +void CVideo::FinishFrames(OutputStream *pStream) { dbg_msg("video_recorder", "------------"); int RetRecv = 0; - AVPacket Packet = { 0 }; + AVPacket Packet = {0}; av_init_packet(&Packet); Packet.data = 0; @@ -750,7 +743,7 @@ void CVideo::FinishFrames(OutputStream* pStream) } } -void CVideo::CloseStream(OutputStream* pStream) +void CVideo::CloseStream(OutputStream *pStream) { avcodec_free_context(&pStream->pEnc); av_frame_free(&pStream->pFrame); diff --git a/src/engine/client/video.h b/src/engine/client/video.h index 63b405c47..47b1fc766 100644 --- a/src/engine/client/video.h +++ b/src/engine/client/video.h @@ -2,41 +2,39 @@ #define ENGINE_CLIENT_VIDEO_H #if defined(__ANDROID__) - #define GL_GLEXT_PROTOTYPES - #include - #include - #include - #define glOrtho glOrthof +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#define glOrtho glOrthof #else - #include "SDL_opengl.h" +#include "SDL_opengl.h" - #if defined(CONF_PLATFORM_MACOSX) - #include "OpenGL/glu.h" - #else - #include "GL/glu.h" - #endif +#if defined(CONF_PLATFORM_MACOSX) +#include "OpenGL/glu.h" +#else +#include "GL/glu.h" +#endif #endif - -extern "C" -{ - #include - #include - #include - #include - #include - #include +extern "C" { +#include +#include +#include +#include +#include +#include }; #include -#include #include +#include #define ALEN 2048 - // a wrapper around a single output AVStream -typedef struct OutputStream { +typedef struct OutputStream +{ AVStream *pSt; AVCodecContext *pEnc; @@ -54,7 +52,7 @@ typedef struct OutputStream { class CVideo : public IVideo { public: - CVideo(class CGraphics_Threaded* pGraphics, class IStorage* pStorage, class IConsole *pConsole, int width, int height, const char *name); + CVideo(class CGraphics_Threaded *pGraphics, class IStorage *pStorage, class IConsole *pConsole, int width, int height, const char *name); ~CVideo(); virtual void Start(); @@ -70,7 +68,7 @@ public: virtual void NextAudioFrameTimeline(); virtual bool AudioFrameRendered() { return !m_NextAudioFrame; } - static IVideo* Current() { return IVideo::ms_pCurrentVideo; } + static IVideo *Current() { return IVideo::ms_pCurrentVideo; } static void Init() { av_log_set_level(AV_LOG_DEBUG); } @@ -83,24 +81,24 @@ private: bool OpenVideo(); bool OpenAudio(); AVFrame *AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height); - AVFrame* AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples); + AVFrame *AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples); - void WriteFrame(OutputStream* pStream); - void FinishFrames(OutputStream* pStream); + void WriteFrame(OutputStream *pStream); + void FinishFrames(OutputStream *pStream); void CloseStream(OutputStream *pStream); bool AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **ppCodec, enum AVCodecID CodecId); - class CGraphics_Threaded* m_pGraphics; - class IStorage* m_pStorage; - class IConsole* m_pConsole; + class CGraphics_Threaded *m_pGraphics; + class IStorage *m_pStorage; + class IConsole *m_pConsole; int m_Width; int m_Height; char m_Name[256]; //FILE *m_dbgfile; int m_Vseq; - short m_aBuffer[ALEN*2]; + short m_aBuffer[ALEN * 2]; int m_Vframe; int m_FPS; @@ -116,23 +114,22 @@ private: bool m_HasAudio; - GLubyte* m_pPixels; + GLubyte *m_pPixels; OutputStream m_VideoStream; OutputStream m_AudioStream; - AVCodec* m_VideoCodec; - AVCodec* m_AudioCodec; + AVCodec *m_VideoCodec; + AVCodec *m_AudioCodec; - AVDictionary* m_pOptDict; + AVDictionary *m_pOptDict; - AVFormatContext* m_pFormatContext; - AVOutputFormat* m_pFormat; + AVFormatContext *m_pFormatContext; + AVOutputFormat *m_pFormat; - uint8_t* m_pRGB; + uint8_t *m_pRGB; int m_SndBufferSize; }; - #endif diff --git a/src/engine/console.h b/src/engine/console.h index dace3fac1..822bb399d 100644 --- a/src/engine/console.h +++ b/src/engine/console.h @@ -3,35 +3,34 @@ #ifndef ENGINE_CONSOLE_H #define ENGINE_CONSOLE_H +#include "kernel.h" #include #include -#include "kernel.h" class IConsole : public IInterface { MACRO_INTERFACE("console", 0) public: - // TODO: rework/cleanup enum { - OUTPUT_LEVEL_STANDARD=0, + OUTPUT_LEVEL_STANDARD = 0, OUTPUT_LEVEL_ADDINFO, OUTPUT_LEVEL_DEBUG, - ACCESS_LEVEL_ADMIN=0, + ACCESS_LEVEL_ADMIN = 0, ACCESS_LEVEL_MOD, ACCESS_LEVEL_HELPER, ACCESS_LEVEL_USER, - TEMPCMD_NAME_LENGTH=32, - TEMPCMD_HELP_LENGTH=96, - TEMPCMD_PARAMS_LENGTH=96, + TEMPCMD_NAME_LENGTH = 32, + TEMPCMD_HELP_LENGTH = 96, + TEMPCMD_PARAMS_LENGTH = 96, - MAX_PRINT_CB=4, + MAX_PRINT_CB = 4, - CLIENT_ID_GAME=-2, - CLIENT_ID_NO_GAME=-3, + CLIENT_ID_GAME = -2, + CLIENT_ID_NO_GAME = -3, }; // TODO: rework this interface to reduce the amount of virtual calls @@ -39,6 +38,7 @@ public: { protected: unsigned m_NumArgs; + public: IResult() { m_NumArgs = 0; } virtual ~IResult() {} @@ -62,6 +62,7 @@ public: { protected: int m_AccessLevel; + public: CCommandInfo() { m_AccessLevel = ACCESS_LEVEL_ADMIN; } virtual ~CCommandInfo() {} diff --git a/src/engine/demo.h b/src/engine/demo.h index 015ec6e89..60df13baf 100644 --- a/src/engine/demo.h +++ b/src/engine/demo.h @@ -3,14 +3,14 @@ #ifndef ENGINE_DEMO_H #define ENGINE_DEMO_H +#include "kernel.h" #include #include #include -#include "kernel.h" enum { - MAX_TIMELINE_MARKERS=64 + MAX_TIMELINE_MARKERS = 64 }; const double g_aSpeeds[] = {0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 20.0, 24.0, 28.0, 32.0, 40.0, 48.0, 56.0, 64.0}; @@ -20,9 +20,9 @@ typedef bool (*DEMOFUNC_FILTER)(const void *pData, int DataSize, void *pUser); // TODO: Properly extend demo format using uuids // "6be6da4a-cebd-380c-9b5b-1289c842d780" // "demoitem-sha256@ddnet.tw" -static const CUuid SHA256_EXTENSION = {{ - 0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c, - 0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80}}; +static const CUuid SHA256_EXTENSION = + {{0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c, + 0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80}}; struct CDemoHeader { @@ -71,7 +71,7 @@ public: enum { - DEMOTYPE_INVALID=0, + DEMOTYPE_INVALID = 0, DEMOTYPE_CLIENT, DEMOTYPE_SERVER, }; @@ -106,7 +106,6 @@ class IDemoEditor : public IInterface { MACRO_INTERFACE("demoeditor", 0) public: - virtual void Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick, DEMOFUNC_FILTER pfnFilter, void *pUser) = 0; }; diff --git a/src/engine/editor.h b/src/engine/editor.h index 4bf639e70..ca108b2f1 100644 --- a/src/engine/editor.h +++ b/src/engine/editor.h @@ -8,7 +8,6 @@ class IEditor : public IInterface { MACRO_INTERFACE("editor", 0) public: - virtual ~IEditor() {} virtual void Init() = 0; virtual void UpdateAndRender() = 0; diff --git a/src/engine/friends.h b/src/engine/friends.h index b62872ed1..02d775c93 100644 --- a/src/engine/friends.h +++ b/src/engine/friends.h @@ -21,11 +21,11 @@ class IFriends : public IInterface public: enum { - FRIEND_NO=0, + FRIEND_NO = 0, FRIEND_CLAN, FRIEND_PLAYER, - MAX_FRIENDS=1024, + MAX_FRIENDS = 1024, }; virtual void Init(bool Foes = false) = 0; diff --git a/src/engine/graphics.h b/src/engine/graphics.h index 581f12b2c..2cad62253 100644 --- a/src/engine/graphics.h +++ b/src/engine/graphics.h @@ -63,10 +63,10 @@ class CImageInfo public: enum { - FORMAT_AUTO=-1, - FORMAT_RGB=0, - FORMAT_RGBA=1, - FORMAT_ALPHA=2, + FORMAT_AUTO = -1, + FORMAT_RGB = 0, + FORMAT_RGBA = 1, + FORMAT_ALPHA = 2, }; /* Variable: width @@ -120,7 +120,10 @@ struct GL_SColorf }; //use normalized color values -struct GL_SColor { unsigned char r, g, b, a; }; +struct GL_SColor +{ + unsigned char r, g, b, a; +}; struct GL_SVertex { @@ -145,12 +148,13 @@ struct GL_SVertexTex3DStream struct SGraphicsWarning { - SGraphicsWarning() : m_WasShown(false) {} + SGraphicsWarning() : + m_WasShown(false) {} char m_aWarningMsg[128]; bool m_WasShown; }; -typedef void(*WINDOW_RESIZE_FUNC)(void *pUser); +typedef void (*WINDOW_RESIZE_FUNC)(void *pUser); class IGraphics : public IInterface { @@ -160,15 +164,16 @@ protected: int m_ScreenHeight; int m_DesktopScreenWidth; int m_DesktopScreenHeight; + public: /* Constants: Texture Loading Flags TEXLOAD_NORESAMPLE - Prevents the texture from any resampling */ enum { - TEXLOAD_NORESAMPLE = 1<<0, - TEXLOAD_NOMIPMAPS = 1<<1, - TEXLOAD_NO_COMPRESSION = 1<<2, + TEXLOAD_NORESAMPLE = 1 << 0, + TEXLOAD_NOMIPMAPS = 1 << 1, + TEXLOAD_NO_COMPRESSION = 1 << 2, TEXLOAD_TO_3D_TEXTURE = (1 << 3), TEXLOAD_TO_2D_ARRAY_TEXTURE = (1 << 4), TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER = (1 << 5), @@ -176,22 +181,23 @@ public: TEXLOAD_NO_2D_TEXTURE = (1 << 7), }; - class CTextureHandle { friend class IGraphics; int m_Id; + public: - CTextureHandle() - : m_Id(-1) - {} + CTextureHandle() : + m_Id(-1) + { + } operator int() const { return m_Id; } }; int ScreenWidth() const { return m_ScreenWidth; } int ScreenHeight() const { return m_ScreenHeight; } - float ScreenAspect() const { return (float)ScreenWidth()/(float)ScreenHeight(); } + float ScreenAspect() const { return (float)ScreenWidth() / (float)ScreenHeight(); } virtual bool Fullscreen(bool State) = 0; virtual void SetWindowBordered(bool State) = 0; @@ -263,7 +269,8 @@ public: { float m_X0, m_Y0, m_X1, m_Y1; CLineItem() {} - CLineItem(float x0, float y0, float x1, float y1) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {} + CLineItem(float x0, float y0, float x1, float y1) : + m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {} }; virtual void LinesBegin() = 0; virtual void LinesEnd() = 0; @@ -285,8 +292,15 @@ public: { float m_X, m_Y, m_Width, m_Height; CQuadItem() {} - CQuadItem(float x, float y, float w, float h) : m_X(x), m_Y(y), m_Width(w), m_Height(h) {} - void Set(float x, float y, float w, float h) { m_X = x; m_Y = y; m_Width = w; m_Height = h; } + CQuadItem(float x, float y, float w, float h) : + m_X(x), m_Y(y), m_Width(w), m_Height(h) {} + void Set(float x, float y, float w, float h) + { + m_X = x; + m_Y = y; + m_Width = w; + m_Height = h; + } }; virtual void QuadsDraw(CQuadItem *pArray, int Num) = 0; virtual void QuadsDrawTL(const CQuadItem *pArray, int Num) = 0; @@ -297,8 +311,8 @@ public: { float m_X0, m_Y0, m_X1, m_Y1, m_X2, m_Y2, m_X3, m_Y3; CFreeformItem() {} - CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {} + CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) : + m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {} }; virtual int CreateQuadContainer() = 0; @@ -328,7 +342,8 @@ public: int m_Index; float m_R, m_G, m_B, m_A; CColorVertex() {} - CColorVertex(int i, float r, float g, float b, float a) : m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {} + CColorVertex(int i, float r, float g, float b, float a) : + m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {} }; virtual void SetColorVertex(const CColorVertex *pArray, int Num) = 0; virtual void SetColor(float r, float g, float b, float a) = 0; @@ -353,6 +368,7 @@ public: virtual void NotifyWindow() = 0; virtual SGraphicsWarning *GetCurWarning() = 0; + protected: inline CTextureHandle CreateTextureHandle(int Index) { diff --git a/src/engine/kernel.h b/src/engine/kernel.h index 736f27719..d65c651d3 100644 --- a/src/engine/kernel.h +++ b/src/engine/kernel.h @@ -13,17 +13,21 @@ class IInterface // friend with the kernel implementation friend class CKernel; IKernel *m_pKernel; + protected: IKernel *Kernel() { return m_pKernel; } + public: - IInterface() : m_pKernel(0) {} + IInterface() : + m_pKernel(0) {} virtual ~IInterface() {} }; #define MACRO_INTERFACE(Name, ver) \ - public: \ - static const char *InterfaceName() { return Name; } \ - private: +public: \ + static const char *InterfaceName() { return Name; } \ +\ +private: // This kernel thingie makes the structure very flat and basiclly singletons. // I'm not sure if this is a good idea but it works for now. @@ -33,6 +37,7 @@ class IKernel virtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface, bool Destroy) = 0; virtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; virtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0; + public: static IKernel *Create(); virtual ~IKernel() {} diff --git a/src/engine/map.h b/src/engine/map.h index cb83ddab8..aeb1c1cdb 100644 --- a/src/engine/map.h +++ b/src/engine/map.h @@ -3,8 +3,8 @@ #ifndef ENGINE_MAP_H #define ENGINE_MAP_H -#include #include "kernel.h" +#include enum { @@ -26,7 +26,6 @@ public: virtual int NumItems() = 0; }; - class IEngineMap : public IMap { MACRO_INTERFACE("enginemap", 0) diff --git a/src/engine/masterserver.h b/src/engine/masterserver.h index d347e7c40..4b820c9d9 100644 --- a/src/engine/masterserver.h +++ b/src/engine/masterserver.h @@ -9,10 +9,9 @@ class IMasterServer : public IInterface { MACRO_INTERFACE("masterserver", 0) public: - enum { - MAX_MASTERSERVERS=4 + MAX_MASTERSERVERS = 4 }; virtual void Init() = 0; diff --git a/src/engine/message.h b/src/engine/message.h index 533044961..8ac4acedc 100644 --- a/src/engine/message.h +++ b/src/engine/message.h @@ -12,7 +12,8 @@ public: int m_MsgID; bool m_System; bool m_NoTranslate; - CMsgPacker(int Type, bool System = false, bool NoTranslate = false) : m_MsgID(Type), m_System(System), m_NoTranslate(NoTranslate) + CMsgPacker(int Type, bool System = false, bool NoTranslate = false) : + m_MsgID(Type), m_System(System), m_NoTranslate(NoTranslate) { Reset(); } diff --git a/src/engine/server.h b/src/engine/server.h index 98253169a..010e3edf0 100644 --- a/src/engine/server.h +++ b/src/engine/server.h @@ -10,10 +10,10 @@ #include "kernel.h" #include "message.h" +#include #include #include #include -#include struct CAntibotRoundData; @@ -62,7 +62,7 @@ public: { int Result = 0; T tmp; - if (ClientID == -1) + if(ClientID == -1) { for(int i = 0; i < MAX_CLIENTS; i++) if(ClientIngame(i)) @@ -70,7 +70,9 @@ public: mem_copy(&tmp, pMsg, sizeof(T)); Result = SendPackMsgTranslate(&tmp, Flags, i); } - } else { + } + else + { mem_copy(&tmp, pMsg, sizeof(T)); Result = SendPackMsgTranslate(&tmp, Flags, ClientID); } @@ -130,8 +132,10 @@ public: int SendPackMsgTranslate(CNetMsg_Sv_KillMsg *pMsg, int Flags, int ClientID) { - if (!Translate(pMsg->m_Victim, ClientID)) return 0; - if (!Translate(pMsg->m_Killer, ClientID)) pMsg->m_Killer = pMsg->m_Victim; + if(!Translate(pMsg->m_Victim, ClientID)) + return 0; + if(!Translate(pMsg->m_Killer, ClientID)) + pMsg->m_Killer = pMsg->m_Victim; return SendPackMsgOne(pMsg, Flags, ClientID); } @@ -146,19 +150,19 @@ public: return SendMsg(&Packer, Flags, ClientID); } - bool Translate(int& Target, int Client) + bool Translate(int &Target, int Client) { if(IsSixup(Client)) return true; CClientInfo Info; GetClientInfo(Client, &Info); - if (Info.m_DDNetVersion >= VERSION_DDNET_OLD) + if(Info.m_DDNetVersion >= VERSION_DDNET_OLD) return true; int *pMap = GetIdMap(Client); bool Found = false; - for (int i = 0; i < VANILLA_MAX_CLIENTS; i++) + for(int i = 0; i < VANILLA_MAX_CLIENTS; i++) { - if (Target == pMap[i]) + if(Target == pMap[i]) { Target = i; Found = true; @@ -168,17 +172,17 @@ public: return Found; } - bool ReverseTranslate(int& Target, int Client) + bool ReverseTranslate(int &Target, int Client) { if(IsSixup(Client)) return true; CClientInfo Info; GetClientInfo(Client, &Info); - if (Info.m_DDNetVersion >= VERSION_DDNET_OLD) + if(Info.m_DDNetVersion >= VERSION_DDNET_OLD) return true; - Target = clamp(Target, 0, VANILLA_MAX_CLIENTS-1); + Target = clamp(Target, 0, VANILLA_MAX_CLIENTS - 1); int *pMap = GetIdMap(Client); - if (pMap[Target] == -1) + if(pMap[Target] == -1) return false; Target = pMap[Target]; return true; @@ -198,9 +202,10 @@ public: virtual void SnapSetStaticsize(int ItemType, int Size) = 0; - enum { - RCON_CID_SERV=-1, - RCON_CID_VOTE=-2, + enum + { + RCON_CID_SERV = -1, + RCON_CID_VOTE = -2, }; virtual void SetRconCID(int ClientID) = 0; virtual int GetAuthedState(int ClientID) = 0; @@ -208,7 +213,6 @@ public: virtual void Kick(int ClientID, const char *pReason) = 0; virtual void Ban(int ClientID, int Seconds, const char *pReason) = 0; - virtual void DemoRecorder_HandleAutoStart() = 0; virtual bool DemoRecorder_IsRecording() = 0; @@ -221,7 +225,7 @@ public: virtual void GetClientAddr(int ClientID, NETADDR *pAddr) = 0; - virtual int* GetIdMap(int ClientID) = 0; + virtual int *GetIdMap(int ClientID) = 0; virtual bool DnsblWhite(int ClientID) = 0; virtual bool DnsblPending(int ClientID) = 0; diff --git a/src/engine/server/antibot.cpp b/src/engine/server/antibot.cpp index 96e972f26..12d7064a3 100644 --- a/src/engine/server/antibot.cpp +++ b/src/engine/server/antibot.cpp @@ -1,13 +1,13 @@ #include "antibot.h" #include -#include #include +#include #include #ifdef CONF_ANTIBOT -CAntibot::CAntibot() - : m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false) +CAntibot::CAntibot() : + m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false) { } CAntibot::~CAntibot() @@ -23,11 +23,11 @@ void CAntibot::Send(int ClientID, const void *pData, int Size, int Flags, void * CAntibot *pAntibot = (CAntibot *)pUser; int RealFlags = MSGFLAG_VITAL; - if(Flags&ANTIBOT_MSGFLAG_NONVITAL) + if(Flags & ANTIBOT_MSGFLAG_NONVITAL) { RealFlags &= ~MSGFLAG_VITAL; } - if(Flags&ANTIBOT_MSGFLAG_FLUSH) + if(Flags & ANTIBOT_MSGFLAG_FLUSH) { RealFlags |= MSGFLAG_FLUSH; } @@ -95,32 +95,80 @@ void CAntibot::Update() } } -void CAntibot::OnPlayerInit(int ClientID) { Update(); AntibotOnPlayerInit(ClientID); } -void CAntibot::OnPlayerDestroy(int ClientID) { Update(); AntibotOnPlayerDestroy(ClientID); } -void CAntibot::OnSpawn(int ClientID) { Update(); AntibotOnSpawn(ClientID); } -void CAntibot::OnHammerFireReloading(int ClientID) { Update(); AntibotOnHammerFireReloading(ClientID); } -void CAntibot::OnHammerFire(int ClientID) { Update(); AntibotOnHammerFire(ClientID); } -void CAntibot::OnHammerHit(int ClientID) { Update(); AntibotOnHammerHit(ClientID); } -void CAntibot::OnDirectInput(int ClientID) { Update(); AntibotOnDirectInput(ClientID); } -void CAntibot::OnCharacterTick(int ClientID) { Update(); AntibotOnCharacterTick(ClientID); } -void CAntibot::OnHookAttach(int ClientID, bool Player) { Update(); AntibotOnHookAttach(ClientID, Player); } +void CAntibot::OnPlayerInit(int ClientID) +{ + Update(); + AntibotOnPlayerInit(ClientID); +} +void CAntibot::OnPlayerDestroy(int ClientID) +{ + Update(); + AntibotOnPlayerDestroy(ClientID); +} +void CAntibot::OnSpawn(int ClientID) +{ + Update(); + AntibotOnSpawn(ClientID); +} +void CAntibot::OnHammerFireReloading(int ClientID) +{ + Update(); + AntibotOnHammerFireReloading(ClientID); +} +void CAntibot::OnHammerFire(int ClientID) +{ + Update(); + AntibotOnHammerFire(ClientID); +} +void CAntibot::OnHammerHit(int ClientID) +{ + Update(); + AntibotOnHammerHit(ClientID); +} +void CAntibot::OnDirectInput(int ClientID) +{ + Update(); + AntibotOnDirectInput(ClientID); +} +void CAntibot::OnCharacterTick(int ClientID) +{ + Update(); + AntibotOnCharacterTick(ClientID); +} +void CAntibot::OnHookAttach(int ClientID, bool Player) +{ + Update(); + AntibotOnHookAttach(ClientID, Player); +} -void CAntibot::OnEngineTick() { Update(); AntibotOnEngineTick(); } -void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) { Update(); AntibotOnEngineClientJoin(ClientID, Sixup); } -void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) { Update(); AntibotOnEngineClientDrop(ClientID, pReason); } +void CAntibot::OnEngineTick() +{ + Update(); + AntibotOnEngineTick(); +} +void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) +{ + Update(); + AntibotOnEngineClientJoin(ClientID, Sixup); +} +void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) +{ + Update(); + AntibotOnEngineClientDrop(ClientID, pReason); +} void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) { Update(); int AntibotFlags = 0; - if((Flags&MSGFLAG_VITAL) == 0) + if((Flags & MSGFLAG_VITAL) == 0) { AntibotFlags |= ANTIBOT_MSGFLAG_NONVITAL; } AntibotOnEngineClientMessage(ClientID, pData, Size, Flags); } #else -CAntibot::CAntibot() - : m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false) +CAntibot::CAntibot() : + m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false) { } CAntibot::~CAntibot() @@ -148,20 +196,23 @@ void CAntibot::Update() { } -void CAntibot::OnPlayerInit(int ClientID) { } -void CAntibot::OnPlayerDestroy(int ClientID) { } -void CAntibot::OnSpawn(int ClientID) { } -void CAntibot::OnHammerFireReloading(int ClientID) { } -void CAntibot::OnHammerFire(int ClientID) { } -void CAntibot::OnHammerHit(int ClientID) { } -void CAntibot::OnDirectInput(int ClientID) { } -void CAntibot::OnCharacterTick(int ClientID) { } -void CAntibot::OnHookAttach(int ClientID, bool Player) { } +void CAntibot::OnPlayerInit(int ClientID) {} +void CAntibot::OnPlayerDestroy(int ClientID) {} +void CAntibot::OnSpawn(int ClientID) {} +void CAntibot::OnHammerFireReloading(int ClientID) {} +void CAntibot::OnHammerFire(int ClientID) {} +void CAntibot::OnHammerHit(int ClientID) {} +void CAntibot::OnDirectInput(int ClientID) {} +void CAntibot::OnCharacterTick(int ClientID) {} +void CAntibot::OnHookAttach(int ClientID, bool Player) {} -void CAntibot::OnEngineTick() { } -void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) { } -void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) { } -void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) { } +void CAntibot::OnEngineTick() {} +void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) {} +void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) {} +void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) {} #endif -IEngineAntibot *CreateEngineAntibot() { return new CAntibot; } +IEngineAntibot *CreateEngineAntibot() +{ + return new CAntibot; +} diff --git a/src/engine/server/antibot.h b/src/engine/server/antibot.h index 6b10df979..ab2ef43c3 100644 --- a/src/engine/server/antibot.h +++ b/src/engine/server/antibot.h @@ -22,6 +22,7 @@ class CAntibot : public IEngineAntibot static void Send(int ClientID, const void *pData, int Size, int Flags, void *pUser); static void Log(const char *pMessage, void *pUser); static void Report(int ClientID, const char *pMessage, void *pUser); + public: CAntibot(); virtual ~CAntibot(); diff --git a/src/engine/server/authmanager.cpp b/src/engine/server/authmanager.cpp index 384215bd7..b25df0d2c 100644 --- a/src/engine/server/authmanager.cpp +++ b/src/engine/server/authmanager.cpp @@ -1,6 +1,6 @@ +#include "authmanager.h" #include #include -#include "authmanager.h" #define ADMIN_IDENT "default_admin" #define MOD_IDENT "default_mod" diff --git a/src/engine/server/authmanager.h b/src/engine/server/authmanager.h index 665415006..33fc54c3f 100644 --- a/src/engine/server/authmanager.h +++ b/src/engine/server/authmanager.h @@ -27,6 +27,7 @@ private: int m_aDefault[3]; bool m_Generated; + public: typedef void (*FListCallback)(const char *pIdent, int Level, void *pUser); diff --git a/src/engine/server/databases/connection.cpp b/src/engine/server/databases/connection.cpp index b7a95caf9..600227602 100644 --- a/src/engine/server/databases/connection.cpp +++ b/src/engine/server/databases/connection.cpp @@ -5,82 +5,82 @@ void IDbConnection::FormatCreateRace(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, - "CREATE TABLE IF NOT EXISTS %s_race (" - " Map VARCHAR(128) COLLATE %s NOT NULL, " - " Name VARCHAR(%d) COLLATE %s NOT NULL, " - " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - " Time FLOAT DEFAULT 0, " - " Server CHAR(4), " - " cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, " - " cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, " - " cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, " - " cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, " - " cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, " - " cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, " - " cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, " - " cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, " - " cp25 FLOAT DEFAULT 0, " - " GameID VARCHAR(64), " - " DDNet7 BOOL DEFAULT FALSE, " - " PRIMARY KEY (Map, Name, Time, Timestamp, Server)" - ");", - GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate()); + "CREATE TABLE IF NOT EXISTS %s_race (" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Time FLOAT DEFAULT 0, " + " Server CHAR(4), " + " cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, " + " cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, " + " cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, " + " cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, " + " cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, " + " cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, " + " cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, " + " cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, " + " cp25 FLOAT DEFAULT 0, " + " GameID VARCHAR(64), " + " DDNet7 BOOL DEFAULT FALSE, " + " PRIMARY KEY (Map, Name, Time, Timestamp, Server)" + ");", + GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate()); } void IDbConnection::FormatCreateTeamrace(char *aBuf, unsigned int BufferSize, const char *pIdType) { str_format(aBuf, BufferSize, - "CREATE TABLE IF NOT EXISTS %s_teamrace (" - " Map VARCHAR(128) COLLATE %s NOT NULL, " - " Name VARCHAR(%d) COLLATE %s NOT NULL, " - " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - " Time FLOAT DEFAULT 0, " - " ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite - " GameID VARCHAR(64), " - " DDNet7 BOOL DEFAULT FALSE, " - " PRIMARY KEY (ID, Name)" - ");", - GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate(), pIdType); + "CREATE TABLE IF NOT EXISTS %s_teamrace (" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Time FLOAT DEFAULT 0, " + " ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite + " GameID VARCHAR(64), " + " DDNet7 BOOL DEFAULT FALSE, " + " PRIMARY KEY (ID, Name)" + ");", + GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate(), pIdType); } void IDbConnection::FormatCreateMaps(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, - "CREATE TABLE IF NOT EXISTS %s_maps (" - " Map VARCHAR(128) COLLATE %s NOT NULL, " - " Server VARCHAR(32) COLLATE %s NOT NULL, " - " Mapper VARCHAR(128) COLLATE %s NOT NULL, " - " Points INT DEFAULT 0, " - " Stars INT DEFAULT 0, " - " Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " - " PRIMARY KEY (Map)" - ");", - GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); + "CREATE TABLE IF NOT EXISTS %s_maps (" + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Server VARCHAR(32) COLLATE %s NOT NULL, " + " Mapper VARCHAR(128) COLLATE %s NOT NULL, " + " Points INT DEFAULT 0, " + " Stars INT DEFAULT 0, " + " Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " + " PRIMARY KEY (Map)" + ");", + GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); } void IDbConnection::FormatCreateSaves(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, - "CREATE TABLE IF NOT EXISTS %s_saves (" - " Savegame TEXT COLLATE %s NOT NULL, " - " Map VARCHAR(128) COLLATE %s NOT NULL, " - " Code VARCHAR(128) COLLATE %s NOT NULL, " - " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " - " Server CHAR(4), " - " DDNet7 BOOL DEFAULT FALSE, " - " SaveID VARCHAR(36) DEFAULT NULL, " - " PRIMARY KEY (Map, Code)" - ");", - GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); + "CREATE TABLE IF NOT EXISTS %s_saves (" + " Savegame TEXT COLLATE %s NOT NULL, " + " Map VARCHAR(128) COLLATE %s NOT NULL, " + " Code VARCHAR(128) COLLATE %s NOT NULL, " + " Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " Server CHAR(4), " + " DDNet7 BOOL DEFAULT FALSE, " + " SaveID VARCHAR(36) DEFAULT NULL, " + " PRIMARY KEY (Map, Code)" + ");", + GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate()); } void IDbConnection::FormatCreatePoints(char *aBuf, unsigned int BufferSize) { str_format(aBuf, BufferSize, - "CREATE TABLE IF NOT EXISTS %s_points (" - " Name VARCHAR(%d) COLLATE %s NOT NULL, " - " Points INT DEFAULT 0, " - " PRIMARY KEY (Name)" - ");", - GetPrefix(), MAX_NAME_LENGTH, BinaryCollate()); + "CREATE TABLE IF NOT EXISTS %s_points (" + " Name VARCHAR(%d) COLLATE %s NOT NULL, " + " Points INT DEFAULT 0, " + " PRIMARY KEY (Name)" + ");", + GetPrefix(), MAX_NAME_LENGTH, BinaryCollate()); } diff --git a/src/engine/server/databases/connection.h b/src/engine/server/databases/connection.h index de58b02cf..d3611be2d 100644 --- a/src/engine/server/databases/connection.h +++ b/src/engine/server/databases/connection.h @@ -14,7 +14,7 @@ public: str_copy(m_aPrefix, pPrefix, sizeof(m_aPrefix)); } virtual ~IDbConnection() {} - IDbConnection& operator=(const IDbConnection&) = delete; + IDbConnection &operator=(const IDbConnection &) = delete; virtual void Print(IConsole *pConsole, const char *Mode) = 0; // copies the credentials, not the active connection diff --git a/src/engine/server/databases/connection_pool.cpp b/src/engine/server/databases/connection_pool.cpp index 5ed2804a9..372688b47 100644 --- a/src/engine/server/databases/connection_pool.cpp +++ b/src/engine/server/databases/connection_pool.cpp @@ -11,13 +11,13 @@ struct CSqlExecData { CSqlExecData( - CDbConnectionPool::FRead pFunc, - std::unique_ptr pThreadData, - const char *pName); + CDbConnectionPool::FRead pFunc, + std::unique_ptr pThreadData, + const char *pName); CSqlExecData( - CDbConnectionPool::FWrite pFunc, - std::unique_ptr pThreadData, - const char *pName); + CDbConnectionPool::FWrite pFunc, + std::unique_ptr pThreadData, + const char *pName); ~CSqlExecData() {} enum @@ -39,9 +39,9 @@ CSqlExecData::CSqlExecData( CDbConnectionPool::FRead pFunc, std::unique_ptr pThreadData, const char *pName) : - m_Mode(READ_ACCESS), - m_pThreadData(std::move(pThreadData)), - m_pName(pName) + m_Mode(READ_ACCESS), + m_pThreadData(std::move(pThreadData)), + m_pName(pName) { m_Ptr.m_pReadFunc = pFunc; } @@ -50,9 +50,9 @@ CSqlExecData::CSqlExecData( CDbConnectionPool::FWrite pFunc, std::unique_ptr pThreadData, const char *pName) : - m_Mode(WRITE_ACCESS), - m_pThreadData(std::move(pThreadData)), - m_pName(pName) + m_Mode(WRITE_ACCESS), + m_pThreadData(std::move(pThreadData)), + m_pName(pName) { m_Ptr.m_pWriteFunc = pFunc; } @@ -86,9 +86,9 @@ void CDbConnectionPool::RegisterDatabase(std::unique_ptr pDatabas } void CDbConnectionPool::Execute( - FRead pFunc, - std::unique_ptr pThreadData, - const char *pName) + FRead pFunc, + std::unique_ptr pThreadData, + const char *pName) { m_aTasks[FirstElem++].reset(new CSqlExecData(pFunc, std::move(pThreadData), pName)); FirstElem %= sizeof(m_aTasks) / sizeof(m_aTasks[0]); @@ -96,9 +96,9 @@ void CDbConnectionPool::Execute( } void CDbConnectionPool::ExecuteWrite( - FWrite pFunc, - std::unique_ptr pThreadData, - const char *pName) + FWrite pFunc, + std::unique_ptr pThreadData, + const char *pName) { m_aTasks[FirstElem++].reset(new CSqlExecData(pFunc, std::move(pThreadData), pName)); FirstElem %= sizeof(m_aTasks) / sizeof(m_aTasks[0]); @@ -112,13 +112,14 @@ void CDbConnectionPool::OnShutdown() int i = 0; while(m_Shutdown.load()) { - if (i > 600) { + if(i > 600) + { dbg_msg("sql", "Waited 60 seconds for score-threads to complete, quitting anyway"); break; } // print a log about every two seconds - if (i % 20 == 0) + if(i % 20 == 0) dbg_msg("sql", "Waiting for score-threads to complete (%ds)", i / 10); ++i; thread_sleep(100000); @@ -163,7 +164,8 @@ void CDbConnectionPool::Worker() break; } } - } break; + } + break; case CSqlExecData::WRITE_ACCESS: { for(int i = 0; i < (int)m_aapDbConnections[Mode::WRITE].size(); i++) @@ -189,7 +191,8 @@ void CDbConnectionPool::Worker() } } } - } break; + } + break; } if(!Success) dbg_msg("sql", "%s failed on all databases", pThreadData->m_pName); @@ -216,16 +219,16 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD } } #if defined(CONF_SQL) - catch (sql::SQLException &e) + catch(sql::SQLException &e) { dbg_msg("sql", "%s MySQL Error: %s", pData->m_pName, e.what()); } #endif - catch (std::runtime_error &e) + catch(std::runtime_error &e) { dbg_msg("sql", "%s SQLite Error: %s", pData->m_pName, e.what()); } - catch (...) + catch(...) { dbg_msg("sql", "%s Unexpected exception caught", pData->m_pName); } @@ -234,16 +237,16 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD pConnection->Unlock(); } #if defined(CONF_SQL) - catch (sql::SQLException &e) + catch(sql::SQLException &e) { dbg_msg("sql", "%s MySQL Error during unlock: %s", pData->m_pName, e.what()); } #endif - catch (std::runtime_error &e) + catch(std::runtime_error &e) { dbg_msg("sql", "%s SQLite Error during unlock: %s", pData->m_pName, e.what()); } - catch (...) + catch(...) { dbg_msg("sql", "%s Unexpected exception caught during unlock", pData->m_pName); } @@ -252,4 +255,3 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD dbg_msg("sql", "%s failed", pData->m_pName); return Success; } - diff --git a/src/engine/server/databases/connection_pool.h b/src/engine/server/databases/connection_pool.h index 7fb87e76c..73f3cf17d 100644 --- a/src/engine/server/databases/connection_pool.h +++ b/src/engine/server/databases/connection_pool.h @@ -1,8 +1,8 @@ #ifndef ENGINE_SERVER_DATABASES_CONNECTION_POOL_H #define ENGINE_SERVER_DATABASES_CONNECTION_POOL_H -#include #include +#include #include #include @@ -10,7 +10,7 @@ class IDbConnection; struct ISqlData { - virtual ~ISqlData() {}; + virtual ~ISqlData(){}; }; class IConsole; @@ -20,7 +20,7 @@ class CDbConnectionPool public: CDbConnectionPool(); ~CDbConnectionPool(); - CDbConnectionPool& operator=(const CDbConnectionPool&) = delete; + CDbConnectionPool &operator=(const CDbConnectionPool &) = delete; typedef bool (*FRead)(IDbConnection *, const ISqlData *); typedef bool (*FWrite)(IDbConnection *, const ISqlData *, bool); @@ -38,14 +38,14 @@ public: void RegisterDatabase(std::unique_ptr pDatabase, Mode DatabaseMode); void Execute( - FRead pFunc, - std::unique_ptr pSqlRequestData, - const char *pName); + FRead pFunc, + std::unique_ptr pSqlRequestData, + const char *pName); // writes to WRITE_BACKUP server in case of failure void ExecuteWrite( - FWrite pFunc, - std::unique_ptr pSqlRequestData, - const char *pName); + FWrite pFunc, + std::unique_ptr pSqlRequestData, + const char *pName); void OnShutdown(); diff --git a/src/engine/server/databases/mysql.cpp b/src/engine/server/databases/mysql.cpp index 2b6647a88..e3d0665db 100644 --- a/src/engine/server/databases/mysql.cpp +++ b/src/engine/server/databases/mysql.cpp @@ -14,13 +14,13 @@ lock CMysqlConnection::m_SqlDriverLock; CMysqlConnection::CMysqlConnection( - const char *pDatabase, - const char *pPrefix, - const char *pUser, - const char *pPass, - const char *pIp, - int Port, - bool Setup) : + const char *pDatabase, + const char *pPrefix, + const char *pUser, + const char *pPass, + const char *pIp, + int Port, + bool Setup) : IDbConnection(pPrefix), #if defined(CONF_SQL) m_NewQuery(false), @@ -52,8 +52,8 @@ void CMysqlConnection::Print(IConsole *pConsole, const char *Mode) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "MySQL-%s: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d", - Mode, m_aDatabase, GetPrefix(), m_aUser, m_aIp, m_Port); + "MySQL-%s: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d", + Mode, m_aDatabase, GetPrefix(), m_aUser, m_aIp, m_Port); pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } @@ -82,19 +82,19 @@ IDbConnection::Status CMysqlConnection::Connect() m_pConnection->setSchema(m_aDatabase); return Status::SUCCESS; } - catch (sql::SQLException &e) + catch(sql::SQLException &e) { dbg_msg("sql", "MySQL Error: %s", e.what()); } - catch (const std::exception& ex) + catch(const std::exception &ex) { dbg_msg("sql", "MySQL Error: %s", ex.what()); } - catch (const std::string& ex) + catch(const std::string &ex) { dbg_msg("sql", "MySQL Error: %s", ex.c_str()); } - catch (...) + catch(...) { dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector"); } @@ -109,10 +109,10 @@ IDbConnection::Status CMysqlConnection::Connect() m_pResults.release(); sql::ConnectOptionsMap connection_properties; - connection_properties["hostName"] = sql::SQLString(m_aIp); - connection_properties["port"] = m_Port; - connection_properties["userName"] = sql::SQLString(m_aUser); - connection_properties["password"] = sql::SQLString(m_aPass); + connection_properties["hostName"] = sql::SQLString(m_aIp); + connection_properties["port"] = m_Port; + connection_properties["userName"] = sql::SQLString(m_aUser); + connection_properties["password"] = sql::SQLString(m_aPass); connection_properties["OPT_CONNECT_TIMEOUT"] = 60; connection_properties["OPT_READ_TIMEOUT"] = 60; connection_properties["OPT_WRITE_TIMEOUT"] = 120; @@ -161,19 +161,19 @@ IDbConnection::Status CMysqlConnection::Connect() dbg_msg("sql", "sql connection established"); return Status::SUCCESS; } - catch (sql::SQLException &e) + catch(sql::SQLException &e) { dbg_msg("sql", "MySQL Error: %s", e.what()); } - catch (const std::exception& ex) + catch(const std::exception &ex) { dbg_msg("sql", "MySQL Error: %s", ex.what()); } - catch (const std::string& ex) + catch(const std::string &ex) { dbg_msg("sql", "MySQL Error: %s", ex.c_str()); } - catch (...) + catch(...) { dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector"); } @@ -230,7 +230,7 @@ void CMysqlConnection::BindBlob(int Idx, unsigned char *pBlob, int Size) { #if defined(CONF_SQL) // copy blob into string - auto Blob = std::string(pBlob, pBlob+Size); + auto Blob = std::string(pBlob, pBlob + Size); m_pPreparedStmt->setString(Idx, Blob); m_NewQuery = true; #endif @@ -316,10 +316,10 @@ void CMysqlConnection::AddPoints(const char *pPlayer, int Points) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "INSERT INTO %s_points(Name, Points) " - "VALUES (?, ?) " - "ON DUPLICATE KEY UPDATE Points=Points+?;", - GetPrefix()); + "INSERT INTO %s_points(Name, Points) " + "VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE Points=Points+?;", + GetPrefix()); PrepareStatement(aBuf); BindString(1, pPlayer); BindInt(2, Points); diff --git a/src/engine/server/databases/mysql.h b/src/engine/server/databases/mysql.h index 4e95dd735..4dbda92bd 100644 --- a/src/engine/server/databases/mysql.h +++ b/src/engine/server/databases/mysql.h @@ -1,8 +1,8 @@ #ifndef ENGINE_SERVER_DATABASES_MYSQL_H #define ENGINE_SERVER_DATABASES_MYSQL_H -#include #include +#include #include class lock; @@ -17,13 +17,13 @@ class CMysqlConnection : public IDbConnection { public: CMysqlConnection( - const char *pDatabase, - const char *pPrefix, - const char *pUser, - const char *pPass, - const char *pIp, - int Port, - bool Setup); + const char *pDatabase, + const char *pPrefix, + const char *pUser, + const char *pPass, + const char *pIp, + int Port, + bool Setup); virtual ~CMysqlConnection(); virtual void Print(IConsole *pConsole, const char *Mode); diff --git a/src/engine/server/databases/sqlite.cpp b/src/engine/server/databases/sqlite.cpp index 865d2d9e8..c4ee46cd0 100644 --- a/src/engine/server/databases/sqlite.cpp +++ b/src/engine/server/databases/sqlite.cpp @@ -3,8 +3,8 @@ #include #include -#include #include +#include CSqliteConnection::CSqliteConnection(const char *pFilename, bool Setup) : IDbConnection("record"), @@ -30,8 +30,8 @@ void CSqliteConnection::Print(IConsole *pConsole, const char *Mode) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SQLite-%s: DB: '%s'", - Mode, m_aFilename); + "SQLite-%s: DB: '%s'", + Mode, m_aFilename); pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } @@ -117,11 +117,11 @@ void CSqliteConnection::PrepareStatement(const char *pStmt) sqlite3_finalize(m_pStmt); m_pStmt = nullptr; int Result = sqlite3_prepare_v2( - m_pDb, - pStmt, - -1, // pStmt can be any length - &m_pStmt, - NULL); + m_pDb, + pStmt, + -1, // pStmt can be any length + &m_pStmt, + NULL); ExceptionOnError(Result); m_Done = false; } @@ -238,10 +238,10 @@ void CSqliteConnection::AddPoints(const char *pPlayer, int Points) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "INSERT INTO %s_points(Name, Points) " - "VALUES (?, ?) " - "ON CONFLICT(Name) UPDATE SET Points=Points+?;", - GetPrefix()); + "INSERT INTO %s_points(Name, Points) " + "VALUES (?, ?) " + "ON CONFLICT(Name) UPDATE SET Points=Points+?;", + GetPrefix()); PrepareStatement(aBuf); BindString(1, pPlayer); BindInt(2, Points); diff --git a/src/engine/server/name_ban.h b/src/engine/server/name_ban.h index 8dfa96d65..ebe1f28ff 100644 --- a/src/engine/server/name_ban.h +++ b/src/engine/server/name_ban.h @@ -6,8 +6,8 @@ enum { - MAX_NAME_SKELETON_LENGTH=MAX_NAME_LENGTH*4, - MAX_NAMEBAN_REASON_LENGTH=64 + MAX_NAME_SKELETON_LENGTH = MAX_NAME_LENGTH * 4, + MAX_NAMEBAN_REASON_LENGTH = 64 }; class CNameBan diff --git a/src/engine/server/register.cpp b/src/engine/server/register.cpp index 2c58e9ce4..f1ecd1188 100644 --- a/src/engine/server/register.cpp +++ b/src/engine/server/register.cpp @@ -1,10 +1,10 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include -#include #include #include +#include +#include #include @@ -82,7 +82,7 @@ void CRegister::RegisterSendHeartbeat(NETADDR Addr, SECURITY_TOKEN ResponseToken if(g_Config.m_SvExternalPort) Port = g_Config.m_SvExternalPort; aData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8; - aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff; + aData[sizeof(SERVERBROWSE_HEARTBEAT) + 1] = Port & 0xff; if(m_Sixup) m_pNetServer->SendConnlessSixup(&Packet, ResponseToken); else @@ -106,7 +106,7 @@ void CRegister::RegisterSendCountRequest(NETADDR Addr, SECURITY_TOKEN ResponseTo void CRegister::RegisterGotCount(CNetChunk *pChunk) { unsigned char *pData = (unsigned char *)pChunk->m_pData; - int Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1]; + int Count = (pData[sizeof(SERVERBROWSE_COUNT)] << 8) | pData[sizeof(SERVERBROWSE_COUNT) + 1]; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { @@ -135,7 +135,7 @@ void CRegister::RegisterUpdate(int Nettype) m_pMasterServer->Update(); - if(m_Sixup && (m_RegisterState == REGISTERSTATE_HEARTBEAT || m_RegisterState == REGISTERSTATE_REGISTERED) && Now > m_LastTokenRequest+Freq*5) + if(m_Sixup && (m_RegisterState == REGISTERSTATE_HEARTBEAT || m_RegisterState == REGISTERSTATE_REGISTERED) && Now > m_LastTokenRequest + Freq * 5) { m_pNetServer->SendTokenSixup(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr, NET_SECURITY_TOKEN_UNKNOWN); m_LastTokenRequest = Now; @@ -191,7 +191,7 @@ void CRegister::RegisterUpdate(int Nettype) if(m_aMasterserverInfo[i].m_Count == -1) { Left++; - if(m_aMasterserverInfo[i].m_LastSend+Freq < Now) + if(m_aMasterserverInfo[i].m_LastSend + Freq < Now) { m_aMasterserverInfo[i].m_LastSend = Now; if(m_Sixup && m_aMasterserverInfo[i].m_Token == NET_SECURITY_TOKEN_UNKNOWN) @@ -203,7 +203,7 @@ void CRegister::RegisterUpdate(int Nettype) } // check if we are done or timed out - if(Left == 0 || Now > m_RegisterStateStart+Freq*5) + if(Left == 0 || Now > m_RegisterStateStart + Freq * 5) { // choose server int Best = -1; @@ -237,13 +237,13 @@ void CRegister::RegisterUpdate(int Nettype) else if(m_RegisterState == REGISTERSTATE_HEARTBEAT) { // check if we should send heartbeat - if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15) + if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend + Freq * 15) { m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now; RegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr, m_aMasterserverInfo[m_RegisterRegisteredServer].m_Token); } - if(Now > m_RegisterStateStart+Freq*60) + if(Now > m_RegisterStateStart + Freq * 60) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_pName, "WARNING: Master server is not responding, switching master"); RegisterNewState(REGISTERSTATE_START); @@ -257,7 +257,7 @@ void CRegister::RegisterUpdate(int Nettype) m_RegisterFirst = 0; // check if we should send new heartbeat again - if(Now > m_RegisterStateStart+Freq) + if(Now > m_RegisterStateStart + Freq) { if(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers RegisterNewState(REGISTERSTATE_START); @@ -271,7 +271,7 @@ void CRegister::RegisterUpdate(int Nettype) else if(m_RegisterState == REGISTERSTATE_ERROR) { // check for restart - if(Now > m_RegisterStateStart+Freq*60) + if(Now > m_RegisterStateStart + Freq * 60) RegisterNewState(REGISTERSTATE_START); } } @@ -317,7 +317,7 @@ int CRegister::RegisterProcessPacket(CNetChunk *pPacket, SECURITY_TOKEN Response //RegisterNewState(REGISTERSTATE_ERROR); return 1; } - else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 && + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT) + 2 && mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) { RegisterGotCount(pPacket); diff --git a/src/engine/server/register.h b/src/engine/server/register.h index 86af0c93c..6dfed8c33 100644 --- a/src/engine/server/register.h +++ b/src/engine/server/register.h @@ -10,7 +10,7 @@ class CRegister { enum { - REGISTERSTATE_START=0, + REGISTERSTATE_START = 0, REGISTERSTATE_UPDATE_ADDRS, REGISTERSTATE_QUERY_COUNT, REGISTERSTATE_HEARTBEAT, diff --git a/src/engine/server/server.cpp b/src/engine/server/server.cpp index 9e96a4bd7..faef2f1eb 100644 --- a/src/engine/server/server.cpp +++ b/src/engine/server/server.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -26,28 +27,26 @@ #include #include #include -#include #include // DDRace -#include #include #include +#include #include #include "register.h" #include "server.h" #if defined(CONF_FAMILY_WINDOWS) - #define WIN32_LEAN_AND_MEAN - #include +#define WIN32_LEAN_AND_MEAN +#include #endif +#include #include #include -#include - CSnapIDPool::CSnapIDPool() { @@ -58,11 +57,11 @@ void CSnapIDPool::Reset() { for(int i = 0; i < MAX_IDS; i++) { - m_aIDs[i].m_Next = i+1; + m_aIDs[i].m_Next = i + 1; m_aIDs[i].m_State = 0; } - m_aIDs[MAX_IDS-1].m_Next = -1; + m_aIDs[MAX_IDS - 1].m_Next = -1; m_FirstFree = 0; m_FirstTimed = -1; m_LastTimed = -1; @@ -70,7 +69,6 @@ void CSnapIDPool::Reset() m_InUsage = 0; } - void CSnapIDPool::RemoveFirstTimeout() { int NextTimed = m_aIDs[m_FirstTimed].m_Next; @@ -122,7 +120,7 @@ void CSnapIDPool::FreeID(int ID) m_InUsage--; m_aIDs[ID].m_State = 2; - m_aIDs[ID].m_Timeout = time_get()+time_freq()*5; + m_aIDs[ID].m_Timeout = time_get() + time_freq() * 5; m_aIDs[ID].m_Next = -1; if(m_LastTimed != -1) @@ -137,7 +135,6 @@ void CSnapIDPool::FreeID(int ID) } } - void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer *pServer) { CNetBan::Init(pConsole, pStorage); @@ -145,9 +142,9 @@ void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer * m_pServer = pServer; // overwrites base command, todo: improve this - Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason"); - Console()->Register("ban_region", "s[region] s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanRegion, this, "Ban player in a region"); - Console()->Register("ban_region_range", "s[region] s[first ip] s[last ip] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanRegionRange, this, "Ban range in a region"); + Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER | CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason"); + Console()->Register("ban_region", "s[region] s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER | CFGFLAG_STORE, ConBanRegion, this, "Ban player in a region"); + Console()->Register("ban_region_range", "s[region] s[first ip] s[last ip] ?i[minutes] r[reason]", CFGFLAG_SERVER | CFGFLAG_STORE, ConBanRegionRange, this, "Ban range in a region"); } template @@ -232,8 +229,8 @@ void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser) CServerBan *pThis = static_cast(pUser); const char *pStr = pResult->GetString(0); - int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; - const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; + int Minutes = pResult->NumArguments() > 1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; + const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(2) : "No reason given"; if(str_isallnum(pStr)) { @@ -241,7 +238,7 @@ void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser) if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)"); else - pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason); + pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes * 60, pReason); } else ConBan(pResult, pUser); @@ -289,7 +286,8 @@ void CServer::CClient::Reset() m_DDNetVersionSettled = false; } -CServer::CServer(): m_Register(false), m_RegSixup(true) +CServer::CServer() : + m_Register(false), m_RegSixup(true) { for(int i = 0; i < MAX_CLIENTS; i++) m_aDemoRecorder[i] = CDemoRecorder(&m_SnapshotDelta, true); @@ -480,7 +478,7 @@ void CServer::Ban(int ClientID, int Seconds, const char *pReason) int64 CServer::TickStartTime(int Tick) { - return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED; + return m_GameStartTime + (time_freq() * Tick) / SERVER_TICK_SPEED; } /*int CServer::TickSpeed() @@ -576,7 +574,6 @@ void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size) net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false); } - const char *CServer::ClientName(int ClientID) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) @@ -585,7 +582,6 @@ const char *CServer::ClientName(int ClientID) return m_aClients[ClientID].m_aName; else return "(connecting)"; - } const char *CServer::ClientClan(int ClientID) @@ -711,11 +707,11 @@ static inline bool RepackMsg(const CMsgPacker *pMsg, CPacker &Packer, bool Sixup } } - Packer.AddInt((MsgId<<1)|(pMsg->m_System?1:0)); + Packer.AddInt((MsgId << 1) | (pMsg->m_System ? 1 : 0)); } else if(!Sixup) { - Packer.AddInt((0<<1)|(pMsg->m_System?1:0)); // NETMSG_EX, NETMSGTYPE_EX + Packer.AddInt((0 << 1) | (pMsg->m_System ? 1 : 0)); // NETMSG_EX, NETMSGTYPE_EX g_UuidManager.PackUuid(MsgId, &Packer); } Packer.AddRaw(pMsg->Data(), pMsg->Size()); @@ -730,9 +726,9 @@ int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) return -1; mem_zero(&Packet, sizeof(CNetChunk)); - if(Flags&MSGFLAG_VITAL) + if(Flags & MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; - if(Flags&MSGFLAG_FLUSH) + if(Flags & MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; if(ClientID < 0) @@ -744,10 +740,10 @@ int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) return -1; // write message to demo recorder - if(!(Flags&MSGFLAG_NORECORD)) + if(!(Flags & MSGFLAG_NORECORD)) m_aDemoRecorder[MAX_CLIENTS].RecordMessage(Pack6.Data(), Pack6.Size()); - if(!(Flags&MSGFLAG_NOSEND)) + if(!(Flags & MSGFLAG_NOSEND)) { for(int i = 0; i < MAX_CLIENTS; i++) { @@ -772,13 +768,13 @@ int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) Packet.m_pData = Pack.Data(); Packet.m_DataSize = Pack.Size(); - if(!(Flags&MSGFLAG_NORECORD)) + if(!(Flags & MSGFLAG_NORECORD)) { m_aDemoRecorder[ClientID].RecordMessage(Pack.Data(), Pack.Size()); m_aDemoRecorder[MAX_CLIENTS].RecordMessage(Pack.Data(), Pack.Size()); } - if(!(Flags&MSGFLAG_NOSEND)) + if(!(Flags & MSGFLAG_NOSEND)) m_NetServer.Send(&Packet); } @@ -793,11 +789,11 @@ void CServer::SendMsgRaw(int ClientID, const void *pData, int Size, int Flags) Packet.m_pData = pData; Packet.m_DataSize = Size; Packet.m_Flags = 0; - if(Flags&MSGFLAG_VITAL) + if(Flags & MSGFLAG_VITAL) { Packet.m_Flags |= NETSENDFLAG_VITAL; } - if(Flags&MSGFLAG_FLUSH) + if(Flags & MSGFLAG_FLUSH) { Packet.m_Flags |= NETSENDFLAG_FLUSH; } @@ -835,16 +831,16 @@ void CServer::DoSnapshot() continue; // this client is trying to recover, don't spam snapshots - if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0) + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick() % 50) != 0) continue; // this client is trying to recover, don't spam snapshots - if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0) + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick() % 10) != 0) continue; { char aData[CSnapshot::MAX_SIZE]; - CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing + CSnapshot *pData = (CSnapshot *)aData; // Fix compiler warning for strict-aliasing char aDeltaData[CSnapshot::MAX_SIZE]; char aCompData[CSnapshot::MAX_SIZE]; int SnapshotSize; @@ -876,7 +872,7 @@ void CServer::DoSnapshot() // remove old snapshos // keep 3 seconds worth of snapshots - m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3); + m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick - SERVER_TICK_SPEED * 3); // save it the snapshot m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0); @@ -909,7 +905,7 @@ void CServer::DoSnapshot() int NumPackets; SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData, sizeof(aCompData)); - NumPackets = (SnapshotSize+MaxSize-1)/MaxSize; + NumPackets = (SnapshotSize + MaxSize - 1) / MaxSize; for(int n = 0, Left = SnapshotSize; Left > 0; n++) { @@ -920,22 +916,22 @@ void CServer::DoSnapshot() { CMsgPacker Msg(NETMSG_SNAPSINGLE, true); Msg.AddInt(m_CurrentGameTick); - Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(m_CurrentGameTick - DeltaTick); Msg.AddInt(Crc); Msg.AddInt(Chunk); - Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + Msg.AddRaw(&aCompData[n * MaxSize], Chunk); SendMsg(&Msg, MSGFLAG_FLUSH, i); } else { CMsgPacker Msg(NETMSG_SNAP, true); Msg.AddInt(m_CurrentGameTick); - Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(m_CurrentGameTick - DeltaTick); Msg.AddInt(NumPackets); Msg.AddInt(n); Msg.AddInt(Crc); Msg.AddInt(Chunk); - Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + Msg.AddRaw(&aCompData[n * MaxSize], Chunk); SendMsg(&Msg, MSGFLAG_FLUSH, i); } } @@ -944,7 +940,7 @@ void CServer::DoSnapshot() { CMsgPacker Msg(NETMSG_SNAPEMPTY, true); Msg.AddInt(m_CurrentGameTick); - Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(m_CurrentGameTick - DeltaTick); SendMsg(&Msg, MSGFLAG_FLUSH, i); } } @@ -1051,7 +1047,7 @@ void CServer::InitDnsbl(int ClientID) } #ifdef CONF_FAMILY_UNIX -void CServer::SendConnLoggingCommand(CONN_LOGGING_CMD Cmd, const NETADDR* pAddr) +void CServer::SendConnLoggingCommand(CONN_LOGGING_CMD Cmd, const NETADDR *pAddr) { if(!g_Config.m_SvConnLoggingServer[0] || !m_ConnLoggingSocketCreated) return; @@ -1148,10 +1144,10 @@ void CServer::SendMap(int ClientID) if(Sixup) { Msg.AddInt(g_Config.m_SvMapWindow); - Msg.AddInt(1024-128); + Msg.AddInt(1024 - 128); Msg.AddRaw(m_aCurrentMapSha256[Sixup].data, sizeof(m_aCurrentMapSha256[Sixup].data)); } - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientID); } m_aClients[ClientID].m_NextMapChunk = 0; @@ -1160,7 +1156,7 @@ void CServer::SendMap(int ClientID) void CServer::SendMapData(int ClientID, int Chunk) { int Sixup = IsSixup(ClientID); - unsigned int ChunkSize = 1024-128; + unsigned int ChunkSize = 1024 - 128; unsigned int Offset = Chunk * ChunkSize; int Last = 0; @@ -1168,9 +1164,9 @@ void CServer::SendMapData(int ClientID, int Chunk) if(Chunk < 0 || Offset > m_aCurrentMapSize[Sixup]) return; - if(Offset+ChunkSize >= m_aCurrentMapSize[Sixup]) + if(Offset + ChunkSize >= m_aCurrentMapSize[Sixup]) { - ChunkSize = m_aCurrentMapSize[Sixup]-Offset; + ChunkSize = m_aCurrentMapSize[Sixup] - Offset; Last = 1; } @@ -1183,7 +1179,7 @@ void CServer::SendMapData(int ClientID, int Chunk) Msg.AddInt(ChunkSize); } Msg.AddRaw(&m_apCurrentMapData[Sixup][Offset], ChunkSize); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientID); if(g_Config.m_Debug) { @@ -1196,7 +1192,7 @@ void CServer::SendMapData(int ClientID, int Chunk) void CServer::SendConnectionReady(int ClientID) { CMsgPacker Msg(NETMSG_CON_READY, true); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientID); } void CServer::SendRconLine(int ClientID, const char *pLine) @@ -1212,7 +1208,8 @@ void CServer::SendRconLineAuthed(const char *pLine, void *pUser, bool Highlighte static volatile int ReentryGuard = 0; int i; - if(ReentryGuard) return; + if(ReentryGuard) + return; ReentryGuard++; const char *pStart = str_find(pLine, "<{"); @@ -1306,7 +1303,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) CMsgPacker Packer(NETMSG_EX, true); int GameFlags = 0; - if(pPacket->m_Flags&NET_CHUNKFLAG_VITAL) + if(pPacket->m_Flags & NET_CHUNKFLAG_VITAL) { GameFlags |= MSGFLAG_VITAL; } @@ -1335,12 +1332,12 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) float Alpha = g_Config.m_SvNetlimitAlpha / 100.0f; float Limit = (float)g_Config.m_SvNetlimit * 1024 / time_freq(); - if (m_aClients[ClientID].m_Traffic > Limit) + if(m_aClients[ClientID].m_Traffic > Limit) { m_NetServer.NetBan()->BanAddr(&pPacket->m_Address, 600, "Stressing network"); return; } - if (Diff > 100) + if(Diff > 100) { m_aClients[ClientID].m_Traffic = (Alpha * ((float)pPacket->m_DataSize / Diff)) + (1.0f - Alpha) * m_aClients[ClientID].m_Traffic; m_aClients[ClientID].m_TrafficSince = Now; @@ -1357,7 +1354,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) // system message if(Msg == NETMSG_CLIENTVER) { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_PREAUTH) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_PREAUTH) { CUuid *pConnectionID = (CUuid *)Unpacker.GetRaw(sizeof(*pConnectionID)); int DDNetVersion = Unpacker.GetInt(); @@ -1376,7 +1373,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) } else if(Msg == NETMSG_INFO) { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && (m_aClients[ClientID].m_State == CClient::STATE_PREAUTH || m_aClients[ClientID].m_State == CClient::STATE_AUTH)) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && (m_aClients[ClientID].m_State == CClient::STATE_PREAUTH || m_aClients[ClientID].m_State == CClient::STATE_AUTH)) { const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(!str_utf8_check(pVersion)) @@ -1419,7 +1416,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) } else if(Msg == NETMSG_REQUEST_MAP_DATA) { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) == 0 || m_aClients[ClientID].m_State < CClient::STATE_CONNECTING) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) == 0 || m_aClients[ClientID].m_State < CClient::STATE_CONNECTING) return; if(m_aClients[ClientID].m_Sixup) @@ -1450,13 +1447,13 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) } else if(Msg == NETMSG_READY) { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_CONNECTING) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_CONNECTING) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; - str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%d addr=<{%s}> secure=%s", ClientID, aAddrStr, m_NetServer.HasSecurityToken(ClientID)?"yes":"no"); + str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%d addr=<{%s}> secure=%s", ClientID, aAddrStr, m_NetServer.HasSecurityToken(ClientID) ? "yes" : "no"); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); m_aClients[ClientID].m_State = CClient::STATE_READY; GameServer()->OnClientConnected(ClientID); @@ -1466,7 +1463,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) } else if(Msg == NETMSG_ENTERGAME) { - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID)) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID)) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); @@ -1479,7 +1476,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) { CMsgPacker Msg(4, true, true); //NETMSG_SERVERINFO //TODO: Import the shared protocol from 7 aswell GetServerInfoSixup(&Msg, -1, false); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientID); } GameServer()->OnClientEnter(ClientID); } @@ -1494,20 +1491,20 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) int Size = Unpacker.GetInt(); // check for errors - if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE) + if(Unpacker.Error() || Size / 4 > MAX_INPUT_SIZE) return; if(m_aClients[ClientID].m_LastAckedSnapshot > 0) m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL; if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0) - m_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq()); + m_aClients[ClientID].m_Latency = (int)(((time_get() - TagTime) * 1000) / time_freq()); // add message to report the input timing // skip packets that are old if(IntendedTick > m_aClients[ClientID].m_LastInputTick) { - int TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq(); + int TimeLeft = ((TickStartTime(IntendedTick) - time_get()) * 1000) / time_freq(); CMsgPacker Msg(NETMSG_INPUTTIMING, true); Msg.AddInt(IntendedTick); @@ -1520,14 +1517,14 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput]; if(IntendedTick <= Tick()) - IntendedTick = Tick()+1; + IntendedTick = Tick() + 1; pInput->m_GameTick = IntendedTick; - for(int i = 0; i < Size/4; i++) + for(int i = 0; i < Size / 4; i++) pInput->m_aData[i] = Unpacker.GetInt(); - mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int)); + mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE * sizeof(int)); m_aClients[ClientID].m_CurrentInput++; m_aClients[ClientID].m_CurrentInput %= 200; @@ -1546,14 +1543,14 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) if(Unpacker.Error() == 0 && !str_comp(pCmd, "crashmeplx")) { int Version = m_aClients[ClientID].m_DDNetVersion; - if (GameServer()->PlayerExists(ClientID) && Version < VERSION_DDNET_OLD) + if(GameServer()->PlayerExists(ClientID) && Version < VERSION_DDNET_OLD) { m_aClients[ClientID].m_DDNetVersion = VERSION_DDNET_OLD; } } - else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) + else if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) { - if (GameServer()->PlayerExists(ClientID)) + if(GameServer()->PlayerExists(ClientID)) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd); @@ -1579,7 +1576,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) return; } - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0) { int AuthLevel = -1; int KeySlot = -1; @@ -1607,8 +1604,8 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) if(!IsSixup(ClientID)) { CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS, true); - Msg.AddInt(1); //authed - Msg.AddInt(1); //cmdlist + Msg.AddInt(1); //authed + Msg.AddInt(1); //cmdlist SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } else @@ -1626,26 +1623,26 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) char aBuf[256]; const char *pIdent = m_AuthManager.KeyIdent(KeySlot); - switch (AuthLevel) + switch(AuthLevel) { - case AUTHED_ADMIN: - { - SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted."); - str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (admin)", ClientID, pIdent); - break; - } - case AUTHED_MOD: - { - SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted."); - str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (moderator)", ClientID, pIdent); - break; - } - case AUTHED_HELPER: - { - SendRconLine(ClientID, "Helper authentication successful. Limited remote console access granted."); - str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (helper)", ClientID, pIdent); - break; - } + case AUTHED_ADMIN: + { + SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (admin)", ClientID, pIdent); + break; + } + case AUTHED_MOD: + { + SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (moderator)", ClientID, pIdent); + break; + } + case AUTHED_HELPER: + { + SendRconLine(ClientID, "Helper authentication successful. Limited remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed with key=%s (helper)", ClientID, pIdent); + break; + } } Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); @@ -1664,7 +1661,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) if(!g_Config.m_SvRconBantime) m_NetServer.Drop(ClientID, "Too many remote console authentication tries"); else - m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries"); + m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime * 60, "Too many remote console authentication tries"); } } else @@ -1687,10 +1684,10 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) for(int b = 0; b < pPacket->m_DataSize && b < 32; b++) { - aBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4]; - aBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf]; - aBuf[b*3+2] = ' '; - aBuf[b*3+3] = 0; + aBuf[b * 3] = aHex[((const unsigned char *)pPacket->m_pData)[b] >> 4]; + aBuf[b * 3 + 1] = aHex[((const unsigned char *)pPacket->m_pData)[b] & 0xf]; + aBuf[b * 3 + 2] = ' '; + aBuf[b * 3 + 3] = 0; } char aBufMsg[256]; @@ -1703,7 +1700,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) else { // game message - if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State >= CClient::STATE_READY) + if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State >= CClient::STATE_READY) GameServer()->OnMessage(Msg, &Unpacker, ClientID); } } @@ -1794,8 +1791,13 @@ void CServer::CacheServerInfo(CCache *pCache, int Type, bool SendClients) p.Reset(); - #define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x)) - #define ADD_INT(p, x) do { str_format(aBuf, sizeof(aBuf), "%d", x); (p).AddString(aBuf, 0); } while(0) +#define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x)) +#define ADD_INT(p, x) \ + do \ + { \ + str_format(aBuf, sizeof(aBuf), "%d", x); \ + (p).AddString(aBuf, 0); \ + } while(0) p.AddString(GameServer()->Version(), 32); if(Type != SERVERINFO_VANILLA) @@ -1859,19 +1861,19 @@ void CServer::CacheServerInfo(CCache *pCache, int Type, bool SendClients) int ChunksStored = 0; int PlayersStored = 0; - #define SAVE(size) \ - do \ - { \ - pCache->AddChunk(pp.Data(), size); \ - ChunksStored++; \ - } while(0) +#define SAVE(size) \ + do \ + { \ + pCache->AddChunk(pp.Data(), size); \ + ChunksStored++; \ + } while(0) - #define RESET() \ - do \ - { \ - pp.Reset(); \ - pp.AddRaw(pPrefix, PrefixSize); \ - } while(0) +#define RESET() \ + do \ + { \ + pp.Reset(); \ + pp.AddRaw(pPrefix, PrefixSize); \ + } while(0) RESET(); @@ -1954,10 +1956,10 @@ void CServer::CacheServerInfo(CCache *pCache, int Type, bool SendClients) } SAVE(pp.Size()); - #undef SAVE - #undef RESET - #undef ADD_RAW - #undef ADD_INT +#undef SAVE +#undef RESET +#undef ADD_RAW +#undef ADD_INT } void CServer::CacheServerInfoSixup(CCache *pCache, bool SendClients) @@ -1993,7 +1995,7 @@ void CServer::CacheServerInfoSixup(CCache *pCache, bool SendClients) // flags int Flags = SERVER_FLAG_TIMESCORE; - if(g_Config.m_Password[0]) // password set + if(g_Config.m_Password[0]) // password set Flags |= SERVER_FLAG_PASSWORD; Packer.AddInt(Flags); @@ -2014,7 +2016,7 @@ void CServer::CacheServerInfoSixup(CCache *pCache, bool SendClients) Packer.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan Packer.AddInt(m_aClients[i].m_Country); // client country Packer.AddInt(m_aClients[i].m_Score == -9999 ? -1 : -m_aClients[i].m_Score); // client score - Packer.AddInt(GameServer()->IsClientPlayer(i)?0:1); // flag spectator=1, bot=2 (player=0) + Packer.AddInt(GameServer()->IsClientPlayer(i) ? 0 : 1); // flag spectator=1, bot=2 (player=0) } } } @@ -2030,8 +2032,13 @@ void CServer::SendServerInfo(const NETADDR *pAddr, int Token, int Type, bool Sen CCache *pCache = &m_ServerInfoCache[GetCacheIndex(Type, SendClients)]; - #define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x)) - #define ADD_INT(p, x) do { str_format(aBuf, sizeof(aBuf), "%d", x); (p).AddString(aBuf, 0); } while(0) +#define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x)) +#define ADD_INT(p, x) \ + do \ + { \ + str_format(aBuf, sizeof(aBuf), "%d", x); \ + (p).AddString(aBuf, 0); \ + } while(0) CNetChunk Packet; Packet.m_ClientID = -1; @@ -2054,7 +2061,7 @@ void CServer::SendServerInfo(const NETADDR *pAddr, int Token, int Type, bool Sen ADD_RAW(p, SERVERBROWSE_INFO_64_LEGACY); ADD_INT(p, Token); } - else if (Type == SERVERINFO_VANILLA || Type == SERVERINFO_INGAME) + else if(Type == SERVERINFO_VANILLA || Type == SERVERINFO_INGAME) { ADD_RAW(p, SERVERBROWSE_INFO); ADD_INT(p, Token); @@ -2115,7 +2122,7 @@ void CServer::UpdateServerInfo(bool Resend) { CMsgPacker Msg(4, true, true); //NETMSG_SERVERINFO //TODO: Import the shared protocol from 7 aswell GetServerInfoSixup(&Msg, -1, false); - SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, i); + SendMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_FLUSH, i); } } } @@ -2213,10 +2220,10 @@ char *CServer::GetMapName() { // get the name of the map without his path char *pMapShortName = &g_Config.m_SvMap[0]; - for(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++) + for(int i = 0; i < str_length(g_Config.m_SvMap) - 1; i++) { if(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\') - pMapShortName = &g_Config.m_SvMap[i+1]; + pMapShortName = &g_Config.m_SvMap[i + 1]; } return pMapShortName; } @@ -2231,7 +2238,7 @@ int CServer::LoadMap(const char *pMapName) return 0; // stop recording when we change map - for(int i = 0; i < MAX_CLIENTS+1; i++) + for(int i = 0; i < MAX_CLIENTS + 1; i++) { if(!m_aDemoRecorder[i].IsRecording()) continue; @@ -2302,7 +2309,7 @@ int CServer::LoadMap(const char *pMapName) } } - for(int i=0; i(new CSqliteConnection( - g_Config.m_SvSqliteFile, true)); + g_Config.m_SvSqliteFile, true)); if(g_Config.m_SvUseSQL) { @@ -2362,16 +2369,16 @@ int CServer::Run() BindAddr.type = NetType; int Port = g_Config.m_SvPort; - for(BindAddr.port = Port != 0 ? Port : 8303; !m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0); BindAddr.port++) + for(BindAddr.port = Port != 0 ? Port : 8303; !m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0); BindAddr.port++) { - if(Port != 0 || BindAddr.port >= 8310) + if(Port != 0 || BindAddr.port >= 8310) { dbg_msg("server", "couldn't open socket. port %d might already be in use", BindAddr.port); return -1; } } - if(Port == 0) + if(Port == 0) dbg_msg("server", "using port %d", BindAddr.port); #if defined(CONF_UPNP) @@ -2469,23 +2476,22 @@ int CServer::Run() } // handle dnsbl - if (g_Config.m_SvDnsbl) + if(g_Config.m_SvDnsbl) { - for (int ClientID = 0; ClientID < MAX_CLIENTS; ClientID++) + for(int ClientID = 0; ClientID < MAX_CLIENTS; ClientID++) { - if (m_aClients[ClientID].m_State == CClient::STATE_EMPTY) + if(m_aClients[ClientID].m_State == CClient::STATE_EMPTY) continue; - if (m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_NONE) + if(m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_NONE) { // initiate dnsbl lookup InitDnsbl(ClientID); } - else if (m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_PENDING && - m_aClients[ClientID].m_pDnsblLookup->Status() == IJob::STATE_DONE) + else if(m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_PENDING && + m_aClients[ClientID].m_pDnsblLookup->Status() == IJob::STATE_DONE) { - - if (m_aClients[ClientID].m_pDnsblLookup->m_Result != 0) + if(m_aClients[ClientID].m_pDnsblLookup->m_Result != 0) { // entry not found -> whitelisted m_aClients[ClientID].m_DnsblState = CClient::DNSBL_STATE_WHITELISTED; @@ -2501,19 +2507,19 @@ int CServer::Run() char aBuf[256]; - str_format(aBuf, sizeof(aBuf), "ClientID=%d addr=<{%s}> secure=%s blacklisted", ClientID, aAddrStr, m_NetServer.HasSecurityToken(ClientID)?"yes":"no"); + str_format(aBuf, sizeof(aBuf), "ClientID=%d addr=<{%s}> secure=%s blacklisted", ClientID, aAddrStr, m_NetServer.HasSecurityToken(ClientID) ? "yes" : "no"); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "dnsbl", aBuf); } } - if (m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_BLACKLISTED && - g_Config.m_SvDnsblBan) - m_NetServer.NetBan()->BanAddr(m_NetServer.ClientAddr(ClientID), 60*10, "VPN detected, try connecting without. Contact admin if mistaken"); + if(m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_BLACKLISTED && + g_Config.m_SvDnsblBan) + m_NetServer.NetBan()->BanAddr(m_NetServer.ClientAddr(ClientID), 60 * 10, "VPN detected, try connecting without. Contact admin if mistaken"); } } - while(t > TickStartTime(m_CurrentGameTick+1)) + while(t > TickStartTime(m_CurrentGameTick + 1)) { for(int c = 0; c < MAX_CLIENTS; c++) if(m_aClients[c].m_State == CClient::STATE_INGAME) @@ -2549,7 +2555,7 @@ int CServer::Run() // snap game if(NewTicks) { - if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0) + if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick % 2) == 0) DoSnapshot(); UpdateClientRconCommands(); @@ -2579,7 +2585,7 @@ int CServer::Run() NonActive = false; // wait for incoming data - if (NonActive) + if(NonActive) { if(g_Config.m_SvReloadWhenEmpty == 1) { @@ -2603,7 +2609,7 @@ int CServer::Run() set_new_tick(); int64 t = time_get(); - int x = (TickStartTime(m_CurrentGameTick+1) - t) * 1000000 / time_freq() + 1; + int x = (TickStartTime(m_CurrentGameTick + 1) - t) * 1000000 / time_freq() + 1; PacketWaiting = x > 0 ? net_socket_read_wait(m_NetServer.Socket(), x) : true; } @@ -2637,7 +2643,7 @@ int CServer::Run() DbPool()->OnShutdown(); delete m_pConnectionPool; -#if defined (CONF_UPNP) +#if defined(CONF_UPNP) m_UPnP.Shutdown(); #endif @@ -2648,14 +2654,14 @@ void CServer::ConTestingCommands(CConsole::IResult *pResult, void *pUser) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Value: %d", g_Config.m_SvTestingCommands); - ((CConsole*)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + ((CConsole *)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); } void CServer::ConRescue(CConsole::IResult *pResult, void *pUser) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Value: %d", g_Config.m_SvRescue); - ((CConsole*)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + ((CConsole *)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); } void CServer::ConKick(IConsole::IResult *pResult, void *pUser) @@ -2693,8 +2699,8 @@ void CServer::ConStatus(IConsole::IResult *pResult, void *pUser) if(g_Config.m_SvDnsbl) { const char *pDnsblStr = pThis->m_aClients[i].m_DnsblState == CClient::DNSBL_STATE_WHITELISTED ? "white" : - pThis->m_aClients[i].m_DnsblState == CClient::DNSBL_STATE_BLACKLISTED ? "black" : - pThis->m_aClients[i].m_DnsblState == CClient::DNSBL_STATE_PENDING ? "pending" : "n/a"; + pThis->m_aClients[i].m_DnsblState == CClient::DNSBL_STATE_BLACKLISTED ? "black" : + pThis->m_aClients[i].m_DnsblState == CClient::DNSBL_STATE_PENDING ? "pending" : "n/a"; str_format(aDnsblStr, sizeof(aDnsblStr), " dnsbl=%s", pDnsblStr); } @@ -2704,8 +2710,8 @@ void CServer::ConStatus(IConsole::IResult *pResult, void *pUser) if(pThis->m_aClients[i].m_AuthKey >= 0) { const char *pAuthStr = pThis->m_aClients[i].m_Authed == AUTHED_ADMIN ? "(Admin)" : - pThis->m_aClients[i].m_Authed == AUTHED_MOD ? "(Mod)" : - pThis->m_aClients[i].m_Authed == AUTHED_HELPER ? "(Helper)" : ""; + pThis->m_aClients[i].m_Authed == AUTHED_MOD ? "(Mod)" : + pThis->m_aClients[i].m_Authed == AUTHED_HELPER ? "(Helper)" : ""; str_format(aAuthStr, sizeof(aAuthStr), " key=%s %s", pThis->m_AuthManager.KeyIdent(pThis->m_aClients[i].m_AuthKey), pAuthStr); } @@ -3128,16 +3134,16 @@ void CServer::ConAddSqlServer(IConsole::IResult *pResult, void *pUserData) return; CServer *pSelf = (CServer *)pUserData; - if (pResult->NumArguments() != 7 && pResult->NumArguments() != 8) + if(pResult->NumArguments() != 7 && pResult->NumArguments() != 8) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "7 or 8 arguments are required"); return; } bool ReadOnly; - if (str_comp_nocase(pResult->GetString(0), "w") == 0) + if(str_comp_nocase(pResult->GetString(0), "w") == 0) ReadOnly = false; - else if (str_comp_nocase(pResult->GetString(0), "r") == 0) + else if(str_comp_nocase(pResult->GetString(0), "r") == 0) ReadOnly = true; else { @@ -3148,16 +3154,16 @@ void CServer::ConAddSqlServer(IConsole::IResult *pResult, void *pUserData) bool SetUpDb = pResult->NumArguments() == 8 ? pResult->GetInteger(7) : true; auto pSqlServers = std::unique_ptr(new CMysqlConnection( - pResult->GetString(1), pResult->GetString(2), pResult->GetString(3), - pResult->GetString(4), pResult->GetString(5), pResult->GetInteger(6), - SetUpDb)); + pResult->GetString(1), pResult->GetString(2), pResult->GetString(3), + pResult->GetString(4), pResult->GetString(5), pResult->GetInteger(6), + SetUpDb)); char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "Added new Sql%sServer: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d", - ReadOnly ? "Read" : "Write", - pResult->GetString(1), pResult->GetString(2), pResult->GetString(3), - pResult->GetString(5), pResult->GetInteger(6)); + "Added new Sql%sServer: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d", + ReadOnly ? "Read" : "Write", + pResult->GetString(1), pResult->GetString(2), pResult->GetString(3), + pResult->GetString(5), pResult->GetInteger(6)); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); pSelf->DbPool()->RegisterDatabase(std::move(pSqlServers), ReadOnly ? CDbConnectionPool::READ : CDbConnectionPool::WRITE); } @@ -3180,7 +3186,6 @@ void CServer::ConDumpSqlServers(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "choose either 'r' for SqlReadServer or 'w' for SqlWriteServer"); return; } - } void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) @@ -3215,9 +3220,9 @@ void CServer::ConchainCommandAccessUpdate(IConsole::IResult *pResult, void *pUse for(int i = 0; i < MAX_CLIENTS; ++i) { if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || - (pInfo->GetAccessLevel() > AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed < OldAccessLevel) || - (pInfo->GetAccessLevel() < AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed > OldAccessLevel) || - (pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0)) + (pInfo->GetAccessLevel() > AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed < OldAccessLevel) || + (pInfo->GetAccessLevel() < AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed > OldAccessLevel) || + (pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0)) continue; if(OldAccessLevel < pInfo->GetAccessLevel()) @@ -3246,8 +3251,8 @@ void CServer::LogoutClient(int ClientID, const char *pReason) if(!IsSixup(ClientID)) { CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS, true); - Msg.AddInt(0); //authed - Msg.AddInt(0); //cmdlist + Msg.AddInt(0); //authed + Msg.AddInt(0); //cmdlist SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } else @@ -3378,19 +3383,19 @@ void CServer::RegisterCommands() Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon"); Console()->Register("show_ips", "?i[show]", CFGFLAG_SERVER, ConShowIps, this, "Show IP addresses in rcon commands (1 = on, 0 = off)"); - Console()->Register("record", "?s[file]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file"); + Console()->Register("record", "?s[file]", CFGFLAG_SERVER | CFGFLAG_STORE, ConRecord, this, "Record to a file"); Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording"); Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map"); - Console()->Register("add_sqlserver", "s['r'|'w'] s[Database] s[Prefix] s[User] s[Password] s[IP] i[Port] ?i[SetUpDatabase ?]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAddSqlServer, this, "add a sqlserver"); + Console()->Register("add_sqlserver", "s['r'|'w'] s[Database] s[Prefix] s[User] s[Password] s[IP] i[Port] ?i[SetUpDatabase ?]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAddSqlServer, this, "add a sqlserver"); Console()->Register("dump_sqlservers", "s['r'|'w']", CFGFLAG_SERVER, ConDumpSqlServers, this, "dumps all sqlservers readservers = r, writeservers = w"); - Console()->Register("auth_add", "s[ident] s[level] s[pw]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAuthAdd, this, "Add a rcon key"); - Console()->Register("auth_add_p", "s[ident] s[level] s[hash] s[salt]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAuthAddHashed, this, "Add a prehashed rcon key"); - Console()->Register("auth_change", "s[ident] s[level] s[pw]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAuthUpdate, this, "Update a rcon key"); - Console()->Register("auth_change_p", "s[ident] s[level] s[hash] s[salt]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAuthUpdateHashed, this, "Update a rcon key with prehashed data"); - Console()->Register("auth_remove", "s[ident]", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, ConAuthRemove, this, "Remove a rcon key"); + Console()->Register("auth_add", "s[ident] s[level] s[pw]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAuthAdd, this, "Add a rcon key"); + Console()->Register("auth_add_p", "s[ident] s[level] s[hash] s[salt]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAuthAddHashed, this, "Add a prehashed rcon key"); + Console()->Register("auth_change", "s[ident] s[level] s[pw]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAuthUpdate, this, "Update a rcon key"); + Console()->Register("auth_change_p", "s[ident] s[level] s[hash] s[salt]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAuthUpdateHashed, this, "Update a rcon key with prehashed data"); + Console()->Register("auth_remove", "s[ident]", CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConAuthRemove, this, "Remove a rcon key"); Console()->Register("auth_list", "", CFGFLAG_SERVER, ConAuthList, this, "List all rcon keys"); Console()->Register("name_ban", "s[name] ?i[distance] ?i[is_substring] ?r[reason]", CFGFLAG_SERVER, ConNameBan, this, "Ban a certain nick name"); @@ -3417,7 +3422,6 @@ void CServer::RegisterCommands() m_pGameServer->OnConsoleInit(); } - int CServer::SnapNewID() { return m_IDPool.NewID(); @@ -3428,8 +3432,6 @@ void CServer::SnapFreeID(int ID) m_IDPool.FreeID(ID); } - - void *CServer::SnapNewItem(int Type, int ID, int Size) { if(Type > 0xffff) @@ -3476,7 +3478,7 @@ int main(int argc, const char **argv) // ignore_convention IEngine *pEngine = CreateEngine("DDNet", Silent, 2); IEngineMap *pEngineMap = CreateEngineMap(); IGameServer *pGameServer = CreateGameServer(); - IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON); + IConsole *pConsole = CreateConsole(CFGFLAG_SERVER | CFGFLAG_ECON); IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention IConfig *pConfig = CreateConfig(); @@ -3490,15 +3492,15 @@ int main(int argc, const char **argv) // ignore_convention RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineMap); // register as both - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMap), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineMasterServer); // register as both - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineMasterServer), false); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngineAntibot); - RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineAntibot), false); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast(pEngineAntibot), false); if(RegisterFail) { @@ -3529,7 +3531,7 @@ int main(int argc, const char **argv) // ignore_convention // parse the command line arguments if(argc > 1) // ignore_convention - pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + pConsole->ParseArguments(argc - 1, &argv[1]); // ignore_convention pConsole->Register("sv_test_cmds", "", CFGFLAG_SERVER, CServer::ConTestingCommands, pConsole, "Turns testing commands aka cheats on/off (setting only works in initial config)"); pConsole->Register("sv_rescue", "", CFGFLAG_SERVER, CServer::ConRescue, pConsole, "Allow /rescue command so players can teleport themselves out of freeze (setting only works in initial config)"); @@ -3562,13 +3564,13 @@ const char *CServer::GetAnnouncementLine(char const *pFileName) if(!File) return 0; - std::vector v; + std::vector v; char *pLine; CLineReader *lr = new CLineReader(); lr->Init(File); while((pLine = lr->Get())) if(str_length(pLine)) - if(pLine[0]!='#') + if(pLine[0] != '#') v.push_back(pLine); if(v.size() == 1) { @@ -3601,7 +3603,7 @@ int *CServer::GetIdMap(int ClientID) bool CServer::SetTimedOut(int ClientID, int OrigID) { - if (!m_NetServer.SetTimedOut(ClientID, OrigID)) + if(!m_NetServer.SetTimedOut(ClientID, OrigID)) { return false; } diff --git a/src/engine/server/server.h b/src/engine/server/server.h index 3868c1b2b..8cc7236f0 100644 --- a/src/engine/server/server.h +++ b/src/engine/server/server.h @@ -10,15 +10,15 @@ #include #include -#include -#include -#include -#include #include #include +#include #include #include #include +#include +#include +#include #include #include @@ -29,15 +29,15 @@ #include "authmanager.h" #include "name_ban.h" -#if defined (CONF_UPNP) - #include "upnp.h" +#if defined(CONF_UPNP) +#include "upnp.h" #endif class CSnapIDPool { enum { - MAX_IDS = 16*1024, + MAX_IDS = 16 * 1024, }; class CID @@ -57,7 +57,6 @@ class CSnapIDPool int m_InUsage; public: - CSnapIDPool(); void Reset(); @@ -67,12 +66,12 @@ public: void FreeID(int ID); }; - class CServerBan : public CNetBan { class CServer *m_pServer; - template int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + template + int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); public: class CServer *Server() const { return m_pServer; } @@ -87,7 +86,6 @@ public: static void ConBanRegionRange(class IConsole::IResult *pResult, void *pUser); }; - class CServer : public IServer { class IGameServer *m_pGameServer; @@ -116,13 +114,12 @@ public: enum { - MAX_RCONCMD_SEND=16, + MAX_RCONCMD_SEND = 16, }; class CClient { public: - enum { STATE_EMPTY = 0, @@ -132,11 +129,11 @@ public: STATE_READY, STATE_INGAME, - SNAPRATE_INIT=0, + SNAPRATE_INIT = 0, SNAPRATE_FULL, SNAPRATE_RECOVER, - DNSBL_STATE_NONE=0, + DNSBL_STATE_NONE = 0, DNSBL_STATE_PENDING, DNSBL_STATE_BLACKLISTED, DNSBL_STATE_WHITELISTED, @@ -217,9 +214,9 @@ public: enum { - UNINITIALIZED=0, - RUNNING=1, - STOPPING=2 + UNINITIALIZED = 0, + RUNNING = 1, + STOPPING = 2 }; int m_RunServer; @@ -235,7 +232,7 @@ public: enum { - SIX=0, + SIX = 0, SIXUP, }; @@ -245,7 +242,7 @@ public: unsigned char *m_apCurrentMapData[2]; unsigned int m_aCurrentMapSize[2]; - CDemoRecorder m_aDemoRecorder[MAX_CLIENTS+1]; + CDemoRecorder m_aDemoRecorder[MAX_CLIENTS + 1]; CRegister m_Register; CRegister m_RegSixup; CAuthManager m_AuthManager; @@ -322,9 +319,11 @@ public: void ProcessClientPacket(CNetChunk *pPacket); - class CCache { + class CCache + { public: - class CCacheChunk { + class CCacheChunk + { public: CCacheChunk(const void *pData, int Size); CCacheChunk(const CCacheChunk &) = delete; @@ -412,7 +411,6 @@ public: void RegisterCommands(); - virtual int SnapNewID(); virtual void SnapFreeID(int ID); virtual void *SnapNewItem(int Type, int ID, int Size); @@ -426,13 +424,13 @@ public: unsigned m_AnnouncementLastLine; void RestrictRconOutput(int ClientID) { m_RconRestrict = ClientID; } - virtual int* GetIdMap(int ClientID); + virtual int *GetIdMap(int ClientID); void InitDnsbl(int ClientID); bool DnsblWhite(int ClientID) { return m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_NONE || - m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_WHITELISTED; + m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_WHITELISTED; } bool DnsblPending(int ClientID) { @@ -460,13 +458,12 @@ public: #ifdef CONF_FAMILY_UNIX enum CONN_LOGGING_CMD { - OPEN_SESSION=1, - CLOSE_SESSION=2, + OPEN_SESSION = 1, + CLOSE_SESSION = 2, }; void SendConnLoggingCommand(CONN_LOGGING_CMD cmd, const NETADDR *pAddr); #endif - }; #endif diff --git a/src/engine/server/sql_string_helpers.cpp b/src/engine/server/sql_string_helpers.cpp index 5de0c4bf2..e07457dd4 100644 --- a/src/engine/server/sql_string_helpers.cpp +++ b/src/engine/server/sql_string_helpers.cpp @@ -6,7 +6,7 @@ void sqlstr::FuzzyString(char *pString, int size) { - char * newString = new char [size * 4 - 1]; + char *newString = new char[size * 4 - 1]; int pos = 0; for(int i = 0; i < size; i++) @@ -15,13 +15,13 @@ void sqlstr::FuzzyString(char *pString, int size) break; newString[pos++] = pString[i]; - if (pString[i] != '\\' && str_utf8_isstart(pString[i+1])) + if(pString[i] != '\\' && str_utf8_isstart(pString[i + 1])) newString[pos++] = '%'; } newString[pos] = '\0'; str_copy(pString, newString, size); - delete [] newString; + delete[] newString; } int sqlstr::EscapeLike(char *pDst, const char *pSrc, int DstSize) @@ -35,7 +35,6 @@ int sqlstr::EscapeLike(char *pDst, const char *pSrc, int DstSize) if(pSrc[Pos] == '\\' || pSrc[Pos] == '%' || pSrc[Pos] == '_' || pSrc[Pos] == '[') pDst[DstPos++] = '\\'; pDst[DstPos++] = pSrc[Pos++]; - } pDst[DstPos++] = '\0'; return DstPos; @@ -45,25 +44,23 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString) { char aBuf[20]; int aTimes[7] = - { - 60 * 60 * 24 * 365 , - 60 * 60 * 24 * 30 , + { + 60 * 60 * 24 * 365, + 60 * 60 * 24 * 30, 60 * 60 * 24 * 7, - 60 * 60 * 24 , - 60 * 60 , - 60 , - 1 - }; + 60 * 60 * 24, + 60 * 60, + 60, + 1}; char aaNames[7][6] = - { + { "year", "month", "week", "day", "hour", "min", - "sec" - }; + "sec"}; int Seconds = 0; char aName[6]; @@ -76,7 +73,7 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString) Seconds = aTimes[i]; strcpy(aName, aaNames[i]); - Count = floor((float)AgoTime/(float)Seconds); + Count = floor((float)AgoTime / (float)Seconds); if(Count != 0) { break; @@ -85,33 +82,33 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString) if(Count == 1) { - str_format(aBuf, sizeof(aBuf), "%d %s", 1 , aName); + str_format(aBuf, sizeof(aBuf), "%d %s", 1, aName); } else { - str_format(aBuf, sizeof(aBuf), "%d %ss", Count , aName); + str_format(aBuf, sizeof(aBuf), "%d %ss", Count, aName); } strcat(pAgoString, aBuf); - if (i + 1 < 7) + if(i + 1 < 7) { // getting second piece now - int Seconds2 = aTimes[i+1]; + int Seconds2 = aTimes[i + 1]; char aName2[6]; - strcpy(aName2, aaNames[i+1]); + strcpy(aName2, aaNames[i + 1]); // add second piece if it's greater than 0 int Count2 = floor((float)(AgoTime - (Seconds * Count)) / (float)Seconds2); - if (Count2 != 0) + if(Count2 != 0) { if(Count2 == 1) { - str_format(aBuf, sizeof(aBuf), " and %d %s", 1 , aName2); + str_format(aBuf, sizeof(aBuf), " and %d %s", 1, aName2); } else { - str_format(aBuf, sizeof(aBuf), " and %d %ss", Count2 , aName2); + str_format(aBuf, sizeof(aBuf), " and %d %ss", Count2, aName2); } strcat(pAgoString, aBuf); } diff --git a/src/engine/server/sql_string_helpers.h b/src/engine/server/sql_string_helpers.h index a827343e5..27557c9f3 100644 --- a/src/engine/server/sql_string_helpers.h +++ b/src/engine/server/sql_string_helpers.h @@ -1,8 +1,7 @@ #ifndef ENGINE_SERVER_SQL_STRING_HELPERS_H #define ENGINE_SERVER_SQL_STRING_HELPERS_H -namespace sqlstr -{ +namespace sqlstr { void FuzzyString(char *pString, int size); @@ -11,6 +10,6 @@ int EscapeLike(char *pDst, const char *pSrc, int DstSize); void AgoTimeToString(int agoTime, char *pAgoString); -} +} // namespace sqlstr #endif diff --git a/src/engine/server/upnp.cpp b/src/engine/server/upnp.cpp index 6649d14fd..519760bc7 100644 --- a/src/engine/server/upnp.cpp +++ b/src/engine/server/upnp.cpp @@ -1,12 +1,12 @@ #ifdef CONF_UPNP +#include "upnp.h" +#include +#include +#include #include #include #include -#include -#include -#include -#include "upnp.h" void CUPnP::Open(NETADDR Address) { @@ -31,10 +31,10 @@ void CUPnP::Open(NETADDR Address) m_Enabled = true; dbg_msg("upnp", "found valid IGD: %s", m_UPnPUrls->controlURL); str_format(aPort, sizeof(aPort), "%d", m_Addr.port); - Error = UPNP_AddPortMapping(m_UPnPUrls->controlURL, m_UPnPData->first.servicetype, - aPort, aPort, aLanAddr, - "DDNet Server " GAME_RELEASE_VERSION, - "UDP", NULL, "0"); + Error = UPNP_AddPortMapping(m_UPnPUrls->controlURL, m_UPnPData->first.servicetype, + aPort, aPort, aLanAddr, + "DDNet Server " GAME_RELEASE_VERSION, + "UDP", NULL, "0"); if(Error) dbg_msg("upnp", "failed to map port, error: %s", strupnperror(Error)); @@ -68,7 +68,6 @@ void CUPnP::Shutdown() m_UPnPUrls = NULL; m_UPnPData = NULL; } - } #endif \ No newline at end of file diff --git a/src/engine/server/upnp.h b/src/engine/server/upnp.h index 58a269ea4..adbb90e93 100644 --- a/src/engine/server/upnp.h +++ b/src/engine/server/upnp.h @@ -12,7 +12,7 @@ class CUPnP public: void Open(NETADDR Address); - void Shutdown(); + void Shutdown(); }; #endif diff --git a/src/engine/serverbrowser.h b/src/engine/serverbrowser.h index 1b67bc717..014c044d2 100644 --- a/src/engine/serverbrowser.h +++ b/src/engine/serverbrowser.h @@ -81,7 +81,6 @@ class IServerBrowser : public IInterface { MACRO_INTERFACE("serverbrowser", 0) public: - /* Constants: Server Browser Sorting SORT_NAME - Sort by name. SORT_PING - Sort by ping. @@ -89,16 +88,17 @@ public: SORT_GAMETYPE - Sort by game type. DM, TDM etc. SORT_NUMPLAYERS - Sort after how many players there are on the server. */ - enum{ + enum + { SORT_NAME = 0, SORT_PING, SORT_MAP, SORT_GAMETYPE, SORT_NUMPLAYERS, - QUICK_SERVERNAME=1, - QUICK_PLAYER=2, - QUICK_MAPNAME=4, + QUICK_SERVERNAME = 1, + QUICK_PLAYER = 2, + QUICK_MAPNAME = 4, TYPE_NONE = 0, TYPE_INTERNET = 1, @@ -107,14 +107,14 @@ public: TYPE_DDNET = 4, TYPE_KOG = 5, - SET_MASTER_ADD=1, + SET_MASTER_ADD = 1, SET_FAV_ADD, SET_DDNET_ADD, SET_KOG_ADD, SET_TOKEN, - NETWORK_DDNET=0, - NETWORK_KOG=1, + NETWORK_DDNET = 0, + NETWORK_KOG = 1, NUM_NETWORKS, }; diff --git a/src/engine/shared/compression.cpp b/src/engine/shared/compression.cpp index fb67a5fc6..a9a8a7be9 100644 --- a/src/engine/shared/compression.cpp +++ b/src/engine/shared/compression.cpp @@ -7,10 +7,10 @@ // Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) { - *pDst = (i>>25)&0x40; // set sign bit if i<0 - i = i^(i>>31); // if(i<0) i = ~i + *pDst = (i >> 25) & 0x40; // set sign bit if i<0 + i = i ^ (i >> 31); // if(i<0) i = ~i - *pDst |= i&0x3F; // pack 6bit into dst + *pDst |= i & 0x3F; // pack 6bit into dst i >>= 6; // discard 6 bits if(i) { @@ -18,9 +18,9 @@ unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) while(1) { pDst++; - *pDst = i&(0x7F); // pack 7bit + *pDst = i & (0x7F); // pack 7bit i >>= 7; // discard 7 bits - *pDst |= (i!=0)<<7; // set extend bit (may branch) + *pDst |= (i != 0) << 7; // set extend bit (may branch) if(!i) break; } @@ -32,26 +32,30 @@ unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut) { - int Sign = (*pSrc>>6)&1; - *pInOut = *pSrc&0x3F; + int Sign = (*pSrc >> 6) & 1; + *pInOut = *pSrc & 0x3F; do { - if(!(*pSrc&0x80)) break; + if(!(*pSrc & 0x80)) + break; pSrc++; - *pInOut |= (*pSrc&(0x7F))<<(6); + *pInOut |= (*pSrc & (0x7F)) << (6); - if(!(*pSrc&0x80)) break; + if(!(*pSrc & 0x80)) + break; pSrc++; - *pInOut |= (*pSrc&(0x7F))<<(6+7); + *pInOut |= (*pSrc & (0x7F)) << (6 + 7); - if(!(*pSrc&0x80)) break; + if(!(*pSrc & 0x80)) + break; pSrc++; - *pInOut |= (*pSrc&(0x7F))<<(6+7+7); + *pInOut |= (*pSrc & (0x7F)) << (6 + 7 + 7); - if(!(*pSrc&0x80)) break; + if(!(*pSrc & 0x80)) + break; pSrc++; - *pInOut |= (*pSrc&(0x7F))<<(6+7+7+7); + *pInOut |= (*pSrc & (0x7F)) << (6 + 7 + 7 + 7); } while(0); pSrc++; @@ -59,7 +63,6 @@ const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut return pSrc; } - long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_, int DstSize) { const unsigned char *pSrc = (unsigned char *)pSrc_; @@ -73,7 +76,7 @@ long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_, int DstS pSrc = CVariableInt::Unpack(pSrc, pDst); pDst++; } - return (unsigned char *)pDst-(unsigned char *)pDst_; + return (unsigned char *)pDst - (unsigned char *)pDst_; } long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_, int DstSize) @@ -90,5 +93,5 @@ long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_, int DstSiz Size--; pSrc++; } - return pDst-(unsigned char *)pDst_; + return pDst - (unsigned char *)pDst_; } diff --git a/src/engine/shared/config.cpp b/src/engine/shared/config.cpp index 5e9cc5d19..b33c77ca6 100644 --- a/src/engine/shared/config.cpp +++ b/src/engine/shared/config.cpp @@ -1,9 +1,9 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include #include #include +#include CConfiguration g_Config; @@ -33,7 +33,6 @@ class CConfig : public IConfig } public: - CConfig() { m_ConfigFile = 0; @@ -49,15 +48,15 @@ public: virtual void Reset() { - #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) g_Config.m_##Name = def; - #define MACRO_CONFIG_COL(Name,ScriptName,def,flags,desc) MACRO_CONFIG_INT(Name,ScriptName,def,0,0,flags,desc) - #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(g_Config.m_##Name, def, len); +#define MACRO_CONFIG_INT(Name, ScriptName, def, min, max, flags, desc) g_Config.m_##Name = def; +#define MACRO_CONFIG_COL(Name, ScriptName, def, flags, desc) MACRO_CONFIG_INT(Name, ScriptName, def, 0, 0, flags, desc) +#define MACRO_CONFIG_STR(Name, ScriptName, len, def, flags, desc) str_copy(g_Config.m_##Name, def, len); - #include "config_variables.h" +#include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR } virtual void Save() @@ -75,18 +74,34 @@ public: m_Failed = false; - char aLineBuf[1024*2]; - char aEscapeBuf[1024*2]; + char aLineBuf[1024 * 2]; + char aEscapeBuf[1024 * 2]; - #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) { str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); } - #define MACRO_CONFIG_COL(Name,ScriptName,def,flags,desc) if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) { str_format(aLineBuf, sizeof(aLineBuf), "%s %u", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); } - #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if((flags)&CFGFLAG_SAVE && str_comp(g_Config.m_##Name, def) != 0) { EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); } +#define MACRO_CONFIG_INT(Name, ScriptName, def, min, max, flags, desc) \ + if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) \ + { \ + str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); \ + WriteLine(aLineBuf); \ + } +#define MACRO_CONFIG_COL(Name, ScriptName, def, flags, desc) \ + if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) \ + { \ + str_format(aLineBuf, sizeof(aLineBuf), "%s %u", #ScriptName, g_Config.m_##Name); \ + WriteLine(aLineBuf); \ + } +#define MACRO_CONFIG_STR(Name, ScriptName, len, def, flags, desc) \ + if((flags)&CFGFLAG_SAVE && str_comp(g_Config.m_##Name, def) != 0) \ + { \ + EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); \ + str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); \ + WriteLine(aLineBuf); \ + } - #include "config_variables.h" +#include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR for(int i = 0; i < m_NumCallbacks; i++) m_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData); diff --git a/src/engine/shared/config.h b/src/engine/shared/config.h index 3d531312f..524c348eb 100644 --- a/src/engine/shared/config.h +++ b/src/engine/shared/config.h @@ -10,33 +10,33 @@ struct CConfiguration { - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name; - #define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) unsigned m_##Name; - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore - #include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Save, Desc) int m_##Name; +#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) unsigned m_##Name; +#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Save, Desc) char m_##Name[Len]; // Flawfinder: ignore +#include "config_variables.h" +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR }; extern CConfiguration g_Config; enum { - CFGFLAG_SAVE=1<<0, - CFGFLAG_CLIENT=1<<1, - CFGFLAG_SERVER=1<<2, - CFGFLAG_STORE=1<<3, - CFGFLAG_MASTER=1<<4, - CFGFLAG_ECON=1<<5, + CFGFLAG_SAVE = 1 << 0, + CFGFLAG_CLIENT = 1 << 1, + CFGFLAG_SERVER = 1 << 2, + CFGFLAG_STORE = 1 << 3, + CFGFLAG_MASTER = 1 << 4, + CFGFLAG_ECON = 1 << 5, // DDRace - CMDFLAG_TEST=1<<6, - CFGFLAG_CHAT=1<<7, - CFGFLAG_GAME=1<<8, - CFGFLAG_NONTEEHISTORIC=1<<9, - CFGFLAG_COLLIGHT=1<<10, - CFGFLAG_COLALPHA=1<<11, + CMDFLAG_TEST = 1 << 6, + CFGFLAG_CHAT = 1 << 7, + CFGFLAG_GAME = 1 << 8, + CFGFLAG_NONTEEHISTORIC = 1 << 9, + CFGFLAG_COLLIGHT = 1 << 10, + CFGFLAG_COLALPHA = 1 << 11, }; #endif diff --git a/src/engine/shared/console.cpp b/src/engine/shared/console.cpp index aa5678583..679a5fee6 100644 --- a/src/engine/shared/console.cpp +++ b/src/engine/shared/console.cpp @@ -2,13 +2,13 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include -#include #include +#include #include +#include -#include #include +#include #include "config.h" #include "console.h" @@ -18,21 +18,21 @@ const char *CConsole::CResult::GetString(unsigned Index) { - if (Index >= m_NumArgs) + if(Index >= m_NumArgs) return ""; return m_apArgs[Index]; } int CConsole::CResult::GetInteger(unsigned Index) { - if (Index >= m_NumArgs) + if(Index >= m_NumArgs) return 0; return str_toint(m_apArgs[Index]); } float CConsole::CResult::GetFloat(unsigned Index) { - if (Index >= m_NumArgs) + if(Index >= m_NumArgs) return 0.0f; return str_tofloat(m_apArgs[Index]); } @@ -44,7 +44,7 @@ ColorHSLA CConsole::CResult::GetColor(unsigned Index, bool Light) return hsl; const char *pStr = m_apArgs[Index]; - if(str_isallnum(pStr) || ((pStr[0] == '-' || pStr[0] == '+') && str_isallnum(pStr+1))) // Teeworlds Color (Packed HSL) + if(str_isallnum(pStr) || ((pStr[0] == '-' || pStr[0] == '+') && str_isallnum(pStr + 1))) // Teeworlds Color (Packed HSL) { hsl = ColorHSLA(str_toulong_base(pStr, 10), true); if(Light) @@ -76,17 +76,17 @@ ColorHSLA CConsole::CResult::GetColor(unsigned Index, bool Light) hsl = color_cast(rgb); } else if(!str_comp_nocase(pStr, "red")) - hsl = ColorHSLA(0.0f/6.0f, 1, .5f); + hsl = ColorHSLA(0.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "yellow")) - hsl = ColorHSLA(1.0f/6.0f, 1, .5f); + hsl = ColorHSLA(1.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "green")) - hsl = ColorHSLA(2.0f/6.0f, 1, .5f); + hsl = ColorHSLA(2.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "cyan")) - hsl = ColorHSLA(3.0f/6.0f, 1, .5f); + hsl = ColorHSLA(3.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "blue")) - hsl = ColorHSLA(4.0f/6.0f, 1, .5f); + hsl = ColorHSLA(4.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "magenta")) - hsl = ColorHSLA(5.0f/6.0f, 1, .5f); + hsl = ColorHSLA(5.0f / 6.0f, 1, .5f); else if(!str_comp_nocase(pStr, "white")) hsl = ColorHSLA(0, 0, 1); else if(!str_comp_nocase(pStr, "gray")) @@ -102,7 +102,7 @@ const IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLeve const CCommand *pInfo = m_pNext; while(pInfo) { - if(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel) + if(pInfo->m_Flags & FlagMask && pInfo->m_AccessLevel >= AccessLevel) break; pInfo = pInfo->m_pNext; } @@ -113,7 +113,7 @@ const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int Fl { for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { - if(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel) + if(pCommand->m_Flags & FlagMask && pCommand->GetAccessLevel() >= AccessLevel) return pCommand; } @@ -122,7 +122,6 @@ const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int Fl // the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces - int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) { char *pStr; @@ -220,7 +219,6 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat) // write null termination *pDst = 0; - pStr++; } else @@ -265,16 +263,16 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat) char CConsole::NextParam(const char *&pFormat) { - if (*pFormat) + if(*pFormat) { pFormat++; - if (*pFormat == '[') + if(*pFormat == '[') { // skip bracket contents - for (; *pFormat != ']'; pFormat++) + for(; *pFormat != ']'; pFormat++) { - if (!*pFormat) + if(!*pFormat) return *pFormat; } @@ -282,7 +280,7 @@ char CConsole::NextParam(const char *&pFormat) pFormat++; // skip space if there is one - if (*pFormat == ' ') + if(*pFormat == ' ') pFormat++; } } @@ -317,7 +315,7 @@ char *CConsole::Format(char *pBuf, int Size, const char *pFrom, const char *pStr void CConsole::Print(int Level, const char *pFrom, const char *pStr, bool Highlighted) { - dbg_msg(pFrom ,"%s", pStr); + dbg_msg(pFrom, "%s", pStr); char aBuf[1024]; Format(aBuf, sizeof(aBuf), pFrom, pStr); for(int i = 0; i < m_NumPrintCB; ++i) @@ -360,7 +358,7 @@ bool CConsole::LineIsValid(const char *pStr) { if(*pEnd == ';') // command separator { - pNextPart = pEnd+1; + pNextPart = pEnd + 1; break; } else if(*pEnd == '#') // comment, no need to do anything more @@ -370,7 +368,7 @@ bool CConsole::LineIsValid(const char *pStr) pEnd++; } - if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) + if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0) return false; CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); @@ -378,8 +376,7 @@ bool CConsole::LineIsValid(const char *pStr) return false; pStr = pNextPart; - } - while(pStr && *pStr); + } while(pStr && *pStr); return true; } @@ -413,7 +410,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo { if(*pEnd == ';') // command separator { - pNextPart = pEnd+1; + pNextPart = pEnd + 1; break; } else if(*pEnd == '#') // comment, no need to do anything more @@ -423,7 +420,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo pEnd++; } - if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) + if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0) return; if(!*Result.m_pCommand) @@ -433,8 +430,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo if(pCommand) { - if(ClientID == IConsole::CLIENT_ID_GAME - && !(pCommand->m_Flags & CFGFLAG_GAME)) + if(ClientID == IConsole::CLIENT_ID_GAME && !(pCommand->m_Flags & CFGFLAG_GAME)) { if(Stroke) { @@ -443,8 +439,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } } - else if(ClientID == IConsole::CLIENT_ID_NO_GAME - && pCommand->m_Flags & CFGFLAG_GAME) + else if(ClientID == IConsole::CLIENT_ID_NO_GAME && pCommand->m_Flags & CFGFLAG_GAME) { if(Stroke) { @@ -473,7 +468,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo str_format(aBuf, sizeof(aBuf), "Invalid arguments... Usage: %s %s", pCommand->m_pName, pCommand->m_pParams); Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } - else if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE) + else if(m_StoreCommands && pCommand->m_Flags & CFGFLAG_STORE) { m_ExecutionQueue.AddEntry(); m_ExecutionQueue.m_pLast->m_pfnCommandCallback = pCommand->m_pfnCallback; @@ -482,10 +477,10 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo } else { - if(pCommand->m_Flags&CMDFLAG_TEST && !g_Config.m_SvTestingCommands) + if(pCommand->m_Flags & CMDFLAG_TEST && !g_Config.m_SvTestingCommands) return; - if(m_pfnTeeHistorianCommandCallback && !(pCommand->m_Flags&CFGFLAG_NONTEEHISTORIC)) + if(m_pfnTeeHistorianCommandCallback && !(pCommand->m_Flags & CFGFLAG_NONTEEHISTORIC)) { m_pfnTeeHistorianCommandCallback(ClientID, m_FlagMask, pCommand->m_pName, &Result, m_pTeeHistorianCommandUserdata); } @@ -495,7 +490,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo if(Result.HasVictim() && Result.GetVictim() == CResult::VICTIM_ALL) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { Result.SetVictim(i); pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); @@ -506,7 +501,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); } - if (pCommand->m_Flags&CMDFLAG_TEST) + if(pCommand->m_Flags & CMDFLAG_TEST) m_Cheated = true; } } @@ -533,7 +528,7 @@ void CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPoss { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { - if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) + if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp) { if(str_find_nocase(pCommand->m_pName, pStr)) pfnCallback(pCommand->m_pName, pUser); @@ -545,7 +540,7 @@ CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { - if(pCommand->m_Flags&FlagMask) + if(pCommand->m_Flags & FlagMask) { if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; @@ -569,7 +564,6 @@ void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask, int ClientID, boo m_FlagMask = Temp; } - void CConsole::ExecuteFile(const char *pFilename, int ClientID, bool LogFailure, int StorageType) { // make sure that this isn't being executed already @@ -618,12 +612,12 @@ void CConsole::ExecuteFile(const char *pFilename, int ClientID, bool LogFailure, void CConsole::Con_Echo(IResult *pResult, void *pUserData) { - ((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0)); + ((CConsole *)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0)); } void CConsole::Con_Exec(IResult *pResult, void *pUserData) { - ((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0), -1, true, IStorage::TYPE_ALL); + ((CConsole *)pUserData)->ExecuteFile(pResult->GetString(0), -1, true, IStorage::TYPE_ALL); } void CConsole::ConCommandAccess(IResult *pResult, void *pUser) @@ -666,7 +660,7 @@ void CConsole::ConCommandStatus(IResult *pResult, void *pUser) for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { - if(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() >= clamp(pResult->GetInteger(0), (int)ACCESS_LEVEL_ADMIN, (int)ACCESS_LEVEL_USER)) + if(pCommand->m_Flags & pConsole->m_FlagMask && pCommand->GetAccessLevel() >= clamp(pResult->GetInteger(0), (int)ACCESS_LEVEL_ADMIN, (int)ACCESS_LEVEL_USER)) { int Length = str_length(pCommand->m_pName); if(Used + Length + 2 < (int)(sizeof(aBuf))) @@ -741,9 +735,9 @@ static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData) // do clamping if(pData->m_Min != pData->m_Max) { - if (Val < pData->m_Min) + if(Val < pData->m_Min) Val = pData->m_Min; - if (pData->m_Max != 0 && Val > pData->m_Max) + if(pData->m_Max != 0 && Val > pData->m_Max) Val = pData->m_Max; } @@ -796,8 +790,6 @@ static void ColVariableCommand(IConsole::IResult *pResult, void *pUserData) } } - - static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData) { CStrVariableData *pData = (CStrVariableData *)pUserData; @@ -812,9 +804,9 @@ static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData) while(*pString) { int Size = str_utf8_encode(aTemp, static_cast(*pString++)); - if(Length+Size < pData->m_MaxSize) + if(Length + Size < pData->m_MaxSize) { - mem_copy(pData->m_pStr+Length, aTemp, Size); + mem_copy(pData->m_pStr + Length, aTemp, Size); Length += Size; } else @@ -857,7 +849,7 @@ void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser) if(pfnCallback == IntVariableCommand) { CIntVariableData *pData = static_cast(pUserData); - int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1); + int Val = *(pData->m_pVariable) == pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1); str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val); pConsole->ExecuteLine(aBuf); aBuf[0] = 0; @@ -914,7 +906,7 @@ void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser) if(pfnCallback == IntVariableCommand) { - int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2); + int Val = pResult->GetInteger(0) == 0 ? pResult->GetInteger(3) : pResult->GetInteger(2); str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val); pConsole->ExecuteLine(aBuf); aBuf[0] = 0; @@ -950,41 +942,41 @@ CConsole::CConsole(int FlagMask) // register some basic commands Register("echo", "r[text]", CFGFLAG_SERVER, Con_Echo, this, "Echo the text"); - Register("exec", "r[file]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); + Register("exec", "r[file]", CFGFLAG_SERVER | CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); - Register("toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value"); + Register("toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_SERVER | CFGFLAG_CLIENT, ConToggle, this, "Toggle config value"); Register("+toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress"); Register("access_level", "s[command] ?i[accesslevel]", CFGFLAG_SERVER, ConCommandAccess, this, "Specify command accessibility (admin = 0, moderator = 1, helper = 2, all = 3)"); Register("access_status", "i[accesslevel]", CFGFLAG_SERVER, ConCommandStatus, this, "List all commands which are accessible for admin = 0, moderator = 1, helper = 2, all = 3"); - Register("cmdlist", "", CFGFLAG_SERVER|CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users"); + Register("cmdlist", "", CFGFLAG_SERVER | CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users"); - // TODO: this should disappear - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ +// TODO: this should disappear +#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \ { \ - static CIntVariableData Data = { this, &g_Config.m_##Name, Min, Max, Def }; \ + static CIntVariableData Data = {this, &g_Config.m_##Name, Min, Max, Def}; \ Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \ } - #define MACRO_CONFIG_COL(Name,ScriptName,Def,Flags,Desc) \ +#define MACRO_CONFIG_COL(Name, ScriptName, Def, Flags, Desc) \ { \ - static CColVariableData Data = { this, &g_Config.m_##Name, static_cast((Flags) & CFGFLAG_COLLIGHT), \ - static_cast((Flags) & CFGFLAG_COLALPHA), Def}; \ + static CColVariableData Data = {this, &g_Config.m_##Name, static_cast((Flags)&CFGFLAG_COLLIGHT), \ + static_cast((Flags)&CFGFLAG_COLALPHA), Def}; \ Register(#ScriptName, "?i", Flags, ColVariableCommand, &Data, Desc); \ } - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ +#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \ { \ static char OldValue[Len] = Def; \ - static CStrVariableData Data = { this, g_Config.m_##Name, Len, OldValue }; \ + static CStrVariableData Data = {this, g_Config.m_##Name, Len, OldValue}; \ Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ } - #include "config_variables.h" +#include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR // DDRace @@ -1014,7 +1006,7 @@ void CConsole::ParseArguments(int NumArgs, const char **ppArguments) if(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0) { if(NumArgs - i > 1) - ExecuteFile(ppArguments[i+1], -1, true, IStorage::TYPE_ABSOLUTE); + ExecuteFile(ppArguments[i + 1], -1, true, IStorage::TYPE_ABSOLUTE); i++; } else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i])) @@ -1077,11 +1069,11 @@ void CConsole::Register(const char *pName, const char *pParams, if(DoAdd) AddCommandSorted(pCommand); - if(pCommand->m_Flags&CFGFLAG_CHAT) + if(pCommand->m_Flags & CFGFLAG_CHAT) pCommand->SetAccessLevel(ACCESS_LEVEL_USER); } -void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) +void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) { CCommand *pCommand; if(m_pRecycleList) @@ -1150,7 +1142,8 @@ void CConsole::DeregisterTemp(const char *pName) void CConsole::DeregisterTempAll() { // set non temp as first one - for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext); + for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext) + ; // remove temp entries from command list for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext) @@ -1158,7 +1151,8 @@ void CConsole::DeregisterTempAll() CCommand *pNext = pCommand->m_pNext; if(pNext->m_Temp) { - for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext); + for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext) + ; pCommand->m_pNext = pNext; } } @@ -1209,12 +1203,11 @@ void CConsole::StoreCommands(bool Store) m_StoreCommands = Store; } - const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { - if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) + if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp) { if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; @@ -1224,14 +1217,13 @@ const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int Fl return 0; } - extern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); } void CConsole::ResetServerGameSettings() { - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ +#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \ { \ - if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \ + if(((Flags) & (CFGFLAG_SERVER | CFGFLAG_GAME)) == (CFGFLAG_SERVER | CFGFLAG_GAME)) \ { \ CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \ void *pUserData = pCommand->m_pUserData; \ @@ -1247,11 +1239,11 @@ void CConsole::ResetServerGameSettings() } \ } - #define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) MACRO_CONFIG_INT(Name,ScriptName,Def,0,0,Save,Desc) +#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) MACRO_CONFIG_INT(Name, ScriptName, Def, 0, 0, Save, Desc) - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ +#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \ { \ - if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \ + if(((Flags) & (CFGFLAG_SERVER | CFGFLAG_GAME)) == (CFGFLAG_SERVER | CFGFLAG_GAME)) \ { \ CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \ void *pUserData = pCommand->m_pUserData; \ @@ -1267,11 +1259,11 @@ void CConsole::ResetServerGameSettings() } \ } - #include "config_variables.h" +#include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_INT +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_STR } int CConsole::CResult::GetVictim() diff --git a/src/engine/shared/console.h b/src/engine/shared/console.h index 8ac40736c..94fd0f292 100644 --- a/src/engine/shared/console.h +++ b/src/engine/shared/console.h @@ -3,10 +3,10 @@ #ifndef ENGINE_SHARED_CONSOLE_H #define ENGINE_SHARED_CONSOLE_H +#include "memheap.h" +#include #include #include -#include -#include "memheap.h" class CConsole : public IConsole { @@ -24,7 +24,6 @@ class CConsole : public IConsole void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_USER)); } }; - class CChain { public: @@ -77,19 +76,20 @@ class CConsole : public IConsole enum { CONSOLE_MAX_STR_LENGTH = 8192, - MAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2 + MAX_PARTS = (CONSOLE_MAX_STR_LENGTH + 1) / 2 }; class CResult : public IResult { public: - char m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1]; + char m_aStringStorage[CONSOLE_MAX_STR_LENGTH + 1]; char *m_pArgsStart; const char *m_pCommand; const char *m_apArgs[MAX_PARTS]; - CResult() : IResult() + CResult() : + IResult() { mem_zero(m_aStringStorage, sizeof(m_aStringStorage)); m_pArgsStart = 0; @@ -97,16 +97,16 @@ class CConsole : public IConsole mem_zero(m_apArgs, sizeof(m_apArgs)); } - CResult &operator =(const CResult &Other) + CResult &operator=(const CResult &Other) { if(this != &Other) { IResult::operator=(Other); mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage)); - m_pArgsStart = m_aStringStorage+(Other.m_pArgsStart-Other.m_aStringStorage); - m_pCommand = m_aStringStorage+(Other.m_pCommand-Other.m_aStringStorage); + m_pArgsStart = m_aStringStorage + (Other.m_pArgsStart - Other.m_aStringStorage); + m_pCommand = m_aStringStorage + (Other.m_pCommand - Other.m_aStringStorage); for(unsigned i = 0; i < Other.m_NumArgs; ++i) - m_apArgs[i] = m_aStringStorage+(Other.m_apArgs[i]-Other.m_aStringStorage); + m_apArgs[i] = m_aStringStorage + (Other.m_apArgs[i] - Other.m_aStringStorage); } return *this; } @@ -134,9 +134,9 @@ class CConsole : public IConsole enum { - VICTIM_NONE=-3, - VICTIM_ME=-2, - VICTIM_ALL=-1, + VICTIM_NONE = -3, + VICTIM_ME = -2, + VICTIM_ALL = -1, }; int m_Victim; @@ -169,7 +169,7 @@ class CConsole : public IConsole FCommandCallback m_pfnCommandCallback; void *m_pCommandUserData; CResult m_Result; - } *m_pFirst, *m_pLast; + } * m_pFirst, *m_pLast; void AddEntry() { diff --git a/src/engine/shared/datafile.cpp b/src/engine/shared/datafile.cpp index 0a243e338..75ab1a609 100644 --- a/src/engine/shared/datafile.cpp +++ b/src/engine/shared/datafile.cpp @@ -3,8 +3,8 @@ #include "datafile.h" -#include #include +#include #include #include @@ -12,12 +12,12 @@ #include -static const int DEBUG=0; +static const int DEBUG = 0; enum { - OFFSET_UUID_TYPE=0x8000, - ITEMTYPE_EX=0xffff, + OFFSET_UUID_TYPE = 0x8000, + ITEMTYPE_EX = 0xffff, }; struct CItemEx @@ -57,13 +57,12 @@ static int GetTypeFromIndex(int Index) return ITEMTYPE_EX - Index - 1; } - struct CDatafileItemType { int m_Type; int m_Start; int m_Num; -} ; +}; struct CDatafileItem { @@ -128,14 +127,13 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int return false; } - // take the CRC of the file and store it unsigned Crc = 0; SHA256_DIGEST Sha256; { enum { - BUFFER_SIZE = 64*1024 + BUFFER_SIZE = 64 * 1024 }; SHA256_CTX Sha256Ctxt; @@ -155,10 +153,9 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int io_seek(File, 0, IOSEEK_START); } - // TODO: change this header CDatafileHeader Header; - if (sizeof(Header) != io_read(File, &Header, sizeof(Header))) + if(sizeof(Header) != io_read(File, &Header, sizeof(Header))) { dbg_msg("datafile", "couldn't load header"); return 0; @@ -173,7 +170,7 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int } #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); + swap_endian(&Header, sizeof(int), sizeof(Header) / sizeof(int)); #endif if(Header.m_Version != 3 && Header.m_Version != 4) { @@ -183,27 +180,27 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int // read in the rest except the data unsigned Size = 0; - Size += Header.m_NumItemTypes*sizeof(CDatafileItemType); - Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int); + Size += Header.m_NumItemTypes * sizeof(CDatafileItemType); + Size += (Header.m_NumItems + Header.m_NumRawData) * sizeof(int); if(Header.m_Version == 4) - Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes as well + Size += Header.m_NumRawData * sizeof(int); // v4 has uncompressed data sizes as well Size += Header.m_ItemSize; unsigned AllocSize = Size; AllocSize += sizeof(CDatafile); // add space for info structure - AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers + AllocSize += Header.m_NumRawData * sizeof(void *); // add space for data pointers CDatafile *pTmpDataFile = (CDatafile *)malloc(AllocSize); pTmpDataFile->m_Header = Header; pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size; - pTmpDataFile->m_ppDataPtrs = (char **)(pTmpDataFile+1); - pTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *); + pTmpDataFile->m_ppDataPtrs = (char **)(pTmpDataFile + 1); + pTmpDataFile->m_pData = (char *)(pTmpDataFile + 1) + Header.m_NumRawData * sizeof(char *); pTmpDataFile->m_File = File; pTmpDataFile->m_Sha256 = Sha256; pTmpDataFile->m_Crc = Crc; // clear the data pointers - mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*)); + mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData * sizeof(void *)); // read types, offsets, sizes and item data unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size); @@ -285,24 +282,33 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int int CDataFileReader::NumData() { - if(!m_pDataFile) { return 0; } + if(!m_pDataFile) + { + return 0; + } return m_pDataFile->m_Header.m_NumRawData; } // returns the size in the file int CDataFileReader::GetFileDataSize(int Index) { - if(!m_pDataFile) { return 0; } + if(!m_pDataFile) + { + return 0; + } - if(Index == m_pDataFile->m_Header.m_NumRawData-1) - return m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index]; - return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index]; + if(Index == m_pDataFile->m_Header.m_NumRawData - 1) + return m_pDataFile->m_Header.m_DataSize - m_pDataFile->m_Info.m_pDataOffsets[Index]; + return m_pDataFile->m_Info.m_pDataOffsets[Index + 1] - m_pDataFile->m_Info.m_pDataOffsets[Index]; } // returns the size of the resulting data int CDataFileReader::GetDataSize(int Index) { - if(!m_pDataFile) { return 0; } + if(!m_pDataFile) + { + return 0; + } if(m_pDataFile->m_Header.m_Version == 4) return m_pDataFile->m_Info.m_pDataSizes[Index]; @@ -312,7 +318,10 @@ int CDataFileReader::GetDataSize(int Index) void *CDataFileReader::GetDataImpl(int Index, int Swap) { - if(!m_pDataFile) { return 0; } + if(!m_pDataFile) + { + return 0; + } if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData) return 0; @@ -337,12 +346,12 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap) m_pDataFile->m_ppDataPtrs[Index] = (char *)malloc(UncompressedSize); // read the compressed data - io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); + io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset + m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); io_read(m_pDataFile->m_File, pTemp, DataSize); // decompress the data, TODO: check for errors s = UncompressedSize; - uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention + uncompress((Bytef *)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef *)pTemp, DataSize); // ignore_convention #if defined(CONF_ARCH_ENDIAN_BIG) SwapSize = s; #endif @@ -355,13 +364,13 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap) // load the data dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize); m_pDataFile->m_ppDataPtrs[Index] = (char *)malloc(DataSize); - io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); + io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset + m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); io_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize); } #if defined(CONF_ARCH_ENDIAN_BIG) if(Swap && SwapSize) - swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int)); + swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize / sizeof(int)); #endif } @@ -392,9 +401,9 @@ int CDataFileReader::GetItemSize(int Index) { if(!m_pDataFile) return 0; - if(Index == m_pDataFile->m_Header.m_NumItems-1) - return m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem); - return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem); + if(Index == m_pDataFile->m_Header.m_NumItems - 1) + return m_pDataFile->m_Header.m_ItemSize - m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem); + return m_pDataFile->m_Info.m_pItemOffsets[Index + 1] - m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem); } int CDataFileReader::GetExternalItemType(int InternalType) @@ -439,19 +448,26 @@ int CDataFileReader::GetInternalItemType(int ExternalType) void *CDataFileReader::GetItem(int Index, int *pType, int *pID) { - if(!m_pDataFile) { if(pType) *pType = 0; if(pID) *pID = 0; return 0; } + if(!m_pDataFile) + { + if(pType) + *pType = 0; + if(pID) + *pID = 0; + return 0; + } - CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]); + CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Info.m_pItemOffsets[Index]); if(pType) { // remove sign extension - *pType = GetExternalItemType((i->m_TypeAndID>>16)&0xffff); + *pType = GetExternalItemType((i->m_TypeAndID >> 16) & 0xffff); } if(pID) { - *pID = i->m_TypeAndID&0xffff; + *pID = i->m_TypeAndID & 0xffff; } - return (void *)(i+1); + return (void *)(i + 1); } void CDataFileReader::GetType(int Type, int *pStart, int *pNum) @@ -507,7 +523,8 @@ void *CDataFileReader::FindItem(int Type, int ID) int CDataFileReader::NumItems() { - if(!m_pDataFile) return 0; + if(!m_pDataFile) + return 0; return m_pDataFile->m_Header.m_NumItems; } @@ -543,23 +560,25 @@ SHA256_DIGEST CDataFileReader::Sha256() unsigned CDataFileReader::Crc() { - if(!m_pDataFile) return 0xFFFFFFFF; + if(!m_pDataFile) + return 0xFFFFFFFF; return m_pDataFile->m_Crc; } int CDataFileReader::MapSize() { - if(!m_pDataFile) return 0; + if(!m_pDataFile) + return 0; return m_pDataFile->m_Header.m_Size + 16; } IOHANDLE CDataFileReader::File() { - if(!m_pDataFile) return 0; + if(!m_pDataFile) + return 0; return m_pDataFile->m_File; } - CDataFileWriter::CDataFileWriter() { m_File = 0; @@ -632,7 +651,7 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) { dbg_assert((Type >= 0 && Type < MAX_ITEM_TYPES) || Type >= OFFSET_UUID, "incorrect type"); dbg_assert(m_NumItems < 1024, "too many items"); - dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + dbg_assert(Size % sizeof(int) == 0, "incorrect boundary"); if(Type >= OFFSET_UUID) { @@ -664,7 +683,7 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) m_pItemTypes[Type].m_Num++; m_NumItems++; - return m_NumItems-1; + return m_NumItems - 1; } int CDataFileWriter::AddData(int Size, void *pData) @@ -675,7 +694,7 @@ int CDataFileWriter::AddData(int Size, void *pData) unsigned long s = compressBound(Size); void *pCompData = malloc(s); // temporary buffer that we use during compression - int Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention + int Result = compress((Bytef *)pCompData, &s, (Bytef *)pData, Size); // ignore_convention if(Result != Z_OK) { dbg_msg("datafile", "compression error %d", Result); @@ -689,17 +708,17 @@ int CDataFileWriter::AddData(int Size, void *pData) free(pCompData); m_NumDatas++; - return m_NumDatas-1; + return m_NumDatas - 1; } int CDataFileWriter::AddDataSwapped(int Size, void *pData) { - dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + dbg_assert(Size % sizeof(int) == 0, "incorrect boundary"); #if defined(CONF_ARCH_ENDIAN_BIG) void *pSwapped = malloc(Size); // temporary buffer that we use during compression mem_copy(pSwapped, pData, Size); - swap_endian(pSwapped, sizeof(int), Size/sizeof(int)); + swap_endian(pSwapped, sizeof(int), Size / sizeof(int)); int Index = AddData(Size, pSwapped); free(pSwapped); return Index; @@ -708,10 +727,10 @@ int CDataFileWriter::AddDataSwapped(int Size, void *pData) #endif } - int CDataFileWriter::Finish() { - if(!m_File) return 1; + if(!m_File) + return 1; int ItemSize = 0; int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize; @@ -730,12 +749,11 @@ int CDataFileWriter::Finish() ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem); } - for(int i = 0; i < m_NumDatas; i++) DataSize += m_pDatas[i].m_CompressedSize; // calculate the complete size - TypesSize = m_NumItemTypes*sizeof(CDatafileItemType); + TypesSize = m_NumItemTypes * sizeof(CDatafileItemType); HeaderSize = sizeof(CDatafileHeader); OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize; @@ -765,7 +783,7 @@ int CDataFileWriter::Finish() if(DEBUG) dbg_msg("datafile", "HeaderSize=%d", (int)sizeof(Header)); #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); + swap_endian(&Header, sizeof(int), sizeof(Header) / sizeof(int)); #endif io_write(m_File, &Header, sizeof(Header)); } @@ -783,7 +801,7 @@ int CDataFileWriter::Finish() if(DEBUG) dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num); #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int)); + swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType) / sizeof(int)); #endif io_write(m_File, &Info, sizeof(Info)); Count += m_pItemTypes[i].m_Num; @@ -803,7 +821,7 @@ int CDataFileWriter::Finish() dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); + swap_endian(&Temp, sizeof(int), sizeof(Temp) / sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pItems[k].m_Size + sizeof(CDatafileItem); @@ -821,7 +839,7 @@ int CDataFileWriter::Finish() dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); + swap_endian(&Temp, sizeof(int), sizeof(Temp) / sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pDatas[i].m_CompressedSize; @@ -834,7 +852,7 @@ int CDataFileWriter::Finish() dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize); int UncompressedSize = m_pDatas[i].m_UncompressedSize; #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int)); + swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize) / sizeof(int)); #endif io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); } @@ -849,14 +867,14 @@ int CDataFileWriter::Finish() while(k != -1) { CDatafileItem Item; - Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID; + Item.m_TypeAndID = (i << 16) | m_pItems[k].m_ID; Item.m_Size = m_pItems[k].m_Size; if(DEBUG) dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size); #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); - swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int)); + swap_endian(&Item, sizeof(int), sizeof(Item) / sizeof(int)); + swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size / sizeof(int)); #endif io_write(m_File, &Item, sizeof(Item)); io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size); diff --git a/src/engine/shared/datafile.h b/src/engine/shared/datafile.h index ac69b986e..54a389366 100644 --- a/src/engine/shared/datafile.h +++ b/src/engine/shared/datafile.h @@ -5,8 +5,8 @@ #include -#include #include +#include // raw datafile access class CDataFileReader @@ -19,7 +19,8 @@ class CDataFileReader int GetInternalItemType(int ExternalType); public: - CDataFileReader() : m_pDataFile(0) {} + CDataFileReader() : + m_pDataFile(0) {} ~CDataFileReader() { Close(); } bool IsOpen() const { return m_pDataFile != 0; } @@ -75,10 +76,10 @@ class CDataFileWriter enum { - MAX_ITEM_TYPES=0x10000, - MAX_ITEMS=1024, - MAX_DATAS=1024, - MAX_EXTENDED_ITEM_TYPES=64, + MAX_ITEM_TYPES = 0x10000, + MAX_ITEMS = 1024, + MAX_DATAS = 1024, + MAX_EXTENDED_ITEM_TYPES = 64, }; IOHANDLE m_File; @@ -105,5 +106,4 @@ public: int Finish(); }; - #endif diff --git a/src/engine/shared/demo.cpp b/src/engine/shared/demo.cpp index f9e3d7cfc..dd0ef103c 100644 --- a/src/engine/shared/demo.cpp +++ b/src/engine/shared/demo.cpp @@ -9,7 +9,7 @@ #include #if defined(CONF_VIDEORECORDER) - #include +#include #endif #include @@ -28,7 +28,6 @@ static const unsigned char gs_VersionTickCompression = 5; // demo files with thi static const int gs_LengthOffset = 152; static const int gs_NumMarkersOffset = 176; - CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool NoMapData) { m_File = 0; @@ -63,7 +62,8 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con CDemoHeader Header; CTimelineMarkers TimelineMarkers; - if(m_File) { + if(m_File) + { io_close(DemoFile); return -1; } @@ -130,13 +130,13 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con Header.m_Version = gs_ActVersion; str_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion)); str_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName)); - Header.m_aMapSize[0] = (MapSize>>24)&0xff; - Header.m_aMapSize[1] = (MapSize>>16)&0xff; - Header.m_aMapSize[2] = (MapSize>>8)&0xff; + Header.m_aMapSize[0] = (MapSize >> 24) & 0xff; + Header.m_aMapSize[1] = (MapSize >> 16) & 0xff; + Header.m_aMapSize[2] = (MapSize >> 8) & 0xff; Header.m_aMapSize[3] = (MapSize)&0xff; - Header.m_aMapCrc[0] = (Crc>>24)&0xff; - Header.m_aMapCrc[1] = (Crc>>16)&0xff; - Header.m_aMapCrc[2] = (Crc>>8)&0xff; + Header.m_aMapCrc[0] = (Crc >> 24) & 0xff; + Header.m_aMapCrc[1] = (Crc >> 16) & 0xff; + Header.m_aMapCrc[2] = (Crc >> 8) & 0xff; Header.m_aMapCrc[3] = (Crc)&0xff; str_copy(Header.m_aType, pType, sizeof(Header.m_aType)); // Header.m_Length - add this on stop @@ -160,7 +160,7 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con // write map data while(1) { - unsigned char aChunk[1024*64]; + unsigned char aChunk[1024 * 64]; int Bytes = io_read(MapFile, &aChunk, sizeof(aChunk)); if(Bytes <= 0) break; @@ -221,13 +221,13 @@ enum void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) { - if(m_LastTickMarker == -1 || Tick-m_LastTickMarker > CHUNKMASK_TICK || Keyframe) + if(m_LastTickMarker == -1 || Tick - m_LastTickMarker > CHUNKMASK_TICK || Keyframe) { unsigned char aChunk[5]; aChunk[0] = CHUNKTYPEFLAG_TICKMARKER; - aChunk[1] = (Tick>>24)&0xff; - aChunk[2] = (Tick>>16)&0xff; - aChunk[3] = (Tick>>8)&0xff; + aChunk[1] = (Tick >> 24) & 0xff; + aChunk[2] = (Tick >> 16) & 0xff; + aChunk[3] = (Tick >> 8) & 0xff; aChunk[4] = (Tick)&0xff; if(Keyframe) @@ -238,7 +238,7 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) else { unsigned char aChunk[1]; - aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick-m_LastTickMarker); + aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick - m_LastTickMarker); io_write(m_File, aChunk, sizeof(aChunk)); } @@ -249,20 +249,20 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) void CDemoRecorder::Write(int Type, const void *pData, int Size) { - char aBuffer[64*1024]; - char aBuffer2[64*1024]; + char aBuffer[64 * 1024]; + char aBuffer2[64 * 1024]; unsigned char aChunk[3]; if(!m_File) return; - if(Size > 64*1024) + if(Size > 64 * 1024) return; /* pad the data with 0 so we get an alignment of 4, else the compression won't work and miss some bytes */ mem_copy(aBuffer2, pData, Size); - while(Size&3) + while(Size & 3) aBuffer2[Size++] = 0; Size = CVariableInt::Compress(aBuffer2, Size, aBuffer, sizeof(aBuffer)); // buffer2 -> buffer if(Size < 0) @@ -272,8 +272,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) if(Size < 0) return; - - aChunk[0] = ((Type&0x3)<<5); + aChunk[0] = ((Type & 0x3) << 5); if(Size < 30) { aChunk[0] |= Size; @@ -284,14 +283,14 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) if(Size < 256) { aChunk[0] |= 30; - aChunk[1] = Size&0xff; + aChunk[1] = Size & 0xff; io_write(m_File, aChunk, 2); } else { aChunk[0] |= 31; - aChunk[1] = Size&0xff; - aChunk[2] = Size>>8; + aChunk[1] = Size & 0xff; + aChunk[2] = Size >> 8; io_write(m_File, aChunk, 3); } } @@ -301,7 +300,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) { - if(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5) + if(m_LastKeyFrame == -1 || (Tick - m_LastKeyFrame) > SERVER_TICK_SPEED * 5) { // write full tickmarker WriteTickMarker(Tick, 1); @@ -315,13 +314,13 @@ void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) else { // create delta, prepend tick - char aDeltaData[CSnapshot::MAX_SIZE+sizeof(int)]; + char aDeltaData[CSnapshot::MAX_SIZE + sizeof(int)]; int DeltaSize; // write tickmarker WriteTickMarker(Tick, 0); - DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData); + DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot *)m_aLastSnapshotData, (CSnapshot *)pData, &aDeltaData); if(DeltaSize) { // record delta @@ -352,27 +351,27 @@ int CDemoRecorder::Stop() io_seek(m_File, gs_LengthOffset, IOSEEK_START); int DemoLength = Length(); char aLength[4]; - aLength[0] = (DemoLength>>24)&0xff; - aLength[1] = (DemoLength>>16)&0xff; - aLength[2] = (DemoLength>>8)&0xff; + aLength[0] = (DemoLength >> 24) & 0xff; + aLength[1] = (DemoLength >> 16) & 0xff; + aLength[2] = (DemoLength >> 8) & 0xff; aLength[3] = (DemoLength)&0xff; io_write(m_File, aLength, sizeof(aLength)); // add the timeline markers to the header io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START); char aNumMarkers[4]; - aNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff; - aNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff; - aNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff; + aNumMarkers[0] = (m_NumTimelineMarkers >> 24) & 0xff; + aNumMarkers[1] = (m_NumTimelineMarkers >> 16) & 0xff; + aNumMarkers[2] = (m_NumTimelineMarkers >> 8) & 0xff; aNumMarkers[3] = (m_NumTimelineMarkers)&0xff; io_write(m_File, aNumMarkers, sizeof(aNumMarkers)); for(int i = 0; i < m_NumTimelineMarkers; i++) { int Marker = m_aTimelineMarkers[i]; char aMarker[4]; - aMarker[0] = (Marker>>24)&0xff; - aMarker[1] = (Marker>>16)&0xff; - aMarker[2] = (Marker>>8)&0xff; + aMarker[0] = (Marker >> 24) & 0xff; + aMarker[1] = (Marker >> 16) & 0xff; + aMarker[2] = (Marker >> 8) & 0xff; aMarker[3] = (Marker)&0xff; io_write(m_File, aMarker, sizeof(aMarker)); } @@ -393,8 +392,8 @@ void CDemoRecorder::AddDemoMarker() // not more than 1 marker in a second if(m_NumTimelineMarkers > 0) { - int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1]; - if(Diff < SERVER_TICK_SPEED*1.0f) + int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers - 1]; + if(Diff < SERVER_TICK_SPEED * 1.0f) return; } @@ -404,8 +403,6 @@ void CDemoRecorder::AddDemoMarker() m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker"); } - - CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta) { m_File = 0; @@ -424,7 +421,6 @@ void CDemoPlayer::SetListener(IListener *pListener) m_pListener = pListener; } - int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) { unsigned char Chunk = 0; @@ -438,19 +434,19 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk)) return -1; - if(Chunk&CHUNKTYPEFLAG_TICKMARKER) + if(Chunk & CHUNKTYPEFLAG_TICKMARKER) { // decode tick marker - int Tickdelta_legacy = Chunk&(CHUNKMASK_TICK_LEGACY); // compatibility - *pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME); + int Tickdelta_legacy = Chunk & (CHUNKMASK_TICK_LEGACY); // compatibility + *pType = Chunk & (CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_KEYFRAME); if(m_Info.m_Header.m_Version < gs_VersionTickCompression && Tickdelta_legacy != 0) { *pTick += Tickdelta_legacy; } - else if(Chunk&(CHUNKTICKFLAG_TICK_COMPRESSED)) + else if(Chunk & (CHUNKTICKFLAG_TICK_COMPRESSED)) { - int Tickdelta = Chunk&(CHUNKMASK_TICK); + int Tickdelta = Chunk & (CHUNKMASK_TICK); *pTick += Tickdelta; } else @@ -458,15 +454,14 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) unsigned char aTickdata[4]; if(io_read(m_File, aTickdata, sizeof(aTickdata)) != sizeof(aTickdata)) return -1; - *pTick = (aTickdata[0]<<24) | (aTickdata[1]<<16) | (aTickdata[2]<<8) | aTickdata[3]; + *pTick = (aTickdata[0] << 24) | (aTickdata[1] << 16) | (aTickdata[2] << 8) | aTickdata[3]; } - } else { // decode normal chunk - *pType = (Chunk&CHUNKMASK_TYPE)>>5; - *pSize = Chunk&CHUNKMASK_SIZE; + *pType = (Chunk & CHUNKMASK_TYPE) >> 5; + *pSize = Chunk & CHUNKMASK_SIZE; if(*pSize == 30) { @@ -474,14 +469,13 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) return -1; *pSize = aSizedata[0]; - } else if(*pSize == 31) { unsigned char aSizedata[2]; if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) return -1; - *pSize = (aSizedata[1]<<8) | aSizedata[0]; + *pSize = (aSizedata[1] << 8) | aSizedata[0]; } } @@ -509,9 +503,9 @@ void CDemoPlayer::ScanFile() break; // read the chunk - if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) + if(ChunkType & CHUNKTYPEFLAG_TICKMARKER) { - if(ChunkType&CHUNKTICKFLAG_KEYFRAME) + if(ChunkType & CHUNKTICKFLAG_KEYFRAME) { CKeyFrameSearch *pKey; @@ -534,7 +528,6 @@ void CDemoPlayer::ScanFile() } else if(ChunkSize) io_skip(m_File, ChunkSize); - } // copy all the frames to an array instead for fast access @@ -567,10 +560,10 @@ void CDemoPlayer::DoTick() // stop on error or eof if(m_pConsole) m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "end of file"); - #if defined(CONF_VIDEORECORDER) - if (IVideo::Current()) - Stop(); - #endif +#if defined(CONF_VIDEORECORDER) + if(IVideo::Current()) + Stop(); +#endif if(m_Info.m_PreviousTick == -1) { if(m_pConsole) @@ -622,7 +615,7 @@ void CDemoPlayer::DoTick() GotSnapshot = 1; - DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewsnap, aData, DataSize); + DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot *)m_aLastSnapshotData, (CSnapshot *)aNewsnap, aData, DataSize); if(DataSize >= 0) { @@ -662,7 +655,7 @@ void CDemoPlayer::DoTick() } // check the remaining types - if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) + if(ChunkType & CHUNKTYPEFLAG_TICKMARKER) { m_Info.m_NextTick = ChunkTick; break; @@ -786,11 +779,11 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const m_DemoType = DEMOTYPE_INVALID; // read map - unsigned MapSize = (m_Info.m_Header.m_aMapSize[0]<<24) | (m_Info.m_Header.m_aMapSize[1]<<16) | (m_Info.m_Header.m_aMapSize[2]<<8) | (m_Info.m_Header.m_aMapSize[3]); + unsigned MapSize = (m_Info.m_Header.m_aMapSize[0] << 24) | (m_Info.m_Header.m_aMapSize[1] << 16) | (m_Info.m_Header.m_aMapSize[2] << 8) | (m_Info.m_Header.m_aMapSize[3]); // check if we already have the map // TODO: improve map checking (maps folder, check crc) - unsigned Crc = (m_Info.m_Header.m_aMapCrc[0]<<24) | (m_Info.m_Header.m_aMapCrc[1]<<16) | (m_Info.m_Header.m_aMapCrc[2]<<8) | (m_Info.m_Header.m_aMapCrc[3]); + unsigned Crc = (m_Info.m_Header.m_aMapCrc[0] << 24) | (m_Info.m_Header.m_aMapCrc[1] << 16) | (m_Info.m_Header.m_aMapCrc[2] << 8) | (m_Info.m_Header.m_aMapCrc[3]); // save byte offset of map for later use m_MapOffset = io_tell(m_File); @@ -805,14 +798,14 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const if(m_Info.m_Header.m_Version > gs_OldVersion) { // get timeline markers - int Num = ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[1]<<16)&0xFF0000) | - ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[3]&0xFF); + int Num = ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[0] << 24) & 0xFF000000) | ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[1] << 16) & 0xFF0000) | + ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[2] << 8) & 0xFF00) | (m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[3] & 0xFF); m_Info.m_Info.m_NumTimelineMarkers = minimum(Num, (int)MAX_TIMELINE_MARKERS); for(int i = 0; i < m_Info.m_Info.m_NumTimelineMarkers; i++) { char *pTimelineMarker = m_Info.m_TimelineMarkers.m_aTimelineMarkers[i]; - m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) | - ((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF); + m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0] << 24) & 0xFF000000) | ((pTimelineMarker[1] << 16) & 0xFF0000) | + ((pTimelineMarker[2] << 8) & 0xFF00) | (pTimelineMarker[3] & 0xFF); } } @@ -879,9 +872,9 @@ int64 CDemoPlayer::time() { #if defined(CONF_VIDEORECORDER) static bool s_Recording = false; - if (IVideo::Current()) + if(IVideo::Current()) { - if (!s_Recording) + if(!s_Recording) { s_Recording = true; m_Info.m_LastUpdate = IVideo::Time(); @@ -891,7 +884,7 @@ int64 CDemoPlayer::time() else { int64 Now = time_get(); - if (s_Recording) + if(s_Recording) { s_Recording = false; m_Info.m_LastUpdate = Now; @@ -912,7 +905,7 @@ int CDemoPlayer::Play() // set start info /*m_Info.start_tick = m_Info.previous_tick; m_Info.start_time = time_get();*/ - m_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED; + m_Info.m_CurrentTime = m_Info.m_PreviousTick * time_freq() / SERVER_TICK_SPEED; m_Info.m_LastUpdate = time(); return 0; } @@ -971,14 +964,14 @@ void CDemoPlayer::SetSpeed(float Speed) void CDemoPlayer::SetSpeedIndex(int Offset) { - m_SpeedIndex = clamp(m_SpeedIndex + Offset, 0, (int)(sizeof(g_aSpeeds)/sizeof(g_aSpeeds[0])-1)); + m_SpeedIndex = clamp(m_SpeedIndex + Offset, 0, (int)(sizeof(g_aSpeeds) / sizeof(g_aSpeeds[0]) - 1)); SetSpeed(g_aSpeeds[m_SpeedIndex]); } int CDemoPlayer::Update(bool RealTime) { int64 Now = time(); - int64 Deltatime = Now-m_Info.m_LastUpdate; + int64 Deltatime = Now - m_Info.m_LastUpdate; m_Info.m_LastUpdate = Now; if(!IsPlaying()) @@ -986,16 +979,15 @@ int CDemoPlayer::Update(bool RealTime) if(m_Info.m_Info.m_Paused) { - } else { int64 Freq = time_freq(); - m_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed); + m_Info.m_CurrentTime += (int64)(Deltatime * (double)m_Info.m_Info.m_Speed); while(1) { - int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; + int64 CurtickStart = (m_Info.m_Info.m_CurrentTick) * Freq / SERVER_TICK_SPEED; // break if we are ready if(RealTime && CurtickStart > m_Info.m_CurrentTime) @@ -1010,9 +1002,9 @@ int CDemoPlayer::Update(bool RealTime) // update intratick { - int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; - int64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED; - m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + int64 CurtickStart = (m_Info.m_Info.m_CurrentTick) * Freq / SERVER_TICK_SPEED; + int64 PrevtickStart = (m_Info.m_PreviousTick) * Freq / SERVER_TICK_SPEED; + m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart - PrevtickStart); m_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq; } @@ -1037,8 +1029,8 @@ int CDemoPlayer::Update(bool RealTime) int CDemoPlayer::Stop() { #if defined(CONF_VIDEORECORDER) - if (IVideo::Current()) - IVideo::Current()->Stop(); + if(IVideo::Current()) + IVideo::Current()->Stop(); #endif if(!m_File) @@ -1062,12 +1054,12 @@ void CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const for(; *pFileName; ++pFileName) { if(*pFileName == '/' || *pFileName == '\\') - pExtractedName = pFileName+1; + pExtractedName = pFileName + 1; else if(*pFileName == '.') pEnd = pFileName; } - int Length = pEnd > pExtractedName ? minimum(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; + int Length = pEnd > pExtractedName ? minimum(BufferSize, (int)(pEnd - pExtractedName + 1)) : BufferSize; str_copy(pBuffer, pExtractedName, Length); } @@ -1087,7 +1079,7 @@ bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, i io_read(File, pTimelineMarkers, sizeof(CTimelineMarkers)); str_copy(pMapInfo->m_aName, pDemoHeader->m_aMapName, sizeof(pMapInfo->m_aName)); - pMapInfo->m_Crc = (pDemoHeader->m_aMapCrc[0]<<24) | (pDemoHeader->m_aMapCrc[1]<<16) | (pDemoHeader->m_aMapCrc[2]<<8) | (pDemoHeader->m_aMapCrc[3]); + pMapInfo->m_Crc = (pDemoHeader->m_aMapCrc[0] << 24) | (pDemoHeader->m_aMapCrc[1] << 16) | (pDemoHeader->m_aMapCrc[2] << 8) | (pDemoHeader->m_aMapCrc[3]); SHA256_DIGEST Sha256 = SHA256_ZEROED; if(pDemoHeader->m_Version >= gs_Sha256Version) @@ -1108,7 +1100,7 @@ bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, i } pMapInfo->m_Sha256 = Sha256; - pMapInfo->m_Size = (pDemoHeader->m_aMapSize[0]<<24) | (pDemoHeader->m_aMapSize[1]<<16) | (pDemoHeader->m_aMapSize[2]<<8) | (pDemoHeader->m_aMapSize[3]); + pMapInfo->m_Size = (pDemoHeader->m_aMapSize[0] << 24) | (pDemoHeader->m_aMapSize[1] << 16) | (pDemoHeader->m_aMapSize[2] << 8) | (pDemoHeader->m_aMapSize[3]); io_close(File); return !(mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) || pDemoHeader->m_Version < gs_OldVersion); @@ -1143,7 +1135,7 @@ void CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int m_SliceTo = EndTick; m_Stop = false; - if (m_pDemoPlayer->Load(m_pStorage, m_pConsole, pDemo, IStorage::TYPE_ALL) == -1) + if(m_pDemoPlayer->Load(m_pStorage, m_pConsole, pDemo, IStorage::TYPE_ALL) == -1) return; const CMapInfo *pMapInfo = m_pDemoPlayer->GetMapInfo(); @@ -1156,16 +1148,16 @@ void CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int Sha256 = pMapInfo->m_Sha256; } - if (m_pDemoRecorder->Start(m_pStorage, m_pConsole, pDst, m_pNetVersion, pMapInfo->m_aName, &Sha256, pMapInfo->m_Crc, "client", pMapInfo->m_Size, NULL, NULL, pfnFilter, pUser) == -1) + if(m_pDemoRecorder->Start(m_pStorage, m_pConsole, pDst, m_pNetVersion, pMapInfo->m_aName, &Sha256, pMapInfo->m_Crc, "client", pMapInfo->m_Size, NULL, NULL, pfnFilter, pUser) == -1) return; - m_pDemoPlayer->Play(); - while (m_pDemoPlayer->IsPlaying() && !m_Stop) { + while(m_pDemoPlayer->IsPlaying() && !m_Stop) + { m_pDemoPlayer->Update(false); - if (pInfo->m_Info.m_Paused) + if(pInfo->m_Info.m_Paused) break; } @@ -1177,9 +1169,9 @@ void CDemoEditor::OnDemoPlayerSnapshot(void *pData, int Size) { const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info(); - if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) + if(m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) m_Stop = true; - else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) + else if(m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) m_pDemoRecorder->RecordSnapshot(pInfo->m_Info.m_CurrentTick, pData, Size); } @@ -1187,8 +1179,8 @@ void CDemoEditor::OnDemoPlayerMessage(void *pData, int Size) { const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info(); - if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) + if(m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) m_Stop = true; - else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) + else if(m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) m_pDemoRecorder->RecordMessage(pData, Size); } diff --git a/src/engine/shared/demo.h b/src/engine/shared/demo.h index 46d91b801..149c0ada3 100644 --- a/src/engine/shared/demo.h +++ b/src/engine/shared/demo.h @@ -30,6 +30,7 @@ class CDemoRecorder : public IDemoRecorder void WriteTickMarker(int Tick, int Keyframe); void Write(int Type, const void *pData, int Size); + public: CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool NoMapData = false); CDemoRecorder() {} @@ -44,7 +45,7 @@ public: bool IsRecording() const { return m_File != 0; } char *GetCurrentFilename() { return m_aCurrentFilename; } - int Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; } + int Length() const { return (m_LastTickMarker - m_FirstTick) / SERVER_TICK_SPEED; } }; class CDemoPlayer : public IDemoPlayer @@ -80,7 +81,6 @@ public: private: IListener *m_pListener; - // Playback struct CKeyFrame { @@ -119,7 +119,6 @@ private: int64 m_Time; public: - CDemoPlayer(class CSnapshotDelta *m_pSnapshotDelta); void SetListener(IListener *pListener); @@ -141,7 +140,7 @@ public: const char *GetDemoFileName() { return m_aFilename; }; int GetDemoType() const; - int Update(bool RealTime=true); + int Update(bool RealTime = true); const CPlaybackInfo *Info() const { return &m_Info; } virtual bool IsPlaying() const { return m_File != 0; } diff --git a/src/engine/shared/econ.cpp b/src/engine/shared/econ.cpp index d3e4b2209..9f9e5a38b 100644 --- a/src/engine/shared/econ.cpp +++ b/src/engine/shared/econ.cpp @@ -4,7 +4,6 @@ #include "econ.h" #include "netban.h" - int CEcon::NewClientCallback(int ClientID, void *pUser) { CEcon *pThis = (CEcon *)pUser; @@ -93,7 +92,7 @@ void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan) m_Ready = true; char aBuf[128]; str_format(aBuf, sizeof(aBuf), "bound to %s:%d", g_Config.m_EcBindaddr, g_Config.m_EcPort); - Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", aBuf); Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this); m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this); @@ -101,7 +100,7 @@ void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan) Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ"); } else - Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", "couldn't open socket. port might already be in use"); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", "couldn't open socket. port might already be in use"); } void CEcon::Update() @@ -114,7 +113,7 @@ void CEcon::Update() char aBuf[NET_MAX_PACKETSIZE]; int ClientID; - while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID)) + while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf)) - 1, &ClientID)) { dbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, "got message from empty slot"); if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED) @@ -138,7 +137,7 @@ void CEcon::Update() if(!g_Config.m_EcBantime) m_NetConsole.Drop(ClientID, "Too many authentication tries"); else - m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, "Too many authentication tries"); + m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime * 60, "Too many authentication tries"); } } } diff --git a/src/engine/shared/econ.h b/src/engine/shared/econ.h index 3478c7e39..9be62263b 100644 --- a/src/engine/shared/econ.h +++ b/src/engine/shared/econ.h @@ -3,12 +3,11 @@ #include "network.h" - class CEcon { enum { - MAX_AUTH_TRIES=3, + MAX_AUTH_TRIES = 3, }; class CClient @@ -16,7 +15,7 @@ class CEcon public: enum { - STATE_EMPTY=0, + STATE_EMPTY = 0, STATE_CONNECTED, STATE_AUTHED, }; @@ -34,7 +33,7 @@ class CEcon int m_PrintCBIndex; int m_UserClientID; - static void SendLineCB(const char *pLine, void *pUserData,bool Highlighted); + static void SendLineCB(const char *pLine, void *pUserData, bool Highlighted); static void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConLogout(IConsole::IResult *pResult, void *pUserData); diff --git a/src/engine/shared/engine.cpp b/src/engine/shared/engine.cpp index 44c24003c..7308480e3 100644 --- a/src/engine/shared/engine.cpp +++ b/src/engine/shared/engine.cpp @@ -5,9 +5,9 @@ #include #include -#include #include #include +#include CHostLookup::CHostLookup() { @@ -19,7 +19,6 @@ CHostLookup::CHostLookup(const char *pHostname, int Nettype) m_Nettype = Nettype; } - void CHostLookup::Run() { m_Result = net_host_lookup(m_aHostname, &m_Addr, m_Nettype); @@ -49,7 +48,7 @@ public: str_format(aFilenameSent, sizeof(aFilenameSent), "dumps/network_sent_%s.txt", aBuf); str_format(aFilenameRecv, sizeof(aFilenameRecv), "dumps/network_recv_%s.txt", aBuf); CNetBase::OpenLog(pEngine->m_pStorage->OpenFile(aFilenameSent, IOFLAG_WRITE, IStorage::TYPE_SAVE), - pEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE)); + pEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE)); pEngine->m_Logging = true; } } @@ -62,13 +61,13 @@ public: // dbg_msg("engine", "running on %s-%s-%s", CONF_FAMILY_STRING, CONF_PLATFORM_STRING, CONF_ARCH_STRING); - #ifdef CONF_ARCH_ENDIAN_LITTLE +#ifdef CONF_ARCH_ENDIAN_LITTLE dbg_msg("engine", "arch is little endian"); - #elif defined(CONF_ARCH_ENDIAN_BIG) +#elif defined(CONF_ARCH_ENDIAN_BIG) dbg_msg("engine", "arch is big endian"); - #else +#else dbg_msg("engine", "unknown endian"); - #endif +#endif // init the network net_init(); @@ -87,7 +86,7 @@ public: if(!m_pConsole || !m_pStorage) return; - m_pConsole->Register("dbg_lognetwork", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgLognetwork, this, "Log the network"); + m_pConsole->Register("dbg_lognetwork", "", CFGFLAG_SERVER | CFGFLAG_CLIENT, Con_DbgLognetwork, this, "Log the network"); } void InitLogfile() diff --git a/src/engine/shared/fifo.cpp b/src/engine/shared/fifo.cpp index 9ff4d45c6..edaa18fa7 100644 --- a/src/engine/shared/fifo.cpp +++ b/src/engine/shared/fifo.cpp @@ -5,10 +5,10 @@ #include -#include -#include -#include #include +#include +#include +#include #include void CFifo::Init(IConsole *pConsole, char *pFifoFile, int Flag) @@ -40,7 +40,7 @@ void CFifo::Init(IConsole *pConsole, char *pFifoFile, int Flag) } } - m_File = open(pFifoFile, O_RDONLY|O_NONBLOCK); + m_File = open(pFifoFile, O_RDONLY | O_NONBLOCK); if(m_File < 0) dbg_msg("fifo", "can't open file '%s'", pFifoFile); } @@ -68,9 +68,9 @@ void CFifo::Update() continue; aBuf[i] = '\0'; m_pConsole->ExecuteLineFlag(pCur, m_Flag, -1); - pCur = aBuf+i+1; + pCur = aBuf + i + 1; } - if(pCur < aBuf+Length) // missed the last line + if(pCur < aBuf + Length) // missed the last line m_pConsole->ExecuteLineFlag(pCur, m_Flag, -1); } #endif diff --git a/src/engine/shared/filecollection.cpp b/src/engine/shared/filecollection.cpp index ca40e48a1..e9c14e65d 100644 --- a/src/engine/shared/filecollection.cpp +++ b/src/engine/shared/filecollection.cpp @@ -12,18 +12,18 @@ bool CFileCollection::IsFilenameValid(const char *pFilename) if(m_aFileDesc[0] == '\0') { int FilenameLength = str_length(pFilename); - if(m_FileExtLength+TIMESTAMP_LENGTH > FilenameLength) + if(m_FileExtLength + TIMESTAMP_LENGTH > FilenameLength) { return false; } - pFilename += FilenameLength-m_FileExtLength-TIMESTAMP_LENGTH; + pFilename += FilenameLength - m_FileExtLength - TIMESTAMP_LENGTH; } else { - if(str_length(pFilename) != m_FileDescLength+TIMESTAMP_LENGTH+m_FileExtLength || + if(str_length(pFilename) != m_FileDescLength + TIMESTAMP_LENGTH + m_FileExtLength || str_comp_num(pFilename, m_aFileDesc, m_FileDescLength) || - str_comp(pFilename+m_FileDescLength+TIMESTAMP_LENGTH, m_aFileExt)) + str_comp(pFilename + m_FileDescLength + TIMESTAMP_LENGTH, m_aFileExt)) return false; pFilename += m_FileDescLength; @@ -56,20 +56,33 @@ bool CFileCollection::IsFilenameValid(const char *pFilename) int64 CFileCollection::ExtractTimestamp(const char *pTimestring) { - int64 Timestamp = pTimestring[0]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[1]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[2]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[3]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[5]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[6]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[8]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[9]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[11]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[12]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[14]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[15]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[17]-'0'; Timestamp <<= 4; - Timestamp += pTimestring[18]-'0'; + int64 Timestamp = pTimestring[0] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[1] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[2] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[3] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[5] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[6] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[8] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[9] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[11] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[12] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[14] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[15] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[17] - '0'; + Timestamp <<= 4; + Timestamp += pTimestring[18] - '0'; return Timestamp; } @@ -77,25 +90,38 @@ int64 CFileCollection::ExtractTimestamp(const char *pTimestring) void CFileCollection::BuildTimestring(int64 Timestamp, char *pTimestring) { pTimestring[19] = 0; - pTimestring[18] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[17] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[18] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[17] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; pTimestring[16] = '-'; - pTimestring[15] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[14] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[15] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[14] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; pTimestring[13] = '-'; - pTimestring[12] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[11] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[12] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[11] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; pTimestring[10] = '_'; - pTimestring[9] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[8] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[9] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[8] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; pTimestring[7] = '-'; - pTimestring[6] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[5] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[6] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[5] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; pTimestring[4] = '-'; - pTimestring[3] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[2] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[1] = (Timestamp&0xF)+'0'; Timestamp >>= 4; - pTimestring[0] = (Timestamp&0xF)+'0'; + pTimestring[3] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[2] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[1] = (Timestamp & 0xF) + '0'; + Timestamp >>= 4; + pTimestring[0] = (Timestamp & 0xF) + '0'; } void CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries) @@ -105,7 +131,7 @@ void CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pF m_Remove = -1; // MAX_ENTRIES - 1 to make sure that we can insert one entry into the sorted // list and then remove the oldest one - m_MaxEntries = clamp(MaxEntries, 1, static_cast(MAX_ENTRIES)-1); + m_MaxEntries = clamp(MaxEntries, 1, static_cast(MAX_ENTRIES) - 1); str_copy(m_aFileDesc, pFileDesc, sizeof(m_aFileDesc)); m_FileDescLength = str_length(m_aFileDesc); str_copy(m_aFileExt, pFileExt, sizeof(m_aFileExt)); @@ -131,18 +157,18 @@ void CFileCollection::AddEntry(int64 Timestamp) // first entry if(m_NumTimestamps <= m_MaxEntries) { - mem_move(m_aTimestamps+1, m_aTimestamps, m_NumTimestamps*sizeof(int64)); + mem_move(m_aTimestamps + 1, m_aTimestamps, m_NumTimestamps * sizeof(int64)); m_aTimestamps[0] = Timestamp; ++m_NumTimestamps; } } - else if(Timestamp >= m_aTimestamps[m_NumTimestamps-1]) + else if(Timestamp >= m_aTimestamps[m_NumTimestamps - 1]) { // last entry if(m_NumTimestamps > m_MaxEntries) { - mem_move(m_aTimestamps, m_aTimestamps+1, (m_NumTimestamps-1)*sizeof(int64)); - m_aTimestamps[m_NumTimestamps-1] = Timestamp; + mem_move(m_aTimestamps, m_aTimestamps + 1, (m_NumTimestamps - 1) * sizeof(int64)); + m_aTimestamps[m_NumTimestamps - 1] = Timestamp; } else m_aTimestamps[m_NumTimestamps++] = Timestamp; @@ -150,10 +176,10 @@ void CFileCollection::AddEntry(int64 Timestamp) else { // middle entry - int Left = 0, Right = m_NumTimestamps-1; - while(Right-Left > 1) + int Left = 0, Right = m_NumTimestamps - 1; + while(Right - Left > 1) { - int Mid = (Left+Right)/2; + int Mid = (Left + Right) / 2; if(m_aTimestamps[Mid] > Timestamp) Right = Mid; else @@ -162,12 +188,12 @@ void CFileCollection::AddEntry(int64 Timestamp) if(m_NumTimestamps > m_MaxEntries) { - mem_move(m_aTimestamps, m_aTimestamps+1, (Right-1)*sizeof(int64)); - m_aTimestamps[Right-1] = Timestamp; + mem_move(m_aTimestamps, m_aTimestamps + 1, (Right - 1) * sizeof(int64)); + m_aTimestamps[Right - 1] = Timestamp; } else { - mem_move(m_aTimestamps+Right+1, m_aTimestamps+Right, (m_NumTimestamps-Right)*sizeof(int64)); + mem_move(m_aTimestamps + Right + 1, m_aTimestamps + Right, (m_NumTimestamps - Right) * sizeof(int64)); m_aTimestamps[Right] = Timestamp; ++m_NumTimestamps; } @@ -200,11 +226,11 @@ int64 CFileCollection::GetTimestamp(const char *pFilename) if(m_aFileDesc[0] == '\0') { int FilenameLength = str_length(pFilename); - return ExtractTimestamp(pFilename+FilenameLength-m_FileExtLength-TIMESTAMP_LENGTH+1); + return ExtractTimestamp(pFilename + FilenameLength - m_FileExtLength - TIMESTAMP_LENGTH + 1); } else { - return ExtractTimestamp(pFilename+m_FileDescLength+1); + return ExtractTimestamp(pFilename + m_FileDescLength + 1); } } diff --git a/src/engine/shared/filecollection.h b/src/engine/shared/filecollection.h index c4ec74dc6..752d9190d 100644 --- a/src/engine/shared/filecollection.h +++ b/src/engine/shared/filecollection.h @@ -7,8 +7,8 @@ class CFileCollection { enum { - MAX_ENTRIES=1001, - TIMESTAMP_LENGTH=20, // _YYYY-MM-DD_HH-MM-SS + MAX_ENTRIES = 1001, + TIMESTAMP_LENGTH = 20, // _YYYY-MM-DD_HH-MM-SS }; int64 m_aTimestamps[MAX_ENTRIES]; diff --git a/src/engine/shared/ghost.cpp b/src/engine/shared/ghost.cpp index 6c67f6c36..d85bbf469 100644 --- a/src/engine/shared/ghost.cpp +++ b/src/engine/shared/ghost.cpp @@ -3,8 +3,8 @@ #include #include -#include "ghost.h" #include "compression.h" +#include "ghost.h" #include "network.h" static const unsigned char gs_aHeaderMarker[8] = {'T', 'W', 'G', 'H', 'O', 'S', 'T', 0}; @@ -24,7 +24,7 @@ void CGhostRecorder::Init() } // Record -int CGhostRecorder::Start(const char *pFilename, const char *pMap, unsigned Crc, const char* pName) +int CGhostRecorder::Start(const char *pFilename, const char *pMap, unsigned Crc, const char *pName) { m_File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!m_File) @@ -42,9 +42,9 @@ int CGhostRecorder::Start(const char *pFilename, const char *pMap, unsigned Crc, Header.m_Version = gs_ActVersion; str_copy(Header.m_aOwner, pName, sizeof(Header.m_aOwner)); str_copy(Header.m_aMap, pMap, sizeof(Header.m_aMap)); - Header.m_aCrc[0] = (Crc>>24)&0xff; - Header.m_aCrc[1] = (Crc>>16)&0xff; - Header.m_aCrc[2] = (Crc>>8)&0xff; + Header.m_aCrc[0] = (Crc >> 24) & 0xff; + Header.m_aCrc[1] = (Crc >> 16) & 0xff; + Header.m_aCrc[2] = (Crc >> 8) & 0xff; Header.m_aCrc[3] = (Crc)&0xff; io_write(m_File, &Header, sizeof(Header)); @@ -84,7 +84,7 @@ void CGhostRecorder::WriteData(int Type, const void *pData, int Size) mem_copy(Data.m_aData, pData, Size); if(m_LastItem.m_Type == Data.m_Type) - DiffItem((int*)m_LastItem.m_aData, (int*)Data.m_aData, (int*)m_pBufferPos, Size/4); + DiffItem((int *)m_LastItem.m_aData, (int *)Data.m_aData, (int *)m_pBufferPos, Size / 4); else { FlushChunk(); @@ -110,7 +110,7 @@ void CGhostRecorder::FlushChunk() if(!m_File || Size == 0) return; - while(Size&3) + while(Size & 3) m_aBuffer[Size++] = 0; Size = CVariableInt::Compress(m_aBuffer, Size, s_aBuffer, sizeof(s_aBuffer)); @@ -121,9 +121,9 @@ void CGhostRecorder::FlushChunk() if(Size < 0) return; - aChunk[0] = Type&0xff; - aChunk[1] = m_BufferNumItems&0xff; - aChunk[2] = (Size>>8)&0xff; + aChunk[0] = Type & 0xff; + aChunk[1] = m_BufferNumItems & 0xff; + aChunk[2] = (Size >> 8) & 0xff; aChunk[3] = (Size)&0xff; io_write(m_File, aChunk, sizeof(aChunk)); @@ -145,14 +145,14 @@ int CGhostRecorder::Stop(int Ticks, int Time) unsigned char aNumTicks[4]; unsigned char aTime[4]; - aNumTicks[0] = (Ticks>>24)&0xff; - aNumTicks[1] = (Ticks>>16)&0xff; - aNumTicks[2] = (Ticks>>8)&0xff; + aNumTicks[0] = (Ticks >> 24) & 0xff; + aNumTicks[1] = (Ticks >> 16) & 0xff; + aNumTicks[2] = (Ticks >> 8) & 0xff; aNumTicks[3] = (Ticks)&0xff; - aTime[0] = (Time>>24)&0xff; - aTime[1] = (Time>>16)&0xff; - aTime[2] = (Time>>8)&0xff; + aTime[0] = (Time >> 24) & 0xff; + aTime[1] = (Time >> 16) & 0xff; + aTime[2] = (Time >> 8) & 0xff; aTime[3] = (Time)&0xff; // write down num shots and time @@ -316,7 +316,7 @@ bool CGhostLoader::ReadData(int Type, void *pData, int Size) CGhostItem Data(Type); if(m_LastItem.m_Type == Data.m_Type) - UndiffItem((int*)m_LastItem.m_aData, (int*)m_pBufferPos, (int*)Data.m_aData, Size/4); + UndiffItem((int *)m_LastItem.m_aData, (int *)m_pBufferPos, (int *)Data.m_aData, Size / 4); else mem_copy(Data.m_aData, m_pBufferPos, Size); @@ -379,10 +379,10 @@ bool CGhostLoader::GetGhostInfo(const char *pFilename, CGhostHeader *pGhostHeade inline void StrToInts(int *pInts, int Num, const char *pStr) { int Index = 0; - while (Num) + while(Num) { - char aBuf[4] = { 0,0,0,0 }; - for (int c = 0; c < 4 && pStr[Index]; c++, Index++) + char aBuf[4] = {0, 0, 0, 0}; + for(int c = 0; c < 4 && pStr[Index]; c++, Index++) aBuf[c] = pStr[Index]; *pInts = ((aBuf[0] + 128) << 24) | ((aBuf[1] + 128) << 16) | ((aBuf[2] + 128) << 8) | (aBuf[3] + 128); pInts++; diff --git a/src/engine/shared/ghost.h b/src/engine/shared/ghost.h index ae63df0fa..79e0b9640 100644 --- a/src/engine/shared/ghost.h +++ b/src/engine/shared/ghost.h @@ -15,8 +15,10 @@ public: unsigned char m_aData[MAX_ITEM_SIZE]; int m_Type; - CGhostItem() : m_Type(-1) {} - CGhostItem(int Type) : m_Type(Type) {} + CGhostItem() : + m_Type(-1) {} + CGhostItem(int Type) : + m_Type(Type) {} void Reset() { m_Type = -1; } }; diff --git a/src/engine/shared/huffman.cpp b/src/engine/shared/huffman.cpp index 892a7197c..00bc78a97 100644 --- a/src/engine/shared/huffman.cpp +++ b/src/engine/shared/huffman.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "huffman.h" +#include struct CHuffmanConstructNode { @@ -12,9 +12,9 @@ struct CHuffmanConstructNode void CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth) { if(pNode->m_aLeafs[1] != 0xffff) - Setbits_r(&m_aNodes[pNode->m_aLeafs[1]], Bits|(1<m_aLeafs[1]], Bits | (1 << Depth), Depth + 1); if(pNode->m_aLeafs[0] != 0xffff) - Setbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth+1); + Setbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth + 1); if(pNode->m_NumBits) { @@ -32,13 +32,13 @@ static void BubbleSort(CHuffmanConstructNode **ppList, int Size) while(Changed) { Changed = 0; - for(int i = 0; i < Size-1; i++) + for(int i = 0; i < Size - 1; i++) { - if(ppList[i]->m_Frequency < ppList[i+1]->m_Frequency) + if(ppList[i]->m_Frequency < ppList[i + 1]->m_Frequency) { pTemp = ppList[i]; - ppList[i] = ppList[i+1]; - ppList[i+1] = pTemp; + ppList[i] = ppList[i + 1]; + ppList[i + 1] = pTemp; Changed = 1; } } @@ -66,7 +66,6 @@ void CHuffman::ConstructTree(const unsigned *pFrequencies) aNodesLeftStorage[i].m_Frequency = pFrequencies[i]; aNodesLeftStorage[i].m_NodeId = i; apNodesLeft[i] = &aNodesLeftStorage[i]; - } m_NumNodes = HUFFMAN_MAX_SYMBOLS; @@ -78,17 +77,17 @@ void CHuffman::ConstructTree(const unsigned *pFrequencies) BubbleSort(apNodesLeft, NumNodesLeft); m_aNodes[m_NumNodes].m_NumBits = 0; - m_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft-1]->m_NodeId; - m_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft-2]->m_NodeId; - apNodesLeft[NumNodesLeft-2]->m_NodeId = m_NumNodes; - apNodesLeft[NumNodesLeft-2]->m_Frequency = apNodesLeft[NumNodesLeft-1]->m_Frequency + apNodesLeft[NumNodesLeft-2]->m_Frequency; + m_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft - 1]->m_NodeId; + m_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft - 2]->m_NodeId; + apNodesLeft[NumNodesLeft - 2]->m_NodeId = m_NumNodes; + apNodesLeft[NumNodesLeft - 2]->m_Frequency = apNodesLeft[NumNodesLeft - 1]->m_Frequency + apNodesLeft[NumNodesLeft - 2]->m_Frequency; m_NumNodes++; NumNodesLeft--; } // set start node - m_pStartNode = &m_aNodes[m_NumNodes-1]; + m_pStartNode = &m_aNodes[m_NumNodes - 1]; // build symbol bits Setbits_r(m_pStartNode, 0, 0); @@ -112,7 +111,7 @@ void CHuffman::Init(const unsigned *pFrequencies) CNode *pNode = m_pStartNode; for(k = 0; k < HUFFMAN_LUTBITS; k++) { - pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + pNode = &m_aNodes[pNode->m_aLeafs[Bits & 1]]; Bits >>= 1; if(!pNode) @@ -128,7 +127,6 @@ void CHuffman::Init(const unsigned *pFrequencies) if(k == HUFFMAN_LUTBITS) m_apDecodeLut[i] = pNode; } - } //*************************************************************** @@ -143,7 +141,7 @@ int CHuffman::Compress(const void *pInput, int InputSize, void *pOutput, int Out #define HUFFMAN_MACRO_WRITE() \ while(Bitcount >= 8) \ { \ - *pDst++ = (unsigned char)(Bits&0xff); \ + *pDst++ = (unsigned char)(Bits & 0xff); \ if(pDst == pDstEnd) \ return -1; \ Bits >>= 8; \ @@ -218,7 +216,7 @@ int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int O // {A} try to load a node now, this will reduce dependency at location {D} pNode = 0; if(Bitcount >= HUFFMAN_LUTBITS) - pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; + pNode = m_apDecodeLut[Bits & HUFFMAN_LUTMASK]; // {B} fill with new bits while(Bitcount < 24 && pSrc != pSrcEnd) @@ -229,7 +227,7 @@ int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int O // {C} load symbol now if we didn't that earlier at location {A} if(!pNode) - pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; + pNode = m_apDecodeLut[Bits & HUFFMAN_LUTMASK]; if(!pNode) return -1; @@ -251,7 +249,7 @@ int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int O while(1) { // traverse tree - pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + pNode = &m_aNodes[pNode->m_aLeafs[Bits & 1]]; // remove bit Bitcount--; diff --git a/src/engine/shared/huffman.h b/src/engine/shared/huffman.h index 0d15ed997..2c31da5d6 100644 --- a/src/engine/shared/huffman.h +++ b/src/engine/shared/huffman.h @@ -3,20 +3,18 @@ #ifndef ENGINE_SHARED_HUFFMAN_H #define ENGINE_SHARED_HUFFMAN_H - - class CHuffman { enum { HUFFMAN_EOF_SYMBOL = 256, - HUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1, - HUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1, + HUFFMAN_MAX_SYMBOLS = HUFFMAN_EOF_SYMBOL + 1, + HUFFMAN_MAX_NODES = HUFFMAN_MAX_SYMBOLS * 2 - 1, HUFFMAN_LUTBITS = 10, - HUFFMAN_LUTSIZE = (1<m_Status = IJob::STATE_DONE; } } - } void CJobPool::Init(int NumThreads) diff --git a/src/engine/shared/jobs.h b/src/engine/shared/jobs.h index c85691e10..44dc07040 100644 --- a/src/engine/shared/jobs.h +++ b/src/engine/shared/jobs.h @@ -30,7 +30,7 @@ public: enum { - STATE_PENDING=0, + STATE_PENDING = 0, STATE_RUNNING, STATE_DONE }; @@ -40,7 +40,7 @@ class CJobPool { enum { - MAX_THREADS=32 + MAX_THREADS = 32 }; int m_NumThreads; void *m_apThreads[MAX_THREADS]; diff --git a/src/engine/shared/json.cpp b/src/engine/shared/json.cpp index 95b695e98..37338ff1b 100644 --- a/src/engine/shared/json.cpp +++ b/src/engine/shared/json.cpp @@ -1,42 +1,46 @@ #include #include -const struct _json_value *json_object_get (const json_value * object, const char * index) +const struct _json_value *json_object_get(const json_value *object, const char *index) { - unsigned int i; + unsigned int i; - if (object->type != json_object) - return &json_value_none; + if(object->type != json_object) + return &json_value_none; - for (i = 0; i < object->u.object.length; ++ i) - if (!str_comp(object->u.object.values [i].name, index)) - return object->u.object.values [i].value; + for(i = 0; i < object->u.object.length; ++i) + if(!str_comp(object->u.object.values[i].name, index)) + return object->u.object.values[i].value; - return &json_value_none; + return &json_value_none; } -const struct _json_value *json_array_get (const json_value * array, int index) +const struct _json_value *json_array_get(const json_value *array, int index) { - if (array->type != json_array || index >= (int)array->u.array.length) - return &json_value_none; + if(array->type != json_array || index >= (int)array->u.array.length) + return &json_value_none; - return array->u.array.values[index]; + return array->u.array.values[index]; } -int json_array_length (const json_value * array) { - return array->u.array.length; +int json_array_length(const json_value *array) +{ + return array->u.array.length; } -const char * json_string_get (const json_value * string) { - return string->u.string.ptr; +const char *json_string_get(const json_value *string) +{ + return string->u.string.ptr; } -int json_int_get (const json_value * integer) { - return integer->u.integer; +int json_int_get(const json_value *integer) +{ + return integer->u.integer; } -int json_boolean_get(const json_value * boolean) { - return boolean->u.boolean != 0; +int json_boolean_get(const json_value *boolean) +{ + return boolean->u.boolean != 0; } static char EscapeJsonChar(char c) diff --git a/src/engine/shared/json.h b/src/engine/shared/json.h index 9b5af36c5..8a09b2c1a 100644 --- a/src/engine/shared/json.h +++ b/src/engine/shared/json.h @@ -3,12 +3,12 @@ #include -const struct _json_value *json_object_get (const json_value * object, const char * index); -const struct _json_value *json_array_get (const json_value * array, int index); -int json_array_length (const json_value * array); -const char * json_string_get (const json_value * string); -int json_int_get (const json_value * integer); -int json_boolean_get(const json_value * boolean); +const struct _json_value *json_object_get(const json_value *object, const char *index); +const struct _json_value *json_array_get(const json_value *array, int index); +int json_array_length(const json_value *array); +const char *json_string_get(const json_value *string); +int json_int_get(const json_value *integer); +int json_boolean_get(const json_value *boolean); char *EscapeJson(char *pBuffer, int BufferSize, const char *pString); const char *JsonBool(bool Bool); diff --git a/src/engine/shared/kernel.cpp b/src/engine/shared/kernel.cpp index 6dc04a670..c159574a1 100644 --- a/src/engine/shared/kernel.cpp +++ b/src/engine/shared/kernel.cpp @@ -7,7 +7,7 @@ class CKernel : public IKernel { enum { - MAX_INTERFACES=32, + MAX_INTERFACES = 32, }; class CInterfaceInfo @@ -39,7 +39,6 @@ class CKernel : public IKernel } public: - CKernel() { m_NumInterfaces = 0; @@ -48,7 +47,7 @@ public: virtual ~CKernel() { // delete interfaces in reverse order just the way it would happen to objects on the stack - for(int i = m_NumInterfaces - 1; i >= 0 ; i--) + for(int i = m_NumInterfaces - 1; i >= 0; i--) { if(m_aInterfaces[i].m_AutoDestroy) { @@ -58,7 +57,6 @@ public: } } - virtual bool RegisterInterfaceImpl(const char *pName, IInterface *pInterface, bool destroy) { // TODO: More error checks here diff --git a/src/engine/shared/linereader.cpp b/src/engine/shared/linereader.cpp index b705ff0ec..de48abb1d 100644 --- a/src/engine/shared/linereader.cpp +++ b/src/engine/shared/linereader.cpp @@ -32,7 +32,7 @@ char *CLineReader::Get() m_BufferPos = Left; // fill the buffer - Read = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize-m_BufferPos); + Read = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize - m_BufferPos); m_BufferSize = Left + Read; LineStart = 0; @@ -56,14 +56,14 @@ char *CLineReader::Get() // line found if(m_aBuffer[m_BufferPos] == '\r') { - if(m_BufferPos+1 >= m_BufferSize) + if(m_BufferPos + 1 >= m_BufferSize) { // read more to get the connected '\n' CRLFBreak = true; ++m_BufferPos; continue; } - else if(m_aBuffer[m_BufferPos+1] == '\n') + else if(m_aBuffer[m_BufferPos + 1] == '\n') m_aBuffer[m_BufferPos++] = 0; } m_aBuffer[m_BufferPos++] = 0; diff --git a/src/engine/shared/linereader.h b/src/engine/shared/linereader.h index f75615fd4..9c7e6a837 100644 --- a/src/engine/shared/linereader.h +++ b/src/engine/shared/linereader.h @@ -7,11 +7,12 @@ // buffered stream for reading lines, should perhaps be something smaller class CLineReader { - char m_aBuffer[4*8192]; + char m_aBuffer[4 * 8192]; unsigned m_BufferPos; unsigned m_BufferSize; unsigned m_BufferMaxSize; IOHANDLE m_IO; + public: void Init(IOHANDLE IoHandle); char *Get(); diff --git a/src/engine/shared/masterserver.cpp b/src/engine/shared/masterserver.cpp index 11c67da04..8760d2f74 100644 --- a/src/engine/shared/masterserver.cpp +++ b/src/engine/shared/masterserver.cpp @@ -1,6 +1,6 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include // sscanf +#include // sscanf #include @@ -138,7 +138,7 @@ public: mem_zero(m_aMasterServers, sizeof(m_aMasterServers)); for(int i = 0; i < MAX_MASTERSERVERS; i++) { - str_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), "master%d.teeworlds.com", i+1); + str_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), "master%d.teeworlds.com", i + 1); m_apLookup[i] = std::make_shared(); } } diff --git a/src/engine/shared/memheap.cpp b/src/engine/shared/memheap.cpp index f6a660c4c..cca49d485 100644 --- a/src/engine/shared/memheap.cpp +++ b/src/engine/shared/memheap.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "memheap.h" +#include // allocates a new chunk to be used void CHeap::NewChunk() @@ -16,8 +16,8 @@ void CHeap::NewChunk() // the chunk structure is located in the beginning of the chunk // init it and return the chunk - pChunk = (CChunk*)pMem; - pChunk->m_pMemory = (char*)(pChunk+1); + pChunk = (CChunk *)pMem; + pChunk->m_pMemory = (char *)(pChunk + 1); pChunk->m_pCurrent = pChunk->m_pMemory; pChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE; pChunk->m_pNext = (CChunk *)0x0; @@ -33,7 +33,7 @@ void *CHeap::AllocateFromChunk(unsigned int Size) // check if we need can fit the allocation if(m_pCurrent->m_pCurrent + Size > m_pCurrent->m_pEnd) - return (void*)0x0; + return (void *)0x0; // get memory and move the pointer forward pMem = m_pCurrent->m_pCurrent; diff --git a/src/engine/shared/memheap.h b/src/engine/shared/memheap.h index 39adf2b1d..f2e4cf5c9 100644 --- a/src/engine/shared/memheap.h +++ b/src/engine/shared/memheap.h @@ -15,12 +15,11 @@ class CHeap enum { // how large each chunk should be - CHUNK_SIZE = 1025*64, + CHUNK_SIZE = 1025 * 64, }; CChunk *m_pCurrent; - void Clear(); void NewChunk(); void *AllocateFromChunk(unsigned int Size); diff --git a/src/engine/shared/netban.cpp b/src/engine/shared/netban.cpp index 23b3f27b9..30add2266 100644 --- a/src/engine/shared/netban.cpp +++ b/src/engine/shared/netban.cpp @@ -1,19 +1,19 @@ #include #include -#include #include +#include #include "netban.h" - CNetBan::CNetHash::CNetHash(const NETADDR *pAddr) { - if(pAddr->type==NETTYPE_IPV4) - m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF; + if(pAddr->type == NETTYPE_IPV4) + m_Hash = (pAddr->ip[0] + pAddr->ip[1] + pAddr->ip[2] + pAddr->ip[3]) & 0xFF; else - m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+ - pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF; + m_Hash = (pAddr->ip[0] + pAddr->ip[1] + pAddr->ip[2] + pAddr->ip[3] + pAddr->ip[4] + pAddr->ip[5] + pAddr->ip[6] + pAddr->ip[7] + + pAddr->ip[8] + pAddr->ip[9] + pAddr->ip[10] + pAddr->ip[11] + pAddr->ip[12] + pAddr->ip[13] + pAddr->ip[14] + pAddr->ip[15]) & + 0xFF; m_HashIndex = 0; } @@ -31,21 +31,20 @@ CNetBan::CNetHash::CNetHash(const CNetRange *pRange) int CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]) { - int Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16; + int Length = pAddr->type == NETTYPE_IPV4 ? 4 : 16; aHash[0].m_Hash = 0; aHash[0].m_HashIndex = 0; for(int i = 1, Sum = 0; i <= Length; ++i) { - Sum += pAddr->ip[i-1]; - aHash[i].m_Hash = Sum&0xFF; - aHash[i].m_HashIndex = i%Length; + Sum += pAddr->ip[i - 1]; + aHash[i].m_Hash = Sum & 0xFF; + aHash[i].m_HashIndex = i % Length; } return Length; } - template -typename CNetBan::CBan *CNetBan::CBanPool::Add(const T *pData, const CBanInfo *pInfo, const CNetHash *pNetHash) +typename CNetBan::CBan *CNetBan::CBanPool::Add(const T *pData, const CBanInfo *pInfo, const CNetHash *pNetHash) { if(!m_pFirstFree) return 0; @@ -72,7 +71,7 @@ typename CNetBan::CBan *CNetBan::CBanPool::Add(const T *pData, // insert it into the used list if(m_pFirstUsed) { - for(CBan *p = m_pFirstUsed; ; p = p->m_pNext) + for(CBan *p = m_pFirstUsed;; p = p->m_pNext) { if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) { @@ -161,7 +160,7 @@ void CNetBan::CBanPool::Update(CBan *pBan, const CBanIn // insert it into the used list if(m_pFirstUsed) { - for(CBan *p = m_pFirstUsed; ; p = p->m_pNext) + for(CBan *p = m_pFirstUsed;; p = p->m_pNext) { if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) { @@ -207,14 +206,14 @@ void CNetBan::CBanPool::Reset() m_pFirstUsed = 0; m_CountUsed = 0; - for(int i = 1; i < MAX_BANS-1; ++i) + for(int i = 1; i < MAX_BANS - 1; ++i) { - m_aBans[i].m_pNext = &m_aBans[i+1]; - m_aBans[i].m_pPrev = &m_aBans[i-1]; + m_aBans[i].m_pNext = &m_aBans[i + 1]; + m_aBans[i].m_pPrev = &m_aBans[i - 1]; } m_aBans[0].m_pNext = &m_aBans[1]; - m_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2]; + m_aBans[MAX_BANS - 1].m_pPrev = &m_aBans[MAX_BANS - 2]; m_pFirstFree = &m_aBans[0]; } @@ -233,7 +232,6 @@ typename CNetBan::CBan *CNetBan::CBanPool::Get(int Index) const return 0; } - template int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) { @@ -244,7 +242,7 @@ int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, c return -1; } - int Stamp = Seconds > 0 ? time_timestamp()+Seconds : CBanInfo::EXPIRES_NEVER; + int Stamp = Seconds > 0 ? time_timestamp() + Seconds : CBanInfo::EXPIRES_NEVER; // set up info CBanInfo Info = {0}; @@ -306,13 +304,13 @@ void CNetBan::Init(IConsole *pConsole, IStorage *pStorage) net_host_lookup("localhost", &m_LocalhostIPV4, NETTYPE_IPV4); net_host_lookup("localhost", &m_LocalhostIPV6, NETTYPE_IPV6); - Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, "Ban ip for x minutes for any reason"); - Console()->Register("ban_range", "s[first ip] s[last ip] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBanRange, this, "Ban ip range for x minutes for any reason"); - Console()->Register("unban", "s[ip|entry]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, "Unban ip/banlist entry"); - Console()->Register("unban_range", "s[first ip] s[last ip]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanRange, this, "Unban ip range"); - Console()->Register("unban_all", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries"); - Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, "Show banlist"); - Console()->Register("bans_save", "s[file]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file"); + Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConBan, this, "Ban ip for x minutes for any reason"); + Console()->Register("ban_range", "s[first ip] s[last ip] ?i[minutes] r[reason]", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConBanRange, this, "Ban ip range for x minutes for any reason"); + Console()->Register("unban", "s[ip|entry]", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConUnban, this, "Unban ip/banlist entry"); + Console()->Register("unban_range", "s[first ip] s[last ip]", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConUnbanRange, this, "Unban ip range"); + Console()->Register("unban_all", "", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries"); + Console()->Register("bans", "", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConBans, this, "Show banlist"); + Console()->Register("bans_save", "s[file]", CFGFLAG_SERVER | CFGFLAG_MASTER | CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file"); } void CNetBan::Update() @@ -375,7 +373,7 @@ int CNetBan::UnbanByIndex(int Index) } else { - CBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num()); + CBanRange *pBan = m_BanRangePool.Get(Index - m_BanAddrPool.Num()); if(pBan) { NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); @@ -398,7 +396,8 @@ bool CNetBan::IsBanned(const NETADDR *pOrigAddr, char *pBuf, unsigned BufferSize { NETADDR addr; const NETADDR *pAddr = pOrigAddr; - if (pOrigAddr->type == NETTYPE_WEBSOCKET_IPV4) { + if(pOrigAddr->type == NETTYPE_WEBSOCKET_IPV4) + { mem_copy(&addr, pOrigAddr, sizeof(NETADDR)); pAddr = &addr; addr.type = NETTYPE_IPV4; @@ -415,7 +414,7 @@ bool CNetBan::IsBanned(const NETADDR *pOrigAddr, char *pBuf, unsigned BufferSize } // check ban ranges - for(int i = Length-1; i >= 0; --i) + for(int i = Length - 1; i >= 0; --i) { for(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext) { @@ -435,12 +434,12 @@ void CNetBan::ConBan(IConsole::IResult *pResult, void *pUser) CNetBan *pThis = static_cast(pUser); const char *pStr = pResult->GetString(0); - int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; - const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; + int Minutes = pResult->NumArguments() > 1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; + const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(2) : "No reason given"; NETADDR Addr; if(net_addr_from_str(&Addr, pStr) == 0) - pThis->BanAddr(&Addr, Minutes*60, pReason); + pThis->BanAddr(&Addr, Minutes * 60, pReason); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid network address)"); } @@ -451,12 +450,12 @@ void CNetBan::ConBanRange(IConsole::IResult *pResult, void *pUser) const char *pStr1 = pResult->GetString(0); const char *pStr2 = pResult->GetString(1); - int Minutes = pResult->NumArguments()>2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30; - const char *pReason = pResult->NumArguments()>3 ? pResult->GetString(3) : "No reason given"; + int Minutes = pResult->NumArguments() > 2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30; + const char *pReason = pResult->NumArguments() > 3 ? pResult->GetString(3) : "No reason given"; CNetRange Range; if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0) - pThis->BanRange(&Range, Minutes*60, pReason); + pThis->BanRange(&Range, Minutes * 60, pReason); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid range)"); } @@ -518,7 +517,7 @@ void CNetBan::ConBans(IConsole::IResult *pResult, void *pUser) str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); } - str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count==1?"ban":"bans"); + str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count == 1 ? "ban" : "bans"); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); } @@ -539,7 +538,7 @@ void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser) char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) { - int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + int Min = pBan->m_Info.m_Expires > -1 ? (pBan->m_Info.m_Expires - Now + 59) / 60 : -1; net_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false); str_format(aBuf, sizeof(aBuf), "ban %s %i %s", aAddrStr1, Min, pBan->m_Info.m_aReason); io_write(File, aBuf, str_length(aBuf)); @@ -547,7 +546,7 @@ void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser) } for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) { - int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + int Min = pBan->m_Info.m_Expires > -1 ? (pBan->m_Info.m_Expires - Now + 59) / 60 : -1; net_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false); net_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false); str_format(aBuf, sizeof(aBuf), "ban_range %s %s %i %s", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason); diff --git a/src/engine/shared/netban.h b/src/engine/shared/netban.h index 4df3b3e7f..7507620f7 100644 --- a/src/engine/shared/netban.h +++ b/src/engine/shared/netban.h @@ -5,7 +5,7 @@ inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2) { - return mem_comp(pAddr1, pAddr2, pAddr1->type==NETTYPE_IPV4 ? 8 : 20); + return mem_comp(pAddr1, pAddr2, pAddr1->type == NETTYPE_IPV4 ? 8 : 20); } class CNetRange @@ -33,12 +33,12 @@ protected: bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const { return pRange->m_LB.type == pAddr->type && (Start == 0 || mem_comp(&pRange->m_LB.ip[0], &pAddr->ip[0], Start) == 0) && - mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0; + mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length - Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length - Start) >= 0; } bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const { - return NetMatch(pRange, pAddr, 0, pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16); + return NetMatch(pRange, pAddr, 0, pRange->m_LB.type == NETTYPE_IPV4 ? 4 : 16); } const char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const @@ -62,7 +62,7 @@ protected: { public: int m_Hash; - int m_HashIndex; // matching parts for ranges, 0 for addr + int m_HashIndex; // matching parts for ranges, 0 for addr CNetHash() {} CNetHash(const NETADDR *pAddr); @@ -75,14 +75,15 @@ protected: { enum { - EXPIRES_NEVER=-1, - REASON_LENGTH=64, + EXPIRES_NEVER = -1, + REASON_LENGTH = 64, }; int m_Expires; char m_aReason[REASON_LENGTH]; }; - template struct CBan + template + struct CBan { T m_Data; CBanInfo m_Info; @@ -97,7 +98,8 @@ protected: CBan *m_pPrev; }; - template class CBanPool + template + class CBanPool { public: typedef T CDataType; @@ -127,7 +129,7 @@ protected: private: enum { - MAX_BANS=1024, + MAX_BANS = 1024, }; CBan *m_paaHashList[HashCount][256]; @@ -142,9 +144,12 @@ protected: typedef CBan CBanAddr; typedef CBan CBanRange; - template void MakeBanInfo(const CBan *pBan, char *pBuf, unsigned BuffSize, int Type) const; - template int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); - template int Unban(T *pBanPool, const typename T::CDataType *pData); + template + void MakeBanInfo(const CBan *pBan, char *pBuf, unsigned BuffSize, int Type) const; + template + int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + template + int Unban(T *pBanPool, const typename T::CDataType *pData); class IConsole *m_pConsole; class IStorage *m_pStorage; @@ -155,7 +160,7 @@ protected: public: enum { - MSGTYPE_PLAYER=0, + MSGTYPE_PLAYER = 0, MSGTYPE_LIST, MSGTYPE_BANADD, MSGTYPE_BANREM, @@ -185,7 +190,6 @@ public: static void ConBansSave(class IConsole::IResult *pResult, void *pUser); }; - template void CNetBan::MakeBanInfo(const CBan *pBan, char *pBuf, unsigned BuffSize, int Type) const { @@ -206,11 +210,14 @@ void CNetBan::MakeBanInfo(const CBan *pBan, char *pBuf, unsigned BuffSize, in switch(Type) { case MSGTYPE_LIST: - str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); + break; case MSGTYPE_BANADD: - str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); + break; case MSGTYPE_BANREM: - str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); + break; default: aBuf[0] = 0; } @@ -219,7 +226,7 @@ void CNetBan::MakeBanInfo(const CBan *pBan, char *pBuf, unsigned BuffSize, in // add info part if(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER) { - int Mins = ((pBan->m_Info.m_Expires-time_timestamp()) + 59) / 60; + int Mins = ((pBan->m_Info.m_Expires - time_timestamp()) + 59) / 60; if(Mins <= 1) str_format(pBuf, BuffSize, "%s for 1 minute (%s)", aBuf, pBan->m_Info.m_aReason); else diff --git a/src/engine/shared/network.cpp b/src/engine/shared/network.cpp index 7f2f67338..d74119580 100644 --- a/src/engine/shared/network.cpp +++ b/src/engine/shared/network.cpp @@ -2,10 +2,9 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include - #include "config.h" -#include "network.h" #include "huffman.h" +#include "network.h" void CNetRecvUnpacker::Clear() { @@ -49,17 +48,17 @@ int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) pData = Header.Unpack(pData, (m_pConnection && m_pConnection->m_Sixup) ? 6 : 4); m_CurrentChunk++; - if(pData+Header.m_Size > pEnd) + if(pData + Header.m_Size > pEnd) { Clear(); return 0; } // handle sequence stuff - if(m_pConnection && (Header.m_Flags&NET_CHUNKFLAG_VITAL)) + if(m_pConnection && (Header.m_Flags & NET_CHUNKFLAG_VITAL)) { // anti spoof: ignore unknown sequence - if(Header.m_Sequence == (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE || m_pConnection->m_UnknownSeq) + if(Header.m_Sequence == (m_pConnection->m_Ack + 1) % NET_MAX_SEQUENCE || m_pConnection->m_UnknownSeq) { m_pConnection->m_UnknownSeq = false; @@ -74,7 +73,7 @@ int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) // out of sequence, request resend if(g_Config.m_Debug) - dbg_msg("conn", "asking for resend %d %d", Header.m_Sequence, (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE); + dbg_msg("conn", "asking for resend %d %d", Header.m_Sequence, (m_pConnection->m_Ack + 1) % NET_MAX_SEQUENCE); m_pConnection->SignalResend(); continue; // take the next chunk in the packet } @@ -127,12 +126,12 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct } int HeaderSize = NET_PACKETHEADERSIZE; - if (Sixup) + if(Sixup) { HeaderSize += 4; mem_copy(&aBuffer[3], &SecurityToken, 4); } - else if (SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) + else if(SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) { // append security token // if SecurityToken is NET_SECURITY_TOKEN_UNKNOWN we will still append it hoping to negotiate it @@ -142,7 +141,7 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct // compress if(!NoCompress) - CompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[HeaderSize], NET_MAX_PACKETSIZE-HeaderSize); + CompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[HeaderSize], NET_MAX_PACKETSIZE - HeaderSize); // check if the compression was enabled, successful and good enough if(!NoCompress && CompressedSize > 0 && CompressedSize < pPacket->m_DataSize) @@ -161,9 +160,12 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct if(Sixup) { unsigned Flags = 0; - if (pPacket->m_Flags&NET_PACKETFLAG_CONTROL) Flags |= 1; - if (pPacket->m_Flags&NET_PACKETFLAG_RESEND) Flags |= 2; - if (pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION) Flags |= 4; + if(pPacket->m_Flags & NET_PACKETFLAG_CONTROL) + Flags |= 1; + if(pPacket->m_Flags & NET_PACKETFLAG_RESEND) + Flags |= 2; + if(pPacket->m_Flags & NET_PACKETFLAG_COMPRESSION) + Flags |= 4; pPacket->m_Flags = Flags; } @@ -171,8 +173,8 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct if(FinalSize >= 0) { FinalSize += HeaderSize; - aBuffer[0] = ((pPacket->m_Flags<<2)&0xfc)|((pPacket->m_Ack>>8)&0x3); - aBuffer[1] = pPacket->m_Ack&0xff; + aBuffer[0] = ((pPacket->m_Flags << 2) & 0xfc) | ((pPacket->m_Ack >> 8) & 0x3); + aBuffer[1] = pPacket->m_Ack & 0xff; aBuffer[2] = pPacket->m_NumChunks; net_udp_send(Socket, pAddr, aBuffer, FinalSize); @@ -189,7 +191,7 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct } // TODO: rename this function -int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket, bool& Sixup, SECURITY_TOKEN *SecurityToken, SECURITY_TOKEN *ResponseToken) +int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket, bool &Sixup, SECURITY_TOKEN *SecurityToken, SECURITY_TOKEN *ResponseToken) { // check the size if(Size < NET_PACKETHEADERSIZE || Size > NET_MAX_PACKETSIZE) @@ -209,14 +211,14 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct } // read the packet - pPacket->m_Flags = pBuffer[0]>>2; + pPacket->m_Flags = pBuffer[0] >> 2; - if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) + if(pPacket->m_Flags & NET_PACKETFLAG_CONNLESS) { if(Size < 1) return -1; - Sixup = (pBuffer[0]&0x3) == 1; + Sixup = (pBuffer[0] & 0x3) == 1; int Offset = Sixup ? 9 : 6; if(Size < Offset) return -1; @@ -241,31 +243,34 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct } else { - if(pPacket->m_Flags&NET_PACKETFLAG_UNUSED) + if(pPacket->m_Flags & NET_PACKETFLAG_UNUSED) Sixup = true; int DataStart = Sixup ? 7 : NET_PACKETHEADERSIZE; if(Size < DataStart) return -1; - pPacket->m_Ack = ((pBuffer[0]&0x3)<<8) | pBuffer[1]; + pPacket->m_Ack = ((pBuffer[0] & 0x3) << 8) | pBuffer[1]; pPacket->m_NumChunks = pBuffer[2]; pPacket->m_DataSize = Size - DataStart; if(Sixup) { unsigned Flags = 0; - if (pPacket->m_Flags&1) Flags |= NET_PACKETFLAG_CONTROL; - if (pPacket->m_Flags&2) Flags |= NET_PACKETFLAG_RESEND; - if (pPacket->m_Flags&4) Flags |= NET_PACKETFLAG_COMPRESSION; + if(pPacket->m_Flags & 1) + Flags |= NET_PACKETFLAG_CONTROL; + if(pPacket->m_Flags & 2) + Flags |= NET_PACKETFLAG_RESEND; + if(pPacket->m_Flags & 4) + Flags |= NET_PACKETFLAG_COMPRESSION; pPacket->m_Flags = Flags; mem_copy(SecurityToken, &pBuffer[3], 4); } - if(pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION) + if(pPacket->m_Flags & NET_PACKETFLAG_COMPRESSION) { // Don't allow compressed control packets. - if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) + if(pPacket->m_Flags & NET_PACKETFLAG_CONTROL) { return -1; } @@ -297,14 +302,13 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct return 0; } - void CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken, bool Sixup) { CNetPacketConstruct Construct; Construct.m_Flags = NET_PACKETFLAG_CONTROL; Construct.m_Ack = Ack; Construct.m_NumChunks = 0; - Construct.m_DataSize = 1+ExtraSize; + Construct.m_DataSize = 1 + ExtraSize; Construct.m_aChunkData[0] = ControlMsg; mem_copy(&Construct.m_aChunkData[1], pExtra, ExtraSize); @@ -312,15 +316,14 @@ void CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int Con CNetBase::SendPacket(Socket, pAddr, &Construct, SecurityToken, Sixup, true); } - unsigned char *CNetChunkHeader::Pack(unsigned char *pData, int split) { - pData[0] = ((m_Flags&3)<<6)|((m_Size>>split)&0x3f); - pData[1] = (m_Size&((1<> split) & 0x3f); + pData[1] = (m_Size & ((1 << split) - 1)); + if(m_Flags & NET_CHUNKFLAG_VITAL) { - pData[1] |= (m_Sequence>>2)&(~((1<> 2) & (~((1 << split) - 1)); + pData[2] = m_Sequence & 0xff; return pData + 3; } return pData + 2; @@ -328,21 +331,20 @@ unsigned char *CNetChunkHeader::Pack(unsigned char *pData, int split) unsigned char *CNetChunkHeader::Unpack(unsigned char *pData, int split) { - m_Flags = (pData[0]>>6)&3; - m_Size = ((pData[0]&0x3f)<> 6) & 3; + m_Size = ((pData[0] & 0x3f) << split) | (pData[1] & ((1 << split) - 1)); m_Sequence = -1; - if(m_Flags&NET_CHUNKFLAG_VITAL) + if(m_Flags & NET_CHUNKFLAG_VITAL) { - m_Sequence = ((pData[1]&(~((1< @@ -34,61 +34,60 @@ CURRENT: enum { - NETFLAG_ALLOWSTATELESS=1, - NETSENDFLAG_VITAL=1, - NETSENDFLAG_CONNLESS=2, - NETSENDFLAG_FLUSH=4, - NETSENDFLAG_EXTENDED=8, + NETFLAG_ALLOWSTATELESS = 1, + NETSENDFLAG_VITAL = 1, + NETSENDFLAG_CONNLESS = 2, + NETSENDFLAG_FLUSH = 4, + NETSENDFLAG_EXTENDED = 8, - NETSTATE_OFFLINE=0, + NETSTATE_OFFLINE = 0, NETSTATE_CONNECTING, NETSTATE_ONLINE, - NETBANTYPE_SOFT=1, - NETBANTYPE_DROP=2 + NETBANTYPE_SOFT = 1, + NETBANTYPE_DROP = 2 }; - enum { NET_VERSION = 2, NET_MAX_PACKETSIZE = 1400, - NET_MAX_PAYLOAD = NET_MAX_PACKETSIZE-6, + NET_MAX_PAYLOAD = NET_MAX_PACKETSIZE - 6, NET_MAX_CHUNKHEADERSIZE = 5, NET_PACKETHEADERSIZE = 3, NET_MAX_CLIENTS = 64, NET_MAX_CONSOLE_CLIENTS = 4, - NET_MAX_SEQUENCE = 1<<10, - NET_SEQUENCE_MASK = NET_MAX_SEQUENCE-1, + NET_MAX_SEQUENCE = 1 << 10, + NET_SEQUENCE_MASK = NET_MAX_SEQUENCE - 1, - NET_CONNSTATE_OFFLINE=0, - NET_CONNSTATE_CONNECT=1, - NET_CONNSTATE_PENDING=2, - NET_CONNSTATE_ONLINE=3, - NET_CONNSTATE_ERROR=4, + NET_CONNSTATE_OFFLINE = 0, + NET_CONNSTATE_CONNECT = 1, + NET_CONNSTATE_PENDING = 2, + NET_CONNSTATE_ONLINE = 3, + NET_CONNSTATE_ERROR = 4, - NET_PACKETFLAG_UNUSED=1<<0, - NET_PACKETFLAG_TOKEN=1<<1, - NET_PACKETFLAG_CONTROL=1<<2, - NET_PACKETFLAG_CONNLESS=1<<3, - NET_PACKETFLAG_RESEND=1<<4, - NET_PACKETFLAG_COMPRESSION=1<<5, + NET_PACKETFLAG_UNUSED = 1 << 0, + NET_PACKETFLAG_TOKEN = 1 << 1, + NET_PACKETFLAG_CONTROL = 1 << 2, + NET_PACKETFLAG_CONNLESS = 1 << 3, + NET_PACKETFLAG_RESEND = 1 << 4, + NET_PACKETFLAG_COMPRESSION = 1 << 5, // NOT SENT VIA THE NETWORK DIRECTLY: - NET_PACKETFLAG_EXTENDED=1<<6, + NET_PACKETFLAG_EXTENDED = 1 << 6, - NET_CHUNKFLAG_VITAL=1, - NET_CHUNKFLAG_RESEND=2, + NET_CHUNKFLAG_VITAL = 1, + NET_CHUNKFLAG_RESEND = 2, - NET_CTRLMSG_KEEPALIVE=0, - NET_CTRLMSG_CONNECT=1, - NET_CTRLMSG_CONNECTACCEPT=2, - NET_CTRLMSG_ACCEPT=3, - NET_CTRLMSG_CLOSE=4, + NET_CTRLMSG_KEEPALIVE = 0, + NET_CTRLMSG_CONNECT = 1, + NET_CTRLMSG_CONNECTACCEPT = 2, + NET_CTRLMSG_ACCEPT = 3, + NET_CTRLMSG_CLOSE = 4, - NET_CONN_BUFFERSIZE=1024*32, + NET_CONN_BUFFERSIZE = 1024 * 32, - NET_CONNLIMIT_IPS=16, + NET_CONNLIMIT_IPS = 16, NET_ENUM_TERMINATOR }; @@ -158,13 +157,13 @@ public: unsigned char m_aExtraData[4]; }; - class CNetConnection { // TODO: is this needed because this needs to be aware of // the ack sequencing number and is also responible for updating // that. this should be fixed. friend class CNetRecvUnpacker; + private: unsigned short m_Sequence; unsigned short m_Ack; @@ -206,7 +205,7 @@ public: bool m_TimeoutProtected; bool m_TimeoutSituation; - void Reset(bool Rejoin=false); + void Reset(bool Rejoin = false); void Init(NETSOCKET Socket, bool BlockCloseMsg); int Connect(NETADDR *pAddr); void Disconnect(const char *pReason); @@ -323,7 +322,6 @@ class CNetServer NETFUNC_CLIENTREJOIN m_pfnClientRejoin; void *m_UserPtr; - int m_NumConAttempts; // log flooding attacks int64 m_TimeNumConAttempts; unsigned char m_SecurityTokenSeed[16]; @@ -344,7 +342,7 @@ class CNetServer int GetClientSlot(const NETADDR &Addr); void SendControl(NETADDR &Addr, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken); - int TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, bool VanillaAuth=false, bool Sixup=false, SECURITY_TOKEN Token=0); + int TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, bool VanillaAuth = false, bool Sixup = false, SECURITY_TOKEN Token = 0); int NumClientsWithAddr(NETADDR Addr); bool Connlimit(NETADDR Addr); void SendMsgs(NETADDR &Addr, const CMsgPacker *Msgs[], int num); @@ -429,13 +427,12 @@ public: class CNetBan *NetBan() const { return m_pNetBan; } }; - - // client side class CNetClient { CNetConnection m_Connection; CNetRecvUnpacker m_RecvUnpacker; + public: NETSOCKET m_Socket; MMSGS m_MMSGS; @@ -466,14 +463,13 @@ public: bool SecurityTokenUnknown() { return m_Connection.SecurityToken() == NET_SECURITY_TOKEN_UNKNOWN; } }; - - // TODO: both, fix these. This feels like a junk class for stuff that doesn't fit anywere class CNetBase { static IOHANDLE ms_DataLogSent; static IOHANDLE ms_DataLogRecv; static CHuffman ms_Huffman; + public: static void OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv); static void CloseLog(); @@ -485,11 +481,10 @@ public: static void SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize, bool Extended, unsigned char aExtra[4]); static void SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket, SECURITY_TOKEN SecurityToken, bool Sixup = false, bool NoCompress = false); - static int UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket, bool& Sixup, SECURITY_TOKEN *SecurityToken = 0, SECURITY_TOKEN *ResponseToken = 0); + static int UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket, bool &Sixup, SECURITY_TOKEN *SecurityToken = 0, SECURITY_TOKEN *ResponseToken = 0); // The backroom is ack-NET_MAX_SEQUENCE/2. Used for knowing if we acked a packet or not static int IsSeqInBackroom(int Seq, int Ack); }; - #endif diff --git a/src/engine/shared/network_client.cpp b/src/engine/shared/network_client.cpp index 950702aed..70f6d9a16 100644 --- a/src/engine/shared/network_client.cpp +++ b/src/engine/shared/network_client.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "network.h" +#include bool CNetClient::Open(NETADDR BindAddr, int Flags) { @@ -28,7 +28,6 @@ int CNetClient::Close() return 0; } - int CNetClient::Disconnect(const char *pReason) { //dbg_msg("netclient", "disconnected. reason=\"%s\"", pReason); @@ -76,14 +75,14 @@ int CNetClient::Recv(CNetChunk *pChunk) bool Sixup = false; if(CNetBase::UnpackPacket(pData, Bytes, &m_RecvUnpacker.m_Data, Sixup) == 0) { - if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_CONNLESS) { pChunk->m_Flags = NETSENDFLAG_CONNLESS; pChunk->m_ClientID = -1; pChunk->m_Address = Addr; pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; - if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_EXTENDED) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_EXTENDED) { pChunk->m_Flags |= NETSENDFLAG_EXTENDED; mem_copy(pChunk->m_aExtraData, m_RecvUnpacker.m_Data.m_aExtraData, sizeof(pChunk->m_aExtraData)); @@ -92,8 +91,7 @@ int CNetClient::Recv(CNetChunk *pChunk) } else { - if(m_Connection.State() != NET_CONNSTATE_OFFLINE && m_Connection.State() != NET_CONNSTATE_ERROR && net_addr_comp(m_Connection.PeerAddress(), &Addr) == 0 - && m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) + if(m_Connection.State() != NET_CONNSTATE_OFFLINE && m_Connection.State() != NET_CONNSTATE_ERROR && net_addr_comp(m_Connection.PeerAddress(), &Addr) == 0 && m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) m_RecvUnpacker.Start(&Addr, &m_Connection, 0); } } @@ -109,23 +107,23 @@ int CNetClient::Send(CNetChunk *pChunk) return -1; } - if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) + if(pChunk->m_Flags & NETSENDFLAG_CONNLESS) { // send connectionless packet CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize, - pChunk->m_Flags&NETSENDFLAG_EXTENDED, pChunk->m_aExtraData); + pChunk->m_Flags & NETSENDFLAG_EXTENDED, pChunk->m_aExtraData); } else { int Flags = 0; dbg_assert(pChunk->m_ClientID == 0, "errornous client id"); - if(pChunk->m_Flags&NETSENDFLAG_VITAL) + if(pChunk->m_Flags & NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData); - if(pChunk->m_Flags&NETSENDFLAG_FLUSH) + if(pChunk->m_Flags & NETSENDFLAG_FLUSH) m_Connection.Flush(); } return 0; diff --git a/src/engine/shared/network_conn.cpp b/src/engine/shared/network_conn.cpp index 2a6a65262..20f7312e7 100644 --- a/src/engine/shared/network_conn.cpp +++ b/src/engine/shared/network_conn.cpp @@ -1,8 +1,8 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "config.h" #include "network.h" +#include SECURITY_TOKEN ToSecurityToken(unsigned char *pData) { @@ -23,7 +23,7 @@ void CNetConnection::Reset(bool Rejoin) m_PeerAck = 0; m_RemoteClosed = 0; - if (!Rejoin) + if(!Rejoin) { m_TimeoutProtected = false; m_TimeoutSituation = false; @@ -106,7 +106,7 @@ int CNetConnection::Flush() int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence) { - if (m_State == NET_CONNSTATE_OFFLINE || m_State == NET_CONNSTATE_ERROR) + if(m_State == NET_CONNSTATE_OFFLINE || m_State == NET_CONNSTATE_ERROR) return -1; unsigned char *pChunkData; @@ -127,20 +127,20 @@ int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int // m_Construct.m_NumChunks++; - m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); + m_Construct.m_DataSize = (int)(pChunkData - m_Construct.m_aChunkData); // set packet flags as well - if(Flags&NET_CHUNKFLAG_VITAL && !(Flags&NET_CHUNKFLAG_RESEND)) + if(Flags & NET_CHUNKFLAG_VITAL && !(Flags & NET_CHUNKFLAG_RESEND)) { // save packet if we need to resend - CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+DataSize); + CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend) + DataSize); if(pResend) { pResend->m_Sequence = Sequence; pResend->m_Flags = Flags; pResend->m_DataSize = DataSize; - pResend->m_pData = (unsigned char *)(pResend+1); + pResend->m_pData = (unsigned char *)(pResend + 1); pResend->m_FirstSendTime = time_get(); pResend->m_LastSendTime = pResend->m_FirstSendTime; mem_copy(pResend->m_pData, pData, DataSize); @@ -157,8 +157,8 @@ int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int int CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData) { - if(Flags&NET_CHUNKFLAG_VITAL) - m_Sequence = (m_Sequence+1)%NET_MAX_SEQUENCE; + if(Flags & NET_CHUNKFLAG_VITAL) + m_Sequence = (m_Sequence + 1) % NET_MAX_SEQUENCE; return QueueChunkEx(Flags, DataSize, pData, m_Sequence); } @@ -171,7 +171,7 @@ void CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSi void CNetConnection::ResendChunk(CNetChunkResend *pResend) { - QueueChunkEx(pResend->m_Flags|NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence); + QueueChunkEx(pResend->m_Flags | NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence); pResend->m_LastSendTime = time_get(); } @@ -205,7 +205,7 @@ void CNetConnection::Disconnect(const char *pReason) if(!m_TimeoutSituation) { if(pReason) - SendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason)+1); + SendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason) + 1); else SendControl(NET_CTRLMSG_CLOSE, 0, 0); } @@ -242,13 +242,13 @@ void CNetConnection::DirectInit(NETADDR &Addr, SECURITY_TOKEN SecurityToken, SEC int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_TOKEN SecurityToken) { - if (!m_Sixup && State() != NET_CONNSTATE_OFFLINE && m_SecurityToken != NET_SECURITY_TOKEN_UNKNOWN && m_SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) + if(!m_Sixup && State() != NET_CONNSTATE_OFFLINE && m_SecurityToken != NET_SECURITY_TOKEN_UNKNOWN && m_SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) { // supposed to have a valid token in this packet, check it - if (pPacket->m_DataSize < (int)sizeof(m_SecurityToken)) + if(pPacket->m_DataSize < (int)sizeof(m_SecurityToken)) return 0; pPacket->m_DataSize -= sizeof(m_SecurityToken); - if (m_SecurityToken != ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize])) + if(m_SecurityToken != ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize])) { if(g_Config.m_Debug) dbg_msg("security", "token mismatch, expected %d got %d", m_SecurityToken, ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize])); @@ -275,11 +275,11 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_ int64 Now = time_get(); // check if resend is requested - if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) + if(pPacket->m_Flags & NET_PACKETFLAG_RESEND) Resend(); // - if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) + if(pPacket->m_Flags & NET_PACKETFLAG_CONTROL) { int CtrlMsg = pPacket->m_aChunkData[0]; @@ -329,9 +329,7 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_ m_LastSendTime = Now; m_LastRecvTime = Now; m_LastUpdateTime = Now; - if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN - && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) - && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) + if(m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) { m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED; if(g_Config.m_Debug) @@ -353,9 +351,7 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_ // connection made if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT) { - if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN - && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) - && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) + if(m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) { m_SecurityToken = ToSecurityToken(&pPacket->m_aChunkData[1 + sizeof(SECURITY_TOKEN_MAGIC)]); if(g_Config.m_Debug) @@ -400,7 +396,7 @@ int CNetConnection::Update() { int64 Now = time_get(); - if(State() == NET_CONNSTATE_ERROR && m_TimeoutSituation && (Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeoutProtection) + if(State() == NET_CONNSTATE_ERROR && m_TimeoutSituation && (Now - m_LastRecvTime) > time_freq() * g_Config.m_ConnTimeoutProtection) { m_TimeoutSituation = false; SetError("Timeout Protection over"); @@ -414,7 +410,7 @@ int CNetConnection::Update() // check for timeout if(State() != NET_CONNSTATE_OFFLINE && State() != NET_CONNSTATE_CONNECT && - (Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeout) + (Now - m_LastRecvTime) > time_freq() * g_Config.m_ConnTimeout) { m_State = NET_CONNSTATE_ERROR; SetError("Timeout"); @@ -427,7 +423,7 @@ int CNetConnection::Update() CNetChunkResend *pResend = m_Buffer.First(); // check if we have some really old stuff laying around and abort if not acked - if(Now-pResend->m_FirstSendTime > time_freq()*g_Config.m_ConnTimeout) + if(Now - pResend->m_FirstSendTime > time_freq() * g_Config.m_ConnTimeout) { m_State = NET_CONNSTATE_ERROR; char aBuf[512]; @@ -438,7 +434,7 @@ int CNetConnection::Update() else { // resend packet if we haven't got it acked in 1 second - if(Now-pResend->m_LastSendTime > time_freq()) + if(Now - pResend->m_LastSendTime > time_freq()) ResendChunk(pResend); } } @@ -446,24 +442,24 @@ int CNetConnection::Update() // send keep alives if nothing has happened for 250ms if(State() == NET_CONNSTATE_ONLINE) { - if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed + if(time_get() - m_LastSendTime > time_freq() / 2) // flush connection after 500ms if needed { int NumFlushedChunks = Flush(); if(NumFlushedChunks && g_Config.m_Debug) dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks); } - if(time_get()-m_LastSendTime > time_freq()) + if(time_get() - m_LastSendTime > time_freq()) SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0); } else if(State() == NET_CONNSTATE_CONNECT) { - if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms + if(time_get() - m_LastSendTime > time_freq() / 2) // send a new connect every 500ms SendControl(NET_CTRLMSG_CONNECT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); } else if(State() == NET_CONNSTATE_PENDING) { - if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms + if(time_get() - m_LastSendTime > time_freq() / 2) // send a new connect/accept every 500ms SendControl(NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); } @@ -489,12 +485,12 @@ void CNetConnection::SetTimedOut(const NETADDR *pAddr, int Sequence, int Ack, SE // copy resend buffer m_Buffer.Init(); - while (pResendBuffer->First()) + while(pResendBuffer->First()) { CNetChunkResend *First = pResendBuffer->First(); - CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+First->m_DataSize); - mem_copy(pResend, First, sizeof(CNetChunkResend)+First->m_DataSize); + CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend) + First->m_DataSize); + mem_copy(pResend, First, sizeof(CNetChunkResend) + First->m_DataSize); pResendBuffer->PopFirst(); } diff --git a/src/engine/shared/network_console.cpp b/src/engine/shared/network_console.cpp index db8104b52..954bd4a61 100644 --- a/src/engine/shared/network_console.cpp +++ b/src/engine/shared/network_console.cpp @@ -7,7 +7,6 @@ #include "netban.h" #include "network.h" - bool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, int Flags) { // zero out the whole structure @@ -60,7 +59,7 @@ int CNetConsole::Drop(int ClientID, const char *pReason) int CNetConsole::AcceptClient(NETSOCKET Socket, const NETADDR *pAddr) { - char aError[256] = { 0 }; + char aError[256] = {0}; int FreeSlot = -1; // look for free slot or multiple client diff --git a/src/engine/shared/network_console_conn.cpp b/src/engine/shared/network_console_conn.cpp index 9bc163aff..b166335f4 100644 --- a/src/engine/shared/network_console_conn.cpp +++ b/src/engine/shared/network_console_conn.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "network.h" +#include void CConsoleNetConnection::Reset() { @@ -16,15 +16,15 @@ void CConsoleNetConnection::Reset() m_BufferOffset = 0; m_LineEndingDetected = false; - #if defined(CONF_FAMILY_WINDOWS) - m_aLineEnding[0] = '\r'; - m_aLineEnding[1] = '\n'; - m_aLineEnding[2] = 0; - #else - m_aLineEnding[0] = '\n'; - m_aLineEnding[1] = 0; - m_aLineEnding[2] = 0; - #endif +#if defined(CONF_FAMILY_WINDOWS) + m_aLineEnding[0] = '\r'; + m_aLineEnding[1] = '\n'; + m_aLineEnding[2] = 0; +#else + m_aLineEnding[0] = '\n'; + m_aLineEnding[1] = 0; + m_aLineEnding[2] = 0; +#endif } void CConsoleNetConnection::Init(NETSOCKET Socket, const NETADDR *pAddr) @@ -62,7 +62,7 @@ int CConsoleNetConnection::Update() return -1; } - int Bytes = net_tcp_recv(m_Socket, m_aBuffer+m_BufferOffset, (int)(sizeof(m_aBuffer))-m_BufferOffset); + int Bytes = net_tcp_recv(m_Socket, m_aBuffer + m_BufferOffset, (int)(sizeof(m_aBuffer)) - m_BufferOffset); if(Bytes > 0) { @@ -102,9 +102,9 @@ int CConsoleNetConnection::Recv(char *pLine, int MaxLength) if(!m_LineEndingDetected) { m_aLineEnding[0] = m_aBuffer[StartOffset]; - if(StartOffset+1 < m_BufferOffset && (m_aBuffer[StartOffset+1] == '\r' || m_aBuffer[StartOffset+1] == '\n') && - m_aBuffer[StartOffset] != m_aBuffer[StartOffset+1]) - m_aLineEnding[1] = m_aBuffer[StartOffset+1]; + if(StartOffset + 1 < m_BufferOffset && (m_aBuffer[StartOffset + 1] == '\r' || m_aBuffer[StartOffset + 1] == '\n') && + m_aBuffer[StartOffset] != m_aBuffer[StartOffset + 1]) + m_aLineEnding[1] = m_aBuffer[StartOffset + 1]; m_LineEndingDetected = true; } @@ -123,7 +123,7 @@ int CConsoleNetConnection::Recv(char *pLine, int MaxLength) { if(StartOffset > 0) { - mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + mem_move(m_aBuffer, m_aBuffer + StartOffset, m_BufferOffset - StartOffset); m_BufferOffset -= StartOffset; } return 0; @@ -131,19 +131,19 @@ int CConsoleNetConnection::Recv(char *pLine, int MaxLength) } // extract message and update buffer - if(MaxLength-1 < EndOffset-StartOffset) + if(MaxLength - 1 < EndOffset - StartOffset) { if(StartOffset > 0) { - mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + mem_move(m_aBuffer, m_aBuffer + StartOffset, m_BufferOffset - StartOffset); m_BufferOffset -= StartOffset; } return 0; } - mem_copy(pLine, m_aBuffer+StartOffset, EndOffset-StartOffset); - pLine[EndOffset-StartOffset] = 0; + mem_copy(pLine, m_aBuffer + StartOffset, EndOffset - StartOffset); + pLine[EndOffset - StartOffset] = 0; str_sanitize_cc(pLine); - mem_move(m_aBuffer, m_aBuffer+EndOffset, m_BufferOffset-EndOffset); + mem_move(m_aBuffer, m_aBuffer + EndOffset, m_BufferOffset - EndOffset); m_BufferOffset -= EndOffset; return 1; } @@ -157,11 +157,11 @@ int CConsoleNetConnection::Send(const char *pLine) return -1; char aBuf[1024]; - str_copy(aBuf, pLine, (int)(sizeof(aBuf))-2); + str_copy(aBuf, pLine, (int)(sizeof(aBuf)) - 2); int Length = str_length(aBuf); aBuf[Length] = m_aLineEnding[0]; - aBuf[Length+1] = m_aLineEnding[1]; - aBuf[Length+2] = m_aLineEnding[2]; + aBuf[Length + 1] = m_aLineEnding[1]; + aBuf[Length + 2] = m_aLineEnding[2]; Length += 3; const char *pData = aBuf; diff --git a/src/engine/shared/network_server.cpp b/src/engine/shared/network_server.cpp index 00cd64aec..9db80304d 100644 --- a/src/engine/shared/network_server.cpp +++ b/src/engine/shared/network_server.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include #include @@ -39,8 +39,7 @@ unsigned char g_aDummyMapData[] = { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x78, 0x9c, 0x63, 0x64, 0x60, 0x60, 0x60, 0x44, - 0xc2, 0x00, 0x00, 0x38, 0x00, 0x05 -}; + 0xc2, 0x00, 0x00, 0x38, 0x00, 0x05}; static SECURITY_TOKEN ToSecurityToken(const unsigned char *pData) { @@ -134,7 +133,7 @@ int CNetServer::Update() m_aSlots[i].m_Connection.Update(); if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR && (!m_aSlots[i].m_Connection.m_TimeoutProtected || - !m_aSlots[i].m_Connection.m_TimeoutSituation)) + !m_aSlots[i].m_Connection.m_TimeoutSituation)) { Drop(i, m_aSlots[i].m_Connection.ErrorString()); } @@ -147,14 +146,14 @@ SECURITY_TOKEN CNetServer::GetToken(const NETADDR &Addr) { SHA256_CTX Sha256; sha256_init(&Sha256); - sha256_update(&Sha256, (unsigned char*)m_SecurityTokenSeed, sizeof(m_SecurityTokenSeed)); - sha256_update(&Sha256, (unsigned char*)&Addr, 20); // omit port, bad idea! + sha256_update(&Sha256, (unsigned char *)m_SecurityTokenSeed, sizeof(m_SecurityTokenSeed)); + sha256_update(&Sha256, (unsigned char *)&Addr, 20); // omit port, bad idea! SECURITY_TOKEN SecurityToken = ToSecurityToken(sha256_finish(&Sha256).data); - if (SecurityToken == NET_SECURITY_TOKEN_UNKNOWN || + if(SecurityToken == NET_SECURITY_TOKEN_UNKNOWN || SecurityToken == NET_SECURITY_TOKEN_UNSUPPORTED) - SecurityToken = 1; + SecurityToken = 1; return SecurityToken; } @@ -172,7 +171,7 @@ int CNetServer::NumClientsWithAddr(NETADDR Addr) if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE || (m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR && (!m_aSlots[i].m_Connection.m_TimeoutProtected || - !m_aSlots[i].m_Connection.m_TimeoutSituation))) + !m_aSlots[i].m_Connection.m_TimeoutSituation))) continue; if(!net_addr_comp_noport(&Addr, m_aSlots[i].m_Connection.PeerAddress())) @@ -224,7 +223,7 @@ int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, boo return -1; // failed to add client? } - if (Connlimit(Addr)) + if(Connlimit(Addr)) { const char Msg[] = "Too many connections in a short time"; CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, Msg, sizeof(Msg), SecurityToken, Sixup); @@ -232,7 +231,7 @@ int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, boo } // check for sv_max_clients_per_ip - if (NumClientsWithAddr(Addr) + 1 > m_MaxClientsPerIP) + if(NumClientsWithAddr(Addr) + 1 > m_MaxClientsPerIP) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Only %d players with the same IP are allowed", m_MaxClientsPerIP); @@ -250,7 +249,7 @@ int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, boo } } - if (Slot == -1) + if(Slot == -1) { const char FullMsg[] = "This server is full"; CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, FullMsg, sizeof(FullMsg), SecurityToken, Sixup); @@ -261,7 +260,7 @@ int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, boo // init connection slot m_aSlots[Slot].m_Connection.DirectInit(Addr, SecurityToken, Token, Sixup); - if (VanillaAuth) + if(VanillaAuth) { // client sequence is unknown if the auth was done // connection-less @@ -270,15 +269,14 @@ int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, boo m_aSlots[Slot].m_Connection.SetSequence(6); } - if (g_Config.m_Debug) + if(g_Config.m_Debug) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); dbg_msg("security", "client accepted %s", aAddrStr); } - - if (VanillaAuth) + if(VanillaAuth) m_pfnNewClientNoAuth(Slot, m_UserPtr); else m_pfnNewClient(Slot, m_UserPtr, Sixup); @@ -292,13 +290,13 @@ void CNetServer::SendMsgs(NETADDR &Addr, const CMsgPacker *Msgs[], int num) mem_zero(&m_Construct, sizeof(m_Construct)); unsigned char *pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize]; - for (int i = 0; i < num; i++) + for(int i = 0; i < num; i++) { const CMsgPacker *pMsg = Msgs[i]; CNetChunkHeader Header; Header.m_Flags = NET_CHUNKFLAG_VITAL; Header.m_Size = pMsg->Size(); - Header.m_Sequence = i+1; + Header.m_Sequence = i + 1; pChunkData = Header.Pack(pChunkData); mem_copy(pChunkData, pMsg->Data(), pMsg->Size()); *pChunkData <<= 1; @@ -308,29 +306,29 @@ void CNetServer::SendMsgs(NETADDR &Addr, const CMsgPacker *Msgs[], int num) } // - m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); + m_Construct.m_DataSize = (int)(pChunkData - m_Construct.m_aChunkData); CNetBase::SendPacket(m_Socket, &Addr, &m_Construct, NET_SECURITY_TOKEN_UNSUPPORTED); } // connection-less msg packet without token-support void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) { - bool IsCtrl = Packet.m_Flags&NET_PACKETFLAG_CONTROL; + bool IsCtrl = Packet.m_Flags & NET_PACKETFLAG_CONTROL; int CtrlMsg = m_RecvUnpacker.m_Data.m_aChunkData[0]; // log flooding //TODO: remove - if (g_Config.m_Debug) + if(g_Config.m_Debug) { int64 Now = time_get(); - if (Now - m_TimeNumConAttempts > time_freq()) + if(Now - m_TimeNumConAttempts > time_freq()) // reset m_NumConAttempts = 0; m_NumConAttempts++; - if (m_NumConAttempts > 100) + if(m_NumConAttempts > 100) { dbg_msg("security", "flooding detected"); @@ -339,14 +337,13 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) } } - - if (IsCtrl && CtrlMsg == NET_CTRLMSG_CONNECT) + if(IsCtrl && CtrlMsg == NET_CTRLMSG_CONNECT) { - if (g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0') + if(g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0') { bool Flooding = false; - if (g_Config.m_SvVanConnPerSecond) + if(g_Config.m_SvVanConnPerSecond) { // detect flooding Flooding = m_VConnNum > g_Config.m_SvVanConnPerSecond; @@ -363,7 +360,7 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) } } - if (g_Config.m_Debug && Flooding) + if(g_Config.m_Debug && Flooding) { dbg_msg("security", "vanilla connection flooding detected"); } @@ -388,7 +385,7 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) // send mapchange + map data + con_ready + 3 x empty snap (with token) CMsgPacker MapChangeMsg(NETMSG_MAP_CHANGE); - if (Flooding) + if(Flooding) { // Fallback to dm1 MapChangeMsg.AddString("dm1", 0); @@ -405,7 +402,7 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) CMsgPacker MapDataMsg(NETMSG_MAP_DATA); - if (Flooding) + if(Flooding) { // send empty map data to keep 0.6.4 support MapDataMsg.AddInt(1); // last chunk @@ -433,7 +430,7 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) // send all chunks/msgs in one packet const CMsgPacker *Msgs[] = {&MapChangeMsg, &MapDataMsg, &ConReadyMsg, - &SnapEmptyMsg, &SnapEmptyMsg, &SnapEmptyMsg}; + &SnapEmptyMsg, &SnapEmptyMsg, &SnapEmptyMsg}; SendMsgs(Addr, Msgs, 6); } else @@ -454,23 +451,22 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) Unpacker.Reset(pData, h.m_Size); int Msg = Unpacker.GetInt() >> 1; - if (Msg == NETMSG_INPUT) + if(Msg == NETMSG_INPUT) { SECURITY_TOKEN SecurityToken = Unpacker.GetInt(); - if (SecurityToken == GetVanillaToken(Addr)) + if(SecurityToken == GetVanillaToken(Addr)) { - if (g_Config.m_Debug) + if(g_Config.m_Debug) dbg_msg("security", "new client (vanilla handshake)"); // try to accept client skipping auth state TryAcceptClient(Addr, NET_SECURITY_TOKEN_UNSUPPORTED, true); } - else if (g_Config.m_Debug) + else if(g_Config.m_Debug) dbg_msg("security", "invalid token (vanilla handshake)"); - } else { - if (g_Config.m_Debug) + if(g_Config.m_Debug) { dbg_msg("security", "invalid preconn msg %d", Msg); } @@ -480,32 +476,32 @@ void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) void CNetServer::OnConnCtrlMsg(NETADDR &Addr, int ClientID, int ControlMsg, const CNetPacketConstruct &Packet) { - if (ControlMsg == NET_CTRLMSG_CONNECT) + if(ControlMsg == NET_CTRLMSG_CONNECT) { // got connection attempt inside of valid session // the client probably wants to reconnect bool SupportsToken = Packet.m_DataSize >= - (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && - !mem_comp(&Packet.m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && + !mem_comp(&Packet.m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); - if (SupportsToken) + if(SupportsToken) { // response connection request with token SECURITY_TOKEN Token = GetToken(Addr); SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC), Token); } - if (g_Config.m_Debug) + if(g_Config.m_Debug) dbg_msg("security", "client %d wants to reconnect", ClientID); } - else if (ControlMsg == NET_CTRLMSG_ACCEPT && Packet.m_DataSize == 1 + sizeof(SECURITY_TOKEN)) + else if(ControlMsg == NET_CTRLMSG_ACCEPT && Packet.m_DataSize == 1 + sizeof(SECURITY_TOKEN)) { SECURITY_TOKEN Token = ToSecurityToken(&Packet.m_aChunkData[1]); - if (Token == GetToken(Addr)) + if(Token == GetToken(Addr)) { // correct token // try to accept client - if (g_Config.m_Debug) + if(g_Config.m_Debug) dbg_msg("security", "client %d reconnect", ClientID); // reset netconn and process rejoin @@ -520,7 +516,6 @@ void CNetServer::OnTokenCtrlMsg(NETADDR &Addr, int ControlMsg, const CNetPacketC if(ClientExists(Addr)) return; // silently ignore - if(Addr.type == NETTYPE_WEBSOCKET_IPV4) { // websocket client doesn't send token @@ -559,7 +554,7 @@ int CNetServer::OnSixupCtrlMsg(NETADDR &Addr, CNetChunk *pChunk, int ControlMsg, if(m_RecvUnpacker.m_Data.m_DataSize < 5 || ClientExists(Addr)) return 0; // silently ignore - mem_copy(&ResponseToken, Packet.m_aChunkData+1, 4); + mem_copy(&ResponseToken, Packet.m_aChunkData + 1, 4); if(ControlMsg == 5) { @@ -610,20 +605,16 @@ int CNetServer::GetClientSlot(const NETADDR &Addr) static bool IsDDNetControlMsg(const CNetPacketConstruct *pPacket) { - if(!(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) - || pPacket->m_DataSize < 1) + if(!(pPacket->m_Flags & NET_PACKETFLAG_CONTROL) || pPacket->m_DataSize < 1) { return false; } - if(pPacket->m_aChunkData[0] == NET_CTRLMSG_CONNECT - && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) - && mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)) == 0) + if(pPacket->m_aChunkData[0] == NET_CTRLMSG_CONNECT && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)) == 0) { // DDNet CONNECT return true; } - if(pPacket->m_aChunkData[0] == NET_CTRLMSG_ACCEPT - && pPacket->m_DataSize >= 1 + (int)sizeof(SECURITY_TOKEN)) + if(pPacket->m_aChunkData[0] == NET_CTRLMSG_ACCEPT && pPacket->m_DataSize >= 1 + (int)sizeof(SECURITY_TOKEN)) { // DDNet ACCEPT return true; @@ -657,7 +648,7 @@ int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *ResponseToken) if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf))) { // banned, reply with a message - CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf)+1, NET_SECURITY_TOKEN_UNSUPPORTED); + CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf) + 1, NET_SECURITY_TOKEN_UNSUPPORTED); continue; } @@ -666,7 +657,7 @@ int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *ResponseToken) *ResponseToken = NET_SECURITY_TOKEN_UNKNOWN; if(CNetBase::UnpackPacket(pData, Bytes, &m_RecvUnpacker.m_Data, Sixup, &Token, ResponseToken) == 0) { - if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_CONNLESS) { if(Sixup && Token != GetToken(Addr)) continue; @@ -676,7 +667,7 @@ int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *ResponseToken) pChunk->m_Address = Addr; pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; - if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_EXTENDED) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_EXTENDED) { pChunk->m_Flags |= NETSENDFLAG_EXTENDED; mem_copy(pChunk->m_aExtraData, m_RecvUnpacker.m_Data.m_aExtraData, sizeof(pChunk->m_aExtraData)); @@ -686,8 +677,8 @@ int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *ResponseToken) else { // drop invalid ctrl packets - if (m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && - m_RecvUnpacker.m_Data.m_DataSize == 0) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_CONTROL && + m_RecvUnpacker.m_Data.m_DataSize == 0) continue; // normal packet, find matching slot @@ -700,12 +691,12 @@ int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *ResponseToken) continue; } - if (Slot != -1) + if(Slot != -1) { // found // control - if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL) + if(m_RecvUnpacker.m_Data.m_Flags & NET_PACKETFLAG_CONTROL) OnConnCtrlMsg(Addr, Slot, m_RecvUnpacker.m_Data.m_aChunkData[0], m_RecvUnpacker.m_Data); if(m_aSlots[Slot].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr, Token)) @@ -745,11 +736,11 @@ int CNetServer::Send(CNetChunk *pChunk) return -1; } - if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) + if(pChunk->m_Flags & NETSENDFLAG_CONNLESS) { // send connectionless packet CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize, - pChunk->m_Flags&NETSENDFLAG_EXTENDED, pChunk->m_aExtraData); + pChunk->m_Flags & NETSENDFLAG_EXTENDED, pChunk->m_aExtraData); } else { @@ -757,12 +748,12 @@ int CNetServer::Send(CNetChunk *pChunk) dbg_assert(pChunk->m_ClientID >= 0, "errornous client id"); dbg_assert(pChunk->m_ClientID < MaxClients(), "errornous client id"); - if(pChunk->m_Flags&NETSENDFLAG_VITAL) + if(pChunk->m_Flags & NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; if(m_aSlots[pChunk->m_ClientID].m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData) == 0) { - if(pChunk->m_Flags&NETSENDFLAG_FLUSH) + if(pChunk->m_Flags & NETSENDFLAG_FLUSH) m_aSlots[pChunk->m_ClientID].m_Connection.Flush(); } else @@ -788,11 +779,11 @@ int CNetServer::SendConnlessSixup(CNetChunk *pChunk, SECURITY_TOKEN ResponseToke return -1; unsigned char aBuffer[NET_MAX_PACKETSIZE]; - aBuffer[0] = NET_PACKETFLAG_CONNLESS<<2 | 1; + aBuffer[0] = NET_PACKETFLAG_CONNLESS << 2 | 1; SECURITY_TOKEN Token = GetToken(pChunk->m_Address); - mem_copy(aBuffer+1, &ResponseToken, 4); - mem_copy(aBuffer+5, &Token, 4); - mem_copy(aBuffer+9, pChunk->m_pData, pChunk->m_DataSize); + mem_copy(aBuffer + 1, &ResponseToken, 4); + mem_copy(aBuffer + 5, &Token, 4); + mem_copy(aBuffer + 9, pChunk->m_pData, pChunk->m_DataSize); net_udp_send(m_Socket, &pChunk->m_Address, aBuffer, pChunk->m_DataSize + 9); return 0; @@ -811,7 +802,7 @@ void CNetServer::SetMaxClientsPerIP(int Max) bool CNetServer::SetTimedOut(int ClientID, int OrigID) { - if (m_aSlots[ClientID].m_Connection.State() != NET_CONNSTATE_ERROR) + if(m_aSlots[ClientID].m_Connection.State() != NET_CONNSTATE_ERROR) return false; m_aSlots[ClientID].m_Connection.SetTimedOut(ClientAddr(OrigID), m_aSlots[OrigID].m_Connection.SeqSequence(), m_aSlots[OrigID].m_Connection.AckSequence(), m_aSlots[OrigID].m_Connection.SecurityToken(), m_aSlots[OrigID].m_Connection.ResendBuffer(), m_aSlots[OrigID].m_Connection.m_Sixup); diff --git a/src/engine/shared/packer.cpp b/src/engine/shared/packer.cpp index 41da49c3a..5f809d754 100644 --- a/src/engine/shared/packer.cpp +++ b/src/engine/shared/packer.cpp @@ -2,9 +2,9 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include "packer.h" #include "compression.h" #include "config.h" +#include "packer.h" void CPacker::Reset() { @@ -68,7 +68,7 @@ void CPacker::AddRaw(const void *pData, int Size) if(m_Error) return; - if(m_pCurrent+Size >= m_pEnd) + if(m_pCurrent + Size >= m_pEnd) { m_Error = 1; return; @@ -82,7 +82,6 @@ void CPacker::AddRaw(const void *pData, int Size) } } - void CUnpacker::Reset(const void *pData, int Size) { m_Error = 0; @@ -149,11 +148,11 @@ const char *CUnpacker::GetString(int SanitizeType) m_pCurrent++; // sanitize all strings - if(SanitizeType&SANITIZE) + if(SanitizeType & SANITIZE) str_sanitize(pPtr); - else if(SanitizeType&SANITIZE_CC) + else if(SanitizeType & SANITIZE_CC) str_sanitize_cc(pPtr); - return SanitizeType&SKIP_START_WHITESPACES ? str_utf8_skip_whitespaces(pPtr) : pPtr; + return SanitizeType & SKIP_START_WHITESPACES ? str_utf8_skip_whitespaces(pPtr) : pPtr; } const unsigned char *CUnpacker::GetRaw(int Size) @@ -163,7 +162,7 @@ const unsigned char *CUnpacker::GetRaw(int Size) return 0; // check for nasty sizes - if(Size < 0 || m_pCurrent+Size > m_pEnd) + if(Size < 0 || m_pCurrent + Size > m_pEnd) { m_Error = 1; return 0; diff --git a/src/engine/shared/packer.h b/src/engine/shared/packer.h index 8e29e3075..7d0dbe3e4 100644 --- a/src/engine/shared/packer.h +++ b/src/engine/shared/packer.h @@ -3,27 +3,27 @@ #ifndef ENGINE_SHARED_PACKER_H #define ENGINE_SHARED_PACKER_H - - class CPacker { public: enum { - PACKER_BUFFER_SIZE=1024*2 + PACKER_BUFFER_SIZE = 1024 * 2 }; + private: unsigned char m_aBuffer[PACKER_BUFFER_SIZE]; unsigned char *m_pCurrent; unsigned char *m_pEnd; int m_Error; + public: void Reset(); void AddInt(int i); void AddString(const char *pStr, int Limit); void AddRaw(const void *pData, int Size); - int Size() const { return (int)(m_pCurrent-m_aBuffer); } + int Size() const { return (int)(m_pCurrent - m_aBuffer); } const unsigned char *Data() const { return m_aBuffer; } bool Error() const { return m_Error; } }; @@ -34,12 +34,13 @@ class CUnpacker const unsigned char *m_pCurrent; const unsigned char *m_pEnd; int m_Error; + public: enum { - SANITIZE=1, - SANITIZE_CC=2, - SKIP_START_WHITESPACES=4 + SANITIZE = 1, + SANITIZE_CC = 2, + SKIP_START_WHITESPACES = 4 }; void Reset(const void *pData, int Size); diff --git a/src/engine/shared/protocol.h b/src/engine/shared/protocol.h index 25276ffeb..8df95dfeb 100644 --- a/src/engine/shared/protocol.h +++ b/src/engine/shared/protocol.h @@ -27,40 +27,39 @@ client_entergame and server_client_enter is called. */ - enum { - NETMSG_EX=0, + NETMSG_EX = 0, // the first thing sent by the client // contains the version info for the client - NETMSG_INFO=1, + NETMSG_INFO = 1, // sent by server - NETMSG_MAP_CHANGE, // sent when client should switch map - NETMSG_MAP_DATA, // map transfer, contains a chunk of the map file - NETMSG_CON_READY, // connection is ready, client should send start info - NETMSG_SNAP, // normal snapshot, multiple parts - NETMSG_SNAPEMPTY, // empty snapshot - NETMSG_SNAPSINGLE, // ? - NETMSG_SNAPSMALL, // - NETMSG_INPUTTIMING, // reports how off the input was - NETMSG_RCON_AUTH_STATUS,// result of the authentication - NETMSG_RCON_LINE, // line that should be printed to the remote console + NETMSG_MAP_CHANGE, // sent when client should switch map + NETMSG_MAP_DATA, // map transfer, contains a chunk of the map file + NETMSG_CON_READY, // connection is ready, client should send start info + NETMSG_SNAP, // normal snapshot, multiple parts + NETMSG_SNAPEMPTY, // empty snapshot + NETMSG_SNAPSINGLE, // ? + NETMSG_SNAPSMALL, // + NETMSG_INPUTTIMING, // reports how off the input was + NETMSG_RCON_AUTH_STATUS, // result of the authentication + NETMSG_RCON_LINE, // line that should be printed to the remote console - NETMSG_AUTH_CHALLANGE, // - NETMSG_AUTH_RESULT, // + NETMSG_AUTH_CHALLANGE, // + NETMSG_AUTH_RESULT, // // sent by client - NETMSG_READY, // + NETMSG_READY, // NETMSG_ENTERGAME, - NETMSG_INPUT, // contains the inputdata from the client - NETMSG_RCON_CMD, // - NETMSG_RCON_AUTH, // - NETMSG_REQUEST_MAP_DATA,// + NETMSG_INPUT, // contains the inputdata from the client + NETMSG_RCON_CMD, // + NETMSG_RCON_AUTH, // + NETMSG_REQUEST_MAP_DATA, // - NETMSG_AUTH_START, // - NETMSG_AUTH_RESPONSE, // + NETMSG_AUTH_START, // + NETMSG_AUTH_RESPONSE, // // sent by both NETMSG_PING, @@ -77,27 +76,27 @@ enum // this should be revised enum { - SERVER_TICK_SPEED=50, - SERVER_FLAG_PASSWORD = 1<<0, - SERVER_FLAG_TIMESCORE = 1<<1, + SERVER_TICK_SPEED = 50, + SERVER_FLAG_PASSWORD = 1 << 0, + SERVER_FLAG_TIMESCORE = 1 << 1, SERVERINFO_LEVEL_MIN = 0, SERVERINFO_LEVEL_MAX = 2, - MAX_CLIENTS=64, - VANILLA_MAX_CLIENTS=16, + MAX_CLIENTS = 64, + VANILLA_MAX_CLIENTS = 16, - MAX_INPUT_SIZE=128, - MAX_SNAPSHOT_PACKSIZE=900, + MAX_INPUT_SIZE = 128, + MAX_SNAPSHOT_PACKSIZE = 900, - MAX_NAME_LENGTH=16, - MAX_CLAN_LENGTH=12, + MAX_NAME_LENGTH = 16, + MAX_CLAN_LENGTH = 12, // message packing - MSGFLAG_VITAL=1, - MSGFLAG_FLUSH=2, - MSGFLAG_NORECORD=4, - MSGFLAG_RECORD=8, - MSGFLAG_NOSEND=16 + MSGFLAG_VITAL = 1, + MSGFLAG_FLUSH = 2, + MSGFLAG_NORECORD = 4, + MSGFLAG_RECORD = 8, + MSGFLAG_NOSEND = 16 }; enum diff --git a/src/engine/shared/protocol_ex.cpp b/src/engine/shared/protocol_ex.cpp index 8cfcbe597..5a3fb93bb 100644 --- a/src/engine/shared/protocol_ex.cpp +++ b/src/engine/shared/protocol_ex.cpp @@ -8,9 +8,9 @@ void RegisterUuids(CUuidManager *pManager) { - #define UUID(id, name) pManager->RegisterName(id, name); - #include "protocol_ex_msgs.h" - #undef UUID +#define UUID(id, name) pManager->RegisterName(id, name); +#include "protocol_ex_msgs.h" +#undef UUID } int UnpackMessageID(int *pID, bool *pSys, struct CUuid *pUuid, CUnpacker *pUnpacker, CMsgPacker *pPacker) @@ -51,26 +51,26 @@ int UnpackMessageID(int *pID, bool *pSys, struct CUuid *pUuid, CUnpacker *pUnpac switch(*pID) { case NETMSG_WHATIS: + { + CUuid Uuid2; + int ID2 = g_UuidManager.UnpackUuid(pUnpacker, &Uuid2); + if(ID2 == UUID_INVALID) { - CUuid Uuid2; - int ID2 = g_UuidManager.UnpackUuid(pUnpacker, &Uuid2); - if(ID2 == UUID_INVALID) - { - break; - } - if(ID2 == UUID_UNKNOWN) - { - new (pPacker) CMsgPacker(NETMSG_IDONTKNOW, true); - pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); - } - else - { - new (pPacker) CMsgPacker(NETMSG_ITIS, true); - pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); - pPacker->AddString(g_UuidManager.GetName(ID2), 0); - } - return UNPACKMESSAGE_ANSWER; + break; } + if(ID2 == UUID_UNKNOWN) + { + new(pPacker) CMsgPacker(NETMSG_IDONTKNOW, true); + pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); + } + else + { + new(pPacker) CMsgPacker(NETMSG_ITIS, true); + pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); + pPacker->AddString(g_UuidManager.GetName(ID2), 0); + } + return UNPACKMESSAGE_ANSWER; + } case NETMSG_IDONTKNOW: if(g_Config.m_Debug) { diff --git a/src/engine/shared/protocol_ex.h b/src/engine/shared/protocol_ex.h index bf6e0f95b..25ce6643b 100644 --- a/src/engine/shared/protocol_ex.h +++ b/src/engine/shared/protocol_ex.h @@ -5,24 +5,24 @@ enum { - NETMSG_EX_INVALID=UUID_INVALID, - NETMSG_EX_UNKNOWN=UUID_UNKNOWN, + NETMSG_EX_INVALID = UUID_INVALID, + NETMSG_EX_UNKNOWN = UUID_UNKNOWN, - OFFSET_NETMSG_UUID=OFFSET_UUID, + OFFSET_NETMSG_UUID = OFFSET_UUID, - __NETMSG_UUID_HELPER=OFFSET_NETMSG_UUID-1, - #define UUID(id, name) id, - #include "protocol_ex_msgs.h" - #undef UUID + __NETMSG_UUID_HELPER = OFFSET_NETMSG_UUID - 1, +#define UUID(id, name) id, +#include "protocol_ex_msgs.h" +#undef UUID OFFSET_TEEHISTORIAN_UUID, - UNPACKMESSAGE_ERROR=0, + UNPACKMESSAGE_ERROR = 0, UNPACKMESSAGE_OK, UNPACKMESSAGE_ANSWER, - SERVERCAP_CURVERSION=1, - SERVERCAPFLAG_DDNET=1<<0, - SERVERCAPFLAG_CHATTIMEOUTCODE=1<<1, + SERVERCAP_CURVERSION = 1, + SERVERCAPFLAG_DDNET = 1 << 0, + SERVERCAPFLAG_CHATTIMEOUTCODE = 1 << 1, }; void RegisterUuids(class CUuidManager *pManager); diff --git a/src/engine/shared/protocol_ex_msgs.h b/src/engine/shared/protocol_ex_msgs.h index cbd360ade..b0253c6cb 100644 --- a/src/engine/shared/protocol_ex_msgs.h +++ b/src/engine/shared/protocol_ex_msgs.h @@ -19,11 +19,11 @@ // This file can be included several times. -UUID(NETMSG_WHATIS, "what-is@ddnet.tw") -UUID(NETMSG_ITIS, "it-is@ddnet.tw") -UUID(NETMSG_IDONTKNOW, "i-dont-know@ddnet.tw") +UUID(NETMSG_WHATIS, "what-is@ddnet.tw") +UUID(NETMSG_ITIS, "it-is@ddnet.tw") +UUID(NETMSG_IDONTKNOW, "i-dont-know@ddnet.tw") -UUID(NETMSG_RCONTYPE, "rcon-type@ddnet.tw") -UUID(NETMSG_MAP_DETAILS, "map-details@ddnet.tw") +UUID(NETMSG_RCONTYPE, "rcon-type@ddnet.tw") +UUID(NETMSG_MAP_DETAILS, "map-details@ddnet.tw") UUID(NETMSG_CAPABILITIES, "capabilities@ddnet.tw") -UUID(NETMSG_CLIENTVER, "clientver@ddnet.tw") +UUID(NETMSG_CLIENTVER, "clientver@ddnet.tw") diff --git a/src/engine/shared/ringbuffer.cpp b/src/engine/shared/ringbuffer.cpp index 2c717fb9b..038306f78 100644 --- a/src/engine/shared/ringbuffer.cpp +++ b/src/engine/shared/ringbuffer.cpp @@ -47,7 +47,7 @@ CRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem) void CRingBufferBase::Init(void *pMemory, int Size, int Flags) { mem_zero(pMemory, Size); - m_Size = (Size)/sizeof(CItem)*sizeof(CItem); + m_Size = (Size) / sizeof(CItem) * sizeof(CItem); m_pFirst = (CItem *)pMemory; m_pFirst->m_Free = 1; m_pFirst->m_Size = m_Size; @@ -55,12 +55,11 @@ void CRingBufferBase::Init(void *pMemory, int Size, int Flags) m_pProduce = m_pFirst; m_pConsume = m_pFirst; m_Flags = Flags; - } void *CRingBufferBase::Allocate(int Size) { - int WantedSize = (Size+sizeof(CItem)+sizeof(CItem)-1)/sizeof(CItem)*sizeof(CItem); + int WantedSize = (Size + sizeof(CItem) + sizeof(CItem) - 1) / sizeof(CItem) * sizeof(CItem); CItem *pBlock = 0; // check if we even can fit this block @@ -87,7 +86,7 @@ void *CRingBufferBase::Allocate(int Size) else { // we have no block, check our policy and see what todo - if(m_Flags&FLAG_RECYCLE) + if(m_Flags & FLAG_RECYCLE) { if(!PopFirst()) return 0; @@ -100,7 +99,7 @@ void *CRingBufferBase::Allocate(int Size) // okey, we have our block // split the block if needed - if(pBlock->m_Size > WantedSize+(int)sizeof(CItem)) + if(pBlock->m_Size > WantedSize + (int)sizeof(CItem)) { CItem *pNewItem = (CItem *)((char *)pBlock + WantedSize); pNewItem->m_pPrev = pBlock; @@ -117,13 +116,12 @@ void *CRingBufferBase::Allocate(int Size) m_pLast = pNewItem; } - // set next block m_pProduce = NextBlock(pBlock); // set as used and return the item pointer pBlock->m_Free = 0; - return (void *)(pBlock+1); + return (void *)(pBlock + 1); } int CRingBufferBase::PopFirst() @@ -151,7 +149,6 @@ int CRingBufferBase::PopFirst() return 1; } - void *CRingBufferBase::Prev(void *pCurrent) { CItem *pItem = ((CItem *)pCurrent) - 1; @@ -162,7 +159,7 @@ void *CRingBufferBase::Prev(void *pCurrent) if(pItem == m_pProduce) return 0; if(!pItem->m_Free) - return pItem+1; + return pItem + 1; } } @@ -176,7 +173,7 @@ void *CRingBufferBase::Next(void *pCurrent) if(pItem == m_pProduce) return 0; if(!pItem->m_Free) - return pItem+1; + return pItem + 1; } } @@ -184,10 +181,10 @@ void *CRingBufferBase::First() { if(m_pConsume->m_Free) return 0; - return (void *)(m_pConsume+1); + return (void *)(m_pConsume + 1); } void *CRingBufferBase::Last() { - return Prev(m_pProduce+1); + return Prev(m_pProduce + 1); } diff --git a/src/engine/shared/ringbuffer.h b/src/engine/shared/ringbuffer.h index acce2320b..57cf670bd 100644 --- a/src/engine/shared/ringbuffer.h +++ b/src/engine/shared/ringbuffer.h @@ -28,6 +28,7 @@ class CRingBufferBase CItem *NextBlock(CItem *pItem); CItem *PrevBlock(CItem *pItem); CItem *MergeBack(CItem *pItem); + protected: void *Allocate(int Size); @@ -38,30 +39,32 @@ protected: void Init(void *pMemory, int Size, int Flags); int PopFirst(); + public: enum { // Will start to destroy items to try to fit the next one - FLAG_RECYCLE=1 + FLAG_RECYCLE = 1 }; }; -template +template class TStaticRingBuffer : public CRingBufferBase { unsigned char m_aBuffer[TSIZE]; + public: TStaticRingBuffer() { Init(); } void Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); } - T *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); } + T *Allocate(int Size) { return (T *)CRingBufferBase::Allocate(Size); } int PopFirst() { return CRingBufferBase::PopFirst(); } - T *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); } - T *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); } - T *First() { return (T*)CRingBufferBase::First(); } - T *Last() { return (T*)CRingBufferBase::Last(); } + T *Prev(T *pCurrent) { return (T *)CRingBufferBase::Prev(pCurrent); } + T *Next(T *pCurrent) { return (T *)CRingBufferBase::Next(pCurrent); } + T *First() { return (T *)CRingBufferBase::First(); } + T *Last() { return (T *)CRingBufferBase::Last(); } }; #endif diff --git a/src/engine/shared/serverbrowser.cpp b/src/engine/shared/serverbrowser.cpp index bdf94ba83..e3a594a0d 100644 --- a/src/engine/shared/serverbrowser.cpp +++ b/src/engine/shared/serverbrowser.cpp @@ -1,13 +1,11 @@ -#include #include +#include // gametypes bool IsVanilla(const CServerInfo *pInfo) { - return !str_comp(pInfo->m_aGameType, "DM") - || !str_comp(pInfo->m_aGameType, "TDM") - || !str_comp(pInfo->m_aGameType, "CTF"); + return !str_comp(pInfo->m_aGameType, "DM") || !str_comp(pInfo->m_aGameType, "TDM") || !str_comp(pInfo->m_aGameType, "CTF"); } bool IsCatch(const CServerInfo *pInfo) @@ -17,9 +15,7 @@ bool IsCatch(const CServerInfo *pInfo) bool IsInsta(const CServerInfo *pInfo) { - return str_find_nocase(pInfo->m_aGameType, "idm") - || str_find_nocase(pInfo->m_aGameType, "itdm") - || str_find_nocase(pInfo->m_aGameType, "ictf"); + return str_find_nocase(pInfo->m_aGameType, "idm") || str_find_nocase(pInfo->m_aGameType, "itdm") || str_find_nocase(pInfo->m_aGameType, "ictf"); } bool IsFNG(const CServerInfo *pInfo) @@ -29,9 +25,7 @@ bool IsFNG(const CServerInfo *pInfo) bool IsRace(const CServerInfo *pInfo) { - return str_find_nocase(pInfo->m_aGameType, "race") - || IsFastCap(pInfo) - || IsDDRace(pInfo); + return str_find_nocase(pInfo->m_aGameType, "race") || IsFastCap(pInfo) || IsDDRace(pInfo); } bool IsFastCap(const CServerInfo *pInfo) @@ -41,9 +35,7 @@ bool IsFastCap(const CServerInfo *pInfo) bool IsDDRace(const CServerInfo *pInfo) { - return str_find_nocase(pInfo->m_aGameType, "ddrace") - || str_find_nocase(pInfo->m_aGameType, "mkrace") - || IsDDNet(pInfo); + return str_find_nocase(pInfo->m_aGameType, "ddrace") || str_find_nocase(pInfo->m_aGameType, "mkrace") || IsDDNet(pInfo); } bool IsBlockInfectionZ(const CServerInfo *pInfo) @@ -54,8 +46,7 @@ bool IsBlockInfectionZ(const CServerInfo *pInfo) bool IsBlockWorlds(const CServerInfo *pInfo) { - return (str_comp_nocase_num(pInfo->m_aGameType, "bw ", 4) == 0) - || (str_comp_nocase(pInfo->m_aGameType, "bw") == 0); + return (str_comp_nocase_num(pInfo->m_aGameType, "bw ", 4) == 0) || (str_comp_nocase(pInfo->m_aGameType, "bw") == 0); } bool IsCity(const CServerInfo *pInfo) @@ -65,20 +56,14 @@ bool IsCity(const CServerInfo *pInfo) bool IsDDNet(const CServerInfo *pInfo) { - return str_find_nocase(pInfo->m_aGameType, "ddracenet") - || str_find_nocase(pInfo->m_aGameType, "ddnet") - || IsBlockInfectionZ(pInfo); + return str_find_nocase(pInfo->m_aGameType, "ddracenet") || str_find_nocase(pInfo->m_aGameType, "ddnet") || IsBlockInfectionZ(pInfo); } // other bool Is64Player(const CServerInfo *pInfo) { - return str_find(pInfo->m_aGameType, "64") - || str_find(pInfo->m_aName, "64") - || IsDDNet(pInfo) - || IsBlockInfectionZ(pInfo) - || IsBlockWorlds(pInfo); + return str_find(pInfo->m_aGameType, "64") || str_find(pInfo->m_aName, "64") || IsDDNet(pInfo) || IsBlockInfectionZ(pInfo) || IsBlockWorlds(pInfo); } bool IsPlus(const CServerInfo *pInfo) diff --git a/src/engine/shared/snapshot.cpp b/src/engine/shared/snapshot.cpp index 23124e3f0..cd6650f57 100644 --- a/src/engine/shared/snapshot.cpp +++ b/src/engine/shared/snapshot.cpp @@ -16,9 +16,9 @@ CSnapshotItem *CSnapshot::GetItem(int Index) int CSnapshot::GetItemSize(int Index) { - if(Index == m_NumItems-1) + if(Index == m_NumItems - 1) return (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem); - return (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem); + return (Offsets()[Index + 1] - Offsets()[Index]) - sizeof(CSnapshotItem); } int CSnapshot::GetItemType(int Index) @@ -68,7 +68,7 @@ int CSnapshot::Crc() CSnapshotItem *pItem = GetItem(i); int Size = GetItemSize(i); - for(int b = 0; b < Size/4; b++) + for(int b = 0; b < Size / 4; b++) Crc += pItem->Data()[b]; } return Crc; @@ -82,12 +82,11 @@ void CSnapshot::DebugDump() CSnapshotItem *pItem = GetItem(i); int Size = GetItemSize(i); dbg_msg("snapshot", "\ttype=%d id=%d", pItem->Type(), pItem->ID()); - for(int b = 0; b < Size/4; b++) + for(int b = 0; b < Size / 4; b++) dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, pItem->Data()[b], pItem->Data()[b]); } } - // CSnapshotDelta struct CItemList @@ -110,7 +109,7 @@ static void GenerateHash(CItemList *pHashlist, CSnapshot *pSnapshot) for(int i = 0; i < pSnapshot->NumItems(); i++) { int Key = pSnapshot->GetItem(i)->Key(); - int HashID = ((Key>>12)&0xf0) | (Key&0xf); + int HashID = ((Key >> 12) & 0xf0) | (Key & 0xf); if(pHashlist[HashID].m_Num != 64) { pHashlist[HashID].m_aIndex[pHashlist[HashID].m_Num] = i; @@ -122,11 +121,11 @@ static void GenerateHash(CItemList *pHashlist, CSnapshot *pSnapshot) static int GetItemIndexHashed(int Key, const CItemList *pHashlist) { - int HashID = ((Key>>12)&0xf0) | (Key&0xf); - for(int i = 0; i < pHashlist[HashID].m_Num; i++) - { - if(pHashlist[HashID].m_aKeys[i] == Key) - return pHashlist[HashID].m_aIndex[i]; + int HashID = ((Key >> 12) & 0xf0) | (Key & 0xf); + for(int i = 0; i < pHashlist[HashID].m_Num; i++) + { + if(pHashlist[HashID].m_aKeys[i] == Key) + return pHashlist[HashID].m_aIndex[i]; } return -1; @@ -137,7 +136,7 @@ int CSnapshotDelta::DiffItem(int *pPast, int *pCurrent, int *pOut, int Size) int Needed = 0; while(Size) { - *pOut = *pCurrent-*pPast; + *pOut = *pCurrent - *pPast; Needed |= *pOut; pOut++; pPast++; @@ -152,7 +151,7 @@ void CSnapshotDelta::UndiffItem(int *pPast, int *pDiff, int *pOut, int Size) { while(Size) { - *pOut = *pPast+*pDiff; + *pOut = *pPast + *pDiff; if(*pDiff == 0) m_aSnapshotDataRate[m_SnapshotCurrent] += 1; @@ -160,7 +159,7 @@ void CSnapshotDelta::UndiffItem(int *pPast, int *pDiff, int *pOut, int Size) { unsigned char aBuf[16]; unsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff); - m_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char*)aBuf) * 8; + m_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char *)aBuf) * 8; } pOut++; @@ -251,21 +250,20 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData if(PastIndex != -1) { - int *pItemDataDst = pData+3; + int *pItemDataDst = pData + 3; pPastItem = pFrom->GetItem(PastIndex); if(m_aItemSizes[pCurItem->Type()]) - pItemDataDst = pData+2; + pItemDataDst = pData + 2; - if(DiffItem(pPastItem->Data(), pCurItem->Data(), pItemDataDst, ItemSize/4)) + if(DiffItem(pPastItem->Data(), pCurItem->Data(), pItemDataDst, ItemSize / 4)) { - *pData++ = pCurItem->Type(); *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) - *pData++ = ItemSize/4; - pData += ItemSize/4; + *pData++ = ItemSize / 4; + pData += ItemSize / 4; pDelta->m_NumUpdateItems++; } } @@ -274,11 +272,11 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData *pData++ = pCurItem->Type(); *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) - *pData++ = ItemSize/4; + *pData++ = ItemSize / 4; mem_copy(pData, pCurItem->Data(), ItemSize); SizeCount += ItemSize; - pData += ItemSize/4; + pData += ItemSize / 4; pDelta->m_NumUpdateItems++; Count++; } @@ -306,7 +304,7 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData if(!pDelta->m_NumDeletedItems && !pDelta->m_NumUpdateItems && !pDelta->m_NumTempItems) return 0; - return (int)((char*)pData-(char*)pDstData); + return (int)((char *)pData - (char *)pDstData); } static int RangeCheck(void *pEnd, void *pPtr, int Size) @@ -366,30 +364,32 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData // unpack updated stuff for(int i = 0; i < pDelta->m_NumUpdateItems; i++) { - if(pData+2 > pEnd) + if(pData + 2 > pEnd) return -1; Type = *pData++; ID = *pData++; - if ((unsigned int)Type < sizeof(m_aItemSizes) / sizeof(m_aItemSizes[0]) && m_aItemSizes[Type]) + if((unsigned int)Type < sizeof(m_aItemSizes) / sizeof(m_aItemSizes[0]) && m_aItemSizes[Type]) ItemSize = m_aItemSizes[Type]; else { - if(pData+1 > pEnd) + if(pData + 1 > pEnd) return -2; ItemSize = (*pData++) * 4; } m_SnapshotCurrent = Type; - if(m_SnapshotCurrent < 0 || m_SnapshotCurrent > 0xFFFF) return -3; - if(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) return -3; + if(m_SnapshotCurrent < 0 || m_SnapshotCurrent > 0xFFFF) + return -3; + if(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) + return -3; - Key = (Type<<16)|ID; + Key = (Type << 16) | ID; // create the item if needed pNewData = Builder.GetItemData(Key); if(!pNewData) - pNewData = (int *)Builder.NewItem(Key>>16, Key&0xffff, ItemSize); + pNewData = (int *)Builder.NewItem(Key >> 16, Key & 0xffff, ItemSize); //if(range_check(pEnd, pNewData, ItemSize)) return -4; @@ -397,24 +397,23 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData if(FromIndex != -1) { // we got an update so we need pTo apply the diff - UndiffItem(pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize/4); + UndiffItem(pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize / 4); m_aSnapshotDataUpdates[m_SnapshotCurrent]++; } else // no previous, just copy the pData { mem_copy(pNewData, pData, ItemSize); - m_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize*8; + m_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize * 8; m_aSnapshotDataUpdates[m_SnapshotCurrent]++; } - pData += ItemSize/4; + pData += ItemSize / 4; } // finish up return Builder.Finish(pTo); } - // CSnapshotStorage void CSnapshotStorage::Init() @@ -453,7 +452,7 @@ void CSnapshotStorage::PurgeUntil(int Tick) free(pHolder); // did we come to the end of the list? - if (!pNext) + if(!pNext) break; m_pFirst = pNext; @@ -470,7 +469,7 @@ void CSnapshotStorage::PurgeUntil(int Tick) void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt) { // allocate memory for holder + snapshot_data - int TotalSize = sizeof(CHolder)+DataSize; + int TotalSize = sizeof(CHolder) + DataSize; if(CreateAlt) TotalSize += DataSize; @@ -481,18 +480,17 @@ void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, i pHolder->m_Tick = Tick; pHolder->m_Tagtime = Tagtime; pHolder->m_SnapSize = DataSize; - pHolder->m_pSnap = (CSnapshot*)(pHolder+1); + pHolder->m_pSnap = (CSnapshot *)(pHolder + 1); mem_copy(pHolder->m_pSnap, pData, DataSize); if(CreateAlt) // create alternative if wanted { - pHolder->m_pAltSnap = (CSnapshot*)(((char *)pHolder->m_pSnap) + DataSize); + pHolder->m_pAltSnap = (CSnapshot *)(((char *)pHolder->m_pSnap) + DataSize); mem_copy(pHolder->m_pAltSnap, pData, DataSize); } else pHolder->m_pAltSnap = 0; - // link pHolder->m_pNext = 0; pHolder->m_pPrev = m_pLast; @@ -565,7 +563,7 @@ int CSnapshotBuilder::Finish(void *SpnapData) //dbg_msg("snap", "---------------------------"); // flattern and make the snapshot CSnapshot *pSnap = (CSnapshot *)SpnapData; - int OffsetSize = sizeof(int)*m_NumItems; + int OffsetSize = sizeof(int) * m_NumItems; pSnap->m_DataSize = m_DataSize; pSnap->m_NumItems = m_NumItems; mem_copy(pSnap->Offsets(), m_aOffsets, OffsetSize); @@ -613,7 +611,7 @@ int CSnapshotBuilder::GetExtendedItemTypeIndex(int TypeID) void *CSnapshotBuilder::NewItem(int Type, int ID, int Size) { if(m_DataSize + sizeof(CSnapshotItem) + Size >= CSnapshot::MAX_SIZE || - m_NumItems+1 >= MAX_ITEMS) + m_NumItems + 1 >= MAX_ITEMS) { dbg_assert(m_DataSize < CSnapshot::MAX_SIZE, "too much data"); dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); @@ -636,11 +634,12 @@ void *CSnapshotBuilder::NewItem(int Type, int ID, int Size) else Type *= -1; - if(Type < 0) return pObj; + if(Type < 0) + return pObj; } mem_zero(pObj, sizeof(CSnapshotItem) + Size); - pObj->m_TypeAndID = (Type<<16)|ID; + pObj->m_TypeAndID = (Type << 16) | ID; m_aOffsets[m_NumItems] = m_DataSize; m_DataSize += sizeof(CSnapshotItem) + Size; m_NumItems++; diff --git a/src/engine/shared/snapshot.h b/src/engine/shared/snapshot.h index 38c23f06a..474eeacda 100644 --- a/src/engine/shared/snapshot.h +++ b/src/engine/shared/snapshot.h @@ -12,32 +12,35 @@ class CSnapshotItem public: int m_TypeAndID; - int *Data() { return (int *)(this+1); } - int Type() { return m_TypeAndID>>16; } - int ID() { return m_TypeAndID&0xffff; } + int *Data() { return (int *)(this + 1); } + int Type() { return m_TypeAndID >> 16; } + int ID() { return m_TypeAndID & 0xffff; } int Key() { return m_TypeAndID; } }; - class CSnapshot { friend class CSnapshotBuilder; int m_DataSize; int m_NumItems; - int *Offsets() const { return (int *)(this+1); } - char *DataStart() const { return (char*)(Offsets()+m_NumItems); } + int *Offsets() const { return (int *)(this + 1); } + char *DataStart() const { return (char *)(Offsets() + m_NumItems); } public: enum { - OFFSET_UUID_TYPE=0x4000, - MAX_TYPE=0x7fff, - MAX_PARTS=64, - MAX_SIZE=MAX_PARTS*1024 + OFFSET_UUID_TYPE = 0x4000, + MAX_TYPE = 0x7fff, + MAX_PARTS = 64, + MAX_SIZE = MAX_PARTS * 1024 }; - void Clear() { m_DataSize = 0; m_NumItems = 0; } + void Clear() + { + m_DataSize = 0; + m_NumItems = 0; + } int NumItems() const { return m_NumItems; } CSnapshotItem *GetItem(int Index); int GetItemSize(int Index); @@ -49,7 +52,6 @@ public: static void RemoveExtraInfo(unsigned char *pData); }; - // CSnapshotDelta class CSnapshotDelta @@ -86,7 +88,6 @@ public: int UnpackDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData, int DataSize); }; - // CSnapshotStorage class CSnapshotStorage @@ -106,7 +107,6 @@ public: CSnapshot *m_pAltSnap; }; - CHolder *m_pFirst; CHolder *m_pLast; @@ -154,5 +154,4 @@ public: int Finish(void *Snapdata); }; - #endif // ENGINE_SNAPSHOT_H diff --git a/src/engine/shared/storage.cpp b/src/engine/shared/storage.cpp index 980a9ee42..2f909d5d0 100644 --- a/src/engine/shared/storage.cpp +++ b/src/engine/shared/storage.cpp @@ -1,9 +1,9 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "linereader.h" #include #include #include -#include "linereader.h" class CStorage : public IStorage { @@ -86,7 +86,7 @@ public: if(Pos < MAX_PATH_LENGTH) { char aBuffer[MAX_PATH_LENGTH]; - str_copy(aBuffer, pArgv0, Pos+1); + str_copy(aBuffer, pArgv0, Pos + 1); str_append(aBuffer, "/storage.cfg", sizeof(aBuffer)); File = io_open(aBuffer, IOFLAG_READ); } @@ -170,19 +170,19 @@ public: return; } - #if defined(DATA_DIR) +#if defined(DATA_DIR) // 2) use compiled-in data-dir if present if(fs_is_dir(DATA_DIR "/mapres")) { str_copy(m_aDatadir, DATA_DIR, sizeof(m_aDatadir)); - #if defined(BINARY_DIR) +#if defined(BINARY_DIR) str_copy(m_aBinarydir, BINARY_DIR, sizeof(m_aBinarydir)); - #else +#else str_copy(m_aBinarydir, DATA_DIR "/..", sizeof(m_aBinarydir)); - #endif +#endif return; } - #endif +#endif // 3) check for usable path in argv[0] { @@ -194,7 +194,7 @@ public: if(Pos < MAX_PATH_LENGTH) { char aBuf[MAX_PATH_LENGTH]; - str_copy(m_aBinarydir, pArgv0, Pos+1); + str_copy(m_aBinarydir, pArgv0, Pos + 1); str_format(aBuf, sizeof(aBuf), "%s/data/mapres", m_aBinarydir); if(fs_is_dir(aBuf)) { @@ -206,7 +206,7 @@ public: } } - #if defined(CONF_FAMILY_UNIX) +#if defined(CONF_FAMILY_UNIX) // 4) check for all default locations { const char *aDirs[] = { @@ -216,12 +216,11 @@ public: "/usr/local/share/games/ddnet", "/usr/pkg/share/ddnet", "/usr/pkg/share/games/ddnet", - "/opt/ddnet" - }; + "/opt/ddnet"}; const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); int i; - for (i = 0; i < DirsCount; i++) + for(i = 0; i < DirsCount; i++) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%s/data/mapres", aDirs[i]); @@ -233,13 +232,12 @@ public: } } } - #endif +#endif // no data-dir found dbg_msg("storage", "warning no data directory found"); } - virtual void ListDirectoryInfo(int Type, const char *pPath, FS_LISTDIR_INFO_CALLBACK pfnCallback, void *pUser) { char aBuffer[MAX_PATH_LENGTH]; @@ -303,14 +301,14 @@ public: pFilename = pFilename + 10; // just start from skins/ } if(pFilename[0] == '/' || pFilename[0] == '\\' || str_find(pFilename, "../") != NULL || str_find(pFilename, "..\\") != NULL - #ifdef CONF_FAMILY_WINDOWS +#ifdef CONF_FAMILY_WINDOWS || (pFilename[0] && pFilename[1] == ':') - #endif +#endif ) { // don't escape base directory } - else if(Flags&IOFLAG_WRITE) + else if(Flags & IOFLAG_WRITE) { return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags); } diff --git a/src/engine/shared/teehistorian_ex.cpp b/src/engine/shared/teehistorian_ex.cpp index 3c771f7d6..558e84575 100644 --- a/src/engine/shared/teehistorian_ex.cpp +++ b/src/engine/shared/teehistorian_ex.cpp @@ -4,7 +4,7 @@ void RegisterTeehistorianUuids(CUuidManager *pManager) { - #define UUID(id, name) pManager->RegisterName(id, name); - #include "teehistorian_ex_chunks.h" - #undef UUID +#define UUID(id, name) pManager->RegisterName(id, name); +#include "teehistorian_ex_chunks.h" +#undef UUID } diff --git a/src/engine/shared/teehistorian_ex.h b/src/engine/shared/teehistorian_ex.h index 017a24387..cdc3b8c81 100644 --- a/src/engine/shared/teehistorian_ex.h +++ b/src/engine/shared/teehistorian_ex.h @@ -4,10 +4,10 @@ enum { - __TEEHISTORIAN_UUID_HELPER=OFFSET_TEEHISTORIAN_UUID-1, - #define UUID(id, name) id, - #include "teehistorian_ex_chunks.h" - #undef UUID + __TEEHISTORIAN_UUID_HELPER = OFFSET_TEEHISTORIAN_UUID - 1, +#define UUID(id, name) id, +#include "teehistorian_ex_chunks.h" +#undef UUID OFFSET_GAME_UUID }; diff --git a/src/engine/shared/teehistorian_ex_chunks.h b/src/engine/shared/teehistorian_ex_chunks.h index d4187a31a..be365474b 100644 --- a/src/engine/shared/teehistorian_ex_chunks.h +++ b/src/engine/shared/teehistorian_ex_chunks.h @@ -1,13 +1,13 @@ // This file can be included several times. -UUID(TEEHISTORIAN_TEST, "teehistorian-test@ddnet.tw") +UUID(TEEHISTORIAN_TEST, "teehistorian-test@ddnet.tw") UUID(TEEHISTORIAN_DDNETVER_OLD, "teehistorian-ddnetver-old@ddnet.tw") -UUID(TEEHISTORIAN_DDNETVER, "teehistorian-ddnetver@ddnet.tw") -UUID(TEEHISTORIAN_AUTH_INIT, "teehistorian-auth-init@ddnet.tw") -UUID(TEEHISTORIAN_AUTH_LOGIN, "teehistorian-auth-login@ddnet.tw") -UUID(TEEHISTORIAN_AUTH_LOGOUT, "teehistorian-auth-logout@ddnet.tw") -UUID(TEEHISTORIAN_JOINVER6, "teehistorian-joinver6@ddnet.tw") -UUID(TEEHISTORIAN_JOINVER7, "teehistorian-joinver7@ddnet.tw") +UUID(TEEHISTORIAN_DDNETVER, "teehistorian-ddnetver@ddnet.tw") +UUID(TEEHISTORIAN_AUTH_INIT, "teehistorian-auth-init@ddnet.tw") +UUID(TEEHISTORIAN_AUTH_LOGIN, "teehistorian-auth-login@ddnet.tw") +UUID(TEEHISTORIAN_AUTH_LOGOUT, "teehistorian-auth-logout@ddnet.tw") +UUID(TEEHISTORIAN_JOINVER6, "teehistorian-joinver6@ddnet.tw") +UUID(TEEHISTORIAN_JOINVER7, "teehistorian-joinver7@ddnet.tw") UUID(TEEHISTORIAN_SAVE_SUCCESS, "teehistorian-save-success@ddnet.tw") UUID(TEEHISTORIAN_SAVE_FAILURE, "teehistorian-save-failure@ddnet.tw") UUID(TEEHISTORIAN_LOAD_SUCCESS, "teehistorian-load-success@ddnet.tw") diff --git a/src/engine/shared/uuid_manager.cpp b/src/engine/shared/uuid_manager.cpp index b4a69eb89..34f3c2166 100644 --- a/src/engine/shared/uuid_manager.cpp +++ b/src/engine/shared/uuid_manager.cpp @@ -5,11 +5,9 @@ #include -static const CUuid TEEWORLDS_NAMESPACE = {{ - // "e05ddaaa-c4e6-4cfb-b642-5d48e80c0029" +static const CUuid TEEWORLDS_NAMESPACE = {{// "e05ddaaa-c4e6-4cfb-b642-5d48e80c0029" 0xe0, 0x5d, 0xda, 0xaa, 0xc4, 0xe6, 0x4c, 0xfb, - 0xb6, 0x42, 0x5d, 0x48, 0xe8, 0x0c, 0x00, 0x29 -}}; + 0xb6, 0x42, 0x5d, 0x48, 0xe8, 0x0c, 0x00, 0x29}}; CUuid RandomUuid() { @@ -63,12 +61,12 @@ void ParseUuid(CUuid *pUuid, char *pBuffer) &p[8], &p[9], &p[10], &p[11], &p[12], &p[13], &p[14], &p[15]); } -bool CUuid::operator==(const CUuid& Other) +bool CUuid::operator==(const CUuid &Other) { return mem_comp(this, &Other, sizeof(*this)) == 0; } -bool CUuid::operator!=(const CUuid& Other) +bool CUuid::operator!=(const CUuid &Other) { return !(*this == Other); } diff --git a/src/engine/shared/uuid_manager.h b/src/engine/shared/uuid_manager.h index 0e45cbda0..3d7560f82 100644 --- a/src/engine/shared/uuid_manager.h +++ b/src/engine/shared/uuid_manager.h @@ -7,10 +7,10 @@ enum { UUID_MAXSTRSIZE = 37, // 12345678-0123-5678-0123-567890123456 - UUID_INVALID=-2, - UUID_UNKNOWN=-1, + UUID_INVALID = -2, + UUID_UNKNOWN = -1, - OFFSET_UUID=1<<16, + OFFSET_UUID = 1 << 16, }; struct CUuid @@ -39,6 +39,7 @@ class CUnpacker; class CUuidManager { array m_aNames; + public: void RegisterName(int ID, const char *pName); CUuid GetUuid(int ID) const; diff --git a/src/engine/shared/video.cpp b/src/engine/shared/video.cpp index ae8508946..6df3241aa 100644 --- a/src/engine/shared/video.cpp +++ b/src/engine/shared/video.cpp @@ -4,7 +4,7 @@ #include "video.h" -IVideo* IVideo::ms_pCurrentVideo = 0; +IVideo *IVideo::ms_pCurrentVideo = 0; int64 IVideo::ms_Time = 0; float IVideo::ms_LocalTime = 0; diff --git a/src/engine/shared/video.h b/src/engine/shared/video.h index ae7055420..bb5169ac5 100644 --- a/src/engine/shared/video.h +++ b/src/engine/shared/video.h @@ -6,7 +6,7 @@ class IVideo { public: - virtual ~IVideo() {}; + virtual ~IVideo(){}; virtual void Start() = 0; virtual void Stop() = 0; @@ -21,8 +21,7 @@ public: virtual bool AudioFrameRendered() = 0; virtual void NextAudioFrameTimeline() = 0; - - static IVideo* Current() { return ms_pCurrentVideo; } + static IVideo *Current() { return ms_pCurrentVideo; } static int64 Time() { return ms_Time; } static float LocalTime() { return ms_LocalTime; } @@ -30,12 +29,11 @@ public: static void SetFPS(int FPS) { ms_TickTime = time_freq() / FPS; } protected: - static IVideo* ms_pCurrentVideo; + static IVideo *ms_pCurrentVideo; static int64 ms_Time; static int64 ms_LocalStartTime; static float ms_LocalTime; static int64 ms_TickTime; }; - #endif diff --git a/src/engine/sound.h b/src/engine/sound.h index db69a9fc8..253d48773 100644 --- a/src/engine/sound.h +++ b/src/engine/sound.h @@ -11,10 +11,10 @@ class ISound : public IInterface public: enum { - FLAG_LOOP=1<<0, - FLAG_POS=1<<1, - FLAG_NO_PANNING=1<<2, - FLAG_ALL=FLAG_LOOP|FLAG_POS|FLAG_NO_PANNING, + FLAG_LOOP = 1 << 0, + FLAG_POS = 1 << 1, + FLAG_NO_PANNING = 1 << 2, + FLAG_ALL = FLAG_LOOP | FLAG_POS | FLAG_NO_PANNING, }; enum @@ -39,19 +39,20 @@ public: friend class ISound; int m_Id; int m_Age; + public: - CVoiceHandle() - : m_Id(-1), m_Age(-1) - {} + CVoiceHandle() : + m_Id(-1), m_Age(-1) + { + } bool IsValid() const { return (Id() >= 0) && (Age() >= 0); } int Id() const { return m_Id; } int Age() const { return m_Age; } - bool operator ==(const CVoiceHandle &Other) const { return m_Id == Other.m_Id && m_Age == Other.m_Age; } + bool operator==(const CVoiceHandle &Other) const { return m_Id == Other.m_Id && m_Age == Other.m_Age; } }; - virtual bool IsSoundEnabled() = 0; virtual int LoadWV(const char *pFilename) = 0; @@ -89,7 +90,6 @@ protected: } }; - class IEngineSound : public ISound { MACRO_INTERFACE("enginesound", 0) diff --git a/src/engine/storage.h b/src/engine/storage.h index 1d6b4eb16..80d9c43d5 100644 --- a/src/engine/storage.h +++ b/src/engine/storage.h @@ -31,7 +31,7 @@ public: virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) = 0; virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) = 0; virtual bool RemoveFile(const char *pFilename, int Type) = 0; - virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0; + virtual bool RenameFile(const char *pOldFilename, const char *pNewFilename, int Type) = 0; virtual bool CreateFolder(const char *pFoldername, int Type) = 0; virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0; @@ -45,5 +45,4 @@ public: extern IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments); extern IStorage *CreateLocalStorage(); - #endif diff --git a/src/engine/textrender.h b/src/engine/textrender.h index c114570ce..a81d3c522 100644 --- a/src/engine/textrender.h +++ b/src/engine/textrender.h @@ -10,21 +10,21 @@ enum { - TEXTFLAG_RENDER=1, - TEXTFLAG_ALLOW_NEWLINE=2, - TEXTFLAG_STOP_AT_END=4 + TEXTFLAG_RENDER = 1, + TEXTFLAG_ALLOW_NEWLINE = 2, + TEXTFLAG_STOP_AT_END = 4 }; enum ETextRenderFlags { - TEXT_RENDER_FLAG_NO_X_BEARING = 1<<0, - TEXT_RENDER_FLAG_NO_Y_BEARING = 1<<1, - TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH = 1<<2, - TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT = 1<<3, - TEXT_RENDER_FLAG_KERNING = 1<<4, - TEXT_RENDER_FLAG_NO_OVERSIZE = 1<<5, - TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING = 1<<6, - TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE = 1<<7, + TEXT_RENDER_FLAG_NO_X_BEARING = 1 << 0, + TEXT_RENDER_FLAG_NO_Y_BEARING = 1 << 1, + TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH = 1 << 2, + TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT = 1 << 3, + TEXT_RENDER_FLAG_KERNING = 1 << 4, + TEXT_RENDER_FLAG_NO_OVERSIZE = 1 << 5, + TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING = 1 << 6, + TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE = 1 << 7, }; enum diff --git a/src/game/bezier.cpp b/src/game/bezier.cpp index 32d9a48a0..a48fce6cf 100644 --- a/src/game/bezier.cpp +++ b/src/game/bezier.cpp @@ -8,16 +8,11 @@ CCubicBezier CCubicBezier::With(float Start, float StartDerivative, float EndDer // f(t) = (1-t)³ a + 3(1-t)²t b + 3(1-t)t² c + t³ d float CCubicBezier::Evaluate(float t) const { - return (1 - t) * (1 - t) * (1 - t) * a - + 3 * (1 - t) * (1 - t) * t * b - + 3 * (1 - t) * t * t * c - + t * t * t * d; + return (1 - t) * (1 - t) * (1 - t) * a + 3 * (1 - t) * (1 - t) * t * b + 3 * (1 - t) * t * t * c + t * t * t * d; } // f(t) = 3(1-t)²(b-a) + 6(1-t)t(c-b) + 3t²(d-c) float CCubicBezier::Derivative(float t) const { - return 3 * (1 - t) * (1 - t) * (b - a) - + 6 * (1 - t) * t * (c - b) - + 3 * t * t * (d - c); + return 3 * (1 - t) * (1 - t) * (b - a) + 6 * (1 - t) * t * (c - b) + 3 * t * t * (d - c); } diff --git a/src/game/bezier.h b/src/game/bezier.h index e6a9f6e7c..845c3e7ee 100644 --- a/src/game/bezier.h +++ b/src/game/bezier.h @@ -19,6 +19,7 @@ class CCubicBezier this->c = c; this->d = d; } + public: CCubicBezier() {} float Evaluate(float t) const; diff --git a/src/game/client/animstate.cpp b/src/game/client/animstate.cpp index dd3a23a72..8ce2f7ab2 100644 --- a/src/game/client/animstate.cpp +++ b/src/game/client/animstate.cpp @@ -2,8 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include #include +#include #include "animstate.h" @@ -28,18 +28,18 @@ static void AnimSeqEval(CAnimSequence *pSeq, float Time, CAnimKeyframe *pFrame) float Blend = 0.0f; // TODO: make this smarter.. binary search - for (int i = 1; i < pSeq->m_NumFrames; i++) + for(int i = 1; i < pSeq->m_NumFrames; i++) { - if (pSeq->m_aFrames[i-1].m_Time <= Time && pSeq->m_aFrames[i].m_Time >= Time) + if(pSeq->m_aFrames[i - 1].m_Time <= Time && pSeq->m_aFrames[i].m_Time >= Time) { - pFrame1 = &pSeq->m_aFrames[i-1]; + pFrame1 = &pSeq->m_aFrames[i - 1]; pFrame2 = &pSeq->m_aFrames[i]; Blend = (Time - pFrame1->m_Time) / (pFrame2->m_Time - pFrame1->m_Time); break; } } - if (pFrame1 && pFrame2) + if(pFrame1 && pFrame2) { pFrame->m_Time = Time; pFrame->m_X = mix(pFrame1->m_X, pFrame2->m_X, Blend); @@ -51,9 +51,9 @@ static void AnimSeqEval(CAnimSequence *pSeq, float Time, CAnimKeyframe *pFrame) static void AnimAddKeyframe(CAnimKeyframe *pSeq, CAnimKeyframe *pAdded, float Amount) { - pSeq->m_X += pAdded->m_X*Amount; - pSeq->m_Y += pAdded->m_Y*Amount; - pSeq->m_Angle += pAdded->m_Angle*Amount; + pSeq->m_X += pAdded->m_X * Amount; + pSeq->m_Y += pAdded->m_Y * Amount; + pSeq->m_Angle += pAdded->m_Angle * Amount; } static void AnimAdd(CAnimState *pState, CAnimState *pAdded, float Amount) @@ -64,7 +64,6 @@ static void AnimAdd(CAnimState *pState, CAnimState *pAdded, float Amount) AnimAddKeyframe(pState->GetAttach(), pAdded->GetAttach(), Amount); } - void CAnimState::Set(CAnimation *pAnim, float Time) { AnimSeqEval(&pAnim->m_Body, Time, &m_Body); diff --git a/src/game/client/component.h b/src/game/client/component.h index 15e20f536..89ad7dd42 100644 --- a/src/game/client/component.h +++ b/src/game/client/component.h @@ -4,11 +4,11 @@ #define GAME_CLIENT_COMPONENT_H #if defined(CONF_VIDEORECORDER) - #include +#include #endif -#include #include "gameclient.h" +#include class CComponent { @@ -33,31 +33,39 @@ protected: class CLayers *Layers() const { return m_pClient->Layers(); } class CCollision *Collision() const { return m_pClient->Collision(); } #if defined(CONF_AUTOUPDATE) - class IUpdater *Updater() const { return m_pClient->Updater(); } + class IUpdater *Updater() const + { + return m_pClient->Updater(); + } #endif #if defined(CONF_VIDEORECORDER) - int64 time() const { return IVideo::Current() ? IVideo::Time() : time_get(); } + int64 time() const + { + return IVideo::Current() ? IVideo::Time() : time_get(); + } float LocalTime() const { return IVideo::Current() ? IVideo::LocalTime() : Client()->LocalTime(); } #else - int64 time() const { return time_get(); } + int64 time() const + { + return time_get(); + } float LocalTime() const { return Client()->LocalTime(); } #endif - public: virtual ~CComponent() {} class CGameClient *GameClient() const { return m_pClient; } class IClient *Client() const { return m_pClient->Client(); } - virtual void OnStateChange(int NewState, int OldState) {}; - virtual void OnConsoleInit() {}; - virtual void OnInit() {}; - virtual void OnReset() {}; + virtual void OnStateChange(int NewState, int OldState){}; + virtual void OnConsoleInit(){}; + virtual void OnInit(){}; + virtual void OnReset(){}; virtual void OnWindowResize() {} - virtual void OnRender() {}; - virtual void OnRelease() {}; - virtual void OnMapLoad() {}; + virtual void OnRender(){}; + virtual void OnRelease(){}; + virtual void OnMapLoad(){}; virtual void OnMessage(int Msg, void *pRawMsg) {} virtual bool OnMouseMove(float x, float y) { return false; } virtual bool OnInput(IInput::CEvent e) { return false; } diff --git a/src/game/client/components/background.cpp b/src/game/client/components/background.cpp index 7604af63c..6b28d8297 100644 --- a/src/game/client/components/background.cpp +++ b/src/game/client/components/background.cpp @@ -1,17 +1,17 @@ #include -#include -#include #include +#include +#include #include -#include #include +#include #include "background.h" -CBackground::CBackground(int MapType, bool OnlineOnly) - : CMapLayers(MapType, OnlineOnly) +CBackground::CBackground(int MapType, bool OnlineOnly) : + CMapLayers(MapType, OnlineOnly) { m_pLayers = new CLayers; m_pBackgroundLayers = m_pLayers; @@ -45,7 +45,7 @@ void CBackground::OnInit() void CBackground::LoadBackground() { - if(time_get()-m_LastLoad < 10*time_freq()) + if(time_get() - m_LastLoad < 10 * time_freq()) return; if(m_Loaded && m_pMap == m_pBackgroundMap) @@ -112,6 +112,6 @@ void CBackground::OnRender() if(g_Config.m_ClOverlayEntities != 100) return; - + CMapLayers::OnRender(); } diff --git a/src/game/client/components/binds.cpp b/src/game/client/components/binds.cpp index 0dbcdb642..621f38da5 100644 --- a/src/game/client/components/binds.cpp +++ b/src/game/client/components/binds.cpp @@ -1,8 +1,8 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "binds.h" #include #include -#include "binds.h" bool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event) { @@ -14,8 +14,8 @@ bool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event) bool ret = false; for(int Mod = 0; Mod < MODIFIER_COMBINATION_COUNT; Mod++) { - if(Mask&(1 << Mod) && m_pBinds->m_aapKeyBindings[Mod][Event.m_Key]) - m_pBinds->GetConsole()->ExecuteLineStroked(Event.m_Flags&IInput::FLAG_PRESS, m_pBinds->m_aapKeyBindings[Mod][Event.m_Key]); + if(Mask & (1 << Mod) && m_pBinds->m_aapKeyBindings[Mod][Event.m_Key]) + m_pBinds->GetConsole()->ExecuteLineStroked(Event.m_Flags & IInput::FLAG_PRESS, m_pBinds->m_aapKeyBindings[Mod][Event.m_Key]); ret = true; } return ret; @@ -135,9 +135,9 @@ bool CBinds::OnInput(IInput::CEvent e) { if(m_aapKeyBindings[Mod][e.m_Key] && (Mask == Mod)) { - if(e.m_Flags&IInput::FLAG_PRESS) + if(e.m_Flags & IInput::FLAG_PRESS) Console()->ExecuteLineStroked(1, m_aapKeyBindings[Mod][e.m_Key]); - if(e.m_Flags&IInput::FLAG_RELEASE) + if(e.m_Flags & IInput::FLAG_RELEASE) Console()->ExecuteLineStroked(0, m_aapKeyBindings[Mod][e.m_Key]); ret = true; } @@ -145,9 +145,9 @@ bool CBinds::OnInput(IInput::CEvent e) if(m_aapKeyBindings[0][e.m_Key] && (!ret || m_aapKeyBindings[0][e.m_Key][0] == '+')) // always trigger +xxx binds despite any modifier { - if(e.m_Flags&IInput::FLAG_PRESS) + if(e.m_Flags & IInput::FLAG_PRESS) Console()->ExecuteLineStroked(1, m_aapKeyBindings[0][e.m_Key]); - if(e.m_Flags&IInput::FLAG_RELEASE) + if(e.m_Flags & IInput::FLAG_RELEASE) Console()->ExecuteLineStroked(0, m_aapKeyBindings[0][e.m_Key]); ret = true; } @@ -290,14 +290,14 @@ void CBinds::ConDumpBinds(IConsole::IResult *pResult, void *pUserData) int Modifier; int id = pBinds->GetBindSlot(pKeyName, &Modifier); - if (!id) + if(!id) { str_format(aBuf, sizeof(aBuf), "key '%s' not found", pKeyName); pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); } else { - if (!pBinds->m_aapKeyBindings[Modifier][id]) + if(!pBinds->m_aapKeyBindings[Modifier][id]) str_format(aBuf, sizeof(aBuf), "%s (%d) is not bound", pKeyName, id); else str_format(aBuf, sizeof(aBuf), "%s (%d) = %s", pKeyName, id, pBinds->m_aapKeyBindings[Modifier][id]); @@ -351,7 +351,7 @@ int CBinds::GetKeyID(const char *pKeyName) // check for numeric if(pKeyName[0] == '&') { - int i = str_toint(pKeyName+1); + int i = str_toint(pKeyName + 1); if(i > 0 && i < KEY_LAST) return i; // numeric } @@ -374,16 +374,16 @@ int CBinds::GetBindSlot(const char *pBindString, int *Mod) const char *pKey = str_next_token(pBindString, "+", aMod, sizeof(aMod)); while(aMod[0] && *(pKey)) { - if (!str_comp(aMod, "shift")) + if(!str_comp(aMod, "shift")) *Mod |= (1 << MODIFIER_SHIFT); - else if (!str_comp(aMod, "ctrl")) + else if(!str_comp(aMod, "ctrl")) *Mod |= (1 << MODIFIER_CTRL); - else if (!str_comp(aMod, "alt")) + else if(!str_comp(aMod, "alt")) *Mod |= (1 << MODIFIER_ALT); else return 0; - if (str_find(pKey + 1, "+")) + if(str_find(pKey + 1, "+")) pKey = str_next_token(pKey + 1, "+", aMod, sizeof(aMod)); else break; @@ -411,10 +411,9 @@ const char *CBinds::GetKeyBindModifiersName(int Modifier) { static char aModifier[256]; aModifier[0] = '\0'; - for (int k = 1; k < MODIFIER_COUNT; k++) + for(int k = 1; k < MODIFIER_COUNT; k++) { - - if (Modifier & (1 << k)) + if(Modifier & (1 << k)) { str_append(aModifier, GetModifierName(k), sizeof(aModifier)); str_append(aModifier, "+", sizeof(aModifier)); @@ -428,7 +427,7 @@ void CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData) CBinds *pSelf = (CBinds *)pUserData; char aBuffer[256]; - char *pEnd = aBuffer+sizeof(aBuffer); + char *pEnd = aBuffer + sizeof(aBuffer); pConfig->WriteLine("unbindall"); for(int i = 0; i < MODIFIER_COMBINATION_COUNT; i++) { diff --git a/src/game/client/components/binds.h b/src/game/client/components/binds.h index 3cf37896a..4eaff794e 100644 --- a/src/game/client/components/binds.h +++ b/src/game/client/components/binds.h @@ -2,8 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_BINDS_H #define GAME_CLIENT_COMPONENTS_BINDS_H -#include #include +#include class CBinds : public CComponent { @@ -28,7 +28,8 @@ public: virtual bool OnInput(IInput::CEvent Event); }; - enum { + enum + { MODIFIER_NONE = 0, MODIFIER_SHIFT, MODIFIER_CTRL, diff --git a/src/game/client/components/broadcast.cpp b/src/game/client/components/broadcast.cpp index 7e923f03c..c7258a1c9 100644 --- a/src/game/client/components/broadcast.cpp +++ b/src/game/client/components/broadcast.cpp @@ -1,10 +1,10 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include #include -#include #include +#include #include @@ -23,13 +23,13 @@ void CBroadcast::OnRender() if(m_pClient->m_pScoreboard->Active() || m_pClient->m_pMotd->IsActive() || !g_Config.m_ClShowBroadcasts) return; - Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); + Graphics()->MapScreen(0, 0, 300 * Graphics()->ScreenAspect(), 300); if(Client()->GameTick(g_Config.m_ClDummy) < m_BroadcastTick) { CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, m_BroadcastRenderOffset, 40.0f, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); - Cursor.m_LineWidth = 300*Graphics()->ScreenAspect()-m_BroadcastRenderOffset; + TextRender()->SetCursor(&Cursor, m_BroadcastRenderOffset, 40.0f, 12.0f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = 300 * Graphics()->ScreenAspect() - m_BroadcastRenderOffset; TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); } } @@ -42,21 +42,21 @@ void CBroadcast::OnMessage(int MsgType, void *pRawMsg) str_copy(m_aBroadcastText, pMsg->m_pMessage, sizeof(m_aBroadcastText)); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, 0, 0, 12.0f, TEXTFLAG_STOP_AT_END); - Cursor.m_LineWidth = 300*Graphics()->ScreenAspect(); + Cursor.m_LineWidth = 300 * Graphics()->ScreenAspect(); TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); - m_BroadcastRenderOffset = 150*Graphics()->ScreenAspect()-Cursor.m_X/2; - m_BroadcastTick = Client()->GameTick(g_Config.m_ClDummy)+Client()->GameTickSpeed()*10; - if (g_Config.m_ClPrintBroadcasts) + m_BroadcastRenderOffset = 150 * Graphics()->ScreenAspect() - Cursor.m_X / 2; + m_BroadcastTick = Client()->GameTick(g_Config.m_ClDummy) + Client()->GameTickSpeed() * 10; + if(g_Config.m_ClPrintBroadcasts) { char aBuf[1024]; int i, ii; - for (i = 0, ii = 0; i < str_length(m_aBroadcastText); i++) + for(i = 0, ii = 0; i < str_length(m_aBroadcastText); i++) { - if (m_aBroadcastText[i] == '\n') + if(m_aBroadcastText[i] == '\n') { aBuf[ii] = '\0'; ii = 0; - if (aBuf[0]) + if(aBuf[0]) m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "broadcast", aBuf, true); } else @@ -66,7 +66,7 @@ void CBroadcast::OnMessage(int MsgType, void *pRawMsg) } } aBuf[ii] = '\0'; - if (aBuf[0]) + if(aBuf[0]) m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "broadcast", aBuf, true); } } diff --git a/src/game/client/components/camera.cpp b/src/game/client/components/camera.cpp index 2cab23422..45e23a83b 100644 --- a/src/game/client/components/camera.cpp +++ b/src/game/client/components/camera.cpp @@ -38,7 +38,7 @@ void CCamera::ScaleZoom(float Factor) float CCamera::MaxZoomLevel() { - return (Graphics()->IsTileBufferingEnabled()? 60 : 30); + return (Graphics()->IsTileBufferingEnabled() ? 60 : 30); } float CCamera::MinZoomLevel() @@ -131,9 +131,9 @@ void CCamera::OnRender() { float DeadZone = g_Config.m_ClDyncam ? g_Config.m_ClDyncamDeadzone : g_Config.m_ClMouseDeadzone; float FollowFactor = (g_Config.m_ClDyncam ? g_Config.m_ClDyncamFollowFactor : g_Config.m_ClMouseFollowfactor) / 100.0f; - float OffsetAmount = maximum(l-DeadZone, 0.0f) * FollowFactor; + float OffsetAmount = maximum(l - DeadZone, 0.0f) * FollowFactor; - CameraOffset = normalize(m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy])*OffsetAmount; + CameraOffset = normalize(m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy]) * OffsetAmount; } if(m_pClient->m_Snap.m_SpecInfo.m_Active) diff --git a/src/game/client/components/camera.h b/src/game/client/components/camera.h index 927567b7d..4305c6cd5 100644 --- a/src/game/client/components/camera.h +++ b/src/game/client/components/camera.h @@ -32,6 +32,7 @@ class CCamera : public CComponent float MinZoomLevel(); float MaxZoomLevel(); + public: vec2 m_Center; bool m_ZoomSet; diff --git a/src/game/client/components/console.cpp b/src/game/client/components/console.cpp index 999f0860d..245e3d851 100644 --- a/src/game/client/components/console.cpp +++ b/src/game/client/components/console.cpp @@ -352,8 +352,8 @@ void CGameConsole::CInstance::PrintLine(const char *pLine, bool Highlighted) pEntry->m_aText[Len] = 0; } -CGameConsole::CGameConsole() - : m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE) +CGameConsole::CGameConsole() : + m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE) { m_ConsoleType = CONSOLETYPE_LOCAL; m_ConsoleState = CONSOLE_CLOSED; diff --git a/src/game/client/components/console.h b/src/game/client/components/console.h index d33722f0c..e088181c6 100644 --- a/src/game/client/components/console.h +++ b/src/game/client/components/console.h @@ -25,8 +25,8 @@ class CGameConsole : public CComponent bool m_Highlighted; char m_aText[1]; }; - TStaticRingBuffer m_Backlog; - TStaticRingBuffer m_History; + TStaticRingBuffer m_Backlog; + TStaticRingBuffer m_History; char *m_pHistoryEntry; CLineInput m_Input; @@ -99,7 +99,7 @@ class CGameConsole : public CComponent public: enum { - CONSOLETYPE_LOCAL=0, + CONSOLETYPE_LOCAL = 0, CONSOLETYPE_REMOTE, }; diff --git a/src/game/client/components/controls.cpp b/src/game/client/components/controls.cpp index 49a995b23..307085ecf 100644 --- a/src/game/client/components/controls.cpp +++ b/src/game/client/components/controls.cpp @@ -6,22 +6,28 @@ #include -#include #include +#include -#include -#include #include #include #include #include +#include +#include #include "controls.h" -enum { LEFT_JOYSTICK_X = 0, LEFT_JOYSTICK_Y = 1, - RIGHT_JOYSTICK_X = 2, RIGHT_JOYSTICK_Y = 3, - SECOND_RIGHT_JOYSTICK_X = 20, SECOND_RIGHT_JOYSTICK_Y = 21, - NUM_JOYSTICK_AXES = 22 }; +enum +{ + LEFT_JOYSTICK_X = 0, + LEFT_JOYSTICK_Y = 1, + RIGHT_JOYSTICK_X = 2, + RIGHT_JOYSTICK_Y = 3, + SECOND_RIGHT_JOYSTICK_X = 20, + SECOND_RIGHT_JOYSTICK_Y = 21, + NUM_JOYSTICK_AXES = 22 +}; CControls::CControls() { @@ -29,11 +35,11 @@ CControls::CControls() m_LastDummy = 0; m_OtherFire = 0; - if (g_Config.m_InpJoystick) + if(g_Config.m_InpJoystick) { SDL_Init(SDL_INIT_JOYSTICK); m_Joystick = SDL_JoystickOpen(0); - if( m_Joystick && SDL_JoystickNumAxes(m_Joystick) < NUM_JOYSTICK_AXES ) + if(m_Joystick && SDL_JoystickNumAxes(m_Joystick) < NUM_JOYSTICK_AXES) { SDL_JoystickClose(m_Joystick); m_Joystick = NULL; @@ -45,7 +51,7 @@ CControls::CControls() m_UsingGamepad = false; #if defined(CONF_FAMILY_UNIX) - if( getenv("OUYA") ) + if(getenv("OUYA")) m_UsingGamepad = true; #endif } @@ -65,7 +71,7 @@ void CControls::OnReset() m_JoystickFirePressed = false; m_JoystickRunPressed = false; m_JoystickTapTime = 0; - for( int i = 0; i < NUM_WEAPONS; i++ ) + for(int i = 0; i < NUM_WEAPONS; i++) m_AmmoCount[i] = 0; m_OldMouseX = m_OldMouseY = 0.0f; } @@ -75,7 +81,7 @@ void CControls::ResetInput(int Dummy) m_LastData[Dummy].m_Direction = 0; //m_LastData[Dummy].m_Hook = 0; // simulate releasing the fire button - if((m_LastData[Dummy].m_Fire&1) != 0) + if((m_LastData[Dummy].m_Fire & 1) != 0) m_LastData[Dummy].m_Fire++; m_LastData[Dummy].m_Fire &= INPUT_STATE_MASK; m_LastData[Dummy].m_Jump = 0; @@ -92,9 +98,9 @@ void CControls::OnRelease() void CControls::OnPlayerDeath() { - if (g_Config.m_ClResetWantedWeaponOnDeath) + if(g_Config.m_ClResetWantedWeaponOnDeath) m_LastData[g_Config.m_ClDummy].m_WantedWeapon = m_InputData[g_Config.m_ClDummy].m_WantedWeapon = 0; - for( int i = 0; i < NUM_WEAPONS; i++ ) + for(int i = 0; i < NUM_WEAPONS; i++) m_AmmoCount[i] = 0; m_JoystickTapTime = 0; // Do not launch hook on first tap } @@ -113,7 +119,7 @@ static void ConKeyInputState(IConsole::IResult *pResult, void *pUserData) if(pState->m_pControls->GameClient()->m_GameInfo.m_BugDDRaceInput && pState->m_pControls->GameClient()->m_Snap.m_SpecInfo.m_Active) return; - if (g_Config.m_ClDummy) + if(g_Config.m_ClDummy) *pState->m_pVariable2 = pResult->GetInteger(0); else *pState->m_pVariable1 = pResult->GetInteger(0); @@ -127,12 +133,12 @@ static void ConKeyInputCounter(IConsole::IResult *pResult, void *pUserData) return; int *v; - if (g_Config.m_ClDummy) + if(g_Config.m_ClDummy) v = pState->m_pVariable2; else v = pState->m_pVariable1; - if(((*v)&1) != pResult->GetInteger(0)) + if(((*v) & 1) != pResult->GetInteger(0)) (*v)++; *v &= INPUT_STATE_MASK; } @@ -150,7 +156,7 @@ static void ConKeyInputSet(IConsole::IResult *pResult, void *pUserData) CInputSet *pSet = (CInputSet *)pUserData; if(pResult->GetInteger(0)) { - if (g_Config.m_ClDummy) + if(g_Config.m_ClDummy) *pSet->m_pVariable2 = pSet->m_Value; else *pSet->m_pVariable1 = pSet->m_Value; @@ -167,22 +173,64 @@ static void ConKeyInputNextPrevWeapon(IConsole::IResult *pResult, void *pUserDat void CControls::OnConsoleInit() { // game commands - { static CInputState s_State = {this, &m_InputDirectionLeft[0], &m_InputDirectionLeft[1]}; Console()->Register("+left", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move left"); } - { static CInputState s_State = {this, &m_InputDirectionRight[0], &m_InputDirectionRight[1]}; Console()->Register("+right", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move right"); } - { static CInputState s_State = {this, &m_InputData[0].m_Jump, &m_InputData[1].m_Jump}; Console()->Register("+jump", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Jump"); } - { static CInputState s_State = {this, &m_InputData[0].m_Hook, &m_InputData[1].m_Hook}; Console()->Register("+hook", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Hook"); } - { static CInputState s_State = {this, &m_InputData[0].m_Fire, &m_InputData[1].m_Fire}; Console()->Register("+fire", "", CFGFLAG_CLIENT, ConKeyInputCounter, (void *)&s_State, "Fire"); } - { static CInputState s_State = {this, &m_ShowHookColl[0], &m_ShowHookColl[1]}; Console()->Register("+showhookcoll", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Show Hook Collision"); } - { static CInputState s_State = {this, &m_ResetDummy[0], &m_ResetDummy[1]}; Console()->Register("+resetdummy", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Reset Dummy"); } + { + static CInputState s_State = {this, &m_InputDirectionLeft[0], &m_InputDirectionLeft[1]}; + Console()->Register("+left", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move left"); + } + { + static CInputState s_State = {this, &m_InputDirectionRight[0], &m_InputDirectionRight[1]}; + Console()->Register("+right", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move right"); + } + { + static CInputState s_State = {this, &m_InputData[0].m_Jump, &m_InputData[1].m_Jump}; + Console()->Register("+jump", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Jump"); + } + { + static CInputState s_State = {this, &m_InputData[0].m_Hook, &m_InputData[1].m_Hook}; + Console()->Register("+hook", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Hook"); + } + { + static CInputState s_State = {this, &m_InputData[0].m_Fire, &m_InputData[1].m_Fire}; + Console()->Register("+fire", "", CFGFLAG_CLIENT, ConKeyInputCounter, (void *)&s_State, "Fire"); + } + { + static CInputState s_State = {this, &m_ShowHookColl[0], &m_ShowHookColl[1]}; + Console()->Register("+showhookcoll", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Show Hook Collision"); + } + { + static CInputState s_State = {this, &m_ResetDummy[0], &m_ResetDummy[1]}; + Console()->Register("+resetdummy", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Reset Dummy"); + } - { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 1}; Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); } - { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 2}; Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); } - { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 3}; Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); } - { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 4}; Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); } - { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 5}; Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to laser"); } + { + static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 1}; + Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); + } + { + static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 2}; + Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); + } + { + static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 3}; + Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); + } + { + static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 4}; + Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); + } + { + static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 5}; + Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to laser"); + } - { static CInputSet s_Set = {this, &m_InputData[0].m_NextWeapon, &m_InputData[1].m_NextWeapon, 0}; Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); } - { static CInputSet s_Set = {this, &m_InputData[0].m_PrevWeapon, &m_InputData[1].m_PrevWeapon, 0}; Console()->Register("+prevweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to previous weapon"); } + { + static CInputSet s_Set = {this, &m_InputData[0].m_NextWeapon, &m_InputData[1].m_NextWeapon, 0}; + Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); + } + { + static CInputSet s_Set = {this, &m_InputData[0].m_PrevWeapon, &m_InputData[1].m_PrevWeapon, 0}; + Console()->Register("+prevweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to previous weapon"); + } } void CControls::OnMessage(int Msg, void *pRawMsg) @@ -191,9 +239,9 @@ void CControls::OnMessage(int Msg, void *pRawMsg) { CNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)pRawMsg; if(g_Config.m_ClAutoswitchWeapons) - m_InputData[g_Config.m_ClDummy].m_WantedWeapon = pMsg->m_Weapon+1; + m_InputData[g_Config.m_ClDummy].m_WantedWeapon = pMsg->m_Weapon + 1; // We don't really know ammo count, until we'll switch to that weapon, but any non-zero count will suffice here - m_AmmoCount[pMsg->m_Weapon%NUM_WEAPONS] = 10; + m_AmmoCount[pMsg->m_Weapon % NUM_WEAPONS] = 10; } } @@ -223,7 +271,7 @@ int CControls::SnapInput(int *pData) if(m_InputData[g_Config.m_ClDummy].m_PlayerFlags != PLAYERFLAG_PLAYING) m_JoystickTapTime = 0; // Do not launch hook on first tap - if (m_pClient->m_pControls->m_ShowHookColl[g_Config.m_ClDummy]) + if(m_pClient->m_pControls->m_ShowHookColl[g_Config.m_ClDummy]) m_InputData[g_Config.m_ClDummy].m_PlayerFlags |= PLAYERFLAG_AIM; if(m_LastData[g_Config.m_ClDummy].m_PlayerFlags != m_InputData[g_Config.m_ClDummy].m_PlayerFlags) @@ -232,7 +280,7 @@ int CControls::SnapInput(int *pData) m_LastData[g_Config.m_ClDummy].m_PlayerFlags = m_InputData[g_Config.m_ClDummy].m_PlayerFlags; // we freeze the input if chat or menu is activated - if(!(m_InputData[g_Config.m_ClDummy].m_PlayerFlags&PLAYERFLAG_PLAYING)) + if(!(m_InputData[g_Config.m_ClDummy].m_PlayerFlags & PLAYERFLAG_PLAYING)) { if(!GameClient()->m_GameInfo.m_BugDDRaceInput) ResetInput(g_Config.m_ClDummy); @@ -284,7 +332,8 @@ int CControls::SnapInput(int *pData) m_InputData[!g_Config.m_ClDummy] = *pDummyInput; } - if(g_Config.m_ClDummyControl){ + if(g_Config.m_ClDummyControl) + { CNetObj_PlayerInput *pDummyInput = &m_pClient->m_DummyInput; pDummyInput->m_Jump = g_Config.m_ClDummyJump; pDummyInput->m_Fire = g_Config.m_ClDummyFire; @@ -311,31 +360,37 @@ int CControls::SnapInput(int *pData) float t = Client()->LocalTime(); mem_zero(&m_InputData[g_Config.m_ClDummy], sizeof(m_InputData[0])); - m_InputData[g_Config.m_ClDummy].m_Direction = ((int)t/2)&1; + m_InputData[g_Config.m_ClDummy].m_Direction = ((int)t / 2) & 1; m_InputData[g_Config.m_ClDummy].m_Jump = ((int)t); - m_InputData[g_Config.m_ClDummy].m_Fire = ((int)(t*10)); - m_InputData[g_Config.m_ClDummy].m_Hook = ((int)(t*2))&1; - m_InputData[g_Config.m_ClDummy].m_WantedWeapon = ((int)t)%NUM_WEAPONS; - m_InputData[g_Config.m_ClDummy].m_TargetX = (int)(sinf(t*3)*100.0f); - m_InputData[g_Config.m_ClDummy].m_TargetY = (int)(cosf(t*3)*100.0f); + m_InputData[g_Config.m_ClDummy].m_Fire = ((int)(t * 10)); + m_InputData[g_Config.m_ClDummy].m_Hook = ((int)(t * 2)) & 1; + m_InputData[g_Config.m_ClDummy].m_WantedWeapon = ((int)t) % NUM_WEAPONS; + m_InputData[g_Config.m_ClDummy].m_TargetX = (int)(sinf(t * 3) * 100.0f); + m_InputData[g_Config.m_ClDummy].m_TargetY = (int)(cosf(t * 3) * 100.0f); } #endif // check if we need to send input - if(m_InputData[g_Config.m_ClDummy].m_Direction != m_LastData[g_Config.m_ClDummy].m_Direction) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_Jump != m_LastData[g_Config.m_ClDummy].m_Jump) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_Fire != m_LastData[g_Config.m_ClDummy].m_Fire) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_Hook != m_LastData[g_Config.m_ClDummy].m_Hook) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_WantedWeapon != m_LastData[g_Config.m_ClDummy].m_WantedWeapon) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_NextWeapon != m_LastData[g_Config.m_ClDummy].m_NextWeapon) Send = true; - else if(m_InputData[g_Config.m_ClDummy].m_PrevWeapon != m_LastData[g_Config.m_ClDummy].m_PrevWeapon) Send = true; - - // send at at least 10hz - if(time_get() > LastSendTime + time_freq()/25) + if(m_InputData[g_Config.m_ClDummy].m_Direction != m_LastData[g_Config.m_ClDummy].m_Direction) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Jump != m_LastData[g_Config.m_ClDummy].m_Jump) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Fire != m_LastData[g_Config.m_ClDummy].m_Fire) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Hook != m_LastData[g_Config.m_ClDummy].m_Hook) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_WantedWeapon != m_LastData[g_Config.m_ClDummy].m_WantedWeapon) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_NextWeapon != m_LastData[g_Config.m_ClDummy].m_NextWeapon) + Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_PrevWeapon != m_LastData[g_Config.m_ClDummy].m_PrevWeapon) Send = true; - if(m_pClient->m_Snap.m_pLocalCharacter && m_pClient->m_Snap.m_pLocalCharacter->m_Weapon == WEAPON_NINJA - && (m_InputData[g_Config.m_ClDummy].m_Direction || m_InputData[g_Config.m_ClDummy].m_Jump || m_InputData[g_Config.m_ClDummy].m_Hook)) + // send at at least 10hz + if(time_get() > LastSendTime + time_freq() / 25) + Send = true; + + if(m_pClient->m_Snap.m_pLocalCharacter && m_pClient->m_Snap.m_pLocalCharacter->m_Weapon == WEAPON_NINJA && (m_InputData[g_Config.m_ClDummy].m_Direction || m_InputData[g_Config.m_ClDummy].m_Jump || m_InputData[g_Config.m_ClDummy].m_Hook)) Send = true; } @@ -352,7 +407,8 @@ int CControls::SnapInput(int *pData) void CControls::OnRender() { - enum { + enum + { JOYSTICK_RUN_DISTANCE = 65536 / 8, GAMEPAD_DEAD_ZONE = 65536 / 8, }; @@ -360,7 +416,7 @@ void CControls::OnRender() int64 CurTime = time_get(); bool FireWasPressed = false; - if( m_Joystick ) + if(m_Joystick) { // Get input from left joystick int RunX = SDL_JoystickGetAxis(m_Joystick, LEFT_JOYSTICK_X); @@ -375,11 +431,11 @@ void CControls::OnRender() int HookY = SDL_JoystickGetAxis(m_Joystick, RIGHT_JOYSTICK_Y); bool HookPressed = (HookX != 0 || HookY != 0); - if( m_JoystickRunPressed != RunPressed ) + if(m_JoystickRunPressed != RunPressed) { - if( RunPressed ) + if(RunPressed) { - if( m_JoystickTapTime + time_freq() > CurTime ) // Tap in less than 1 second to jump + if(m_JoystickTapTime + time_freq() > CurTime) // Tap in less than 1 second to jump m_InputData[g_Config.m_ClDummy].m_Jump = 1; } else @@ -389,20 +445,20 @@ void CControls::OnRender() m_JoystickRunPressed = RunPressed; - if( RunPressed ) + if(RunPressed) { m_InputDirectionLeft[g_Config.m_ClDummy] = (RunX < -JOYSTICK_RUN_DISTANCE); m_InputDirectionRight[g_Config.m_ClDummy] = (RunX > JOYSTICK_RUN_DISTANCE); } // Move 500ms in the same direction, to prevent speed bump when tapping - if( !RunPressed && m_JoystickTapTime + time_freq() / 2 > CurTime ) + if(!RunPressed && m_JoystickTapTime + time_freq() / 2 > CurTime) { m_InputDirectionLeft[g_Config.m_ClDummy] = 0; m_InputDirectionRight[g_Config.m_ClDummy] = 0; } - if( HookPressed ) + if(HookPressed) { m_MousePos[g_Config.m_ClDummy] = vec2(HookX / 30, HookY / 30); ClampMousePos(); @@ -413,20 +469,20 @@ void CControls::OnRender() m_InputData[g_Config.m_ClDummy].m_Hook = 0; } - if( AimPressed ) + if(AimPressed) { m_MousePos[g_Config.m_ClDummy] = vec2(AimX / 30, AimY / 30); ClampMousePos(); } - if( AimPressed != m_JoystickFirePressed ) + if(AimPressed != m_JoystickFirePressed) { // Fire when releasing joystick - if( !AimPressed ) + if(!AimPressed) { - m_InputData[g_Config.m_ClDummy].m_Fire ++; - if( (bool)(m_InputData[g_Config.m_ClDummy].m_Fire % 2) != AimPressed ) - m_InputData[g_Config.m_ClDummy].m_Fire ++; + m_InputData[g_Config.m_ClDummy].m_Fire++; + if((bool)(m_InputData[g_Config.m_ClDummy].m_Fire % 2) != AimPressed) + m_InputData[g_Config.m_ClDummy].m_Fire++; FireWasPressed = true; } } @@ -434,12 +490,12 @@ void CControls::OnRender() m_JoystickFirePressed = AimPressed; } - if( m_Gamepad ) + if(m_Gamepad) { // Get input from left joystick int RunX = SDL_JoystickGetAxis(m_Gamepad, LEFT_JOYSTICK_X); int RunY = SDL_JoystickGetAxis(m_Gamepad, LEFT_JOYSTICK_Y); - if( m_UsingGamepad ) + if(m_UsingGamepad) { m_InputDirectionLeft[g_Config.m_ClDummy] = (RunX < -GAMEPAD_DEAD_ZONE); m_InputDirectionRight[g_Config.m_ClDummy] = (RunX > GAMEPAD_DEAD_ZONE); @@ -448,13 +504,13 @@ void CControls::OnRender() // Get input from right joystick int AimX = SDL_JoystickGetAxis(m_Gamepad, RIGHT_JOYSTICK_X); int AimY = SDL_JoystickGetAxis(m_Gamepad, RIGHT_JOYSTICK_Y); - if( abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE ) + if(abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE) { m_MousePos[g_Config.m_ClDummy] = vec2(AimX / 30, AimY / 30); ClampMousePos(); } - if( !m_UsingGamepad && (abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE || abs(RunX) > GAMEPAD_DEAD_ZONE || abs(RunY) > GAMEPAD_DEAD_ZONE) ) + if(!m_UsingGamepad && (abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE || abs(RunX) > GAMEPAD_DEAD_ZONE || abs(RunY) > GAMEPAD_DEAD_ZONE)) { m_UsingGamepad = true; } @@ -463,23 +519,23 @@ void CControls::OnRender() if(g_Config.m_ClAutoswitchWeaponsOutOfAmmo && !GameClient()->m_GameInfo.m_UnlimitedAmmo && m_pClient->m_Snap.m_pLocalCharacter) { // Keep track of ammo count, we know weapon ammo only when we switch to that weapon, this is tracked on server and protocol does not track that - m_AmmoCount[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS] = m_pClient->m_Snap.m_pLocalCharacter->m_AmmoCount; + m_AmmoCount[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon % NUM_WEAPONS] = m_pClient->m_Snap.m_pLocalCharacter->m_AmmoCount; // Autoswitch weapon if we're out of ammo - if( (m_InputData[g_Config.m_ClDummy].m_Fire % 2 != 0 || FireWasPressed) && + if((m_InputData[g_Config.m_ClDummy].m_Fire % 2 != 0 || FireWasPressed) && m_pClient->m_Snap.m_pLocalCharacter->m_AmmoCount == 0 && m_pClient->m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_HAMMER && - m_pClient->m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_NINJA ) + m_pClient->m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_NINJA) { int w; - for( w = WEAPON_LASER; w > WEAPON_GUN; w-- ) + for(w = WEAPON_LASER; w > WEAPON_GUN; w--) { - if( w == m_pClient->m_Snap.m_pLocalCharacter->m_Weapon ) + if(w == m_pClient->m_Snap.m_pLocalCharacter->m_Weapon) continue; - if( m_AmmoCount[w] > 0 ) + if(m_AmmoCount[w] > 0) break; } - if( w != m_pClient->m_Snap.m_pLocalCharacter->m_Weapon ) - m_InputData[g_Config.m_ClDummy].m_WantedWeapon = w+1; + if(w != m_pClient->m_Snap.m_pLocalCharacter->m_Weapon) + m_InputData[g_Config.m_ClDummy].m_WantedWeapon = w + 1; } } @@ -494,7 +550,7 @@ void CControls::OnRender() bool CControls::OnMouseMove(float x, float y) { - if((m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + if((m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) return false; if(g_Config.m_ClDyncam && g_Config.m_ClDyncamMousesens) @@ -512,8 +568,8 @@ void CControls::ClampMousePos() { if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID < 0) { - m_MousePos[g_Config.m_ClDummy].x = clamp(m_MousePos[g_Config.m_ClDummy].x, 200.0f, Collision()->GetWidth()*32-200.0f); - m_MousePos[g_Config.m_ClDummy].y = clamp(m_MousePos[g_Config.m_ClDummy].y, 200.0f, Collision()->GetHeight()*32-200.0f); + m_MousePos[g_Config.m_ClDummy].x = clamp(m_MousePos[g_Config.m_ClDummy].x, 200.0f, Collision()->GetWidth() * 32 - 200.0f); + m_MousePos[g_Config.m_ClDummy].y = clamp(m_MousePos[g_Config.m_ClDummy].y, 200.0f, Collision()->GetHeight() * 32 - 200.0f); } else { @@ -521,13 +577,13 @@ void CControls::ClampMousePos() float FollowFactor = (g_Config.m_ClDyncam ? g_Config.m_ClDyncamFollowFactor : g_Config.m_ClMouseFollowfactor) / 100.0f; float DeadZone = g_Config.m_ClDyncam ? g_Config.m_ClDyncamDeadzone : g_Config.m_ClMouseDeadzone; float MaxDistance = g_Config.m_ClDyncam ? g_Config.m_ClDyncamMaxDistance : g_Config.m_ClMouseMaxDistance; - float MouseMax = minimum((FollowFactor != 0 ? CameraMaxDistance/FollowFactor + DeadZone : MaxDistance), MaxDistance); + float MouseMax = minimum((FollowFactor != 0 ? CameraMaxDistance / FollowFactor + DeadZone : MaxDistance), MaxDistance); float MinDistance = g_Config.m_ClDyncam ? g_Config.m_ClDyncamMinDistance : g_Config.m_ClMouseMinDistance; float MouseMin = MinDistance; if(length(m_MousePos[g_Config.m_ClDummy]) < MouseMin) - m_MousePos[g_Config.m_ClDummy] = normalize(m_MousePos[g_Config.m_ClDummy])*MouseMin; + m_MousePos[g_Config.m_ClDummy] = normalize(m_MousePos[g_Config.m_ClDummy]) * MouseMin; if(length(m_MousePos[g_Config.m_ClDummy]) > MouseMax) - m_MousePos[g_Config.m_ClDummy] = normalize(m_MousePos[g_Config.m_ClDummy])*MouseMax; + m_MousePos[g_Config.m_ClDummy] = normalize(m_MousePos[g_Config.m_ClDummy]) * MouseMax; } } diff --git a/src/game/client/components/controls.h b/src/game/client/components/controls.h index f65bc5468..e012b1d72 100644 --- a/src/game/client/components/controls.h +++ b/src/game/client/components/controls.h @@ -3,8 +3,8 @@ #ifndef GAME_CLIENT_COMPONENTS_CONTROLS_H #define GAME_CLIENT_COMPONENTS_CONTROLS_H #include -#include #include +#include #include class CControls : public CComponent diff --git a/src/game/client/components/countryflags.cpp b/src/game/client/components/countryflags.cpp index 68183bab4..7776f94b3 100644 --- a/src/game/client/components/countryflags.cpp +++ b/src/game/client/components/countryflags.cpp @@ -5,14 +5,13 @@ #include #include -#include -#include #include #include +#include +#include #include "countryflags.h" - void CCountryFlags::LoadCountryflagsIndexfile() { IOHANDLE File = Storage()->OpenFile("countryflags/index.txt", IOFLAG_READ, IStorage::TYPE_ALL); @@ -47,7 +46,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() continue; } - int CountryCode = str_toint(pReplacement+3); + int CountryCode = str_toint(pReplacement + 3); if(CountryCode < CODE_LB || CountryCode > CODE_UB) { char aBuf[128]; @@ -107,7 +106,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() else mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT)); for(int i = 0; i < m_aCountryFlags.size(); ++i) - m_CodeIndexLUT[maximum(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i; + m_CodeIndexLUT[maximum(0, (m_aCountryFlags[i].m_CountryCode - CODE_LB) % CODE_RANGE)] = i; } void CCountryFlags::OnInit() @@ -132,12 +131,12 @@ int CCountryFlags::Num() const const CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const { - return GetByIndex(m_CodeIndexLUT[maximum(0, (CountryCode-CODE_LB)%CODE_RANGE)]); + return GetByIndex(m_CodeIndexLUT[maximum(0, (CountryCode - CODE_LB) % CODE_RANGE)]); } const CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index) const { - return &m_aCountryFlags[maximum(0, Index%m_aCountryFlags.size())]; + return &m_aCountryFlags[maximum(0, Index % m_aCountryFlags.size())]; } void CCountryFlags::Render(int CountryCode, const ColorRGBA *pColor, float x, float y, float w, float h) @@ -155,7 +154,7 @@ void CCountryFlags::Render(int CountryCode, const ColorRGBA *pColor, float x, fl else { CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = w; TextRender()->TextEx(&Cursor, pFlag->m_aCountryCodeString, -1); } diff --git a/src/game/client/components/countryflags.h b/src/game/client/components/countryflags.h index 60dbab7ef..7e1e9e85d 100644 --- a/src/game/client/components/countryflags.h +++ b/src/game/client/components/countryflags.h @@ -2,8 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H #define GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H -#include #include +#include #include class CCountryFlags : public CComponent @@ -28,9 +28,9 @@ public: private: enum { - CODE_LB=-1, - CODE_UB=999, - CODE_RANGE=CODE_UB-CODE_LB+1, + CODE_LB = -1, + CODE_UB = 999, + CODE_RANGE = CODE_UB - CODE_LB + 1, }; sorted_array m_aCountryFlags; int m_CodeIndexLUT[CODE_RANGE]; diff --git a/src/game/client/components/damageind.cpp b/src/game/client/components/damageind.cpp index c5eab703a..033178268 100644 --- a/src/game/client/components/damageind.cpp +++ b/src/game/client/components/damageind.cpp @@ -2,13 +2,13 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include #include -#include #include +#include -#include // get_angle -#include -#include #include "damageind.h" +#include +#include +#include // get_angle CDamageInd::CDamageInd() { @@ -40,8 +40,8 @@ void CDamageInd::Create(vec2 Pos, vec2 Dir) { i->m_Pos = Pos; i->m_StartTime = LocalTime(); - i->m_Dir = Dir*-1; - i->m_StartAngle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi; + i->m_Dir = Dir * -1; + i->m_StartAngle = (((float)rand() / (float)RAND_MAX) - 1.0f) * 2.0f * pi; } } @@ -55,14 +55,14 @@ void CDamageInd::OnRender() { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) - m_aItems[i].m_StartTime += LocalTime()-s_LastLocalTime; + m_aItems[i].m_StartTime += LocalTime() - s_LastLocalTime; else - m_aItems[i].m_StartTime += (LocalTime()-s_LastLocalTime)*(1.0f-pInfo->m_Speed); + m_aItems[i].m_StartTime += (LocalTime() - s_LastLocalTime) * (1.0f - pInfo->m_Speed); } else { - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) - m_aItems[i].m_StartTime += LocalTime()-s_LastLocalTime; + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) + m_aItems[i].m_StartTime += LocalTime() - s_LastLocalTime; } float Life = 0.75f - (LocalTime() - m_aItems[i].m_StartTime); @@ -70,8 +70,8 @@ void CDamageInd::OnRender() DestroyI(&m_aItems[i]); else { - vec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((Life-0.60f)/0.15f, 0.0f, 1.0f)); - Graphics()->SetColor(1.0f,1.0f,1.0f, Life/0.1f); + vec2 Pos = mix(m_aItems[i].m_Pos + m_aItems[i].m_Dir * 75.0f, m_aItems[i].m_Pos, clamp((Life - 0.60f) / 0.15f, 0.0f, 1.0f)); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, Life / 0.1f); Graphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + Life * 2.0f); Graphics()->RenderQuadContainerAsSprite(m_DmgIndQuadContainerIndex, 0, Pos.x, Pos.y); i++; diff --git a/src/game/client/components/damageind.h b/src/game/client/components/damageind.h index e33a5d64e..5d0b8eeee 100644 --- a/src/game/client/components/damageind.h +++ b/src/game/client/components/damageind.h @@ -18,7 +18,7 @@ class CDamageInd : public CComponent enum { - MAX_ITEMS=64, + MAX_ITEMS = 64, }; CItem m_aItems[MAX_ITEMS]; @@ -28,6 +28,7 @@ class CDamageInd : public CComponent void DestroyI(CItem *i); int m_DmgIndQuadContainerIndex; + public: CDamageInd(); diff --git a/src/game/client/components/debughud.cpp b/src/game/client/components/debughud.cpp index c9ab0d3ad..2516e52d6 100644 --- a/src/game/client/components/debughud.cpp +++ b/src/game/client/components/debughud.cpp @@ -1,16 +1,16 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include #include -#include #include +#include #include -#include #include +#include #include //#include "controls.h" @@ -22,60 +22,60 @@ void CDebugHud::RenderNetCorrections() if(!g_Config.m_Debug || g_Config.m_DbgGraphs || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter) return; - float Width = 300*Graphics()->ScreenAspect(); + float Width = 300 * Graphics()->ScreenAspect(); Graphics()->MapScreen(0, 0, Width, 300); /*float speed = distance(vec2(netobjects.local_prev_character->x, netobjects.local_prev_character->y), vec2(netobjects.local_character->x, netobjects.local_character->y));*/ - float Velspeed = length(vec2(m_pClient->m_Snap.m_pLocalCharacter->m_VelX/256.0f, m_pClient->m_Snap.m_pLocalCharacter->m_VelY/256.0f))*50; + float Velspeed = length(vec2(m_pClient->m_Snap.m_pLocalCharacter->m_VelX / 256.0f, m_pClient->m_Snap.m_pLocalCharacter->m_VelY / 256.0f)) * 50; float Ramp = VelocityRamp(Velspeed, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); const char *paStrings[] = {"velspeed:", "velspeed*ramp:", "ramp:", "checkpoint:", "Pos", " x:", " y:", "angle:", "netobj corrections", " num:", " on:"}; - const int Num = sizeof(paStrings)/sizeof(char *); + const int Num = sizeof(paStrings) / sizeof(char *); const float LineHeight = 6.0f; const float Fontsize = 5.0f; - float x = Width-100.0f, y = 50.0f; + float x = Width - 100.0f, y = 50.0f; for(int i = 0; i < Num; ++i) - TextRender()->Text(0, x, y+i*LineHeight, Fontsize, paStrings[i], -1.0f); + TextRender()->Text(0, x, y + i * LineHeight, Fontsize, paStrings[i], -1.0f); - x = Width-10.0f; + x = Width - 10.0f; char aBuf[128]; - str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32); + str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed / 32); float w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; - str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32*Ramp); + str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed / 32 * Ramp); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%.2f", Ramp); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_GameWorld.GetCharacterByID(m_pClient->m_Snap.m_LocalClientID)->m_TeleCheckpoint); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); - y += 2*LineHeight; - str_format(aBuf, sizeof(aBuf), "%.2f", static_cast(m_pClient->m_Snap.m_pLocalCharacter->m_X)/32.0f); + y += 2 * LineHeight; + str_format(aBuf, sizeof(aBuf), "%.2f", static_cast(m_pClient->m_Snap.m_pLocalCharacter->m_X) / 32.0f); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; - str_format(aBuf, sizeof(aBuf), "%.2f", static_cast(m_pClient->m_Snap.m_pLocalCharacter->m_Y)/32.0f); + str_format(aBuf, sizeof(aBuf), "%.2f", static_cast(m_pClient->m_Snap.m_pLocalCharacter->m_Y) / 32.0f); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_Snap.m_pLocalCharacter->m_Angle); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); - y += 2*LineHeight; + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); + y += 2 * LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->NetobjNumCorrections()); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, aBuf, -1.0f); y += LineHeight; w = TextRender()->TextWidth(0, Fontsize, m_pClient->NetobjCorrectedOn(), -1, -1.0f); - TextRender()->Text(0, x-w, y, Fontsize, m_pClient->NetobjCorrectedOn(), -1.0f); + TextRender()->Text(0, x - w, y, Fontsize, m_pClient->NetobjCorrectedOn(), -1.0f); } void CDebugHud::RenderTuning() @@ -86,7 +86,7 @@ void CDebugHud::RenderTuning() CTuningParams StandardTuning; - Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); + Graphics()->MapScreen(0, 0, 300 * Graphics()->ScreenAspect(), 300); float y = 27.0f; int Count = 0; @@ -98,9 +98,9 @@ void CDebugHud::RenderTuning() StandardTuning.Get(i, &Standard); if(Standard == Current) - TextRender()->TextColor(1,1,1,1.0f); + TextRender()->TextColor(1, 1, 1, 1.0f); else - TextRender()->TextColor(1,0.25f,0.25f,1.0f); + TextRender()->TextColor(1, 0.25f, 0.25f, 1.0f); float w; float x = 5.0f; @@ -108,20 +108,20 @@ void CDebugHud::RenderTuning() str_format(aBuf, sizeof(aBuf), "%.2f", Standard); x += 20.0f; w = TextRender()->TextWidth(0, 5, aBuf, -1, -1.0f); - TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1.0f); + TextRender()->Text(0x0, x - w, y + Count * 6, 5, aBuf, -1.0f); str_format(aBuf, sizeof(aBuf), "%.2f", Current); x += 20.0f; w = TextRender()->TextWidth(0, 5, aBuf, -1, -1.0f); - TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1.0f); + TextRender()->Text(0x0, x - w, y + Count * 6, 5, aBuf, -1.0f); x += 5.0f; - TextRender()->Text(0x0, x, y+Count*6, 5, m_pClient->m_Tuning[g_Config.m_ClDummy].ms_apNames[i], -1.0f); + TextRender()->Text(0x0, x, y + Count * 6, 5, m_pClient->m_Tuning[g_Config.m_ClDummy].ms_apNames[i], -1.0f); Count++; } - y = y+Count*6; + y = y + Count * 6; Graphics()->TextureClear(); Graphics()->BlendNormal(); @@ -131,16 +131,16 @@ void CDebugHud::RenderTuning() IGraphics::CLineItem Array[100]; for(int i = 0; i < 100; i++) { - float Speed = i/100.0f * 3000; + float Speed = i / 100.0f * 3000; float Ramp = VelocityRamp(Speed, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); - float RampedSpeed = (Speed * Ramp)/1000.0f; - Array[i] = IGraphics::CLineItem((i-1)*2, y+Height-pv*Height, i*2, y+Height-RampedSpeed*Height); + float RampedSpeed = (Speed * Ramp) / 1000.0f; + Array[i] = IGraphics::CLineItem((i - 1) * 2, y + Height - pv * Height, i * 2, y + Height - RampedSpeed * Height); //Graphics()->LinesDraw((i-1)*2, 200, i*2, 200); pv = RampedSpeed; } Graphics()->LinesDraw(Array, 100); Graphics()->LinesEnd(); - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); } void CDebugHud::OnRender() diff --git a/src/game/client/components/debughud.h b/src/game/client/components/debughud.h index 145f921a9..c7b2173fc 100644 --- a/src/game/client/components/debughud.h +++ b/src/game/client/components/debughud.h @@ -8,6 +8,7 @@ class CDebugHud : public CComponent { void RenderNetCorrections(); void RenderTuning(); + public: virtual void OnRender(); }; diff --git a/src/game/client/components/effects.cpp b/src/game/client/components/effects.cpp index 8bc61e2cd..c465b5fe5 100644 --- a/src/game/client/components/effects.cpp +++ b/src/game/client/components/effects.cpp @@ -10,16 +10,16 @@ #include +#include +#include #include #include -#include -#include #include #include #include "effects.h" -inline vec2 RandomDir() { return normalize(vec2(frandom()-0.5f, frandom()-0.5f)); } +inline vec2 RandomDir() { return normalize(vec2(frandom() - 0.5f, frandom() - 0.5f)); } CEffects::CEffects() { @@ -37,8 +37,8 @@ void CEffects::AirJump(vec2 Pos) p.m_LifeSpan = 0.5f; p.m_StartSize = 48.0f; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; - p.m_Rotspeed = pi*2; + p.m_Rot = frandom() * pi * 2; + p.m_Rotspeed = pi * 2; p.m_Gravity = 500; p.m_Friction = 0.7f; p.m_FlowAffected = 0.0f; @@ -69,13 +69,13 @@ void CEffects::PowerupShine(vec2 Pos, vec2 size) CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SLICE; - p.m_Pos = Pos + vec2((frandom()-0.5f)*size.x, (frandom()-0.5f)*size.y); + p.m_Pos = Pos + vec2((frandom() - 0.5f) * size.x, (frandom() - 0.5f) * size.y); p.m_Vel = vec2(0, 0); p.m_LifeSpan = 0.5f; p.m_StartSize = 16.0f; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; - p.m_Rotspeed = pi*2; + p.m_Rot = frandom() * pi * 2; + p.m_Rotspeed = pi * 2; p.m_Gravity = 500; p.m_Friction = 0.9f; p.m_FlowAffected = 0.0f; @@ -91,17 +91,16 @@ void CEffects::SmokeTrail(vec2 Pos, vec2 Vel, float Alpha, float TimePassed) p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; - p.m_Vel = Vel + RandomDir()*50.0f; - p.m_LifeSpan = 0.5f + frandom()*0.5f; - p.m_StartSize = 12.0f + frandom()*8; + p.m_Vel = Vel + RandomDir() * 50.0f; + p.m_LifeSpan = 0.5f + frandom() * 0.5f; + p.m_StartSize = 12.0f + frandom() * 8; p.m_EndSize = 0; p.m_Friction = 0.7f; - p.m_Gravity = frandom()*-500.0f; + p.m_Gravity = frandom() * -500.0f; p.m_Color.a *= Alpha; m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p, TimePassed); } - void CEffects::SkidTrail(vec2 Pos, vec2 Vel) { if(!m_Add100hz) @@ -111,13 +110,13 @@ void CEffects::SkidTrail(vec2 Pos, vec2 Vel) p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; - p.m_Vel = Vel + RandomDir()*50.0f; - p.m_LifeSpan = 0.5f + frandom()*0.5f; - p.m_StartSize = 24.0f + frandom()*12; + p.m_Vel = Vel + RandomDir() * 50.0f; + p.m_LifeSpan = 0.5f + frandom() * 0.5f; + p.m_StartSize = 24.0f + frandom() * 12; p.m_EndSize = 0; p.m_Friction = 0.7f; - p.m_Gravity = frandom()*-500.0f; - p.m_Color = ColorRGBA(0.75f,0.75f,0.75f,1.0f); + p.m_Gravity = frandom() * -500.0f; + p.m_Color = ColorRGBA(0.75f, 0.75f, 0.75f, 1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } @@ -130,7 +129,7 @@ void CEffects::BulletTrail(vec2 Pos, float Alpha, float TimePassed) p.SetDefault(); p.m_Spr = SPRITE_PART_BALL; p.m_Pos = Pos; - p.m_LifeSpan = 0.25f + frandom()*0.25f; + p.m_LifeSpan = 0.25f + frandom() * 0.25f; p.m_StartSize = 8.0f; p.m_EndSize = 0; p.m_Friction = 0.7f; @@ -146,17 +145,16 @@ void CEffects::PlayerSpawn(vec2 Pos) p.SetDefault(); p.m_Spr = SPRITE_PART_SHELL; p.m_Pos = Pos; - p.m_Vel = RandomDir() * (powf(frandom(), 3)*600.0f); - p.m_LifeSpan = 0.3f + frandom()*0.3f; - p.m_StartSize = 64.0f + frandom()*32; + p.m_Vel = RandomDir() * (powf(frandom(), 3) * 600.0f); + p.m_LifeSpan = 0.3f + frandom() * 0.3f; + p.m_StartSize = 64.0f + frandom() * 32; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; + p.m_Rot = frandom() * pi * 2; p.m_Rotspeed = frandom(); - p.m_Gravity = frandom()*-400.0f; + p.m_Gravity = frandom() * -400.0f; p.m_Friction = 0.7f; - p.m_Color = ColorRGBA(0xb5/255.0f, 0x50/255.0f, 0xcb/255.0f, 1.0f); + p.m_Color = ColorRGBA(0xb5 / 255.0f, 0x50 / 255.0f, 0xcb / 255.0f, 1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); - } if(g_Config.m_SndGame) m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos); @@ -164,7 +162,7 @@ void CEffects::PlayerSpawn(vec2 Pos) void CEffects::PlayerDeath(vec2 Pos, int ClientID) { - ColorRGBA BloodColor(1.0f,1.0f,1.0f); + ColorRGBA BloodColor(1.0f, 1.0f, 1.0f); if(ClientID >= 0) { @@ -182,23 +180,22 @@ void CEffects::PlayerDeath(vec2 Pos, int ClientID) { CParticle p; p.SetDefault(); - p.m_Spr = SPRITE_PART_SPLAT01 + (rand()%3); + p.m_Spr = SPRITE_PART_SPLAT01 + (rand() % 3); p.m_Pos = Pos; - p.m_Vel = RandomDir() * ((frandom()+0.1f)*900.0f); - p.m_LifeSpan = 0.3f + frandom()*0.3f; - p.m_StartSize = 24.0f + frandom()*16; + p.m_Vel = RandomDir() * ((frandom() + 0.1f) * 900.0f); + p.m_LifeSpan = 0.3f + frandom() * 0.3f; + p.m_StartSize = 24.0f + frandom() * 16; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; - p.m_Rotspeed = (frandom()-0.5f) * pi; + p.m_Rot = frandom() * pi * 2; + p.m_Rotspeed = (frandom() - 0.5f) * pi; p.m_Gravity = 800.0f; p.m_Friction = 0.8f; - ColorRGBA c = BloodColor.v4() * (0.75f + frandom()*0.25f); + ColorRGBA c = BloodColor.v4() * (0.75f + frandom() * 0.25f); p.m_Color = ColorRGBA(c.r, c.g, c.b, 0.75f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } - void CEffects::Explosion(vec2 Pos) { // add to flow @@ -208,8 +205,8 @@ void CEffects::Explosion(vec2 Pos) if(x == 0 && y == 0) continue; - float a = 1 - (length(vec2(x,y)) / length(vec2(8,8))); - m_pClient->m_pFlow->Add(Pos+vec2(x,y)*16, normalize(vec2(x,y))*5000.0f*a, 10.0f); + float a = 1 - (length(vec2(x, y)) / length(vec2(8, 8))); + m_pClient->m_pFlow->Add(Pos + vec2(x, y) * 16, normalize(vec2(x, y)) * 5000.0f * a, 10.0f); } // add the explosion @@ -220,7 +217,7 @@ void CEffects::Explosion(vec2 Pos) p.m_LifeSpan = 0.4f; p.m_StartSize = 150.0f; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; + p.m_Rot = frandom() * pi * 2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); // add the smoke @@ -230,18 +227,17 @@ void CEffects::Explosion(vec2 Pos) p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; - p.m_Vel = RandomDir() * ((1.0f + frandom()*0.2f) * 1000.0f); - p.m_LifeSpan = 0.5f + frandom()*0.4f; - p.m_StartSize = 32.0f + frandom()*8; + p.m_Vel = RandomDir() * ((1.0f + frandom() * 0.2f) * 1000.0f); + p.m_LifeSpan = 0.5f + frandom() * 0.4f; + p.m_StartSize = 32.0f + frandom() * 8; p.m_EndSize = 0; - p.m_Gravity = frandom()*-800.0f; + p.m_Gravity = frandom() * -800.0f; p.m_Friction = 0.4f; - p.m_Color = mix(vec4(0.75f,0.75f,0.75f,1.0f), vec4(0.5f,0.5f,0.5f,1.0f), frandom()); + p.m_Color = mix(vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.5f, 0.5f, 0.5f, 1.0f), frandom()); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } - void CEffects::HammerHit(vec2 Pos) { // add the explosion @@ -252,7 +248,7 @@ void CEffects::HammerHit(vec2 Pos) p.m_LifeSpan = 0.3f; p.m_StartSize = 120.0f; p.m_EndSize = 0; - p.m_Rot = frandom()*pi*2; + p.m_Rot = frandom() * pi * 2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); if(g_Config.m_SndGame) m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos); @@ -267,7 +263,7 @@ void CEffects::OnRender() { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); - if(time()-LastUpdate100hz > time_freq()/(100*pInfo->m_Speed)) + if(time() - LastUpdate100hz > time_freq() / (100 * pInfo->m_Speed)) { m_Add100hz = true; LastUpdate100hz = time(); @@ -275,7 +271,7 @@ void CEffects::OnRender() else m_Add100hz = false; - if(time()-LastUpdate50hz > time_freq()/(100*pInfo->m_Speed)) + if(time() - LastUpdate50hz > time_freq() / (100 * pInfo->m_Speed)) { m_Add50hz = true; LastUpdate50hz = time(); @@ -289,7 +285,7 @@ void CEffects::OnRender() return; } - if(time()-LastUpdate100hz > time_freq()/100) + if(time() - LastUpdate100hz > time_freq() / 100) { m_Add100hz = true; LastUpdate100hz = time(); @@ -297,7 +293,7 @@ void CEffects::OnRender() else m_Add100hz = false; - if(time()-LastUpdate50hz > time_freq()/100) + if(time() - LastUpdate50hz > time_freq() / 100) { m_Add50hz = true; LastUpdate50hz = time(); diff --git a/src/game/client/components/effects.h b/src/game/client/components/effects.h index 0446e0ae8..8b6c4359e 100644 --- a/src/game/client/components/effects.h +++ b/src/game/client/components/effects.h @@ -8,6 +8,7 @@ class CEffects : public CComponent { bool m_Add50hz; bool m_Add100hz; + public: CEffects(); diff --git a/src/game/client/components/emoticon.cpp b/src/game/client/components/emoticon.cpp index a4c9e539a..2aa6c877e 100644 --- a/src/game/client/components/emoticon.cpp +++ b/src/game/client/components/emoticon.cpp @@ -3,15 +3,15 @@ #include #include #include -#include #include +#include -#include // get_angle -#include -#include -#include #include "chat.h" #include "emoticon.h" +#include +#include +#include +#include // get_angle CEmoticon::CEmoticon() { @@ -55,7 +55,7 @@ bool CEmoticon::OnMouseMove(float x, float y) return false; UI()->ConvertMouseMove(&x, &y); - m_SelectorMouse += vec2(x,y); + m_SelectorMouse += vec2(x, y); return true; } @@ -64,7 +64,6 @@ void CEmoticon::DrawCircle(float x, float y, float r, int Segments) RenderTools()->DrawCircle(x, y, r, Segments); } - void CEmoticon::OnRender() { if(!m_Active) @@ -86,20 +85,19 @@ void CEmoticon::OnRender() m_WasActive = true; - if (length(m_SelectorMouse) > 170.0f) + if(length(m_SelectorMouse) > 170.0f) m_SelectorMouse = normalize(m_SelectorMouse) * 170.0f; - float SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24; - if (SelectedAngle < 0) - SelectedAngle += 2*pi; + float SelectedAngle = GetAngle(m_SelectorMouse) + 2 * pi / 24; + if(SelectedAngle < 0) + SelectedAngle += 2 * pi; m_SelectedEmote = -1; m_SelectedEyeEmote = -1; - if (length(m_SelectorMouse) > 110.0f) - m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS); + if(length(m_SelectorMouse) > 110.0f) + m_SelectedEmote = (int)(SelectedAngle / (2 * pi) * NUM_EMOTICONS); else if(length(m_SelectorMouse) > 40.0f) - m_SelectedEyeEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTES); - + m_SelectedEyeEmote = (int)(SelectedAngle / (2 * pi) * NUM_EMOTES); CUIRect Screen = *UI()->Screen(); @@ -109,18 +107,18 @@ void CEmoticon::OnRender() Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.3f); - DrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64); + Graphics()->SetColor(0, 0, 0, 0.3f); + DrawCircle(Screen.w / 2, Screen.h / 2, 190.0f, 64); Graphics()->QuadsEnd(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); - for (int i = 0; i < NUM_EMOTICONS; i++) + for(int i = 0; i < NUM_EMOTICONS; i++) { - float Angle = 2*pi*i/NUM_EMOTICONS; - if (Angle > pi) - Angle -= 2*pi; + float Angle = 2 * pi * i / NUM_EMOTICONS; + if(Angle > pi) + Angle -= 2 * pi; bool Selected = m_SelectedEmote == i; @@ -129,7 +127,7 @@ void CEmoticon::OnRender() float NudgeX = 150.0f * cosf(Angle); float NudgeY = 150.0f * sinf(Angle); RenderTools()->SelectSprite(SPRITE_OOP + i); - IGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size); + IGraphics::CQuadItem QuadItem(Screen.w / 2 + NudgeX, Screen.h / 2 + NudgeY, Size, Size); Graphics()->QuadsDraw(&QuadItem, 1); } @@ -139,19 +137,19 @@ void CEmoticon::OnRender() { Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(1.0,1.0,1.0,0.3f); - DrawCircle(Screen.w/2, Screen.h/2, 100.0f, 64); + Graphics()->SetColor(1.0, 1.0, 1.0, 0.3f); + DrawCircle(Screen.w / 2, Screen.h / 2, 100.0f, 64); Graphics()->QuadsEnd(); CTeeRenderInfo *pTeeInfo = &m_pClient->m_aClients[m_pClient->m_LocalIDs[g_Config.m_ClDummy]].m_RenderInfo; Graphics()->TextureSet(pTeeInfo->m_Texture); - for (int i = 0; i < NUM_EMOTES; i++) + for(int i = 0; i < NUM_EMOTES; i++) { - float Angle = 2*pi*i/NUM_EMOTES; - if (Angle > pi) - Angle -= 2*pi; + float Angle = 2 * pi * i / NUM_EMOTES; + if(Angle > pi) + Angle -= 2 * pi; bool Selected = m_SelectedEyeEmote == i; @@ -159,14 +157,14 @@ void CEmoticon::OnRender() float NudgeY = 70.0f * sinf(Angle); pTeeInfo->m_Size = Selected ? 64.0f : 48.0f; - RenderTools()->RenderTee(CAnimState::GetIdle(), pTeeInfo, i, vec2(-1,0), vec2(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY)); + RenderTools()->RenderTee(CAnimState::GetIdle(), pTeeInfo, i, vec2(-1, 0), vec2(Screen.w / 2 + NudgeX, Screen.h / 2 + NudgeY)); pTeeInfo->m_Size = 64.0f; } Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.3f); - DrawCircle(Screen.w/2, Screen.h/2, 30.0f, 64); + Graphics()->SetColor(0, 0, 0, 0.3f); + DrawCircle(Screen.w / 2, Screen.h / 2, 30.0f, 64); Graphics()->QuadsEnd(); } else @@ -175,8 +173,8 @@ void CEmoticon::OnRender() Graphics()->WrapClamp(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); - Graphics()->SetColor(1,1,1,1); - IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Screen.w/2,m_SelectorMouse.y+Screen.h/2,24,24); + Graphics()->SetColor(1, 1, 1, 1); + IGraphics::CQuadItem QuadItem(m_SelectorMouse.x + Screen.w / 2, m_SelectorMouse.y + Screen.h / 2, 24, 24); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); Graphics()->WrapNormal(); diff --git a/src/game/client/components/flow.cpp b/src/game/client/components/flow.cpp index 9a9982435..d60a2020f 100644 --- a/src/game/client/components/flow.cpp +++ b/src/game/client/components/flow.cpp @@ -1,9 +1,9 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include -#include -#include #include "flow.h" +#include +#include +#include CFlow::CFlow() { @@ -25,9 +25,9 @@ void CFlow::DbgRender() for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) { - vec2 Pos(x*m_Spacing, y*m_Spacing); - vec2 Vel = m_pCells[y*m_Width+x].m_Vel * 0.01f; - Array[NumItems++] = IGraphics::CLineItem(Pos.x, Pos.y, Pos.x+Vel.x, Pos.y+Vel.y); + vec2 Pos(x * m_Spacing, y * m_Spacing); + vec2 Vel = m_pCells[y * m_Width + x].m_Vel * 0.01f; + Array[NumItems++] = IGraphics::CLineItem(Pos.x, Pos.y, Pos.x + Vel.x, Pos.y + Vel.y); if(NumItems == 1024) { Graphics()->LinesDraw(Array, 1024); @@ -46,14 +46,14 @@ void CFlow::Init() m_pCells = 0; CMapItemLayerTilemap *pTilemap = Layers()->GameLayer(); - m_Width = pTilemap->m_Width*32/m_Spacing; - m_Height = pTilemap->m_Height*32/m_Spacing; + m_Width = pTilemap->m_Width * 32 / m_Spacing; + m_Height = pTilemap->m_Height * 32 / m_Spacing; // allocate and clear m_pCells = (CCell *)calloc(m_Width * m_Height, sizeof(CCell)); for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - m_pCells[y*m_Width+x].m_Vel = vec2(0.0f, 0.0f); + m_pCells[y * m_Width + x].m_Vel = vec2(0.0f, 0.0f); } void CFlow::Update() @@ -63,20 +63,20 @@ void CFlow::Update() for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - m_pCells[y*m_Width+x].m_Vel *= 0.85f; + m_pCells[y * m_Width + x].m_Vel *= 0.85f; } vec2 CFlow::Get(vec2 Pos) { if(!m_pCells) - return vec2(0,0); + return vec2(0, 0); int x = (int)(Pos.x / m_Spacing); int y = (int)(Pos.y / m_Spacing); if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) - return vec2(0,0); + return vec2(0, 0); - return m_pCells[y*m_Width+x].m_Vel; + return m_pCells[y * m_Width + x].m_Vel; } void CFlow::Add(vec2 Pos, vec2 Vel, float Size) @@ -89,5 +89,5 @@ void CFlow::Add(vec2 Pos, vec2 Vel, float Size) if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) return; - m_pCells[y*m_Width+x].m_Vel += Vel; + m_pCells[y * m_Width + x].m_Vel += Vel; } diff --git a/src/game/client/components/flow.h b/src/game/client/components/flow.h index 0b8e590f6..f34db1bce 100644 --- a/src/game/client/components/flow.h +++ b/src/game/client/components/flow.h @@ -19,6 +19,7 @@ class CFlow : public CComponent void DbgRender(); void Init(); + public: CFlow(); diff --git a/src/game/client/components/ghost.cpp b/src/game/client/components/ghost.cpp index a523e1778..b61cb000c 100644 --- a/src/game/client/components/ghost.cpp +++ b/src/game/client/components/ghost.cpp @@ -2,19 +2,20 @@ #include #include -#include #include +#include #include +#include "ghost.h" +#include "menus.h" #include "players.h" #include "skins.h" -#include "menus.h" -#include "ghost.h" const char *CGhost::ms_pGhostDir = "ghosts"; -CGhost::CGhost() : m_NewRenderTick(-1), m_StartRenderTick(-1), m_LastDeathTick(-1), m_LastRaceTick(-1), m_Recording(false), m_Rendering(false) {} +CGhost::CGhost() : + m_NewRenderTick(-1), m_StartRenderTick(-1), m_LastDeathTick(-1), m_LastRaceTick(-1), m_Recording(false), m_Rendering(false) {} void CGhost::GetGhostSkin(CGhostSkin *pSkin, const char *pSkinName, int UseCustomColor, int ColorBody, int ColorFeet) { @@ -58,14 +59,14 @@ void CGhost::GetNetObjCharacter(CNetObj_Character *pChar, const CGhostCharacter pChar->m_Tick = pGhostChar->m_Tick; } -CGhost::CGhostPath::CGhostPath(CGhostPath &&Other) - : m_ChunkSize(Other.m_ChunkSize), m_NumItems(Other.m_NumItems), m_lChunks(std::move(Other.m_lChunks)) +CGhost::CGhostPath::CGhostPath(CGhostPath &&Other) : + m_ChunkSize(Other.m_ChunkSize), m_NumItems(Other.m_NumItems), m_lChunks(std::move(Other.m_lChunks)) { Other.m_NumItems = 0; Other.m_lChunks.clear(); } -CGhost::CGhostPath &CGhost::CGhostPath::operator = (CGhostPath &&Other) +CGhost::CGhostPath &CGhost::CGhostPath::operator=(CGhostPath &&Other) { Reset(Other.m_ChunkSize); m_NumItems = Other.m_NumItems; @@ -264,7 +265,7 @@ void CGhost::OnNewSnapshot() if(!m_pClient->m_Snap.m_pGameInfoObj || m_pClient->m_Snap.m_SpecInfo.m_Active || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter) return; - bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_RACETIME; + bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME; bool ServerControl = RaceFlag && g_Config.m_ClRaceGhostServerControl; if(g_Config.m_ClRaceGhost) @@ -290,7 +291,7 @@ void CGhost::OnNewPredictedSnapshot() if(!m_pClient->m_Snap.m_pGameInfoObj || m_pClient->m_Snap.m_SpecInfo.m_Active || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter) return; - bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_RACETIME; + bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME; bool ServerControl = RaceFlag && g_Config.m_ClRaceGhostServerControl; if(!ServerControl) @@ -339,7 +340,7 @@ void CGhost::OnRender() Player.m_AttackTick += Client()->GameTick(g_Config.m_ClDummy) - GhostTick; - m_pClient->m_pPlayers->RenderHook(&Prev, &Player, &pGhost->m_RenderInfo , -2, IntraTick); + m_pClient->m_pPlayers->RenderHook(&Prev, &Player, &pGhost->m_RenderInfo, -2, IntraTick); m_pClient->m_pPlayers->RenderPlayer(&Prev, &Player, &pGhost->m_RenderInfo, -2, IntraTick); } } diff --git a/src/game/client/components/ghost.h b/src/game/client/components/ghost.h index 617b54f96..78da9c66a 100644 --- a/src/game/client/components/ghost.h +++ b/src/game/client/components/ghost.h @@ -60,16 +60,16 @@ private: int m_ChunkSize; int m_NumItems; - std::vector m_lChunks; + std::vector m_lChunks; public: CGhostPath() { Reset(); } ~CGhostPath() { Reset(); } CGhostPath(const CGhostPath &Other) = delete; - CGhostPath &operator = (const CGhostPath &Other) = delete; + CGhostPath &operator=(const CGhostPath &Other) = delete; CGhostPath(CGhostPath &&Other); - CGhostPath &operator = (CGhostPath &&Other); + CGhostPath &operator=(CGhostPath &&Other); void Reset(int ChunkSize = 25 * 60); // one minute with default snap rate void SetSize(int Items); diff --git a/src/game/client/components/hud.cpp b/src/game/client/components/hud.cpp index f3c15601e..4e0c4b146 100644 --- a/src/game/client/components/hud.cpp +++ b/src/game/client/components/hud.cpp @@ -2,24 +2,24 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include #include -#include #include +#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include #include -#include "controls.h" +#include "binds.h" #include "camera.h" +#include "controls.h" #include "hud.h" #include "voting.h" -#include "binds.h" CHud::CHud() { @@ -64,7 +64,6 @@ void CHud::OnWindowResize() ResetHudContainers(); } - void CHud::OnReset() { m_CheckpointDiff = 0.0f; @@ -102,35 +101,35 @@ void CHud::OnInit() void CHud::RenderGameTimer() { - float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; + float Half = 300.0f * Graphics()->ScreenAspect() / 2.0f; - if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH)) + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_SUDDENDEATH)) { char aBuf[32]; int Time = 0; if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit && (m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer <= 0)) { - Time = m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit*60 - ((Client()->GameTick(g_Config.m_ClDummy)-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick)/Client()->GameTickSpeed()); + Time = m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit * 60 - ((Client()->GameTick(g_Config.m_ClDummy) - m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / Client()->GameTickSpeed()); - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) Time = 0; } - else if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_RACETIME) + else if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME) { //The Warmup timer is negative in this case to make sure that incompatible clients will not see a warmup timer - Time = (Client()->GameTick(g_Config.m_ClDummy)+m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer)/Client()->GameTickSpeed(); + Time = (Client()->GameTick(g_Config.m_ClDummy) + m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer) / Client()->GameTickSpeed(); } else - Time = (Client()->GameTick(g_Config.m_ClDummy)-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick)/Client()->GameTickSpeed(); + Time = (Client()->GameTick(g_Config.m_ClDummy) - m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / Client()->GameTickSpeed(); if(Time <= 0 && g_Config.m_ClShowDecisecs) str_format(aBuf, sizeof(aBuf), "00:00.0"); else if(Time <= 0) str_format(aBuf, sizeof(aBuf), "00:00"); else if(g_Config.m_ClShowDecisecs) - str_format(aBuf, sizeof(aBuf), "%02d:%02d.%d", Time/60, Time%60, m_DDRaceTick/10); + str_format(aBuf, sizeof(aBuf), "%02d:%02d.%d", Time / 60, Time % 60, m_DDRaceTick / 10); else - str_format(aBuf, sizeof(aBuf), "%02d:%02d", Time/60, Time%60); + str_format(aBuf, sizeof(aBuf), "%02d:%02d", Time / 60, Time % 60); float FontSize = 10.0f; float w; if(g_Config.m_ClShowDecisecs) @@ -140,62 +139,61 @@ void CHud::RenderGameTimer() // last 60 sec red, last 10 sec blink if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit && Time <= 60 && (m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer <= 0)) { - float Alpha = Time <= 10 && (2*time()/time_freq()) % 2 ? 0.5f : 1.0f; + float Alpha = Time <= 10 && (2 * time() / time_freq()) % 2 ? 0.5f : 1.0f; TextRender()->TextColor(1.0f, 0.25f, 0.25f, Alpha); } - TextRender()->Text(0, Half-w/2, 2, FontSize, aBuf, -1.0f); + TextRender()->Text(0, Half - w / 2, 2, FontSize, aBuf, -1.0f); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } void CHud::RenderPauseNotification() { - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED && - !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED && + !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER)) { const char *pText = Localize("Game paused"); float FontSize = 20.0f; - float w = TextRender()->TextWidth(0, FontSize,pText, -1, -1.0f); - TextRender()->Text(0, 150.0f*Graphics()->ScreenAspect()+-w/2.0f, 50.0f, FontSize, pText, -1.0f); + float w = TextRender()->TextWidth(0, FontSize, pText, -1, -1.0f); + TextRender()->Text(0, 150.0f * Graphics()->ScreenAspect() + -w / 2.0f, 50.0f, FontSize, pText, -1.0f); } } void CHud::RenderSuddenDeath() { - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_SUDDENDEATH) { - float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; + float Half = 300.0f * Graphics()->ScreenAspect() / 2.0f; const char *pText = Localize("Sudden Death"); float FontSize = 12.0f; float w = TextRender()->TextWidth(0, FontSize, pText, -1, -1.0f); - TextRender()->Text(0, Half-w/2, 2, FontSize, pText, -1.0f); + TextRender()->Text(0, Half - w / 2, 2, FontSize, pText, -1.0f); } } void CHud::RenderScoreHud() { // render small score hud - if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER)) { int GameFlags = m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags; - float Whole = 300*Graphics()->ScreenAspect(); + float Whole = 300 * Graphics()->ScreenAspect(); float StartY = 229.0f; bool ForceScoreInfoInit = !m_aScoreInfo[0].m_Initialized || !m_aScoreInfo[1].m_Initialized; m_aScoreInfo[0].m_Initialized = m_aScoreInfo[1].m_Initialized = true; - if(GameFlags&GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataObj) + if(GameFlags & GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataObj) { char aScoreTeam[2][16]; str_format(aScoreTeam[TEAM_RED], sizeof(aScoreTeam), "%d", m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed); str_format(aScoreTeam[TEAM_BLUE], sizeof(aScoreTeam), "%d", m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue); - bool RecreateTeamScore[2] = { str_comp(aScoreTeam[0], m_aScoreInfo[0].m_aScoreText) != 0, str_comp(aScoreTeam[1], m_aScoreInfo[1].m_aScoreText) != 0 }; + bool RecreateTeamScore[2] = {str_comp(aScoreTeam[0], m_aScoreInfo[0].m_aScoreText) != 0, str_comp(aScoreTeam[1], m_aScoreInfo[1].m_aScoreText) != 0}; int FlagCarrier[2] = { m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed, - m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue - }; + m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue}; bool RecreateRect = ForceScoreInfoInit; for(int t = 0; t < 2; t++) @@ -249,11 +247,13 @@ void CHud::RenderScoreHud() TextRender()->RenderTextContainer(m_aScoreInfo[t].m_TextScoreContainerIndex, &TColor, &TOutlineColor); } - if(GameFlags&GAMEFLAG_FLAGS) + if(GameFlags & GAMEFLAG_FLAGS) { int BlinkTimer = (m_pClient->m_FlagDropTick[t] != 0 && - (Client()->GameTick(g_Config.m_ClDummy)-m_pClient->m_FlagDropTick[t])/Client()->GameTickSpeed() >= 25) ? 10 : 20; - if(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick(g_Config.m_ClDummy)/BlinkTimer)&1))) + (Client()->GameTick(g_Config.m_ClDummy) - m_pClient->m_FlagDropTick[t]) / Client()->GameTickSpeed() >= 25) ? + 10 : + 20; + if(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick(g_Config.m_ClDummy) / BlinkTimer) & 1))) { // draw flag Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); @@ -264,7 +264,7 @@ void CHud::RenderScoreHud() else if(FlagCarrier[t] >= 0) { // draw name of the flag holder - int ID = FlagCarrier[t]%MAX_CLIENTS; + int ID = FlagCarrier[t] % MAX_CLIENTS; const char *pName = m_pClient->m_aClients[ID].m_aName; if(str_comp(pName, m_aScoreInfo[t].m_aPlayerNameText) != 0 || RecreateRect) { @@ -276,7 +276,7 @@ void CHud::RenderScoreHud() float w = TextRender()->TextWidth(0, 8.0f, pName, -1, -1.0f); CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, minimum(Whole - w - 1.0f, Whole - ScoreWidthMax - ImageSize - 2 * Split), StartY + (t + 1)*20.0f - 2.0f, 8.0f, TEXTFLAG_RENDER); + TextRender()->SetCursor(&Cursor, minimum(Whole - w - 1.0f, Whole - ScoreWidthMax - ImageSize - 2 * Split), StartY + (t + 1) * 20.0f - 2.0f, 8.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = -1; m_aScoreInfo[t].m_OptionalNameTextContainerIndex = TextRender()->CreateTextContainer(&Cursor, pName); } @@ -291,8 +291,8 @@ void CHud::RenderScoreHud() // draw tee of the flag holder CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; Info.m_Size = 18.0f; - RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), - vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1, 0), + vec2(Whole - ScoreWidthMax - Info.m_Size / 2 - Split, StartY + 1.0f + Info.m_Size / 2 + t * 20)); } } StartY += 8.0f; @@ -301,8 +301,8 @@ void CHud::RenderScoreHud() else { int Local = -1; - int aPos[2] = { 1, 2 }; - const CNetObj_PlayerInfo *apPlayerInfo[2] = { 0, 0 }; + int aPos[2] = {1, 2}; + const CNetObj_PlayerInfo *apPlayerInfo[2] = {0, 0}; int i = 0; for(int t = 0; t < 2 && i < MAX_CLIENTS && m_pClient->m_Snap.m_paInfoByScore[i]; ++i) { @@ -337,18 +337,18 @@ void CHud::RenderScoreHud() if(m_pClient->m_GameInfo.m_TimeScore && g_Config.m_ClDDRaceScoreBoard) { if(apPlayerInfo[t]->m_Score != -9999) - str_format(aScore[t], sizeof(aScore[t]), "%02d:%02d", abs(apPlayerInfo[t]->m_Score)/60, abs(apPlayerInfo[t]->m_Score)%60); + str_format(aScore[t], sizeof(aScore[t]), "%02d:%02d", abs(apPlayerInfo[t]->m_Score) / 60, abs(apPlayerInfo[t]->m_Score) % 60); else aScore[t][0] = 0; } else - str_format(aScore[t], sizeof(aScore)/2, "%d", apPlayerInfo[t]->m_Score); + str_format(aScore[t], sizeof(aScore) / 2, "%d", apPlayerInfo[t]->m_Score); } else aScore[t][0] = 0; } - bool RecreateScore[2] = { str_comp(aScore[0], m_aScoreInfo[0].m_aScoreText) != 0, str_comp(aScore[1], m_aScoreInfo[1].m_aScoreText) != 0 }; + bool RecreateScore[2] = {str_comp(aScore[0], m_aScoreInfo[0].m_aScoreText) != 0, str_comp(aScore[1], m_aScoreInfo[1].m_aScoreText) != 0}; bool RecreateRect = ForceScoreInfoInit; for(int t = 0; t < 2; t++) @@ -440,7 +440,7 @@ void CHud::RenderScoreHud() float w = TextRender()->TextWidth(0, 8.0f, pName, -1, -1.0f); CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, minimum(Whole - w - 1.0f, Whole - ScoreWidthMax - ImageSize - 2 * Split - PosSize), StartY + (t + 1)*20.0f - 2.0f, 8.0f, TEXTFLAG_RENDER); + TextRender()->SetCursor(&Cursor, minimum(Whole - w - 1.0f, Whole - ScoreWidthMax - ImageSize - 2 * Split - PosSize), StartY + (t + 1) * 20.0f - 2.0f, 8.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = -1; m_aScoreInfo[t].m_OptionalNameTextContainerIndex = TextRender()->CreateTextContainer(&Cursor, pName); } @@ -455,8 +455,8 @@ void CHud::RenderScoreHud() // draw tee CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; Info.m_Size = 18.0f; - RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), - vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1, 0), + vec2(Whole - ScoreWidthMax - Info.m_Size / 2 - Split, StartY + 1.0f + Info.m_Size / 2 + t * 20)); } } else @@ -495,20 +495,20 @@ void CHud::RenderScoreHud() void CHud::RenderWarmupTimer() { // render warmup timer - if(m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer > 0 && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_RACETIME)) + if(m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer > 0 && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME)) { char Buf[256]; float FontSize = 20.0f; float w = TextRender()->TextWidth(0, FontSize, Localize("Warmup"), -1, -1.0f); - TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, Localize("Warmup"), -1.0f); + TextRender()->Text(0, 150 * Graphics()->ScreenAspect() + -w / 2, 50, FontSize, Localize("Warmup"), -1.0f); - int Seconds = m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer/SERVER_TICK_SPEED; + int Seconds = m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer / SERVER_TICK_SPEED; if(Seconds < 5) - str_format(Buf, sizeof(Buf), "%d.%d", Seconds, (m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer*10/SERVER_TICK_SPEED)%10); + str_format(Buf, sizeof(Buf), "%d.%d", Seconds, (m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer * 10 / SERVER_TICK_SPEED) % 10); else str_format(Buf, sizeof(Buf), "%d", Seconds); w = TextRender()->TextWidth(0, FontSize, Buf, -1, -1.0f); - TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, Buf, -1.0f); + TextRender()->Text(0, 150 * Graphics()->ScreenAspect() + -w / 2, 75, FontSize, Buf, -1.0f); } } @@ -525,7 +525,7 @@ void CHud::RenderTextInfo() if(g_Config.m_ClShowfps) { // calculate avg. fps - m_FrameTimeAvg = m_FrameTimeAvg*0.9f + Client()->RenderFrameTime()*0.1f; + m_FrameTimeAvg = m_FrameTimeAvg * 0.9f + Client()->RenderFrameTime() * 0.1f; char Buf[64]; int FrameTime = (int)(1.0f / m_FrameTimeAvg + 0.5f); str_format(Buf, sizeof(Buf), "%d", FrameTime); @@ -535,7 +535,7 @@ void CHud::RenderTextInfo() static float s_TextWidth000 = TextRender()->TextWidth(0, 12.f, "000", -1, -1.0f); static float s_TextWidth0000 = TextRender()->TextWidth(0, 12.f, "0000", -1, -1.0f); static float s_TextWidth00000 = TextRender()->TextWidth(0, 12.f, "00000", -1, -1.0f); - static float s_TextWidth[5] = { s_TextWidth0, s_TextWidth00, s_TextWidth000, s_TextWidth0000, s_TextWidth00000 }; + static float s_TextWidth[5] = {s_TextWidth0, s_TextWidth00, s_TextWidth000, s_TextWidth0000, s_TextWidth00000}; int DigitIndex = (int)log10((FrameTime ? FrameTime : 1)); if(DigitIndex > 4) @@ -564,7 +564,7 @@ void CHud::RenderTextInfo() { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%d", Client()->GetPredictionTime()); - TextRender()->Text(0, m_Width-10-TextRender()->TextWidth(0,12,aBuf,-1,-1.0f), g_Config.m_ClShowfps ? 20 : 5, 12, aBuf, -1.0f); + TextRender()->Text(0, m_Width - 10 - TextRender()->TextWidth(0, 12, aBuf, -1, -1.0f), g_Config.m_ClShowfps ? 20 : 5, 12, aBuf, -1.0f); } } @@ -574,31 +574,30 @@ void CHud::RenderConnectionWarning() { const char *pText = Localize("Connection Problems..."); float w = TextRender()->TextWidth(0, 24, pText, -1, -1.0f); - TextRender()->Text(0, 150*Graphics()->ScreenAspect()-w/2, 50, 24, pText, -1.0f); + TextRender()->Text(0, 150 * Graphics()->ScreenAspect() - w / 2, 50, 24, pText, -1.0f); } } void CHud::RenderTeambalanceWarning() { // render prompt about team-balance - bool Flash = time()/(time_freq()/2)%2 == 0; - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + bool Flash = time() / (time_freq() / 2) % 2 == 0; + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { - int TeamDiff = m_pClient->m_Snap.m_aTeamSize[TEAM_RED]-m_pClient->m_Snap.m_aTeamSize[TEAM_BLUE]; + int TeamDiff = m_pClient->m_Snap.m_aTeamSize[TEAM_RED] - m_pClient->m_Snap.m_aTeamSize[TEAM_BLUE]; if(g_Config.m_ClWarningTeambalance && (TeamDiff >= 2 || TeamDiff <= -2)) { const char *pText = Localize("Please balance teams!"); if(Flash) - TextRender()->TextColor(1,1,0.5f,1); + TextRender()->TextColor(1, 1, 0.5f, 1); else - TextRender()->TextColor(0.7f,0.7f,0.2f,1.0f); + TextRender()->TextColor(0.7f, 0.7f, 0.2f, 1.0f); TextRender()->Text(0x0, 5, 50, 6, pText, -1.0f); - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); } } } - void CHud::RenderVoting() { if((!g_Config.m_ClShowVotesAfterVoting && !m_pClient->m_pScoreboard->Active() && m_pClient->m_pVoting->TakenChoice()) || !m_pClient->m_pVoting->IsVoting() || Client()->State() == IClient::STATE_DEMOPLAYBACK) @@ -606,28 +605,28 @@ void CHud::RenderVoting() Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.40f); + Graphics()->SetColor(0, 0, 0, 0.40f); - RenderTools()->DrawRoundRect(-10, 60-2, 100+10+4+5, 46, 5.0f); + RenderTools()->DrawRoundRect(-10, 60 - 2, 100 + 10 + 4 + 5, 46, 5.0f); Graphics()->QuadsEnd(); - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); CTextCursor Cursor; char aBuf[512]; str_format(aBuf, sizeof(aBuf), Localize("%ds left"), m_pClient->m_pVoting->SecondsLeft()); float tw = TextRender()->TextWidth(0x0, 6, aBuf, -1, -1.0f); - TextRender()->SetCursor(&Cursor, 5.0f+100.0f-tw, 60.0f, 6.0f, TEXTFLAG_RENDER); + TextRender()->SetCursor(&Cursor, 5.0f + 100.0f - tw, 60.0f, 6.0f, TEXTFLAG_RENDER); TextRender()->TextEx(&Cursor, aBuf, -1); TextRender()->SetCursor(&Cursor, 5.0f, 60.0f, 6.0f, TEXTFLAG_RENDER); - Cursor.m_LineWidth = 100.0f-tw; + Cursor.m_LineWidth = 100.0f - tw; Cursor.m_MaxLines = 3; TextRender()->TextEx(&Cursor, m_pClient->m_pVoting->VoteDescription(), -1); // reason str_format(aBuf, sizeof(aBuf), "%s %s", Localize("Reason:"), m_pClient->m_pVoting->VoteReason()); - TextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = 100.0f; TextRender()->TextEx(&Cursor, aBuf, -1); @@ -656,7 +655,7 @@ void CHud::RenderCursor() Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); // render cursor - int QuadOffset = NUM_WEAPONS * 10 + 40 + (m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS); + int QuadOffset = NUM_WEAPONS * 10 + 40 + (m_pClient->m_Snap.m_pLocalCharacter->m_Weapon % NUM_WEAPONS); Graphics()->SetColor(1.f, 1.f, 1.f, 1.f); Graphics()->RenderQuadContainerAsSprite(m_HudQuadContainerIndex, QuadOffset, m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy].x, m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy].y); } @@ -671,7 +670,7 @@ void CHud::PrepareHealthAmoQuads() for(int i = 0; i < NUM_WEAPONS; ++i) { - RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[i%NUM_WEAPONS].m_pSpriteProj); + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[i % NUM_WEAPONS].m_pSpriteProj); for(int n = 0; n < 10; n++) Array[n] = IGraphics::CQuadItem(x + n * 12, y + 24, 10, 10); Graphics()->QuadContainerAddQuads(m_HudQuadContainerIndex, Array, 10); @@ -709,7 +708,7 @@ void CHud::RenderHealthAndAmmo(const CNetObj_Character *pCharacter) Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); - int QuadOffset = pCharacter->m_Weapon%NUM_WEAPONS * 10; + int QuadOffset = pCharacter->m_Weapon % NUM_WEAPONS * 10; Graphics()->RenderQuadContainer(m_HudQuadContainerIndex, QuadOffset, minimum(pCharacter->m_AmmoCount, 10)); QuadOffset = NUM_WEAPONS * 10; @@ -733,14 +732,13 @@ void CHud::RenderSpectatorHud() Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); - RenderTools()->DrawRoundRectExt(m_Width-180.0f, m_Height-15.0f, 180.0f, 15.0f, 5.0f, CUI::CORNER_TL); + RenderTools()->DrawRoundRectExt(m_Width - 180.0f, m_Height - 15.0f, 180.0f, 15.0f, 5.0f, CUI::CORNER_TL); Graphics()->QuadsEnd(); // draw the text char aBuf[128]; - str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Spectate"), m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW ? - m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName : Localize("Free-View")); - TextRender()->Text(0, m_Width-174.0f, m_Height-15.0f + (15.f - 8.f) / 2.f, 8.0f, aBuf, -1.0f); + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Spectate"), m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW ? m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName : Localize("Free-View")); + TextRender()->Text(0, m_Width - 174.0f, m_Height - 15.0f + (15.f - 8.f) / 2.f, 8.0f, aBuf, -1.0f); } void CHud::RenderLocalTime(float x) @@ -753,13 +751,13 @@ void CHud::RenderLocalTime(float x) Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); - RenderTools()->DrawRoundRectExt(x-30.0f, 0.0f, 25.0f, 12.5f, 3.75f, CUI::CORNER_B); + RenderTools()->DrawRoundRectExt(x - 30.0f, 0.0f, 25.0f, 12.5f, 3.75f, CUI::CORNER_B); Graphics()->QuadsEnd(); //draw the text char aTimeStr[6]; str_timestamp_format(aTimeStr, sizeof(aTimeStr), "%H:%M"); - TextRender()->Text(0, x-25.0f, (12.5f - 5.f) / 2.f, 5.0f, aTimeStr, -1.0f); + TextRender()->Text(0, x - 25.0f, (12.5f - 5.f) / 2.f, 5.0f, aTimeStr, -1.0f); } void CHud::OnRender() @@ -767,17 +765,17 @@ void CHud::OnRender() if(!m_pClient->m_Snap.m_pGameInfoObj) return; - m_Width = 300.0f*Graphics()->ScreenAspect(); + m_Width = 300.0f * Graphics()->ScreenAspect(); m_Height = 300.0f; Graphics()->MapScreen(0.0f, 0.0f, m_Width, m_Height); #if defined(CONF_VIDEORECORDER) - if((IVideo::Current()&&g_Config.m_ClVideoShowhud)||(!IVideo::Current()&&g_Config.m_ClShowhud)) + if((IVideo::Current() && g_Config.m_ClVideoShowhud) || (!IVideo::Current() && g_Config.m_ClShowhud)) #else if(g_Config.m_ClShowhud) #endif { - if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER)) { if(g_Config.m_ClShowhudHealthAmmo) RenderHealthAndAmmo(m_pClient->m_Snap.m_pLocalCharacter); @@ -797,26 +795,24 @@ void CHud::OnRender() RenderScoreHud(); RenderWarmupTimer(); RenderTextInfo(); - RenderLocalTime((m_Width/7)*3); + RenderLocalTime((m_Width / 7) * 3); if(Client()->State() != IClient::STATE_DEMOPLAYBACK) RenderConnectionWarning(); RenderTeambalanceWarning(); RenderVoting(); if(g_Config.m_ClShowRecord) RenderRecord(); - } RenderCursor(); - static int LastChangeTick = 0; - if (LastChangeTick != Client()->PredGameTick(g_Config.m_ClDummy)) + if(LastChangeTick != Client()->PredGameTick(g_Config.m_ClDummy)) { m_DDRaceTick += 100 / Client()->GameTickSpeed(); LastChangeTick = Client()->PredGameTick(g_Config.m_ClDummy); } - if (m_DDRaceTick >= 100) + if(m_DDRaceTick >= 100) m_DDRaceTick = 0; } @@ -837,7 +833,7 @@ void CHud::OnMessage(int MsgType, void *pRawMsg) if(pMsg->m_Check) { - m_CheckpointDiff = (float)pMsg->m_Check/100; + m_CheckpointDiff = (float)pMsg->m_Check / 100; m_CheckpointTick = Client()->GameTick(g_Config.m_ClDummy); } } @@ -866,14 +862,14 @@ void CHud::OnMessage(int MsgType, void *pRawMsg) if(pMsg->m_PlayerTimeBest) // Second value: m_Check { - m_CheckpointDiff = (float)pMsg->m_PlayerTimeBest/100; + m_CheckpointDiff = (float)pMsg->m_PlayerTimeBest / 100; m_CheckpointTick = Client()->GameTick(g_Config.m_ClDummy); } } else if(GameClient()->m_GameInfo.m_RaceRecordMessage) { - m_ServerRecord = (float)pMsg->m_ServerTimeBest/100; - m_PlayerRecord[g_Config.m_ClDummy] = (float)pMsg->m_PlayerTimeBest/100; + m_ServerRecord = (float)pMsg->m_ServerTimeBest / 100; + m_PlayerRecord[g_Config.m_ClDummy] = (float)pMsg->m_PlayerTimeBest / 100; } } } @@ -881,7 +877,7 @@ void CHud::OnMessage(int MsgType, void *pRawMsg) void CHud::RenderDDRaceEffects() { // check racestate - if(m_FinishTime && m_LastReceivedTimeTick + Client()->GameTickSpeed()*2 < Client()->GameTick(g_Config.m_ClDummy)) + if(m_FinishTime && m_LastReceivedTimeTick + Client()->GameTickSpeed() * 2 < Client()->GameTick(g_Config.m_ClDummy)) { m_FinishTime = false; m_DDRaceTimeReceived = false; @@ -893,33 +889,33 @@ void CHud::RenderDDRaceEffects() char aBuf[64]; if(m_FinishTime) { - str_format(aBuf, sizeof(aBuf), "Finish time: %02d:%02d.%02d", m_DDRaceTime/6000, m_DDRaceTime/100-m_DDRaceTime/6000 * 60, m_DDRaceTime % 100); - TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0, 12, aBuf, -1, -1.0f)/2, 20, 12, aBuf, -1.0f); + str_format(aBuf, sizeof(aBuf), "Finish time: %02d:%02d.%02d", m_DDRaceTime / 6000, m_DDRaceTime / 100 - m_DDRaceTime / 6000 * 60, m_DDRaceTime % 100); + TextRender()->Text(0, 150 * Graphics()->ScreenAspect() - TextRender()->TextWidth(0, 12, aBuf, -1, -1.0f) / 2, 20, 12, aBuf, -1.0f); } - else if(m_CheckpointTick + Client()->GameTickSpeed()*6 > Client()->GameTick(g_Config.m_ClDummy)) + else if(m_CheckpointTick + Client()->GameTickSpeed() * 6 > Client()->GameTick(g_Config.m_ClDummy)) { str_format(aBuf, sizeof(aBuf), "%+5.2f", m_CheckpointDiff); // calculate alpha (4 sec 1 than get lower the next 2 sec) float a = 1.0f; - if(m_CheckpointTick+Client()->GameTickSpeed()*4 < Client()->GameTick(g_Config.m_ClDummy) && m_CheckpointTick+Client()->GameTickSpeed()*6 > Client()->GameTick(g_Config.m_ClDummy)) + if(m_CheckpointTick + Client()->GameTickSpeed() * 4 < Client()->GameTick(g_Config.m_ClDummy) && m_CheckpointTick + Client()->GameTickSpeed() * 6 > Client()->GameTick(g_Config.m_ClDummy)) { // lower the alpha slowly to blend text out - a = ((float)(m_CheckpointTick+Client()->GameTickSpeed()*6) - (float)Client()->GameTick(g_Config.m_ClDummy)) / (float)(Client()->GameTickSpeed()*2); + a = ((float)(m_CheckpointTick + Client()->GameTickSpeed() * 6) - (float)Client()->GameTick(g_Config.m_ClDummy)) / (float)(Client()->GameTickSpeed() * 2); } if(m_CheckpointDiff > 0) - TextRender()->TextColor(1.0f,0.5f,0.5f,a); // red + TextRender()->TextColor(1.0f, 0.5f, 0.5f, a); // red else if(m_CheckpointDiff < 0) - TextRender()->TextColor(0.5f,1.0f,0.5f,a); // green + TextRender()->TextColor(0.5f, 1.0f, 0.5f, a); // green else if(!m_CheckpointDiff) - TextRender()->TextColor(1,1,1,a); // white - TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0, 10, aBuf, -1, -1.0f)/2, 20, 10, aBuf, -1.0f); + TextRender()->TextColor(1, 1, 1, a); // white + TextRender()->Text(0, 150 * Graphics()->ScreenAspect() - TextRender()->TextWidth(0, 10, aBuf, -1, -1.0f) / 2, 20, 10, aBuf, -1.0f); - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); } } - /*else if(m_DDRaceTimeReceived) + /*else if(m_DDRaceTimeReceived) { str_format(aBuf, sizeof(aBuf), "%02d:%02d.%d", m_DDRaceTime/60, m_DDRaceTime%60, m_DDRaceTick/10); TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0, 12, "00:00.0", -1, -1.0f)/2, 20, 12, aBuf, -1.0f); // use fixed value for text width so its not shaky @@ -928,22 +924,22 @@ void CHud::RenderDDRaceEffects() void CHud::RenderRecord() { - if(m_ServerRecord > 0 ) + if(m_ServerRecord > 0) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), Localize("Server best:")); TextRender()->Text(0, 5, 40, 6, aBuf, -1.0f); - str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)m_ServerRecord/60, m_ServerRecord-((int)m_ServerRecord/60*60)); + str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)m_ServerRecord / 60, m_ServerRecord - ((int)m_ServerRecord / 60 * 60)); TextRender()->Text(0, 53, 40, 6, aBuf, -1.0f); } const float PlayerRecord = m_PlayerRecord[g_Config.m_ClDummy]; - if(PlayerRecord > 0 ) + if(PlayerRecord > 0) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), Localize("Personal best:")); TextRender()->Text(0, 5, 47, 6, aBuf, -1.0f); - str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)PlayerRecord/60, PlayerRecord-((int)PlayerRecord/60*60)); + str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)PlayerRecord / 60, PlayerRecord - ((int)PlayerRecord / 60 * 60)); TextRender()->Text(0, 53, 47, 6, aBuf, -1.0f); } } diff --git a/src/game/client/components/hud.h b/src/game/client/components/hud.h index 87b33c772..e3f75df5c 100644 --- a/src/game/client/components/hud.h +++ b/src/game/client/components/hud.h @@ -10,7 +10,7 @@ struct SScoreInfo { Reset(); } - + void Reset() { m_TextRankContainerIndex = m_TextScoreContainerIndex = m_RoundRectQuadContainerIndex = m_OptionalNameTextContainerIndex = -1; @@ -61,6 +61,7 @@ class CHud : public CComponent void RenderLocalTime(float x); void MapscreenToGroup(float CenterX, float CenterY, struct CMapItemGroup *PGroup); + public: CHud(); @@ -75,7 +76,6 @@ public: virtual void OnMessage(int MsgType, void *pRawMsg); private: - void RenderRecord(); void RenderDDRaceEffects(); float m_CheckpointDiff; diff --git a/src/game/client/components/items.cpp b/src/game/client/components/items.cpp index 729d64d2d..b73fb41cb 100644 --- a/src/game/client/components/items.cpp +++ b/src/game/client/components/items.cpp @@ -1,18 +1,18 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include -#include -#include +#include #include +#include +#include -#include #include -#include #include +#include +#include -#include #include +#include #include "items.h" @@ -48,14 +48,14 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) LocalPlayerInGame = m_pClient->m_aClients[m_pClient->m_Snap.m_pLocalInfo->m_ClientID].m_Team != -1; static float s_LastGameTickTime = Client()->GameTickTime(g_Config.m_ClDummy); - if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) s_LastGameTickTime = Client()->GameTickTime(g_Config.m_ClDummy); float Ct; if(m_pClient->Predict() && m_pClient->AntiPingGrenade() && LocalPlayerInGame && !(Client()->State() == IClient::STATE_DEMOPLAYBACK)) - Ct = ((float)(Client()->PredGameTick(g_Config.m_ClDummy) - 1 - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy))/(float)SERVER_TICK_SPEED; + Ct = ((float)(Client()->PredGameTick(g_Config.m_ClDummy) - 1 - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy)) / (float)SERVER_TICK_SPEED; else - Ct = (Client()->PrevGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; + Ct = (Client()->PrevGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) / (float)SERVER_TICK_SPEED + s_LastGameTickTime; if(Ct < 0) return; // projectile haven't been shot yet @@ -65,7 +65,7 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) ExtractInfo(pCurrent, &StartPos, &StartVel); vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct); - vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct-0.001f); + vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct - 0.001f); float Alpha = 1.f; if(UseExtraInfo(pCurrent)) @@ -81,13 +81,13 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) int QuadOffset = 2 + 4 + NUM_WEAPONS + clamp(pCurrent->m_Type, 0, NUM_WEAPONS - 1); - vec2 Vel = Pos-PrevPos; + vec2 Vel = Pos - PrevPos; //vec2 pos = mix(vec2(prev->x, prev->y), vec2(current->x, current->y), Client()->IntraGameTick(g_Config.m_ClDummy)); // add particle for this projectile if(pCurrent->m_Type == WEAPON_GRENADE) { - m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1, Alpha); + m_pClient->m_pEffects->SmokeTrail(Pos, Vel * -1, Alpha); static float s_Time = 0.0f; static float s_LastLocalTime = LocalTime(); @@ -95,15 +95,15 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) - s_Time += (LocalTime()-s_LastLocalTime)*pInfo->m_Speed; + s_Time += (LocalTime() - s_LastLocalTime) * pInfo->m_Speed; } else { - if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) - s_Time += LocalTime()-s_LastLocalTime; + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) + s_Time += LocalTime() - s_LastLocalTime; } - Graphics()->QuadsSetRotation(s_Time*pi*2*2 + ItemID); + Graphics()->QuadsSetRotation(s_Time * pi * 2 * 2 + ItemID); s_LastLocalTime = LocalTime(); } else @@ -114,7 +114,6 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) Graphics()->QuadsSetRotation(GetAngle(Vel)); else Graphics()->QuadsSetRotation(0); - } Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y); @@ -142,13 +141,12 @@ void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCu SPRITE_PICKUP_HEALTH, SPRITE_PICKUP_ARMOR, SPRITE_PICKUP_WEAPON, - SPRITE_PICKUP_NINJA - }; + SPRITE_PICKUP_NINJA}; QuadOffset += pCurrent->m_Type; if(c[pCurrent->m_Type] == SPRITE_PICKUP_NINJA) { - m_pClient->m_pEffects->PowerupShine(Pos, vec2(96,18)); + m_pClient->m_pEffects->PowerupShine(Pos, vec2(96, 18)); Pos.x -= 10.0f; } } @@ -157,20 +155,20 @@ void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCu static float s_Time = 0.0f; static float s_LastLocalTime = LocalTime(); - float Offset = Pos.y/32.0f + Pos.x/32.0f; + float Offset = Pos.y / 32.0f + Pos.x / 32.0f; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) - s_Time += (LocalTime()-s_LastLocalTime)*pInfo->m_Speed; + s_Time += (LocalTime() - s_LastLocalTime) * pInfo->m_Speed; } else { - if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) - s_Time += LocalTime()-s_LastLocalTime; + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) + s_Time += LocalTime() - s_LastLocalTime; } - Pos.x += cosf(s_Time*2.0f+Offset)*2.5f; - Pos.y += sinf(s_Time*2.0f+Offset)*2.5f; + Pos.x += cosf(s_Time * 2.0f + Offset) * 2.5f; + Pos.y += sinf(s_Time * 2.0f + Offset) * 2.5f; s_LastLocalTime = LocalTime(); Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y); @@ -203,30 +201,29 @@ void CItems::RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, // make sure that the flag isn't interpolated between capture and return if(pPrevGameData && ((pCurrent->m_Team == TEAM_RED && pPrevGameData->m_FlagCarrierRed != pCurGameData->m_FlagCarrierRed) || - (pCurrent->m_Team == TEAM_BLUE && pPrevGameData->m_FlagCarrierBlue != pCurGameData->m_FlagCarrierBlue))) + (pCurrent->m_Team == TEAM_BLUE && pPrevGameData->m_FlagCarrierBlue != pCurGameData->m_FlagCarrierBlue))) Pos = vec2(pCurrent->m_X, pCurrent->m_Y); } - Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y-Size*0.75f); + Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y - Size * 0.75f); } - void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent, bool IsPredicted) { ColorRGBA RGB; vec2 Pos = vec2(pCurrent->m_X, pCurrent->m_Y); vec2 From = vec2(pCurrent->m_FromX, pCurrent->m_FromY); - vec2 Dir = normalize(Pos-From); + vec2 Dir = normalize(Pos - From); float Ticks; if(IsPredicted) Ticks = (float)(Client()->PredGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy); else Ticks = (float)(Client()->GameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) + Client()->IntraGameTick(g_Config.m_ClDummy); - float Ms = (Ticks/50.0f) * 1000.0f; + float Ms = (Ticks / 50.0f) * 1000.0f; float a = Ms / m_pClient->m_Tuning[g_Config.m_ClDummy].m_LaserBounceDelay; a = clamp(a, 0.0f, 1.0f); - float Ia = 1-a; + float Ia = 1 - a; vec2 Out, Border; @@ -237,26 +234,26 @@ void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent, bool IsPredicted) RGB = color_cast(ColorHSLA(g_Config.m_ClLaserOutlineColor)); ColorRGBA OuterColor(RGB.r, RGB.g, RGB.b, 1.0f); Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); - Out = vec2(Dir.y, -Dir.x) * (7.0f*Ia); + Out = vec2(Dir.y, -Dir.x) * (7.0f * Ia); IGraphics::CFreeformItem Freeform( - From.x-Out.x, From.y-Out.y, - From.x+Out.x, From.y+Out.y, - Pos.x-Out.x, Pos.y-Out.y, - Pos.x+Out.x, Pos.y+Out.y); + From.x - Out.x, From.y - Out.y, + From.x + Out.x, From.y + Out.y, + Pos.x - Out.x, Pos.y - Out.y, + Pos.x + Out.x, Pos.y + Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); // do inner RGB = color_cast(ColorHSLA(g_Config.m_ClLaserInnerColor)); ColorRGBA InnerColor(RGB.r, RGB.g, RGB.b, 1.0f); - Out = vec2(Dir.y, -Dir.x) * (5.0f*Ia); + Out = vec2(Dir.y, -Dir.x) * (5.0f * Ia); Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); // center Freeform = IGraphics::CFreeformItem( - From.x-Out.x, From.y-Out.y, - From.x+Out.x, From.y+Out.y, - Pos.x-Out.x, Pos.y-Out.y, - Pos.x+Out.x, Pos.y+Out.y); + From.x - Out.x, From.y - Out.y, + From.x + Out.x, From.y + Out.y, + Pos.x - Out.x, Pos.y - Out.y, + Pos.x + Out.x, Pos.y + Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); Graphics()->QuadsEnd(); @@ -270,7 +267,7 @@ void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent, bool IsPredicted) Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y); Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); - Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y, 20.f/24.f, 20.f / 24.f); + Graphics()->RenderQuadContainerAsSprite(m_ItemsQuadContainerIndex, QuadOffset, Pos.x, Pos.y, 20.f / 24.f, 20.f / 24.f); } } @@ -282,7 +279,7 @@ void CItems::OnRender() bool UsePredicted = GameClient()->Predict() && GameClient()->AntiPingGunfire(); if(UsePredicted) { - for(auto *pProj = (CProjectile*) GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_PROJECTILE); pProj; pProj = (CProjectile*) pProj->NextEntity()) + for(auto *pProj = (CProjectile *)GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_PROJECTILE); pProj; pProj = (CProjectile *)pProj->NextEntity()) { CNetObj_Projectile Data; if(pProj->m_Type != WEAPON_SHOTGUN || pProj->m_Explosive || pProj->m_Freeze) @@ -291,7 +288,7 @@ void CItems::OnRender() pProj->FillInfo(&Data); RenderProjectile(&Data, pProj->ID()); } - for(auto *pLaser = (CLaser*) GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_LASER); pLaser; pLaser = (CLaser*) pLaser->NextEntity()) + for(auto *pLaser = (CLaser *)GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_LASER); pLaser; pLaser = (CLaser *)pLaser->NextEntity()) { if(pLaser->GetOwner() < 0 || (pLaser->GetOwner() >= 0 && !GameClient()->m_aClients[pLaser->GetOwner()].m_IsPredictedLocal)) continue; @@ -299,9 +296,9 @@ void CItems::OnRender() pLaser->FillInfo(&Data); RenderLaser(&Data, true); } - for(auto *pPickup = (CPickup*) GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_PICKUP); pPickup; pPickup = (CPickup*) pPickup->NextEntity()) + for(auto *pPickup = (CPickup *)GameClient()->m_PredictedWorld.FindFirst(CGameWorld::ENTTYPE_PICKUP); pPickup; pPickup = (CPickup *)pPickup->NextEntity()) { - if(auto *pPrev = (CPickup*) GameClient()->m_PrevPredictedWorld.GetEntity(pPickup->ID(), CGameWorld::ENTTYPE_PICKUP)) + if(auto *pPrev = (CPickup *)GameClient()->m_PrevPredictedWorld.GetEntity(pPickup->ID(), CGameWorld::ENTTYPE_PICKUP)) { CNetObj_Pickup Data, Prev; pPickup->FillInfo(&Data); @@ -321,13 +318,12 @@ void CItems::OnRender() { if(UsePredicted) { - if(auto *pProj = (CProjectile*) GameClient()->m_GameWorld.FindMatch(Item.m_ID, Item.m_Type, pData)) + if(auto *pProj = (CProjectile *)GameClient()->m_GameWorld.FindMatch(Item.m_ID, Item.m_Type, pData)) { - if(pProj->m_LastRenderTick <= 0 - && (pProj->m_Type != WEAPON_SHOTGUN || (!pProj->m_Freeze && !pProj->m_Explosive)) // skip ddrace shotgun bullets - && (pProj->m_Type == WEAPON_SHOTGUN || fabs(length(pProj->m_Direction) - 1.f) < 0.02) // workaround to skip grenades on ball mod - && (pProj->GetOwner() < 0 || !GameClient()->m_aClients[pProj->GetOwner()].m_IsPredictedLocal) // skip locally predicted projectiles - && !Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID)) + if(pProj->m_LastRenderTick <= 0 && (pProj->m_Type != WEAPON_SHOTGUN || (!pProj->m_Freeze && !pProj->m_Explosive)) // skip ddrace shotgun bullets + && (pProj->m_Type == WEAPON_SHOTGUN || fabs(length(pProj->m_Direction) - 1.f) < 0.02) // workaround to skip grenades on ball mod + && (pProj->GetOwner() < 0 || !GameClient()->m_aClients[pProj->GetOwner()].m_IsPredictedLocal) // skip locally predicted projectiles + && !Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID)) { ReconstructSmokeTrail((const CNetObj_Projectile *)pData, Item.m_ID, pProj->m_DestroyTick); } @@ -349,7 +345,7 @@ void CItems::OnRender() { if(UsePredicted) { - auto *pLaser = (CLaser*) GameClient()->m_GameWorld.FindMatch(Item.m_ID, Item.m_Type, pData); + auto *pLaser = (CLaser *)GameClient()->m_GameWorld.FindMatch(Item.m_ID, Item.m_Type, pData); if(pLaser && pLaser->GetOwner() >= 0 && GameClient()->m_aClients[pLaser->GetOwner()].m_IsPredictedLocal) continue; } @@ -370,7 +366,7 @@ void CItems::OnRender() { const void *pPrevGameData = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_GAMEDATA, m_pClient->m_Snap.m_GameDataSnapID); RenderFlag(static_cast(pPrev), static_cast(pData), - static_cast(pPrevGameData), m_pClient->m_Snap.m_pGameDataObj); + static_cast(pPrevGameData), m_pClient->m_Snap.m_pGameDataObj); } } } @@ -380,7 +376,7 @@ void CItems::OnRender() { if(m_aExtraProjectiles[i].m_StartTick < Client()->GameTick(g_Config.m_ClDummy)) { - m_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles-1]; + m_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles - 1]; m_NumExtraProjectiles--; } else if(!UsePredicted) @@ -403,7 +399,6 @@ void CItems::OnInit() RenderTools()->SelectSprite(SPRITE_FLAG_BLUE); RenderTools()->QuadContainerAddSprite(m_ItemsQuadContainerIndex, -21.f, -42.f, 42.f, 84.f); - RenderTools()->SelectSprite(SPRITE_PICKUP_HEALTH); RenderTools()->QuadContainerAddSprite(m_ItemsQuadContainerIndex, 64.f); RenderTools()->SelectSprite(SPRITE_PICKUP_ARMOR); @@ -472,11 +467,11 @@ void CItems::ReconstructSmokeTrail(const CNetObj_Projectile *pCurrent, int ItemI Speed = m_pClient->m_Tuning[g_Config.m_ClDummy].m_GunSpeed; } - float Pt = ((float)(Client()->PredGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy))/(float)SERVER_TICK_SPEED; + float Pt = ((float)(Client()->PredGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy)) / (float)SERVER_TICK_SPEED; if(Pt < 0) return; // projectile haven't been shot yet - float Gt = (Client()->PrevGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime(g_Config.m_ClDummy); + float Gt = (Client()->PrevGameTick(g_Config.m_ClDummy) - pCurrent->m_StartTick) / (float)SERVER_TICK_SPEED + Client()->GameTickTime(g_Config.m_ClDummy); vec2 StartPos; vec2 StartVel; @@ -494,22 +489,22 @@ void CItems::ReconstructSmokeTrail(const CNetObj_Projectile *pCurrent, int ItemI float T = Pt; if(DestroyTick >= 0) - T = minimum(Pt, ((float)(DestroyTick - 1 - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy))/(float)SERVER_TICK_SPEED); + T = minimum(Pt, ((float)(DestroyTick - 1 - pCurrent->m_StartTick) + Client()->PredIntraGameTick(g_Config.m_ClDummy)) / (float)SERVER_TICK_SPEED); float MinTrailSpan = 0.4f * ((pCurrent->m_Type == WEAPON_GRENADE) ? 0.5f : 0.25f); float Step = maximum(Client()->FrameTimeAvg(), (pCurrent->m_Type == WEAPON_GRENADE) ? 0.02f : 0.01f); - for(int i = 1+(int)(Gt/Step); i < (int)(T/Step); i++) + for(int i = 1 + (int)(Gt / Step); i < (int)(T / Step); i++) { float t = Step * (float)i + 0.4f * Step * (frandom() - 0.5f); vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, t); - vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, t-0.001f); - vec2 Vel = Pos-PrevPos; - float TimePassed = Pt-t; + vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, t - 0.001f); + vec2 Vel = Pos - PrevPos; + float TimePassed = Pt - t; if(Pt - MinTrailSpan > 0.01f) - TimePassed = minimum(TimePassed, (TimePassed-MinTrailSpan)/(Pt - MinTrailSpan)*(MinTrailSpan * 0.5f) + MinTrailSpan); + TimePassed = minimum(TimePassed, (TimePassed - MinTrailSpan) / (Pt - MinTrailSpan) * (MinTrailSpan * 0.5f) + MinTrailSpan); // add particle for this projectile if(pCurrent->m_Type == WEAPON_GRENADE) - m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1, Alpha, TimePassed); + m_pClient->m_pEffects->SmokeTrail(Pos, Vel * -1, Alpha, TimePassed); else m_pClient->m_pEffects->BulletTrail(Pos, Alpha, TimePassed); } diff --git a/src/game/client/components/items.h b/src/game/client/components/items.h index c05aec8f4..f380c96f9 100644 --- a/src/game/client/components/items.h +++ b/src/game/client/components/items.h @@ -8,7 +8,7 @@ class CItems : public CComponent { enum { - MAX_EXTRA_PROJECTILES=32, + MAX_EXTRA_PROJECTILES = 32, }; CNetObj_Projectile m_aExtraProjectiles[MAX_EXTRA_PROJECTILES]; @@ -20,6 +20,7 @@ class CItems : public CComponent void RenderLaser(const struct CNetObj_Laser *pCurrent, bool IsPredicted = false); int m_ItemsQuadContainerIndex; + public: virtual void OnReset(); virtual void OnRender(); diff --git a/src/game/client/components/killmessages.cpp b/src/game/client/components/killmessages.cpp index 858418bb9..09d3763da 100644 --- a/src/game/client/components/killmessages.cpp +++ b/src/game/client/components/killmessages.cpp @@ -1,14 +1,14 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include -#include -#include #include +#include +#include +#include -#include -#include #include "killmessages.h" +#include +#include void CKillMessages::OnWindowResize() { @@ -25,7 +25,7 @@ void CKillMessages::OnWindowResize() void CKillMessages::OnReset() { m_KillmsgCurrent = 0; - for (int i = 0; i < MAX_KILLMSGS; i++) + for(int i = 0; i < MAX_KILLMSGS; i++) { m_aKillmsgs[i].m_Tick = -100000; @@ -35,7 +35,6 @@ void CKillMessages::OnReset() if(m_aKillmsgs[i].m_KillerTextContainerIndex != -1) TextRender()->DeleteTextContainer(m_aKillmsgs[i].m_KillerTextContainerIndex); - m_aKillmsgs[i].m_VictimTextContainerIndex = m_aKillmsgs[i].m_KillerTextContainerIndex = -1; } } @@ -89,10 +88,10 @@ void CKillMessages::OnMessage(int MsgType, void *pRawMsg) Kill.m_VitctimTextWidth = Kill.m_KillerTextWidth = 0.f; - float Width = 400 * 3.0f*Graphics()->ScreenAspect(); + float Width = 400 * 3.0f * Graphics()->ScreenAspect(); float Height = 400 * 3.0f; - Graphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f); + Graphics()->MapScreen(0, 0, Width * 1.5f, Height * 1.5f); float FontSize = 36.0f; if(Kill.m_aVictimName[0] != 0) @@ -118,7 +117,7 @@ void CKillMessages::OnMessage(int MsgType, void *pRawMsg) } // add the message - m_KillmsgCurrent = (m_KillmsgCurrent+1)%MAX_KILLMSGS; + m_KillmsgCurrent = (m_KillmsgCurrent + 1) % MAX_KILLMSGS; if(m_aKillmsgs[m_KillmsgCurrent].m_VictimTextContainerIndex != -1) { @@ -141,19 +140,19 @@ void CKillMessages::OnRender() if(!g_Config.m_ClShowKillMessages) return; - float Width = 400*3.0f*Graphics()->ScreenAspect(); - float Height = 400*3.0f; + float Width = 400 * 3.0f * Graphics()->ScreenAspect(); + float Height = 400 * 3.0f; - Graphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f); + Graphics()->MapScreen(0, 0, Width * 1.5f, Height * 1.5f); Graphics()->SetColor(1.f, 1.f, 1.f, 1.f); - float StartX = Width*1.5f-10.0f; + float StartX = Width * 1.5f - 10.0f; float y = 30.0f + 100.0f * ((g_Config.m_ClShowfps ? 1 : 0) + g_Config.m_ClShowpred); for(int i = 1; i <= MAX_KILLMSGS; i++) { - int r = (m_KillmsgCurrent+i)%MAX_KILLMSGS; - if(Client()->GameTick(g_Config.m_ClDummy) > m_aKillmsgs[r].m_Tick+50*10) + int r = (m_KillmsgCurrent + i) % MAX_KILLMSGS; + if(Client()->GameTick(g_Config.m_ClDummy) > m_aKillmsgs[r].m_Tick + 50 * 10) continue; float x = StartX; @@ -175,20 +174,20 @@ void CKillMessages::OnRender() // render victim tee x -= 24.0f; - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_FLAGS) { - if(m_aKillmsgs[r].m_ModeSpecial&1) + if(m_aKillmsgs[r].m_ModeSpecial & 1) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); int QuadOffset = 0; if(m_aKillmsgs[r].m_VictimID == m_aKillmsgs[r].m_FlagCarrierBlue) ++QuadOffset; - Graphics()->RenderQuadContainerAsSprite(m_SpriteQuadContainerIndex, QuadOffset, x, y-16); + Graphics()->RenderQuadContainerAsSprite(m_SpriteQuadContainerIndex, QuadOffset, x, y - 16); } } - RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1,0), vec2(x, y+28)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1, 0), vec2(x, y + 28)); x -= 32.0f; // render weapon @@ -202,9 +201,9 @@ void CKillMessages::OnRender() if(m_aKillmsgs[r].m_VictimID != m_aKillmsgs[r].m_KillerID) { - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_FLAGS) { - if(m_aKillmsgs[r].m_ModeSpecial&2) + if(m_aKillmsgs[r].m_ModeSpecial & 2) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); @@ -218,7 +217,7 @@ void CKillMessages::OnRender() // render killer tee x -= 24.0f; - RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1, 0), vec2(x, y + 28)); x -= 32.0f; // render killer name diff --git a/src/game/client/components/killmessages.h b/src/game/client/components/killmessages.h index 438dd272b..3cfbf5c20 100644 --- a/src/game/client/components/killmessages.h +++ b/src/game/client/components/killmessages.h @@ -7,6 +7,7 @@ class CKillMessages : public CComponent { int m_SpriteQuadContainerIndex; + public: // kill messages struct CKillMsg diff --git a/src/game/client/components/mapimages.cpp b/src/game/client/components/mapimages.cpp index fe54f5acf..c4df0d4ef 100644 --- a/src/game/client/components/mapimages.cpp +++ b/src/game/client/components/mapimages.cpp @@ -2,19 +2,20 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include #include -#include #include -#include +#include #include +#include #include #include "mapimages.h" -CMapImages::CMapImages() : CMapImages(100) +CMapImages::CMapImages() : + CMapImages(100) { } -CMapImages::CMapImages(int TextureSize) +CMapImages::CMapImages(int TextureSize) { m_Count = 0; m_TextureScale = TextureSize; @@ -55,7 +56,7 @@ void CMapImages::OnMapLoadImpl(class CLayers *pLayers, IMap *pMap) for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer + l); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTLayer = (CMapItemLayerTilemap *)pLayer; @@ -81,7 +82,7 @@ void CMapImages::OnMapLoadImpl(class CLayers *pLayers, IMap *pMap) for(int i = 0; i < m_Count; i++) { int LoadFlag = (((m_aTextureUsedByTileOrQuadLayerFlag[i] & 1) != 0) ? TextureLoadFlag : 0) | (((m_aTextureUsedByTileOrQuadLayerFlag[i] & 2) != 0) ? 0 : (Graphics()->IsTileBufferingEnabled() ? IGraphics::TEXLOAD_NO_2D_TEXTURE : 0)); - CMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0); + CMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start + i, 0, 0); if(pImg->m_External) { char Buf[256]; @@ -371,7 +372,7 @@ int CMapImages::GetTextureScale() } IGraphics::CTextureHandle CMapImages::UploadEntityLayerText(int TextureSize, int MaxWidth, int YOffset) -{ +{ void *pMem = calloc(1024 * 1024 * 4, 1); UpdateEntityLayerText(pMem, 4, 1024, 1024, TextureSize, MaxWidth, YOffset, 0); @@ -385,10 +386,10 @@ IGraphics::CTextureHandle CMapImages::UploadEntityLayerText(int TextureSize, int return Texture; } -void CMapImages::UpdateEntityLayerText(void* pTexBuffer, int ImageColorChannelCount, int TexWidth, int TexHeight, int TextureSize, int MaxWidth, int YOffset, int NumbersPower, int MaxNumber) +void CMapImages::UpdateEntityLayerText(void *pTexBuffer, int ImageColorChannelCount, int TexWidth, int TexHeight, int TextureSize, int MaxWidth, int YOffset, int NumbersPower, int MaxNumber) { char aBuf[4]; - int DigitsCount = NumbersPower+1; + int DigitsCount = NumbersPower + 1; int CurrentNumber = pow(10, NumbersPower); @@ -402,12 +403,12 @@ void CMapImages::UpdateEntityLayerText(void* pTexBuffer, int ImageColorChannelCo YOffset += ((TextureSize - UniversalSuitableFontSize) / 2); - for (; CurrentNumber <= MaxNumber; ++CurrentNumber) + for(; CurrentNumber <= MaxNumber; ++CurrentNumber) { str_format(aBuf, 4, "%d", CurrentNumber); - float x = (CurrentNumber%16)*64; - float y = (CurrentNumber/16)*64; + float x = (CurrentNumber % 16) * 64; + float y = (CurrentNumber / 16) * 64; int ApproximateTextWidth = TextRender()->CalculateTextWidth(aBuf, DigitsCount, 0, UniversalSuitableFontSize); int XOffSet = (MaxWidth - clamp(ApproximateTextWidth, 0, MaxWidth)) / 2; @@ -418,17 +419,17 @@ void CMapImages::UpdateEntityLayerText(void* pTexBuffer, int ImageColorChannelCo void CMapImages::InitOverlayTextures() { - int TextureSize = 64*m_TextureScale/100; - int TextureToVerticalCenterOffset = (64-TextureSize)/2; // should be used to move texture to the center of 64 pixels area - + int TextureSize = 64 * m_TextureScale / 100; + int TextureToVerticalCenterOffset = (64 - TextureSize) / 2; // should be used to move texture to the center of 64 pixels area + if(m_OverlayBottomTexture == -1) { - m_OverlayBottomTexture = UploadEntityLayerText(TextureSize/2, 64, 32+TextureToVerticalCenterOffset/2); + m_OverlayBottomTexture = UploadEntityLayerText(TextureSize / 2, 64, 32 + TextureToVerticalCenterOffset / 2); } if(m_OverlayTopTexture == -1) { - m_OverlayTopTexture = UploadEntityLayerText(TextureSize/2, 64, TextureToVerticalCenterOffset/2); + m_OverlayTopTexture = UploadEntityLayerText(TextureSize / 2, 64, TextureToVerticalCenterOffset / 2); } if(m_OverlayCenterTexture == -1) diff --git a/src/game/client/components/mapimages.h b/src/game/client/components/mapimages.h index 46c1f3ea0..92b081dcf 100644 --- a/src/game/client/components/mapimages.h +++ b/src/game/client/components/mapimages.h @@ -79,7 +79,7 @@ private: void InitOverlayTextures(); IGraphics::CTextureHandle UploadEntityLayerText(int TextureSize, int MaxWidth, int YOffset); - void UpdateEntityLayerText(void* pTexBuffer, int ImageColorChannelCount, int TexWidth, int TexHeight, int TextureSize, int MaxWidth, int YOffset, int NumbersPower, int MaxNumber = -1); + void UpdateEntityLayerText(void *pTexBuffer, int ImageColorChannelCount, int TexWidth, int TexHeight, int TextureSize, int MaxWidth, int YOffset, int NumbersPower, int MaxNumber = -1); }; #endif diff --git a/src/game/client/components/maplayers.cpp b/src/game/client/components/maplayers.cpp index 79ffc417d..5c7b9d5f0 100644 --- a/src/game/client/components/maplayers.cpp +++ b/src/game/client/components/maplayers.cpp @@ -1,16 +1,16 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include #include #include -#include #include #include #include -#include -#include #include +#include #include +#include #include #include @@ -51,7 +51,6 @@ void CMapLayers::EnvelopeUpdate() } } - void CMapLayers::MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup, float Zoom) { float Points[4]; @@ -83,7 +82,7 @@ void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void if(Env >= Num) return; - CMapItemEnvelope *pItem = (CMapItemEnvelope *)pThis->m_pLayers->Map()->GetItem(Start+Env, 0, 0); + CMapItemEnvelope *pItem = (CMapItemEnvelope *)pThis->m_pLayers->Map()->GetItem(Start + Env, 0, 0); static float s_Time = 0.0f; static float s_LastLocalTime = pThis->LocalTime(); @@ -100,18 +99,18 @@ void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void } if(pItem->m_Version < 2 || pItem->m_Synchronized) { - s_Time = mix((pThis->Client()->PrevGameTick(g_Config.m_ClDummy)-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), - (pThis->Client()->GameTick(g_Config.m_ClDummy)-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), - pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); + s_Time = mix((pThis->Client()->PrevGameTick(g_Config.m_ClDummy) - pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + (pThis->Client()->GameTick(g_Config.m_ClDummy) - pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); } else { s_Time = mix(pThis->m_LastLocalTick / (float)pThis->Client()->GameTickSpeed(), - pThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(), - pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); + pThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(), + pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); } } - pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); + pThis->RenderTools()->RenderEvalEnvelope(pPoints + pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time + TimeOffset, pChannels); } else { @@ -119,9 +118,9 @@ void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void { if(pThis->m_OnlineOnly && pThis->m_pClient->m_Snap.m_pGameInfoObj) // && !(pThis->m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) { - s_Time = mix((pThis->Client()->PrevGameTick(g_Config.m_ClDummy)-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), - (pThis->Client()->GameTick(g_Config.m_ClDummy)-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), - pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); + s_Time = mix((pThis->Client()->PrevGameTick(g_Config.m_ClDummy) - pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + (pThis->Client()->GameTick(g_Config.m_ClDummy) - pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + pThis->Client()->IntraGameTick(g_Config.m_ClDummy)); } } else if(pThis->m_OnlineOnly) @@ -139,7 +138,7 @@ void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void } } -void FillTmpTileSpeedup(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool As3DTextureCoord, unsigned char Flags, unsigned char Index, int x, int y, int Scale, CMapItemGroup* pGroup, short AngleRotate) +void FillTmpTileSpeedup(SGraphicTile *pTmpTile, SGraphicTileTexureCoords *pTmpTex, bool As3DTextureCoord, unsigned char Flags, unsigned char Index, int x, int y, int Scale, CMapItemGroup *pGroup, short AngleRotate) { if(pTmpTex) { @@ -178,38 +177,38 @@ void FillTmpTileSpeedup(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTe } //same as in rotate from Graphics() - float Angle = (float)AngleRotate*(3.14159265f/180.0f); + float Angle = (float)AngleRotate * (3.14159265f / 180.0f); float c = cosf(Angle); float s = sinf(Angle); float xR, yR; int i; int ScaleSmaller = 2; - pTmpTile->m_TopLeft.x = x*Scale + ScaleSmaller; - pTmpTile->m_TopLeft.y = y*Scale + ScaleSmaller; - pTmpTile->m_BottomLeft.x = x*Scale + ScaleSmaller; - pTmpTile->m_BottomLeft.y = y*Scale + Scale - ScaleSmaller; - pTmpTile->m_TopRight.x = x*Scale + Scale - ScaleSmaller; - pTmpTile->m_TopRight.y = y*Scale + ScaleSmaller; - pTmpTile->m_BottomRight.x = x*Scale + Scale - ScaleSmaller; - pTmpTile->m_BottomRight.y = y*Scale + Scale - ScaleSmaller; + pTmpTile->m_TopLeft.x = x * Scale + ScaleSmaller; + pTmpTile->m_TopLeft.y = y * Scale + ScaleSmaller; + pTmpTile->m_BottomLeft.x = x * Scale + ScaleSmaller; + pTmpTile->m_BottomLeft.y = y * Scale + Scale - ScaleSmaller; + pTmpTile->m_TopRight.x = x * Scale + Scale - ScaleSmaller; + pTmpTile->m_TopRight.y = y * Scale + ScaleSmaller; + pTmpTile->m_BottomRight.x = x * Scale + Scale - ScaleSmaller; + pTmpTile->m_BottomRight.y = y * Scale + Scale - ScaleSmaller; - float* pTmpTileVertices = (float*)pTmpTile; + float *pTmpTileVertices = (float *)pTmpTile; vec2 Center; - Center.x = pTmpTile->m_TopLeft.x + (Scale-ScaleSmaller)/2.f; - Center.y = pTmpTile->m_TopLeft.y + (Scale-ScaleSmaller)/2.f; + Center.x = pTmpTile->m_TopLeft.x + (Scale - ScaleSmaller) / 2.f; + Center.y = pTmpTile->m_TopLeft.y + (Scale - ScaleSmaller) / 2.f; for(i = 0; i < 4; i++) { - xR = pTmpTileVertices[i*2] - Center.x; - yR = pTmpTileVertices[i*2+1] - Center.y; - pTmpTileVertices[i*2] = xR * c - yR * s + Center.x; - pTmpTileVertices[i*2+1] = xR * s + yR * c + Center.y; + xR = pTmpTileVertices[i * 2] - Center.x; + yR = pTmpTileVertices[i * 2 + 1] - Center.y; + pTmpTileVertices[i * 2] = xR * c - yR * s + Center.x; + pTmpTileVertices[i * 2 + 1] = xR * s + yR * c + Center.y; } } -void FillTmpTile(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool As3DTextureCoord, unsigned char Flags, unsigned char Index, int x, int y, int Scale, CMapItemGroup* pGroup) +void FillTmpTile(SGraphicTile *pTmpTile, SGraphicTileTexureCoords *pTmpTex, bool As3DTextureCoord, unsigned char Flags, unsigned char Index, int x, int y, int Scale, CMapItemGroup *pGroup) { if(pTmpTex) { @@ -222,7 +221,7 @@ void FillTmpTile(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool unsigned char x3 = x0; unsigned char y3 = y0 + 1; - if(Flags&TILEFLAG_VFLIP) + if(Flags & TILEFLAG_VFLIP) { x0 = x2; x1 = x3; @@ -230,7 +229,7 @@ void FillTmpTile(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool x3 = x0; } - if(Flags&TILEFLAG_HFLIP) + if(Flags & TILEFLAG_HFLIP) { y0 = y3; y2 = y1; @@ -238,7 +237,7 @@ void FillTmpTile(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool y1 = y0; } - if(Flags&TILEFLAG_ROTATE) + if(Flags & TILEFLAG_ROTATE) { unsigned char Tmp = x0; x0 = x3; @@ -277,14 +276,14 @@ void FillTmpTile(SGraphicTile* pTmpTile, SGraphicTileTexureCoords* pTmpTex, bool } } - pTmpTile->m_TopLeft.x = x*Scale; - pTmpTile->m_TopLeft.y = y*Scale; - pTmpTile->m_BottomLeft.x = x*Scale; - pTmpTile->m_BottomLeft.y = y*Scale + Scale; - pTmpTile->m_TopRight.x = x*Scale + Scale; - pTmpTile->m_TopRight.y = y*Scale; - pTmpTile->m_BottomRight.x = x*Scale + Scale; - pTmpTile->m_BottomRight.y = y*Scale + Scale; + pTmpTile->m_TopLeft.x = x * Scale; + pTmpTile->m_TopLeft.y = y * Scale; + pTmpTile->m_BottomLeft.x = x * Scale; + pTmpTile->m_BottomLeft.y = y * Scale + Scale; + pTmpTile->m_TopRight.x = x * Scale + Scale; + pTmpTile->m_TopRight.y = y * Scale; + pTmpTile->m_BottomRight.x = x * Scale + Scale; + pTmpTile->m_BottomRight.y = y * Scale + Scale; } bool CMapLayers::STileLayerVisuals::Init(unsigned int Width, unsigned int Height) @@ -294,17 +293,17 @@ bool CMapLayers::STileLayerVisuals::Init(unsigned int Width, unsigned int Height if(Width == 0 || Height == 0) return false; - m_TilesOfLayer = new CMapLayers::STileLayerVisuals::STileVisual[Height*Width]; + m_TilesOfLayer = new CMapLayers::STileLayerVisuals::STileVisual[Height * Width]; if(Width > 2) { - m_BorderTop = new CMapLayers::STileLayerVisuals::STileVisual[Width-2]; - m_BorderBottom = new CMapLayers::STileLayerVisuals::STileVisual[Width-2]; + m_BorderTop = new CMapLayers::STileLayerVisuals::STileVisual[Width - 2]; + m_BorderBottom = new CMapLayers::STileLayerVisuals::STileVisual[Width - 2]; } if(Height > 2) { - m_BorderLeft = new CMapLayers::STileLayerVisuals::STileVisual[Height-2]; - m_BorderRight = new CMapLayers::STileLayerVisuals::STileVisual[Height-2]; + m_BorderLeft = new CMapLayers::STileLayerVisuals::STileVisual[Height - 2]; + m_BorderRight = new CMapLayers::STileLayerVisuals::STileVisual[Height - 2]; } return true; } @@ -332,17 +331,17 @@ CMapLayers::STileLayerVisuals::~STileLayerVisuals() m_BorderRight = NULL; } -bool AddTile(std::vector& TmpTiles, std::vector& TmpTileTexCoords, bool As3DTextureCoord, unsigned char Index, unsigned char Flags, int x, int y, CMapItemGroup* pGroup, bool DoTextureCoords, bool FillSpeedup = false, int AngleRotate = -1) +bool AddTile(std::vector &TmpTiles, std::vector &TmpTileTexCoords, bool As3DTextureCoord, unsigned char Index, unsigned char Flags, int x, int y, CMapItemGroup *pGroup, bool DoTextureCoords, bool FillSpeedup = false, int AngleRotate = -1) { if(Index) { TmpTiles.push_back(SGraphicTile()); - SGraphicTile& Tile = TmpTiles.back(); - SGraphicTileTexureCoords* pTileTex = NULL; + SGraphicTile &Tile = TmpTiles.back(); + SGraphicTileTexureCoords *pTileTex = NULL; if(DoTextureCoords) { TmpTileTexCoords.push_back(SGraphicTileTexureCoords()); - SGraphicTileTexureCoords& TileTex = TmpTileTexCoords.back(); + SGraphicTileTexureCoords &TileTex = TmpTileTexCoords.back(); pTileTex = &TileTex; } if(FillSpeedup) @@ -383,7 +382,7 @@ void mem_copy_special(void *pDest, void *pSource, size_t Size, size_t Count, siz size_t CurStep = 0; for(size_t i = 0; i < Count; ++i) { - mem_copy(((char*)pDest) + CurStep + i * Size, ((char*)pSource) + i * Size, Size); + mem_copy(((char *)pDest) + CurStep + i * Size, ((char *)pSource) + i * Size, Size); CurStep += Steps; } } @@ -447,7 +446,7 @@ void CMapLayers::OnMapLoad() for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer + l); bool IsFrontLayer = false; bool IsSwitchLayer = false; bool IsTeleLayer = false; @@ -456,26 +455,26 @@ void CMapLayers::OnMapLoad() bool IsGameLayer = false; bool IsEntityLayer = false; - if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->GameLayer()) { IsGameLayer = true; IsEntityLayer = true; PassedGameLayer = true; } - if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->FrontLayer()) IsEntityLayer = IsFrontLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SwitchLayer()) IsEntityLayer = IsSwitchLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TeleLayer()) IsEntityLayer = IsTeleLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SpeedupLayer()) IsEntityLayer = IsSpeedupLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TuneLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TuneLayer()) IsEntityLayer = IsTuneLayer = true; if(m_Type <= TYPE_BACKGROUND_FORCE) @@ -501,7 +500,6 @@ void CMapLayers::OnMapLoad() else DoTextureCoords = true; - int DataIndex = 0; unsigned int TileSize = 0; int OverlayCount = 0; @@ -539,16 +537,16 @@ void CMapLayers::OnMapLoad() TileSize = sizeof(CTile); } unsigned int Size = m_pLayers->Map()->GetDataSize(DataIndex); - void* pTiles = m_pLayers->Map()->GetData(DataIndex); + void *pTiles = m_pLayers->Map()->GetData(DataIndex); - if(Size >= pTMap->m_Width*pTMap->m_Height*TileSize) + if(Size >= pTMap->m_Width * pTMap->m_Height * TileSize) { int CurOverlay = 0; while(CurOverlay < OverlayCount + 1) { // We can later just count the tile layers to get the idx in the vector m_TileLayerVisuals.push_back(new STileLayerVisuals()); - STileLayerVisuals& Visuals = *m_TileLayerVisuals.back(); + STileLayerVisuals &Visuals = *m_TileLayerVisuals.back(); if(!Visuals.Init(pTMap->m_Width, pTMap->m_Height)) { ++CurOverlay; @@ -570,16 +568,18 @@ void CMapLayers::OnMapLoad() tmpBorderBottomTilesTexCoords.clear(); tmpBorderCornersTexCoords.clear(); - if(!DoTextureCoords) { - tmpTiles.reserve((size_t)(pTMap->m_Width*pTMap->m_Height)); + if(!DoTextureCoords) + { + tmpTiles.reserve((size_t)(pTMap->m_Width * pTMap->m_Height)); tmpBorderTopTiles.reserve((size_t)pTMap->m_Width); tmpBorderBottomTiles.reserve((size_t)pTMap->m_Width); tmpBorderLeftTiles.reserve((size_t)pTMap->m_Height); tmpBorderRightTiles.reserve((size_t)pTMap->m_Height); tmpBorderCorners.reserve((size_t)4); } - else { - tmpTileTexCoords.reserve((size_t)(pTMap->m_Width*pTMap->m_Height)); + else + { + tmpTileTexCoords.reserve((size_t)(pTMap->m_Width * pTMap->m_Height)); tmpBorderTopTilesTexCoords.reserve((size_t)pTMap->m_Width); tmpBorderBottomTilesTexCoords.reserve((size_t)pTMap->m_Width); tmpBorderLeftTilesTexCoords.reserve((size_t)pTMap->m_Height); @@ -593,7 +593,6 @@ void CMapLayers::OnMapLoad() { for(x = 0; x < pTMap->m_Width; ++x) { - unsigned char Index = 0; unsigned char Flags = 0; int AngleRotate = -1; @@ -615,121 +614,121 @@ void CMapLayers::OnMapLoad() Index = ((CSwitchTile *)pTiles)[y * pTMap->m_Width + x].m_Type; if(CurOverlay == 0) { - Flags = ((CSwitchTile*)pTiles)[y*pTMap->m_Width+x].m_Flags; - if(Index == TILE_SWITCHTIMEDOPEN) Index = 8; + Flags = ((CSwitchTile *)pTiles)[y * pTMap->m_Width + x].m_Flags; + if(Index == TILE_SWITCHTIMEDOPEN) + Index = 8; } else if(CurOverlay == 1) - Index = ((CSwitchTile*)pTiles)[y*pTMap->m_Width+x].m_Number; + Index = ((CSwitchTile *)pTiles)[y * pTMap->m_Width + x].m_Number; else if(CurOverlay == 2) - Index = ((CSwitchTile*)pTiles)[y*pTMap->m_Width+x].m_Delay; + Index = ((CSwitchTile *)pTiles)[y * pTMap->m_Width + x].m_Delay; } if(IsTeleLayer) { - Index = ((CTeleTile*)pTiles)[y*pTMap->m_Width+x].m_Type; + Index = ((CTeleTile *)pTiles)[y * pTMap->m_Width + x].m_Type; Flags = 0; if(CurOverlay == 1) { if(Index != TILE_TELECHECKIN && Index != TILE_TELECHECKINEVIL) - Index = ((CTeleTile*)pTiles)[y*pTMap->m_Width+x].m_Number; - else Index = 0; + Index = ((CTeleTile *)pTiles)[y * pTMap->m_Width + x].m_Number; + else + Index = 0; } } if(IsSpeedupLayer) { - Index = ((CSpeedupTile*)pTiles)[y*pTMap->m_Width+x].m_Type; + Index = ((CSpeedupTile *)pTiles)[y * pTMap->m_Width + x].m_Type; Flags = 0; AngleRotate = ((CSpeedupTile *)pTiles)[y * pTMap->m_Width + x].m_Angle; if(((CSpeedupTile *)pTiles)[y * pTMap->m_Width + x].m_Force == 0) Index = 0; else if(CurOverlay == 1) - Index = ((CSpeedupTile*)pTiles)[y*pTMap->m_Width+x].m_Force; + Index = ((CSpeedupTile *)pTiles)[y * pTMap->m_Width + x].m_Force; else if(CurOverlay == 2) - Index = ((CSpeedupTile*)pTiles)[y*pTMap->m_Width+x].m_MaxSpeed; + Index = ((CSpeedupTile *)pTiles)[y * pTMap->m_Width + x].m_MaxSpeed; } if(IsTuneLayer) { Index = ((CTuneTile *)pTiles)[y * pTMap->m_Width + x].m_Type; Flags = 0; } - } else + } + else { - Index = ((CTile*)pTiles)[y*pTMap->m_Width+x].m_Index; - Flags = ((CTile*)pTiles)[y*pTMap->m_Width+x].m_Flags; + Index = ((CTile *)pTiles)[y * pTMap->m_Width + x].m_Index; + Flags = ((CTile *)pTiles)[y * pTMap->m_Width + x].m_Flags; } //the amount of tiles handled before this tile int TilesHandledCount = tmpTiles.size(); - Visuals.m_TilesOfLayer[y*pTMap->m_Width + x].SetIndexBufferByteOffset((offset_ptr32)(TilesHandledCount*6*sizeof(unsigned int))); + Visuals.m_TilesOfLayer[y * pTMap->m_Width + x].SetIndexBufferByteOffset((offset_ptr32)(TilesHandledCount * 6 * sizeof(unsigned int))); bool AddAsSpeedup = false; if(IsSpeedupLayer && CurOverlay == 0) AddAsSpeedup = true; if(AddTile(tmpTiles, tmpTileTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) - Visuals.m_TilesOfLayer[y*pTMap->m_Width + x].Draw(true); + Visuals.m_TilesOfLayer[y * pTMap->m_Width + x].Draw(true); //do the border tiles if(x == 0) { if(y == 0) { - Visuals.m_BorderTopLeft.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size()*6*sizeof(unsigned int))); + Visuals.m_BorderTopLeft.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderCorners, tmpBorderCornersTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) Visuals.m_BorderTopLeft.Draw(true); } else if(y == pTMap->m_Height - 1) { - Visuals.m_BorderBottomLeft.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size()*6*sizeof(unsigned int))); + Visuals.m_BorderBottomLeft.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderCorners, tmpBorderCornersTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) Visuals.m_BorderBottomLeft.Draw(true); - } else { - Visuals.m_BorderLeft[y-1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderLeftTiles.size()*6*sizeof(unsigned int))); + Visuals.m_BorderLeft[y - 1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderLeftTiles.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderLeftTiles, tmpBorderLeftTilesTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) - Visuals.m_BorderLeft[y-1].Draw(true); + Visuals.m_BorderLeft[y - 1].Draw(true); } } else if(x == pTMap->m_Width - 1) { if(y == 0) { - Visuals.m_BorderTopRight.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size()*6*sizeof(unsigned int))); + Visuals.m_BorderTopRight.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderCorners, tmpBorderCornersTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) Visuals.m_BorderTopRight.Draw(true); - } else if(y == pTMap->m_Height - 1) { - Visuals.m_BorderBottomRight.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size()*6*sizeof(unsigned int))); + Visuals.m_BorderBottomRight.SetIndexBufferByteOffset((offset_ptr32)(tmpBorderCorners.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderCorners, tmpBorderCornersTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) Visuals.m_BorderBottomRight.Draw(true); - } else { - Visuals.m_BorderRight[y-1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderRightTiles.size()*6*sizeof(unsigned int))); + Visuals.m_BorderRight[y - 1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderRightTiles.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderRightTiles, tmpBorderRightTilesTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) - Visuals.m_BorderRight[y-1].Draw(true); + Visuals.m_BorderRight[y - 1].Draw(true); } } else if(y == 0) { if(x > 0 && x < pTMap->m_Width - 1) { - Visuals.m_BorderTop[x-1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderTopTiles.size()*6*sizeof(unsigned int))); + Visuals.m_BorderTop[x - 1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderTopTiles.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderTopTiles, tmpBorderTopTilesTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) - Visuals.m_BorderTop[x-1].Draw(true); + Visuals.m_BorderTop[x - 1].Draw(true); } } else if(y == pTMap->m_Height - 1) { if(x > 0 && x < pTMap->m_Width - 1) { - Visuals.m_BorderBottom[x-1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderBottomTiles.size()*6*sizeof(unsigned int))); + Visuals.m_BorderBottom[x - 1].SetIndexBufferByteOffset((offset_ptr32)(tmpBorderBottomTiles.size() * 6 * sizeof(unsigned int))); if(AddTile(tmpBorderBottomTiles, tmpBorderBottomTilesTexCoords, As3DTextureCoords, Index, Flags, x, y, pGroup, DoTextureCoords, AddAsSpeedup, AngleRotate)) - Visuals.m_BorderBottom[x-1].Draw(true); + Visuals.m_BorderBottom[x - 1].Draw(true); } } } @@ -745,10 +744,10 @@ void CMapLayers::OnMapLoad() //add the border corners, then the borders and fix their byte offsets int TilesHandledCount = tmpTiles.size(); - Visuals.m_BorderTopLeft.AddIndexBufferByteOffset(TilesHandledCount*6*sizeof(unsigned int)); - Visuals.m_BorderTopRight.AddIndexBufferByteOffset(TilesHandledCount*6*sizeof(unsigned int)); - Visuals.m_BorderBottomLeft.AddIndexBufferByteOffset(TilesHandledCount*6*sizeof(unsigned int)); - Visuals.m_BorderBottomRight.AddIndexBufferByteOffset(TilesHandledCount*6*sizeof(unsigned int)); + Visuals.m_BorderTopLeft.AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); + Visuals.m_BorderTopRight.AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); + Visuals.m_BorderBottomLeft.AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); + Visuals.m_BorderBottomRight.AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); //add the Corners to the tiles tmpTiles.insert(tmpTiles.end(), tmpBorderCorners.begin(), tmpBorderCorners.end()); tmpTileTexCoords.insert(tmpTileTexCoords.end(), tmpBorderCornersTexCoords.begin(), tmpBorderCornersTexCoords.end()); @@ -757,7 +756,7 @@ void CMapLayers::OnMapLoad() TilesHandledCount = tmpTiles.size(); if(pTMap->m_Width > 2) { - for(int i = 0; i < pTMap->m_Width-2; ++i) + for(int i = 0; i < pTMap->m_Width - 2; ++i) { Visuals.m_BorderTop[i].AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); } @@ -768,7 +767,7 @@ void CMapLayers::OnMapLoad() TilesHandledCount = tmpTiles.size(); if(pTMap->m_Width > 2) { - for(int i = 0; i < pTMap->m_Width-2; ++i) + for(int i = 0; i < pTMap->m_Width - 2; ++i) { Visuals.m_BorderBottom[i].AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); } @@ -779,7 +778,7 @@ void CMapLayers::OnMapLoad() TilesHandledCount = tmpTiles.size(); if(pTMap->m_Height > 2) { - for(int i = 0; i < pTMap->m_Height-2; ++i) + for(int i = 0; i < pTMap->m_Height - 2; ++i) { Visuals.m_BorderLeft[i].AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); } @@ -790,7 +789,7 @@ void CMapLayers::OnMapLoad() TilesHandledCount = tmpTiles.size(); if(pTMap->m_Height > 2) { - for(int i = 0; i < pTMap->m_Height-2; ++i) + for(int i = 0; i < pTMap->m_Height - 2; ++i) { Visuals.m_BorderRight[i].AddIndexBufferByteOffset(TilesHandledCount * 6 * sizeof(unsigned int)); } @@ -799,14 +798,14 @@ void CMapLayers::OnMapLoad() tmpTileTexCoords.insert(tmpTileTexCoords.end(), tmpBorderRightTilesTexCoords.begin(), tmpBorderRightTilesTexCoords.end()); //setup params - float* pTmpTiles = (tmpTiles.size() == 0) ? NULL : (float*)&tmpTiles[0]; - unsigned char* pTmpTileTexCoords = (tmpTileTexCoords.size() == 0) ? NULL : (unsigned char*)&tmpTileTexCoords[0]; + float *pTmpTiles = (tmpTiles.size() == 0) ? NULL : (float *)&tmpTiles[0]; + unsigned char *pTmpTileTexCoords = (tmpTileTexCoords.size() == 0) ? NULL : (unsigned char *)&tmpTileTexCoords[0]; Visuals.m_BufferContainerIndex = -1; size_t UploadDataSize = tmpTileTexCoords.size() * sizeof(SGraphicTileTexureCoords) + tmpTiles.size() * sizeof(SGraphicTile); if(UploadDataSize > 0) { - char* pUploadData = new char[UploadDataSize]; + char *pUploadData = new char[UploadDataSize]; mem_copy_special(pUploadData, pTmpTiles, sizeof(vec2), tmpTiles.size() * 4, (DoTextureCoords ? sizeof(vec3) : 0)); if(DoTextureCoords) @@ -822,7 +821,7 @@ void CMapLayers::OnMapLoad() SBufferContainerInfo ContainerInfo; ContainerInfo.m_Stride = (DoTextureCoords ? (sizeof(float) * 2 + sizeof(vec3)) : 0); ContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); - SBufferContainerInfo::SAttribute* pAttr = &ContainerInfo.m_Attributes.back(); + SBufferContainerInfo::SAttribute *pAttr = &ContainerInfo.m_Attributes.back(); pAttr->m_DataTypeCount = 2; pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_Normalized = false; @@ -836,7 +835,7 @@ void CMapLayers::OnMapLoad() pAttr->m_DataTypeCount = 3; pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_Normalized = false; - pAttr->m_pOffset = (void*)(sizeof(vec2)); + pAttr->m_pOffset = (void *)(sizeof(vec2)); pAttr->m_FuncType = 0; pAttr->m_VertBufferBindingIndex = BufferObjectIndex; } @@ -855,7 +854,7 @@ void CMapLayers::OnMapLoad() CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; m_QuadLayerVisuals.push_back(new SQuadLayerVisuals()); - SQuadLayerVisuals* pQLayerVisuals = m_QuadLayerVisuals.back(); + SQuadLayerVisuals *pQLayerVisuals = m_QuadLayerVisuals.back(); bool Textured = (pQLayer->m_Image == -1 ? false : true); @@ -913,8 +912,9 @@ void CMapLayers::OnMapLoad() else UploadDataSize = tmpQuads.size() * sizeof(STmpQuad); - if(UploadDataSize > 0) { - void* pUploadData = NULL; + if(UploadDataSize > 0) + { + void *pUploadData = NULL; if(Textured) pUploadData = &tmpQuadsTextured[0]; else @@ -925,7 +925,7 @@ void CMapLayers::OnMapLoad() SBufferContainerInfo ContainerInfo; ContainerInfo.m_Stride = (Textured ? (sizeof(STmpQuadTextured) / 4) : (sizeof(STmpQuad) / 4)); ContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute()); - SBufferContainerInfo::SAttribute* pAttr = &ContainerInfo.m_Attributes.back(); + SBufferContainerInfo::SAttribute *pAttr = &ContainerInfo.m_Attributes.back(); pAttr->m_DataTypeCount = 4; pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_Normalized = false; @@ -937,7 +937,7 @@ void CMapLayers::OnMapLoad() pAttr->m_DataTypeCount = 4; pAttr->m_Type = GRAPHICS_TYPE_UNSIGNED_BYTE; pAttr->m_Normalized = true; - pAttr->m_pOffset = (void*)(sizeof(float) * 4); + pAttr->m_pOffset = (void *)(sizeof(float) * 4); pAttr->m_FuncType = 0; pAttr->m_VertBufferBindingIndex = BufferObjectIndex; if(Textured) @@ -947,7 +947,7 @@ void CMapLayers::OnMapLoad() pAttr->m_DataTypeCount = 2; pAttr->m_Type = GRAPHICS_TYPE_FLOAT; pAttr->m_Normalized = false; - pAttr->m_pOffset = (void*)(sizeof(float) * 4 + sizeof(unsigned char) * 4); + pAttr->m_pOffset = (void *)(sizeof(float) * 4 + sizeof(unsigned char) * 4); pAttr->m_FuncType = 0; pAttr->m_VertBufferBindingIndex = BufferObjectIndex; } @@ -961,20 +961,20 @@ void CMapLayers::OnMapLoad() } } -void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup) +void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup) { - STileLayerVisuals& Visuals = *m_TileLayerVisuals[LayerIndex]; + STileLayerVisuals &Visuals = *m_TileLayerVisuals[LayerIndex]; if(Visuals.m_BufferContainerIndex == -1) return; //no visuals were created float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - float r=1, g=1, b=1, a=1; + float r = 1, g = 1, b = 1, a = 1; if(pTileLayer->m_ColorEnv >= 0) { float aChannels[4]; - EnvelopeEval(pTileLayer->m_ColorEnvOffset/1000.0f, pTileLayer->m_ColorEnv, aChannels, this); + EnvelopeEval(pTileLayer->m_ColorEnvOffset / 1000.0f, pTileLayer->m_ColorEnv, aChannels, this); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; @@ -984,10 +984,10 @@ void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLaye int BorderX0, BorderY0, BorderX1, BorderY1; bool DrawBorder = false; - int Y0 = BorderY0 = (int)floorf((ScreenY0)/32); - int X0 = BorderX0 = (int)floorf((ScreenX0)/32); - int Y1 = BorderY1 = (int)floorf((ScreenY1)/32); - int X1 = BorderX1 = (int)floorf((ScreenX1)/32); + int Y0 = BorderY0 = (int)floorf((ScreenY0) / 32); + int X0 = BorderX0 = (int)floorf((ScreenX0) / 32); + int Y1 = BorderY1 = (int)floorf((ScreenY1) / 32); + int X1 = BorderX1 = (int)floorf((ScreenX1) / 32); if(X0 <= 0) { @@ -1023,7 +1023,7 @@ void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLaye if(DrawLayer) { //create the indice buffers we want to draw -- reuse them - static std::vector s_IndexOffsets; + static std::vector s_IndexOffsets; static std::vector s_DrawCounts; s_IndexOffsets.clear(); @@ -1038,13 +1038,13 @@ void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLaye if(X0 > X1) continue; - dbg_assert(Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X1].IndexBufferByteOffset() >= Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X0].IndexBufferByteOffset(), "Tile count wrong."); + dbg_assert(Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X1].IndexBufferByteOffset() >= Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X0].IndexBufferByteOffset(), "Tile count wrong."); - unsigned int NumVertices = ((Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X1].IndexBufferByteOffset() - Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X0].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X1].DoDraw() ? 6lu : 0lu); + unsigned int NumVertices = ((Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X1].IndexBufferByteOffset() - Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X0].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X1].DoDraw() ? 6lu : 0lu); if(NumVertices) { - s_IndexOffsets.push_back((offset_ptr_size)Visuals.m_TilesOfLayer[y*pTileLayer->m_Width + X0].IndexBufferByteOffset()); + s_IndexOffsets.push_back((offset_ptr_size)Visuals.m_TilesOfLayer[y * pTileLayer->m_Width + X0].IndexBufferByteOffset()); s_DrawCounts.push_back(NumVertices); } } @@ -1057,7 +1057,7 @@ void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLaye int DrawCount = s_IndexOffsets.size(); if(DrawCount != 0) { - Graphics()->RenderTileLayer(Visuals.m_BufferContainerIndex, (float*)pColor, &s_IndexOffsets[0], &s_DrawCounts[0], DrawCount); + Graphics()->RenderTileLayer(Visuals.m_BufferContainerIndex, (float *)pColor, &s_IndexOffsets[0], &s_DrawCounts[0], DrawCount); } } @@ -1065,7 +1065,7 @@ void CMapLayers::RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLaye RenderTileBorder(LayerIndex, pColor, pTileLayer, pGroup, BorderX0, BorderY0, BorderX1, BorderY1, (int)(-floorf((-ScreenX1) / 32.f)) - BorderX0, (int)(-floorf((-ScreenY1) / 32.f)) - BorderY0); } -void CMapLayers::RenderTileBorderCornerTiles(int WidthOffsetToOrigin, int HeightOffsetToOrigin, int TileCountWidth, int TileCountHeight, int BufferContainerIndex, float* pColor, offset_ptr_size IndexBufferOffset, float* pOffset, float* pDir) +void CMapLayers::RenderTileBorderCornerTiles(int WidthOffsetToOrigin, int HeightOffsetToOrigin, int TileCountWidth, int TileCountHeight, int BufferContainerIndex, float *pColor, offset_ptr_size IndexBufferOffset, float *pOffset, float *pDir) { // if border is still in range of the original corner, it doesn't needs to be redrawn bool CornerVisible = (WidthOffsetToOrigin - 1 < TileCountWidth) && (HeightOffsetToOrigin - 1 < TileCountHeight); @@ -1078,9 +1078,9 @@ void CMapLayers::RenderTileBorderCornerTiles(int WidthOffsetToOrigin, int Height Graphics()->RenderBorderTiles(BufferContainerIndex, pColor, IndexBufferOffset, pOffset, pDir, CountX, Count); } -void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup, int BorderX0, int BorderY0, int BorderX1, int BorderY1, int ScreenWidthTileCount, int ScreenHeightTileCount) +void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup, int BorderX0, int BorderY0, int BorderX1, int BorderY1, int ScreenWidthTileCount, int ScreenHeightTileCount) { - STileLayerVisuals& Visuals = *m_TileLayerVisuals[LayerIndex]; + STileLayerVisuals &Visuals = *m_TileLayerVisuals[LayerIndex]; int Y0 = BorderY0; int X0 = BorderX0; @@ -1113,7 +1113,7 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay Dir.x = 32.f; Dir.y = 32.f; - RenderTileBorderCornerTiles(absolute(BorderX0) + 1, absolute(BorderY0) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderTopLeft.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir); + RenderTileBorderCornerTiles(absolute(BorderX0) + 1, absolute(BorderY0) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderTopLeft.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir); } } if(BorderY1 >= pTileLayer->m_Height - 1) @@ -1127,7 +1127,7 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay Dir.x = 32.f; Dir.y = -32.f; - RenderTileBorderCornerTiles(absolute(BorderX0) + 1, (BorderY1 - (pTileLayer->m_Height - 1)) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderBottomLeft.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir); + RenderTileBorderCornerTiles(absolute(BorderX0) + 1, (BorderY1 - (pTileLayer->m_Height - 1)) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderBottomLeft.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir); } } } @@ -1137,14 +1137,14 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay if(Y0 < pTileLayer->m_Height - 1 && Y1 > 0) { unsigned int DrawNum = ((Visuals.m_BorderLeft[Y1 - 1].IndexBufferByteOffset() - Visuals.m_BorderLeft[Y0 - 1].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_BorderLeft[Y1 - 1].DoDraw() ? 6lu : 0lu); - offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderLeft[Y0-1].IndexBufferByteOffset(); + offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderLeft[Y0 - 1].IndexBufferByteOffset(); vec2 Offset; Offset.x = 32.f * BorderX0; Offset.y = 0.f; vec2 Dir; Dir.x = 32.f; Dir.y = 0.f; - Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float*)pColor, pOffset, (float*)&Offset, (float*)&Dir, DrawNum, minimum(absolute(BorderX0), CountWidth)); + Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float *)pColor, pOffset, (float *)&Offset, (float *)&Dir, DrawNum, minimum(absolute(BorderX0), CountWidth)); } } @@ -1162,7 +1162,7 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay Dir.x = -32.f; Dir.y = 32.f; - RenderTileBorderCornerTiles((BorderX1 - (pTileLayer->m_Width - 1)) + 1, absolute(BorderY0) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderTopRight.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir); + RenderTileBorderCornerTiles((BorderX1 - (pTileLayer->m_Width - 1)) + 1, absolute(BorderY0) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderTopRight.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir); } } if(BorderY1 >= pTileLayer->m_Height - 1) @@ -1176,7 +1176,7 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay Dir.x = -32.f; Dir.y = -32.f; - RenderTileBorderCornerTiles((BorderX1 - (pTileLayer->m_Width - 1)) + 1, (BorderY1 - (pTileLayer->m_Height - 1)) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderBottomRight.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir); + RenderTileBorderCornerTiles((BorderX1 - (pTileLayer->m_Width - 1)) + 1, (BorderY1 - (pTileLayer->m_Height - 1)) + 1, CountWidth, CountHeight, Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderBottomRight.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir); } } } @@ -1186,14 +1186,14 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay if(Y0 < pTileLayer->m_Height - 1 && Y1 > 0) { unsigned int DrawNum = ((Visuals.m_BorderRight[Y1 - 1].IndexBufferByteOffset() - Visuals.m_BorderRight[Y0 - 1].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_BorderRight[Y1 - 1].DoDraw() ? 6lu : 0lu); - offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderRight[Y0-1].IndexBufferByteOffset(); + offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderRight[Y0 - 1].IndexBufferByteOffset(); vec2 Offset; Offset.x = 32.f * (BorderX1 - (pTileLayer->m_Width - 1)); Offset.y = 0.f; vec2 Dir; Dir.x = -32.f; Dir.y = 0.f; - Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float*)pColor, pOffset, (float*)&Offset, (float*)&Dir, DrawNum, minimum((BorderX1 - (pTileLayer->m_Width - 1)), CountWidth)); + Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float *)pColor, pOffset, (float *)&Offset, (float *)&Dir, DrawNum, minimum((BorderX1 - (pTileLayer->m_Width - 1)), CountWidth)); } } if(BorderY0 < 0) @@ -1202,14 +1202,14 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay if(X0 < pTileLayer->m_Width - 1 && X1 > 0) { unsigned int DrawNum = ((Visuals.m_BorderTop[X1 - 1].IndexBufferByteOffset() - Visuals.m_BorderTop[X0 - 1].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_BorderTop[X1 - 1].DoDraw() ? 6lu : 0lu); - offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderTop[X0-1].IndexBufferByteOffset(); + offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderTop[X0 - 1].IndexBufferByteOffset(); vec2 Offset; Offset.x = 0.f; Offset.y = 32.f * BorderY0; vec2 Dir; Dir.x = 0.f; Dir.y = 32.f; - Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float*)pColor, pOffset, (float*)&Offset, (float*)&Dir, DrawNum, minimum(absolute(BorderY0), CountHeight)); + Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float *)pColor, pOffset, (float *)&Offset, (float *)&Dir, DrawNum, minimum(absolute(BorderY0), CountHeight)); } } if(BorderY1 >= pTileLayer->m_Height) @@ -1218,32 +1218,33 @@ void CMapLayers::RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLay if(X0 < pTileLayer->m_Width - 1 && X1 > 0) { unsigned int DrawNum = ((Visuals.m_BorderBottom[X1 - 1].IndexBufferByteOffset() - Visuals.m_BorderBottom[X0 - 1].IndexBufferByteOffset()) / sizeof(unsigned int)) + (Visuals.m_BorderBottom[X1 - 1].DoDraw() ? 6lu : 0lu); - offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderBottom[X0-1].IndexBufferByteOffset(); + offset_ptr_size pOffset = (offset_ptr_size)Visuals.m_BorderBottom[X0 - 1].IndexBufferByteOffset(); vec2 Offset; Offset.x = 0.f; Offset.y = 32.f * (BorderY1 - (pTileLayer->m_Height - 1)); vec2 Dir; Dir.x = 0.f; Dir.y = -32.f; - Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float*)pColor, pOffset, (float*)&Offset, (float*)&Dir, DrawNum, minimum((BorderY1 - (pTileLayer->m_Height - 1)), CountHeight)); + Graphics()->RenderBorderTileLines(Visuals.m_BufferContainerIndex, (float *)pColor, pOffset, (float *)&Offset, (float *)&Dir, DrawNum, minimum((BorderY1 - (pTileLayer->m_Height - 1)), CountHeight)); } } } -void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup) +void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup) { - STileLayerVisuals& Visuals = *m_TileLayerVisuals[LayerIndex]; - if(Visuals.m_BufferContainerIndex == -1) return; //no visuals were created + STileLayerVisuals &Visuals = *m_TileLayerVisuals[LayerIndex]; + if(Visuals.m_BufferContainerIndex == -1) + return; //no visuals were created float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); bool DrawBorder = false; - int BorderY0 = (int)(ScreenY0/32)-1; - int BorderX0 = (int)(ScreenX0/32)-1; - int BorderY1 = (int)(ScreenY1/32)+1; - int BorderX1 = (int)(ScreenX1/32)+1; + int BorderY0 = (int)(ScreenY0 / 32) - 1; + int BorderX0 = (int)(ScreenX0 / 32) - 1; + int BorderY1 = (int)(ScreenY1 / 32) + 1; + int BorderX1 = (int)(ScreenX1 / 32) + 1; if(BorderX0 < -201) DrawBorder = true; @@ -1289,7 +1290,7 @@ void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapIte int Count = (absolute(BorderX0) - 201) * (BorderY1 - BorderY0); - Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir, (absolute(BorderX0) - 201), Count); + Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir, (absolute(BorderX0) - 201), Count); } // Draw top kill tile border if(BorderY0 < -201) @@ -1305,9 +1306,9 @@ void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapIte Dir.x = 32.f; Dir.y = 32.f; - int Count = (OffX1 - OffX0) * (absolute(BorderY0)-201); + int Count = (OffX1 - OffX0) * (absolute(BorderY0) - 201); - Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir, (OffX1 - OffX0), Count); + Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir, (OffX1 - OffX0), Count); } if(BorderX1 >= pTileLayer->m_Width + 201) { @@ -1320,7 +1321,7 @@ void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapIte int Count = (BorderX1 - (pTileLayer->m_Width + 201)) * (BorderY1 - BorderY0); - Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir, (BorderX1 - (pTileLayer->m_Width + 201)), Count); + Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir, (BorderX1 - (pTileLayer->m_Width + 201)), Count); } if(BorderY1 >= pTileLayer->m_Height + 201) { @@ -1335,15 +1336,15 @@ void CMapLayers::RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapIte Dir.x = 32.f; Dir.y = 32.f; - int Count = (OffX1 - OffX0) * (BorderY1-(pTileLayer->m_Height + 201)); + int Count = (OffX1 - OffX0) * (BorderY1 - (pTileLayer->m_Height + 201)); - Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float*)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float*)&Offset, (float*)&Dir, (OffX1 - OffX0), Count); + Graphics()->RenderBorderTiles(Visuals.m_BufferContainerIndex, (float *)pColor, (offset_ptr_size)Visuals.m_BorderKillTile.IndexBufferByteOffset(), (float *)&Offset, (float *)&Dir, (OffX1 - OffX0), Count); } } -void CMapLayers::RenderQuadLayer(int LayerIndex, CMapItemLayerQuads* pQuadLayer, CMapItemGroup* pGroup, bool Force) +void CMapLayers::RenderQuadLayer(int LayerIndex, CMapItemLayerQuads *pQuadLayer, CMapItemGroup *pGroup, bool Force) { - SQuadLayerVisuals& Visuals = *m_QuadLayerVisuals[LayerIndex]; + SQuadLayerVisuals &Visuals = *m_QuadLayerVisuals[LayerIndex]; if(Visuals.m_BufferContainerIndex == -1) return; //no visuals were created @@ -1376,10 +1377,10 @@ void CMapLayers::RenderQuadLayer(int LayerIndex, CMapItemLayerQuads* pQuadLayer, EnvelopeEval(q->m_PosEnvOffset / 1000.0f, q->m_PosEnv, aChannels, this); OffsetX = aChannels[0]; OffsetY = aChannels[1]; - Rot = aChannels[2] / 180.0f*pi; + Rot = aChannels[2] / 180.0f * pi; } - SQuadRenderInfo& QInfo = s_QuadRenderInfo[i]; + SQuadRenderInfo &QInfo = s_QuadRenderInfo[i]; mem_copy(QInfo.m_aColor, aColor, sizeof(aColor)); QInfo.m_aOffsets[0] = OffsetX; QInfo.m_aOffsets[1] = OffsetY; @@ -1388,40 +1389,39 @@ void CMapLayers::RenderQuadLayer(int LayerIndex, CMapItemLayerQuads* pQuadLayer, Graphics()->RenderQuadLayer(Visuals.m_BufferContainerIndex, &s_QuadRenderInfo[0], pQuadLayer->m_NumQuads); } -void CMapLayers::LayersOfGroupCount(CMapItemGroup* pGroup, int& TileLayerCount, int& QuadLayerCount, bool& PassedGameLayer) +void CMapLayers::LayersOfGroupCount(CMapItemGroup *pGroup, int &TileLayerCount, int &QuadLayerCount, bool &PassedGameLayer) { int TileLayerCounter = 0; int QuadLayerCounter = 0; for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer + l); bool IsFrontLayer = false; bool IsSwitchLayer = false; bool IsTeleLayer = false; bool IsSpeedupLayer = false; bool IsTuneLayer = false; - if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->GameLayer()) { PassedGameLayer = true; } - if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->FrontLayer()) IsFrontLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SwitchLayer()) IsSwitchLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TeleLayer()) IsTeleLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SpeedupLayer()) IsSpeedupLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TuneLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TuneLayer()) IsTuneLayer = true; - if(m_Type <= TYPE_BACKGROUND_FORCE) { if(PassedGameLayer) @@ -1477,7 +1477,7 @@ void CMapLayers::LayersOfGroupCount(CMapItemGroup* pGroup, int& TileLayerCount, } unsigned int Size = m_pLayers->Map()->GetDataSize(DataIndex); - if(Size >= pTMap->m_Width*pTMap->m_Height*TileSize) + if(Size >= pTMap->m_Width * pTMap->m_Height * TileSize) { TileLayerCounter += TileLayerAndOverlayCount; } @@ -1524,10 +1524,10 @@ void CMapLayers::OnRender() float Points[4]; MapScreenToGroup(Center.x, Center.y, m_pLayers->GameGroup(), GetCurCamera()->m_Zoom); Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); - float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); - float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); - float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); - float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); + float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2] - Points[0]); + float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3] - Points[1]); + float x1 = ((pGroup->m_ClipX + pGroup->m_ClipW) - Points[0]) / (Points[2] - Points[0]); + float y1 = ((pGroup->m_ClipY + pGroup->m_ClipH) - Points[1]) / (Points[3] - Points[1]); if(x1 < 0.0f || x0 > 1.0f || y1 < 0.0f || y0 > 1.0f) { @@ -1536,8 +1536,8 @@ void CMapLayers::OnRender() continue; } - Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), - (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); + Graphics()->ClipEnable((int)(x0 * Graphics()->ScreenWidth()), (int)(y0 * Graphics()->ScreenHeight()), + (int)((x1 - x0) * Graphics()->ScreenWidth()), (int)((y1 - y0) * Graphics()->ScreenHeight())); } if((!g_Config.m_ClZoomBackgroundLayers || m_Type == TYPE_FULL_DESIGN) && !pGroup->m_ParallaxX && !pGroup->m_ParallaxY) @@ -1549,7 +1549,7 @@ void CMapLayers::OnRender() for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer + l); bool Render = false; bool IsGameLayer = false; bool IsFrontLayer = false; @@ -1559,25 +1559,25 @@ void CMapLayers::OnRender() bool IsTuneLayer = false; bool IsEntityLayer = false; - if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->GameLayer()) { IsEntityLayer = IsGameLayer = true; PassedGameLayer = true; } - if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->FrontLayer()) IsEntityLayer = IsFrontLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SwitchLayer()) IsEntityLayer = IsSwitchLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TeleLayer()) IsEntityLayer = IsTeleLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->SpeedupLayer()) IsEntityLayer = IsSpeedupLayer = true; - if(pLayer == (CMapItemLayer*)m_pLayers->TuneLayer()) + if(pLayer == (CMapItemLayer *)m_pLayers->TuneLayer()) IsEntityLayer = IsTuneLayer = true; if(m_Type == -1) @@ -1619,7 +1619,7 @@ void CMapLayers::OnRender() for(int y = 0; y < pTMap->m_Height; y++) { for(int x = 0; x < pTMap->m_Width; x++) - io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); + io_write(File, &(pTiles[y * pTMap->m_Width + x].m_Index), sizeof(pTiles[y * pTMap->m_Width + x].m_Index)); io_write_newline(File); } io_close(File); @@ -1670,7 +1670,7 @@ void CMapLayers::OnRender() } unsigned int Size = m_pLayers->Map()->GetDataSize(DataIndex); - if(Size >= pTMap->m_Width*pTMap->m_Height*TileSize) + if(Size >= pTMap->m_Width * pTMap->m_Height * TileSize) { TileLayerCounter += TileLayerAndOverlayCount; } @@ -1706,7 +1706,7 @@ void CMapLayers::OnRender() CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Data); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f); if(IsGameLayer && EntityOverlayVal) @@ -1716,8 +1716,8 @@ void CMapLayers::OnRender() if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, - EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); @@ -1725,17 +1725,17 @@ void CMapLayers::OnRender() if(IsGameLayer) { // slow blinking to hint that it's not a part of the map - double Seconds = time_get()/(double)time_freq(); - ColorRGBA ColorHint = ColorRGBA(1.0f, 1.0f, 1.0f, 0.3f + 0.7f*(1.0f+sin(2.0f*pi*Seconds/3.f))/2.0f); + double Seconds = time_get() / (double)time_freq(); + ColorRGBA ColorHint = ColorRGBA(1.0f, 1.0f, 1.0f, 0.3f + 0.7f * (1.0f + sin(2.0f * pi * Seconds / 3.f)) / 2.0f); - RenderTools()->RenderTileRectangle(-201, -201, pTMap->m_Width+402, pTMap->m_Height+402, - 0, TILE_DEATH, // display air inside, death outside - 32.0f, Color.v4()*ColorHint.v4(), TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, - EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + RenderTools()->RenderTileRectangle(-201, -201, pTMap->m_Width + 402, pTMap->m_Height + 402, + 0, TILE_DEATH, // display air inside, death outside + 32.0f, Color.v4() * ColorHint.v4(), TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } - RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, - EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else { @@ -1745,12 +1745,12 @@ void CMapLayers::OnRender() { // slow blinking to hint that it's not a part of the map double Seconds = time_get() / (double)time_freq(); - ColorRGBA ColorHint = ColorRGBA(1.0f, 1.0f, 1.0f, 0.3f + 0.7f*(1.0 + sin(2.0f*pi*Seconds / 3.f)) / 2.0f); + ColorRGBA ColorHint = ColorRGBA(1.0f, 1.0f, 1.0f, 0.3f + 0.7f * (1.0 + sin(2.0f * pi * Seconds / 3.f)) / 2.0f); - ColorRGBA ColorKill(Color.x*ColorHint.x,Color.y*ColorHint.y,Color.z*ColorHint.z,Color.w*ColorHint.w); - RenderKillTileBorder(TileLayerCounter-1, &ColorKill, pTMap, pGroup); + ColorRGBA ColorKill(Color.x * ColorHint.x, Color.y * ColorHint.y, Color.z * ColorHint.z, Color.w * ColorHint.w); + RenderKillTileBorder(TileLayerCounter - 1, &ColorKill, pTMap, pGroup); } - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } @@ -1776,7 +1776,7 @@ void CMapLayers::OnRender() } else { - RenderQuadLayer(QuadLayerCounter-1, pQLayer, pGroup, true); + RenderQuadLayer(QuadLayerCounter - 1, pQLayer, pGroup, true); } } } @@ -1791,7 +1791,7 @@ void CMapLayers::OnRender() } else { - RenderQuadLayer(QuadLayerCounter-1, pQLayer, pGroup, false); + RenderQuadLayer(QuadLayerCounter - 1, pQLayer, pGroup, false); } } } @@ -1804,22 +1804,22 @@ void CMapLayers::OnRender() CTile *pFrontTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Front); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Front); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f * EntityOverlayVal / 100.0f); if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, - EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); - RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, - EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else { Graphics()->BlendNormal(); - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } @@ -1831,13 +1831,13 @@ void CMapLayers::OnRender() CSwitchTile *pSwitchTiles = (CSwitchTile *)m_pLayers->Map()->GetData(pTMap->m_Switch); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Switch); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSwitchTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CSwitchTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f * EntityOverlayVal / 100.0f); if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSwitchOverlay(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, EntityOverlayVal / 100.0f); @@ -1845,13 +1845,13 @@ void CMapLayers::OnRender() else { Graphics()->BlendNormal(); - RenderTileLayer(TileLayerCounter-3, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 3, &Color, pTMap, pGroup); if(g_Config.m_ClTextEntities) { Graphics()->TextureSet(m_pImages->GetOverlayBottom()); - RenderTileLayer(TileLayerCounter-2, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 2, &Color, pTMap, pGroup); Graphics()->TextureSet(m_pImages->GetOverlayTop()); - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } @@ -1864,13 +1864,13 @@ void CMapLayers::OnRender() CTeleTile *pTeleTiles = (CTeleTile *)m_pLayers->Map()->GetData(pTMap->m_Tele); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Tele); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTeleTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CTeleTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f * EntityOverlayVal / 100.0f); if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderTeleOverlay(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, EntityOverlayVal / 100.0f); @@ -1878,11 +1878,11 @@ void CMapLayers::OnRender() else { Graphics()->BlendNormal(); - RenderTileLayer(TileLayerCounter-2, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 2, &Color, pTMap, pGroup); if(g_Config.m_ClTextEntities) { Graphics()->TextureSet(m_pImages->GetOverlayCenter()); - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } @@ -1895,13 +1895,13 @@ void CMapLayers::OnRender() CSpeedupTile *pSpeedupTiles = (CSpeedupTile *)m_pLayers->Map()->GetData(pTMap->m_Speedup); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Speedup); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSpeedupTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CSpeedupTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f * EntityOverlayVal / 100.0f); if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSpeedupOverlay(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, EntityOverlayVal / 100.0f); @@ -1913,14 +1913,14 @@ void CMapLayers::OnRender() // draw arrow -- clamp to the edge of the arrow image Graphics()->WrapClamp(); Graphics()->TextureSet(m_pImages->GetSpeedupArrow()); - RenderTileLayer(TileLayerCounter-3, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 3, &Color, pTMap, pGroup); Graphics()->WrapNormal(); if(g_Config.m_ClTextEntities) { Graphics()->TextureSet(m_pImages->GetOverlayBottom()); - RenderTileLayer(TileLayerCounter-2, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 2, &Color, pTMap, pGroup); Graphics()->TextureSet(m_pImages->GetOverlayTop()); - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } @@ -1933,13 +1933,13 @@ void CMapLayers::OnRender() CTuneTile *pTuneTiles = (CTuneTile *)m_pLayers->Map()->GetData(pTMap->m_Tune); unsigned int Size = m_pLayers->Map()->GetDataSize(pTMap->m_Tune); - if(Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTuneTile)) + if(Size >= pTMap->m_Width * pTMap->m_Height * sizeof(CTuneTile)) { ColorRGBA Color = ColorRGBA(pTMap->m_Color.r / 255.0f, pTMap->m_Color.g / 255.0f, pTMap->m_Color.b / 255.0f, pTMap->m_Color.a / 255.0f * EntityOverlayVal / 100.0f); if(!Graphics()->IsTileBufferingEnabled()) { Graphics()->BlendNone(); - RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND | LAYERRENDERFLAG_TRANSPARENT); //RenderTools()->RenderTuneOverlay(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, EntityOverlayVal/100.0f); @@ -1947,7 +1947,7 @@ void CMapLayers::OnRender() else { Graphics()->BlendNormal(); - RenderTileLayer(TileLayerCounter-1, &Color, pTMap, pGroup); + RenderTileLayer(TileLayerCounter - 1, &Color, pTMap, pGroup); } } } diff --git a/src/game/client/components/maplayers.h b/src/game/client/components/maplayers.h index 58ae1e6b5..b2ff03418 100644 --- a/src/game/client/components/maplayers.h +++ b/src/game/client/components/maplayers.h @@ -4,15 +4,14 @@ #define GAME_CLIENT_COMPONENTS_MAPLAYERS_H #include -#include #include - +#include #define INDEX_BUFFER_GROUP_WIDTH 12 #define INDEX_BUFFER_GROUP_HEIGHT 9 #define INDEX_BORDER_BUFFER_GROUP_SIZE 20 -typedef char* offset_ptr_size; +typedef char *offset_ptr_size; typedef uintptr_t offset_ptr; typedef unsigned int offset_ptr32; @@ -34,7 +33,8 @@ class CMapLayers : public CComponent struct STileLayerVisuals { - STileLayerVisuals() : m_TilesOfLayer(NULL), m_BorderTop(NULL), m_BorderLeft(NULL), m_BorderRight(NULL), m_BorderBottom(NULL) + STileLayerVisuals() : + m_TilesOfLayer(NULL), m_BorderTop(NULL), m_BorderLeft(NULL), m_BorderRight(NULL), m_BorderBottom(NULL) { m_Width = 0; m_Height = 0; @@ -48,13 +48,16 @@ class CMapLayers : public CComponent struct STileVisual { - STileVisual() : m_IndexBufferByteOffset(0) { } + STileVisual() : + m_IndexBufferByteOffset(0) {} + private: offset_ptr32 m_IndexBufferByteOffset; + public: bool DoDraw() { - return (m_IndexBufferByteOffset&0x00000001) != 0; + return (m_IndexBufferByteOffset & 0x00000001) != 0; } void Draw(bool SetDraw) @@ -77,7 +80,7 @@ class CMapLayers : public CComponent m_IndexBufferByteOffset = ((m_IndexBufferByteOffset & 0xFFFFFFFE) + IndexBufferByteOff) | (m_IndexBufferByteOffset & 0x00000001); } }; - STileVisual* m_TilesOfLayer; + STileVisual *m_TilesOfLayer; STileVisual m_BorderTopLeft; STileVisual m_BorderTopRight; @@ -86,42 +89,45 @@ class CMapLayers : public CComponent STileVisual m_BorderKillTile; //end of map kill tile -- game layer only - STileVisual* m_BorderTop; - STileVisual* m_BorderLeft; - STileVisual* m_BorderRight; - STileVisual* m_BorderBottom; + STileVisual *m_BorderTop; + STileVisual *m_BorderLeft; + STileVisual *m_BorderRight; + STileVisual *m_BorderBottom; unsigned int m_Width; unsigned int m_Height; int m_BufferContainerIndex; bool m_IsTextured; }; - std::vector m_TileLayerVisuals; + std::vector m_TileLayerVisuals; struct SQuadLayerVisuals { - SQuadLayerVisuals() : m_QuadNum(0), m_QuadsOfLayer(NULL), m_BufferContainerIndex(-1), m_IsTextured(false) {} + SQuadLayerVisuals() : + m_QuadNum(0), m_QuadsOfLayer(NULL), m_BufferContainerIndex(-1), m_IsTextured(false) {} struct SQuadVisual { - SQuadVisual() : m_IndexBufferByteOffset(0) {} + SQuadVisual() : + m_IndexBufferByteOffset(0) {} offset_ptr m_IndexBufferByteOffset; }; int m_QuadNum; - SQuadVisual* m_QuadsOfLayer; + SQuadVisual *m_QuadsOfLayer; int m_BufferContainerIndex; bool m_IsTextured; }; - std::vector m_QuadLayerVisuals; + std::vector m_QuadLayerVisuals; virtual class CCamera *GetCurCamera(); void LayersOfGroupCount(CMapItemGroup *pGroup, int &TileLayerCount, int &QuadLayerCount, bool &PassedGameLayer); void RenderTileBorderCornerTiles(int WidthOffsetToOrigin, int HeightOffsetToOrigin, int TileCountWidth, int TileCountHeight, int BufferContainerIndex, float *pColor, offset_ptr_size IndexBufferOffset, float *pOffset, float *pDir); + public: enum { @@ -137,10 +143,10 @@ public: virtual void OnRender(); virtual void OnMapLoad(); - void RenderTileLayer(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup); - void RenderTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup, int BorderX0, int BorderY0, int BorderX1, int BorderY1, int ScreenWidthTileCount, int ScreenHeightTileCount); - void RenderKillTileBorder(int LayerIndex, ColorRGBA* pColor, CMapItemLayerTilemap* pTileLayer, CMapItemGroup* pGroup); - void RenderQuadLayer(int LayerIndex, CMapItemLayerQuads* pQuadLayer, CMapItemGroup* pGroup, bool ForceRender = false); + void RenderTileLayer(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup); + void RenderTileBorder(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup, int BorderX0, int BorderY0, int BorderX1, int BorderY1, int ScreenWidthTileCount, int ScreenHeightTileCount); + void RenderKillTileBorder(int LayerIndex, ColorRGBA *pColor, CMapItemLayerTilemap *pTileLayer, CMapItemGroup *pGroup); + void RenderQuadLayer(int LayerIndex, CMapItemLayerQuads *pQuadLayer, CMapItemGroup *pGroup, bool ForceRender = false); void EnvelopeUpdate(); diff --git a/src/game/client/components/mapsounds.cpp b/src/game/client/components/mapsounds.cpp index e795cf4ee..eec4163fa 100644 --- a/src/game/client/components/mapsounds.cpp +++ b/src/game/client/components/mapsounds.cpp @@ -28,7 +28,7 @@ void CMapSounds::OnMapLoad() { m_aSounds[i] = 0; - CMapItemSound *pSound = (CMapItemSound *)pMap->GetItem(Start+i, 0, 0); + CMapItemSound *pSound = (CMapItemSound *)pMap->GetItem(Start + i, 0, 0); if(pSound->m_External) { char Buf[256]; @@ -55,7 +55,7 @@ void CMapSounds::OnMapLoad() for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer + l); if(!pLayer) continue; @@ -75,11 +75,12 @@ void CMapSounds::OnMapLoad() if(!pSources) continue; - for(int i = 0; i < pSoundLayer->m_NumSources; i++) { + for(int i = 0; i < pSoundLayer->m_NumSources; i++) + { CSourceQueueEntry source; source.m_Sound = pSoundLayer->m_Sound; source.m_pSource = &pSources[i]; - source.m_HighDetail = pLayer->m_Flags&LAYERFLAG_DETAIL; + source.m_HighDetail = pLayer->m_Flags & LAYERFLAG_DETAIL; if(!source.m_pSource || source.m_Sound == -1) continue; @@ -106,11 +107,11 @@ void CMapSounds::OnRender() static float s_Time = 0.0f; if(m_pClient->m_Snap.m_pGameInfoObj) // && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) { - s_Time = mix((Client()->PrevGameTick(g_Config.m_ClDummy)-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), - (Client()->GameTick(g_Config.m_ClDummy)-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), - Client()->IntraGameTick(g_Config.m_ClDummy)); + s_Time = mix((Client()->PrevGameTick(g_Config.m_ClDummy) - m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), + (Client()->GameTick(g_Config.m_ClDummy) - m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), + Client()->IntraGameTick(g_Config.m_ClDummy)); } - float Offset = s_Time-pSource->m_pSource->m_TimeDelay; + float Offset = s_Time - pSource->m_pSource->m_TimeDelay; if(!DemoPlayerPaused && Offset >= 0.0f && g_Config.m_SndEnable && (g_Config.m_GfxHighDetail || !pSource->m_HighDetail)) { if(pSource->m_Voice.IsValid()) @@ -122,25 +123,27 @@ void CMapSounds::OnRender() { // need to enqueue int Flags = 0; - if(pSource->m_pSource->m_Loop) Flags |= ISound::FLAG_LOOP; - if(!pSource->m_pSource->m_Pan) Flags |= ISound::FLAG_NO_PANNING; + if(pSource->m_pSource->m_Loop) + Flags |= ISound::FLAG_LOOP; + if(!pSource->m_pSource->m_Pan) + Flags |= ISound::FLAG_NO_PANNING; pSource->m_Voice = m_pClient->m_pSounds->PlaySampleAt(CSounds::CHN_MAPSOUND, m_aSounds[pSource->m_Sound], 1.0f, vec2(fx2f(pSource->m_pSource->m_Position.x), fx2f(pSource->m_pSource->m_Position.y)), Flags); Sound()->SetVoiceTimeOffset(pSource->m_Voice, Offset); - Sound()->SetVoiceFalloff(pSource->m_Voice, pSource->m_pSource->m_Falloff/255.0f); + Sound()->SetVoiceFalloff(pSource->m_Voice, pSource->m_pSource->m_Falloff / 255.0f); switch(pSource->m_pSource->m_Shape.m_Type) { case CSoundShape::SHAPE_CIRCLE: - { - Sound()->SetVoiceCircle(pSource->m_Voice, pSource->m_pSource->m_Shape.m_Circle.m_Radius); - break; - } + { + Sound()->SetVoiceCircle(pSource->m_Voice, pSource->m_pSource->m_Shape.m_Circle.m_Radius); + break; + } case CSoundShape::SHAPE_RECTANGLE: - { - Sound()->SetVoiceRectangle(pSource->m_Voice, fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Width), fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Height)); - break; - } + { + Sound()->SetVoiceRectangle(pSource->m_Voice, fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Width), fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Height)); + break; + } }; } } @@ -162,7 +165,7 @@ void CMapSounds::OnRender() for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer + l); if(!pLayer) continue; @@ -179,7 +182,8 @@ void CMapSounds::OnRender() if(!pSources) continue; - for(int s = 0; s < pSoundLayer->m_NumSources; s++) { + for(int s = 0; s < pSoundLayer->m_NumSources; s++) + { for(int i = 0; i < m_lSourceQueue.size(); i++) { CSourceQueueEntry *pVoice = &m_lSourceQueue[i]; @@ -195,25 +199,26 @@ void CMapSounds::OnRender() if(pVoice->m_pSource->m_PosEnv >= 0) { float aChannels[4]; - CMapLayers::EnvelopeEval(pVoice->m_pSource->m_PosEnvOffset/1000.0f, pVoice->m_pSource->m_PosEnv, aChannels, m_pClient->m_pMapLayersBackGround); + CMapLayers::EnvelopeEval(pVoice->m_pSource->m_PosEnvOffset / 1000.0f, pVoice->m_pSource->m_PosEnv, aChannels, m_pClient->m_pMapLayersBackGround); OffsetX = aChannels[0]; OffsetY = aChannels[1]; } - float x = fx2f(pVoice->m_pSource->m_Position.x)+OffsetX; - float y = fx2f(pVoice->m_pSource->m_Position.y)+OffsetY; + float x = fx2f(pVoice->m_pSource->m_Position.x) + OffsetX; + float y = fx2f(pVoice->m_pSource->m_Position.y) + OffsetY; - x += Center.x*(1.0f-pGroup->m_ParallaxX/100.0f); - y += Center.y*(1.0f-pGroup->m_ParallaxY/100.0f); + x += Center.x * (1.0f - pGroup->m_ParallaxX / 100.0f); + y += Center.y * (1.0f - pGroup->m_ParallaxY / 100.0f); - x -= pGroup->m_OffsetX; y -= pGroup->m_OffsetY; + x -= pGroup->m_OffsetX; + y -= pGroup->m_OffsetY; Sound()->SetVoiceLocation(pVoice->m_Voice, x, y); if(pVoice->m_pSource->m_SoundEnv >= 0) { float aChannels[4]; - CMapLayers::EnvelopeEval(pVoice->m_pSource->m_SoundEnvOffset/1000.0f, pVoice->m_pSource->m_SoundEnv, aChannels, m_pClient->m_pMapLayersBackGround); + CMapLayers::EnvelopeEval(pVoice->m_pSource->m_SoundEnvOffset / 1000.0f, pVoice->m_pSource->m_SoundEnv, aChannels, m_pClient->m_pMapLayersBackGround); float Volume = clamp(aChannels[0], 0.0f, 1.0f); Sound()->SetVoiceVolume(pVoice->m_Voice, Volume); diff --git a/src/game/client/components/mapsounds.h b/src/game/client/components/mapsounds.h index ffc1a58de..f3ecc0f3d 100644 --- a/src/game/client/components/mapsounds.h +++ b/src/game/client/components/mapsounds.h @@ -19,7 +19,7 @@ class CMapSounds : public CComponent ISound::CVoiceHandle m_Voice; CSoundSource *m_pSource; - bool operator ==(const CSourceQueueEntry &Other) const { return (m_Sound == Other.m_Sound) && (m_Voice == Other.m_Voice) && (m_pSource == Other.m_pSource); } + bool operator==(const CSourceQueueEntry &Other) const { return (m_Sound == Other.m_Sound) && (m_Voice == Other.m_Voice) && (m_pSource == Other.m_pSource); } }; array m_lSourceQueue; diff --git a/src/game/client/components/menu_background.cpp b/src/game/client/components/menu_background.cpp index c748a1ed1..4a25376aa 100644 --- a/src/game/client/components/menu_background.cpp +++ b/src/game/client/components/menu_background.cpp @@ -12,8 +12,8 @@ #include "menu_background.h" -CMenuBackground::CMenuBackground() - : CBackground(CMapLayers::TYPE_FULL_DESIGN, false) +CMenuBackground::CMenuBackground() : + CBackground(CMapLayers::TYPE_FULL_DESIGN, false) { m_RotationCenter = vec2(0.0f, 0.0f); m_AnimationStartPos = vec2(0.0f, 0.0f); diff --git a/src/game/client/components/menu_background.h b/src/game/client/components/menu_background.h index e94ba8cd3..d509a36f2 100644 --- a/src/game/client/components/menu_background.h +++ b/src/game/client/components/menu_background.h @@ -16,8 +16,8 @@ class CTheme { public: CTheme() {} - CTheme(const char *n, bool HasDay, bool HasNight) - : m_Name(n), m_HasDay(HasDay), m_HasNight(HasNight) {} + CTheme(const char *n, bool HasDay, bool HasNight) : + m_Name(n), m_HasDay(HasDay), m_HasNight(HasNight) {} string m_Name; bool m_HasDay; diff --git a/src/game/client/components/menus.h b/src/game/client/components/menus.h index b2bbe8c60..dfbb3abfd 100644 --- a/src/game/client/components/menus.h +++ b/src/game/client/components/menus.h @@ -3,17 +3,17 @@ #ifndef GAME_CLIENT_COMPONENTS_MENUS_H #define GAME_CLIENT_COMPONENTS_MENUS_H -#include #include +#include #include #include #include #include -#include #include #include +#include struct CServerProcess { @@ -141,7 +141,10 @@ class CMenus : public CComponent void PopupMessage(const char *pTopic, const char *pBody, const char *pButton); // TODO: this is a bit ugly but.. well.. yeah - enum { MAX_INPUTEVENTS = 32 }; + enum + { + MAX_INPUTEVENTS = 32 + }; static IInput::CEvent m_aInputEvents[MAX_INPUTEVENTS]; static int m_NumInputEvents; @@ -181,7 +184,7 @@ class CMenus : public CComponent // demo enum { - SORT_DEMONAME=0, + SORT_DEMONAME = 0, SORT_MARKERS, SORT_LENGTH, SORT_DATE, @@ -203,14 +206,14 @@ class CMenus : public CComponent int NumMarkers() const { - return ((m_TimelineMarkers.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_TimelineMarkers.m_aNumTimelineMarkers[1]<<16)&0xFF0000) | - ((m_TimelineMarkers.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_TimelineMarkers.m_aNumTimelineMarkers[3]&0xFF); + return ((m_TimelineMarkers.m_aNumTimelineMarkers[0] << 24) & 0xFF000000) | ((m_TimelineMarkers.m_aNumTimelineMarkers[1] << 16) & 0xFF0000) | + ((m_TimelineMarkers.m_aNumTimelineMarkers[2] << 8) & 0xFF00) | (m_TimelineMarkers.m_aNumTimelineMarkers[3] & 0xFF); } int Length() const { - return ((m_Info.m_aLength[0]<<24)&0xFF000000) | ((m_Info.m_aLength[1]<<16)&0xFF0000) | - ((m_Info.m_aLength[2]<<8)&0xFF00) | (m_Info.m_aLength[3]&0xFF); + return ((m_Info.m_aLength[0] << 24) & 0xFF000000) | ((m_Info.m_aLength[1] << 16) & 0xFF0000) | + ((m_Info.m_aLength[2] << 8) & 0xFF00) | (m_Info.m_aLength[3] & 0xFF); } bool operator<(const CDemoItem &Other) const @@ -356,7 +359,7 @@ public: CMenus(); void RenderLoading(); - void RenderUpdating(const char *pCaption, int current=0, int total=0); + void RenderUpdating(const char *pCaption, int current = 0, int total = 0); bool IsActive() const { return m_MenuActive; } void KillServer(); @@ -371,7 +374,7 @@ public: enum { - PAGE_NEWS=1, + PAGE_NEWS = 1, PAGE_GAME, PAGE_PLAYERS, PAGE_SERVER_INFO, @@ -387,7 +390,7 @@ public: PAGE_NETWORK, PAGE_GHOST, - SETTINGS_LANGUAGE=0, + SETTINGS_LANGUAGE = 0, SETTINGS_GENERAL, SETTINGS_PLAYER, SETTINGS_TEE, @@ -416,7 +419,8 @@ public: int m_Slot; bool m_Own; - CGhostItem() : m_Slot(-1), m_Own(false) { m_aFilename[0] = 0; } + CGhostItem() : + m_Slot(-1), m_Own(false) { m_aFilename[0] = 0; } bool operator<(const CGhostItem &Other) { return m_Time < Other.m_Time; } @@ -445,7 +449,7 @@ public: enum { - POPUP_NONE=0, + POPUP_NONE = 0, POPUP_FIRST_LAUNCH, POPUP_CONNECTING, POPUP_MESSAGE, @@ -466,7 +470,7 @@ public: POPUP_WARNING, // demo player states - DEMOPLAYER_NONE=0, + DEMOPLAYER_NONE = 0, DEMOPLAYER_SLICE_SAVE, }; diff --git a/src/game/client/components/menus_browser.cpp b/src/game/client/components/menus_browser.cpp index 70093209a..7f37decc7 100644 --- a/src/game/client/components/menus_browser.cpp +++ b/src/game/client/components/menus_browser.cpp @@ -5,23 +5,22 @@ #include #include #include +#include #include #include -#include #include #include -#include -#include +#include +#include #include #include -#include -#include +#include +#include #include "menus.h" - void CMenus::RenderServerbrowserServerList(CUIRect View) { CUIRect Headers; @@ -31,7 +30,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) View.HSplitBottom(70.0f, &View, &Status); // split of the scrollbar - RenderTools()->DrawUIRect(&Headers, ColorRGBA(1,1,1,0.25f), CUI::CORNER_T, 5.0f); + RenderTools()->DrawUIRect(&Headers, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_T, 5.0f); Headers.VSplitRight(20.0f, &Headers, 0); struct CColumn @@ -48,10 +47,10 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) enum { - FIXED=1, - SPACER=2, + FIXED = 1, + SPACER = 2, - COL_FLAG_LOCK=0, + COL_FLAG_LOCK = 0, COL_FLAG_FAV, COL_FLAG_OFFICIAL, COL_NAME, @@ -63,21 +62,21 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) }; CColumn s_aCols[] = { - {-1, -1, " ", -1, 2.0f, 0, {0}, {0}}, - {COL_FLAG_LOCK, -1, " ", -1, 14.0f, 0, {0}, {0}}, - {COL_FLAG_FAV, -1, " ", -1, 14.0f, 0, {0}, {0}}, - {COL_FLAG_OFFICIAL, -1, " ", -1, 14.0f, 0, {0}, {0}}, - {COL_NAME, IServerBrowser::SORT_NAME, "Name", 0, 50.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString - {COL_GAMETYPE, IServerBrowser::SORT_GAMETYPE, "Type", 1, 50.0f, 0, {0}, {0}}, - {COL_MAP, IServerBrowser::SORT_MAP, "Map", 1, 120.0f + (Headers.w - 480) / 8, 0, {0}, {0}}, - {COL_PLAYERS, IServerBrowser::SORT_NUMPLAYERS, "Players", 1, 60.0f, 0, {0}, {0}}, - {-1, -1, " ", 1, 10.0f, 0, {0}, {0}}, - {COL_PING, IServerBrowser::SORT_PING, "Ping", 1, 40.0f, FIXED, {0}, {0}}, + {-1, -1, " ", -1, 2.0f, 0, {0}, {0}}, + {COL_FLAG_LOCK, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_FLAG_FAV, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_FLAG_OFFICIAL, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_NAME, IServerBrowser::SORT_NAME, "Name", 0, 50.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString + {COL_GAMETYPE, IServerBrowser::SORT_GAMETYPE, "Type", 1, 50.0f, 0, {0}, {0}}, + {COL_MAP, IServerBrowser::SORT_MAP, "Map", 1, 120.0f + (Headers.w - 480) / 8, 0, {0}, {0}}, + {COL_PLAYERS, IServerBrowser::SORT_NUMPLAYERS, "Players", 1, 60.0f, 0, {0}, {0}}, + {-1, -1, " ", 1, 10.0f, 0, {0}, {0}}, + {COL_PING, IServerBrowser::SORT_PING, "Ping", 1, 40.0f, FIXED, {0}, {0}}, }; // This is just for scripts/update_localization.py to work correctly (all other strings are already Localize()'d somewhere else). Don't remove! // Localize("Type"); - int NumCols = sizeof(s_aCols)/sizeof(CColumn); + int NumCols = sizeof(s_aCols) / sizeof(CColumn); // do layout for(int i = 0; i < NumCols; i++) @@ -86,7 +85,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) { Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); - if(i+1 < NumCols) + if(i + 1 < NumCols) { //Cols[i].flags |= SPACER; Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); @@ -94,7 +93,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } } - for(int i = NumCols-1; i >= 0; i--) + for(int i = NumCols - 1; i >= 0; i--) { if(s_aCols[i].m_Direction == 1) { @@ -125,9 +124,9 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) if(g_Config.m_BrSort == s_aCols[i].m_Sort) { if(PlayersOrPing) - g_Config.m_BrSortOrder = (g_Config.m_BrSortOrder+1)%3; + g_Config.m_BrSortOrder = (g_Config.m_BrSortOrder + 1) % 3; else - g_Config.m_BrSortOrder = (g_Config.m_BrSortOrder+1)%2; + g_Config.m_BrSortOrder = (g_Config.m_BrSortOrder + 1) % 2; } else g_Config.m_BrSortOrder = 0; @@ -136,7 +135,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } } - RenderTools()->DrawUIRect(&View, ColorRGBA(0,0,0,0.15f), 0, 0); + RenderTools()->DrawUIRect(&View, ColorRGBA(0, 0, 0, 0.15f), 0, 0); CUIRect Scroll; View.VSplitRight(15, &View, &Scroll); @@ -156,25 +155,25 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) UI()->DoLabelScaled(&MsgBox, Localize("No servers match your filter criteria"), 16.0f, 0); } - int Num = (int)(View.h/s_aCols[0].m_Rect.h) + 1; + int Num = (int)(View.h / s_aCols[0].m_Rect.h) + 1; static int s_ScrollBar = 0; static float s_ScrollValue = 0; Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); - int ScrollNum = NumServers-Num+1; + int ScrollNum = NumServers - Num + 1; if(ScrollNum > 0) { if(m_ScrollOffset >= 0) { - s_ScrollValue = (float)(m_ScrollOffset)/ScrollNum; + s_ScrollValue = (float)(m_ScrollOffset) / ScrollNum; m_ScrollOffset = -1; } if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) - s_ScrollValue -= 3.0f/ScrollNum; + s_ScrollValue -= 3.0f / ScrollNum; if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) - s_ScrollValue += 3.0f/ScrollNum; + s_ScrollValue += 3.0f / ScrollNum; } else ScrollNum = 0; @@ -192,31 +191,37 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; - if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + if(m_aInputEvents[i].m_Flags & IInput::FLAG_PRESS) { - if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = minimum(m_SelectedIndex + 1, NumServers - 1); - else if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = maximum(m_SelectedIndex - 1, 0); - else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) NewIndex = maximum(m_SelectedIndex - 25, 0); - else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) NewIndex = minimum(m_SelectedIndex + 25, NumServers - 1); - else if(m_aInputEvents[i].m_Key == KEY_HOME) NewIndex = 0; - else if(m_aInputEvents[i].m_Key == KEY_END) NewIndex = NumServers - 1; + if(m_aInputEvents[i].m_Key == KEY_DOWN) + NewIndex = minimum(m_SelectedIndex + 1, NumServers - 1); + else if(m_aInputEvents[i].m_Key == KEY_UP) + NewIndex = maximum(m_SelectedIndex - 1, 0); + else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) + NewIndex = maximum(m_SelectedIndex - 25, 0); + else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) + NewIndex = minimum(m_SelectedIndex + 25, NumServers - 1); + else if(m_aInputEvents[i].m_Key == KEY_HOME) + NewIndex = 0; + else if(m_aInputEvents[i].m_Key == KEY_END) + NewIndex = NumServers - 1; } if(NewIndex > -1 && NewIndex < NumServers) { //scroll - float IndexY = View.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; - int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; + float IndexY = View.y - s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h + NewIndex * s_aCols[0].m_Rect.h; + int Scroll = View.y > IndexY ? -1 : View.y + View.h < IndexY + s_aCols[0].m_Rect.h ? 1 : 0; if(Scroll) { if(Scroll < 0) { - int NumScrolls = (View.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (View.y - IndexY + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f / ScrollNum) * NumScrolls; } else { - int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(View.y+View.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (IndexY + s_aCols[0].m_Rect.h - (View.y + View.h) + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f / ScrollNum) * NumScrolls; } } @@ -227,14 +232,16 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } } - if(s_ScrollValue < 0) s_ScrollValue = 0; - if(s_ScrollValue > 1) s_ScrollValue = 1; + if(s_ScrollValue < 0) + s_ScrollValue = 0; + if(s_ScrollValue > 1) + s_ScrollValue = 1; // set clipping UI()->ClipEnable(&View); CUIRect OriginalView = View; - View.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + View.y -= s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h; int NewSelected = -1; int DoubleClicked = 0; @@ -243,7 +250,8 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) m_SelectedIndex = -1; // reset friend counter - for(int i = 0; i < m_lFriends.size(); m_lFriends[i++].m_NumFound = 0); + for(int i = 0; i < m_lFriends.size(); m_lFriends[i++].m_NumFound = 0) + ; for(int i = 0; i < NumServers; i++) { @@ -285,19 +293,19 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } // make sure that only those in view can be selected - if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + if(Row.y + Row.h > OriginalView.y && Row.y < OriginalView.y + OriginalView.h) { if(Selected) { CUIRect r = Row; r.Margin(0.5f, &r); - RenderTools()->DrawUIRect(&r, ColorRGBA(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + RenderTools()->DrawUIRect(&r, ColorRGBA(1, 1, 1, 0.5f), CUI::CORNER_ALL, 4.0f); } // clip the selection if(SelectHitBox.y < OriginalView.y) // top { - SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.h -= OriginalView.y - SelectHitBox.y; SelectHitBox.y = OriginalView.y; } else if(SelectHitBox.y + SelectHitBox.h > OriginalView.y + OriginalView.h) // bottom @@ -358,20 +366,20 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) { CTextCursor Cursor; float FontSize = 12.0f * UI()->Scale(); - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; - if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_SERVERNAME)) + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit & IServerBrowser::QUICK_SERVERNAME)) { // highlight the parts that matches const char *pStr = str_find_nocase(pItem->m_aName, g_Config.m_BrFilterString); if(pStr) { - TextRender()->TextEx(&Cursor, pItem->m_aName, (int)(pStr-pItem->m_aName)); - TextRender()->TextColor(0.4f,0.4f,1.0f,1); + TextRender()->TextEx(&Cursor, pItem->m_aName, (int)(pStr - pItem->m_aName)); + TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1); TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); - TextRender()->TextColor(1,1,1,1); - TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); + TextRender()->TextColor(1, 1, 1, 1); + TextRender()->TextEx(&Cursor, pStr + str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pItem->m_aName, -1); @@ -388,26 +396,26 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) Button.VSplitLeft(Button.h, &Icon, &Button); Icon.Margin(2.0f, &Icon); - if (g_Config.m_BrIndicateFinished && pItem->m_HasRank == 1) - DoButton_Icon(IMAGE_BROWSEICONS, SPRITE_BROWSE_RANK, &Icon); + if(g_Config.m_BrIndicateFinished && pItem->m_HasRank == 1) + DoButton_Icon(IMAGE_BROWSEICONS, SPRITE_BROWSE_RANK, &Icon); } CTextCursor Cursor; float FontSize = 12.0f * UI()->Scale(); - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; - if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_MAPNAME)) + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit & IServerBrowser::QUICK_MAPNAME)) { // highlight the parts that matches const char *pStr = str_find_nocase(pItem->m_aMap, g_Config.m_BrFilterString); if(pStr) { - TextRender()->TextEx(&Cursor, pItem->m_aMap, (int)(pStr-pItem->m_aMap)); - TextRender()->TextColor(0.4f,0.4f,1.0f,1); + TextRender()->TextEx(&Cursor, pItem->m_aMap, (int)(pStr - pItem->m_aMap)); + TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1); TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); - TextRender()->TextColor(1,1,1,1); - TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); + TextRender()->TextColor(1, 1, 1, 1); + TextRender()->TextEx(&Cursor, pStr + str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pItem->m_aMap, -1); @@ -427,10 +435,10 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } str_format(aTemp, sizeof(aTemp), "%i/%i", pItem->m_NumFilteredPlayers, ServerBrowser()->Max(*pItem)); - if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_PLAYER)) - TextRender()->TextColor(0.4f,0.4f,1.0f,1); + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit & IServerBrowser::QUICK_PLAYER)) + TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1); UI()->DoLabelScaled(&Button, aTemp, 12.0f, 1); - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); } else if(ID == COL_PING) { @@ -453,7 +461,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) { CTextCursor Cursor; float FontSize = 12.0f * UI()->Scale(); - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, 12.0f*UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - FontSize) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; if(g_Config.m_UiColorizeGametype) @@ -720,7 +728,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) if(g_Config.m_BrFilterPing != 0) str_format(aBuf, sizeof(aBuf), "%d", g_Config.m_BrFilterPing); static float Offset = 0.0f; - if (DoEditBox(&g_Config.m_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset)) + if(DoEditBox(&g_Config.m_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset)) { g_Config.m_BrFilterPing = clamp(str_toint(aBuf), 0, 999); Client()->ServerBrowserUpdate(); @@ -747,9 +755,9 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) g_Config.m_BrFilterCountry ^= 1; float OldWidth = Rect.w; - Rect.w = Rect.h*2; - Rect.x += (OldWidth-Rect.w)/2.0f; - ColorRGBA Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f); + Rect.w = Rect.h * 2; + Rect.x += (OldWidth - Rect.w) / 2.0f; + ColorRGBA Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry ? 1.0f : 0.5f); m_pClient->m_pCountryFlags->Render(g_Config.m_BrFilterCountryIndex, &Color, Rect.x, Rect.y, Rect.w, Rect.h); if(g_Config.m_BrFilterCountry && UI()->DoButtonLogic(&g_Config.m_BrFilterCountryIndex, "", 0, &Rect)) @@ -776,7 +784,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) { g_Config.m_BrIndicateFinished ^= 1; - if (g_Config.m_BrIndicateFinished) + if(g_Config.m_BrIndicateFinished) ServerBrowser()->Refresh(ServerBrowser()->GetCurrentType()); } @@ -846,7 +854,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) const char *pName = ServerBrowser()->GetType(Network, TypeIndex); bool Active = !ServerBrowser()->DDNetFiltered(pFilterExcludeTypes, pName); - vec2 Pos = vec2(TypesRect.x+TypesRect.w*((i+0.5f)/(float)PerLine), TypesRect.y); + vec2 Pos = vec2(TypesRect.x + TypesRect.w * ((i + 0.5f) / (float)PerLine), TypesRect.y); // correct pos Pos.x -= TypesWidth / 2.0f; @@ -921,7 +929,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) bool Active = !ServerBrowser()->DDNetFiltered(pFilterExcludeCountries, pName); int FlagID = ServerBrowser()->GetCountryFlag(Network, CountryIndex); - vec2 Pos = vec2(FlagsRect.x+FlagsRect.w*((i+0.5f)/(float)PerLine), FlagsRect.y); + vec2 Pos = vec2(FlagsRect.x + FlagsRect.w * ((i + 0.5f) / (float)PerLine), FlagsRect.y); // correct pos Pos.x -= FlagWidth / 2.0f; @@ -1011,9 +1019,9 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) CTextCursor Cursor; const float FontSize = 12.0f; ServerDetails.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerDetails); - RenderTools()->DrawUIRect(&ServerHeader, ColorRGBA(1,1,1,0.25f), CUI::CORNER_T, 4.0f); - RenderTools()->DrawUIRect(&ServerDetails, ColorRGBA(0,0,0,0.15f), CUI::CORNER_B, 4.0f); - UI()->DoLabelScaled(&ServerHeader, Localize("Server details"), FontSize+2.0f, 0); + RenderTools()->DrawUIRect(&ServerHeader, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_T, 4.0f); + RenderTools()->DrawUIRect(&ServerDetails, ColorRGBA(0, 0, 0, 0.15f), CUI::CORNER_B, 4.0f); + UI()->DoLabelScaled(&ServerHeader, Localize("Server details"), FontSize + 2.0f, 0); if(pSelectedServer) { @@ -1022,7 +1030,7 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) CUIRect Row; static CLocConstString s_aLabels[] = { - "Version", // Localize - these strings are localized within CLocConstString + "Version", // Localize - these strings are localized within CLocConstString "Game type", "Ping"}; @@ -1054,22 +1062,21 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) } RightColumn.HSplitTop(15.0f, &Row, &RightColumn); - TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, pSelectedServer->m_aVersion, -1); RightColumn.HSplitTop(15.0f, &Row, &RightColumn); - TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, pSelectedServer->m_aGameType, -1); char aTemp[16]; str_format(aTemp, sizeof(aTemp), "%d", pSelectedServer->m_Latency); RightColumn.HSplitTop(15.0f, &Row, &RightColumn); - TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Row.x, Row.y + (15.f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, aTemp, -1); - } // server scoreboard @@ -1101,8 +1108,8 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) } ColorRGBA Color = pSelectedServer->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? - ColorRGBA(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) : - ColorRGBA(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f); + ColorRGBA(1.0f, 1.0f, 1.0f, (i % 2 + 1) * 0.05f) : + ColorRGBA(0.5f, 1.0f, 0.5f, 0.15f + (i % 2 + 1) * 0.05f); RenderTools()->DrawUIRect(&Name, Color, CUI::CORNER_ALL, 4.0f); Name.VSplitLeft(5.0f, 0, &Name); Name.VSplitLeft(34.0f, &Score, &Name); @@ -1124,13 +1131,13 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) else { int Time = abs(pSelectedServer->m_aClients[i].m_Score); - str_format(aTemp, sizeof(aTemp), "%02d:%02d", Time/60, Time%60); + str_format(aTemp, sizeof(aTemp), "%02d:%02d", Time / 60, Time % 60); } } else str_format(aTemp, sizeof(aTemp), "%d", pSelectedServer->m_aClients[i].m_Score); - TextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/2.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Score.x, Score.y + (Score.h - FontSize) / 2.0f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Score.w; TextRender()->TextEx(&Cursor, aTemp, -1); @@ -1144,11 +1151,11 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) const char *s = str_find_nocase(pName, g_Config.m_BrFilterString); if(s) { - TextRender()->TextEx(&Cursor, pName, (int)(s-pName)); + TextRender()->TextEx(&Cursor, pName, (int)(s - pName)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); - TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); + TextRender()->TextEx(&Cursor, s + str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pName, -1); @@ -1166,11 +1173,11 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) const char *s = str_find_nocase(pClan, g_Config.m_BrFilterString); if(s) { - TextRender()->TextEx(&Cursor, pClan, (int)(s-pClan)); + TextRender()->TextEx(&Cursor, pClan, (int)(s - pClan)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); - TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); + TextRender()->TextEx(&Cursor, s + str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pClan, -1); @@ -1216,9 +1223,9 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) // header ServerFriends.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFriends); - RenderTools()->DrawUIRect(&FilterHeader, ColorRGBA(1,1,1,0.25f), CUI::CORNER_T, 4.0f); - RenderTools()->DrawUIRect(&ServerFriends, ColorRGBA(0,0,0,0.15f), 0, 4.0f); - UI()->DoLabelScaled(&FilterHeader, Localize("Friends"), FontSize+4.0f, 0); + RenderTools()->DrawUIRect(&FilterHeader, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_T, 4.0f); + RenderTools()->DrawUIRect(&ServerFriends, ColorRGBA(0, 0, 0, 0.15f), 0, 4.0f); + UI()->DoLabelScaled(&FilterHeader, Localize("Friends"), FontSize + 4.0f, 0); CUIRect Button, List; ServerFriends.Margin(3.0f, &ServerFriends); @@ -1228,7 +1235,7 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) // friends list(remove friend) static float s_ScrollValue = 0; if(m_FriendlistSelectedIndex >= m_lFriends.size()) - m_FriendlistSelectedIndex = m_lFriends.size()-1; + m_FriendlistSelectedIndex = m_lFriends.size() - 1; UiDoListboxStart(&m_lFriends, &List, 30.0f, "", "", m_lFriends.size(), 1, m_FriendlistSelectedIndex, s_ScrollValue); m_lFriends.sort_range(); @@ -1249,11 +1256,11 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) UI()->DoLabelScaled(&Button, m_lFriends[i].m_pFriendInfo->m_aClan, FontSize, -1); RenderTools()->DrawUIRect(&OnState, m_lFriends[i].m_NumFound ? ColorRGBA(0.0f, 1.0f, 0.0f, 0.25f) : ColorRGBA(1.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_R, 4.0f); - OnState.HMargin((OnState.h-FontSize)/3, &OnState); + OnState.HMargin((OnState.h - FontSize) / 3, &OnState); OnState.VMargin(5.0f, &OnState); char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%i", m_lFriends[i].m_NumFound); - UI()->DoLabelScaled(&OnState, aBuf, FontSize+2, 1); + UI()->DoLabelScaled(&OnState, aBuf, FontSize + 2, 1); } } @@ -1267,7 +1274,7 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) int NumServers = ServerBrowser()->NumSortedServers(); for(int i = 0; i < NumServers && !Found; i++) { - int ItemIndex = m_SelectedIndex != -1 ? (m_SelectedIndex+i+1)%NumServers : i; + int ItemIndex = m_SelectedIndex != -1 ? (m_SelectedIndex + i + 1) % NumServers : i; const CServerInfo *pItem = ServerBrowser()->SortedGet(ItemIndex); if(pItem->m_FriendState != IFriends::FRIEND_NO) { @@ -1276,7 +1283,7 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) if(pItem->m_aClients[j].m_FriendState != IFriends::FRIEND_NO && ((g_Config.m_ClFriendsIgnoreClan && m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0]) || str_quickhash(pItem->m_aClients[j].m_aClan) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_ClanHash) && (!m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0] || - str_quickhash(pItem->m_aClients[j].m_aName) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_NameHash)) + str_quickhash(pItem->m_aClients[j].m_aName) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_NameHash)) { str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); m_ScrollOffset = ItemIndex; diff --git a/src/game/client/components/menus_demo.cpp b/src/game/client/components/menus_demo.cpp index 3d2b29eb4..17cf50053 100644 --- a/src/game/client/components/menus_demo.cpp +++ b/src/game/client/components/menus_demo.cpp @@ -3,18 +3,18 @@ #include -#include #include +#include #include -#include #include -#include +#include #include +#include -#include -#include #include +#include +#include #include #include @@ -26,14 +26,14 @@ int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { - RenderTools()->DrawUIRect(pRect, ColorRGBA(1,1,1, (Checked ? 0.10f : 0.5f)*ButtonColorMul(pID)), CUI::CORNER_ALL, 5.0f); + RenderTools()->DrawUIRect(pRect, ColorRGBA(1, 1, 1, (Checked ? 0.10f : 0.5f) * ButtonColorMul(pID)), CUI::CORNER_ALL, 5.0f); UI()->DoLabel(pRect, pText, 14.0f, 0); return UI()->DoButtonLogic(pID, pText, Checked, pRect); } int CMenus::DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Checked, const CUIRect *pRect, int Corners) { - RenderTools()->DrawUIRect(pRect, ColorRGBA(1.0f, 1.0f, 1.0f, (Checked ? 0.10f : 0.5f)*ButtonColorMul(pID)), Corners, 5.0f); + RenderTools()->DrawUIRect(pRect, ColorRGBA(1.0f, 1.0f, 1.0f, (Checked ? 0.10f : 0.5f) * ButtonColorMul(pID)), Corners, 5.0f); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); if(!Checked) @@ -58,7 +58,7 @@ bool CMenus::DemoFilterChat(const void *pData, int Size, void *pUser) Unpacker.Reset(pData, Size); int Msg = Unpacker.GetInt(); - int Sys = Msg&1; + int Sys = Msg & 1; Msg >>= 1; return !Unpacker.Error() && !Sys && Msg == NETMSGTYPE_SV_CHAT; @@ -81,21 +81,20 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) CUIRect Screen = *UI()->Screen(); CUIRect Box, Part, Part2; Box = Screen; - Box.VMargin(150.0f/UI()->Scale(), &Box); - Box.HMargin(150.0f/UI()->Scale(), &Box); + Box.VMargin(150.0f / UI()->Scale(), &Box); + Box.HMargin(150.0f / UI()->Scale(), &Box); // render the box - RenderTools()->DrawUIRect(&Box, ColorRGBA(0,0,0,0.5f), CUI::CORNER_ALL, 15.0f); + RenderTools()->DrawUIRect(&Box, ColorRGBA(0, 0, 0, 0.5f), CUI::CORNER_ALL, 15.0f); - Box.HSplitTop(20.f/UI()->Scale(), &Part, &Box); - Box.HSplitTop(24.f/UI()->Scale(), &Part, &Box); + Box.HSplitTop(20.f / UI()->Scale(), &Part, &Box); + Box.HSplitTop(24.f / UI()->Scale(), &Part, &Box); UI()->DoLabelScaled(&Part, Localize("Select a name"), 24.f, 0); - Box.HSplitTop(20.f/UI()->Scale(), &Part, &Box); - Box.HSplitTop(24.f/UI()->Scale(), &Part, &Box); - Part.VMargin(20.f/UI()->Scale(), &Part); + Box.HSplitTop(20.f / UI()->Scale(), &Part, &Box); + Box.HSplitTop(24.f / UI()->Scale(), &Part, &Box); + Part.VMargin(20.f / UI()->Scale(), &Part); UI()->DoLabelScaled(&Part, m_aDemoPlayerPopupHint, 24.f, 0); - CUIRect Label, TextBox, Ok, Abort; Box.HSplitBottom(20.f, &Box, &Part); @@ -232,7 +231,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) } } - TotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3; + TotalHeight = SeekBarHeight + ButtonbarHeight + NameBarHeight + Margins * 3; // render speed info if(g_Config.m_ClDemoShowSpeed && time_get() - LastSpeedChange < time_freq() * 1) @@ -241,7 +240,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) char aSpeedBuf[256]; str_format(aSpeedBuf, sizeof(aSpeedBuf), "×%.2f", pInfo->m_Speed); - TextRender()->Text(0, 120.0f, Screen.y+Screen.h - 120.0f - TotalHeight, 60.0f, aSpeedBuf, -1.0f); + TextRender()->Text(0, 120.0f, Screen.y + Screen.h - 120.0f - TotalHeight, 60.0f, aSpeedBuf, -1.0f); } if(!m_MenuActive) @@ -272,22 +271,22 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) char aBuffer[128]; // draw seek bar - RenderTools()->DrawUIRect(&SeekBar, ColorRGBA(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f); + RenderTools()->DrawUIRect(&SeekBar, ColorRGBA(0, 0, 0, 0.5f), CUI::CORNER_ALL, 5.0f); // draw filled bar - float Amount = CurrentTick/(float)TotalTicks; + float Amount = CurrentTick / (float)TotalTicks; CUIRect FilledBar = SeekBar; - FilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount; - RenderTools()->DrawUIRect(&FilledBar, ColorRGBA(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f); + FilledBar.w = 10.0f + (FilledBar.w - 10.0f) * Amount; + RenderTools()->DrawUIRect(&FilledBar, ColorRGBA(1, 1, 1, 0.5f), CUI::CORNER_ALL, 5.0f); // draw markers for(int i = 0; i < pInfo->m_NumTimelineMarkers; i++) { - float Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks; + float Ratio = (pInfo->m_aTimelineMarkers[i] - pInfo->m_FirstTick) / (float)TotalTicks; Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); - IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w - 10.0f) * Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } @@ -296,11 +295,11 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) // begin if(g_Config.m_ClDemoSliceBegin != -1) { - float Ratio = (g_Config.m_ClDemoSliceBegin-pInfo->m_FirstTick) / (float)TotalTicks; + float Ratio = (g_Config.m_ClDemoSliceBegin - pInfo->m_FirstTick) / (float)TotalTicks; Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); - IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w - 10.0f) * Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } @@ -308,20 +307,20 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) // end if(g_Config.m_ClDemoSliceEnd != -1) { - float Ratio = (g_Config.m_ClDemoSliceEnd-pInfo->m_FirstTick) / (float)TotalTicks; + float Ratio = (g_Config.m_ClDemoSliceEnd - pInfo->m_FirstTick) / (float)TotalTicks; Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); - IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w - 10.0f) * Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } // draw time str_format(aBuffer, sizeof(aBuffer), "%d:%02d / %d:%02d", - CurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60, - TotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60); - UI()->DoLabel(&SeekBar, aBuffer, SeekBar.h*0.70f, 0); + CurrentTick / SERVER_TICK_SPEED / 60, (CurrentTick / SERVER_TICK_SPEED) % 60, + TotalTicks / SERVER_TICK_SPEED / 60, (TotalTicks / SERVER_TICK_SPEED) % 60); + UI()->DoLabel(&SeekBar, aBuffer, SeekBar.h * 0.70f, 0); // do the logic int Inside = UI()->MouseInside(&SeekBar); @@ -333,13 +332,13 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) else { static float PrevAmount = 0.0f; - float Amount = (UI()->MouseX()-SeekBar.x)/SeekBar.w; + float Amount = (UI()->MouseX() - SeekBar.x) / SeekBar.w; if(Input()->KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) { - Amount = PrevAmount + (Amount-PrevAmount) * 0.05f; + Amount = PrevAmount + (Amount - PrevAmount) * 0.05f; - if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.0001f) + if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount - Amount) >= 0.0001f) { //PrevAmount = Amount; m_pClient->m_SuppressEvents = true; @@ -351,7 +350,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) } else { - if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.001f) + if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount - Amount) >= 0.001f) { PrevAmount = Amount; m_pClient->m_SuppressEvents = true; @@ -425,13 +424,13 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) IncreaseDemoSpeed = true; // speed meter - ButtonBar.VSplitLeft(Margins*3, 0, &ButtonBar); + ButtonBar.VSplitLeft(Margins * 3, 0, &ButtonBar); char aBuffer[64]; str_format(aBuffer, sizeof(aBuffer), "×%g", pInfo->m_Speed); - UI()->DoLabel(&ButtonBar, aBuffer, Button.h*0.7f, -1); + UI()->DoLabel(&ButtonBar, aBuffer, Button.h * 0.7f, -1); // slice begin button - ButtonBar.VSplitLeft(Margins*10, 0, &ButtonBar); + ButtonBar.VSplitLeft(Margins * 10, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_SliceBeginButton = 0; if(DoButton_Sprite(&s_SliceBeginButton, IMAGE_DEMOBUTTONS2, SPRITE_DEMOBUTTON_SLICE_BEGIN, 0, &Button, CUI::CORNER_ALL)) @@ -456,7 +455,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) } // close button - ButtonBar.VSplitRight(ButtonbarHeight*3, &ButtonBar, &Button); + ButtonBar.VSplitRight(ButtonbarHeight * 3, &ButtonBar, &Button); static int s_ExitButton = 0; if(DoButton_DemoPlayer(&s_ExitButton, Localize("Close"), 0, &Button) || (Input()->KeyPress(KEY_C) && m_pClient->m_pGameConsole->IsClosed() && m_DemoPlayerState == DEMOPLAYER_NONE)) { @@ -465,7 +464,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) } // toggle keyboard shortcuts button - ButtonBar.VSplitRight(Margins*3, &ButtonBar, 0); + ButtonBar.VSplitRight(Margins * 3, &ButtonBar, 0); ButtonBar.VSplitRight(ButtonbarHeight, &ButtonBar, &Button); static int s_KeyboardShortcutsButton = 0; int Sprite = g_Config.m_ClDemoKeyboardShortcuts ? SPRITE_DEMOBUTTON_SHORTCUTS_ENABLED : SPRITE_DEMOBUTTON_SHORTCUTS_DISABLED; @@ -480,7 +479,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) char aBuf[128]; str_format(aBuf, sizeof(aBuf), Localize("Demofile: %s"), aDemoName); CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y + (NameBar.h - (Button.h*0.5f)) / 2.f, Button.h*0.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y + (NameBar.h - (Button.h * 0.5f)) / 2.f, Button.h * 0.5f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = MainView.w; TextRender()->TextEx(&Cursor, aBuf, -1); @@ -510,7 +509,7 @@ static bool gs_ListBoxItemActivated; static bool gs_ListBoxClicked; void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHeight, const char *pTitle, const char *pBottomText, int NumItems, - int ItemsPerRow, int SelectedIndex, float ScrollValue) + int ItemsPerRow, int SelectedIndex, float ScrollValue) { CUIRect Scroll, Row; CUIRect View = *pRect; @@ -518,17 +517,17 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe // draw header View.HSplitTop(ms_ListheaderHeight, &Header, &View); - RenderTools()->DrawUIRect(&Header, ColorRGBA(1,1,1,0.25f), CUI::CORNER_T, 5.0f); - UI()->DoLabel(&Header, pTitle, Header.h*ms_FontmodHeight, 0); + RenderTools()->DrawUIRect(&Header, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_T, 5.0f); + UI()->DoLabel(&Header, pTitle, Header.h * ms_FontmodHeight, 0); // draw footers View.HSplitBottom(ms_ListheaderHeight, &View, &Footer); - RenderTools()->DrawUIRect(&Footer, ColorRGBA(1,1,1,0.25f), CUI::CORNER_B, 5.0f); + RenderTools()->DrawUIRect(&Footer, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_B, 5.0f); Footer.VSplitLeft(10.0f, 0, &Footer); - UI()->DoLabel(&Footer, pBottomText, Header.h*ms_FontmodHeight, 0); + UI()->DoLabel(&Footer, pBottomText, Header.h * ms_FontmodHeight, 0); // background - RenderTools()->DrawUIRect(&View, ColorRGBA(0,0,0,0.15f), 0, 0); + RenderTools()->DrawUIRect(&View, ColorRGBA(0, 0, 0, 0.15f), 0, 0); // prepare the scroll View.VSplitRight(15, &View, &Scroll); @@ -549,8 +548,8 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe // do the scrollbar View.HSplitTop(gs_ListBoxRowHeight, &Row, 0); - int NumViewable = (int)(gs_ListBoxOriginalView.h/Row.h) + 1; - int Num = (NumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; + int NumViewable = (int)(gs_ListBoxOriginalView.h / Row.h) + 1; + int Num = (NumItems + gs_ListBoxItemsPerRow - 1) / gs_ListBoxItemsPerRow - NumViewable + 1; if(Num <= 0) { Num = 0; @@ -562,18 +561,22 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) gs_ListBoxScrollValue += 0.1f; - if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; - if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; + if(gs_ListBoxScrollValue < 0.0f) + gs_ListBoxScrollValue = 0.0f; + if(gs_ListBoxScrollValue > 1.0f) + gs_ListBoxScrollValue = 1.0f; } else { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) - gs_ListBoxScrollValue -= 3.0f/Num; + gs_ListBoxScrollValue -= 3.0f / Num; if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) - gs_ListBoxScrollValue += 3.0f/Num; + gs_ListBoxScrollValue += 3.0f / Num; - if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; - if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; + if(gs_ListBoxScrollValue < 0.0f) + gs_ListBoxScrollValue = 0.0f; + if(gs_ListBoxScrollValue > 1.0f) + gs_ListBoxScrollValue = 1.0f; } Scroll.HMargin(5.0f, &Scroll); @@ -583,17 +586,17 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe gs_ListBoxView = gs_ListBoxOriginalView; gs_ListBoxView.VMargin(5.0f, &gs_ListBoxView); UI()->ClipEnable(&gs_ListBoxView); - gs_ListBoxView.y -= gs_ListBoxScrollValue*Num*Row.h; + gs_ListBoxView.y -= gs_ListBoxScrollValue * Num * Row.h; } CMenus::CListboxItem CMenus::UiDoListboxNextRow() { static CUIRect s_RowView; CListboxItem Item = {0}; - if(gs_ListBoxItemIndex%gs_ListBoxItemsPerRow == 0) + if(gs_ListBoxItemIndex % gs_ListBoxItemsPerRow == 0) gs_ListBoxView.HSplitTop(gs_ListBoxRowHeight /*-2.0f*/, &s_RowView, &gs_ListBoxView); - s_RowView.VSplitLeft(s_RowView.w/(gs_ListBoxItemsPerRow-gs_ListBoxItemIndex%gs_ListBoxItemsPerRow)/(UI()->Scale()), &Item.m_Rect, &s_RowView); + s_RowView.VSplitLeft(s_RowView.w / (gs_ListBoxItemsPerRow - gs_ListBoxItemIndex % gs_ListBoxItemsPerRow) / (UI()->Scale()), &Item.m_Rect, &s_RowView); Item.m_Visible = 1; //item.rect = row; @@ -606,21 +609,19 @@ CMenus::CListboxItem CMenus::UiDoListboxNextRow() Item.m_Selected = 1; // make sure that only those in view can be selected - if(Item.m_Rect.y+Item.m_Rect.h > gs_ListBoxOriginalView.y) + if(Item.m_Rect.y + Item.m_Rect.h > gs_ListBoxOriginalView.y) { - if(Item.m_HitRect.y < Item.m_HitRect.y) // clip the selection { - Item.m_HitRect.h -= gs_ListBoxOriginalView.y-Item.m_HitRect.y; + Item.m_HitRect.h -= gs_ListBoxOriginalView.y - Item.m_HitRect.y; Item.m_HitRect.y = gs_ListBoxOriginalView.y; } - } else Item.m_Visible = 0; // check if we need to do more - if(Item.m_Rect.y > gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h) + if(Item.m_Rect.y > gs_ListBoxOriginalView.y + gs_ListBoxOriginalView.h) Item.m_Visible = 0; gs_ListBoxItemIndex++; @@ -662,38 +663,46 @@ CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected, for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; - if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + if(m_aInputEvents[i].m_Flags & IInput::FLAG_PRESS) { - if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = gs_ListBoxNewSelected + 1; - else if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = gs_ListBoxNewSelected - 1; - else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) NewIndex = maximum(gs_ListBoxNewSelected - 20, 0); - else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) NewIndex = minimum(gs_ListBoxNewSelected + 20, gs_ListBoxNumItems - 1); - else if(m_aInputEvents[i].m_Key == KEY_HOME) NewIndex = 0; - else if(m_aInputEvents[i].m_Key == KEY_END) NewIndex = gs_ListBoxNumItems - 1; + if(m_aInputEvents[i].m_Key == KEY_DOWN) + NewIndex = gs_ListBoxNewSelected + 1; + else if(m_aInputEvents[i].m_Key == KEY_UP) + NewIndex = gs_ListBoxNewSelected - 1; + else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) + NewIndex = maximum(gs_ListBoxNewSelected - 20, 0); + else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) + NewIndex = minimum(gs_ListBoxNewSelected + 20, gs_ListBoxNumItems - 1); + else if(m_aInputEvents[i].m_Key == KEY_HOME) + NewIndex = 0; + else if(m_aInputEvents[i].m_Key == KEY_END) + NewIndex = gs_ListBoxNumItems - 1; } if(NewIndex > -1 && NewIndex < gs_ListBoxNumItems) { // scroll - float Offset = (NewIndex/gs_ListBoxItemsPerRow-gs_ListBoxNewSelected/gs_ListBoxItemsPerRow)*gs_ListBoxRowHeight; - int Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y+Offset ? -1 : - gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h < Item.m_Rect.y+Item.m_Rect.h+Offset ? 1 : 0; + float Offset = (NewIndex / gs_ListBoxItemsPerRow - gs_ListBoxNewSelected / gs_ListBoxItemsPerRow) * gs_ListBoxRowHeight; + int Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y + Offset ? -1 : + gs_ListBoxOriginalView.y + gs_ListBoxOriginalView.h < Item.m_Rect.y + Item.m_Rect.h + Offset ? 1 : 0; if(Scroll) { - int NumViewable = (int)(gs_ListBoxOriginalView.h/gs_ListBoxRowHeight) + 1; - int ScrollNum = (gs_ListBoxNumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; + int NumViewable = (int)(gs_ListBoxOriginalView.h / gs_ListBoxRowHeight) + 1; + int ScrollNum = (gs_ListBoxNumItems + gs_ListBoxItemsPerRow - 1) / gs_ListBoxItemsPerRow - NumViewable + 1; if(Scroll < 0) { - int Num = (gs_ListBoxOriginalView.y-Item.m_Rect.y-Offset+gs_ListBoxRowHeight-1.0f)/gs_ListBoxRowHeight; - gs_ListBoxScrollValue -= (1.0f/ScrollNum)*Num; + int Num = (gs_ListBoxOriginalView.y - Item.m_Rect.y - Offset + gs_ListBoxRowHeight - 1.0f) / gs_ListBoxRowHeight; + gs_ListBoxScrollValue -= (1.0f / ScrollNum) * Num; } else { - int Num = (Item.m_Rect.y+Item.m_Rect.h+Offset-(gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)+gs_ListBoxRowHeight-1.0f)/ - gs_ListBoxRowHeight; - gs_ListBoxScrollValue += (1.0f/ScrollNum)*Num; + int Num = (Item.m_Rect.y + Item.m_Rect.h + Offset - (gs_ListBoxOriginalView.y + gs_ListBoxOriginalView.h) + gs_ListBoxRowHeight - 1.0f) / + gs_ListBoxRowHeight; + gs_ListBoxScrollValue += (1.0f / ScrollNum) * Num; } - if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; - if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; + if(gs_ListBoxScrollValue < 0.0f) + gs_ListBoxScrollValue = 0.0f; + if(gs_ListBoxScrollValue > 1.0f) + gs_ListBoxScrollValue = 1.0f; } gs_ListBoxNewSelected = NewIndex; @@ -705,7 +714,7 @@ CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected, //selected_index = i; CUIRect r = Item.m_Rect; r.Margin(1.5f, &r); - RenderTools()->DrawUIRect(&r, ColorRGBA(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + RenderTools()->DrawUIRect(&r, ColorRGBA(1, 1, 1, 0.5f), CUI::CORNER_ALL, 4.0f); } else if(UI()->MouseInside(&Item.m_Rect) && !NoHoverEffects) { @@ -732,9 +741,7 @@ int CMenus::UiDoListboxEnd(float *pScrollValue, bool *pItemActivated, bool *pLis int CMenus::DemolistFetchCallback(const char *pName, time_t Date, int IsDir, int StorageType, void *pUser) { CMenus *pSelf = (CMenus *)pUser; - if(str_comp(pName, ".") == 0 - || (str_comp(pName, "..") == 0 && str_comp(pSelf->m_aCurrentDemoFolder, "demos") == 0) - || (!IsDir && !str_endswith(pName, ".demo"))) + if(str_comp(pName, ".") == 0 || (str_comp(pName, "..") == 0 && str_comp(pSelf->m_aCurrentDemoFolder, "demos") == 0) || (!IsDir && !str_endswith(pName, ".demo"))) { return 0; } @@ -798,7 +805,7 @@ void CMenus::DemolistOnUpdate(bool Reset) } m_DemolistSelectedIndex = Reset ? m_lDemos.size() > 0 ? 0 : -1 : - m_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size()-1 : m_DemolistSelectedIndex; + m_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size() - 1 : m_DemolistSelectedIndex; m_DemolistSelectedIsDir = m_DemolistSelectedIndex < 0 ? false : m_lDemos[m_DemolistSelectedIndex].m_IsDir; } @@ -856,7 +863,7 @@ void CMenus::RenderDemoList(CUIRect MainView) #else CUIRect ButtonBar, RefreshRect, FetchRect, PlayRect, DeleteRect, RenameRect, LabelRect, ListBox; #endif - MainView.HSplitBottom(ms_ButtonHeight+5.0f, &MainView, &ButtonBar); + MainView.HSplitBottom(ms_ButtonHeight + 5.0f, &MainView, &ButtonBar); ButtonBar.HSplitTop(5.0f, 0, &ButtonBar); ButtonBar.VSplitRight(110.0f, &ButtonBar, &PlayRect); ButtonBar.VSplitLeft(110.0f, &RefreshRect, &ButtonBar); @@ -877,7 +884,7 @@ void CMenus::RenderDemoList(CUIRect MainView) // render demo info MainView.VMargin(5.0f, &MainView); MainView.HSplitBottom(5.0f, &MainView, 0); - RenderTools()->DrawUIRect(&MainView, ColorRGBA(0,0,0,0.15f), CUI::CORNER_B, 4.0f); + RenderTools()->DrawUIRect(&MainView, ColorRGBA(0, 0, 0, 0.15f), CUI::CORNER_B, 4.0f); if(!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid) { CUIRect Left, Right, Labels; @@ -905,7 +912,7 @@ void CMenus::RenderDemoList(CUIRect MainView) UI()->DoLabelScaled(&Left, Localize("Length:"), 14.0f, -1); int Length = m_lDemos[m_DemolistSelectedIndex].Length(); char aBuf[64]; - str_format(aBuf, sizeof(aBuf), "%d:%02d", Length/60, Length%60); + str_format(aBuf, sizeof(aBuf), "%d:%02d", Length / 60, Length % 60); UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); Labels.HSplitTop(5.0f, 0, &Labels); Labels.HSplitTop(20.0f, &Left, &Labels); @@ -930,12 +937,12 @@ void CMenus::RenderDemoList(CUIRect MainView) Labels.HSplitTop(20.0f, &Left, &Labels); Left.VSplitLeft(150.0f, &Left, &Right); UI()->DoLabelScaled(&Left, Localize("Size:"), 14.0f, -1); - unsigned Size = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1]<<16) | - (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]); - if(Size > 1024*1024) - str_format(aBuf, sizeof(aBuf), Localize("%.2f MiB"), float(Size)/(1024*1024)); + unsigned Size = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0] << 24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1] << 16) | + (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2] << 8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]); + if(Size > 1024 * 1024) + str_format(aBuf, sizeof(aBuf), Localize("%.2f MiB"), float(Size) / (1024 * 1024)); else - str_format(aBuf, sizeof(aBuf), Localize("%.2f KiB"), float(Size)/1024); + str_format(aBuf, sizeof(aBuf), Localize("%.2f KiB"), float(Size) / 1024); UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); Labels.HSplitTop(5.0f, 0, &Labels); Labels.HSplitTop(20.0f, &Left, &Labels); @@ -951,7 +958,7 @@ void CMenus::RenderDemoList(CUIRect MainView) Left.VSplitLeft(150.0f, &Left, &Right); UI()->DoLabelScaled(&Left, "SHA256:", 14.0f, -1); char aSha[SHA256_MAXSTRSIZE]; - sha256_str(m_lDemos[m_DemolistSelectedIndex].m_MapInfo.m_Sha256, aSha, sizeof(aSha)/2); + sha256_str(m_lDemos[m_DemolistSelectedIndex].m_MapInfo.m_Sha256, aSha, sizeof(aSha) / 2); UI()->DoLabelScaled(&Right, aSha, Right.w > 235 ? 14.0f : 11.0f, -1); Labels.HSplitTop(5.0f, 0, &Labels); Labels.HSplitTop(20.0f, &Left, &Labels); @@ -962,7 +969,6 @@ void CMenus::RenderDemoList(CUIRect MainView) UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion, 14.0f, -1); } - // demo list CUIRect Headers; @@ -983,7 +989,7 @@ void CMenus::RenderDemoList(CUIRect MainView) enum { - COL_ICON=0, + COL_ICON = 0, COL_DEMONAME, COL_MARKERS, COL_LENGTH, @@ -1001,9 +1007,9 @@ void CMenus::RenderDemoList(CUIRect MainView) Localize("Demo");Localize("Markers");Localize("Length");Localize("Date"); */ - RenderTools()->DrawUIRect(&Headers, ColorRGBA(0.0f,0,0,0.15f), 0, 0); + RenderTools()->DrawUIRect(&Headers, ColorRGBA(0.0f, 0, 0, 0.15f), 0, 0); - int NumCols = sizeof(s_aCols)/sizeof(CColumn); + int NumCols = sizeof(s_aCols) / sizeof(CColumn); // do layout for(int i = 0; i < NumCols; i++) @@ -1012,7 +1018,7 @@ void CMenus::RenderDemoList(CUIRect MainView) { Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); - if(i+1 < NumCols) + if(i + 1 < NumCols) { //Cols[i].flags |= SPACER; Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); @@ -1020,7 +1026,7 @@ void CMenus::RenderDemoList(CUIRect MainView) } } - for(int i = NumCols-1; i >= 0; i--) + for(int i = NumCols - 1; i >= 0; i--) { if(s_aCols[i].m_Direction == 1) { @@ -1059,25 +1065,25 @@ void CMenus::RenderDemoList(CUIRect MainView) CUIRect Scroll; ListBox.VSplitRight(15, &ListBox, &Scroll); - int Num = (int)(ListBox.h/s_aCols[0].m_Rect.h) + 1; + int Num = (int)(ListBox.h / s_aCols[0].m_Rect.h) + 1; static int s_ScrollBar = 0; static float s_ScrollValue = 0; Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); - int ScrollNum = m_lDemos.size()-Num+1; + int ScrollNum = m_lDemos.size() - Num + 1; if(ScrollNum > 0) { if(m_ScrollOffset) { - s_ScrollValue = (float)(m_ScrollOffset)/ScrollNum; + s_ScrollValue = (float)(m_ScrollOffset) / ScrollNum; m_ScrollOffset = 0; } if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&ListBox)) - s_ScrollValue -= 3.0f/ScrollNum; + s_ScrollValue -= 3.0f / ScrollNum; if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&ListBox)) - s_ScrollValue += 3.0f/ScrollNum; + s_ScrollValue += 3.0f / ScrollNum; } else ScrollNum = 0; @@ -1087,31 +1093,37 @@ void CMenus::RenderDemoList(CUIRect MainView) for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; - if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + if(m_aInputEvents[i].m_Flags & IInput::FLAG_PRESS) { - if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = m_DemolistSelectedIndex + 1; - else if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = m_DemolistSelectedIndex - 1; - else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) NewIndex = maximum(m_DemolistSelectedIndex - 20, 0); - else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) NewIndex = minimum(m_DemolistSelectedIndex + 20, m_lDemos.size() - 1); - else if(m_aInputEvents[i].m_Key == KEY_HOME) NewIndex = 0; - else if(m_aInputEvents[i].m_Key == KEY_END) NewIndex = m_lDemos.size() - 1; + if(m_aInputEvents[i].m_Key == KEY_DOWN) + NewIndex = m_DemolistSelectedIndex + 1; + else if(m_aInputEvents[i].m_Key == KEY_UP) + NewIndex = m_DemolistSelectedIndex - 1; + else if(m_aInputEvents[i].m_Key == KEY_PAGEUP) + NewIndex = maximum(m_DemolistSelectedIndex - 20, 0); + else if(m_aInputEvents[i].m_Key == KEY_PAGEDOWN) + NewIndex = minimum(m_DemolistSelectedIndex + 20, m_lDemos.size() - 1); + else if(m_aInputEvents[i].m_Key == KEY_HOME) + NewIndex = 0; + else if(m_aInputEvents[i].m_Key == KEY_END) + NewIndex = m_lDemos.size() - 1; } if(NewIndex > -1 && NewIndex < m_lDemos.size()) { //scroll - float IndexY = ListBox.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; - int Scroll = ListBox.y > IndexY ? -1 : ListBox.y+ListBox.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; + float IndexY = ListBox.y - s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h + NewIndex * s_aCols[0].m_Rect.h; + int Scroll = ListBox.y > IndexY ? -1 : ListBox.y + ListBox.h < IndexY + s_aCols[0].m_Rect.h ? 1 : 0; if(Scroll) { if(Scroll < 0) { - int NumScrolls = (ListBox.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (ListBox.y - IndexY + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f / ScrollNum) * NumScrolls; } else { - int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(ListBox.y+ListBox.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (IndexY + s_aCols[0].m_Rect.h - (ListBox.y + ListBox.h) + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f / ScrollNum) * NumScrolls; } } @@ -1123,14 +1135,16 @@ void CMenus::RenderDemoList(CUIRect MainView) } } - if(s_ScrollValue < 0) s_ScrollValue = 0; - if(s_ScrollValue > 1) s_ScrollValue = 1; + if(s_ScrollValue < 0) + s_ScrollValue = 0; + if(s_ScrollValue > 1) + s_ScrollValue = 1; // set clipping UI()->ClipEnable(&ListBox); CUIRect OriginalView = ListBox; - ListBox.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + ListBox.y -= s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h; int NewSelected = -1; int ItemIndex = -1; @@ -1148,7 +1162,7 @@ void CMenus::RenderDemoList(CUIRect MainView) int Selected = ItemIndex == m_DemolistSelectedIndex; // make sure that only those in view can be selected - if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + if(Row.y + Row.h > OriginalView.y && Row.y < OriginalView.y + OriginalView.h) { if(Selected) { @@ -1166,11 +1180,11 @@ void CMenus::RenderDemoList(CUIRect MainView) // clip the selection if(SelectHitBox.y < OriginalView.y) // top { - SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.h -= OriginalView.y - SelectHitBox.y; SelectHitBox.y = OriginalView.y; } - else if(SelectHitBox.y+SelectHitBox.h > OriginalView.y+OriginalView.h) // bottom - SelectHitBox.h = OriginalView.y+OriginalView.h-SelectHitBox.y; + else if(SelectHitBox.y + SelectHitBox.h > OriginalView.y + OriginalView.h) // bottom + SelectHitBox.h = OriginalView.y + OriginalView.h - SelectHitBox.y; if(UI()->DoButtonLogic(r.front().m_aName /* TODO: */, "", Selected, &SelectHitBox)) { @@ -1198,16 +1212,15 @@ void CMenus::RenderDemoList(CUIRect MainView) if(ID == COL_ICON) { - DoButton_Icon(IMAGE_FILEICONS, r.front().m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_DEMO1, &Button); + DoButton_Icon(IMAGE_FILEICONS, r.front().m_IsDir ? SPRITE_FILE_FOLDER : SPRITE_FILE_DEMO1, &Button); } else if(ID == COL_DEMONAME) { CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; TextRender()->TextEx(&Cursor, r.front().m_aName, -1); - } else if(ID == COL_MARKERS && !r.front().m_IsDir && r.front().m_InfosLoaded) { @@ -1220,7 +1233,7 @@ void CMenus::RenderDemoList(CUIRect MainView) { int Length = r.front().Length(); char aBuf[32]; - str_format(aBuf, sizeof(aBuf), "%d:%02d", Length/60, Length%60); + str_format(aBuf, sizeof(aBuf), "%d:%02d", Length / 60, Length % 60); Button.VMargin(4.0f, &Button); UI()->DoLabelScaled(&Button, aBuf, 12.0f, 1); } @@ -1236,7 +1249,6 @@ void CMenus::RenderDemoList(CUIRect MainView) UI()->ClipDisable(); - bool Activated = false; if(m_EnterPressed || (Input()->MouseDoubleClick() && UI()->HotItem() == m_lDemos[m_DemolistSelectedIndex].m_aName)) @@ -1264,11 +1276,11 @@ void CMenus::RenderDemoList(CUIRect MainView) { if(m_DemolistSelectedIndex >= 0) { - if(m_DemolistSelectedIsDir) // folder + if(m_DemolistSelectedIsDir) // folder { - if(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, "..") == 0) // parent folder + if(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, "..") == 0) // parent folder fs_parent_dir(m_aCurrentDemoFolder); - else // sub folder + else // sub folder { char aTemp[256]; str_copy(aTemp, m_aCurrentDemoFolder, sizeof(aTemp)); diff --git a/src/game/client/components/menus_ingame.cpp b/src/game/client/components/menus_ingame.cpp index 93aa6d4b2..6d76abf84 100644 --- a/src/game/client/components/menus_ingame.cpp +++ b/src/game/client/components/menus_ingame.cpp @@ -8,27 +8,27 @@ #include #include #include -#include #include +#include -#include #include +#include -#include -#include #include +#include #include #include #include +#include #include "menus.h" #include "motd.h" #include "voting.h" +#include "ghost.h" #include #include #include -#include "ghost.h" void CMenus::RenderGame(CUIRect MainView) { @@ -214,7 +214,7 @@ void CMenus::RenderPlayers(CUIRect MainView) UI()->DoLabelScaled(&Player, Localize("Player"), 24.0f, -1); ButtonBar.HMargin(1.0f, &ButtonBar); - float Width = ButtonBar.h*2.0f; + float Width = ButtonBar.h * 2.0f; ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id); Graphics()->QuadsBegin(); @@ -282,7 +282,7 @@ void CMenus::RenderPlayers(CUIRect MainView) if(!Item.m_Visible) continue; - if(Count%2 == 1) + if(Count % 2 == 1) RenderTools()->DrawUIRect(&Item.m_Rect, ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); Item.m_Rect.VSplitRight(300.0f, &Player, &Item.m_Rect); @@ -290,17 +290,17 @@ void CMenus::RenderPlayers(CUIRect MainView) Player.VSplitLeft(28.0f, &Button, &Player); CTeeRenderInfo Info = m_pClient->m_aClients[Index].m_RenderInfo; Info.m_Size = Button.h; - RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x+Button.h/2, Button.y+Button.h/2)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x + Button.h / 2, Button.y + Button.h / 2)); Player.HSplitTop(1.5f, 0, &Player); Player.VSplitMid(&Player, &Button); Item.m_Rect.VSplitRight(200.0f, &Button2, &Item.m_Rect); CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, Player.x, Player.y + (Player.h - 14.f) / 2.f, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Player.x, Player.y + (Player.h - 14.f) / 2.f, 14.0f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Player.w; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aName, -1); - TextRender()->SetCursor(&Cursor, Button.x,Button.y + (Button.h - 14.f) / 2.f, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 14.f) / 2.f, 14.0f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aClan, -1); @@ -308,34 +308,32 @@ void CMenus::RenderPlayers(CUIRect MainView) //Cursor.m_LineWidth = Button.w; ColorRGBA Color(1.0f, 1.0f, 1.0f, 0.5f); m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[Index].m_Country, &Color, - Button2.x, Button2.y + Button2.h/2.0f - 0.75*Button2.h/2.0f, 1.5f*Button2.h, 0.75f*Button2.h); + Button2.x, Button2.y + Button2.h / 2.0f - 0.75 * Button2.h / 2.0f, 1.5f * Button2.h, 0.75f * Button2.h); // ignore chat button Item.m_Rect.HMargin(2.0f, &Item.m_Rect); Item.m_Rect.VSplitLeft(Width, &Button, &Item.m_Rect); - Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); + Button.VSplitLeft((Width - Button.h) / 4.0f, 0, &Button); Button.VSplitLeft(Button.h, &Button, 0); if(g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[Index].m_Friend) DoButton_Toggle(&s_aPlayerIDs[Index][0], 1, &Button, false); - else - if(DoButton_Toggle(&s_aPlayerIDs[Index][0], m_pClient->m_aClients[Index].m_ChatIgnore, &Button, true)) - m_pClient->m_aClients[Index].m_ChatIgnore ^= 1; + else if(DoButton_Toggle(&s_aPlayerIDs[Index][0], m_pClient->m_aClients[Index].m_ChatIgnore, &Button, true)) + m_pClient->m_aClients[Index].m_ChatIgnore ^= 1; // ignore emoticon button Item.m_Rect.VSplitLeft(20.0f, &Button, &Item.m_Rect); Item.m_Rect.VSplitLeft(Width, &Button, &Item.m_Rect); - Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); + Button.VSplitLeft((Width - Button.h) / 4.0f, 0, &Button); Button.VSplitLeft(Button.h, &Button, 0); if(g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[Index].m_Friend) DoButton_Toggle(&s_aPlayerIDs[Index][1], 1, &Button, false); - else - if(DoButton_Toggle(&s_aPlayerIDs[Index][1], m_pClient->m_aClients[Index].m_EmoticonIgnore, &Button, true)) - m_pClient->m_aClients[Index].m_EmoticonIgnore ^= 1; + else if(DoButton_Toggle(&s_aPlayerIDs[Index][1], m_pClient->m_aClients[Index].m_EmoticonIgnore, &Button, true)) + m_pClient->m_aClients[Index].m_EmoticonIgnore ^= 1; // friend button Item.m_Rect.VSplitLeft(20.0f, &Button, &Item.m_Rect); Item.m_Rect.VSplitLeft(Width, &Button, &Item.m_Rect); - Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); + Button.VSplitLeft((Width - Button.h) / 4.0f, 0, &Button); Button.VSplitLeft(Button.h, &Button, 0); if(DoButton_Toggle(&s_aPlayerIDs[Index][2], m_pClient->m_aClients[Index].m_Friend, &Button, true)) { @@ -422,17 +420,17 @@ void CMenus::RenderServerInfo(CUIRect MainView) MainView.Margin(10.0f, &View); // serverinfo - View.HSplitTop(View.h/2/UI()->Scale()-5.0f, &ServerInfo, &Motd); - ServerInfo.VSplitLeft(View.w/2/UI()->Scale()-5.0f, &ServerInfo, &GameInfo); - RenderTools()->DrawUIRect(&ServerInfo, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + View.HSplitTop(View.h / 2 / UI()->Scale() - 5.0f, &ServerInfo, &Motd); + ServerInfo.VSplitLeft(View.w / 2 / UI()->Scale() - 5.0f, &ServerInfo, &GameInfo); + RenderTools()->DrawUIRect(&ServerInfo, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); ServerInfo.Margin(5.0f, &ServerInfo); x = 5.0f; y = 0.0f; - TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 32, Localize("Server info"), 250.0f); - y += 32.0f+5.0f; + TextRender()->Text(0, ServerInfo.x + x, ServerInfo.y + y, 32, Localize("Server info"), 250.0f); + y += 32.0f + 5.0f; mem_zero(aBuf, sizeof(aBuf)); str_format( @@ -447,10 +445,9 @@ void CMenus::RenderServerInfo(CUIRect MainView) Localize("Address"), CurrentServerInfo.m_aAddress, Localize("Ping"), m_pClient->m_Snap.m_pLocalInfo->m_Latency, Localize("Version"), CurrentServerInfo.m_aVersion, - Localize("Password"), CurrentServerInfo.m_Flags &1 ? Localize("Yes") : Localize("No") - ); + Localize("Password"), CurrentServerInfo.m_Flags & 1 ? Localize("Yes") : Localize("No")); - TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 20, aBuf, 250.0f); + TextRender()->Text(0, ServerInfo.x + x, ServerInfo.y + y, 20, aBuf, 250.0f); { CUIRect Button; @@ -468,15 +465,15 @@ void CMenus::RenderServerInfo(CUIRect MainView) // gameinfo GameInfo.VSplitLeft(10.0f, 0x0, &GameInfo); - RenderTools()->DrawUIRect(&GameInfo, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&GameInfo, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); GameInfo.Margin(5.0f, &GameInfo); x = 5.0f; y = 0.0f; - TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 32, Localize("Game info"), 250.0f); - y += 32.0f+5.0f; + TextRender()->Text(0, GameInfo.x + x, GameInfo.y + y, 32, Localize("Game info"), 250.0f); + y += 32.0f + 5.0f; if(m_pClient->m_Snap.m_pGameInfoObj) { @@ -495,20 +492,19 @@ void CMenus::RenderServerInfo(CUIRect MainView) Localize("Map"), CurrentServerInfo.m_aMap, Localize("Score limit"), m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit, Localize("Time limit"), m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit, - Localize("Players"), m_pClient->m_Snap.m_NumPlayers, CurrentServerInfo.m_MaxClients - ); - TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 20, aBuf, 250.0f); + Localize("Players"), m_pClient->m_Snap.m_NumPlayers, CurrentServerInfo.m_MaxClients); + TextRender()->Text(0, GameInfo.x + x, GameInfo.y + y, 20, aBuf, 250.0f); } // motd Motd.HSplitTop(10.0f, 0, &Motd); - RenderTools()->DrawUIRect(&Motd, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&Motd, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); Motd.Margin(5.0f, &Motd); y = 0.0f; x = 5.0f; - TextRender()->Text(0, Motd.x+x, Motd.y+y, 32, Localize("MOTD"), -1.0f); - y += 32.0f+5.0f; - TextRender()->Text(0, Motd.x+x, Motd.y+y, 16, m_pClient->m_pMotd->m_aServerMotd, Motd.w); + TextRender()->Text(0, Motd.x + x, Motd.y + y, 32, Localize("MOTD"), -1.0f); + y += 32.0f + 5.0f; + TextRender()->Text(0, Motd.x + x, Motd.y + y, 16, m_pClient->m_pMotd->m_aServerMotd, Motd.w); } bool CMenus::RenderServerControlServer(CUIRect MainView) @@ -617,7 +613,7 @@ void CMenus::RenderServerControl(CUIRect MainView) // tab bar { - TabBar.VSplitLeft(TabBar.w/3, &Button, &TabBar); + TabBar.VSplitLeft(TabBar.w / 3, &Button, &TabBar); static int s_Button0 = 0; if(DoButton_MenuTab(&s_Button0, Localize("Change settings"), s_ControlPage == 0, &Button, 0)) s_ControlPage = 0; @@ -633,7 +629,7 @@ void CMenus::RenderServerControl(CUIRect MainView) } // render page - MainView.HSplitBottom(ms_ButtonHeight + 5*2, &MainView, &Bottom); + MainView.HSplitBottom(ms_ButtonHeight + 5 * 2, &MainView, &Bottom); Bottom.HMargin(5.0f, &Bottom); bool Call = false; @@ -712,7 +708,7 @@ void CMenus::RenderServerControl(CUIRect MainView) const char *pLabel = Localize("Reason:"); UI()->DoLabelScaled(&Reason, pLabel, 14.0f, -1); float w = TextRender()->TextWidth(0, 14.0f, pLabel, -1, -1.0f); - Reason.VSplitLeft(w+10.0f, 0, &Reason); + Reason.VSplitLeft(w + 10.0f, 0, &Reason); static float s_Offset = 0.0f; if(Input()->KeyPress(KEY_R) && (Input()->KeyIsPressed(KEY_LCTRL) || Input()->KeyIsPressed(KEY_RCTRL))) UI()->SetActiveItem(&m_aCallvoteReason); @@ -764,7 +760,6 @@ void CMenus::RenderServerControl(CUIRect MainView) if(DoButton_Menu(&s_RemoveVoteButton, Localize("Remove"), 0, &Button)) m_pClient->m_pVoting->RemovevoteOption(m_CallvoteSelectedOption); - // add vote Extended.HSplitTop(20.0f, &Bottom, &Extended); Bottom.VSplitLeft(5.0f, 0, &Bottom); @@ -811,8 +806,8 @@ void CMenus::RenderInGameNetwork(CUIRect MainView) Box.HSplitTop(24.0f, &Box, &MainView); Box.VSplitLeft(100.0f, &Button, &Box); - static int s_InternetButton=0; - if(DoButton_MenuTab(&s_InternetButton, Localize("Internet"), Page==PAGE_INTERNET, &Button, 0)) + static int s_InternetButton = 0; + if(DoButton_MenuTab(&s_InternetButton, Localize("Internet"), Page == PAGE_INTERNET, &Button, 0)) { if(Page != PAGE_INTERNET) ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); @@ -820,8 +815,8 @@ void CMenus::RenderInGameNetwork(CUIRect MainView) } Box.VSplitLeft(80.0f, &Button, &Box); - static int s_LanButton=0; - if(DoButton_MenuTab(&s_LanButton, Localize("LAN"), Page==PAGE_LAN, &Button, 0)) + static int s_LanButton = 0; + if(DoButton_MenuTab(&s_LanButton, Localize("LAN"), Page == PAGE_LAN, &Button, 0)) { if(Page != PAGE_LAN) ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); @@ -829,8 +824,8 @@ void CMenus::RenderInGameNetwork(CUIRect MainView) } Box.VSplitLeft(110.0f, &Button, &Box); - static int s_FavoritesButton=0; - if(DoButton_MenuTab(&s_FavoritesButton, Localize("Favorites"), Page==PAGE_FAVORITES, &Button, 0)) + static int s_FavoritesButton = 0; + if(DoButton_MenuTab(&s_FavoritesButton, Localize("Favorites"), Page == PAGE_FAVORITES, &Button, 0)) { if(Page != PAGE_FAVORITES) ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); @@ -838,8 +833,8 @@ void CMenus::RenderInGameNetwork(CUIRect MainView) } Box.VSplitLeft(110.0f, &Button, &Box); - static int s_DDNetButton=0; - if(DoButton_MenuTab(&s_DDNetButton, "DDNet", Page==PAGE_DDNET, &Button, 0) || Page < PAGE_INTERNET || Page > PAGE_KOG) + static int s_DDNetButton = 0; + if(DoButton_MenuTab(&s_DDNetButton, "DDNet", Page == PAGE_DDNET, &Button, 0) || Page < PAGE_INTERNET || Page > PAGE_KOG) { if(Page != PAGE_DDNET) { @@ -850,8 +845,8 @@ void CMenus::RenderInGameNetwork(CUIRect MainView) } Box.VSplitLeft(110.0f, &Button, &Box); - static int s_KoGButton=0; - if(DoButton_MenuTab(&s_KoGButton, "KoG", Page==PAGE_KOG, &Button, CUI::CORNER_BR)) + static int s_KoGButton = 0; + if(DoButton_MenuTab(&s_KoGButton, "KoG", Page == PAGE_KOG, &Button, CUI::CORNER_BR)) { if(Page != PAGE_KOG) { @@ -965,7 +960,7 @@ void CMenus::RenderGhost(CUIRect MainView) View.HSplitBottom(28.0f, &View, &Status); // split of the scrollbar - RenderTools()->DrawUIRect(&Headers, ColorRGBA(1,1,1,0.25f), CUI::CORNER_T, 5.0f); + RenderTools()->DrawUIRect(&Headers, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_T, 5.0f); Headers.VSplitRight(20.0f, &Headers, 0); struct CColumn @@ -979,26 +974,26 @@ void CMenus::RenderGhost(CUIRect MainView) enum { - COL_ACTIVE=0, + COL_ACTIVE = 0, COL_NAME, COL_TIME, }; static CColumn s_aCols[] = { - {-1, " ", 2.0f, {0}, {0}}, - {COL_ACTIVE, " ", 30.0f, {0}, {0}}, - {COL_NAME, "Name", 300.0f, {0}, {0}}, - {COL_TIME, "Time", 200.0f, {0}, {0}}, + {-1, " ", 2.0f, {0}, {0}}, + {COL_ACTIVE, " ", 30.0f, {0}, {0}}, + {COL_NAME, "Name", 300.0f, {0}, {0}}, + {COL_TIME, "Time", 200.0f, {0}, {0}}, }; - int NumCols = sizeof(s_aCols)/sizeof(CColumn); + int NumCols = sizeof(s_aCols) / sizeof(CColumn); // do layout for(int i = 0; i < NumCols; i++) { Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); - if(i+1 < NumCols) + if(i + 1 < NumCols) Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); } @@ -1006,27 +1001,27 @@ void CMenus::RenderGhost(CUIRect MainView) for(int i = 0; i < NumCols; i++) DoButton_GridHeader(s_aCols[i].m_Caption, s_aCols[i].m_Caption, 0, &s_aCols[i].m_Rect); - RenderTools()->DrawUIRect(&View, ColorRGBA(0,0,0,0.15f), 0, 0); + RenderTools()->DrawUIRect(&View, ColorRGBA(0, 0, 0, 0.15f), 0, 0); CUIRect Scroll; View.VSplitRight(15, &View, &Scroll); int NumGhosts = m_lGhosts.size(); - int Num = (int)(View.h/s_aCols[0].m_Rect.h) + 1; + int Num = (int)(View.h / s_aCols[0].m_Rect.h) + 1; static int s_ScrollBar = 0; static float s_ScrollValue = 0; Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); - int ScrollNum = NumGhosts-Num+1; + int ScrollNum = NumGhosts - Num + 1; if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue -= 1.0f/ScrollNum; + s_ScrollValue -= 1.0f / ScrollNum; if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue += 1.0f/ScrollNum; + s_ScrollValue += 1.0f / ScrollNum; } else ScrollNum = 0; @@ -1035,27 +1030,29 @@ void CMenus::RenderGhost(CUIRect MainView) for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; - if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + if(m_aInputEvents[i].m_Flags & IInput::FLAG_PRESS) { - if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = s_SelectedIndex + 1; - if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = s_SelectedIndex - 1; + if(m_aInputEvents[i].m_Key == KEY_DOWN) + NewIndex = s_SelectedIndex + 1; + if(m_aInputEvents[i].m_Key == KEY_UP) + NewIndex = s_SelectedIndex - 1; } if(NewIndex > -1 && NewIndex < NumGhosts) { //scroll - float IndexY = View.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; - int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; + float IndexY = View.y - s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h + NewIndex * s_aCols[0].m_Rect.h; + int Scroll = View.y > IndexY ? -1 : View.y + View.h < IndexY + s_aCols[0].m_Rect.h ? 1 : 0; if(Scroll) { if(Scroll < 0) { - int NumScrolls = (View.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (View.y - IndexY + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f / ScrollNum) * NumScrolls; } else { - int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(View.y+View.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; - s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + int NumScrolls = (IndexY + s_aCols[0].m_Rect.h - (View.y + View.h) + s_aCols[0].m_Rect.h - 1.0f) / s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f / ScrollNum) * NumScrolls; } } @@ -1063,14 +1060,16 @@ void CMenus::RenderGhost(CUIRect MainView) } } - if(s_ScrollValue < 0) s_ScrollValue = 0; - if(s_ScrollValue > 1) s_ScrollValue = 1; + if(s_ScrollValue < 0) + s_ScrollValue = 0; + if(s_ScrollValue > 1) + s_ScrollValue = 1; // set clipping UI()->ClipEnable(&View); CUIRect OriginalView = View; - View.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + View.y -= s_ScrollValue * ScrollNum * s_aCols[0].m_Rect.h; int NewSelected = -1; @@ -1084,23 +1083,23 @@ void CMenus::RenderGhost(CUIRect MainView) SelectHitBox = Row; // make sure that only those in view can be selected - if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + if(Row.y + Row.h > OriginalView.y && Row.y < OriginalView.y + OriginalView.h) { if(i == s_SelectedIndex) { CUIRect r = Row; r.Margin(1.5f, &r); - RenderTools()->DrawUIRect(&r, ColorRGBA(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + RenderTools()->DrawUIRect(&r, ColorRGBA(1, 1, 1, 0.5f), CUI::CORNER_ALL, 4.0f); } // clip the selection if(SelectHitBox.y < OriginalView.y) // top { - SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.h -= OriginalView.y - SelectHitBox.y; SelectHitBox.y = OriginalView.y; } - else if(SelectHitBox.y+SelectHitBox.h > OriginalView.y+OriginalView.h) // bottom - SelectHitBox.h = OriginalView.y+OriginalView.h-SelectHitBox.y; + else if(SelectHitBox.y + SelectHitBox.h > OriginalView.y + OriginalView.h) // bottom + SelectHitBox.h = OriginalView.y + OriginalView.h - SelectHitBox.y; if(UI()->DoButtonLogic(pItem, "", 0, &SelectHitBox)) { @@ -1131,7 +1130,7 @@ void CMenus::RenderGhost(CUIRect MainView) Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SPRITE_OOP + 7); - IGraphics::CQuadItem QuadItem(Button.x+Button.w/2, Button.y+Button.h/2, 20.0f, 20.0f); + IGraphics::CQuadItem QuadItem(Button.x + Button.w / 2, Button.y + Button.h / 2, 20.0f, 20.0f); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); @@ -1140,7 +1139,7 @@ void CMenus::RenderGhost(CUIRect MainView) else if(Id == COL_NAME) { CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; TextRender()->TextEx(&Cursor, pItem->m_aPlayer, -1); @@ -1148,7 +1147,7 @@ void CMenus::RenderGhost(CUIRect MainView) else if(Id == COL_TIME) { CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, Button.x, Button.y + (Button.h - 12.0f * UI()->Scale()) / 2.f, 12.0f * UI()->Scale(), TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; char aBuf[64]; @@ -1165,7 +1164,7 @@ void CMenus::RenderGhost(CUIRect MainView) if(NewSelected != -1) s_SelectedIndex = NewSelected; - RenderTools()->DrawUIRect(&Status, ColorRGBA(1,1,1,0.25f), CUI::CORNER_B, 5.0f); + RenderTools()->DrawUIRect(&Status, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_B, 5.0f); Status.Margin(5.0f, &Status); CUIRect Button; diff --git a/src/game/client/components/menus_settings.cpp b/src/game/client/components/menus_settings.cpp index f76ee62d3..167edbc0f 100644 --- a/src/game/client/components/menus_settings.cpp +++ b/src/game/client/components/menus_settings.cpp @@ -8,14 +8,14 @@ #include #include +#include +#include #include #include #include -#include -#include -#include #include +#include #include #include @@ -45,7 +45,7 @@ bool CMenusKeyBinder::OnInput(IInput::CEvent Event) if(m_TakeKey) { int TriggeringEvent = (Event.m_Key == KEY_MOUSE_1) ? IInput::FLAG_PRESS : IInput::FLAG_RELEASE; - if(Event.m_Flags&TriggeringEvent) + if(Event.m_Flags & TriggeringEvent) { m_Key = Event; m_GotKey = true; @@ -53,7 +53,7 @@ bool CMenusKeyBinder::OnInput(IInput::CEvent Event) int Mask = CBinds::GetModifierMask(Input()); m_Modifier = 0; - while(!(Mask&1)) + while(!(Mask & 1)) { Mask >>= 1; m_Modifier++; @@ -142,7 +142,7 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Name plates size"), g_Config.m_ClNameplatesSize); UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); Button.HMargin(2.0f, &Button); - g_Config.m_ClNameplatesSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesSize, &Button, g_Config.m_ClNameplatesSize/100.0f)*100.0f+0.1f); + g_Config.m_ClNameplatesSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesSize, &Button, g_Config.m_ClNameplatesSize / 100.0f) * 100.0f + 0.1f); Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClNameplatesTeamcolors, Localize("Use team colors for name plates"), g_Config.m_ClNameplatesTeamcolors, &Button)) @@ -152,18 +152,18 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClNameplatesClan, Localize("Show clan above name plates"), g_Config.m_ClNameplatesClan, &Button)) g_Config.m_ClNameplatesClan ^= 1; - } + } - if(g_Config.m_ClNameplatesClan) - { - Right.HSplitTop(2.5f, 0, &Right); - Right.HSplitTop(20.0f, &Label, &Right); - Right.HSplitTop(20.0f, &Button, &Right); - str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Clan plates size"), g_Config.m_ClNameplatesClanSize); - UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); - Button.HMargin(2.0f, &Button); - g_Config.m_ClNameplatesClanSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesClanSize, &Button, g_Config.m_ClNameplatesClanSize/100.0f)*100.0f+0.1f); - } + if(g_Config.m_ClNameplatesClan) + { + Right.HSplitTop(2.5f, 0, &Right); + Right.HSplitTop(20.0f, &Label, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Clan plates size"), g_Config.m_ClNameplatesClanSize); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Button.HMargin(2.0f, &Button); + g_Config.m_ClNameplatesClanSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesClanSize, &Button, g_Config.m_ClNameplatesClanSize / 100.0f) * 100.0f + 0.1f); + } } // client @@ -205,7 +205,7 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); Left.HSplitTop(20.0f, &Button, 0); Button.HMargin(2.0f, &Button); - g_Config.m_ClAutoDemoMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoDemoMax, &Button, g_Config.m_ClAutoDemoMax/1000.0f)*1000.0f+0.1f); + g_Config.m_ClAutoDemoMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoDemoMax, &Button, g_Config.m_ClAutoDemoMax / 1000.0f) * 1000.0f + 0.1f); Right.HSplitTop(10.0f, 0, &Right); Right.HSplitTop(20.0f, &Label, &Right); @@ -217,7 +217,7 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); Right.HSplitTop(20.0f, &Button, 0); Button.HMargin(2.0f, &Button); - g_Config.m_ClAutoScreenshotMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoScreenshotMax, &Button, g_Config.m_ClAutoScreenshotMax/1000.0f)*1000.0f+0.1f); + g_Config.m_ClAutoScreenshotMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoScreenshotMax, &Button, g_Config.m_ClAutoScreenshotMax / 1000.0f) * 1000.0f + 0.1f); } Left.HSplitTop(20.0f, 0, &Left); @@ -231,7 +231,7 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); Left.HSplitTop(20.0f, &Button, &Left); Button.HMargin(2.0f, &Button); - g_Config.m_ClRefreshRate= static_cast(DoScrollbarH(&g_Config.m_ClRefreshRate, &Button, g_Config.m_ClRefreshRate/10000.0f)*10000.0f+0.1f); + g_Config.m_ClRefreshRate = static_cast(DoScrollbarH(&g_Config.m_ClRefreshRate, &Button, g_Config.m_ClRefreshRate / 10000.0f) * 10000.0f + 0.1f); #if defined(CONF_FAMILY_WINDOWS) Left.HSplitTop(20.0f, &Button, &Left); @@ -254,8 +254,8 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Right.HSplitTop(20.0f, 0, &Right); // Make some distance so it looks more natural Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClAutoStatboardScreenshot, - Localize("Automatically take statboard screenshot"), - g_Config.m_ClAutoStatboardScreenshot, &Button)) + Localize("Automatically take statboard screenshot"), + g_Config.m_ClAutoStatboardScreenshot, &Button)) { g_Config.m_ClAutoStatboardScreenshot ^= 1; } @@ -272,8 +272,10 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Button.HMargin(2.0f, &Button); g_Config.m_ClAutoStatboardScreenshotMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoStatboardScreenshotMax, - &Button, - g_Config.m_ClAutoStatboardScreenshotMax/1000.0f)*1000.0f+0.1f); + &Button, + g_Config.m_ClAutoStatboardScreenshotMax / 1000.0f) * + 1000.0f + + 0.1f); } // auto statboard csv @@ -282,8 +284,8 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Right.HSplitTop(20.0f, 0, &Right); // Make some distance so it looks more natural Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClAutoCSV, - Localize("Automatically create statboard csv"), - g_Config.m_ClAutoCSV, &Button)) + Localize("Automatically create statboard csv"), + g_Config.m_ClAutoCSV, &Button)) { g_Config.m_ClAutoCSV ^= 1; } @@ -300,8 +302,10 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Button.HMargin(2.0f, &Button); g_Config.m_ClAutoCSVMax = static_cast(DoScrollbarH(&g_Config.m_ClAutoCSVMax, - &Button, - g_Config.m_ClAutoCSVMax / 1000.0f)*1000.0f + 0.1f); + &Button, + g_Config.m_ClAutoCSVMax / 1000.0f) * + 1000.0f + + 0.1f); } } } @@ -385,8 +389,8 @@ void CMenus::RenderSettingsPlayer(CUIRect MainView) Item.m_Rect.Margin(5.0f, &Item.m_Rect); Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label); float OldWidth = Item.m_Rect.w; - Item.m_Rect.w = Item.m_Rect.h*2; - Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f; + Item.m_Rect.w = Item.m_Rect.h * 2; + Item.m_Rect.x += (OldWidth - Item.m_Rect.w) / 2.0f; ColorRGBA Color(1.0f, 1.0f, 1.0f, 1.0f); m_pClient->m_pCountryFlags->Render(pEntry->m_CountryCode, &Color, Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h); if(pEntry->m_Texture != -1) @@ -446,7 +450,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) OwnSkinInfo.m_ColorBody = ColorRGBA(1.0f, 1.0f, 1.0f); OwnSkinInfo.m_ColorFeet = ColorRGBA(1.0f, 1.0f, 1.0f); } - OwnSkinInfo.m_Size = 50.0f*UI()->Scale(); + OwnSkinInfo.m_Size = 50.0f * UI()->Scale(); MainView.HSplitTop(20.0f, &Label, &MainView); Label.VSplitLeft(280.0f, &Label, &Dummy); @@ -481,7 +485,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) Dummy.HSplitTop(20.0f, &DummyLabel, &Dummy); - if (DoButton_CheckBox(&g_Config.m_ClFatSkins, Localize("Fat skins (DDFat)"), g_Config.m_ClFatSkins, &DummyLabel)) + if(DoButton_CheckBox(&g_Config.m_ClFatSkins, Localize("Fat skins (DDFat)"), g_Config.m_ClFatSkins, &DummyLabel)) { g_Config.m_ClFatSkins ^= 1; } @@ -529,7 +533,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) Button.VSplitMid(&Button, &Button2); if(DoButton_CheckBox(&ColorBody, Localize("Custom colors"), *UseCustomColor, &Button)) { - *UseCustomColor = *UseCustomColor?0:1; + *UseCustomColor = *UseCustomColor ? 0 : 1; if(m_Dummy) m_NeedSendDummyinfo = true; else @@ -590,7 +594,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) continue; // vanilla skins only - if (g_Config.m_ClVanillaSkinsOnly && !s->m_IsVanilla) + if(g_Config.m_ClVanillaSkinsOnly && !s->m_IsVanilla) continue; s_paSkinList.add_unsorted(s); @@ -618,11 +622,11 @@ void CMenus::RenderSettingsTee(CUIRect MainView) Info.m_Texture = *UseCustomColor ? s->m_ColorTexture : s->m_OrgTexture; Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top - RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+30, Item.m_Rect.y+Item.m_Rect.h/2)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x + 30, Item.m_Rect.y + Item.m_Rect.h / 2)); Item.m_Rect.VSplitLeft(60.0f, 0, &Item.m_Rect); str_format(aBuf, sizeof(aBuf), "%s", s->m_aName); - RenderTools()->UI()->DoLabelScaled(&Item.m_Rect, aBuf, 12.0f, -1,Item.m_Rect.w); + RenderTools()->UI()->DoLabelScaled(&Item.m_Rect, aBuf, 12.0f, -1, Item.m_Rect.w); if(g_Config.m_Debug) { ColorRGBA BloodColor = *UseCustomColor ? color_cast(ColorHSLA(*ColorBody)) : s->m_BloodColor; @@ -660,7 +664,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) TextRender()->SetCurFont(NULL); QuickSearch.VSplitLeft(wSearch, 0, &QuickSearch); QuickSearch.VSplitLeft(5.0f, 0, &QuickSearch); - QuickSearch.VSplitLeft(QuickSearch.w-15.0f, &QuickSearch, &QuickSearchClearButton); + QuickSearch.VSplitLeft(QuickSearch.w - 15.0f, &QuickSearch, &QuickSearchClearButton); static int s_ClearButton = 0; static float Offset = 0.0f; if(Input()->KeyPress(KEY_F) && (Input()->KeyIsPressed(KEY_LCTRL) || Input()->KeyIsPressed(KEY_RCTRL))) @@ -691,54 +695,54 @@ typedef struct } CKeyInfo; static CKeyInfo gs_aKeys[] = -{ - { "Move left", "+left", 0, 0 }, // Localize - these strings are localized within CLocConstString - { "Move right", "+right", 0, 0 }, - { "Jump", "+jump", 0, 0 }, - { "Fire", "+fire", 0, 0 }, - { "Hook", "+hook", 0, 0 }, - { "Hook collisions", "+showhookcoll", 0, 0 }, - { "Pause", "say /pause", 0, 0 }, - { "Kill", "kill", 0, 0 }, - { "Zoom in", "zoom+", 0, 0 }, - { "Zoom out", "zoom-", 0, 0 }, - { "Default zoom", "zoom", 0, 0 }, - { "Show others", "say /showothers", 0, 0 }, - { "Show all", "say /showall", 0, 0 }, - { "Toggle dyncam", "toggle cl_dyncam 0 1", 0, 0 }, - { "Toggle dummy", "toggle cl_dummy 0 1", 0, 0 }, - { "Toggle ghost", "toggle cl_race_show_ghost 0 1", 0, 0 }, - { "Dummy copy", "toggle cl_dummy_copy_moves 0 1", 0, 0 }, - { "Hammerfly dummy", "toggle cl_dummy_hammer 0 1", 0, 0 }, + { + {"Move left", "+left", 0, 0}, // Localize - these strings are localized within CLocConstString + {"Move right", "+right", 0, 0}, + {"Jump", "+jump", 0, 0}, + {"Fire", "+fire", 0, 0}, + {"Hook", "+hook", 0, 0}, + {"Hook collisions", "+showhookcoll", 0, 0}, + {"Pause", "say /pause", 0, 0}, + {"Kill", "kill", 0, 0}, + {"Zoom in", "zoom+", 0, 0}, + {"Zoom out", "zoom-", 0, 0}, + {"Default zoom", "zoom", 0, 0}, + {"Show others", "say /showothers", 0, 0}, + {"Show all", "say /showall", 0, 0}, + {"Toggle dyncam", "toggle cl_dyncam 0 1", 0, 0}, + {"Toggle dummy", "toggle cl_dummy 0 1", 0, 0}, + {"Toggle ghost", "toggle cl_race_show_ghost 0 1", 0, 0}, + {"Dummy copy", "toggle cl_dummy_copy_moves 0 1", 0, 0}, + {"Hammerfly dummy", "toggle cl_dummy_hammer 0 1", 0, 0}, - { "Hammer", "+weapon1", 0, 0 }, - { "Pistol", "+weapon2", 0, 0 }, - { "Shotgun", "+weapon3", 0, 0 }, - { "Grenade", "+weapon4", 0, 0 }, - { "Laser", "+weapon5", 0, 0 }, - { "Next weapon", "+nextweapon", 0, 0 }, - { "Prev. weapon", "+prevweapon", 0, 0 }, + {"Hammer", "+weapon1", 0, 0}, + {"Pistol", "+weapon2", 0, 0}, + {"Shotgun", "+weapon3", 0, 0}, + {"Grenade", "+weapon4", 0, 0}, + {"Laser", "+weapon5", 0, 0}, + {"Next weapon", "+nextweapon", 0, 0}, + {"Prev. weapon", "+prevweapon", 0, 0}, - { "Vote yes", "vote yes", 0, 0 }, - { "Vote no", "vote no", 0, 0 }, + {"Vote yes", "vote yes", 0, 0}, + {"Vote no", "vote no", 0, 0}, - { "Chat", "+show_chat; chat all", 0, 0 }, - { "Team chat", "+show_chat; chat team", 0, 0 }, - { "Converse", "+show_chat; chat all /c ", 0, 0 }, - { "Show chat", "+show_chat", 0, 0 }, + {"Chat", "+show_chat; chat all", 0, 0}, + {"Team chat", "+show_chat; chat team", 0, 0}, + {"Converse", "+show_chat; chat all /c ", 0, 0}, + {"Show chat", "+show_chat", 0, 0}, - { "Emoticon", "+emote", 0, 0 }, - { "Spectator mode", "+spectate", 0, 0 }, - { "Spectate next", "spectate_next", 0, 0 }, - { "Spectate previous", "spectate_previous", 0, 0 }, - { "Console", "toggle_local_console", 0, 0 }, - { "Remote console", "toggle_remote_console", 0, 0 }, - { "Screenshot", "screenshot", 0, 0 }, - { "Scoreboard", "+scoreboard", 0, 0 }, - { "Statboard", "+statboard", 0, 0 }, - { "Lock team", "say /lock", 0, 0 }, - { "Show entities", "toggle cl_overlay_entities 0 100", 0, 0 }, - { "Show HUD", "toggle cl_showhud 0 1", 0, 0 }, + {"Emoticon", "+emote", 0, 0}, + {"Spectator mode", "+spectate", 0, 0}, + {"Spectate next", "spectate_next", 0, 0}, + {"Spectate previous", "spectate_previous", 0, 0}, + {"Console", "toggle_local_console", 0, 0}, + {"Remote console", "toggle_remote_console", 0, 0}, + {"Screenshot", "screenshot", 0, 0}, + {"Scoreboard", "+scoreboard", 0, 0}, + {"Statboard", "+statboard", 0, 0}, + {"Lock team", "say /lock", 0, 0}, + {"Show entities", "toggle cl_overlay_entities 0 100", 0, 0}, + {"Show HUD", "toggle cl_showhud 0 1", 0, 0}, }; /* This is for scripts/languages to work, don't remove! @@ -817,7 +821,7 @@ void CMenus::RenderSettingsControls(CUIRect MainView) static int s_SelectedControl = -1; static float s_ScrollValue = 0; int OldSelected = s_SelectedControl; - UiDoListboxStart(&s_ControlsList , &MainView, 475.0f, Localize("Controls"), "", 1, 1, s_SelectedControl, s_ScrollValue); + UiDoListboxStart(&s_ControlsList, &MainView, 475.0f, Localize("Controls"), "", 1, 1, s_SelectedControl, s_ScrollValue); CUIRect MovementSettings, WeaponSettings, VotingSettings, ChatSettings, MiscSettings, ResetButton; CListboxItem Item = UiDoListboxNextItem(&OldSelected, false, false, true); @@ -828,21 +832,21 @@ void CMenus::RenderSettingsControls(CUIRect MainView) { MovementSettings.VMargin(5.0f, &MovementSettings); MovementSettings.HSplitTop(515.0f, &MovementSettings, &WeaponSettings); - RenderTools()->DrawUIRect(&MovementSettings, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&MovementSettings, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); MovementSettings.VMargin(10.0f, &MovementSettings); - TextRender()->Text(0, MovementSettings.x, MovementSettings.y + (14.0f + 5.0f + 10.0f - 14.0f*UI()->Scale()) / 2.f, 14.0f*UI()->Scale(), Localize("Movement"), -1.0f); + TextRender()->Text(0, MovementSettings.x, MovementSettings.y + (14.0f + 5.0f + 10.0f - 14.0f * UI()->Scale()) / 2.f, 14.0f * UI()->Scale(), Localize("Movement"), -1.0f); - MovementSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &MovementSettings); + MovementSettings.HSplitTop(14.0f + 5.0f + 10.0f, 0, &MovementSettings); { CUIRect Button, Label; MovementSettings.HSplitTop(20.0f, &Button, &MovementSettings); Button.VSplitLeft(160.0f, &Label, &Button); str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Mouse sens."), g_Config.m_InpMousesens); - UI()->DoLabel(&Label, aBuf, 14.0f*UI()->Scale(), -1); + UI()->DoLabel(&Label, aBuf, 14.0f * UI()->Scale(), -1); Button.HMargin(2.0f, &Button); - int NewValue = (int)(DoScrollbarH(&g_Config.m_InpMousesens, &Button, (minimum(g_Config.m_InpMousesens, 500)-1)/500.0f)*500.0f)+1; + int NewValue = (int)(DoScrollbarH(&g_Config.m_InpMousesens, &Button, (minimum(g_Config.m_InpMousesens, 500) - 1) / 500.0f) * 500.0f) + 1; if(g_Config.m_InpMousesens < 500 || NewValue < 500) g_Config.m_InpMousesens = minimum(NewValue, 500); MovementSettings.HSplitTop(20.0f, 0, &MovementSettings); @@ -853,28 +857,27 @@ void CMenus::RenderSettingsControls(CUIRect MainView) MovementSettings.HSplitTop(20.0f, &Button, &MovementSettings); Button.VSplitLeft(160.0f, &Label, &Button); str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("UI mouse s."), g_Config.m_UiMousesens); - UI()->DoLabel(&Label, aBuf, 14.0f*UI()->Scale(), -1); + UI()->DoLabel(&Label, aBuf, 14.0f * UI()->Scale(), -1); Button.HMargin(2.0f, &Button); - int NewValue = (int)(DoScrollbarH(&g_Config.m_UiMousesens, &Button, (minimum(g_Config.m_UiMousesens, 500)-1)/500.0f)*500.0f)+1; + int NewValue = (int)(DoScrollbarH(&g_Config.m_UiMousesens, &Button, (minimum(g_Config.m_UiMousesens, 500) - 1) / 500.0f) * 500.0f) + 1; if(g_Config.m_UiMousesens < 500 || NewValue < 500) g_Config.m_UiMousesens = minimum(NewValue, 500); MovementSettings.HSplitTop(20.0f, 0, &MovementSettings); } UiDoGetButtons(0, 18, MovementSettings, MainView); - } // weapon settings { WeaponSettings.HSplitTop(10.0f, 0, &WeaponSettings); WeaponSettings.HSplitTop(190.0f, &WeaponSettings, &ResetButton); - RenderTools()->DrawUIRect(&WeaponSettings, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&WeaponSettings, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); WeaponSettings.VMargin(10.0f, &WeaponSettings); - TextRender()->Text(0, WeaponSettings.x, WeaponSettings.y + (14.0f + 5.0f + 10.0f - 14.0f*UI()->Scale()) / 2.f, 14.0f*UI()->Scale(), Localize("Weapon"), -1.0f); + TextRender()->Text(0, WeaponSettings.x, WeaponSettings.y + (14.0f + 5.0f + 10.0f - 14.0f * UI()->Scale()) / 2.f, 14.0f * UI()->Scale(), Localize("Weapon"), -1.0f); - WeaponSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &WeaponSettings); + WeaponSettings.HSplitTop(14.0f + 5.0f + 10.0f, 0, &WeaponSettings); UiDoGetButtons(18, 25, WeaponSettings, MainView); } @@ -882,12 +885,12 @@ void CMenus::RenderSettingsControls(CUIRect MainView) { ResetButton.HSplitTop(10.0f, 0, &ResetButton); ResetButton.HSplitTop(40.0f, &ResetButton, 0); - RenderTools()->DrawUIRect(&ResetButton, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&ResetButton, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); ResetButton.HMargin(10.0f, &ResetButton); ResetButton.VMargin(30.0f, &ResetButton); ResetButton.HSplitTop(20.0f, &ResetButton, 0); static int s_DefaultButton = 0; - if(DoButton_Menu((void*)&s_DefaultButton, Localize("Reset to defaults"), 0, &ResetButton)) + if(DoButton_Menu((void *)&s_DefaultButton, Localize("Reset to defaults"), 0, &ResetButton)) m_pClient->m_pBinds->SetDefaults(); } @@ -895,12 +898,12 @@ void CMenus::RenderSettingsControls(CUIRect MainView) { VotingSettings.VMargin(5.0f, &VotingSettings); VotingSettings.HSplitTop(80.0f, &VotingSettings, &ChatSettings); - RenderTools()->DrawUIRect(&VotingSettings, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&VotingSettings, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); VotingSettings.VMargin(10.0f, &VotingSettings); - TextRender()->Text(0, VotingSettings.x, VotingSettings.y + (14.0f + 5.0f + 10.0f - 14.0f*UI()->Scale()) / 2.f, 14.0f*UI()->Scale(), Localize("Voting"), -1.0f); + TextRender()->Text(0, VotingSettings.x, VotingSettings.y + (14.0f + 5.0f + 10.0f - 14.0f * UI()->Scale()) / 2.f, 14.0f * UI()->Scale(), Localize("Voting"), -1.0f); - VotingSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &VotingSettings); + VotingSettings.HSplitTop(14.0f + 5.0f + 10.0f, 0, &VotingSettings); UiDoGetButtons(25, 27, VotingSettings, MainView); } @@ -908,12 +911,12 @@ void CMenus::RenderSettingsControls(CUIRect MainView) { ChatSettings.HSplitTop(10.0f, 0, &ChatSettings); ChatSettings.HSplitTop(125.0f, &ChatSettings, &MiscSettings); - RenderTools()->DrawUIRect(&ChatSettings, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&ChatSettings, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); ChatSettings.VMargin(10.0f, &ChatSettings); - TextRender()->Text(0, ChatSettings.x, ChatSettings.y + (14.0f + 5.0f + 10.0f - 14.0f*UI()->Scale()) / 2.f, 14.0f*UI()->Scale(), Localize("Chat"), -1.0f); + TextRender()->Text(0, ChatSettings.x, ChatSettings.y + (14.0f + 5.0f + 10.0f - 14.0f * UI()->Scale()) / 2.f, 14.0f * UI()->Scale(), Localize("Chat"), -1.0f); - ChatSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &ChatSettings); + ChatSettings.HSplitTop(14.0f + 5.0f + 10.0f, 0, &ChatSettings); UiDoGetButtons(27, 31, ChatSettings, MainView); } @@ -921,12 +924,12 @@ void CMenus::RenderSettingsControls(CUIRect MainView) { MiscSettings.HSplitTop(10.0f, 0, &MiscSettings); MiscSettings.HSplitTop(300.0f, &MiscSettings, 0); - RenderTools()->DrawUIRect(&MiscSettings, ColorRGBA(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + RenderTools()->DrawUIRect(&MiscSettings, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_ALL, 10.0f); MiscSettings.VMargin(10.0f, &MiscSettings); - TextRender()->Text(0, MiscSettings.x, MiscSettings.y + (14.0f + 5.0f + 10.0f - 14.0f*UI()->Scale()) / 2.f, 14.0f*UI()->Scale(), Localize("Miscellaneous"), -1.0f); + TextRender()->Text(0, MiscSettings.x, MiscSettings.y + (14.0f + 5.0f + 10.0f - 14.0f * UI()->Scale()) / 2.f, 14.0f * UI()->Scale(), Localize("Miscellaneous"), -1.0f); - MiscSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &MiscSettings); + MiscSettings.HSplitTop(14.0f + 5.0f + 10.0f, 0, &MiscSettings); UiDoGetButtons(31, 43, MiscSettings, MainView); } @@ -957,7 +960,7 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) // draw allmodes switch ModeList.HSplitTop(20, &Button, &ModeList); - if(DoButton_CheckBox(&g_Config.m_GfxDisplayAllModes, Localize("Show only supported"), g_Config.m_GfxDisplayAllModes^1, &Button)) + if(DoButton_CheckBox(&g_Config.m_GfxDisplayAllModes, Localize("Show only supported"), g_Config.m_GfxDisplayAllModes ^ 1, &Button)) { g_Config.m_GfxDisplayAllModes ^= 1; s_NumNodes = Graphics()->GetVideoModes(s_aModes, MAX_RESOLUTIONS, g_Config.m_GfxScreen); @@ -967,12 +970,12 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) static float s_ScrollValue = 0; int OldSelected = -1; int G = gcd(s_GfxScreenWidth, s_GfxScreenHeight); - str_format(aBuf, sizeof(aBuf), "%s: %dx%d %d bit (%d:%d)", Localize("Current"), s_GfxScreenWidth, s_GfxScreenHeight, s_GfxColorDepth, s_GfxScreenWidth/G, s_GfxScreenHeight/G); - UiDoListboxStart(&s_NumNodes , &ModeList, 24.0f, Localize("Display Modes"), aBuf, s_NumNodes, 1, OldSelected, s_ScrollValue); + str_format(aBuf, sizeof(aBuf), "%s: %dx%d %d bit (%d:%d)", Localize("Current"), s_GfxScreenWidth, s_GfxScreenHeight, s_GfxColorDepth, s_GfxScreenWidth / G, s_GfxScreenHeight / G); + UiDoListboxStart(&s_NumNodes, &ModeList, 24.0f, Localize("Display Modes"), aBuf, s_NumNodes, 1, OldSelected, s_ScrollValue); for(int i = 0; i < s_NumNodes; ++i) { - const int Depth = s_aModes[i].m_Red+s_aModes[i].m_Green+s_aModes[i].m_Blue > 16 ? 24 : 16; + const int Depth = s_aModes[i].m_Red + s_aModes[i].m_Green + s_aModes[i].m_Blue > 16 ? 24 : 16; if(g_Config.m_GfxColorDepth == Depth && g_Config.m_GfxScreenWidth == s_aModes[i].m_Width && g_Config.m_GfxScreenHeight == s_aModes[i].m_Height) @@ -984,7 +987,7 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) if(Item.m_Visible) { int G = gcd(s_aModes[i].m_Width, s_aModes[i].m_Height); - str_format(aBuf, sizeof(aBuf), " %dx%d %d bit (%d:%d)", s_aModes[i].m_Width, s_aModes[i].m_Height, Depth, s_aModes[i].m_Width/G, s_aModes[i].m_Height/G); + str_format(aBuf, sizeof(aBuf), " %dx%d %d bit (%d:%d)", s_aModes[i].m_Width, s_aModes[i].m_Height, Depth, s_aModes[i].m_Width / G, s_aModes[i].m_Height / G); UI()->DoLabelScaled(&Item.m_Rect, aBuf, 16.0f, -1); } } @@ -992,7 +995,7 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(OldSelected != NewSelected) { - const int Depth = s_aModes[NewSelected].m_Red+s_aModes[NewSelected].m_Green+s_aModes[NewSelected].m_Blue > 16 ? 24 : 16; + const int Depth = s_aModes[NewSelected].m_Red + s_aModes[NewSelected].m_Green + s_aModes[NewSelected].m_Blue > 16 ? 24 : 16; g_Config.m_GfxColorDepth = Depth; g_Config.m_GfxScreenWidth = s_aModes[NewSelected].m_Width; g_Config.m_GfxScreenHeight = s_aModes[NewSelected].m_Height; @@ -1030,12 +1033,12 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) int Screen_MouseButton = DoButton_CheckBox_Number(&g_Config.m_GfxScreen, Localize("Screen"), g_Config.m_GfxScreen, &Button); if(Screen_MouseButton == 1) //inc { - Client()->SwitchWindowScreen((g_Config.m_GfxScreen+1)%NumScreens); + Client()->SwitchWindowScreen((g_Config.m_GfxScreen + 1) % NumScreens); s_NumNodes = Graphics()->GetVideoModes(s_aModes, MAX_RESOLUTIONS, g_Config.m_GfxScreen); } else if(Screen_MouseButton == 2) //dec { - Client()->SwitchWindowScreen((g_Config.m_GfxScreen-1+NumScreens)%NumScreens); + Client()->SwitchWindowScreen((g_Config.m_GfxScreen - 1 + NumScreens) % NumScreens); s_NumNodes = Graphics()->GetVideoModes(s_aModes, MAX_RESOLUTIONS, g_Config.m_GfxScreen); } } @@ -1045,12 +1048,12 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) int GfxFsaaSamples_MouseButton = DoButton_CheckBox_Number(&g_Config.m_GfxFsaaSamples, aBuf, g_Config.m_GfxFsaaSamples, &Button); if(GfxFsaaSamples_MouseButton == 1) //inc { - g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples+1)%17; + g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples + 1) % 17; CheckSettings = true; } else if(GfxFsaaSamples_MouseButton == 2) //dec { - g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples-1 +17)%17; + g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples - 1 + 17) % 17; CheckSettings = true; } @@ -1103,7 +1106,6 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) g_Config.m_GfxHighdpi ^= 1; } - // check if the new settings require a restart if(CheckSettings) { @@ -1129,7 +1131,7 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Refresh Rate"), "∞"); UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); Button.HMargin(2.0f, &Button); - int NewRefreshRate = static_cast(DoScrollbarH(&g_Config.m_GfxRefreshRate, &Button, (minimum(g_Config.m_GfxRefreshRate, 1000))/1000.0f)*1000.0f+0.1f); + int NewRefreshRate = static_cast(DoScrollbarH(&g_Config.m_GfxRefreshRate, &Button, (minimum(g_Config.m_GfxRefreshRate, 1000)) / 1000.0f) * 1000.0f + 0.1f); if(g_Config.m_GfxRefreshRate <= 1000 || NewRefreshRate < 1000) g_Config.m_GfxRefreshRate = NewRefreshRate; @@ -1235,7 +1237,7 @@ void CMenus::RenderSettingsSound(CUIRect MainView) Button.VSplitLeft(190.0f, &Label, &Button); Button.HMargin(2.0f, &Button); UI()->DoLabelScaled(&Label, Localize("Sound volume"), 14.0f, -1); - g_Config.m_SndVolume = (int)(DoScrollbarH(&g_Config.m_SndVolume, &Button, g_Config.m_SndVolume/100.0f)*100.0f); + g_Config.m_SndVolume = (int)(DoScrollbarH(&g_Config.m_SndVolume, &Button, g_Config.m_SndVolume / 100.0f) * 100.0f); } // volume slider map sounds @@ -1246,7 +1248,7 @@ void CMenus::RenderSettingsSound(CUIRect MainView) Button.VSplitLeft(190.0f, &Label, &Button); Button.HMargin(2.0f, &Button); UI()->DoLabelScaled(&Label, Localize("Map sound volume"), 14.0f, -1); - g_Config.m_SndMapSoundVolume = (int)(DoScrollbarH(&g_Config.m_SndMapSoundVolume, &Button, g_Config.m_SndMapSoundVolume/100.0f)*100.0f); + g_Config.m_SndMapSoundVolume = (int)(DoScrollbarH(&g_Config.m_SndMapSoundVolume, &Button, g_Config.m_SndMapSoundVolume / 100.0f) * 100.0f); } } @@ -1254,7 +1256,8 @@ class CLanguage { public: CLanguage() {} - CLanguage(const char *n, const char *f, int Code) : m_Name(n), m_FileName(f), m_CountryCode(Code) {} + CLanguage(const char *n, const char *f, int Code) : + m_Name(n), m_FileName(f), m_CountryCode(Code) {} string m_Name; string m_FileName; @@ -1299,7 +1302,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< (void)LineReader.Get(); continue; } - str_copy(aReplacement, pLine+3, sizeof(aReplacement)); + str_copy(aReplacement, pLine + 3, sizeof(aReplacement)); pLine = LineReader.Get(); if(!pLine) @@ -1318,7 +1321,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< char aFileName[128]; str_format(aFileName, sizeof(aFileName), "languages/%s.txt", aOrigin); - pLanguages->add(CLanguage(aReplacement, aFileName, str_toint(pLine+3))); + pLanguages->add(CLanguage(aReplacement, aFileName, str_toint(pLine + 3))); } io_close(File); } @@ -1344,7 +1347,7 @@ void CMenus::RenderLanguageSelection(CUIRect MainView) int OldSelected = s_SelectedLanguage; - UiDoListboxStart(&s_LanguageList , &MainView, 24.0f, Localize("Language"), "", s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue); + UiDoListboxStart(&s_LanguageList, &MainView, 24.0f, Localize("Language"), "", s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue); for(sorted_array::range r = s_Languages.all(); !r.empty(); r.pop_front()) { @@ -1353,7 +1356,7 @@ void CMenus::RenderLanguageSelection(CUIRect MainView) if(Item.m_Visible) { CUIRect Rect; - Item.m_Rect.VSplitLeft(Item.m_Rect.h*2.0f, &Rect, &Item.m_Rect); + Item.m_Rect.VSplitLeft(Item.m_Rect.h * 2.0f, &Rect, &Item.m_Rect); Rect.VMargin(6.0f, &Rect); Rect.HMargin(3.0f, &Rect); ColorRGBA Color(1.0f, 1.0f, 1.0f, 1.0f); @@ -1396,10 +1399,9 @@ void CMenus::RenderSettings(CUIRect MainView) Localize("Controls"), Localize("Graphics"), Localize("Sound"), - Localize("DDNet") - }; + Localize("DDNet")}; - int NumTabs = (int)(sizeof(aTabs)/sizeof(*aTabs)); + int NumTabs = (int)(sizeof(aTabs) / sizeof(*aTabs)); for(int i = 0; i < NumTabs; i++) { @@ -1522,7 +1524,6 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) if(DoButton_CheckBox(&g_Config.m_ClShowhud, Localize("Show ingame HUD"), g_Config.m_ClShowhud, &Button)) g_Config.m_ClShowhud ^= 1; - Left.HSplitTop(20.0f, &Button, &Left); if(DoButton_CheckBox(&g_Config.m_ClDDRaceScoreBoard, Localize("Use DDRace Scoreboard"), g_Config.m_ClDDRaceScoreBoard, &Button)) { @@ -1599,7 +1600,6 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) ColorRGBA rgb = color_cast(SMColor); TextRender()->TextColor(rgb); - char aName[16]; str_copy(aName, Client()->PlayerName(), sizeof(aName)); str_format(aBuf, sizeof(aBuf), "*** '%s' entered and joined the spectators", aName); @@ -1639,7 +1639,7 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) TextRender()->TextColor(rgb); char aName[16]; str_copy(aName, Client()->PlayerName(), sizeof(aName)); - str_format(aBuf, sizeof(aBuf), ": %s: %s", aName, Localize ("Look out!")); + str_format(aBuf, sizeof(aBuf), ": %s: %s", aName, Localize("Look out!")); while(TextRender()->TextWidth(0, 12.0f, aBuf, -1, -1.0f) > Button.w) { aName[str_length(aName) - 1] = 0; @@ -1676,7 +1676,7 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) ColorRGBA rgb = color_cast(TMColor); TextRender()->TextColor(rgb); - str_format(aBuf, sizeof(aBuf), ": %s!", Localize("We will win")); + str_format(aBuf, sizeof(aBuf), ": %s!", Localize("We will win")); UI()->DoLabelScaled(&Button, aBuf, 12.0f, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); @@ -1686,14 +1686,14 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) char aBuf[64]; Right.HSplitTop(20.0f, &Label, &Right); Label.VSplitRight(50.0f, &Label, &Button); - float twh = TextRender()->TextWidth(0, 16.0f, Localize("Friend message"), -1, -1.0f) ; + float twh = TextRender()->TextWidth(0, 16.0f, Localize("Friend message"), -1, -1.0f); Label.VSplitLeft(twh + 5.0f, &Label, &Enable); Enable.VSplitLeft(20.0f, &Enable, 0); UI()->DoLabelScaled(&Label, Localize("Friend message"), 16.0f, -1); { static int s_DefaultButton = 0; if(DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)) - g_Config.m_ClMessageFriendColor = ColorHSLA(0, 1, 145/255.0f).Pack(false); + g_Config.m_ClMessageFriendColor = ColorHSLA(0, 1, 145 / 255.0f).Pack(false); } if(DoButton_CheckBox(&g_Config.m_ClMessageFriend, "", g_Config.m_ClMessageFriend, &Enable)) @@ -1776,7 +1776,6 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) ColorRGBA rgb = color_cast(CMColor); TextRender()->TextColor(rgb); - UI()->DoLabelScaled(&Label, "*** Dynamic camera activated", 12.0f, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); Right.HSplitTop(20.0f, 0, &Right); @@ -1869,7 +1868,7 @@ void CMenus::RenderSettingsHUD(CUIRect MainView) Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); Graphics()->QuadsBegin(); - int Sprites[] = { SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03 }; + int Sprites[] = {SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03}; RenderTools()->SelectSprite(Sprites[time_get() % 3]); Graphics()->QuadsSetRotation(time_get()); Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); @@ -1917,7 +1916,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) bool CheckSettings = false; static int s_InpMouseOld = g_Config.m_InpMouseOld; - MainView.HSplitTop(100.0f, &Demo , &MainView); + MainView.HSplitTop(100.0f, &Demo, &MainView); Demo.HSplitTop(30.0f, &Label, &Demo); UI()->DoLabelScaled(&Label, Localize("Demo"), 20.0f, -1); @@ -1943,7 +1942,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) str_format(aBuf, sizeof(aBuf), Localize("Default length: %d"), g_Config.m_ClReplayLength); UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); - int NewValue = (int)(DoScrollbarH(&g_Config.m_ClReplayLength, &Button, (minimum(g_Config.m_ClReplayLength, 600) - 10) / 590.0f)*590.0f) + 10; + int NewValue = (int)(DoScrollbarH(&g_Config.m_ClReplayLength, &Button, (minimum(g_Config.m_ClReplayLength, 600) - 10) / 590.0f) * 590.0f) + 10; if(g_Config.m_ClReplayLength < 600 || NewValue < 600) g_Config.m_ClReplayLength = minimum(NewValue, 600); @@ -1984,7 +1983,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) } } - MainView.HSplitTop(310.0f, &Gameplay , &MainView); + MainView.HSplitTop(310.0f, &Gameplay, &MainView); Gameplay.HSplitTop(30.0f, &Label, &Gameplay); UI()->DoLabelScaled(&Label, Localize("Gameplay"), 20.0f, -1); @@ -1999,7 +1998,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) Button.VSplitLeft(120.0f, &Label, &Button); Button.HMargin(2.0f, &Button); UI()->DoLabelScaled(&Label, Localize("Overlay entities"), 14.0f, -1); - g_Config.m_ClOverlayEntities = (int)(DoScrollbarH(&g_Config.m_ClOverlayEntities, &Button, g_Config.m_ClOverlayEntities/100.0f)*100.0f); + g_Config.m_ClOverlayEntities = (int)(DoScrollbarH(&g_Config.m_ClOverlayEntities, &Button, g_Config.m_ClOverlayEntities / 100.0f) * 100.0f); } { @@ -2010,7 +2009,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) Button.VSplitLeft(50.0f, &Label, &Button); Button.HMargin(2.0f, &Button); UI()->DoLabelScaled(&Label, Localize("Size"), 14.0f, -1); - g_Config.m_ClTextEntitiesSize = (int)(DoScrollbarH(&g_Config.m_ClTextEntitiesSize, &Button, g_Config.m_ClTextEntitiesSize/100.0f)*100.0f); + g_Config.m_ClTextEntitiesSize = (int)(DoScrollbarH(&g_Config.m_ClTextEntitiesSize, &Button, g_Config.m_ClTextEntitiesSize / 100.0f) * 100.0f); if(DoButton_CheckBox(&g_Config.m_ClTextEntities, Localize("Show text entities"), g_Config.m_ClTextEntities, &LeftLeft)) { @@ -2026,7 +2025,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) Button.VSplitLeft(50.0f, &Label, &Button); Button.HMargin(2.0f, &Button); UI()->DoLabelScaled(&Label, Localize("Alpha"), 14.0f, -1); - g_Config.m_ClShowOthersAlpha = (int)(DoScrollbarH(&g_Config.m_ClShowOthersAlpha, &Button, g_Config.m_ClShowOthersAlpha /100.0f)*100.0f); + g_Config.m_ClShowOthersAlpha = (int)(DoScrollbarH(&g_Config.m_ClShowOthersAlpha, &Button, g_Config.m_ClShowOthersAlpha / 100.0f) * 100.0f); if(DoButton_CheckBox(&g_Config.m_ClShowOthers, Localize("Show others"), g_Config.m_ClShowOthers == 1, &LeftLeft)) { @@ -2054,7 +2053,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); //Right.HSplitTop(20.0f, &Button, 0); Button.HMargin(2.0f, &Button); - g_Config.m_ClDefaultZoom= static_cast(DoScrollbarH(&g_Config.m_ClDefaultZoom, &Button, g_Config.m_ClDefaultZoom/20.0f)*20.0f+0.1f); + g_Config.m_ClDefaultZoom = static_cast(DoScrollbarH(&g_Config.m_ClDefaultZoom, &Button, g_Config.m_ClDefaultZoom / 20.0f) * 20.0f + 0.1f); Right.HSplitTop(20.0f, &Label, &Right); Label.VSplitLeft(130.0f, &Label, &Button); @@ -2062,7 +2061,7 @@ void CMenus::RenderSettingsDDNet(CUIRect MainView) UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); //Right.HSplitTop(20.0f, &Button, 0); Button.HMargin(2.0f, &Button); - g_Config.m_ClAntiPingLimit= static_cast(DoScrollbarH(&g_Config.m_ClAntiPingLimit, &Button, g_Config.m_ClAntiPingLimit/200.0f)*200.0f+0.1f); + g_Config.m_ClAntiPingLimit = static_cast(DoScrollbarH(&g_Config.m_ClAntiPingLimit, &Button, g_Config.m_ClAntiPingLimit / 200.0f) * 200.0f + 0.1f); Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClAntiPing, Localize("AntiPing"), g_Config.m_ClAntiPing, &Button)) diff --git a/src/game/client/components/motd.cpp b/src/game/client/components/motd.cpp index bca6ff1f7..b5ef4ce5a 100644 --- a/src/game/client/components/motd.cpp +++ b/src/game/client/components/motd.cpp @@ -1,13 +1,13 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include -#include #include +#include +#include -#include -#include #include +#include +#include #include "motd.h" @@ -32,24 +32,24 @@ void CMotd::OnRender() if(!IsActive()) return; - float Width = 400*3.0f*Graphics()->ScreenAspect(); - float Height = 400*3.0f; + float Width = 400 * 3.0f * Graphics()->ScreenAspect(); + float Height = 400 * 3.0f; Graphics()->MapScreen(0, 0, Width, Height); float h = 800.0f; float w = 650.0f; - float x = Width/2 - w/2; + float x = Width / 2 - w / 2; float y = 150.0f; Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.5f); + Graphics()->SetColor(0, 0, 0, 0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 40.0f); Graphics()->QuadsEnd(); - TextRender()->Text(0, x+40.0f, y+40.0f, 32.0f, m_aServerMotd, w-80.0f); + TextRender()->Text(0, x + 40.0f, y + 40.0f, 32.0f, m_aServerMotd, w - 80.0f); } void CMotd::OnMessage(int MsgType, void *pRawMsg) @@ -68,7 +68,7 @@ void CMotd::OnMessage(int MsgType, void *pRawMsg) for(int i = 0, k = 0; i < MotdLen && k < (int)sizeof(m_aServerMotd); i++, k++) { // handle incoming "\\n" - if(pMsgStr[i] == '\\' && pMsgStr[i+1] == 'n') + if(pMsgStr[i] == '\\' && pMsgStr[i + 1] == 'n') { m_aServerMotd[k] = '\n'; i++; // skip the 'n' @@ -82,7 +82,7 @@ void CMotd::OnMessage(int MsgType, void *pRawMsg) m_aServerMotd[k] = '\0'; m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "motd", pLast, true); m_aServerMotd[k] = '\n'; - pLast = m_aServerMotd + k+1; + pLast = m_aServerMotd + k + 1; } } m_aServerMotd[sizeof(m_aServerMotd) - 1] = '\0'; @@ -90,7 +90,7 @@ void CMotd::OnMessage(int MsgType, void *pRawMsg) m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "motd", pLast, true); if(m_aServerMotd[0] && g_Config.m_ClMotdTime) - m_ServerMotdTime = time()+time_freq()*g_Config.m_ClMotdTime; + m_ServerMotdTime = time() + time_freq() * g_Config.m_ClMotdTime; else m_ServerMotdTime = 0; } @@ -98,7 +98,7 @@ void CMotd::OnMessage(int MsgType, void *pRawMsg) bool CMotd::OnInput(IInput::CEvent Event) { - if(IsActive() && Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) + if(IsActive() && Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) { Clear(); return true; diff --git a/src/game/client/components/motd.h b/src/game/client/components/motd.h index f47adafff..338ca22d1 100644 --- a/src/game/client/components/motd.h +++ b/src/game/client/components/motd.h @@ -8,6 +8,7 @@ class CMotd : public CComponent { // motd int64 m_ServerMotdTime; + public: char m_aServerMotd[900]; diff --git a/src/game/client/components/nameplates.cpp b/src/game/client/components/nameplates.cpp index dba2cd91c..515c0c4d1 100644 --- a/src/game/client/components/nameplates.cpp +++ b/src/game/client/components/nameplates.cpp @@ -1,16 +1,16 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include #include -#include +#include #include +#include -#include -#include -#include "nameplates.h" -#include "controls.h" #include "camera.h" +#include "controls.h" +#include "nameplates.h" +#include +#include #include "players.h" @@ -24,8 +24,7 @@ void CNamePlates::MapscreenToGroup(float CenterX, float CenterY, CMapItemGroup * void CNamePlates::RenderNameplate( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, - const CNetObj_PlayerInfo *pPlayerInfo - ) + const CNetObj_PlayerInfo *pPlayerInfo) { int ClientID = pPlayerInfo->m_ClientID; @@ -53,7 +52,7 @@ void CNamePlates::RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pP TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE); float a = 1; if(g_Config.m_ClNameplatesAlways == 0) - a = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy], Position)/200.0f,16.0f), 0.0f, 1.0f); + a = clamp(1 - powf(distance(m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy], Position) / 200.0f, 16.0f), 0.0f, 1.0f); const char *pName = m_pClient->m_aClients[pPlayerInfo->m_ClientID].m_aName; if(str_comp(pName, m_aNamePlates[ClientID].m_aName) != 0 || FontSize != m_aNamePlates[ClientID].m_NameTextFontSize) @@ -121,10 +120,10 @@ void CNamePlates::RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pP } else { - TOutlineColor.Set(0.0f, 0.0f, 0.0f, 0.5f*a); + TOutlineColor.Set(0.0f, 0.0f, 0.0f, 0.5f * a); TColor.Set(rgb.r, rgb.g, rgb.b, a); } - if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED) TColor.Set(1.0f, 0.5f, 0.5f, a); @@ -135,7 +134,7 @@ void CNamePlates::RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pP TOutlineColor.m_A *= Alpha; TColor.m_A *= Alpha; - float YOffset = Position.y-38; + float YOffset = Position.y - 38; if(m_aNamePlates[ClientID].m_NameTextContainerIndex != -1) { @@ -150,30 +149,30 @@ void CNamePlates::RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pP TextRender()->RenderTextContainer(m_aNamePlates[ClientID].m_ClanNameTextContainerIndex, &TColor, &TOutlineColor, Position.x - m_aNamePlates[ClientID].m_ClanNameTextWidth / 2.0f, YOffset); } - if (g_Config.m_ClNameplatesFriendMark && m_pClient->m_aClients[ClientID].m_Friend) + if(g_Config.m_ClNameplatesFriendMark && m_pClient->m_aClients[ClientID].m_Friend) { YOffset -= FontSize; - char aFriendMark[] = "♥"; + char aFriendMark[] = "♥"; TextRender()->TextColor(ColorRGBA(1.0f, 0.0f, 0.0f)); - float XOffSet = TextRender()->TextWidth(0, FontSize, aFriendMark, -1, -1.0f)/2.0f; - TextRender()->Text(0, Position.x-XOffSet, YOffset, FontSize, aFriendMark, -1.0f); + float XOffSet = TextRender()->TextWidth(0, FontSize, aFriendMark, -1, -1.0f) / 2.0f; + TextRender()->Text(0, Position.x - XOffSet, YOffset, FontSize, aFriendMark, -1.0f); } if(g_Config.m_Debug || g_Config.m_ClNameplatesIDs) // render client id when in debug as well { YOffset -= FontSize; char aBuf[128]; - str_format(aBuf, sizeof(aBuf),"%d", pPlayerInfo->m_ClientID); - float XOffset = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f)/2.0f; + str_format(aBuf, sizeof(aBuf), "%d", pPlayerInfo->m_ClientID); + float XOffset = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f) / 2.0f; TextRender()->TextColor(rgb); - TextRender()->Text(0, Position.x-XOffset, YOffset, FontSize, aBuf, -1.0f); + TextRender()->Text(0, Position.x - XOffset, YOffset, FontSize, aBuf, -1.0f); } if(g_Config.m_ClNameplatesHA) // render health and armor in nameplate { int Health = m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_Health; int Armor = m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_Armor; - + if(Health > 0 || Armor > 0) { float HFontSize = 5.0f + 20.0f * g_Config.m_ClNameplatesHASize / 100.0f; @@ -191,20 +190,19 @@ void CNamePlates::RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pP str_append(aArmor, "⚪", sizeof(aArmor)); str_append(aArmor, "\0", sizeof(aArmor)); - - YOffset -= HFontSize+AFontSize; + YOffset -= HFontSize + AFontSize; float PosHealth = TextRender()->TextWidth(0, HFontSize, aHealth, -1, -1.0f); TextRender()->TextColor(ColorRGBA(1.0f, 0.0f, 0.0f)); - TextRender()->Text(0, Position.x-PosHealth/2.0f, YOffset, HFontSize, aHealth, -1); + TextRender()->Text(0, Position.x - PosHealth / 2.0f, YOffset, HFontSize, aHealth, -1); - YOffset -= -AFontSize+3.0f; + YOffset -= -AFontSize + 3.0f; float PosArmor = TextRender()->TextWidth(0, AFontSize, aArmor, -1, -1.0f); TextRender()->TextColor(ColorRGBA(1.0f, 1.0f, 0.0f)); - TextRender()->Text(0, Position.x-PosArmor/2.0f, YOffset, AFontSize, aArmor, -1); + TextRender()->Text(0, Position.x - PosArmor / 2.0f, YOffset, AFontSize, aArmor, -1); } } - TextRender()->TextColor(1,1,1,1); + TextRender()->TextColor(1, 1, 1, 1); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); TextRender()->SetRenderFlags(0); @@ -243,7 +241,7 @@ void CNamePlates::OnRender() } } -void CNamePlates::SetPlayers(CPlayers* pPlayers) +void CNamePlates::SetPlayers(CPlayers *pPlayers) { m_pPlayers = pPlayers; } @@ -259,7 +257,6 @@ void CNamePlates::ResetNamePlates() m_aNamePlates[i].Reset(); } - } void CNamePlates::OnWindowResize() diff --git a/src/game/client/components/nameplates.h b/src/game/client/components/nameplates.h index 93eb6d03e..35529922e 100644 --- a/src/game/client/components/nameplates.h +++ b/src/game/client/components/nameplates.h @@ -37,20 +37,20 @@ class CNamePlates : public CComponent void RenderNameplate( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, - const CNetObj_PlayerInfo *pPlayerInfo - ); + const CNetObj_PlayerInfo *pPlayerInfo); void RenderNameplatePos(vec2 Position, const CNetObj_PlayerInfo *pPlayerInfo, float Alpha); SPlayerNamePlate m_aNamePlates[MAX_CLIENTS]; - class CPlayers* m_pPlayers; - + class CPlayers *m_pPlayers; + void ResetNamePlates(); + public: virtual void OnWindowResize(); virtual void OnInit(); virtual void OnRender(); - void SetPlayers(class CPlayers* pPlayers); + void SetPlayers(class CPlayers *pPlayers); }; #endif diff --git a/src/game/client/components/particles.cpp b/src/game/client/components/particles.cpp index f92c04a26..7045279fc 100644 --- a/src/game/client/components/particles.cpp +++ b/src/game/client/components/particles.cpp @@ -1,13 +1,13 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include #include +#include -#include +#include "particles.h" #include #include -#include "particles.h" +#include CParticles::CParticles() { @@ -17,18 +17,17 @@ CParticles::CParticles() m_RenderGeneral.m_pParts = this; } - void CParticles::OnReset() { // reset particles for(int i = 0; i < MAX_PARTICLES; i++) { - m_aParticles[i].m_PrevPart = i-1; - m_aParticles[i].m_NextPart = i+1; + m_aParticles[i].m_PrevPart = i - 1; + m_aParticles[i].m_NextPart = i + 1; } m_aParticles[0].m_PrevPart = 0; - m_aParticles[MAX_PARTICLES-1].m_NextPart = -1; + m_aParticles[MAX_PARTICLES - 1].m_NextPart = -1; m_FirstFree = 0; for(int i = 0; i < NUM_GROUPS; i++) @@ -45,7 +44,7 @@ void CParticles::Add(int Group, CParticle *pPart, float TimePassed) } else { - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) return; } @@ -97,15 +96,15 @@ void CParticles::Update(float TimePassed) { int Next = m_aParticles[i].m_NextPart; //m_aParticles[i].vel += flow_get(m_aParticles[i].pos)*time_passed * m_aParticles[i].flow_affected; - m_aParticles[i].m_Vel.y += m_aParticles[i].m_Gravity*TimePassed; + m_aParticles[i].m_Vel.y += m_aParticles[i].m_Gravity * TimePassed; for(int f = 0; f < FrictionCount; f++) // apply friction m_aParticles[i].m_Vel *= m_aParticles[i].m_Friction; // move the point - vec2 Vel = m_aParticles[i].m_Vel*TimePassed; - Collision()->MovePoint(&m_aParticles[i].m_Pos, &Vel, 0.1f+0.9f*frandom(), NULL); - m_aParticles[i].m_Vel = Vel* (1.0f/TimePassed); + vec2 Vel = m_aParticles[i].m_Vel * TimePassed; + Collision()->MovePoint(&m_aParticles[i].m_Pos, &Vel, 0.1f + 0.9f * frandom(), NULL); + m_aParticles[i].m_Vel = Vel * (1.0f / TimePassed); m_aParticles[i].m_Life += TimePassed; m_aParticles[i].m_Rot += TimePassed * m_aParticles[i].m_Rotspeed; @@ -148,12 +147,12 @@ void CParticles::OnRender() { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) - Update((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed); + Update((float)((t - LastTime) / (double)time_freq()) * pInfo->m_Speed); } else { - if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) - Update((float)((t-LastTime)/(double)time_freq())); + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) + Update((float)((t - LastTime) / (double)time_freq())); } LastTime = t; @@ -176,7 +175,7 @@ void CParticles::OnInit() void CParticles::RenderGroup(int Group) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); - + // don't use the buffer methods here, else the old renderer gets many draw calls if(Graphics()->IsQuadContainerBufferingEnabled()) { @@ -205,14 +204,14 @@ void CParticles::RenderGroup(int Group) LastQuadOffset = m_aParticles[i].m_Spr; } - + while(i != -1) { int QuadOffset = m_aParticles[i].m_Spr; float a = m_aParticles[i].m_Life / m_aParticles[i].m_LifeSpan; vec2 p = m_aParticles[i].m_Pos; float Size = mix(m_aParticles[i].m_StartSize, m_aParticles[i].m_EndSize, a); - + if(LastColor[0] != m_aParticles[i].m_Color.r || LastColor[1] != m_aParticles[i].m_Color.g || LastColor[2] != m_aParticles[i].m_Color.b || LastColor[3] != m_aParticles[i].m_Color.a || LastQuadOffset != QuadOffset) { Graphics()->RenderQuadContainerAsSpriteMultiple(m_ParticleQuadContainerIndex, LastQuadOffset, CurParticleRenderCount, s_aParticleRenderInfo); @@ -236,14 +235,13 @@ void CParticles::RenderGroup(int Group) s_aParticleRenderInfo[CurParticleRenderCount].m_Scale = Size; s_aParticleRenderInfo[CurParticleRenderCount].m_Rotation = m_aParticles[i].m_Rot; - - ++CurParticleRenderCount; + + ++CurParticleRenderCount; i = m_aParticles[i].m_NextPart; } Graphics()->RenderQuadContainerAsSpriteMultiple(m_ParticleQuadContainerIndex, LastQuadOffset, CurParticleRenderCount, s_aParticleRenderInfo); - } else { diff --git a/src/game/client/components/particles.h b/src/game/client/components/particles.h index b20a6013d..df76b1806 100644 --- a/src/game/client/components/particles.h +++ b/src/game/client/components/particles.h @@ -10,7 +10,7 @@ struct CParticle { void SetDefault() { - m_Vel = vec2(0,0); + m_Vel = vec2(0, 0); m_LifeSpan = 0; m_StartSize = 32; m_EndSize = 32; @@ -19,7 +19,7 @@ struct CParticle m_Gravity = 0; m_Friction = 0; m_FlowAffected = 1.0f; - m_Color = ColorRGBA(1,1,1,1); + m_Color = ColorRGBA(1, 1, 1, 1); } vec2 m_Pos; @@ -51,10 +51,11 @@ struct CParticle class CParticles : public CComponent { friend class CGameClient; + public: enum { - GROUP_PROJECTILE_TRAIL=0, + GROUP_PROJECTILE_TRAIL = 0, GROUP_EXPLOSIONS, GROUP_GENERAL, NUM_GROUPS @@ -67,12 +68,13 @@ public: virtual void OnReset(); virtual void OnRender(); virtual void OnInit(); + private: int m_ParticleQuadContainerIndex; enum { - MAX_PARTICLES=1024*8, + MAX_PARTICLES = 1024 * 8, }; CParticle m_aParticles[MAX_PARTICLES]; diff --git a/src/game/client/components/players.cpp b/src/game/client/components/players.cpp index 3bb6aa19e..2bf8f30a8 100644 --- a/src/game/client/components/players.cpp +++ b/src/game/client/components/players.cpp @@ -6,22 +6,22 @@ #include #include #include -#include #include -#include +#include #include +#include -#include // get_angle #include #include -#include #include +#include +#include // get_angle +#include +#include #include #include -#include #include -#include #include @@ -37,7 +37,7 @@ void CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float Angle += AngleOffset; vec2 DirX = Dir; - vec2 DirY(-Dir.y,Dir.x); + vec2 DirY(-Dir.y, Dir.x); if(Dir.x < 0) DirY = -DirY; @@ -56,22 +56,21 @@ void CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float Graphics()->QuadsSetRotation(Angle); Graphics()->RenderQuadContainerAsSprite(m_WeaponEmoteQuadContainerIndex, QuadOffset, HandPos.x, HandPos.y); } - } inline float NormalizeAngular(float f) { - return fmod(f+pi*2, pi*2); + return fmod(f + pi * 2, pi * 2); } -inline float AngularMixDirection (float Src, float Dst) { return sinf(Dst-Src) >0?1:-1; } -inline float AngularDistance(float Src, float Dst) { return asinf(sinf(Dst-Src)); } +inline float AngularMixDirection(float Src, float Dst) { return sinf(Dst - Src) > 0 ? 1 : -1; } +inline float AngularDistance(float Src, float Dst) { return asinf(sinf(Dst - Src)); } inline float AngularApproach(float Src, float Dst, float Amount) { - float d = AngularMixDirection (Src, Dst); - float n = Src + Amount*d; - if(AngularMixDirection (n, Dst) != d) + float d = AngularMixDirection(Src, Dst); + float n = Src + Amount * d; + if(AngularMixDirection(n, Dst) != d) return Dst; return n; } @@ -81,8 +80,7 @@ void CPlayers::RenderHook( const CNetObj_Character *pPlayerChar, const CTeeRenderInfo *pRenderInfo, int ClientID, - float Intra - ) + float Intra) { CNetObj_Character Prev; CNetObj_Character Player; @@ -104,13 +102,13 @@ void CPlayers::RenderHook( RenderInfo.m_Size = 64.0f; vec2 Position; - if(in_range(ClientID, MAX_CLIENTS-1)) + if(in_range(ClientID, MAX_CLIENTS - 1)) Position = m_pClient->m_aClients[ClientID].m_RenderPos; else Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); - + // draw hook - if(Prev.m_HookState>0 && Player.m_HookState>0) + if(Prev.m_HookState > 0 && Player.m_HookState > 0) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); @@ -121,16 +119,15 @@ void CPlayers::RenderHook( vec2 Pos = Position; vec2 HookPos; - if(in_range(pPlayerChar->m_HookedPlayer, MAX_CLIENTS-1)) + if(in_range(pPlayerChar->m_HookedPlayer, MAX_CLIENTS - 1)) HookPos = m_pClient->m_aClients[pPlayerChar->m_HookedPlayer].m_RenderPos; else HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick); - float d = distance(Pos, HookPos); - vec2 Dir = normalize(Pos-HookPos); + vec2 Dir = normalize(Pos - HookPos); - Graphics()->QuadsSetRotation(GetAngle(Dir)+pi); + Graphics()->QuadsSetRotation(GetAngle(Dir) + pi); // render head int QuadOffset = NUM_WEAPONS * 2 + 2; if(OtherTeam) @@ -143,7 +140,7 @@ void CPlayers::RenderHook( int HookChainCount = 0; for(float f = 24; f < d && HookChainCount < 1024; f += 24, ++HookChainCount) { - vec2 p = HookPos + Dir*f; + vec2 p = HookPos + Dir * f; s_HookChainRenderInfo[HookChainCount].m_Pos[0] = p.x; s_HookChainRenderInfo[HookChainCount].m_Pos[1] = p.y; @@ -156,7 +153,7 @@ void CPlayers::RenderHook( Graphics()->QuadsSetRotation(0); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); - RenderHand(&RenderInfo, Position, normalize(HookPos-Pos), -pi/2, vec2(20, 0), OtherTeam ? g_Config.m_ClShowOthersAlpha / 100.0f : 1.0f); + RenderHand(&RenderInfo, Position, normalize(HookPos - Pos), -pi / 2, vec2(20, 0), OtherTeam ? g_Config.m_ClShowOthersAlpha / 100.0f : 1.0f); } } @@ -165,8 +162,7 @@ void CPlayers::RenderPlayer( const CNetObj_Character *pPlayerChar, const CTeeRenderInfo *pRenderInfo, int ClientID, - float Intra - ) + float Intra) { CNetObj_Character Prev; CNetObj_Character Player; @@ -188,7 +184,7 @@ void CPlayers::RenderPlayer( static float s_LastGameTickTime = Client()->GameTickTime(g_Config.m_ClDummy); static float s_LastPredIntraTick = Client()->PredIntraGameTick(g_Config.m_ClDummy); - if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED)) { s_LastGameTickTime = Client()->GameTickTime(g_Config.m_ClDummy); s_LastPredIntraTick = Client()->PredIntraGameTick(g_Config.m_ClDummy); @@ -203,7 +199,7 @@ void CPlayers::RenderPlayer( AttackTime = (Client()->PredIntraGameTick(g_Config.m_ClDummy) + (Client()->PredGameTick(g_Config.m_ClDummy) - 1 - Player.m_AttackTick)) / (float)SERVER_TICK_SPEED; LastAttackTime = (s_LastPredIntraTick + (Client()->PredGameTick(g_Config.m_ClDummy) - 1 - Player.m_AttackTick)) / (float)SERVER_TICK_SPEED; } - float AttackTicksPassed = AttackTime*SERVER_TICK_SPEED; + float AttackTicksPassed = AttackTime * SERVER_TICK_SPEED; float Angle; if(Local && Client()->State() != IClient::STATE_DEMOPLAYBACK) @@ -225,28 +221,28 @@ void CPlayers::RenderPlayer( else if(Player.m_Angle < 0 && Prev.m_Angle > (256.0f * pi)) Player.m_Angle += 256.0f * 2 * pi; - Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, AngleIntraTick)/256.0f; + Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, AngleIntraTick) / 256.0f; } - vec2 Direction = GetDirection((int)(Angle*256.0f)); + vec2 Direction = GetDirection((int)(Angle * 256.0f)); vec2 Position; - if(in_range(ClientID, MAX_CLIENTS-1)) + if(in_range(ClientID, MAX_CLIENTS - 1)) Position = m_pClient->m_aClients[ClientID].m_RenderPos; else Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); - - vec2 Vel = mix(vec2(Prev.m_VelX/256.0f, Prev.m_VelY/256.0f), vec2(Player.m_VelX/256.0f, Player.m_VelY/256.0f), IntraTick); - m_pClient->m_pFlow->Add(Position, Vel*100.0f, 10.0f); + vec2 Vel = mix(vec2(Prev.m_VelX / 256.0f, Prev.m_VelY / 256.0f), vec2(Player.m_VelX / 256.0f, Player.m_VelY / 256.0f), IntraTick); - RenderInfo.m_GotAirJump = Player.m_Jumped&2?0:1; + m_pClient->m_pFlow->Add(Position, Vel * 100.0f, 10.0f); + + RenderInfo.m_GotAirJump = Player.m_Jumped & 2 ? 0 : 1; bool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1; - bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16); + bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y + 16); bool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0); // evaluate animation - float WalkTime = fmod(absolute(Position.x), 100.0f)/100.0f; + float WalkTime = fmod(absolute(Position.x), 100.0f) / 100.0f; CAnimState State; State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); @@ -258,15 +254,15 @@ void CPlayers::RenderPlayer( State.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f); if(Player.m_Weapon == WEAPON_HAMMER) - State.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(LastAttackTime*5.0f,0.0f,1.0f), 1.0f); + State.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(LastAttackTime * 5.0f, 0.0f, 1.0f), 1.0f); if(Player.m_Weapon == WEAPON_NINJA) - State.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(LastAttackTime*2.0f,0.0f,1.0f), 1.0f); + State.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(LastAttackTime * 2.0f, 0.0f, 1.0f), 1.0f); // do skidding - if(!InAir && WantOtherDir && length(Vel*50) > 500.0f) + if(!InAir && WantOtherDir && length(Vel * 50) > 500.0f) { static int64 SkidSoundTime = 0; - if(time()-SkidSoundTime > time_freq()/10) + if(time() - SkidSoundTime > time_freq() / 10) { if(g_Config.m_SndGame) m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position); @@ -274,9 +270,8 @@ void CPlayers::RenderPlayer( } m_pClient->m_pEffects->SkidTrail( - Position+vec2(-Player.m_Direction*6,12), - vec2(-Player.m_Direction*100*length(Vel),-50) - ); + Position + vec2(-Player.m_Direction * 6, 12), + vec2(-Player.m_Direction * 100 * length(Vel), -50)); } // draw gun @@ -296,7 +291,7 @@ void CPlayers::RenderPlayer( Graphics()->TextureClear(); vec2 InitPos = Position; - vec2 FinishPos = InitPos + ExDirection * (m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength-42.0f); + vec2 FinishPos = InitPos + ExDirection * (m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength - 42.0f); Graphics()->LinesBegin(); ColorRGBA HookCollColor(1.0f, 0.0f, 0.0f); @@ -309,13 +304,14 @@ void CPlayers::RenderPlayer( bool DoBreak = false; int Hit = 0; - do { + do + { OldPos = NewPos; NewPos = OldPos + ExDirection * m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookFireSpeed; if(distance(InitPos, NewPos) > m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength) { - NewPos = InitPos + normalize(NewPos-InitPos) * m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength; + NewPos = InitPos + normalize(NewPos - InitPos) * m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength; DoBreak = true; } @@ -326,7 +322,7 @@ void CPlayers::RenderPlayer( { if(Hit != TILE_NOHOOK) { - HookCollColor = ColorRGBA(130.0f/255.0f, 232.0f/255.0f, 160.0f/255.0f); + HookCollColor = ColorRGBA(130.0f / 255.0f, 232.0f / 255.0f, 160.0f / 255.0f); } } @@ -345,9 +341,9 @@ void CPlayers::RenderPlayer( if(OldPos == NewPos) break; - ExDirection.x = round_to_int(ExDirection.x*256.0f) / 256.0f; - ExDirection.y = round_to_int(ExDirection.y*256.0f) / 256.0f; - } while (!DoBreak); + ExDirection.x = round_to_int(ExDirection.x * 256.0f) / 256.0f; + ExDirection.y = round_to_int(ExDirection.y * 256.0f) / 256.0f; + } while(!DoBreak); if(AlwaysRenderHookColl && RenderHookCollPlayer) { @@ -362,13 +358,13 @@ void CPlayers::RenderPlayer( Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); - Graphics()->QuadsSetRotation(State.GetAttach()->m_Angle*pi*2+Angle); + Graphics()->QuadsSetRotation(State.GetAttach()->m_Angle * pi * 2 + Angle); if(ClientID < 0) Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); // normal weapons - int iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS-1); + int iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS - 1); int QuadOffset = iw * 2 + (Direction.x < 0 ? 1 : 0); Graphics()->SetColor(1.0f, 1.0f, 1.0f, Alpha); @@ -384,12 +380,12 @@ void CPlayers::RenderPlayer( // if attack is under way, bash stuffs if(Direction.x < 0) { - Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); + Graphics()->QuadsSetRotation(-pi / 2 - State.GetAttach()->m_Angle * pi * 2); p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; } else { - Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); + Graphics()->QuadsSetRotation(-pi / 2 + State.GetAttach()->m_Angle * pi * 2); } Graphics()->RenderQuadContainerAsSprite(m_WeaponEmoteQuadContainerIndex, QuadOffset, p.x, p.y); } @@ -400,19 +396,19 @@ void CPlayers::RenderPlayer( if(Direction.x < 0) { - Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); + Graphics()->QuadsSetRotation(-pi / 2 - State.GetAttach()->m_Angle * pi * 2); p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; - m_pClient->m_pEffects->PowerupShine(p+vec2(32,0), vec2(32,12)); + m_pClient->m_pEffects->PowerupShine(p + vec2(32, 0), vec2(32, 12)); } else { - Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); - m_pClient->m_pEffects->PowerupShine(p-vec2(32,0), vec2(32,12)); + Graphics()->QuadsSetRotation(-pi / 2 + State.GetAttach()->m_Angle * pi * 2); + m_pClient->m_pEffects->PowerupShine(p - vec2(32, 0), vec2(32, 12)); } Graphics()->RenderQuadContainerAsSprite(m_WeaponEmoteQuadContainerIndex, QuadOffset, p.x, p.y); // HADOKEN - if(AttackTime <= 1/6.f && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles) + if(AttackTime <= 1 / 6.f && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles) { int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; static int s_LastIteX = IteX; @@ -426,7 +422,7 @@ void CPlayers::RenderPlayer( } else { - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) IteX = s_LastIteX; else s_LastIteX = IteX; @@ -435,14 +431,14 @@ void CPlayers::RenderPlayer( { vec2 Dir; if(PredictLocalWeapons) - Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y); + Dir = vec2(pPlayerChar->m_X, pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y); else Dir = vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_Y) - vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_Y); Dir = normalize(Dir); float HadOkenAngle = GetAngle(Dir); Graphics()->QuadsSetRotation(HadOkenAngle); int QuadOffset = IteX * 2; - vec2 DirY(-Dir.y,Dir.x); + vec2 DirY(-Dir.y, Dir.x); p = Position; float OffsetX = g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx; p -= Dir * OffsetX; @@ -454,10 +450,10 @@ void CPlayers::RenderPlayer( { // TODO: should be an animation Recoil = 0; - float a = AttackTicksPassed/5.0f; + float a = AttackTicksPassed / 5.0f; if(a < 1) - Recoil = sinf(a*pi); - p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir*Recoil*10.0f; + Recoil = sinf(a * pi); + p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir * Recoil * 10.0f; p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; if(Player.m_Weapon == WEAPON_GUN && g_Config.m_ClOldGunPosition) p.y -= 8; @@ -467,13 +463,13 @@ void CPlayers::RenderPlayer( if(Player.m_Weapon == WEAPON_GUN || Player.m_Weapon == WEAPON_SHOTGUN) { // check if we're firing stuff - if(g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)//prev.attackticks) + if(g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles) //prev.attackticks) { float Alpha = 0.0f; if(AttackTicksPassed < g_pData->m_Weapons.m_aId[iw].m_Muzzleduration + 3) { - float t = AttackTicksPassed/g_pData->m_Weapons.m_aId[iw].m_Muzzleduration; - Alpha = mix(2.0f, 0.0f, minimum(1.0f,maximum(0.0f,t))); + float t = AttackTicksPassed / g_pData->m_Weapons.m_aId[iw].m_Muzzleduration; + Alpha = mix(2.0f, 0.0f, minimum(1.0f, maximum(0.0f, t))); } int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; @@ -488,7 +484,7 @@ void CPlayers::RenderPlayer( } else { - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) IteX = s_LastIteX; else s_LastIteX = IteX; @@ -500,7 +496,7 @@ void CPlayers::RenderPlayer( if(Direction.x < 0) OffsetY = -OffsetY; - vec2 DirY(-Dir.y,Dir.x); + vec2 DirY(-Dir.y, Dir.x); vec2 MuzzlePos = p + Dir * g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx + DirY * OffsetY; Graphics()->RenderQuadContainerAsSprite(m_WeaponSpriteMuzzleQuadContainerIndex[iw], QuadOffset, MuzzlePos.x, MuzzlePos.y); } @@ -509,13 +505,12 @@ void CPlayers::RenderPlayer( Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); Graphics()->QuadsSetRotation(0); - switch (Player.m_Weapon) + switch(Player.m_Weapon) { - case WEAPON_GUN: RenderHand(&RenderInfo, p, Direction, -3*pi/4, vec2(-15, 4), Alpha); break; - case WEAPON_SHOTGUN: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-5, 4), Alpha); break; - case WEAPON_GRENADE: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-4, 7), Alpha); break; + case WEAPON_GUN: RenderHand(&RenderInfo, p, Direction, -3 * pi / 4, vec2(-15, 4), Alpha); break; + case WEAPON_SHOTGUN: RenderHand(&RenderInfo, p, Direction, -pi / 2, vec2(-5, 4), Alpha); break; + case WEAPON_GRENADE: RenderHand(&RenderInfo, p, Direction, -pi / 2, vec2(-4, 7), Alpha); break; } - } // render the "shadow" tee @@ -524,9 +519,9 @@ void CPlayers::RenderPlayer( vec2 GhostPosition = Position; if(ClientID >= 0) GhostPosition = mix( - vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_Y), - vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_Y), - Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Prev.m_Y), + vec2(m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_X, m_pClient->m_Snap.m_aCharacters[ClientID].m_Cur.m_Y), + Client()->IntraGameTick(g_Config.m_ClDummy)); CTeeRenderInfo Ghost = RenderInfo; RenderTools()->RenderTee(&State, &Ghost, Player.m_Emote, Direction, GhostPosition, 0.5f); // render ghost @@ -537,7 +532,7 @@ void CPlayers::RenderPlayer( Graphics()->SetColor(1.0f, 1.0f, 1.0f, Alpha); Graphics()->QuadsSetRotation(0); #if defined(CONF_VIDEORECORDER) - if(((!IVideo::Current()&&g_Config.m_ClShowDirection)||(IVideo::Current()&&g_Config.m_ClVideoShowDirection)) && ClientID >= 0 && (!Local || DemoPlayer()->IsPlaying())) + if(((!IVideo::Current() && g_Config.m_ClShowDirection) || (IVideo::Current() && g_Config.m_ClVideoShowDirection)) && ClientID >= 0 && (!Local || DemoPlayer()->IsPlaying())) #else if(g_Config.m_ClShowDirection && ClientID >= 0 && (!Local || DemoPlayer()->IsPlaying())) #endif @@ -553,7 +548,7 @@ void CPlayers::RenderPlayer( Graphics()->TextureSet(g_pData->m_aImages[IMAGE_ARROW].m_Id); Graphics()->RenderQuadContainerAsSprite(m_DirectionQuadContainerIndex, 0, Position.x + 30.f, Position.y - 70.f); } - if(Player.m_Jumped&1) + if(Player.m_Jumped & 1) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_ARROW].m_Id); Graphics()->QuadsSetRotation(pi * 3 / 2); @@ -569,7 +564,7 @@ void CPlayers::RenderPlayer( RenderTools()->RenderTee(&State, &RenderInfo, Player.m_Emote, Direction, Position); int QuadOffsetToEmoticon = NUM_WEAPONS * 2 + 2 + 2; - if(Player.m_PlayerFlags&PLAYERFLAG_CHATTING) + if(Player.m_PlayerFlags & PLAYERFLAG_CHATTING) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); int QuadOffset = QuadOffsetToEmoticon + (SPRITE_DOTDOT - SPRITE_OOP); @@ -583,7 +578,7 @@ void CPlayers::RenderPlayer( if(ClientID < 0) return; - if(g_Config.m_ClAfkEmote && m_pClient->m_aClients[ClientID].m_Afk && !(Player.m_PlayerFlags&PLAYERFLAG_CHATTING) && !(Client()->DummyConnected() && ClientID == m_pClient->m_LocalIDs[!g_Config.m_ClDummy])) + if(g_Config.m_ClAfkEmote && m_pClient->m_aClients[ClientID].m_Afk && !(Player.m_PlayerFlags & PLAYERFLAG_CHATTING) && !(Client()->DummyConnected() && ClientID == m_pClient->m_LocalIDs[!g_Config.m_ClDummy])) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); int QuadOffset = QuadOffsetToEmoticon + (SPRITE_ZZZ - SPRITE_OOP); @@ -614,14 +609,14 @@ void CPlayers::RenderPlayer( if(SinceStart < Client()->GameTickSpeed() / 5) Wiggle = SinceStart / (Client()->GameTickSpeed() / 5.0f); - float WiggleAngle = sinf(5*Wiggle); + float WiggleAngle = sinf(5 * Wiggle); - Graphics()->QuadsSetRotation(pi/6*WiggleAngle); + Graphics()->QuadsSetRotation(pi / 6 * WiggleAngle); - Graphics()->SetColor(1.0f,1.0f,1.0f,a * Alpha); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, a * Alpha); // client_datas::emoticon is an offset from the first emoticon int QuadOffset = QuadOffsetToEmoticon + m_pClient->m_aClients[ClientID].m_Emoticon; - Graphics()->RenderQuadContainerAsSprite(m_WeaponEmoteQuadContainerIndex, QuadOffset, Position.x, Position.y - 23.f - 32.f * h, 1.f, (64.f*h) / 64.f); + Graphics()->RenderQuadContainerAsSprite(m_WeaponEmoteQuadContainerIndex, QuadOffset, Position.x, Position.y - 23.f - 32.f * h, 1.f, (64.f * h) / 64.f); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); Graphics()->QuadsSetRotation(0); @@ -633,7 +628,7 @@ void CPlayers::OnRender() // update RenderInfo for ninja bool IsTeamplay = false; if(m_pClient->m_Snap.m_pGameInfoObj) - IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0; + IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) != 0; for(int i = 0; i < MAX_CLIENTS; ++i) { m_aRenderInfo[i] = m_pClient->m_aClients[i].m_RenderInfo; @@ -648,8 +643,8 @@ void CPlayers::OnRender() else { m_aRenderInfo[i].m_Texture = m_pClient->m_pSkins->Get(Skin)->m_OrgTexture; - m_aRenderInfo[i].m_ColorBody = ColorRGBA(1,1,1); - m_aRenderInfo[i].m_ColorFeet = ColorRGBA(1,1,1); + m_aRenderInfo[i].m_ColorBody = ColorRGBA(1, 1, 1); + m_aRenderInfo[i].m_ColorFeet = ColorRGBA(1, 1, 1); } } } @@ -690,13 +685,15 @@ void CPlayers::OnRender() } bool Local = m_pClient->m_Snap.m_LocalClientID == i; - if((p % 3) == 1 && Local) continue; - if((p % 3) == 2 && !Local) continue; + if((p % 3) == 1 && Local) + continue; + if((p % 3) == 2 && !Local) + continue; CNetObj_Character PrevChar = m_pClient->m_aClients[i].m_RenderPrev; CNetObj_Character CurChar = m_pClient->m_aClients[i].m_RenderCur; - if(p<3) + if(p < 3) { RenderHook(&PrevChar, &CurChar, &m_aRenderInfo[i], i); } @@ -772,5 +769,4 @@ void CPlayers::OnInit() IGraphics::CQuadItem QuadItem(0.f, 0.f, 22.f, 22.f); Graphics()->QuadContainerAddQuads(m_DirectionQuadContainerIndex, &QuadItem, 1); - } diff --git a/src/game/client/components/players.h b/src/game/client/components/players.h index 4f35351dd..cd0e928e9 100644 --- a/src/game/client/components/players.h +++ b/src/game/client/components/players.h @@ -16,19 +16,18 @@ class CPlayers : public CComponent const CNetObj_Character *pPlayerChar, const CTeeRenderInfo *pRenderInfo, int ClientID, - float Intra = 0.f - ); + float Intra = 0.f); void RenderHook( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CTeeRenderInfo *pRenderInfo, int ClientID, - float Intra = 0.f - ); + float Intra = 0.f); int m_WeaponEmoteQuadContainerIndex; int m_DirectionQuadContainerIndex; int m_WeaponSpriteMuzzleQuadContainerIndex[NUM_WEAPONS]; + public: vec2 m_CurPredictedPos[MAX_CLIENTS]; virtual void OnInit(); diff --git a/src/game/client/components/race_demo.cpp b/src/game/client/components/race_demo.cpp index 626cb4a78..94b5ad188 100644 --- a/src/game/client/components/race_demo.cpp +++ b/src/game/client/components/race_demo.cpp @@ -3,8 +3,8 @@ #include #include -#include #include +#include #include #include @@ -26,7 +26,8 @@ struct CDemoListParam const char *pMap; }; -CRaceDemo::CRaceDemo() : m_RaceState(RACE_NONE), m_RaceStartTick(-1), m_RecordStopTick(-1), m_Time(0) {} +CRaceDemo::CRaceDemo() : + m_RaceState(RACE_NONE), m_RaceStartTick(-1), m_RecordStopTick(-1), m_Time(0) {} void CRaceDemo::GetPath(char *pBuf, int Size, int Time) const { @@ -60,7 +61,7 @@ void CRaceDemo::OnNewSnapshot() static int s_LastRaceTick = -1; - bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_RACETIME; + bool RaceFlag = m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_RACETIME; bool ServerControl = RaceFlag && g_Config.m_ClRaceRecordServerControl; int RaceTick = -m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer; @@ -174,7 +175,7 @@ void CRaceDemo::StopRecord(int Time) int CRaceDemo::RaceDemolistFetchCallback(const char *pName, time_t Date, int IsDir, int StorageType, void *pUser) { - CDemoListParam *pParam = (CDemoListParam*) pUser; + CDemoListParam *pParam = (CDemoListParam *)pUser; int Length = str_length(pName); int MapLen = str_length(pParam->pMap); if(IsDir || !str_endswith(pName, ".demo") || !str_startswith(pName, pParam->pMap) || pName[MapLen] != '_') @@ -210,7 +211,7 @@ int CRaceDemo::RaceDemolistFetchCallback(const char *pName, time_t Date, int IsD bool CRaceDemo::CheckDemo(int Time) const { std::vector lDemos; - CDemoListParam Param = { this, &lDemos, Client()->GetCurrentMap() }; + CDemoListParam Param = {this, &lDemos, Client()->GetCurrentMap()}; Storage()->ListDirectoryInfo(IStorage::TYPE_SAVE, ms_pRaceDemoDir, RaceDemolistFetchCallback, &Param); // loop through demo files diff --git a/src/game/client/components/scoreboard.cpp b/src/game/client/components/scoreboard.cpp index 511796890..5916b37fe 100644 --- a/src/game/client/components/scoreboard.cpp +++ b/src/game/client/components/scoreboard.cpp @@ -2,20 +2,20 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include #include -#include #include +#include #include #include -#include #include -#include -#include #include #include -#include #include +#include +#include +#include +#include #include "scoreboard.h" @@ -49,7 +49,7 @@ void CScoreboard::OnMessage(int MsgType, void *pRawMsg) if(MsgType == NETMSGTYPE_SV_RECORD) { CNetMsg_Sv_Record *pMsg = (CNetMsg_Sv_Record *)pRawMsg; - m_ServerRecord = (float)pMsg->m_ServerTimeBest/100; + m_ServerRecord = (float)pMsg->m_ServerTimeBest / 100; //m_PlayerRecord = (float)pMsg->m_PlayerTimeBest/100; } } @@ -66,7 +66,7 @@ void CScoreboard::RenderGoals(float x, float y, float w) Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.5f); + Graphics()->SetColor(0, 0, 0, 0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); Graphics()->QuadsEnd(); @@ -77,20 +77,20 @@ void CScoreboard::RenderGoals(float x, float y, float w) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Score limit"), m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit); - TextRender()->Text(0, x+10.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); + TextRender()->Text(0, x + 10.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); } if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), Localize("Time limit: %d min"), m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit); - TextRender()->Text(0, x+230.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); + TextRender()->Text(0, x + 230.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); } if(m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum && m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s %d/%d", Localize("Round"), m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent, m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum); float tw = TextRender()->TextWidth(0, 20.0f, aBuf, -1, -1.0f); - TextRender()->Text(0, x+w-tw-10.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); + TextRender()->Text(0, x + w - tw - 10.0f, y + (h - 20.f) / 2.f, 20.0f, aBuf, -1.0f); } } } @@ -103,21 +103,21 @@ void CScoreboard::RenderSpectators(float x, float y, float w) Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.5f); + Graphics()->SetColor(0, 0, 0, 0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); Graphics()->QuadsEnd(); // Headline y += 10.0f; - TextRender()->Text(0, x+10.0f, y + (30.f - 28.f) / 2.f, 28.0f, Localize("Spectators"), w-20.0f); + TextRender()->Text(0, x + 10.0f, y + (30.f - 28.f) / 2.f, 28.0f, Localize("Spectators"), w - 20.0f); // spectator names y += 30.0f; bool Multiple = false; CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, x+10.0f, y, 22.0f, TEXTFLAG_RENDER); - Cursor.m_LineWidth = w-20.0f; + TextRender()->SetCursor(&Cursor, x + 10.0f, y, 22.0f, TEXTFLAG_RENDER); + Cursor.m_LineWidth = w - 20.0f; Cursor.m_MaxLines = 4; for(int i = 0; i < MAX_CLIENTS; ++i) @@ -197,7 +197,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch float TitleFontsize = 40.0f; if(!pTitle) { - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) pTitle = Localize("Game over"); else { @@ -209,7 +209,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch } TextRender()->Text(0, x + 20.0f, y + (50.f - TitleFontsize) / 2.f, TitleFontsize, pTitle, -1.0f); - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { if(m_pClient->m_Snap.m_pGameDataObj) { @@ -234,9 +234,9 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch if(m_pClient->m_GameInfo.m_TimeScore && g_Config.m_ClDDRaceScoreBoard) { - if (m_ServerRecord > 0) + if(m_ServerRecord > 0) { - str_format(aBuf, sizeof(aBuf), "%02d:%02d", ((int)m_ServerRecord)/60, ((int)m_ServerRecord)%60); + str_format(aBuf, sizeof(aBuf), "%02d:%02d", ((int)m_ServerRecord) / 60, ((int)m_ServerRecord) % 60); } else aBuf[0] = 0; @@ -244,10 +244,10 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch float tw; - if (!lower16 && !lower32 && !lower24) + if(!lower16 && !lower32 && !lower24) { tw = TextRender()->TextWidth(0, TitleFontsize, aBuf, -1, -1.0f); - TextRender()->Text(0, x+w-tw-20.0f, y + (50.f - TitleFontsize) / 2.f, TitleFontsize, aBuf, -1.0f); + TextRender()->Text(0, x + w - tw - 20.0f, y + (50.f - TitleFontsize) / 2.f, TitleFontsize, aBuf, -1.0f); } // calculate measurements @@ -308,21 +308,21 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch TextRender()->Text(0, NameOffset, y + (HeadlineFontsize * 2.f - HeadlineFontsize) / 2.f, HeadlineFontsize, Localize("Name"), -1.0f); tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Clan"), -1, -1.0f); - TextRender()->Text(0, ClanOffset+ClanLength/2-tw/2, y + (HeadlineFontsize * 2.f - HeadlineFontsize) / 2.f, HeadlineFontsize, Localize("Clan"), -1.0f); + TextRender()->Text(0, ClanOffset + ClanLength / 2 - tw / 2, y + (HeadlineFontsize * 2.f - HeadlineFontsize) / 2.f, HeadlineFontsize, Localize("Clan"), -1.0f); tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Ping"), -1, -1.0f); - TextRender()->Text(0, PingOffset+PingLength-tw, y + (HeadlineFontsize * 2.f - HeadlineFontsize) / 2.f, HeadlineFontsize, Localize("Ping"), -1.0f); + TextRender()->Text(0, PingOffset + PingLength - tw, y + (HeadlineFontsize * 2.f - HeadlineFontsize) / 2.f, HeadlineFontsize, Localize("Ping"), -1.0f); // render player entries y += HeadlineFontsize * 2.0f; CTextCursor Cursor; int rendered = 0; - if (upper16) + if(upper16) rendered = -16; - if (upper32) + if(upper32) rendered = -32; - if (upper24) + if(upper24) rendered = -24; int OldDDTeam = -1; @@ -334,7 +334,8 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch if(!pInfo || pInfo->m_Team != Team) continue; - if (rendered++ < 0) continue; + if(rendered++ < 0) + continue; int DDTeam = m_pClient->m_Teams.Team(pInfo->m_ClientID); int NextDDTeam = 0; @@ -350,9 +351,9 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch break; } - if (OldDDTeam == -1) + if(OldDDTeam == -1) { - for (int j = i - 1; j >= 0; j--) + for(int j = i - 1; j >= 0; j--) { const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeamScore[j]; @@ -364,7 +365,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch } } - if (DDTeam != TEAM_FLOCK) + if(DDTeam != TEAM_FLOCK) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); @@ -373,30 +374,30 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch int Corners = 0; - if (OldDDTeam != DDTeam) + if(OldDDTeam != DDTeam) Corners |= CUI::CORNER_TL | CUI::CORNER_TR; - if (NextDDTeam != DDTeam) + if(NextDDTeam != DDTeam) Corners |= CUI::CORNER_BL | CUI::CORNER_BR; RenderTools()->DrawRoundRectExt(x - 10.0f, y, w, LineHeight + Spacing, RoundRadius, Corners); Graphics()->QuadsEnd(); - if (NextDDTeam != DDTeam) + if(NextDDTeam != DDTeam) { char aBuf[64]; if(m_pClient->m_Snap.m_aTeamSize[0] > 8) { - str_format(aBuf, sizeof(aBuf),"%d", DDTeam); - TextRender()->SetCursor(&Cursor, x - 10.0f, y + Spacing + FontSize - (FontSize/1.5f), FontSize/1.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); - Cursor.m_LineWidth = NameLength+3; + str_format(aBuf, sizeof(aBuf), "%d", DDTeam); + TextRender()->SetCursor(&Cursor, x - 10.0f, y + Spacing + FontSize - (FontSize / 1.5f), FontSize / 1.5f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NameLength + 3; } else { - str_format(aBuf, sizeof(aBuf),"Team %d", DDTeam); + str_format(aBuf, sizeof(aBuf), "Team %d", DDTeam); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->SetCursor(&Cursor, ScoreOffset+w/2.0f-tw/2.0f, y + LineHeight, FontSize/1.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); - Cursor.m_LineWidth = NameLength+3; + TextRender()->SetCursor(&Cursor, ScoreOffset + w / 2.0f - tw / 2.0f, y + LineHeight, FontSize / 1.5f, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NameLength + 3; } TextRender()->TextEx(&Cursor, aBuf, -1); } @@ -410,14 +411,14 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); - RenderTools()->DrawRoundRect(x, y, w-20.0f, LineHeight, RoundRadius); + RenderTools()->DrawRoundRect(x, y, w - 20.0f, LineHeight, RoundRadius); Graphics()->QuadsEnd(); } // score if(m_pClient->m_GameInfo.m_TimeScore && g_Config.m_ClDDRaceScoreBoard) { - if (pInfo->m_Score == -9999) + if(pInfo->m_Score == -9999) aBuf[0] = 0; else { @@ -431,13 +432,12 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch else str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Score, -999, 99999)); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->SetCursor(&Cursor, ScoreOffset+ScoreLength-tw, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER); + TextRender()->SetCursor(&Cursor, ScoreOffset + ScoreLength - tw, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER); TextRender()->TextEx(&Cursor, aBuf, -1); // flag - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS && - m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == pInfo->m_ClientID || - m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == pInfo->m_ClientID)) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_FLAGS && + m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == pInfo->m_ClientID || m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == pInfo->m_ClientID)) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); @@ -446,7 +446,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch RenderTools()->SelectSprite(m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == pInfo->m_ClientID ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = LineHeight; - IGraphics::CQuadItem QuadItem(TeeOffset+0.0f, y-5.0f-Spacing/2.0f, Size/2.0f, Size); + IGraphics::CQuadItem QuadItem(TeeOffset + 0.0f, y - 5.0f - Spacing / 2.0f, Size / 2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } @@ -454,10 +454,10 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch // avatar CTeeRenderInfo TeeInfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo; TeeInfo.m_Size *= TeeSizeMod; - RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset+TeeLength/2, y+LineHeight/2)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset + TeeLength / 2, y + LineHeight / 2)); // name - TextRender()->SetCursor(&Cursor, NameOffset, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, NameOffset, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); if(m_pClient->m_aClients[pInfo->m_ClientID].m_AuthLevel) { ColorRGBA Color = color_cast(ColorHSLA(g_Config.m_ClAuthedPlayerColor)); @@ -479,7 +479,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch // clan if(str_comp(m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, - m_pClient->m_aClients[GameClient()->m_LocalIDs[g_Config.m_ClDummy]].m_aClan) == 0) + m_pClient->m_aClients[GameClient()->m_LocalIDs[g_Config.m_ClDummy]].m_aClan) == 0) { ColorRGBA Color = color_cast(ColorHSLA(g_Config.m_ClSameClanColor)); TextRender()->TextColor(Color); @@ -488,7 +488,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); tw = TextRender()->TextWidth(nullptr, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1, -1.0f); - TextRender()->SetCursor(&Cursor, ClanOffset + ClanLength / 2 - tw / 2, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, ClanOffset + ClanLength / 2 - tw / 2, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = ClanLength; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1); @@ -497,7 +497,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch // country flag ColorRGBA Color(1.0f, 1.0f, 1.0f, 0.5f); m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color, - CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f); + CountryOffset, y + (Spacing + TeeSizeMod * 5.0f) / 2.0f, CountryLength, LineHeight - Spacing - TeeSizeMod * 5.0f); // ping if(g_Config.m_ClEnablePingColor) @@ -507,19 +507,27 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch } str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Latency, 0, 999)); tw = TextRender()->TextWidth(nullptr, FontSize, aBuf, -1, -1.0f); - TextRender()->SetCursor(&Cursor, PingOffset+PingLength-tw, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, PingOffset + PingLength - tw, y + (LineHeight - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = PingLength; TextRender()->TextEx(&Cursor, aBuf, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); - y += LineHeight+Spacing; - if (lower32 || upper32) { - if (rendered == 32) break; - } else if (lower24 || upper24) { - if (rendered == 24) break; - } else { - if (rendered == 16) break; + y += LineHeight + Spacing; + if(lower32 || upper32) + { + if(rendered == 32) + break; + } + else if(lower24 || upper24) + { + if(rendered == 24) + break; + } + else + { + if(rendered == 16) + break; } } } @@ -527,9 +535,9 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch void CScoreboard::RenderRecordingNotification(float x) { if(!m_pClient->DemoRecorder(RECORDER_MANUAL)->IsRecording() && - !m_pClient->DemoRecorder(RECORDER_AUTO)->IsRecording() && - !m_pClient->DemoRecorder(RECORDER_RACE)->IsRecording() && - !m_pClient->DemoRecorder(RECORDER_REPLAYS)->IsRecording()) + !m_pClient->DemoRecorder(RECORDER_AUTO)->IsRecording() && + !m_pClient->DemoRecorder(RECORDER_RACE)->IsRecording() && + !m_pClient->DemoRecorder(RECORDER_REPLAYS)->IsRecording()) { return; } @@ -542,19 +550,19 @@ void CScoreboard::RenderRecordingNotification(float x) if(m_pClient->DemoRecorder(RECORDER_MANUAL)->IsRecording()) { Seconds = m_pClient->DemoRecorder(RECORDER_MANUAL)->Length(); - str_format(aBuf2, sizeof(aBuf2), Localize("Manual %3d:%02d "), Seconds/60, Seconds%60); + str_format(aBuf2, sizeof(aBuf2), Localize("Manual %3d:%02d "), Seconds / 60, Seconds % 60); str_append(aBuf, aBuf2, sizeof(aBuf)); } if(m_pClient->DemoRecorder(RECORDER_RACE)->IsRecording()) { Seconds = m_pClient->DemoRecorder(RECORDER_RACE)->Length(); - str_format(aBuf2, sizeof(aBuf2), Localize("Race %3d:%02d "), Seconds/60, Seconds%60); + str_format(aBuf2, sizeof(aBuf2), Localize("Race %3d:%02d "), Seconds / 60, Seconds % 60); str_append(aBuf, aBuf2, sizeof(aBuf)); } if(m_pClient->DemoRecorder(RECORDER_AUTO)->IsRecording()) { Seconds = m_pClient->DemoRecorder(RECORDER_AUTO)->Length(); - str_format(aBuf2, sizeof(aBuf2), Localize("Auto %3d:%02d "), Seconds/60, Seconds%60); + str_format(aBuf2, sizeof(aBuf2), Localize("Auto %3d:%02d "), Seconds / 60, Seconds % 60); str_append(aBuf, aBuf2, sizeof(aBuf)); } if(m_pClient->DemoRecorder(RECORDER_REPLAYS)->IsRecording()) @@ -571,19 +579,18 @@ void CScoreboard::RenderRecordingNotification(float x) Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); - RenderTools()->DrawRoundRectExt(x, 0.0f, w+60.0f, 50.0f, 15.0f, CUI::CORNER_B); + RenderTools()->DrawRoundRectExt(x, 0.0f, w + 60.0f, 50.0f, 15.0f, CUI::CORNER_B); Graphics()->QuadsEnd(); //draw the red dot Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); - RenderTools()->DrawRoundRect(x+20, 15.0f, 20.0f, 20.0f, 10.0f); + RenderTools()->DrawRoundRect(x + 20, 15.0f, 20.0f, 20.0f, 10.0f); Graphics()->QuadsEnd(); - TextRender()->Text(0, x+50.0f, (50.f - 20.f) / 2.f, 20.0f, aBuf, -1.0f); + TextRender()->Text(0, x + 50.0f, (50.f - 20.f) / 2.f, 20.0f, aBuf, -1.0f); } - void CScoreboard::OnRender() { if(!Active()) @@ -593,9 +600,8 @@ void CScoreboard::OnRender() if(m_pClient->m_pMotd->IsActive()) m_pClient->m_pMotd->Clear(); - - float Width = 400*3.0f*Graphics()->ScreenAspect(); - float Height = 400*3.0f; + float Width = 400 * 3.0f * Graphics()->ScreenAspect(); + float Height = 400 * 3.0f; Graphics()->MapScreen(0, 0, Width, Height); @@ -603,23 +609,26 @@ void CScoreboard::OnRender() if(m_pClient->m_Snap.m_pGameInfoObj) { - if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS)) + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS)) { if(m_pClient->m_Snap.m_aTeamSize[0] > 48) { - RenderScoreboard(Width/2-w, 150.0f, w, -4, 0); - RenderScoreboard(Width/2, 150.0f, w, -5, ""); - } else if(m_pClient->m_Snap.m_aTeamSize[0] > 32) + RenderScoreboard(Width / 2 - w, 150.0f, w, -4, 0); + RenderScoreboard(Width / 2, 150.0f, w, -5, ""); + } + else if(m_pClient->m_Snap.m_aTeamSize[0] > 32) { - RenderScoreboard(Width/2-w, 150.0f, w, -7, 0); - RenderScoreboard(Width/2, 150.0f, w, -8, ""); - } else if(m_pClient->m_Snap.m_aTeamSize[0] > 16) + RenderScoreboard(Width / 2 - w, 150.0f, w, -7, 0); + RenderScoreboard(Width / 2, 150.0f, w, -8, ""); + } + else if(m_pClient->m_Snap.m_aTeamSize[0] > 16) { - RenderScoreboard(Width/2-w, 150.0f, w, -6, 0); - RenderScoreboard(Width/2, 150.0f, w, -3, ""); - } else + RenderScoreboard(Width / 2 - w, 150.0f, w, -6, 0); + RenderScoreboard(Width / 2, 150.0f, w, -3, ""); + } + else { - RenderScoreboard(Width/2-w/2, 150.0f, w, 0, 0); + RenderScoreboard(Width / 2 - w / 2, 150.0f, w, 0, 0); } } else @@ -627,7 +636,7 @@ void CScoreboard::OnRender() const char *pRedClanName = GetClanName(TEAM_RED); const char *pBlueClanName = GetClanName(TEAM_BLUE); - if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER && m_pClient->m_Snap.m_pGameDataObj) + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER && m_pClient->m_Snap.m_pGameDataObj) { char aText[256]; str_copy(aText, Localize("Draw!"), sizeof(aText)); @@ -648,17 +657,17 @@ void CScoreboard::OnRender() } float w = TextRender()->TextWidth(0, 86.0f, aText, -1, -1.0f); - TextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1.0f); + TextRender()->Text(0, Width / 2 - w / 2, 39, 86.0f, aText, -1.0f); } - RenderScoreboard(Width/2-w-5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize("Red team")); - RenderScoreboard(Width/2+5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize("Blue team")); + RenderScoreboard(Width / 2 - w - 5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize("Red team")); + RenderScoreboard(Width / 2 + 5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize("Blue team")); } } - RenderGoals(Width/2-w/2, 150+760+10, w); - RenderSpectators(Width/2-w/2, 150+760+10+50+10, w); - RenderRecordingNotification((Width/7)*4); + RenderGoals(Width / 2 - w / 2, 150 + 760 + 10, w); + RenderSpectators(Width / 2 - w / 2, 150 + 760 + 10 + 50 + 10, w); + RenderRecordingNotification((Width / 7) * 4); } bool CScoreboard::Active() @@ -678,7 +687,7 @@ bool CScoreboard::Active() } // if the game is over - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) return true; return false; diff --git a/src/game/client/components/scoreboard.h b/src/game/client/components/scoreboard.h index 190e9783e..0ccaf8d91 100644 --- a/src/game/client/components/scoreboard.h +++ b/src/game/client/components/scoreboard.h @@ -31,7 +31,6 @@ public: virtual void OnMessage(int MsgType, void *pRawMsg); private: - float m_ServerRecord; }; diff --git a/src/game/client/components/skins.cpp b/src/game/client/components/skins.cpp index d46bc5d26..2f6f6bac2 100644 --- a/src/game/client/components/skins.cpp +++ b/src/game/client/components/skins.cpp @@ -2,8 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include #include +#include #include #include @@ -71,10 +71,10 @@ int CSkins::LoadSkin(const char *pName, const char *pPath, int DirType) Skin.m_OrgTexture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); int BodySize = 96; // body size - if (BodySize > Info.m_Height) + if(BodySize > Info.m_Height) return 0; unsigned char *d = (unsigned char *)Info.m_pData; - int Pitch = Info.m_Width*4; + int Pitch = Info.m_Width * 4; // dig out blood color { @@ -82,11 +82,11 @@ int CSkins::LoadSkin(const char *pName, const char *pPath, int DirType) for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { - if(d[y*Pitch+x*4+3] > 128) + if(d[y * Pitch + x * 4 + 3] > 128) { - aColors[0] += d[y*Pitch+x*4+0]; - aColors[1] += d[y*Pitch+x*4+1]; - aColors[2] += d[y*Pitch+x*4+2]; + aColors[0] += d[y * Pitch + x * 4 + 0]; + aColors[1] += d[y * Pitch + x * 4 + 1]; + aColors[2] += d[y * Pitch + x * 4 + 2]; } } @@ -97,15 +97,14 @@ int CSkins::LoadSkin(const char *pName, const char *pPath, int DirType) int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3; // make the texture gray scale - for(int i = 0; i < Info.m_Width*Info.m_Height; i++) + for(int i = 0; i < Info.m_Width * Info.m_Height; i++) { - int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3; - d[i*Step] = v; - d[i*Step+1] = v; - d[i*Step+2] = v; + int v = (d[i * Step] + d[i * Step + 1] + d[i * Step + 2]) / 3; + d[i * Step] = v; + d[i * Step + 1] = v; + d[i * Step + 2] = v; } - int Freq[256] = {0}; int OrgWeight = 0; int NewWeight = 192; @@ -114,8 +113,8 @@ int CSkins::LoadSkin(const char *pName, const char *pPath, int DirType) for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { - if(d[y*Pitch+x*4+3] > 128) - Freq[d[y*Pitch+x*4]]++; + if(d[y * Pitch + x * 4 + 3] > 128) + Freq[d[y * Pitch + x * 4]]++; } for(int i = 1; i < 256; i++) @@ -125,19 +124,19 @@ int CSkins::LoadSkin(const char *pName, const char *pPath, int DirType) } // reorder - int InvOrgWeight = 255-OrgWeight; - int InvNewWeight = 255-NewWeight; + int InvOrgWeight = 255 - OrgWeight; + int InvNewWeight = 255 - NewWeight; for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { - int v = d[y*Pitch+x*4]; + int v = d[y * Pitch + x * 4]; if(v <= OrgWeight) - v = (int)(((v/(float)OrgWeight) * NewWeight)); + v = (int)(((v / (float)OrgWeight) * NewWeight)); else - v = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight); - d[y*Pitch+x*4] = v; - d[y*Pitch+x*4+1] = v; - d[y*Pitch+x*4+2] = v; + v = (int)(((v - OrgWeight) / (float)InvOrgWeight) * InvNewWeight + NewWeight); + d[y * Pitch + x * 4] = v; + d[y * Pitch + x * 4 + 1] = v; + d[y * Pitch + x * 4 + 2] = v; } Skin.m_ColorTexture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); @@ -162,7 +161,7 @@ void CSkins::OnInit() if(g_Config.m_Events) { time_t rawtime; - struct tm* timeinfo; + struct tm *timeinfo; std::time(&rawtime); timeinfo = localtime(&rawtime); if(timeinfo->tm_mon == 11 && timeinfo->tm_mday >= 24 && timeinfo->tm_mday <= 26) @@ -196,7 +195,7 @@ const CSkins::CSkin *CSkins::Get(int Index) { Index = Find("default"); - if (Index < 0) + if(Index < 0) Index = 0; } return &m_aSkins[Index % m_aSkins.size()]; diff --git a/src/game/client/components/sounds.cpp b/src/game/client/components/sounds.cpp index e165520a2..4b9ef11e3 100644 --- a/src/game/client/components/sounds.cpp +++ b/src/game/client/components/sounds.cpp @@ -3,15 +3,14 @@ #include +#include "sounds.h" #include -#include #include -#include -#include +#include #include #include -#include "sounds.h" - +#include +#include CSoundLoading::CSoundLoading(CGameClient *pGameClient, bool Render) : m_pGameClient(pGameClient), @@ -51,8 +50,7 @@ int CSounds::GetSampleId(int SetId) do { Id = rand() % pSet->m_NumSounds; - } - while(Id == pSet->m_Last); + } while(Id == pSet->m_Last); pSet->m_Last = Id; return pSet->m_aSounds[Id].m_Id; } @@ -60,7 +58,7 @@ int CSounds::GetSampleId(int SetId) void CSounds::OnInit() { // setup sound channels - m_MapSoundVolume = g_Config.m_SndMapSoundVolume/100.0f; + m_MapSoundVolume = g_Config.m_SndMapSoundVolume / 100.0f; Sound()->SetChannel(CSounds::CHN_GUI, 1.0f, 0.0f); Sound()->SetChannel(CSounds::CHN_MUSIC, 1.0f, 0.0f); @@ -116,7 +114,7 @@ void CSounds::OnRender() Sound()->SetListenerPos(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y); // update volume - float NewMapSoundVol = g_Config.m_SndMapSoundVolume/100.0f; + float NewMapSoundVol = g_Config.m_SndMapSoundVolume / 100.0f; if(NewMapSoundVol != m_MapSoundVolume) { m_MapSoundVolume = NewMapSoundVol; @@ -130,9 +128,9 @@ void CSounds::OnRender() if(m_QueueWaitTime <= Now) { Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f); - m_QueueWaitTime = Now+time_freq()*3/10; // wait 300ms before playing the next one + m_QueueWaitTime = Now + time_freq() * 3 / 10; // wait 300ms before playing the next one if(--m_QueuePos > 0) - mem_move(m_aQueue, m_aQueue+1, m_QueuePos*sizeof(QueueEntry)); + mem_move(m_aQueue, m_aQueue + 1, m_QueuePos * sizeof(QueueEntry)); } } } @@ -161,7 +159,7 @@ void CSounds::PlayAndRecord(int Chn, int SetId, float Vol, vec2 Pos) { CNetMsg_Sv_SoundGlobal Msg; Msg.m_SoundID = SetId; - Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD); + Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND | MSGFLAG_RECORD); Play(Chn, SetId, Vol); } diff --git a/src/game/client/components/sounds.h b/src/game/client/components/sounds.h index ecc988bce..862e1282b 100644 --- a/src/game/client/components/sounds.h +++ b/src/game/client/components/sounds.h @@ -40,7 +40,7 @@ public: // sound channels enum { - CHN_GUI=0, + CHN_GUI = 0, CHN_MUSIC, CHN_WORLD, CHN_GLOBAL, @@ -63,5 +63,4 @@ public: ISound::CVoiceHandle PlaySampleAt(int Channel, int SampleId, float Vol, vec2 Pos, int Flags = 0); }; - #endif diff --git a/src/game/client/components/spectator.cpp b/src/game/client/components/spectator.cpp index 1be0af5ed..c5c0ff5b9 100644 --- a/src/game/client/components/spectator.cpp +++ b/src/game/client/components/spectator.cpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include #include #include @@ -14,9 +14,8 @@ #include #include -#include "spectator.h" #include "camera.h" - +#include "spectator.h" void CSpectator::ConKeySpectator(IConsole::IResult *pResult, void *pUserData) { @@ -98,7 +97,7 @@ void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { - for(int i = MAX_CLIENTS -1; i > -1; i--) + for(int i = MAX_CLIENTS - 1; i > -1; i--) { if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeamName[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_Team == TEAM_SPECTATORS) continue; @@ -146,7 +145,7 @@ void CSpectator::ConSpectateClosest(IConsole::IResult *pResult, void *pUserData) vec2 CurPosition(pSelf->m_pClient->m_pCamera->m_Center); if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(pSelf->m_pClient->m_Snap.m_paInfoByDDTeamName[i] && pSelf->m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_ClientID == pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID) { @@ -197,7 +196,7 @@ bool CSpectator::OnMouseMove(float x, float y) return false; UI()->ConvertMouseMove(&x, &y); - m_SelectorMouse += vec2(x,y); + m_SelectorMouse += vec2(x, y); return true; } @@ -230,8 +229,8 @@ void CSpectator::OnRender() m_SelectedSpectatorID = NO_SELECTION; // draw background - float Width = 400*3.0f*Graphics()->ScreenAspect(); - float Height = 400*3.0f; + float Width = 400 * 3.0f * Graphics()->ScreenAspect(); + float Height = 400 * 3.0f; float ObjWidth = 300.0f; float FontSize = 20.0f; float BigFontSize = 20.0f; @@ -252,7 +251,7 @@ void CSpectator::OnRender() ++TotalPlayers; } - if (TotalPlayers > 32) + if(TotalPlayers > 32) { FontSize = 18.0f; LineHeight = 30.0f; @@ -261,7 +260,7 @@ void CSpectator::OnRender() RoundRadius = 10.0f; BoxMove = 3.0f; } - if (TotalPlayers > 16) + if(TotalPlayers > 16) { ObjWidth = 600.0f; } @@ -272,7 +271,7 @@ void CSpectator::OnRender() Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.3f); - RenderTools()->DrawRoundRect(Width/2.0f-ObjWidth, Height/2.0f-300.0f, ObjWidth*2, 600.0f, 20.0f); + RenderTools()->DrawRoundRect(Width / 2.0f - ObjWidth, Height / 2.0f - 300.0f, ObjWidth * 2, 600.0f, 20.0f); Graphics()->QuadsEnd(); // clamp mouse position to selector area @@ -281,12 +280,12 @@ void CSpectator::OnRender() // draw selections if((Client()->State() == IClient::STATE_DEMOPLAYBACK && m_pClient->m_DemoSpecID == SPEC_FREEVIEW) || - m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); - RenderTools()->DrawRoundRect(Width/2.0f-(ObjWidth - 20.0f), Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); + RenderTools()->DrawRoundRect(Width / 2.0f - (ObjWidth - 20.0f), Height / 2.0f - 280.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } @@ -295,30 +294,30 @@ void CSpectator::OnRender() Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); - RenderTools()->DrawRoundRect(Width/2.0f-(ObjWidth - 310.0f), Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); + RenderTools()->DrawRoundRect(Width / 2.0f - (ObjWidth - 310.0f), Height / 2.0f - 280.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } - if(m_SelectorMouse.x >= -(ObjWidth-20.0f) && m_SelectorMouse.x <= -(ObjWidth-290+10.0f) && + if(m_SelectorMouse.x >= -(ObjWidth - 20.0f) && m_SelectorMouse.x <= -(ObjWidth - 290 + 10.0f) && m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) { m_SelectedSpectatorID = SPEC_FREEVIEW; Selected = true; } - TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); - TextRender()->Text(0, Width/2.0f-(ObjWidth-60.0f), Height/2.0f-280.f + (60.f - BigFontSize) / 2.f, BigFontSize, Localize("Free-View"), -1.0f); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected ? 1.0f : 0.5f); + TextRender()->Text(0, Width / 2.0f - (ObjWidth - 60.0f), Height / 2.0f - 280.f + (60.f - BigFontSize) / 2.f, BigFontSize, Localize("Free-View"), -1.0f); if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { Selected = false; - if(m_SelectorMouse.x > -(ObjWidth-290.0f) && m_SelectorMouse.x <= -(ObjWidth-590.0f) && + if(m_SelectorMouse.x > -(ObjWidth - 290.0f) && m_SelectorMouse.x <= -(ObjWidth - 590.0f) && m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) { m_SelectedSpectatorID = SPEC_FOLLOW; Selected = true; } - TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); - TextRender()->Text(0, Width/2.0f-(ObjWidth-350.0f), Height/2.0f-280.0f + (60.f - BigFontSize) / 2.f, BigFontSize, Localize("Follow"), -1.0f); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected ? 1.0f : 0.5f); + TextRender()->Text(0, Width / 2.0f - (ObjWidth - 350.0f), Height / 2.0f - 280.0f + (60.f - BigFontSize) / 2.f, BigFontSize, Localize("Follow"), -1.0f); } float x = -(ObjWidth - 30.0f), y = StartY; @@ -332,7 +331,7 @@ void CSpectator::OnRender() ++Count; - if(Count == PerLine + 1 || (Count > PerLine + 1 && (Count-1)%PerLine == 0)) + if(Count == PerLine + 1 || (Count > PerLine + 1 && (Count - 1) % PerLine == 0)) { x += 290.0f; y = StartY; @@ -353,9 +352,9 @@ void CSpectator::OnRender() break; } - if (OldDDTeam == -1) + if(OldDDTeam == -1) { - for (int j = i - 1; j >= 0; j--) + for(int j = i - 1; j >= 0; j--) { const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeamName[j]; @@ -367,7 +366,7 @@ void CSpectator::OnRender() } } - if (DDTeam != TEAM_FLOCK) + if(DDTeam != TEAM_FLOCK) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); @@ -376,12 +375,12 @@ void CSpectator::OnRender() int Corners = 0; - if (OldDDTeam != DDTeam) + if(OldDDTeam != DDTeam) Corners |= CUI::CORNER_TL | CUI::CORNER_TR; - if (NextDDTeam != DDTeam) + if(NextDDTeam != DDTeam) Corners |= CUI::CORNER_BL | CUI::CORNER_BR; - RenderTools()->DrawRoundRectExt(Width/2.0f+x-10.0f, Height/2.0f+y+BoxMove, 270.0f, LineHeight, RoundRadius, Corners); + RenderTools()->DrawRoundRectExt(Width / 2.0f + x - 10.0f, Height / 2.0f + y + BoxMove, 270.0f, LineHeight, RoundRadius, Corners); Graphics()->QuadsEnd(); } @@ -393,13 +392,13 @@ void CSpectator::OnRender() Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); - RenderTools()->DrawRoundRect(Width/2.0f+x-10.0f, Height/2.0f+y+BoxMove, 270.0f, LineHeight, RoundRadius); + RenderTools()->DrawRoundRect(Width / 2.0f + x - 10.0f, Height / 2.0f + y + BoxMove, 270.0f, LineHeight, RoundRadius); Graphics()->QuadsEnd(); } Selected = false; - if(m_SelectorMouse.x >= x-10.0f && m_SelectorMouse.x < x+260.0f && - m_SelectorMouse.y >= y-(LineHeight/6.0f) && m_SelectorMouse.y < y+(LineHeight*5.0f/6.0f)) + if(m_SelectorMouse.x >= x - 10.0f && m_SelectorMouse.x < x + 260.0f && + m_SelectorMouse.y >= y - (LineHeight / 6.0f) && m_SelectorMouse.y < y + (LineHeight * 5.0f / 6.0f)) { m_SelectedSpectatorID = m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_ClientID; Selected = true; @@ -413,7 +412,7 @@ void CSpectator::OnRender() } else { - TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected ? 1.0f : 0.5f); TeeAlpha = 1.0f; } TextRender()->Text(0, Width / 2.0f + x + 50.0f, Height / 2.0f + y + BoxMove + (LineHeight - FontSize) / 2.f, FontSize, m_pClient->m_aClients[m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_ClientID].m_aName, 220.0f); @@ -429,14 +428,14 @@ void CSpectator::OnRender() RenderTools()->SelectSprite(m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_ClientID ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = LineHeight; - IGraphics::CQuadItem QuadItem(Width/2.0f+x-LineHeight/5.0f, Height/2.0f+y-LineHeight/3.0f, Size/2.0f, Size); + IGraphics::CQuadItem QuadItem(Width / 2.0f + x - LineHeight / 5.0f, Height / 2.0f + y - LineHeight / 3.0f, Size / 2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } CTeeRenderInfo TeeInfo = m_pClient->m_aClients[m_pClient->m_Snap.m_paInfoByDDTeamName[i]->m_ClientID].m_RenderInfo; TeeInfo.m_Size *= TeeSizeMod; - RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width/2.0f+x+20.0f, Height/2.0f+y+20.0f), TeeAlpha); + RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width / 2.0f + x + 20.0f, Height / 2.0f + y + 20.0f), TeeAlpha); y += LineHeight; } @@ -447,7 +446,7 @@ void CSpectator::OnRender() Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); - IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Width/2.0f, m_SelectorMouse.y+Height/2.0f, 48.0f, 48.0f); + IGraphics::CQuadItem QuadItem(m_SelectorMouse.x + Width / 2.0f, m_SelectorMouse.y + Height / 2.0f, 48.0f, 48.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); Graphics()->WrapNormal(); @@ -464,7 +463,7 @@ void CSpectator::Spectate(int SpectatorID) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { - m_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FOLLOW, MAX_CLIENTS-1); + m_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FOLLOW, MAX_CLIENTS - 1); return; } diff --git a/src/game/client/components/spectator.h b/src/game/client/components/spectator.h index faf4dbebe..48a575123 100644 --- a/src/game/client/components/spectator.h +++ b/src/game/client/components/spectator.h @@ -10,7 +10,7 @@ class CSpectator : public CComponent { enum { - NO_SELECTION=-3, + NO_SELECTION = -3, }; bool m_Active; diff --git a/src/game/client/components/statboard.cpp b/src/game/client/components/statboard.cpp index fdbda893a..4248739dd 100644 --- a/src/game/client/components/statboard.cpp +++ b/src/game/client/components/statboard.cpp @@ -1,13 +1,13 @@ -#include -#include #include #include +#include #include -#include -#include +#include #include #include #include +#include +#include CStatboard::CStatboard() { @@ -19,7 +19,7 @@ CStatboard::CStatboard() void CStatboard::OnReset() { - for(int i=0; im_aStats[i].Reset(); m_Active = false; m_ScreenshotTaken = false; @@ -105,9 +105,9 @@ void CStatboard::OnMessage(int MsgType, void *pRawMsg) void CStatboard::OnRender() { - if((g_Config.m_ClAutoStatboardScreenshot||g_Config.m_ClAutoCSV) && Client()->State() != IClient::STATE_DEMOPLAYBACK) + if((g_Config.m_ClAutoStatboardScreenshot || g_Config.m_ClAutoCSV) && Client()->State() != IClient::STATE_DEMOPLAYBACK) { - if(m_ScreenshotTime < 0 && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + if(m_ScreenshotTime < 0 && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) m_ScreenshotTime = time_get() + time_freq() * 3; if(m_ScreenshotTime > -1 && m_ScreenshotTime < time_get()) m_Active = true; @@ -127,8 +127,8 @@ void CStatboard::OnRender() void CStatboard::RenderGlobalStats() { - const float StatboardWidth = 400*3.0f*Graphics()->ScreenAspect(); - const float StatboardHeight = 400*3.0f; + const float StatboardWidth = 400 * 3.0f * Graphics()->ScreenAspect(); + const float StatboardHeight = 400 * 3.0f; float StatboardContentWidth = 260.0f; float StatboardContentHeight = 750.0f; @@ -146,7 +146,7 @@ void CStatboard::RenderGlobalStats() } // sort blue players by score after - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { for(int i = 0; i < MAX_CLIENTS; i++) { @@ -168,7 +168,7 @@ void CStatboard::RenderGlobalStats() m_pClient->m_pMotd->Clear(); bool GameWithFlags = m_pClient->m_Snap.m_pGameInfoObj && - m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS; + m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_FLAGS; StatboardContentWidth += 7 * 85 + 95; // Suicides 95; other labels 85 @@ -179,14 +179,14 @@ void CStatboard::RenderGlobalStats() for(int i = 0; i < NumPlayers; i++) { const CGameClient::CClientStats *pStats = &m_pClient->m_aStats[apPlayers[i]->m_ClientID]; - for(int j=0; jm_aFragsWith[j] || pStats->m_aDeathsFrom[j]; } for(int i = 0; i < NUM_WEAPONS; i++) if(aDisplayWeapon[i]) StatboardContentWidth += 80; - float x = StatboardWidth/2-StatboardContentWidth/2; + float x = StatboardWidth / 2 - StatboardContentWidth / 2; float y = 200.0f; Graphics()->MapScreen(0, 0, StatboardWidth, StatboardHeight); @@ -194,19 +194,18 @@ void CStatboard::RenderGlobalStats() Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,0,0.5f); - RenderTools()->DrawRoundRect(x-10.f, y-10.f, StatboardContentWidth, StatboardContentHeight, 17.0f); + Graphics()->SetColor(0, 0, 0, 0.5f); + RenderTools()->DrawRoundRect(x - 10.f, y - 10.f, StatboardContentWidth, StatboardContentHeight, 17.0f); Graphics()->QuadsEnd(); float tw; int px = 325; - TextRender()->Text(0, x+10, y-5, 22.0f, Localize("Name"), -1.0f); + TextRender()->Text(0, x + 10, y - 5, 22.0f, Localize("Name"), -1.0f); const char *apHeaders[] = { Localize("Frags"), Localize("Deaths"), Localize("Suicides"), Localize("Ratio"), Localize("Net"), Localize("FPM"), - Localize("Spree"), Localize("Best"), Localize("Grabs") - }; + Localize("Spree"), Localize("Best"), Localize("Grabs")}; for(int i = 0; i < 9; i++) { if(i == 2) @@ -214,7 +213,7 @@ void CStatboard::RenderGlobalStats() if(i == 8 && !GameWithFlags) // Don't draw "Grabs" in game with no flag continue; tw = TextRender()->TextWidth(0, 22.0f, apHeaders[i], -1, -1.0f); - TextRender()->Text(0, x+px-tw, y-5, 22.0f, apHeaders[i], -1.0f); + TextRender()->Text(0, x + px - tw, y - 5, 22.0f, apHeaders[i], -1.0f); px += 85; } @@ -227,9 +226,9 @@ void CStatboard::RenderGlobalStats() continue; RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[i].m_pSpriteBody); if(i == 0) - RenderTools()->DrawSprite(x+px, y+10, g_pData->m_Weapons.m_aId[i].m_VisualSize*0.8f); + RenderTools()->DrawSprite(x + px, y + 10, g_pData->m_Weapons.m_aId[i].m_VisualSize * 0.8f); else - RenderTools()->DrawSprite(x+px, y+10, g_pData->m_Weapons.m_aId[i].m_VisualSize); + RenderTools()->DrawSprite(x + px, y + 10, g_pData->m_Weapons.m_aId[i].m_VisualSize); px += 80; } Graphics()->QuadsEnd(); @@ -240,7 +239,7 @@ void CStatboard::RenderGlobalStats() Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(0.78f); RenderTools()->SelectSprite(SPRITE_FLAG_RED); - RenderTools()->DrawSprite(x+px, y+15, 48); + RenderTools()->DrawSprite(x + px, y + 15, 48); Graphics()->QuadsEnd(); } else @@ -268,25 +267,24 @@ void CStatboard::RenderGlobalStats() const CNetObj_PlayerInfo *pInfo = apPlayers[j]; const CGameClient::CClientStats *pStats = &m_pClient->m_aStats[pInfo->m_ClientID]; - if(m_pClient->m_Snap.m_LocalClientID == pInfo->m_ClientID - || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)) + if(m_pClient->m_Snap.m_LocalClientID == pInfo->m_ClientID || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)) { // background so it's easy to find the local player Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(1,1,1,0.25f); - RenderTools()->DrawRoundRect(x, y, StatboardContentWidth-20, LineHeight*0.95f, 17.0f); + Graphics()->SetColor(1, 1, 1, 0.25f); + RenderTools()->DrawRoundRect(x, y, StatboardContentWidth - 20, LineHeight * 0.95f, 17.0f); Graphics()->QuadsEnd(); } CTeeRenderInfo Teeinfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo; Teeinfo.m_Size *= TeeSizemod; - RenderTools()->RenderTee(CAnimState::GetIdle(), &Teeinfo, EMOTE_NORMAL, vec2(1,0), vec2(x+28, y+28+TeeOffset)); + RenderTools()->RenderTee(CAnimState::GetIdle(), &Teeinfo, EMOTE_NORMAL, vec2(1, 0), vec2(x + 28, y + 28 + TeeOffset)); char aBuf[128]; CTextCursor Cursor; tw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1, -1.0f); - TextRender()->SetCursor(&Cursor, x+64, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + TextRender()->SetCursor(&Cursor, x + 64, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, TEXTFLAG_RENDER | TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = 220; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1); @@ -296,14 +294,14 @@ void CStatboard::RenderGlobalStats() { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_Frags); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // DEATHS { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_Deaths); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // SUICIDES @@ -311,7 +309,7 @@ void CStatboard::RenderGlobalStats() px += 10; str_format(aBuf, sizeof(aBuf), "%d", pStats->m_Suicides); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // RATIO @@ -319,16 +317,16 @@ void CStatboard::RenderGlobalStats() if(pStats->m_Deaths == 0) str_format(aBuf, sizeof(aBuf), "--"); else - str_format(aBuf, sizeof(aBuf), "%.2f", (float)(pStats->m_Frags)/pStats->m_Deaths); + str_format(aBuf, sizeof(aBuf), "%.2f", (float)(pStats->m_Frags) / pStats->m_Deaths); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // NET { - str_format(aBuf, sizeof(aBuf), "%+d", pStats->m_Frags-pStats->m_Deaths); + str_format(aBuf, sizeof(aBuf), "%+d", pStats->m_Frags - pStats->m_Deaths); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // FPM @@ -336,21 +334,21 @@ void CStatboard::RenderGlobalStats() float Fpm = pStats->GetFPM(Client()->GameTick(g_Config.m_ClDummy), Client()->GameTickSpeed()); str_format(aBuf, sizeof(aBuf), "%.1f", Fpm); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // SPREE { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_CurrentSpree); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // BEST SPREE { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_BestSpree); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // GRABS @@ -358,7 +356,7 @@ void CStatboard::RenderGlobalStats() { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_FlagGrabs); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } // WEAPONS @@ -370,7 +368,7 @@ void CStatboard::RenderGlobalStats() str_format(aBuf, sizeof(aBuf), "%d/%d", pStats->m_aFragsWith[i], pStats->m_aDeathsFrom[i]); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x+px-tw/2, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x + px - tw / 2, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 80; } // FLAGS @@ -378,7 +376,7 @@ void CStatboard::RenderGlobalStats() { str_format(aBuf, sizeof(aBuf), "%d", pStats->m_FlagCaptures); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f); - TextRender()->Text(0, x-tw+px, y + (LineHeight*0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); + TextRender()->Text(0, x - tw + px, y + (LineHeight * 0.95f - FontSize) / 2.f, FontSize, aBuf, -1.0f); px += 85; } y += LineHeight; @@ -412,7 +410,7 @@ void CStatboard::AutoStatCSV() } } -char* CStatboard::ReplaceCommata(char* pStr) +char *CStatboard::ReplaceCommata(char *pStr) { if(!str_find(pStr, ",")) return pStr; @@ -436,7 +434,7 @@ char* CStatboard::ReplaceCommata(char* pStr) } unsigned int len = str_length(aOutbuf); - char* buf = new char[len]; + char *buf = new char[len]; mem_copy(buf, aOutbuf, len); return buf; } @@ -449,7 +447,6 @@ void CStatboard::FormatStats() char aServerStats[1024]; str_format(aServerStats, sizeof(aServerStats), "Servername,Game-type,Map\n%s,%s,%s", ReplaceCommata(CurrentServerInfo.m_aName), CurrentServerInfo.m_aGameType, CurrentServerInfo.m_aMap); - // player stats // sort players @@ -457,7 +454,7 @@ void CStatboard::FormatStats() int NumPlayers = 0; // sort red or dm players by score - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i]; if(!pInfo || !m_pClient->m_aStats[pInfo->m_ClientID].IsActive() || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != TEAM_RED) @@ -467,9 +464,9 @@ void CStatboard::FormatStats() } // sort blue players by score after - if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i]; if(!pInfo || !m_pClient->m_aStats[pInfo->m_ClientID].IsActive() || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != TEAM_BLUE) @@ -481,7 +478,7 @@ void CStatboard::FormatStats() char aPlayerStats[1024 * VANILLA_MAX_CLIENTS]; str_format(aPlayerStats, sizeof(aPlayerStats), "Local-player,Team,Name,Clan,Score,Frags,Deaths,Suicides,F/D-ratio,Net,FPM,Spree,Best,Hammer-F/D,Gun-F/D,Shotgun-F/D,Grenade-F/D,Laser-F/D,Ninja-F/D,GameWithFlags,Flag-grabs,Flag-captures\n"); - for (int i = 0; i < NumPlayers; i++) + for(int i = 0; i < NumPlayers; i++) { const CNetObj_PlayerInfo *pInfo = apPlayers[i]; const CGameClient::CClientStats *pStats = &m_pClient->m_aStats[pInfo->m_ClientID]; @@ -490,7 +487,7 @@ void CStatboard::FormatStats() // Weapons frags/deaths char aWeaponFD[64 * NUM_WEAPONS]; - for (int j = 0; j < NUM_WEAPONS; j++) + for(int j = 0; j < NUM_WEAPONS; j++) { if(j == 0) str_format(aWeaponFD, sizeof(aWeaponFD), "%d/%d", pStats->m_aFragsWith[j], pStats->m_aDeathsFrom[j]); @@ -499,40 +496,40 @@ void CStatboard::FormatStats() } // Frag/Death ratio - float fdratio=0.0f; + float fdratio = 0.0f; if(pStats->m_Deaths != 0) - fdratio = (float) (pStats->m_Frags) / pStats->m_Deaths; + fdratio = (float)(pStats->m_Frags) / pStats->m_Deaths; // Local player bool localPlayer = (m_pClient->m_Snap.m_LocalClientID == pInfo->m_ClientID || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)); // Game with flags - bool GameWithFlags = (m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS); + bool GameWithFlags = (m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_FLAGS); char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "%d,%d,%s,%s,%d,%d,%d,%d,%.2f,%i,%.1f,%d,%d,%s,%d,%d,%d\n", - localPlayer?1:0, // Local player - m_pClient->m_aClients[pInfo->m_ClientID].m_Team, // Team - ReplaceCommata(m_pClient->m_aClients[pInfo->m_ClientID].m_aName), // Name - ReplaceCommata(m_pClient->m_aClients[pInfo->m_ClientID].m_aClan), // Clan - clamp(pInfo->m_Score, -999, 999), // Score - pStats->m_Frags, // Frags - pStats->m_Deaths, // Deaths - pStats->m_Suicides, // Suicides - fdratio, // fdratio - pStats->m_Frags - pStats->m_Deaths, // Net - pStats->GetFPM(Client()->GameTick(g_Config.m_ClDummy), Client()->GameTickSpeed()), // FPM - pStats->m_CurrentSpree, // CurSpree - pStats->m_BestSpree, // BestSpree - aWeaponFD, // WeaponFD - GameWithFlags?1:0, // GameWithFlags - pStats->m_FlagGrabs, // Flag grabs - pStats->m_FlagCaptures); // Flag captures + localPlayer ? 1 : 0, // Local player + m_pClient->m_aClients[pInfo->m_ClientID].m_Team, // Team + ReplaceCommata(m_pClient->m_aClients[pInfo->m_ClientID].m_aName), // Name + ReplaceCommata(m_pClient->m_aClients[pInfo->m_ClientID].m_aClan), // Clan + clamp(pInfo->m_Score, -999, 999), // Score + pStats->m_Frags, // Frags + pStats->m_Deaths, // Deaths + pStats->m_Suicides, // Suicides + fdratio, // fdratio + pStats->m_Frags - pStats->m_Deaths, // Net + pStats->GetFPM(Client()->GameTick(g_Config.m_ClDummy), Client()->GameTickSpeed()), // FPM + pStats->m_CurrentSpree, // CurSpree + pStats->m_BestSpree, // BestSpree + aWeaponFD, // WeaponFD + GameWithFlags ? 1 : 0, // GameWithFlags + pStats->m_FlagGrabs, // Flag grabs + pStats->m_FlagCaptures); // Flag captures str_append(aPlayerStats, aBuf, sizeof(aPlayerStats)); } - char aStats[1024*(VANILLA_MAX_CLIENTS+1)]; + char aStats[1024 * (VANILLA_MAX_CLIENTS + 1)]; str_format(aStats, sizeof(aStats), "%s\n\n%s", aServerStats, aPlayerStats); unsigned int Len = str_length(aStats); diff --git a/src/game/client/components/statboard.h b/src/game/client/components/statboard.h index 0e9a8008d..4f099ea7c 100644 --- a/src/game/client/components/statboard.h +++ b/src/game/client/components/statboard.h @@ -3,29 +3,29 @@ #include -class CStatboard: public CComponent +class CStatboard : public CComponent { - private: - bool m_Active; - bool m_ScreenshotTaken; - int64 m_ScreenshotTime; - static void ConKeyStats(IConsole::IResult *pResult, void *pUserData); - void RenderGlobalStats(); - void AutoStatScreenshot(); - void AutoStatCSV(); +private: + bool m_Active; + bool m_ScreenshotTaken; + int64 m_ScreenshotTime; + static void ConKeyStats(IConsole::IResult *pResult, void *pUserData); + void RenderGlobalStats(); + void AutoStatScreenshot(); + void AutoStatCSV(); - char* m_pCSVstr; - char* ReplaceCommata(char* pStr); - void FormatStats(); + char *m_pCSVstr; + char *ReplaceCommata(char *pStr); + void FormatStats(); - public: - CStatboard(); - virtual void OnReset(); - virtual void OnConsoleInit(); - virtual void OnRender(); - virtual void OnRelease(); - virtual void OnMessage(int MsgType, void *pRawMsg); - bool IsActive(); +public: + CStatboard(); + virtual void OnReset(); + virtual void OnConsoleInit(); + virtual void OnRender(); + virtual void OnRelease(); + virtual void OnMessage(int MsgType, void *pRawMsg); + bool IsActive(); }; #endif // GAME_CLIENT_COMPONENTS_STATBOARD_H diff --git a/src/game/client/components/voting.cpp b/src/game/client/components/voting.cpp index b26f1dd4a..c764ec9e3 100644 --- a/src/game/client/components/voting.cpp +++ b/src/game/client/components/voting.cpp @@ -2,14 +2,14 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include +#include "voting.h" #include #include -#include "voting.h" +#include void CVoting::ConCallvote(IConsole::IResult *pResult, void *pUserData) { - CVoting *pSelf = (CVoting*)pUserData; + CVoting *pSelf = (CVoting *)pUserData; pSelf->Callvote(pResult->GetString(0), pResult->GetString(1), pResult->NumArguments() > 2 ? pResult->GetString(2) : ""); } @@ -279,16 +279,15 @@ void CVoting::OnRender() { } - void CVoting::RenderBars(CUIRect Bars, bool Text) { - RenderTools()->DrawUIRect(&Bars, ColorRGBA(0.8f,0.8f,0.8f,0.5f), CUI::CORNER_ALL, Bars.h/3); + RenderTools()->DrawUIRect(&Bars, ColorRGBA(0.8f, 0.8f, 0.8f, 0.5f), CUI::CORNER_ALL, Bars.h / 3); CUIRect Splitter = Bars; - Splitter.x = Splitter.x+Splitter.w/2; - Splitter.w = Splitter.h/2.0f; - Splitter.x -= Splitter.w/2; - RenderTools()->DrawUIRect(&Splitter, ColorRGBA(0.4f,0.4f,0.4f,0.5f), CUI::CORNER_ALL, Splitter.h/4); + Splitter.x = Splitter.x + Splitter.w / 2; + Splitter.w = Splitter.h / 2.0f; + Splitter.x -= Splitter.w / 2; + RenderTools()->DrawUIRect(&Splitter, ColorRGBA(0.4f, 0.4f, 0.4f, 0.5f), CUI::CORNER_ALL, Splitter.h / 4); if(m_Total) { @@ -296,14 +295,14 @@ void CVoting::RenderBars(CUIRect Bars, bool Text) if(m_Yes) { CUIRect YesArea = Bars; - YesArea.w *= m_Yes/(float)m_Total; - RenderTools()->DrawUIRect(&YesArea, ColorRGBA(0.2f,0.9f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); + YesArea.w *= m_Yes / (float)m_Total; + RenderTools()->DrawUIRect(&YesArea, ColorRGBA(0.2f, 0.9f, 0.2f, 0.85f), CUI::CORNER_ALL, Bars.h / 3); if(Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_Yes); - UI()->DoLabel(&YesArea, Buf, Bars.h*0.75f, 0); + UI()->DoLabel(&YesArea, Buf, Bars.h * 0.75f, 0); } PassArea.x += YesArea.w; @@ -313,15 +312,15 @@ void CVoting::RenderBars(CUIRect Bars, bool Text) if(m_No) { CUIRect NoArea = Bars; - NoArea.w *= m_No/(float)m_Total; - NoArea.x = (Bars.x + Bars.w)-NoArea.w; - RenderTools()->DrawUIRect(&NoArea, ColorRGBA(0.9f,0.2f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); + NoArea.w *= m_No / (float)m_Total; + NoArea.x = (Bars.x + Bars.w) - NoArea.w; + RenderTools()->DrawUIRect(&NoArea, ColorRGBA(0.9f, 0.2f, 0.2f, 0.85f), CUI::CORNER_ALL, Bars.h / 3); if(Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_No); - UI()->DoLabel(&NoArea, Buf, Bars.h*0.75f, 0); + UI()->DoLabel(&NoArea, Buf, Bars.h * 0.75f, 0); } PassArea.w -= NoArea.w; @@ -331,7 +330,7 @@ void CVoting::RenderBars(CUIRect Bars, bool Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_Pass); - UI()->DoLabel(&PassArea, Buf, Bars.h*0.75f, 0); + UI()->DoLabel(&PassArea, Buf, Bars.h * 0.75f, 0); } } } diff --git a/src/game/client/components/voting.h b/src/game/client/components/voting.h index 6e73ba085..0d9f7995b 100644 --- a/src/game/client/components/voting.h +++ b/src/game/client/components/voting.h @@ -5,9 +5,9 @@ #include -#include #include #include +#include class CVoting : public CComponent { @@ -50,7 +50,7 @@ public: void Vote(int v); // -1 = no, 1 = yes - int SecondsLeft() { return (m_Closetime - time())/time_freq(); } + int SecondsLeft() { return (m_Closetime - time()) / time_freq(); } bool IsVoting() { return m_Closetime != 0; } int TakenChoice() const { return m_Voted; } const char *VoteDescription() const { return m_aDescription; } diff --git a/src/game/client/gameclient.cpp b/src/game/client/gameclient.cpp index 0283a6e26..d3009f1cc 100644 --- a/src/game/client/gameclient.cpp +++ b/src/game/client/gameclient.cpp @@ -3,31 +3,31 @@ #include +#include #include #include #include #include -#include -#include #include -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include -#include #include +#include #include #include +#include "race.h" +#include "render.h" #include #include #include -#include "race.h" -#include "render.h" #include "gameclient.h" @@ -63,9 +63,9 @@ #include "components/statboard.h" #include "components/voting.h" -#include -#include "components/race_demo.h" #include "components/ghost.h" +#include "components/race_demo.h" +#include CGameClient g_GameClient; @@ -187,7 +187,7 @@ void CGameClient::OnConsoleInit() m_All.Add(m_pRaceDemo); m_All.Add(m_pMapSounds); - m_All.Add(&gs_BackGround); //render instead of gs_MapLayersBackGround when g_Config.m_ClOverlayEntities == 100 + m_All.Add(&gs_BackGround); //render instead of gs_MapLayersBackGround when g_Config.m_ClOverlayEntities == 100 m_All.Add(&gs_MapLayersBackGround); // first to render m_All.Add(&m_pParticles->m_RenderTrail); m_All.Add(m_pItems); @@ -249,7 +249,7 @@ void CGameClient::OnConsoleInit() Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, 0, 0, "Shuffle the current teams"); // register tune zone command to allow the client prediction to load tunezones from the map - Console()->Register("tune_zone", "i[zone] s[tuning] i[value]", CFGFLAG_CLIENT|CFGFLAG_GAME, ConTuneZone, this, "Tune in zone a variable to value"); + Console()->Register("tune_zone", "i[zone] s[tuning] i[value]", CFGFLAG_CLIENT | CFGFLAG_GAME, ConTuneZone, this, "Tune in zone a variable to value"); for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->m_pClient = this; @@ -258,7 +258,6 @@ void CGameClient::OnConsoleInit() for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnConsoleInit(); - // Console()->Chain("player_name", ConchainSpecialInfoupdate, this); Console()->Chain("player_clan", ConchainSpecialInfoupdate, this); @@ -318,7 +317,7 @@ void CGameClient::OnInit() Client()->LoadFont(); // init all components - for(int i = m_All.m_Num-1; i >= 0; --i) + for(int i = m_All.m_Num - 1; i >= 0; --i) m_All.m_paComponents[i]->OnInit(); char aBuf[256]; @@ -348,7 +347,7 @@ void CGameClient::OnInit() for(unsigned int i = 0; i < 16; i++) { if(rand() % 2) - g_Config.m_ClTimeoutCode[i] =(char)((rand() % 26) + 97); + g_Config.m_ClTimeoutCode[i] = (char)((rand() % 26) + 97); else g_Config.m_ClTimeoutCode[i] = (char)((rand() % 26) + 65); } @@ -366,7 +365,7 @@ void CGameClient::OnInit() } int64 End = time_get(); - str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End-Start)*1000)/(float)time_freq()); + str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End - Start) * 1000) / (float)time_freq()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "gameclient", aBuf); m_GameWorld.m_GameTickSpeed = SERVER_TICK_SPEED; @@ -434,7 +433,7 @@ int CGameClient::OnSnapInput(int *pData, bool Dummy, bool Force) { if(m_DummyFire != 0) { - m_DummyInput.m_Fire = (m_HammerInput.m_Fire+1) & ~1; + m_DummyInput.m_Fire = (m_HammerInput.m_Fire + 1) & ~1; m_DummyFire = 0; } @@ -455,7 +454,7 @@ int CGameClient::OnSnapInput(int *pData, bool Dummy, bool Force) } m_DummyFire++; - m_HammerInput.m_Fire = (m_HammerInput.m_Fire+1) | 1; + m_HammerInput.m_Fire = (m_HammerInput.m_Fire + 1) | 1; m_HammerInput.m_WantedWeapon = WEAPON_HAMMER + 1; if(!g_Config.m_ClDummyRestoreWeapon) { @@ -486,7 +485,7 @@ void CGameClient::OnConnected() CTile *pGameTiles = static_cast(Layers()->Map()->GetData(Layers()->GameLayer()->m_Data)); // get flag positions - for(int i = 0; i < m_Collision.GetWidth()*m_Collision.GetHeight(); i++) + for(int i = 0; i < m_Collision.GetWidth() * m_Collision.GetHeight(); i++) { if(pGameTiles[i].m_Index - ENTITY_OFFSET == ENTITY_FLAGSTAND_RED) CRaceHelper::ms_aFlagIndex[TEAM_RED] = i; @@ -551,7 +550,6 @@ void CGameClient::OnReset() m_ReceivedDDNetPlayer = false; } - void CGameClient::UpdatePositions() { // local character position @@ -559,7 +557,7 @@ void CGameClient::UpdatePositions() { if(!AntiPingPlayers()) { - if(!m_Snap.m_pLocalCharacter || (m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + if(!m_Snap.m_pLocalCharacter || (m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER)) { // don't use predicted } @@ -568,13 +566,13 @@ void CGameClient::UpdatePositions() } else { - if(!(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + if(!(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER)) { if(m_Snap.m_pLocalCharacter) m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick(g_Config.m_ClDummy)); } - // else - // m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick(g_Config.m_ClDummy)); + // else + // m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick(g_Config.m_ClDummy)); } } else if(m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter) @@ -599,7 +597,7 @@ void CGameClient::UpdatePositions() { if(m_Snap.m_pPrevSpectatorInfo && m_Snap.m_pPrevSpectatorInfo->m_SpectatorID == m_Snap.m_pSpectatorInfo->m_SpectatorID) m_Snap.m_SpecInfo.m_Position = mix(vec2(m_Snap.m_pPrevSpectatorInfo->m_X, m_Snap.m_pPrevSpectatorInfo->m_Y), - vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), Client()->IntraGameTick(g_Config.m_ClDummy)); else m_Snap.m_SpecInfo.m_Position = vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y); m_Snap.m_SpecInfo.m_UsePosition = true; @@ -609,7 +607,6 @@ void CGameClient::UpdatePositions() UpdateRenderedCharacters(); } - static void Evolve(CNetObj_Character *pCharacter, int Tick) { CWorldCore TempWorld; @@ -640,7 +637,7 @@ void CGameClient::OnRender() // display gfx warnings if(g_Config.m_GfxShowWarnings == 1) { - SGraphicsWarning* pWarning = Graphics()->GetCurWarning(); + SGraphicsWarning *pWarning = Graphics()->GetCurWarning(); if(pWarning != NULL) { if(m_pMenus->CanDisplayWarning()) @@ -667,17 +664,18 @@ void CGameClient::OnRender() g_Config.m_ClDummy = 0; // resend player and dummy info if it was filtered by server - if(Client()->State() == IClient::STATE_ONLINE && !m_pMenus->IsActive()) { - if(m_CheckInfo[0] == 0) { + if(Client()->State() == IClient::STATE_ONLINE && !m_pMenus->IsActive()) + { + if(m_CheckInfo[0] == 0) + { if( - str_comp(m_aClients[m_LocalIDs[0]].m_aName, Client()->PlayerName()) || - str_comp(m_aClients[m_LocalIDs[0]].m_aClan, g_Config.m_PlayerClan) || - m_aClients[m_LocalIDs[0]].m_Country != g_Config.m_PlayerCountry || - str_comp(m_aClients[m_LocalIDs[0]].m_aSkinName, g_Config.m_ClPlayerSkin) || - m_aClients[m_LocalIDs[0]].m_UseCustomColor != g_Config.m_ClPlayerUseCustomColor || - m_aClients[m_LocalIDs[0]].m_ColorBody != (int)g_Config.m_ClPlayerColorBody || - m_aClients[m_LocalIDs[0]].m_ColorFeet != (int)g_Config.m_ClPlayerColorFeet - ) + str_comp(m_aClients[m_LocalIDs[0]].m_aName, Client()->PlayerName()) || + str_comp(m_aClients[m_LocalIDs[0]].m_aClan, g_Config.m_PlayerClan) || + m_aClients[m_LocalIDs[0]].m_Country != g_Config.m_PlayerCountry || + str_comp(m_aClients[m_LocalIDs[0]].m_aSkinName, g_Config.m_ClPlayerSkin) || + m_aClients[m_LocalIDs[0]].m_UseCustomColor != g_Config.m_ClPlayerUseCustomColor || + m_aClients[m_LocalIDs[0]].m_ColorBody != (int)g_Config.m_ClPlayerColorBody || + m_aClients[m_LocalIDs[0]].m_ColorFeet != (int)g_Config.m_ClPlayerColorFeet) SendInfo(false); else m_CheckInfo[0] = -1; @@ -686,17 +684,18 @@ void CGameClient::OnRender() if(m_CheckInfo[0] > 0) m_CheckInfo[0]--; - if(Client()->DummyConnected()) { - if(m_CheckInfo[1] == 0) { + if(Client()->DummyConnected()) + { + if(m_CheckInfo[1] == 0) + { if( - str_comp(m_aClients[m_LocalIDs[1]].m_aName, Client()->DummyName()) || - str_comp(m_aClients[m_LocalIDs[1]].m_aClan, g_Config.m_ClDummyClan) || - m_aClients[m_LocalIDs[1]].m_Country != g_Config.m_ClDummyCountry || - str_comp(m_aClients[m_LocalIDs[1]].m_aSkinName, g_Config.m_ClDummySkin) || - m_aClients[m_LocalIDs[1]].m_UseCustomColor != g_Config.m_ClDummyUseCustomColor || - m_aClients[m_LocalIDs[1]].m_ColorBody != (int)g_Config.m_ClDummyColorBody || - m_aClients[m_LocalIDs[1]].m_ColorFeet != (int)g_Config.m_ClDummyColorFeet - ) + str_comp(m_aClients[m_LocalIDs[1]].m_aName, Client()->DummyName()) || + str_comp(m_aClients[m_LocalIDs[1]].m_aClan, g_Config.m_ClDummyClan) || + m_aClients[m_LocalIDs[1]].m_Country != g_Config.m_ClDummyCountry || + str_comp(m_aClients[m_LocalIDs[1]].m_aSkinName, g_Config.m_ClDummySkin) || + m_aClients[m_LocalIDs[1]].m_UseCustomColor != g_Config.m_ClDummyUseCustomColor || + m_aClients[m_LocalIDs[1]].m_ColorBody != (int)g_Config.m_ClDummyColorBody || + m_aClients[m_LocalIDs[1]].m_ColorFeet != (int)g_Config.m_ClDummyColorFeet) SendDummyInfo(false); else m_CheckInfo[1] = -1; @@ -738,7 +737,7 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker, bool IsDummy) for(int k = 0; k < Num; k++) { CNetObj_Projectile Proj; - for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) + for(unsigned i = 0; i < sizeof(CNetObj_Projectile) / sizeof(int); i++) ((int *)&Proj)[i] = pUnpacker->GetInt(); if(pUnpacker->Error()) @@ -756,7 +755,7 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker, bool IsDummy) int *pParams = (int *)&NewTuning; // No jetpack on DDNet incompatible servers: NewTuning.m_JetpackStrength = 0; - for(unsigned i = 0; i < sizeof(CTuningParams)/sizeof(int); i++) + for(unsigned i = 0; i < sizeof(CTuningParams) / sizeof(int); i++) { int value = pUnpacker->GetInt(); @@ -785,16 +784,11 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker, bool IsDummy) if(IsDummy) { - if(MsgId == NETMSGTYPE_SV_CHAT - && m_LocalIDs[0] >= 0 - && m_LocalIDs[1] >= 0) + if(MsgId == NETMSGTYPE_SV_CHAT && m_LocalIDs[0] >= 0 && m_LocalIDs[1] >= 0) { CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; - if((pMsg->m_Team == 1 - && (m_aClients[m_LocalIDs[0]].m_Team != m_aClients[m_LocalIDs[1]].m_Team - || m_Teams.Team(m_LocalIDs[0]) != m_Teams.Team(m_LocalIDs[1]))) - || pMsg->m_Team > 1) + if((pMsg->m_Team == 1 && (m_aClients[m_LocalIDs[0]].m_Team != m_aClients[m_LocalIDs[1]].m_Team || m_Teams.Team(m_LocalIDs[0]) != m_Teams.Team(m_LocalIDs[1]))) || pMsg->m_Team > 1) { m_pChat->OnMessage(MsgId, pRawMsg); } @@ -937,7 +931,7 @@ void CGameClient::OnWindowResize() void CGameClient::OnWindowResizeCB(void *pUser) { - CGameClient *pClient = (CGameClient*)pUser; + CGameClient *pClient = (CGameClient *)pUser; pClient->OnWindowResize(); } @@ -1089,39 +1083,39 @@ static CGameInfo GetGameInfo(const CNetObj_GameInfoEx *pInfoEx, int InfoExSize, if(Version >= 0) { - Info.m_TimeScore = Flags&GAMEINFOFLAG_TIMESCORE; + Info.m_TimeScore = Flags & GAMEINFOFLAG_TIMESCORE; } if(Version >= 2) { - Info.m_FlagStartsRace = Flags&GAMEINFOFLAG_FLAG_STARTS_RACE; - Info.m_UnlimitedAmmo = Flags&GAMEINFOFLAG_UNLIMITED_AMMO; - Info.m_DDRaceRecordMessage = Flags&GAMEINFOFLAG_DDRACE_RECORD_MESSAGE; - Info.m_RaceRecordMessage = Flags&GAMEINFOFLAG_RACE_RECORD_MESSAGE; - Info.m_AllowEyeWheel = Flags&GAMEINFOFLAG_ALLOW_EYE_WHEEL; - Info.m_AllowHookColl = Flags&GAMEINFOFLAG_ALLOW_HOOK_COLL; - Info.m_AllowZoom = Flags&GAMEINFOFLAG_ALLOW_ZOOM; - Info.m_BugDDRaceGhost = Flags&GAMEINFOFLAG_BUG_DDRACE_GHOST; - Info.m_BugDDRaceInput = Flags&GAMEINFOFLAG_BUG_DDRACE_INPUT; - Info.m_BugFNGLaserRange = Flags&GAMEINFOFLAG_BUG_FNG_LASER_RANGE; - Info.m_BugVanillaBounce = Flags&GAMEINFOFLAG_BUG_VANILLA_BOUNCE; - Info.m_PredictFNG = Flags&GAMEINFOFLAG_PREDICT_FNG; - Info.m_PredictDDRace = Flags&GAMEINFOFLAG_PREDICT_DDRACE; - Info.m_PredictDDRaceTiles = Flags&GAMEINFOFLAG_PREDICT_DDRACE_TILES; - Info.m_PredictVanilla = Flags&GAMEINFOFLAG_PREDICT_VANILLA; - Info.m_EntitiesDDNet = Flags&GAMEINFOFLAG_ENTITIES_DDNET; - Info.m_EntitiesDDRace = Flags&GAMEINFOFLAG_ENTITIES_DDRACE; - Info.m_EntitiesRace = Flags&GAMEINFOFLAG_ENTITIES_RACE; - Info.m_EntitiesFNG = Flags&GAMEINFOFLAG_ENTITIES_FNG; - Info.m_EntitiesVanilla = Flags&GAMEINFOFLAG_ENTITIES_VANILLA; + Info.m_FlagStartsRace = Flags & GAMEINFOFLAG_FLAG_STARTS_RACE; + Info.m_UnlimitedAmmo = Flags & GAMEINFOFLAG_UNLIMITED_AMMO; + Info.m_DDRaceRecordMessage = Flags & GAMEINFOFLAG_DDRACE_RECORD_MESSAGE; + Info.m_RaceRecordMessage = Flags & GAMEINFOFLAG_RACE_RECORD_MESSAGE; + Info.m_AllowEyeWheel = Flags & GAMEINFOFLAG_ALLOW_EYE_WHEEL; + Info.m_AllowHookColl = Flags & GAMEINFOFLAG_ALLOW_HOOK_COLL; + Info.m_AllowZoom = Flags & GAMEINFOFLAG_ALLOW_ZOOM; + Info.m_BugDDRaceGhost = Flags & GAMEINFOFLAG_BUG_DDRACE_GHOST; + Info.m_BugDDRaceInput = Flags & GAMEINFOFLAG_BUG_DDRACE_INPUT; + Info.m_BugFNGLaserRange = Flags & GAMEINFOFLAG_BUG_FNG_LASER_RANGE; + Info.m_BugVanillaBounce = Flags & GAMEINFOFLAG_BUG_VANILLA_BOUNCE; + Info.m_PredictFNG = Flags & GAMEINFOFLAG_PREDICT_FNG; + Info.m_PredictDDRace = Flags & GAMEINFOFLAG_PREDICT_DDRACE; + Info.m_PredictDDRaceTiles = Flags & GAMEINFOFLAG_PREDICT_DDRACE_TILES; + Info.m_PredictVanilla = Flags & GAMEINFOFLAG_PREDICT_VANILLA; + Info.m_EntitiesDDNet = Flags & GAMEINFOFLAG_ENTITIES_DDNET; + Info.m_EntitiesDDRace = Flags & GAMEINFOFLAG_ENTITIES_DDRACE; + Info.m_EntitiesRace = Flags & GAMEINFOFLAG_ENTITIES_RACE; + Info.m_EntitiesFNG = Flags & GAMEINFOFLAG_ENTITIES_FNG; + Info.m_EntitiesVanilla = Flags & GAMEINFOFLAG_ENTITIES_VANILLA; } if(Version >= 3) { - Info.m_Race = Flags&GAMEINFOFLAG_RACE; - Info.m_DontMaskEntities = Flags&GAMEINFOFLAG_DONT_MASK_ENTITIES; + Info.m_Race = Flags & GAMEINFOFLAG_RACE; + Info.m_DontMaskEntities = Flags & GAMEINFOFLAG_DONT_MASK_ENTITIES; } if(Version >= 4) { - Info.m_EntitiesBW = Flags&GAMEINFOFLAG_ENTITIES_BW; + Info.m_EntitiesBW = Flags & GAMEINFOFLAG_ENTITIES_BW; } if(Version >= 5) { @@ -1168,16 +1162,16 @@ void CGameClient::OnNewSnapshot() #ifdef CONF_DEBUG if(g_Config.m_DbgStress) { - if((Client()->GameTick(g_Config.m_ClDummy)%100) == 0) + if((Client()->GameTick(g_Config.m_ClDummy) % 100) == 0) { char aMessage[64]; - int MsgLen = rand()%(sizeof(aMessage)-1); + int MsgLen = rand() % (sizeof(aMessage) - 1); for(int i = 0; i < MsgLen; i++) aMessage[i] = (char)('a' + (rand() % ('z' - 'a'))); aMessage[MsgLen] = 0; CNetMsg_Cl_Say Msg; - Msg.m_Team = rand()&1; + Msg.m_Team = rand() & 1; Msg.m_pMessage = aMessage; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } @@ -1234,13 +1228,12 @@ void CGameClient::OnNewSnapshot() else { pClient->m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(pClient->m_SkinID)->m_OrgTexture; - pClient->m_SkinInfo.m_ColorBody = ColorRGBA(1,1,1); - pClient->m_SkinInfo.m_ColorFeet = ColorRGBA(1,1,1); + pClient->m_SkinInfo.m_ColorBody = ColorRGBA(1, 1, 1); + pClient->m_SkinInfo.m_ColorFeet = ColorRGBA(1, 1, 1); } pClient->UpdateRenderInfo(); } - } else if(Item.m_Type == NETOBJTYPE_PLAYERINFO) { @@ -1275,7 +1268,6 @@ void CGameClient::OnNewSnapshot() else if(m_aStats[pInfo->m_ClientID].IsActive()) m_aStats[pInfo->m_ClientID].JoinSpec(Client()->GameTick(g_Config.m_ClDummy)); } - } else if(Item.m_Type == NETOBJTYPE_DDNETPLAYER) { @@ -1391,10 +1383,10 @@ void CGameClient::OnNewSnapshot() // Reset statboard when new round is started (RoundStartTick changed) // New round is usually started after `restart` on server if(m_Snap.m_pGameInfoObj->m_RoundStartTick != m_LastRoundStartTick - // In GamePaused or GameOver state RoundStartTick is updated on each tick - // hence no need to reset stats until player leaves GameOver - // and it would be a mistake to reset stats after or during the pause - && !(CurrentTickGameOver || m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED || s_GamePaused)) + // In GamePaused or GameOver state RoundStartTick is updated on each tick + // hence no need to reset stats until player leaves GameOver + // and it would be a mistake to reset stats after or during the pause + && !(CurrentTickGameOver || m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED || s_GamePaused)) m_pStatboard->OnReset(); m_LastRoundStartTick = m_Snap.m_pGameInfoObj->m_RoundStartTick; s_GameOver = CurrentTickGameOver; @@ -1421,14 +1413,14 @@ void CGameClient::OnNewSnapshot() m_FlagDropTick[TEAM_RED] = Client()->GameTick(g_Config.m_ClDummy); } else if(m_FlagDropTick[TEAM_RED] != 0) - m_FlagDropTick[TEAM_RED] = 0; + m_FlagDropTick[TEAM_RED] = 0; if(m_Snap.m_pGameDataObj->m_FlagCarrierBlue == FLAG_TAKEN) { if(m_FlagDropTick[TEAM_BLUE] == 0) m_FlagDropTick[TEAM_BLUE] = Client()->GameTick(g_Config.m_ClDummy); } else if(m_FlagDropTick[TEAM_BLUE] != 0) - m_FlagDropTick[TEAM_BLUE] = 0; + m_FlagDropTick[TEAM_BLUE] = 0; if(m_LastFlagCarrierRed == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierRed >= 0) OnFlagGrab(TEAM_RED); else if(m_LastFlagCarrierBlue == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierBlue >= 0) @@ -1438,7 +1430,7 @@ void CGameClient::OnNewSnapshot() m_LastFlagCarrierBlue = m_Snap.m_pGameDataObj->m_FlagCarrierBlue; } else if(Item.m_Type == NETOBJTYPE_FLAG) - m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData; + m_Snap.m_paFlags[Item.m_ID % 2] = (const CNetObj_Flag *)pData; } } @@ -1496,24 +1488,19 @@ void CGameClient::OnNewSnapshot() for(int i = 0; i < MAX_CLIENTS; ++i) { // update friend state - m_aClients[i].m_Friend = !(i == m_Snap.m_LocalClientID - || !m_Snap.m_paPlayerInfos[i] - || !Friends()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)); + m_aClients[i].m_Friend = !(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Friends()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)); // update foe state - m_aClients[i].m_Foe = !(i == m_Snap.m_LocalClientID - || !m_Snap.m_paPlayerInfos[i] - || !Foes()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)); + m_aClients[i].m_Foe = !(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Foes()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)); } // sort player infos by name mem_copy(m_Snap.m_paInfoByName, m_Snap.m_paPlayerInfos, sizeof(m_Snap.m_paInfoByName)); std::stable_sort(m_Snap.m_paInfoByName, m_Snap.m_paInfoByName + MAX_CLIENTS, - [this](const CNetObj_PlayerInfo* p1, const CNetObj_PlayerInfo* p2) -> bool - { - if (!p2) + [this](const CNetObj_PlayerInfo *p1, const CNetObj_PlayerInfo *p2) -> bool { + if(!p2) return static_cast(p1); - if (!p1) + if(!p1) return false; return str_comp_nocase(m_aClients[p1->m_ClientID].m_aName, m_aClients[p2->m_ClientID].m_aName) < 0; }); @@ -1523,11 +1510,10 @@ void CGameClient::OnNewSnapshot() // sort player infos by score mem_copy(m_Snap.m_paInfoByScore, m_Snap.m_paInfoByName, sizeof(m_Snap.m_paInfoByScore)); std::stable_sort(m_Snap.m_paInfoByScore, m_Snap.m_paInfoByScore + MAX_CLIENTS, - [TimeScore](const CNetObj_PlayerInfo* p1, const CNetObj_PlayerInfo* p2) -> bool - { - if (!p2) + [TimeScore](const CNetObj_PlayerInfo *p1, const CNetObj_PlayerInfo *p2) -> bool { + if(!p2) return static_cast(p1); - if (!p1) + if(!p1) return false; return (((TimeScore && p1->m_Score == -9999) ? std::numeric_limits::min() : p1->m_Score) > ((TimeScore && p2->m_Score == -9999) ? std::numeric_limits::min() : p2->m_Score)); @@ -1580,9 +1566,9 @@ void CGameClient::OnNewSnapshot() { CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = (int *)&m_Tuning[g_Config.m_ClDummy]; - for(unsigned i = 0; i < sizeof(m_Tuning[0])/sizeof(int); i++) + for(unsigned i = 0; i < sizeof(m_Tuning[0]) / sizeof(int); i++) Msg.AddInt(pParams[i]); - Client()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND); + Client()->SendMsg(&Msg, MSGFLAG_RECORD | MSGFLAG_NOSEND); } if(!m_DDRaceMsgSent[0] && m_Snap.m_pLocalInfo) @@ -1617,9 +1603,12 @@ void CGameClient::OnNewSnapshot() static float LastScreenAspect = .0; static bool LastDummyConnected = false; float ZoomToSend = m_pCamera->m_ZoomSmoothingTarget == .0 ? m_pCamera->m_Zoom // Initial - : m_pCamera->m_ZoomSmoothingTarget > m_pCamera->m_Zoom ? m_pCamera->m_ZoomSmoothingTarget // Zooming out - : m_pCamera->m_ZoomSmoothingTarget < m_pCamera->m_Zoom ? LastZoom // Zooming in - : m_pCamera->m_Zoom; // Not zooming + : + m_pCamera->m_ZoomSmoothingTarget > m_pCamera->m_Zoom ? m_pCamera->m_ZoomSmoothingTarget // Zooming out + : + m_pCamera->m_ZoomSmoothingTarget < m_pCamera->m_Zoom ? LastZoom // Zooming in + : + m_pCamera->m_Zoom; // Not zooming if(ZoomToSend != LastZoom || Graphics()->ScreenAspect() != LastScreenAspect || (Client()->DummyConnected() && !LastDummyConnected)) { CNetMsg_Cl_ShowDistance Msg; @@ -1643,12 +1632,12 @@ void CGameClient::OnNewSnapshot() // detect air jump for unpredicted players for(int i = 0; i < MAX_CLIENTS; i++) - if(m_Snap.m_aCharacters[i].m_Active && (m_Snap.m_aCharacters[i].m_Cur.m_Jumped&2) && !(m_Snap.m_aCharacters[i].m_Prev.m_Jumped&2)) + if(m_Snap.m_aCharacters[i].m_Active && (m_Snap.m_aCharacters[i].m_Cur.m_Jumped & 2) && !(m_Snap.m_aCharacters[i].m_Prev.m_Jumped & 2)) if(!Predict() || (!AntiPingPlayers() && i != m_Snap.m_LocalClientID)) { vec2 Pos = mix(vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), - vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), - Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), + Client()->IntraGameTick(g_Config.m_ClDummy)); m_pEffects->AirJump(Pos); } @@ -1674,7 +1663,7 @@ void CGameClient::OnPredict() return; // don't predict anything if we are paused - if(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + if(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_PAUSED) { if(m_Snap.m_pLocalCharacter) { @@ -1724,12 +1713,12 @@ void CGameClient::OnPredict() } // optionally allow some movement in freeze by not predicting freeze the last one to two ticks - if(g_Config.m_ClPredictFreeze == 2 && Client()->PredGameTick(g_Config.m_ClDummy) - 1 - Client()->PredGameTick(g_Config.m_ClDummy)%2 <= Tick) + if(g_Config.m_ClPredictFreeze == 2 && Client()->PredGameTick(g_Config.m_ClDummy) - 1 - Client()->PredGameTick(g_Config.m_ClDummy) % 2 <= Tick) pLocalChar->m_CanMoveInFreeze = true; // apply inputs and tick - CNetObj_PlayerInput *pInputData = (CNetObj_PlayerInput*) Client()->GetDirectInput(Tick, m_IsDummySwapping); - CNetObj_PlayerInput *pDummyInputData = !pDummyChar ? 0 : (CNetObj_PlayerInput*) Client()->GetDirectInput(Tick, m_IsDummySwapping^1); + CNetObj_PlayerInput *pInputData = (CNetObj_PlayerInput *)Client()->GetDirectInput(Tick, m_IsDummySwapping); + CNetObj_PlayerInput *pDummyInputData = !pDummyChar ? 0 : (CNetObj_PlayerInput *)Client()->GetDirectInput(Tick, m_IsDummySwapping ^ 1); bool DummyFirst = pInputData && pDummyInputData && pDummyChar->GetCID() < pLocalChar->GetCID(); if(DummyFirst) @@ -1769,28 +1758,28 @@ void CGameClient::OnPredict() vec2 Pos = pLocalChar->Core()->m_Pos; int Events = pLocalChar->Core()->m_TriggeredEvents; if(g_Config.m_ClPredict) - if(Events&COREEVENT_AIR_JUMP) + if(Events & COREEVENT_AIR_JUMP) m_pEffects->AirJump(Pos); if(g_Config.m_SndGame) { - if(Events&COREEVENT_GROUND_JUMP) + if(Events & COREEVENT_GROUND_JUMP) m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos); - if(Events&COREEVENT_HOOK_ATTACH_GROUND) + if(Events & COREEVENT_HOOK_ATTACH_GROUND) m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_GROUND, 1.0f, Pos); - if(Events&COREEVENT_HOOK_HIT_NOHOOK) + if(Events & COREEVENT_HOOK_HIT_NOHOOK) m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_HOOK_NOATTACH, 1.0f, Pos); } } } // detect mispredictions of other players and make corrections smoother when possible - static vec2 s_aLastPos[MAX_CLIENTS] = {{0,0}}; + static vec2 s_aLastPos[MAX_CLIENTS] = {{0, 0}}; static bool s_aLastActive[MAX_CLIENTS] = {0}; - if(g_Config.m_ClAntiPingSmooth && Predict() && AntiPingPlayers() && m_NewTick && abs(m_PredictedTick - Client()->PredGameTick(g_Config.m_ClDummy)) <= 1 && abs(Client()->GameTick(g_Config.m_ClDummy) - Client()->PrevGameTick(g_Config.m_ClDummy)) <= 2) + if(g_Config.m_ClAntiPingSmooth && Predict() && AntiPingPlayers() && m_NewTick && abs(m_PredictedTick - Client()->PredGameTick(g_Config.m_ClDummy)) <= 1 && abs(Client()->GameTick(g_Config.m_ClDummy) - Client()->PrevGameTick(g_Config.m_ClDummy)) <= 2) { int PredTime = clamp(Client()->GetPredictionTime(), 0, 800); - float SmoothPace = 4 - 1.5f * PredTime/800.f; // smoothing pace (a lower value will make the smoothing quicker) + float SmoothPace = 4 - 1.5f * PredTime / 800.f; // smoothing pace (a lower value will make the smoothing quicker) int64 Len = 1000 * PredTime * SmoothPace; for(int i = 0; i < MAX_CLIENTS; i++) @@ -1798,14 +1787,14 @@ void CGameClient::OnPredict() if(!m_Snap.m_aCharacters[i].m_Active || i == m_Snap.m_LocalClientID || !s_aLastActive[i]) continue; vec2 NewPos = (m_PredictedTick == Client()->PredGameTick(g_Config.m_ClDummy)) ? m_aClients[i].m_Predicted.m_Pos : m_aClients[i].m_PrevPredicted.m_Pos; - vec2 PredErr = (s_aLastPos[i] - NewPos)/(float)minimum(Client()->GetPredictionTime(), 200); + vec2 PredErr = (s_aLastPos[i] - NewPos) / (float)minimum(Client()->GetPredictionTime(), 200); if(in_range(length(PredErr), 0.05f, 5.f)) { vec2 PredPos = mix(m_aClients[i].m_PrevPredicted.m_Pos, m_aClients[i].m_Predicted.m_Pos, Client()->PredIntraGameTick(g_Config.m_ClDummy)); vec2 CurPos = mix( - vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), - vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), - Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), + vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), + Client()->IntraGameTick(g_Config.m_ClDummy)); vec2 RenderDiff = PredPos - aBeforeRender[i]; vec2 PredDiff = PredPos - CurPos; @@ -1819,20 +1808,19 @@ void CGameClient::OnPredict() if(fabs(RenderDiff[j]) > 0.01f) { MixAmount[j] = 1.f - clamp(RenderDiff[j] / PredDiff[j], 0.f, 1.f); - MixAmount[j] = 1.f - powf(1.f - MixAmount[j], 1/1.2f); + MixAmount[j] = 1.f - powf(1.f - MixAmount[j], 1 / 1.2f); } } int64 TimePassed = time_get() - m_aClients[i].m_SmoothStart[j]; - if(in_range(TimePassed, (int64)0, Len-1)) - MixAmount[j] = minimum(MixAmount[j], (float)(TimePassed/(double)Len)); - + if(in_range(TimePassed, (int64)0, Len - 1)) + MixAmount[j] = minimum(MixAmount[j], (float)(TimePassed / (double)Len)); } for(int j = 0; j < 2; j++) - if(fabs(RenderDiff[j]) < 0.01f && fabs(PredDiff[j]) < 0.01f && fabs(m_aClients[i].m_PrevPredicted.m_Pos[j] - m_aClients[i].m_Predicted.m_Pos[j]) < 0.01f && MixAmount[j] > MixAmount[j^1]) - MixAmount[j] = MixAmount[j^1]; + if(fabs(RenderDiff[j]) < 0.01f && fabs(PredDiff[j]) < 0.01f && fabs(m_aClients[i].m_PrevPredicted.m_Pos[j] - m_aClients[i].m_Predicted.m_Pos[j]) < 0.01f && MixAmount[j] > MixAmount[j ^ 1]) + MixAmount[j] = MixAmount[j ^ 1]; for(int j = 0; j < 2; j++) { - int64 Remaining = minimum((1.f-MixAmount[j])*Len, minimum(time_freq()*0.700f, (1.f-MixAmount[j^1])*Len + time_freq()*0.300f)); // don't smooth for longer than 700ms, or more than 300ms longer along one axis than the other axis + int64 Remaining = minimum((1.f - MixAmount[j]) * Len, minimum(time_freq() * 0.700f, (1.f - MixAmount[j ^ 1]) * Len + time_freq() * 0.300f)); // don't smooth for longer than 700ms, or more than 300ms longer along one axis than the other axis int64 Start = time_get() - (Len - Remaining); if(!in_range(Start + Len, m_aClients[i].m_SmoothStart[j], m_aClients[i].m_SmoothStart[j] + Len)) { @@ -1866,7 +1854,7 @@ void CGameClient::OnPredict() if(mem_comp(&Before, &Now, sizeof(CNetObj_CharacterCore)) != 0) { Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "prediction error"); - for(unsigned i = 0; i < sizeof(CNetObj_CharacterCore)/sizeof(int); i++) + for(unsigned i = 0; i < sizeof(CNetObj_CharacterCore) / sizeof(int); i++) if(((int *)&Before)[i] != ((int *)&Now)[i]) { char aBuf[256]; @@ -1916,7 +1904,7 @@ void CGameClient::CClientData::UpdateRenderInfo() m_RenderInfo = m_SkinInfo; // force team colors - if(g_GameClient.m_Snap.m_pGameInfoObj && g_GameClient.m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + if(g_GameClient.m_Snap.m_pGameInfoObj && g_GameClient.m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { m_RenderInfo.m_Texture = g_GameClient.m_pSkins->Get(m_SkinID)->m_ColorTexture; const int TeamColors[2] = {65461, 10223541}; @@ -1953,8 +1941,8 @@ void CGameClient::CClientData::Reset() m_Paused = false; m_Spec = false; m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(-1)->m_OrgTexture; - m_SkinInfo.m_ColorBody = ColorRGBA(1,1,1); - m_SkinInfo.m_ColorFeet = ColorRGBA(1,1,1); + m_SkinInfo.m_ColorBody = ColorRGBA(1, 1, 1); + m_SkinInfo.m_ColorFeet = ColorRGBA(1, 1, 1); m_Solo = false; m_Jetpack = false; @@ -2073,33 +2061,33 @@ void CGameClient::SendKill(int ClientID) void CGameClient::ConTeam(IConsole::IResult *pResult, void *pUserData) { - ((CGameClient*)pUserData)->SendSwitchTeam(pResult->GetInteger(0)); + ((CGameClient *)pUserData)->SendSwitchTeam(pResult->GetInteger(0)); } void CGameClient::ConKill(IConsole::IResult *pResult, void *pUserData) { - ((CGameClient*)pUserData)->SendKill(-1); + ((CGameClient *)pUserData)->SendKill(-1); } void CGameClient::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) - ((CGameClient*)pUserData)->SendInfo(false); + ((CGameClient *)pUserData)->SendInfo(false); } void CGameClient::ConchainSpecialDummyInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) - ((CGameClient*)pUserData)->SendDummyInfo(false); + ((CGameClient *)pUserData)->SendDummyInfo(false); } void CGameClient::ConchainSpecialDummy(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) - if(g_Config.m_ClDummy && !((CGameClient*)pUserData)->Client()->DummyConnected()) + if(g_Config.m_ClDummy && !((CGameClient *)pUserData)->Client()->DummyConnected()) g_Config.m_ClDummy = 0; } @@ -2109,7 +2097,7 @@ void CGameClient::ConchainClTextEntitiesSize(IConsole::IResult *pResult, void *p if(pResult->NumArguments()) { - CGameClient *pGameClient = (CGameClient*)pUserData; + CGameClient *pGameClient = (CGameClient *)pUserData; pGameClient->m_pMapimages->SetTextureScale(g_Config.m_ClTextEntitiesSize); } } @@ -2119,7 +2107,7 @@ IGameClient *CreateGameClient() return &g_GameClient; } -int CGameClient::IntersectCharacter(vec2 HookPos, vec2 NewPos, vec2& NewPos2, int ownID) +int CGameClient::IntersectCharacter(vec2 HookPos, vec2 NewPos, vec2 &NewPos2, int ownID) { float PhysSize = 28.0f; float Distance = 0.0f; @@ -2250,10 +2238,10 @@ void CGameClient::UpdatePrediction() { for(int Tick = m_GameWorld.GameTick() + 1; Tick <= Client()->GameTick(g_Config.m_ClDummy); Tick++) { - CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput*) Client()->GetDirectInput(Tick); + CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetDirectInput(Tick); CNetObj_PlayerInput *pDummyInput = 0; if(pDummyChar) - pDummyInput = (CNetObj_PlayerInput*) Client()->GetDirectInput(Tick, 1); + pDummyInput = (CNetObj_PlayerInput *)Client()->GetDirectInput(Tick, 1); if(pInput) pLocalChar->OnDirectInput(pInput); if(pDummyInput) @@ -2278,10 +2266,10 @@ void CGameClient::UpdatePrediction() // skip to current gametick m_GameWorld.m_GameTick = Client()->GameTick(g_Config.m_ClDummy); if(pLocalChar) - if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput*) Client()->GetInput(Client()->GameTick(g_Config.m_ClDummy))) + if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetInput(Client()->GameTick(g_Config.m_ClDummy))) pLocalChar->SetInput(pInput); if(pDummyChar) - if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput*) Client()->GetInput(Client()->GameTick(g_Config.m_ClDummy), 1)) + if(CNetObj_PlayerInput *pInput = (CNetObj_PlayerInput *)Client()->GetInput(Client()->GameTick(g_Config.m_ClDummy), 1)) pDummyChar->SetInput(pInput); } @@ -2301,10 +2289,10 @@ void CGameClient::UpdatePrediction() if(m_Snap.m_aCharacters[i].m_Active) { bool IsLocal = (i == m_Snap.m_LocalClientID || (PredictDummy() && i == m_PredictedDummyID)); - int GameTeam = (m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) ? m_aClients[i].m_Team : i; + int GameTeam = (m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) ? m_aClients[i].m_Team : i; m_GameWorld.NetCharAdd(i, &m_Snap.m_aCharacters[i].m_Cur, - m_Snap.m_aCharacters[i].m_HasExtendedData ? &m_Snap.m_aCharacters[i].m_ExtendedData : 0, - GameTeam, IsLocal); + m_Snap.m_aCharacters[i].m_HasExtendedData ? &m_Snap.m_aCharacters[i].m_ExtendedData : 0, + GameTeam, IsLocal); } for(int Index = 0; Index < Num; Index++) { @@ -2334,9 +2322,9 @@ void CGameClient::UpdateRenderedCharacters() m_aClients[i].m_IsPredicted = false; m_aClients[i].m_IsPredictedLocal = false; vec2 UnpredPos = mix( - vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), - vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), - Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), + vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), + Client()->IntraGameTick(g_Config.m_ClDummy)); vec2 Pos = UnpredPos; if(Predict() && (i == m_Snap.m_LocalClientID || AntiPingPlayers())) @@ -2347,9 +2335,9 @@ void CGameClient::UpdateRenderedCharacters() m_aClients[i].m_IsPredicted = true; Pos = mix( - vec2(m_aClients[i].m_RenderPrev.m_X, m_aClients[i].m_RenderPrev.m_Y), - vec2(m_aClients[i].m_RenderCur.m_X, m_aClients[i].m_RenderCur.m_Y), - m_aClients[i].m_IsPredicted ? Client()->PredIntraGameTick(g_Config.m_ClDummy) : Client()->IntraGameTick(g_Config.m_ClDummy)); + vec2(m_aClients[i].m_RenderPrev.m_X, m_aClients[i].m_RenderPrev.m_Y), + vec2(m_aClients[i].m_RenderCur.m_X, m_aClients[i].m_RenderCur.m_Y), + m_aClients[i].m_IsPredicted ? Client()->PredIntraGameTick(g_Config.m_ClDummy) : Client()->IntraGameTick(g_Config.m_ClDummy)); if(i == m_Snap.m_LocalClientID) { @@ -2371,7 +2359,6 @@ void CGameClient::UpdateRenderedCharacters() if(g_Config.m_ClAntiPingSmooth) Pos = GetSmoothPos(i); } - } m_Snap.m_aCharacters[i].m_Position = Pos; m_aClients[i].m_RenderPos = Pos; @@ -2391,10 +2378,9 @@ void CGameClient::DetectStrongHook() int ToPlayer = m_Snap.m_aCharacters[FromPlayer].m_Prev.m_HookedPlayer; if(ToPlayer < 0 || ToPlayer >= MAX_CLIENTS || !m_Snap.m_aCharacters[ToPlayer].m_Active || ToPlayer != m_Snap.m_aCharacters[FromPlayer].m_Cur.m_HookedPlayer) continue; - if(abs(minimum(s_LastUpdateTick[ToPlayer], s_LastUpdateTick[FromPlayer]) - Client()->GameTick(g_Config.m_ClDummy)) < SERVER_TICK_SPEED/4) + if(abs(minimum(s_LastUpdateTick[ToPlayer], s_LastUpdateTick[FromPlayer]) - Client()->GameTick(g_Config.m_ClDummy)) < SERVER_TICK_SPEED / 4) continue; - if(m_Snap.m_aCharacters[FromPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[FromPlayer].m_Cur.m_Direction - || m_Snap.m_aCharacters[ToPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[ToPlayer].m_Cur.m_Direction) + if(m_Snap.m_aCharacters[FromPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[FromPlayer].m_Cur.m_Direction || m_Snap.m_aCharacters[ToPlayer].m_Prev.m_Direction != m_Snap.m_aCharacters[ToPlayer].m_Cur.m_Direction) continue; CCharacter *pFromCharWorld = m_GameWorld.GetCharacterByID(FromPlayer); @@ -2473,16 +2459,16 @@ vec2 CGameClient::GetSmoothPos(int ClientID) int64 Now = time_get(); for(int i = 0; i < 2; i++) { - int64 Len = clamp(m_aClients[ClientID].m_SmoothLen[i], (int64) 1, time_freq()); + int64 Len = clamp(m_aClients[ClientID].m_SmoothLen[i], (int64)1, time_freq()); int64 TimePassed = Now - m_aClients[ClientID].m_SmoothStart[i]; - if(in_range(TimePassed, (int64)0, Len-1)) + if(in_range(TimePassed, (int64)0, Len - 1)) { - float MixAmount = 1.f - powf(1.f - TimePassed/(float)Len, 1.2f); + float MixAmount = 1.f - powf(1.f - TimePassed / (float)Len, 1.2f); int SmoothTick; float SmoothIntra; Client()->GetSmoothTick(&SmoothTick, &SmoothIntra, MixAmount); - if(SmoothTick > 0 && m_aClients[ClientID].m_PredTick[(SmoothTick-1) % 200] >= Client()->PrevGameTick(g_Config.m_ClDummy) && m_aClients[ClientID].m_PredTick[SmoothTick % 200] <= Client()->PredGameTick(g_Config.m_ClDummy)) - Pos[i] = mix(m_aClients[ClientID].m_PredPos[(SmoothTick-1) % 200][i], m_aClients[ClientID].m_PredPos[SmoothTick % 200][i], SmoothIntra); + if(SmoothTick > 0 && m_aClients[ClientID].m_PredTick[(SmoothTick - 1) % 200] >= Client()->PrevGameTick(g_Config.m_ClDummy) && m_aClients[ClientID].m_PredTick[SmoothTick % 200] <= Client()->PredGameTick(g_Config.m_ClDummy)) + Pos[i] = mix(m_aClients[ClientID].m_PredPos[(SmoothTick - 1) % 200][i], m_aClients[ClientID].m_PredPos[SmoothTick % 200][i], SmoothIntra); } } return Pos; @@ -2543,7 +2529,7 @@ void CGameClient::LoadMapSettings() int Size = pMap->GetDataSize(pItem->m_Settings); char *pSettings = (char *)pMap->GetData(pItem->m_Settings); char *pNext = pSettings; - dbg_msg("New tune ","%s", pNext); + dbg_msg("New tune ", "%s", pNext); while(pNext < pSettings + Size) { int StrSize = str_length(pNext) + 1; diff --git a/src/game/client/gameclient.h b/src/game/client/gameclient.h index c484ac91b..340cbfa90 100644 --- a/src/game/client/gameclient.h +++ b/src/game/client/gameclient.h @@ -3,22 +3,22 @@ #ifndef GAME_CLIENT_GAMECLIENT_H #define GAME_CLIENT_GAMECLIENT_H +#include "render.h" #include #include #include #include #include +#include #include #include -#include -#include "render.h" #include -#include #include #include #include +#include class CGameInfo { @@ -146,10 +146,16 @@ public: class IFriends *Friends() { return m_pFriends; } class IFriends *Foes() { return m_pFoes; } #if defined(CONF_AUTOUPDATE) - class IUpdater *Updater() { return m_pUpdater; } + class IUpdater *Updater() + { + return m_pUpdater; + } #endif - int NetobjNumCorrections() { return m_NetObjHandler.NumObjCorrections(); } + int NetobjNumCorrections() + { + return m_NetObjHandler.NumObjCorrections(); + } const char *NetobjCorrectedOn() { return m_NetObjHandler.CorrectedObjOn(); } bool m_SuppressEvents; @@ -162,7 +168,7 @@ public: enum { - SERVERMODE_PURE=0, + SERVERMODE_PURE = 0, SERVERMODE_MOD, SERVERMODE_PUREMOD, }; @@ -263,7 +269,6 @@ public: int m_FreezeEnd; bool m_DeepFrozen; - CCharacterCore m_Predicted; CCharacterCore m_PrevPredicted; @@ -327,8 +332,16 @@ public: void Reset(); bool IsActive() const { return m_Active; } - void JoinGame(int Tick) { m_Active = true; m_JoinTick = Tick; }; - void JoinSpec(int Tick) { m_Active = false; m_IngameTicks += Tick - m_JoinTick; }; + void JoinGame(int Tick) + { + m_Active = true; + m_JoinTick = Tick; + }; + void JoinSpec(int Tick) + { + m_Active = false; + m_IngameTicks += Tick - m_JoinTick; + }; int GetIngameTicks(int Tick) const { return m_IngameTicks + Tick - m_JoinTick; }; float GetFPM(int Tick, int TickSpeed) const { return (float)(m_Frags * TickSpeed * 60) / GetIngameTicks(Tick); }; }; @@ -419,7 +432,7 @@ public: class CGhost *m_pGhost; class CTeamsCore m_Teams; - int IntersectCharacter(vec2 Pos0, vec2 Pos1, vec2& NewPos, int ownID); + int IntersectCharacter(vec2 Pos0, vec2 Pos1, vec2 &NewPos, int ownID); virtual int GetLastRaceTick(); @@ -427,7 +440,7 @@ public: bool AntiPingGrenade() { return g_Config.m_ClAntiPing && g_Config.m_ClAntiPingGrenade && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK; } bool AntiPingWeapons() { return g_Config.m_ClAntiPing && g_Config.m_ClAntiPingWeapons && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK; } bool AntiPingGunfire() { return AntiPingGrenade() && AntiPingWeapons() && g_Config.m_ClAntiPingGunfire; } - bool Predict() { return g_Config.m_ClPredict && !(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK && m_Snap.m_pLocalCharacter; } + bool Predict() { return g_Config.m_ClPredict && !(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags & GAMESTATEFLAG_GAMEOVER) && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK && m_Snap.m_pLocalCharacter; } bool PredictDummy() { return g_Config.m_ClPredictDummy && Client()->DummyConnected() && m_Snap.m_LocalClientID >= 0 && m_PredictedDummyID >= 0; } CGameWorld m_GameWorld; diff --git a/src/game/client/lineinput.cpp b/src/game/client/lineinput.cpp index 18779d84a..4257116e7 100644 --- a/src/game/client/lineinput.cpp +++ b/src/game/client/lineinput.cpp @@ -1,7 +1,7 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "lineinput.h" +#include CLineInput::CLineInput() { @@ -38,8 +38,8 @@ void CLineInput::Editing(const char *pString, int Cursor) int NewTextLen = str_length(Texting); int CharsLeft = (int)sizeof(m_DisplayStr) - str_length(m_DisplayStr) - 1; int FillCharLen = NewTextLen < CharsLeft ? NewTextLen : CharsLeft; - for(int i = str_length(m_DisplayStr) - 1; i >= m_CursorPos ; i--) - m_DisplayStr[i+FillCharLen] = m_DisplayStr[i]; + for(int i = str_length(m_DisplayStr) - 1; i >= m_CursorPos; i--) + m_DisplayStr[i + FillCharLen] = m_DisplayStr[i]; for(int i = 0; i < FillCharLen; i++) { if(Texting[i] == 28) @@ -70,7 +70,7 @@ bool CLineInput::Manipulate(IInput::CEvent Event, char *pStr, int StrMaxSize, in if(CursorPos > Len) CursorPos = Len; - if(Event.m_Flags&IInput::FLAG_TEXT) + if(Event.m_Flags & IInput::FLAG_TEXT) { // gather string stats int CharCount = 0; @@ -88,11 +88,11 @@ bool CLineInput::Manipulate(IInput::CEvent Event, char *pStr, int StrMaxSize, in // add new string if(CharCount) { - if(Len+CharSize < StrMaxSize && CursorPos+CharSize < StrMaxSize && NumChars+CharCount < StrMaxChars) + if(Len + CharSize < StrMaxSize && CursorPos + CharSize < StrMaxSize && NumChars + CharCount < StrMaxChars) { - mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len-CursorPos+1); // +1 == null term + mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len - CursorPos + 1); // +1 == null term for(int i = 0; i < CharSize; i++) - pStr[CursorPos+i] = Event.m_aText[i]; + pStr[CursorPos + i] = Event.m_aText[i]; CursorPos += CharSize; Len += CharSize; NumChars += CharCount; @@ -101,14 +101,14 @@ bool CLineInput::Manipulate(IInput::CEvent Event, char *pStr, int StrMaxSize, in } } - if(Event.m_Flags&IInput::FLAG_PRESS) + if(Event.m_Flags & IInput::FLAG_PRESS) { int Key = Event.m_Key; if(Key == KEY_BACKSPACE && CursorPos > 0) { int NewCursorPos = str_utf8_rewind(pStr, CursorPos); - int CharSize = CursorPos-NewCursorPos; - mem_move(pStr+NewCursorPos, pStr+CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term + int CharSize = CursorPos - NewCursorPos; + mem_move(pStr + NewCursorPos, pStr + CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term CursorPos = NewCursorPos; Len -= CharSize; if(CharSize > 0) @@ -118,7 +118,7 @@ bool CLineInput::Manipulate(IInput::CEvent Event, char *pStr, int StrMaxSize, in else if(Key == KEY_DELETE && CursorPos < Len) { int p = str_utf8_forward(pStr, CursorPos); - int CharSize = p-CursorPos; + int CharSize = p - CursorPos; mem_move(pStr + CursorPos, pStr + CursorPos + CharSize, Len - CursorPos - CharSize + 1); // +1 == null term Len -= CharSize; if(CharSize > 0) @@ -146,7 +146,8 @@ void CLineInput::DeleteUntilCursor() { char aBuf[MAX_SIZE]; str_copy(aBuf, &m_Str[m_CursorPos], sizeof(aBuf)); - Set(aBuf); SetCursorOffset(0); + Set(aBuf); + SetCursorOffset(0); } void CLineInput::DeleteFromCursor() diff --git a/src/game/client/lineinput.h b/src/game/client/lineinput.h index 428b6c005..a8d106349 100644 --- a/src/game/client/lineinput.h +++ b/src/game/client/lineinput.h @@ -10,17 +10,18 @@ class CLineInput { enum { - MAX_SIZE=512, - MAX_CHARS=MAX_SIZE/2, + MAX_SIZE = 512, + MAX_CHARS = MAX_SIZE / 2, }; char m_Str[MAX_SIZE]; int m_Len; int m_CursorPos; int m_NumChars; - char m_DisplayStr[MAX_SIZE+34]; + char m_DisplayStr[MAX_SIZE + 34]; int m_FakeLen; int m_FakeCursorPos; + public: static bool Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int StrMaxChars, int *pStrLenPtr, int *pCursorPosPtr, int *pNumCharsPtr); diff --git a/src/game/client/prediction/entities/character.cpp b/src/game/client/prediction/entities/character.cpp index 03122b2fb..cc5b0939a 100644 --- a/src/game/client/prediction/entities/character.cpp +++ b/src/game/client/prediction/entities/character.cpp @@ -1,12 +1,12 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include #include +#include #include "character.h" -#include "projectile.h" #include "laser.h" +#include "projectile.h" // Character, "physical" player's part @@ -31,13 +31,13 @@ void CCharacter::SetSolo(bool Solo) bool CCharacter::IsGrounded() { - if(Collision()->CheckPoint(m_Pos.x+m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + if(Collision()->CheckPoint(m_Pos.x + m_ProximityRadius / 2, m_Pos.y + m_ProximityRadius / 2 + 5)) return true; - if(Collision()->CheckPoint(m_Pos.x-m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + if(Collision()->CheckPoint(m_Pos.x - m_ProximityRadius / 2, m_Pos.y + m_ProximityRadius / 2 + 5)) return true; int MoveRestrictionsBelow = Collision()->GetMoveRestrictions(m_Pos + vec2(0, m_ProximityRadius / 2 + 4), 0.0f); - if(MoveRestrictionsBelow&CANTMOVE_DOWN) + if(MoveRestrictionsBelow & CANTMOVE_DOWN) { return true; } @@ -55,7 +55,7 @@ void CCharacter::HandleJetpack() bool FullAuto = false; if(m_Core.m_ActiveWeapon == WEAPON_GRENADE || m_Core.m_ActiveWeapon == WEAPON_SHOTGUN || m_Core.m_ActiveWeapon == WEAPON_LASER) FullAuto = true; - if (m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) + if(m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) FullAuto = true; // check if we gonna fire @@ -63,7 +63,7 @@ void CCharacter::HandleJetpack() if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; - if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + if(FullAuto && (m_LatestInput.m_Fire & 1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) WillFire = true; if(!WillFire) @@ -77,17 +77,17 @@ void CCharacter::HandleJetpack() switch(m_Core.m_ActiveWeapon) { - case WEAPON_GUN: + case WEAPON_GUN: + { + if(m_Jetpack) { - if (m_Jetpack) - { - float Strength = GetTuning(m_TuneZone)->m_JetpackStrength; - if(!m_TuneZone) - Strength = m_LastJetpackStrength; - TakeDamage(Direction * -1.0f * (Strength / 100.0f / 6.11f), 0, GetCID(), m_Core.m_ActiveWeapon); - } + float Strength = GetTuning(m_TuneZone)->m_JetpackStrength; + if(!m_TuneZone) + Strength = m_LastJetpackStrength; + TakeDamage(Direction * -1.0f * (Strength / 100.0f / 6.11f), 0, GetCID(), m_Core.m_ActiveWeapon); } } + } } void CCharacter::RemoveNinja() @@ -104,7 +104,7 @@ void CCharacter::HandleNinja() if(m_Core.m_ActiveWeapon != WEAPON_NINJA) return; - if ((GameWorld()->GameTick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * GameWorld()->GameTickSpeed() / 1000)) + if((GameWorld()->GameTick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * GameWorld()->GameTickSpeed() / 1000)) { // time's up, return RemoveNinja(); @@ -116,13 +116,13 @@ void CCharacter::HandleNinja() m_Ninja.m_CurrentMoveTime--; - if (m_Ninja.m_CurrentMoveTime == 0) + if(m_Ninja.m_CurrentMoveTime == 0) { // reset velocity - m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; + m_Core.m_Vel = m_Ninja.m_ActivationDir * m_Ninja.m_OldVelAmount; } - if (m_Ninja.m_CurrentMoveTime > 0) + if(m_Ninja.m_CurrentMoveTime > 0) { // Set velocity m_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity; @@ -138,37 +138,37 @@ void CCharacter::HandleNinja() vec2 Dir = m_Pos - OldPos; float Radius = m_ProximityRadius * 2.0f; vec2 Center = OldPos + Dir * 0.5f; - int Num = GameWorld()->FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + int Num = GameWorld()->FindEntities(Center, Radius, (CEntity **)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); // check that we're not in solo part - if (TeamsCore()->GetSolo(GetCID())) + if(TeamsCore()->GetSolo(GetCID())) return; - for (int i = 0; i < Num; ++i) + for(int i = 0; i < Num; ++i) { - if (aEnts[i] == this) + if(aEnts[i] == this) continue; // Don't hit players in other teams - if (Team() != aEnts[i]->Team()) + if(Team() != aEnts[i]->Team()) continue; // Don't hit players in solo parts - if (TeamsCore()->GetSolo(aEnts[i]->GetCID())) + if(TeamsCore()->GetSolo(aEnts[i]->GetCID())) return; // make sure we haven't Hit this object before bool bAlreadyHit = false; - for (int j = 0; j < m_NumObjectsHit; j++) + for(int j = 0; j < m_NumObjectsHit; j++) { - if (m_aHitObjects[j] == aEnts[i]->GetCID()) + if(m_aHitObjects[j] == aEnts[i]->GetCID()) bAlreadyHit = true; } - if (bAlreadyHit) + if(bAlreadyHit) continue; // check so we are sufficiently close - if (distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) + if(distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) continue; // Hit a player, give him damage and stuffs... @@ -208,11 +208,11 @@ void CCharacter::HandleWeaponSwitch() WantedWeapon = m_QueuedWeapon; bool Anything = false; - for(int i = 0; i < NUM_WEAPONS - 1; ++i) - if(m_aWeapons[i].m_Got) - Anything = true; - if(!Anything) - return; + for(int i = 0; i < NUM_WEAPONS - 1; ++i) + if(m_aWeapons[i].m_Got) + Anything = true; + if(!Anything) + return; // select Weapon int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses; int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses; @@ -221,7 +221,7 @@ void CCharacter::HandleWeaponSwitch() { while(Next) // Next Weapon selection { - WantedWeapon = (WantedWeapon+1)%NUM_WEAPONS; + WantedWeapon = (WantedWeapon + 1) % NUM_WEAPONS; if(m_aWeapons[WantedWeapon].m_Got) Next--; } @@ -231,7 +231,7 @@ void CCharacter::HandleWeaponSwitch() { while(Prev) // Prev Weapon selection { - WantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1; + WantedWeapon = (WantedWeapon - 1) < 0 ? NUM_WEAPONS - 1 : WantedWeapon - 1; if(m_aWeapons[WantedWeapon].m_Got) Prev--; } @@ -239,7 +239,7 @@ void CCharacter::HandleWeaponSwitch() // Direct Weapon selection if(m_LatestInput.m_WantedWeapon) - WantedWeapon = m_Input.m_WantedWeapon-1; + WantedWeapon = m_Input.m_WantedWeapon - 1; // check for insane values if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_Core.m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) @@ -279,7 +279,7 @@ void CCharacter::FireWeapon() if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; - if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + if(FullAuto && (m_LatestInput.m_Fire & 1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) WillFire = true; if(!WillFire) @@ -291,167 +291,169 @@ void CCharacter::FireWeapon() return; } - vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f; + vec2 ProjStartPos = m_Pos + Direction * m_ProximityRadius * 0.75f; switch(m_Core.m_ActiveWeapon) { - case WEAPON_HAMMER: + case WEAPON_HAMMER: + { + // reset objects Hit + m_NumObjectsHit = 0; + + if(m_Hit & DISABLE_HIT_HAMMER) + break; + + CCharacter *apEnts[MAX_CLIENTS]; + int Hits = 0; + int Num = GameWorld()->FindEntities(ProjStartPos, m_ProximityRadius * 0.5f, (CEntity **)apEnts, + MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + for(int i = 0; i < Num; ++i) { - // reset objects Hit - m_NumObjectsHit = 0; + CCharacter *pTarget = apEnts[i]; - if (m_Hit&DISABLE_HIT_HAMMER) break; + if((pTarget == this || (pTarget->IsAlive() && !CanCollide(pTarget->GetCID())))) + continue; - CCharacter *apEnts[MAX_CLIENTS]; - int Hits = 0; - int Num = GameWorld()->FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts, - MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + // set his velocity to fast upward (for now) - for (int i = 0; i < Num; ++i) + vec2 Dir; + if(length(pTarget->m_Pos - m_Pos) > 0.0f) + Dir = normalize(pTarget->m_Pos - m_Pos); + else + Dir = vec2(0.f, -1.f); + + float Strength = GetTuning(m_TuneZone)->m_HammerStrength; + + vec2 Temp = pTarget->m_Core.m_Vel + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f; + Temp = ClampVel(pTarget->m_MoveRestrictions, Temp); + Temp -= pTarget->m_Core.m_Vel; + + vec2 Force = vec2(0.f, -1.0f) + Temp; + + if(GameWorld()->m_WorldConfig.m_IsFNG) { - CCharacter *pTarget = apEnts[i]; - - if((pTarget == this || (pTarget->IsAlive() && !CanCollide(pTarget->GetCID())))) - continue; - - // set his velocity to fast upward (for now) - - vec2 Dir; - if (length(pTarget->m_Pos - m_Pos) > 0.0f) - Dir = normalize(pTarget->m_Pos - m_Pos); - else - Dir = vec2(0.f, -1.f); - - float Strength = GetTuning(m_TuneZone)->m_HammerStrength; - - vec2 Temp = pTarget->m_Core.m_Vel + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f; - Temp = ClampVel(pTarget->m_MoveRestrictions, Temp); - Temp -= pTarget->m_Core.m_Vel; - - vec2 Force = vec2(0.f, -1.0f) + Temp; - - if(GameWorld()->m_WorldConfig.m_IsFNG) + if(m_GameTeam == pTarget->m_GameTeam && pTarget->m_LastSnapWeapon == WEAPON_NINJA) // melt hammer { - if(m_GameTeam == pTarget->m_GameTeam && pTarget->m_LastSnapWeapon == WEAPON_NINJA) // melt hammer - { - Force.x *= 50 * 0.01f; - Force.y *= 50 * 0.01f; - } - else - { - Force.x *= 320 * 0.01f; - Force.y *= 120 * 0.01f; - } + Force.x *= 50 * 0.01f; + Force.y *= 50 * 0.01f; } else - Force *= Strength; - - pTarget->TakeDamage(Force, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, - GetCID(), m_Core.m_ActiveWeapon); - pTarget->UnFreeze(); - - Hits++; - } - - // if we Hit anything, we have to wait for the reload - if(Hits) - m_ReloadTimer = GameWorld()->GameTickSpeed()/3; - - } break; - - case WEAPON_GUN: - { - if (!m_Jetpack) - { - int Lifetime = (int)(GameWorld()->GameTickSpeed()*GetTuning(m_TuneZone)->m_GunLifetime); - - new CProjectile - ( - GameWorld(), - WEAPON_GUN,//Type - GetCID(),//Owner - ProjStartPos,//Pos - Direction,//Dir - Lifetime,//Span - 0,//Freeze - 0,//Explosive - 0,//Force - -1//SoundImpact - ); - } - } break; - - case WEAPON_SHOTGUN: - { - if(GameWorld()->m_WorldConfig.m_IsVanilla) - { - int ShotSpread = 2; - for(int i = -ShotSpread; i <= ShotSpread; ++i) { - float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f}; - float a = GetAngle(Direction); - a += Spreading[i+2]; - float v = 1-(absolute(i)/(float)ShotSpread); - float Speed = mix((float)Tuning()->m_ShotgunSpeeddiff, 1.0f, v); - new CProjectile - ( - GameWorld(), - WEAPON_SHOTGUN,//Type - GetCID(),//Owner - ProjStartPos,//Pos - vec2(cosf(a), sinf(a))*Speed,//Dir - (int)(GameWorld()->GameTickSpeed()*Tuning()->m_ShotgunLifetime),//Span - 0,//Freeze - 0,//Explosive - 0,//Force - -1//SoundImpact - ); + Force.x *= 320 * 0.01f; + Force.y *= 120 * 0.01f; } } - else if(GameWorld()->m_WorldConfig.m_IsDDRace) - { - float LaserReach = GetTuning(m_TuneZone)->m_LaserReach; + else + Force *= Strength; - new CLaser(GameWorld(), m_Pos, Direction, LaserReach, GetCID(), WEAPON_SHOTGUN); - } - } break; + pTarget->TakeDamage(Force, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, + GetCID(), m_Core.m_ActiveWeapon); + pTarget->UnFreeze(); - case WEAPON_GRENADE: + Hits++; + } + + // if we Hit anything, we have to wait for the reload + if(Hits) + m_ReloadTimer = GameWorld()->GameTickSpeed() / 3; + } + break; + + case WEAPON_GUN: + { + if(!m_Jetpack) { - int Lifetime = (int)(GameWorld()->GameTickSpeed()*GetTuning(m_TuneZone)->m_GrenadeLifetime); + int Lifetime = (int)(GameWorld()->GameTickSpeed() * GetTuning(m_TuneZone)->m_GunLifetime); - new CProjectile - ( + new CProjectile( + GameWorld(), + WEAPON_GUN, //Type + GetCID(), //Owner + ProjStartPos, //Pos + Direction, //Dir + Lifetime, //Span + 0, //Freeze + 0, //Explosive + 0, //Force + -1 //SoundImpact + ); + } + } + break; + + case WEAPON_SHOTGUN: + { + if(GameWorld()->m_WorldConfig.m_IsVanilla) + { + int ShotSpread = 2; + for(int i = -ShotSpread; i <= ShotSpread; ++i) + { + float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f}; + float a = GetAngle(Direction); + a += Spreading[i + 2]; + float v = 1 - (absolute(i) / (float)ShotSpread); + float Speed = mix((float)Tuning()->m_ShotgunSpeeddiff, 1.0f, v); + new CProjectile( GameWorld(), - WEAPON_GRENADE,//Type - GetCID(),//Owner - ProjStartPos,//Pos - Direction,//Dir - Lifetime,//Span - 0,//Freeze - true,//Explosive - 0,//Force - SOUND_GRENADE_EXPLODE//SoundImpact - );//SoundImpact - } break; - - case WEAPON_LASER: + WEAPON_SHOTGUN, //Type + GetCID(), //Owner + ProjStartPos, //Pos + vec2(cosf(a), sinf(a)) * Speed, //Dir + (int)(GameWorld()->GameTickSpeed() * Tuning()->m_ShotgunLifetime), //Span + 0, //Freeze + 0, //Explosive + 0, //Force + -1 //SoundImpact + ); + } + } + else if(GameWorld()->m_WorldConfig.m_IsDDRace) { float LaserReach = GetTuning(m_TuneZone)->m_LaserReach; - new CLaser(GameWorld(), m_Pos, Direction, LaserReach, GetCID(), WEAPON_LASER); - } break; + new CLaser(GameWorld(), m_Pos, Direction, LaserReach, GetCID(), WEAPON_SHOTGUN); + } + } + break; - case WEAPON_NINJA: - { - // reset Hit objects - m_NumObjectsHit = 0; + case WEAPON_GRENADE: + { + int Lifetime = (int)(GameWorld()->GameTickSpeed() * GetTuning(m_TuneZone)->m_GrenadeLifetime); - m_Ninja.m_ActivationDir = Direction; - m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * GameWorld()->GameTickSpeed() / 1000; - m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); - } break; + new CProjectile( + GameWorld(), + WEAPON_GRENADE, //Type + GetCID(), //Owner + ProjStartPos, //Pos + Direction, //Dir + Lifetime, //Span + 0, //Freeze + true, //Explosive + 0, //Force + SOUND_GRENADE_EXPLODE //SoundImpact + ); //SoundImpact + } + break; + case WEAPON_LASER: + { + float LaserReach = GetTuning(m_TuneZone)->m_LaserReach; + + new CLaser(GameWorld(), m_Pos, Direction, LaserReach, GetCID(), WEAPON_LASER); + } + break; + + case WEAPON_NINJA: + { + // reset Hit objects + m_NumObjectsHit = 0; + + m_Ninja.m_ActivationDir = Direction; + m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * GameWorld()->GameTickSpeed() / 1000; + m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); + } + break; } m_AttackTick = GameWorld()->GameTick(); @@ -488,9 +490,9 @@ void CCharacter::GiveNinja() { m_Ninja.m_ActivationTick = GameWorld()->GameTick(); m_aWeapons[WEAPON_NINJA].m_Got = true; - if (!m_FreezeTime) + if(!m_FreezeTime) m_aWeapons[WEAPON_NINJA].m_Ammo = -1; - if (m_Core.m_ActiveWeapon != WEAPON_NINJA) + if(m_Core.m_ActiveWeapon != WEAPON_NINJA) m_LastWeapon = m_Core.m_ActiveWeapon; m_Core.m_ActiveWeapon = WEAPON_NINJA; } @@ -498,7 +500,7 @@ void CCharacter::GiveNinja() void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput) { // skip the input if chat is active - if(pNewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) + if(pNewInput->m_PlayerFlags & PLAYERFLAG_CHATTING) return; // copy new input @@ -515,7 +517,7 @@ void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput) void CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput) { // skip the input if chat is active - if(pNewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) + if(pNewInput->m_PlayerFlags & PLAYERFLAG_CHATTING) { // reset input ResetInput(); @@ -542,14 +544,14 @@ void CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput) void CCharacter::ResetInput() { - m_Input.m_Direction = 0; - //m_Input.m_Hook = 0; - // simulate releasing the fire button - if((m_Input.m_Fire&1) != 0) - m_Input.m_Fire++; - m_Input.m_Fire &= INPUT_STATE_MASK; - m_Input.m_Jump = 0; - m_LatestPrevInput = m_LatestInput = m_Input; + m_Input.m_Direction = 0; + //m_Input.m_Hook = 0; + // simulate releasing the fire button + if((m_Input.m_Fire & 1) != 0) + m_Input.m_Fire++; + m_Input.m_Fire &= INPUT_STATE_MASK; + m_Input.m_Jump = 0; + m_LatestPrevInput = m_LatestInput = m_Input; } void CCharacter::Tick() @@ -617,11 +619,12 @@ void CCharacter::HandleSkippableTiles(int Index) Collision()->GetSpeedup(Index, &Direction, &Force, &MaxSpeed); if(Force == 255 && MaxSpeed) { - m_Core.m_Vel = Direction * (MaxSpeed/5); + m_Core.m_Vel = Direction * (MaxSpeed / 5); } else { - if(MaxSpeed > 0 && MaxSpeed < 5) MaxSpeed = 5; + if(MaxSpeed > 0 && MaxSpeed < 5) + MaxSpeed = 5; if(MaxSpeed > 0) { if(Direction.x > 0.0000001f) @@ -681,7 +684,7 @@ void CCharacter::HandleTiles(int Index) m_MoveRestrictions = Collision()->GetMoveRestrictions(IsSwitchActiveCb, this, m_Pos); // stopper - if(m_Core.m_Vel.y > 0 && (m_MoveRestrictions&CANTMOVE_DOWN)) + if(m_Core.m_Vel.y > 0 && (m_MoveRestrictions & CANTMOVE_DOWN)) { m_Core.m_Jumped = 0; m_Core.m_JumpedTotal = 0; @@ -816,13 +819,13 @@ void CCharacter::HandleTiles(int Index) else if(Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDOPEN && Team() != TEAM_SUPER && Collision()->GetSwitchNumber(MapIndex) > 0) { Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = true; - Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = GameWorld()->GameTick() + 1 + Collision()->GetSwitchDelay(MapIndex)*GameWorld()->GameTickSpeed() ; + Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = GameWorld()->GameTick() + 1 + Collision()->GetSwitchDelay(MapIndex) * GameWorld()->GameTickSpeed(); Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDOPEN; } else if(Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDCLOSE && Team() != TEAM_SUPER && Collision()->GetSwitchNumber(MapIndex) > 0) { Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = false; - Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = GameWorld()->GameTick() + 1 + Collision()->GetSwitchDelay(MapIndex)*GameWorld()->GameTickSpeed(); + Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = GameWorld()->GameTick() + 1 + Collision()->GetSwitchDelay(MapIndex) * GameWorld()->GameTickSpeed(); Collision()->m_pSwitchers[Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDCLOSE; } else if(Collision()->IsSwitch(MapIndex) == TILE_SWITCHCLOSE && Team() != TEAM_SUPER && Collision()->GetSwitchNumber(MapIndex) > 0) @@ -848,7 +851,7 @@ void CCharacter::HandleTiles(int Index) { int newJumps = Collision()->GetSwitchDelay(MapIndex); - if (newJumps != m_Core.m_Jumps) + if(newJumps != m_Core.m_Jumps) { m_Core.m_Jumps = newJumps; } @@ -878,7 +881,7 @@ void CCharacter::DDRaceTick() m_Input.m_Jump = 0; m_Input.m_Hook = 0; } - if (m_FreezeTime == 1) + if(m_FreezeTime == 1) UnFreeze(); } @@ -890,31 +893,31 @@ void CCharacter::DDRacePostCoreTick() if(!GameWorld()->m_WorldConfig.m_PredictDDRace) return; - if (m_EndlessHook) + if(m_EndlessHook) m_Core.m_HookTick = 0; m_FrozenLastTick = false; - if (m_DeepFreeze && !m_Super) + if(m_DeepFreeze && !m_Super) Freeze(); - if (m_Core.m_Jumps == 0 && !m_Super) + if(m_Core.m_Jumps == 0 && !m_Super) m_Core.m_Jumped = 3; - else if (m_Core.m_Jumps == 1 && m_Core.m_Jumped > 0) + else if(m_Core.m_Jumps == 1 && m_Core.m_Jumped > 0) m_Core.m_Jumped = 3; - else if (m_Core.m_JumpedTotal < m_Core.m_Jumps - 1 && m_Core.m_Jumped > 1) + else if(m_Core.m_JumpedTotal < m_Core.m_Jumps - 1 && m_Core.m_Jumped > 1) m_Core.m_Jumped = 1; - if ((m_Super || m_SuperJump) && m_Core.m_Jumped > 1) + if((m_Super || m_SuperJump) && m_Core.m_Jumped > 1) m_Core.m_Jumped = 1; int CurrentIndex = Collision()->GetMapIndex(m_Pos); HandleSkippableTiles(CurrentIndex); // handle Anti-Skip tiles - std::list < int > Indices = Collision()->GetMapIndices(m_PrevPos, m_Pos); + std::list Indices = Collision()->GetMapIndices(m_PrevPos, m_Pos); if(!Indices.empty()) - for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + for(std::list::iterator i = Indices.begin(); i != Indices.end(); i++) HandleTiles(*i); else { @@ -926,9 +929,9 @@ bool CCharacter::Freeze(int Seconds) { if(!GameWorld()->m_WorldConfig.m_PredictFreeze) return false; - if ((Seconds <= 0 || m_Super || m_FreezeTime == -1 || m_FreezeTime > Seconds * GameWorld()->GameTickSpeed()) && Seconds != -1) - return false; - if (m_FreezeTick < GameWorld()->GameTick() - GameWorld()->GameTickSpeed() || Seconds == -1) + if((Seconds <= 0 || m_Super || m_FreezeTime == -1 || m_FreezeTime > Seconds * GameWorld()->GameTickSpeed()) && Seconds != -1) + return false; + if(m_FreezeTick < GameWorld()->GameTick() - GameWorld()->GameTickSpeed() || Seconds == -1) { m_FreezeTime = Seconds == -1 ? Seconds : Seconds * GameWorld()->GameTickSpeed(); m_FreezeTick = GameWorld()->GameTick(); @@ -944,7 +947,7 @@ bool CCharacter::Freeze() bool CCharacter::UnFreeze() { - if (m_FreezeTime > 0) + if(m_FreezeTime > 0) { if(!m_aWeapons[m_Core.m_ActiveWeapon].m_Got) m_Core.m_ActiveWeapon = WEAPON_GUN; @@ -982,19 +985,19 @@ void CCharacter::GiveWeapon(int Weapon, bool Remove) void CCharacter::GiveAllWeapons() { - for(int i=WEAPON_GUN;im_WorldConfig.m_PredictTiles) { - if(pChar->m_Jumped&2) + if(pChar->m_Jumped & 2) { m_SuperJump = false; if(m_Core.m_Jumps > m_Core.m_JumpedTotal && m_Core.m_JumpedTotal > 0 && m_Core.m_Jumps > 2) @@ -1179,7 +1182,7 @@ void CCharacter::Read(CNetObj_Character *pChar, CNetObj_DDNetCharacter *pExtende // detect unfreeze (in case the player was frozen in the tile prediction and not correctly unfrozen) if(pChar->m_Emote != EMOTE_PAIN && pChar->m_Emote != EMOTE_NORMAL) m_DeepFreeze = false; - if(pChar->m_Weapon != WEAPON_NINJA || pChar->m_AttackTick > m_FreezeTick || absolute(pChar->m_VelX) == 256*10 || !GameWorld()->m_WorldConfig.m_PredictFreeze) + if(pChar->m_Weapon != WEAPON_NINJA || pChar->m_AttackTick > m_FreezeTick || absolute(pChar->m_VelX) == 256 * 10 || !GameWorld()->m_WorldConfig.m_PredictFreeze) { m_DeepFreeze = false; UnFreeze(); @@ -1195,7 +1198,7 @@ void CCharacter::Read(CNetObj_Character *pChar, CNetObj_DDNetCharacter *pExtende if(distance(m_PrevPos, m_Pos) > 10.f * 32.f) // reset prevpos if the distance is high m_PrevPos = m_Pos; - if(pChar->m_Jumped&2) + if(pChar->m_Jumped & 2) m_Core.m_JumpedTotal = m_Core.m_Jumps; m_AttackTick = pChar->m_AttackTick; m_LastSnapWeapon = pChar->m_Weapon; @@ -1218,8 +1221,8 @@ void CCharacter::Read(CNetObj_Character *pChar, CNetObj_DDNetCharacter *pExtende mem_zero(&m_SavedInput, sizeof(m_SavedInput)); m_Input.m_Direction = m_SavedInput.m_Direction = m_Core.m_Direction; m_Input.m_Hook = m_SavedInput.m_Hook = (m_Core.m_HookState != HOOK_IDLE); - m_Input.m_TargetX = cosf(pChar->m_Angle/256.0f); - m_Input.m_TargetY = sinf(pChar->m_Angle/256.0f); + m_Input.m_TargetX = cosf(pChar->m_Angle / 256.0f); + m_Input.m_TargetY = sinf(pChar->m_Angle / 256.0f); } // in most cases the reload timer can be determined from the last attack tick diff --git a/src/game/client/prediction/entities/character.h b/src/game/client/prediction/entities/character.h index a5d13ac24..085f5676a 100644 --- a/src/game/client/prediction/entities/character.h +++ b/src/game/client/prediction/entities/character.h @@ -3,8 +3,8 @@ #ifndef GAME_CLIENT_PREDICTION_ENTITIES_CHARACTER_H #define GAME_CLIENT_PREDICTION_ENTITIES_CHARACTER_H -#include #include "projectile.h" +#include #include #include @@ -31,6 +31,7 @@ enum class CCharacter : public CEntity { friend class CGameWorld; + public: //character's size static const int ms_PhysSize = 28; @@ -64,7 +65,7 @@ public: bool m_Alive; - CTeamsCore* TeamsCore(); + CTeamsCore *TeamsCore(); bool Freeze(int Time); bool Freeze(); bool UnFreeze(); @@ -83,11 +84,11 @@ public: bool m_EndlessHook; enum { - HIT_ALL=0, - DISABLE_HIT_HAMMER=1, - DISABLE_HIT_SHOTGUN=2, - DISABLE_HIT_GRENADE=4, - DISABLE_HIT_LASER=8 + HIT_ALL = 0, + DISABLE_HIT_HAMMER = 1, + DISABLE_HIT_SHOTGUN = 2, + DISABLE_HIT_GRENADE = 4, + DISABLE_HIT_LASER = 8 }; int m_Hit; int m_TuneZone; @@ -108,7 +109,7 @@ public: void SetActiveWeapon(int ActiveWeap); CCharacterCore GetCore() { return m_Core; }; void SetCore(CCharacterCore Core) { m_Core = Core; }; - CCharacterCore* Core() { return &m_Core; }; + CCharacterCore *Core() { return &m_Core; }; bool GetWeaponGot(int Type) { return m_aWeapons[Type].m_Got; }; void SetWeaponGot(int Type, bool Value) { m_aWeapons[Type].m_Got = Value; }; int GetWeaponAmmo(int Type) { return m_aWeapons[Type].m_Ammo; }; diff --git a/src/game/client/prediction/entities/laser.cpp b/src/game/client/prediction/entities/laser.cpp index 8f8469266..6c471745d 100644 --- a/src/game/client/prediction/entities/laser.cpp +++ b/src/game/client/prediction/entities/laser.cpp @@ -1,13 +1,13 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include -#include "character.h" #include "laser.h" +#include "character.h" +#include #include -CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Pos = Pos; m_Owner = Owner; @@ -17,7 +17,7 @@ CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEner m_Dir = Direction; m_Bounces = 0; m_EvalTick = 0; - m_TelePos = vec2(0,0); + m_TelePos = vec2(0, 0); m_WasTele = false; m_Type = Type; m_TuneZone = GameWorld()->m_WorldConfig.m_PredictTiles ? Collision()->IsTune(Collision()->GetMapIndex(m_Pos)) : 0; @@ -32,17 +32,17 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) CCharacter *pHit; bool pDontHitSelf = g_Config.m_SvOldLaser || (m_Bounces == 0 && !m_WasTele); - if(pOwnerChar ? (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) || (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN) && m_Type == WEAPON_SHOTGUN) : g_Config.m_SvHit) + if(pOwnerChar ? (!(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) || (!(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_SHOTGUN) && m_Type == WEAPON_SHOTGUN) : g_Config.m_SvHit) pHit = GameWorld()->IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner); else pHit = GameWorld()->IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner, pOwnerChar); - if(!pHit || (pHit == pOwnerChar && g_Config.m_SvOldLaser) || (pHit != pOwnerChar && pOwnerChar ? (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_LASER && m_Type == WEAPON_LASER) || (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN && m_Type == WEAPON_SHOTGUN) : !g_Config.m_SvHit)) + if(!pHit || (pHit == pOwnerChar && g_Config.m_SvOldLaser) || (pHit != pOwnerChar && pOwnerChar ? (pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_LASER && m_Type == WEAPON_LASER) || (pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_SHOTGUN && m_Type == WEAPON_SHOTGUN) : !g_Config.m_SvHit)) return false; m_From = From; m_Pos = At; m_Energy = -1; - if (m_Type == WEAPON_SHOTGUN) + if(m_Type == WEAPON_SHOTGUN) { vec2 Temp; @@ -54,7 +54,7 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) Temp = pHit->Core()->m_Vel + normalize(pOwnerChar->Core()->m_Pos - pHit->Core()->m_Pos) * Strength; pHit->Core()->m_Vel = ClampVel(pHit->m_MoveRestrictions, Temp); } - else if (m_Type == WEAPON_LASER) + else if(m_Type == WEAPON_LASER) { pHit->UnFreeze(); } @@ -76,11 +76,11 @@ void CLaser::DoBounce() int Res; int z; - if (m_WasTele) + if(m_WasTele) { m_PrevPos = m_TelePos; m_Pos = m_TelePos; - m_TelePos = vec2(0,0); + m_TelePos = vec2(0, 0); } vec2 To = m_Pos + m_Dir * m_Energy; @@ -140,18 +140,18 @@ void CLaser::Tick() if(GameWorld()->m_WorldConfig.m_IsVanilla) // predict old physics on vanilla 0.6 servers { - if(GameWorld()->GameTick() > m_EvalTick+(GameWorld()->GameTickSpeed()*Delay/1000.0f)) + if(GameWorld()->GameTick() > m_EvalTick + (GameWorld()->GameTickSpeed() * Delay / 1000.0f)) DoBounce(); } else { - if((GameWorld()->GameTick() - m_EvalTick) > (GameWorld()->GameTickSpeed()*Delay/1000.0f)) + if((GameWorld()->GameTick() - m_EvalTick) > (GameWorld()->GameTickSpeed() * Delay / 1000.0f)) DoBounce(); } } -CLaser::CLaser(CGameWorld *pGameWorld, int ID, CNetObj_Laser *pLaser) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +CLaser::CLaser(CGameWorld *pGameWorld, int ID, CNetObj_Laser *pLaser) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Pos.x = pLaser->m_X; m_Pos.y = pLaser->m_Y; @@ -191,7 +191,7 @@ bool CLaser::Match(CLaser *pLaser) return false; const vec2 ThisDiff = m_Pos - m_From; const vec2 OtherDiff = pLaser->m_Pos - pLaser->m_From; - const float DirError = distance(normalize(OtherDiff)*length(ThisDiff), ThisDiff); + const float DirError = distance(normalize(OtherDiff) * length(ThisDiff), ThisDiff); if(DirError > 2.f) return false; return true; diff --git a/src/game/client/prediction/entities/laser.h b/src/game/client/prediction/entities/laser.h index b93284560..964025fa1 100644 --- a/src/game/client/prediction/entities/laser.h +++ b/src/game/client/prediction/entities/laser.h @@ -8,6 +8,7 @@ class CLaser : public CEntity { friend class CGameWorld; + public: CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type); diff --git a/src/game/client/prediction/entities/pickup.cpp b/src/game/client/prediction/entities/pickup.cpp index 45a2b97f3..9825da3fd 100644 --- a/src/game/client/prediction/entities/pickup.cpp +++ b/src/game/client/prediction/entities/pickup.cpp @@ -1,67 +1,69 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include -#include "character.h" #include "pickup.h" +#include "character.h" +#include void CPickup::Tick() { Move(); // Check if a player intersected us CCharacter *apEnts[MAX_CLIENTS]; - int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); - for(int i = 0; i < Num; ++i) { - CCharacter * pChr = apEnts[i]; + int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity **)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; ++i) + { + CCharacter *pChr = apEnts[i]; if(pChr && pChr->IsAlive()) { - if(GameWorld()->m_WorldConfig.m_IsVanilla && distance(m_Pos, pChr->m_Pos) >= 20.0f*2) // pickup distance is shorter on vanilla due to using ClosestEntity + if(GameWorld()->m_WorldConfig.m_IsVanilla && distance(m_Pos, pChr->m_Pos) >= 20.0f * 2) // pickup distance is shorter on vanilla due to using ClosestEntity + continue; + if(m_Layer == LAYER_SWITCH && !Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) continue; - if(m_Layer == LAYER_SWITCH && !Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) continue; bool sound = false; // player picked us up, is someone was hooking us, let them go - switch (m_Type) + switch(m_Type) { - case POWERUP_HEALTH: - //pChr->Freeze(); - break; + case POWERUP_HEALTH: + //pChr->Freeze(); + break; - case POWERUP_ARMOR: - if(!GameWorld()->m_WorldConfig.m_IsDDRace || !GameWorld()->m_WorldConfig.m_PredictDDRace) - continue; - if(pChr->m_Super) - continue; - for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++) + case POWERUP_ARMOR: + if(!GameWorld()->m_WorldConfig.m_IsDDRace || !GameWorld()->m_WorldConfig.m_PredictDDRace) + continue; + if(pChr->m_Super) + continue; + for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++) + { + if(pChr->GetWeaponGot(i)) { - if(pChr->GetWeaponGot(i)) - { - pChr->SetWeaponGot(i, false); - pChr->SetWeaponAmmo(i, 0); - sound = true; - } + pChr->SetWeaponGot(i, false); + pChr->SetWeaponAmmo(i, 0); + sound = true; } - pChr->SetNinjaActivationDir(vec2(0,0)); - pChr->SetNinjaActivationTick(-500); - pChr->SetNinjaCurrentMoveTime(0); - if (sound) - pChr->SetLastWeapon(WEAPON_GUN); - if(pChr->GetActiveWeapon() >= WEAPON_SHOTGUN) - pChr->SetActiveWeapon(WEAPON_HAMMER); - break; + } + pChr->SetNinjaActivationDir(vec2(0, 0)); + pChr->SetNinjaActivationTick(-500); + pChr->SetNinjaCurrentMoveTime(0); + if(sound) + pChr->SetLastWeapon(WEAPON_GUN); + if(pChr->GetActiveWeapon() >= WEAPON_SHOTGUN) + pChr->SetActiveWeapon(WEAPON_HAMMER); + break; - case POWERUP_WEAPON: - if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || pChr->GetWeaponAmmo(m_Subtype) != -1)) - pChr->GiveWeapon(m_Subtype); - break; + case POWERUP_WEAPON: + if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || pChr->GetWeaponAmmo(m_Subtype) != -1)) + pChr->GiveWeapon(m_Subtype); + break; - case POWERUP_NINJA: - { - // activate ninja on target player - pChr->GiveNinja(); - break; - } + case POWERUP_NINJA: + { + // activate ninja on target player + pChr->GiveNinja(); + break; + } - default: - break; + default: + break; }; } } @@ -69,20 +71,20 @@ void CPickup::Tick() void CPickup::Move() { - if (GameWorld()->GameTick()%int(GameWorld()->GameTickSpeed() * 0.15f) == 0) + if(GameWorld()->GameTick() % int(GameWorld()->GameTickSpeed() * 0.15f) == 0) { int Flags; - int index = Collision()->IsMover(m_Pos.x,m_Pos.y, &Flags); - if (index) + int index = Collision()->IsMover(m_Pos.x, m_Pos.y, &Flags); + if(index) { - m_Core=Collision()->CpSpeed(index, Flags); + m_Core = Collision()->CpSpeed(index, Flags); } m_Pos += m_Core; } } -CPickup::CPickup(CGameWorld *pGameWorld, int ID, CNetObj_Pickup *pPickup) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) +CPickup::CPickup(CGameWorld *pGameWorld, int ID, CNetObj_Pickup *pPickup) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) { m_Pos.x = pPickup->m_X; m_Pos.y = pPickup->m_Y; diff --git a/src/game/client/prediction/entities/projectile.cpp b/src/game/client/prediction/entities/projectile.cpp index 888cd689e..c2e3578c5 100644 --- a/src/game/client/prediction/entities/projectile.cpp +++ b/src/game/client/prediction/entities/projectile.cpp @@ -1,26 +1,24 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include "projectile.h" +#include #include -CProjectile::CProjectile - ( - CGameWorld *pGameWorld, - int Type, - int Owner, - vec2 Pos, - vec2 Dir, - int Span, - bool Freeze, - bool Explosive, - float Force, - int SoundImpact, - int Layer, - int Number - ) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) +CProjectile::CProjectile( + CGameWorld *pGameWorld, + int Type, + int Owner, + vec2 Pos, + vec2 Dir, + int Span, + bool Freeze, + bool Explosive, + float Force, + int SoundImpact, + int Layer, + int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) { m_Type = Type; m_Pos = Pos; @@ -49,30 +47,29 @@ vec2 CProjectile::GetPos(float Time) switch(m_Type) { - case WEAPON_GRENADE: - Curvature = pTuning->m_GrenadeCurvature; - Speed = pTuning->m_GrenadeSpeed; - break; + case WEAPON_GRENADE: + Curvature = pTuning->m_GrenadeCurvature; + Speed = pTuning->m_GrenadeSpeed; + break; - case WEAPON_SHOTGUN: - Curvature = pTuning->m_ShotgunCurvature; - Speed = pTuning->m_ShotgunSpeed; - break; + case WEAPON_SHOTGUN: + Curvature = pTuning->m_ShotgunCurvature; + Speed = pTuning->m_ShotgunSpeed; + break; - case WEAPON_GUN: - Curvature = pTuning->m_GunCurvature; - Speed = pTuning->m_GunSpeed; - break; + case WEAPON_GUN: + Curvature = pTuning->m_GunCurvature; + Speed = pTuning->m_GunSpeed; + break; } return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); } - void CProjectile::Tick() { - float Pt = (GameWorld()->GameTick()-m_StartTick-1)/(float)GameWorld()->GameTickSpeed(); - float Ct = (GameWorld()->GameTick()-m_StartTick)/(float)GameWorld()->GameTickSpeed(); + float Pt = (GameWorld()->GameTick() - m_StartTick - 1) / (float)GameWorld()->GameTickSpeed(); + float Ct = (GameWorld()->GameTick() - m_StartTick) / (float)GameWorld()->GameTickSpeed(); vec2 PrevPos = GetPos(Pt); vec2 CurPos = GetPos(Ct); vec2 ColPos; @@ -90,48 +87,45 @@ void CProjectile::Tick() int64 TeamMask = -1LL; bool isWeaponCollide = false; - if - ( - pOwnerChar && - pTargetChr && - pOwnerChar->IsAlive() && - pTargetChr->IsAlive() && - !pTargetChr->CanCollide(m_Owner) - ) + if( + pOwnerChar && + pTargetChr && + pOwnerChar->IsAlive() && + pTargetChr->IsAlive() && + !pTargetChr->CanCollide(m_Owner)) { - isWeaponCollide = true; + isWeaponCollide = true; } - if( ((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !isWeaponCollide) + if(((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !isWeaponCollide) { if(m_Explosive && (!pTargetChr || (pTargetChr && (!m_Freeze || (m_Type == WEAPON_SHOTGUN && Collide))))) { GameWorld()->CreateExplosion(ColPos, m_Owner, m_Type, m_Owner == -1, (!pTargetChr ? -1 : pTargetChr->Team()), - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); } else if(pTargetChr && m_Freeze && ((m_Layer == LAYER_SWITCH && Collision()->m_pSwitchers[m_Number].m_Status[pTargetChr->Team()]) || m_Layer != LAYER_SWITCH)) pTargetChr->Freeze(); if(Collide && m_Bouncing != 0) { m_StartTick = GameWorld()->GameTick(); - m_Pos = NewPos+(-(m_Direction*4)); - if (m_Bouncing == 1) + m_Pos = NewPos + (-(m_Direction * 4)); + if(m_Bouncing == 1) m_Direction.x = -m_Direction.x; else if(m_Bouncing == 2) m_Direction.y = -m_Direction.y; - if (fabs(m_Direction.x) < 1e-6) + if(fabs(m_Direction.x) < 1e-6) m_Direction.x = 0; - if (fabs(m_Direction.y) < 1e-6) + if(fabs(m_Direction.y) < 1e-6) m_Direction.y = 0; m_Pos += m_Direction; } - else if (m_Type == WEAPON_GUN) + else if(m_Type == WEAPON_GUN) { GameWorld()->DestroyEntity(this); } - else - if (!m_Freeze) - GameWorld()->DestroyEntity(this); + else if(!m_Freeze) + GameWorld()->DestroyEntity(this); } if(m_LifeSpan == -1) { @@ -143,7 +137,7 @@ void CProjectile::Tick() int64 TeamMask = -1LL; GameWorld()->CreateExplosion(ColPos, m_Owner, m_Type, m_Owner == -1, (!pOwnerChar ? -1 : pOwnerChar->Team()), - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); } GameWorld()->DestroyEntity(this); } @@ -156,8 +150,8 @@ void CProjectile::SetBouncing(int Value) m_Bouncing = Value; } -CProjectile::CProjectile(CGameWorld *pGameWorld, int ID, CNetObj_Projectile *pProj) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) +CProjectile::CProjectile(CGameWorld *pGameWorld, int ID, CNetObj_Projectile *pProj) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) { ExtractInfo(pProj, &m_Pos, &m_Direction); if(UseExtraInfo(pProj)) @@ -191,16 +185,16 @@ void CProjectile::FillInfo(CNetObj_Projectile *pProj) { pProj->m_X = (int)m_Pos.x; pProj->m_Y = (int)m_Pos.y; - pProj->m_VelX = (int)(m_Direction.x*100.0f); - pProj->m_VelY = (int)(m_Direction.y*100.0f); + pProj->m_VelX = (int)(m_Direction.x * 100.0f); + pProj->m_VelY = (int)(m_Direction.y * 100.0f); pProj->m_StartTick = m_StartTick; pProj->m_Type = m_Type; } void CProjectile::FillExtraInfo(CNetObj_Projectile *pProj) { - const int MaxPos = 0x7fffffff/100; - if(abs((int)m_Pos.y)+1 >= MaxPos || abs((int)m_Pos.x)+1 >= MaxPos) + const int MaxPos = 0x7fffffff / 100; + if(abs((int)m_Pos.y) + 1 >= MaxPos || abs((int)m_Pos.x) + 1 >= MaxPos) { //If the modified data would be too large to fit in an integer, send normal data instead FillInfo(pProj); @@ -210,15 +204,15 @@ void CProjectile::FillExtraInfo(CNetObj_Projectile *pProj) float Angle = -atan2f(m_Direction.x, m_Direction.y); int Data = 0; - Data |= (abs(m_Owner) & 255)<<0; + Data |= (abs(m_Owner) & 255) << 0; if(m_Owner < 0) - Data |= 1<<8; - Data |= 1<<9; //This bit tells the client to use the extra info - Data |= (m_Bouncing & 3)<<10; + Data |= 1 << 8; + Data |= 1 << 9; //This bit tells the client to use the extra info + Data |= (m_Bouncing & 3) << 10; if(m_Explosive) - Data |= 1<<12; + Data |= 1 << 12; if(m_Freeze) - Data |= 1<<13; + Data |= 1 << 13; pProj->m_X = (int)(m_Pos.x * 100.0f); pProj->m_Y = (int)(m_Pos.y * 100.0f); @@ -243,6 +237,6 @@ bool CProjectile::Match(CProjectile *pProj) int CProjectile::NetworkClipped(vec2 ViewPos) { - float Ct = (GameWorld()->GameTick()-m_StartTick)/(float)GameWorld()->GameTickSpeed(); - return ((CEntity*) this)->NetworkClipped(GetPos(Ct), ViewPos); + float Ct = (GameWorld()->GameTick() - m_StartTick) / (float)GameWorld()->GameTickSpeed(); + return ((CEntity *)this)->NetworkClipped(GetPos(Ct), ViewPos); } diff --git a/src/game/client/prediction/entities/projectile.h b/src/game/client/prediction/entities/projectile.h index 9c3e0bc27..63fe2dcd2 100644 --- a/src/game/client/prediction/entities/projectile.h +++ b/src/game/client/prediction/entities/projectile.h @@ -3,17 +3,17 @@ #ifndef GAME_CLIENT_PREDICTION_ENTITIES_PROJECTILE_H #define GAME_CLIENT_PREDICTION_ENTITIES_PROJECTILE_H -#include #include "character.h" +#include #include class CProjectile : public CEntity { friend class CGameWorld; friend class CItems; + public: - CProjectile - ( + CProjectile( CGameWorld *pGameWorld, int Type, int Owner, @@ -25,8 +25,7 @@ public: float Force, int SoundImpact, int Layer = 0, - int Number = 0 - ); + int Number = 0); vec2 GetPos(float Time); void FillInfo(CNetObj_Projectile *pProj); diff --git a/src/game/client/prediction/entity.cpp b/src/game/client/prediction/entity.cpp index 94723c6b8..8132d092c 100644 --- a/src/game/client/prediction/entity.cpp +++ b/src/game/client/prediction/entity.cpp @@ -11,7 +11,7 @@ CEntity::CEntity(CGameWorld *pGameWorld, int ObjType) m_pGameWorld = pGameWorld; m_ObjType = ObjType; - m_Pos = vec2(0,0); + m_Pos = vec2(0, 0); m_ProximityRadius = 0; m_MarkedForDestroy = false; @@ -40,8 +40,8 @@ int CEntity::NetworkClipped(vec2 ViewPos) int CEntity::NetworkClipped(vec2 CheckPos, vec2 ViewPos) { - float dx = ViewPos.x-CheckPos.x; - float dy = ViewPos.y-CheckPos.y; + float dx = ViewPos.x - CheckPos.x; + float dy = ViewPos.y - CheckPos.y; if(absolute(dx) > 1000.0f || absolute(dy) > 800.0f) return 1; @@ -53,6 +53,8 @@ int CEntity::NetworkClipped(vec2 CheckPos, vec2 ViewPos) bool CEntity::GameLayerClipped(vec2 CheckPos) { - return round_to_int(CheckPos.x)/32 < -200 || round_to_int(CheckPos.x)/32 > Collision()->GetWidth()+200 || - round_to_int(CheckPos.y)/32 < -200 || round_to_int(CheckPos.y)/32 > Collision()->GetHeight()+200 ? true : false; + return round_to_int(CheckPos.x) / 32 < -200 || round_to_int(CheckPos.x) / 32 > Collision()->GetWidth() + 200 || + round_to_int(CheckPos.y) / 32 < -200 || round_to_int(CheckPos.y) / 32 > Collision()->GetHeight() + 200 ? + true : + false; } diff --git a/src/game/client/prediction/entity.h b/src/game/client/prediction/entity.h index 1a3070b7a..06b38115a 100644 --- a/src/game/client/prediction/entity.h +++ b/src/game/client/prediction/entity.h @@ -3,12 +3,12 @@ #ifndef GAME_CLIENT_PREDICTION_ENTITY_H #define GAME_CLIENT_PREDICTION_ENTITY_H -#include -#include #include "gameworld.h" +#include +#include #define MACRO_ALLOC_HEAP() \ - public: \ +public: \ void *operator new(size_t Size) \ { \ void *p = malloc(Size); \ @@ -21,19 +21,22 @@ /*dbg_msg("", "-- %p", p);*/ \ free(pPtr); \ } \ - private: +\ +private: class CEntity { MACRO_ALLOC_HEAP() - friend class CGameWorld; // entity list handling + friend class CGameWorld; // entity list handling CEntity *m_pPrevTypeEntity; CEntity *m_pNextTypeEntity; + protected: class CGameWorld *m_pGameWorld; bool m_MarkedForDestroy; int m_ID; int m_ObjType; + public: CEntity(CGameWorld *pGameWorld, int Objtype); virtual ~CEntity(); @@ -64,10 +67,18 @@ public: CEntity *m_pParent; CEntity *NextEntity() { return m_pNextTypeEntity; } int ID() { return m_ID; } - void Keep() { m_SnapTicks = 0; m_MarkedForDestroy = false; } + void Keep() + { + m_SnapTicks = 0; + m_MarkedForDestroy = false; + } void DetachFromGameWorld() { m_pGameWorld = 0; } - CEntity() { m_ID = -1; m_pGameWorld = 0; } + CEntity() + { + m_ID = -1; + m_pGameWorld = 0; + } }; #endif diff --git a/src/game/client/prediction/gameworld.cpp b/src/game/client/prediction/gameworld.cpp index 121a61822..6f4e66ecc 100644 --- a/src/game/client/prediction/gameworld.cpp +++ b/src/game/client/prediction/gameworld.cpp @@ -2,14 +2,14 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "gameworld.h" -#include "entity.h" #include "entities/character.h" -#include "entities/projectile.h" #include "entities/laser.h" #include "entities/pickup.h" +#include "entities/projectile.h" +#include "entity.h" #include -#include #include +#include ////////////////////////////////////////////////// // game world @@ -63,7 +63,7 @@ int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Num = 0; for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) { - if(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius) + if(distance(pEnt->m_Pos, Pos) < Radius + pEnt->m_ProximityRadius) { if(ppEnts) ppEnts[Num] = pEnt; @@ -109,7 +109,7 @@ void CGameWorld::InsertEntity(CEntity *pEnt, bool Last) if(pEnt->m_ObjType == ENTTYPE_CHARACTER) { - auto *pChar = (CCharacter*) pEnt; + auto *pChar = (CCharacter *)pEnt; int ID = pChar->GetCID(); if(ID >= 0 && ID < MAX_CLIENTS) { @@ -148,7 +148,7 @@ void CGameWorld::RemoveEntity(CEntity *pEnt) if(pEnt->m_ObjType == ENTTYPE_CHARACTER) { - CCharacter *pChar = (CCharacter*) pEnt; + CCharacter *pChar = (CCharacter *)pEnt; int ID = pChar->GetCID(); if(ID >= 0 && ID < MAX_CLIENTS) { @@ -166,7 +166,7 @@ void CGameWorld::RemoveEntities() { // destroy objects marked for destruction for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; if(pEnt->m_MarkedForDestroy) @@ -178,7 +178,7 @@ void CGameWorld::RemoveEntities() } } -bool distCompare(std::pair a, std::pair b) +bool distCompare(std::pair a, std::pair b) { return (a.first < b.first); } @@ -187,7 +187,7 @@ void CGameWorld::Tick() { // update all objects for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Tick(); @@ -195,7 +195,7 @@ void CGameWorld::Tick() } for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->TickDefered(); @@ -208,9 +208,8 @@ void CGameWorld::Tick() OnModified(); } - // TODO: should be more general -CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CCharacter *pNotThis, int CollideWith, class CCharacter *pThisOnly) +CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, CCharacter *pNotThis, int CollideWith, class CCharacter *pThisOnly) { // Find other players float ClosestLen = distance(Pos0, Pos1) * 100.0f; @@ -230,7 +229,7 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos); float Len = distance(p->m_Pos, IntersectPos); - if(Len < p->m_ProximityRadius+Radius) + if(Len < p->m_ProximityRadius + Radius) { Len = distance(Pos0, IntersectPos); if(Len < ClosestLen) @@ -247,7 +246,7 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v std::list CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, class CEntity *pNotThis) { - std::list< CCharacter * > listOfChars; + std::list listOfChars; CCharacter *pChr = (CCharacter *)FindFirst(CGameWorld::ENTTYPE_CHARACTER); for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) @@ -257,7 +256,7 @@ std::list CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, pChr->m_Pos); float Len = distance(pChr->m_Pos, IntersectPos); - if(Len < pChr->m_ProximityRadius+Radius) + if(Len < pChr->m_ProximityRadius + Radius) { listOfChars.push_back(pChr); } @@ -270,7 +269,7 @@ void CGameWorld::ReleaseHooked(int ClientID) CCharacter *pChr = (CCharacter *)CGameWorld::FindFirst(CGameWorld::ENTTYPE_CHARACTER); for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) { - CCharacterCore* Core = pChr->Core(); + CCharacterCore *Core = pChr->Core(); if(Core->m_HookedPlayer == ClientID) { Core->m_HookedPlayer = -1; @@ -303,16 +302,16 @@ void CGameWorld::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, CEntity *apEnts[MAX_CLIENTS]; float Radius = 135.0f; float InnerRadius = 48.0f; - int Num = FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + int Num = FindEntities(Pos, Radius, (CEntity **)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for(int i = 0; i < Num; i++) { - CCharacter *pChar = (CCharacter*) apEnts[i]; + CCharacter *pChar = (CCharacter *)apEnts[i]; vec2 Diff = pChar->m_Pos - Pos; - vec2 ForceDir(0,1); + vec2 ForceDir(0, 1); float l = length(Diff); if(l) ForceDir = normalize(Diff); - l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); + l = 1 - clamp((l - InnerRadius) / (Radius - InnerRadius), 0.0f, 1.0f); float Strength; if(Owner == -1 || !GetCharacterByID(Owner)) Strength = Tuning()->m_ExplosionStrength; @@ -321,14 +320,14 @@ void CGameWorld::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, float Dmg = Strength * l; if((int)Dmg) - if((GetCharacterByID(Owner) ? !(GetCharacterByID(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || NoDamage) || Owner == pChar->GetCID()) + if((GetCharacterByID(Owner) ? !(GetCharacterByID(Owner)->m_Hit & CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || NoDamage) || Owner == pChar->GetCID()) { if(Owner != -1 && pChar->IsAlive() && !pChar->CanCollide(Owner)) continue; if(Owner == -1 && ActivatedTeam != -1 && pChar->IsAlive() && pChar->Team() != ActivatedTeam) continue; - pChar->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon); - if(GetCharacterByID(Owner) ? GetCharacterByID(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE : !g_Config.m_SvHit || NoDamage) + pChar->TakeDamage(ForceDir * Dmg * 2, (int)Dmg, Owner, Weapon); + if(GetCharacterByID(Owner) ? GetCharacterByID(Owner)->m_Hit & CCharacter::DISABLE_HIT_GRENADE : !g_Config.m_SvHit || NoDamage) break; } } @@ -341,7 +340,7 @@ void CGameWorld::NetObjBegin() { pEnt->m_MarkedForDestroy = true; if(i == ENTTYPE_CHARACTER) - ((CCharacter*)pEnt)->m_KeepHooked = false; + ((CCharacter *)pEnt)->m_KeepHooked = false; } OnModified(); } @@ -349,7 +348,7 @@ void CGameWorld::NetObjBegin() void CGameWorld::NetCharAdd(int ObjID, CNetObj_Character *pCharObj, CNetObj_DDNetCharacter *pExtended, int GameTeam, bool IsLocal) { CCharacter *pChar; - if((pChar = (CCharacter*) GetEntity(ObjID, ENTTYPE_CHARACTER))) + if((pChar = (CCharacter *)GetEntity(ObjID, ENTTYPE_CHARACTER))) { pChar->Read(pCharObj, pExtended, IsLocal); pChar->Keep(); @@ -365,12 +364,12 @@ void CGameWorld::NetObjAdd(int ObjID, int ObjType, const void *pObjData) { if(ObjType == NETOBJTYPE_PROJECTILE && m_WorldConfig.m_PredictWeapons) { - CProjectile NetProj = CProjectile(this, ObjID, (CNetObj_Projectile*) pObjData); + CProjectile NetProj = CProjectile(this, ObjID, (CNetObj_Projectile *)pObjData); if(NetProj.m_Type != WEAPON_SHOTGUN && fabs(length(NetProj.m_Direction) - 1.f) > 0.02f) // workaround to skip grenades on ball mod return; - if(CProjectile *pProj = (CProjectile*) GetEntity(ObjID, ENTTYPE_PROJECTILE)) + if(CProjectile *pProj = (CProjectile *)GetEntity(ObjID, ENTTYPE_PROJECTILE)) { if(NetProj.Match(pProj)) { @@ -380,10 +379,10 @@ void CGameWorld::NetObjAdd(int ObjID, int ObjType, const void *pObjData) return; } } - if(!UseExtraInfo((CNetObj_Projectile*)pObjData)) + if(!UseExtraInfo((CNetObj_Projectile *)pObjData)) { // try to match the newly received (unrecognized) projectile with a locally fired one - for(CProjectile *pProj = (CProjectile*) FindFirst(CGameWorld::ENTTYPE_PROJECTILE); pProj; pProj = (CProjectile*) pProj->TypeNext()) + for(CProjectile *pProj = (CProjectile *)FindFirst(CGameWorld::ENTTYPE_PROJECTILE); pProj; pProj = (CProjectile *)pProj->TypeNext()) { if(pProj->m_ID == -1 && NetProj.Match(pProj)) { @@ -393,13 +392,13 @@ void CGameWorld::NetObjAdd(int ObjID, int ObjType, const void *pObjData) } } // otherwise try to determine its owner by checking if there is only one player nearby - if(NetProj.m_StartTick >= GameTick()-4) + if(NetProj.m_StartTick >= GameTick() - 4) { - const vec2 NetPos = NetProj.m_Pos - normalize(NetProj.m_Direction)*28.0*0.75; - const bool Prev = (GameTick()-NetProj.m_StartTick) > 1; + const vec2 NetPos = NetProj.m_Pos - normalize(NetProj.m_Direction) * 28.0 * 0.75; + const bool Prev = (GameTick() - NetProj.m_StartTick) > 1; float First = 200.0f, Second = 200.0f; CCharacter *pClosest = 0; - for(CCharacter *pChar = (CCharacter*) FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter *) pChar->TypeNext()) + for(CCharacter *pChar = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter *)pChar->TypeNext()) { float Dist = distance(Prev ? pChar->m_PrevPrevPos : pChar->m_PrevPos, NetPos); if(Dist < First) @@ -410,17 +409,17 @@ void CGameWorld::NetObjAdd(int ObjID, int ObjType, const void *pObjData) else if(Dist < Second) Second = Dist; } - if(pClosest && maximum(First, 2.f)*1.2f < Second) + if(pClosest && maximum(First, 2.f) * 1.2f < Second) NetProj.m_Owner = pClosest->m_ID; } } CProjectile *pProj = new CProjectile(NetProj); - InsertEntity((CEntity*)pProj); + InsertEntity((CEntity *)pProj); } else if(ObjType == NETOBJTYPE_PICKUP && m_WorldConfig.m_PredictWeapons) { - CPickup NetPickup = CPickup(this, ObjID, (CNetObj_Pickup*) pObjData); - if(CPickup *pPickup = (CPickup*) GetEntity(ObjID, ENTTYPE_PICKUP)) + CPickup NetPickup = CPickup(this, ObjID, (CNetObj_Pickup *)pObjData); + if(CPickup *pPickup = (CPickup *)GetEntity(ObjID, ENTTYPE_PICKUP)) { if(NetPickup.Match(pPickup)) { @@ -434,14 +433,14 @@ void CGameWorld::NetObjAdd(int ObjID, int ObjType, const void *pObjData) } else if(ObjType == NETOBJTYPE_LASER && m_WorldConfig.m_PredictWeapons) { - CLaser NetLaser = CLaser(this, ObjID, (CNetObj_Laser*) pObjData); + CLaser NetLaser = CLaser(this, ObjID, (CNetObj_Laser *)pObjData); CLaser *pMatching = 0; - if(CLaser *pLaser = (CLaser*) GetEntity(ObjID, ENTTYPE_LASER)) + if(CLaser *pLaser = (CLaser *)GetEntity(ObjID, ENTTYPE_LASER)) if(NetLaser.Match(pLaser)) pMatching = pLaser; if(!pMatching) { - for(CLaser *pLaser = (CLaser*) FindFirst(CGameWorld::ENTTYPE_LASER); pLaser; pLaser = (CLaser*) pLaser->TypeNext()) + for(CLaser *pLaser = (CLaser *)FindFirst(CGameWorld::ENTTYPE_LASER); pLaser; pLaser = (CLaser *)pLaser->TypeNext()) { if(pLaser->m_ID == -1 && NetLaser.Match(pLaser)) { @@ -474,7 +473,7 @@ void CGameWorld::NetObjEnd(int LocalID) if(pHookedChar->m_MarkedForDestroy) { pHookedChar->m_Pos = pHookedChar->m_Core.m_Pos = pChar->m_Core.m_HookPos; - pHookedChar->m_Core.m_Vel = vec2(0,0); + pHookedChar->m_Core.m_Vel = vec2(0, 0); mem_zero(&pHookedChar->m_SavedInput, sizeof(pHookedChar->m_SavedInput)); pHookedChar->m_KeepHooked = true; pHookedChar->m_MarkedForDestroy = false; @@ -482,7 +481,7 @@ void CGameWorld::NetObjEnd(int LocalID) // keep entities that are out of view for a short while, for some entity types if(CCharacter *pLocal = GetCharacterByID(LocalID)) for(int i : {ENTTYPE_CHARACTER, ENTTYPE_PROJECTILE, ENTTYPE_LASER}) - for(CEntity *pEnt = FindFirst(i); pEnt; pEnt=pEnt->TypeNext()) + for(CEntity *pEnt = FindFirst(i); pEnt; pEnt = pEnt->TypeNext()) if(pEnt->m_MarkedForDestroy) if(pEnt->m_SnapTicks < 2 * SERVER_TICK_SPEED || (i != ENTTYPE_CHARACTER && pEnt->m_SnapTicks < 5 * SERVER_TICK_SPEED)) if(pEnt->NetworkClipped(pLocal->m_Core.m_Pos)) @@ -495,7 +494,7 @@ void CGameWorld::NetObjEnd(int LocalID) m_apCharacters[i] = 0; m_Core.m_apCharacters[i] = 0; } - for(CCharacter *pChar = (CCharacter*) FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter*) pChar->TypeNext()) + for(CCharacter *pChar = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter *)pChar->TypeNext()) { int ID = pChar->GetCID(); if(ID >= 0 && ID < MAX_CLIENTS) @@ -543,13 +542,13 @@ void CGameWorld::CopyWorld(CGameWorld *pFrom) { CEntity *pCopy = 0; if(Type == ENTTYPE_PROJECTILE) - pCopy = new CProjectile(*((CProjectile*)pEnt)); + pCopy = new CProjectile(*((CProjectile *)pEnt)); else if(Type == ENTTYPE_LASER) - pCopy = new CLaser(*((CLaser*)pEnt)); + pCopy = new CLaser(*((CLaser *)pEnt)); else if(Type == ENTTYPE_CHARACTER) - pCopy = new CCharacter(*((CCharacter*)pEnt)); + pCopy = new CCharacter(*((CCharacter *)pEnt)); else if(Type == ENTTYPE_PICKUP) - pCopy = new CPickup(*((CPickup*)pEnt)); + pCopy = new CPickup(*((CPickup *)pEnt)); if(pCopy) { pCopy->m_pParent = pEnt; @@ -565,16 +564,16 @@ CEntity *CGameWorld::FindMatch(int ObjID, int ObjType, const void *pObjData) #define FindType(EntType, EntClass, ObjClass) \ { \ CEntity *pEnt = GetEntity(ObjID, EntType); \ - if(pEnt && EntClass(this, ObjID, (ObjClass*) pObjData).Match((EntClass*)pEnt)) \ + if(pEnt && EntClass(this, ObjID, (ObjClass *)pObjData).Match((EntClass *)pEnt)) \ return pEnt; \ return 0; \ } switch(ObjType) { - case NETOBJTYPE_CHARACTER: FindType(ENTTYPE_CHARACTER, CCharacter, CNetObj_Character); - case NETOBJTYPE_PROJECTILE: FindType(ENTTYPE_PROJECTILE, CProjectile, CNetObj_Projectile); - case NETOBJTYPE_LASER: FindType(ENTTYPE_LASER, CLaser, CNetObj_Laser); - case NETOBJTYPE_PICKUP: FindType(ENTTYPE_PICKUP, CPickup, CNetObj_Pickup); + case NETOBJTYPE_CHARACTER: FindType(ENTTYPE_CHARACTER, CCharacter, CNetObj_Character); + case NETOBJTYPE_PROJECTILE: FindType(ENTTYPE_PROJECTILE, CProjectile, CNetObj_Projectile); + case NETOBJTYPE_LASER: FindType(ENTTYPE_LASER, CLaser, CNetObj_Laser); + case NETOBJTYPE_PICKUP: FindType(ENTTYPE_PICKUP, CPickup, CNetObj_Pickup); } return 0; } diff --git a/src/game/client/prediction/gameworld.h b/src/game/client/prediction/gameworld.h index caa2f1639..7f6ff50f6 100644 --- a/src/game/client/prediction/gameworld.h +++ b/src/game/client/prediction/gameworld.h @@ -13,6 +13,7 @@ class CCharacter; class CGameWorld { friend class CCharacter; + public: enum { diff --git a/src/game/client/race.cpp b/src/game/client/race.cpp index 86f89a272..22be0f0f8 100644 --- a/src/game/client/race.cpp +++ b/src/game/client/race.cpp @@ -8,7 +8,7 @@ #include "race.h" -int CRaceHelper::ms_aFlagIndex[2] = { -1, -1 }; +int CRaceHelper::ms_aFlagIndex[2] = {-1, -1}; int CRaceHelper::TimeFromSecondsStr(const char *pStr) { @@ -22,7 +22,7 @@ int CRaceHelper::TimeFromSecondsStr(const char *pStr) if(*pStr == '.' || *pStr == ',') { pStr++; - static const int s_aMult[3] = { 100, 10, 1 }; + static const int s_aMult[3] = {100, 10, 1}; for(int i = 0; isdigit(pStr[i]) && i < 3; i++) Time += (pStr[i] - '0') * s_aMult[i]; } @@ -31,8 +31,8 @@ int CRaceHelper::TimeFromSecondsStr(const char *pStr) int CRaceHelper::TimeFromStr(const char *pStr) { - static const char * const s_pMinutesStr = " minute(s) "; - static const char * const s_pSecondsStr = " second(s)"; + static const char *const s_pMinutesStr = " minute(s) "; + static const char *const s_pSecondsStr = " second(s)"; const char *pSeconds = str_find(pStr, s_pSecondsStr); if(!pSeconds) @@ -54,7 +54,7 @@ int CRaceHelper::TimeFromStr(const char *pStr) int CRaceHelper::TimeFromFinishMessage(const char *pStr, char *pNameBuf, int NameBufSize) { - static const char * const s_pFinishedStr = " finished in: "; + static const char *const s_pFinishedStr = " finished in: "; const char *pFinished = str_find(pStr, s_pFinishedStr); if(!pFinished) return -1; @@ -78,9 +78,9 @@ bool CRaceHelper::IsStart(CGameClient *pClient, vec2 Prev, vec2 Pos) } else { - std::list < int > Indices = pCollision->GetMapIndices(Prev, Pos); + std::list Indices = pCollision->GetMapIndices(Prev, Pos); if(!Indices.empty()) - for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + for(std::list::iterator i = Indices.begin(); i != Indices.end(); i++) { if(pCollision->GetTileIndex(*i) == TILE_START) return true; diff --git a/src/game/client/render.cpp b/src/game/client/render.cpp index 1213ba0fd..909550bd8 100644 --- a/src/game/client/render.cpp +++ b/src/game/client/render.cpp @@ -4,19 +4,18 @@ #include -#include +#include "animstate.h" +#include "render.h" #include #include +#include #include #include #include -#include "animstate.h" -#include "render.h" static float gs_SpriteWScale; static float gs_SpriteHScale; - /* static void layershot_begin() { @@ -50,15 +49,15 @@ void CRenderTools::Init(IGraphics *pGraphics, CUI *pUI) QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f, false); SelectSprite(SPRITE_TEE_EYE_PAIN, 0, 0, 0); - QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f*0.4f, false); + QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f * 0.4f, false); SelectSprite(SPRITE_TEE_EYE_HAPPY, 0, 0, 0); - QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f*0.4f, false); + QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f * 0.4f, false); SelectSprite(SPRITE_TEE_EYE_SURPRISE, 0, 0, 0); - QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f*0.4f, false); + QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f * 0.4f, false); SelectSprite(SPRITE_TEE_EYE_ANGRY, 0, 0, 0); - QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f*0.4f, false); + QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f * 0.4f, false); SelectSprite(SPRITE_TEE_EYE_NORMAL, 0, 0, 0); - QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f*0.4f, false); + QuadContainerAddSprite(m_TeeQuadContainerIndex, 64.f * 0.4f, false); SelectSprite(SPRITE_TEE_FOOT_OUTLINE, 0, 0, 0); QuadContainerAddSprite(m_TeeQuadContainerIndex, -32.f, -16.f, 64.f, 32.f); @@ -68,31 +67,31 @@ void CRenderTools::Init(IGraphics *pGraphics, CUI *pUI) void CRenderTools::SelectSprite(CDataSprite *pSpr, int Flags, int sx, int sy) { - int x = pSpr->m_X+sx; - int y = pSpr->m_Y+sy; + int x = pSpr->m_X + sx; + int y = pSpr->m_Y + sy; int w = pSpr->m_W; int h = pSpr->m_H; int cx = pSpr->m_pSet->m_Gridx; int cy = pSpr->m_pSet->m_Gridy; - float f = sqrtf(h*h + w*w); - gs_SpriteWScale = w/f; - gs_SpriteHScale = h/f; + float f = sqrtf(h * h + w * w); + gs_SpriteWScale = w / f; + gs_SpriteHScale = h / f; - float x1 = x/(float)cx + 0.5f/(float)(cx*32); - float x2 = (x+w)/(float)cx - 0.5f/(float)(cx*32); - float y1 = y/(float)cy + 0.5f/(float)(cy*32); - float y2 = (y+h)/(float)cy - 0.5f/(float)(cy*32); + float x1 = x / (float)cx + 0.5f / (float)(cx * 32); + float x2 = (x + w) / (float)cx - 0.5f / (float)(cx * 32); + float y1 = y / (float)cy + 0.5f / (float)(cy * 32); + float y2 = (y + h) / (float)cy - 0.5f / (float)(cy * 32); float Temp = 0; - if(Flags&SPRITE_FLAG_FLIP_Y) + if(Flags & SPRITE_FLAG_FLIP_Y) { Temp = y1; y1 = y2; y2 = Temp; } - if(Flags&SPRITE_FLAG_FLIP_X) + if(Flags & SPRITE_FLAG_FLIP_X) { Temp = x1; x1 = x2; @@ -111,7 +110,7 @@ void CRenderTools::SelectSprite(int Id, int Flags, int sx, int sy) void CRenderTools::DrawSprite(float x, float y, float Size) { - IGraphics::CQuadItem QuadItem(x, y, Size*gs_SpriteWScale, Size*gs_SpriteHScale); + IGraphics::CQuadItem QuadItem(x, y, Size * gs_SpriteWScale, Size * gs_SpriteHScale); Graphics()->QuadsDraw(&QuadItem, 1); } @@ -119,7 +118,7 @@ void CRenderTools::QuadContainerAddSprite(int QuadContainerIndex, float x, float { if(DoSpriteScale) { - IGraphics::CQuadItem QuadItem(x, y, Size*gs_SpriteWScale, Size*gs_SpriteHScale); + IGraphics::CQuadItem QuadItem(x, y, Size * gs_SpriteWScale, Size * gs_SpriteHScale); Graphics()->QuadContainerAddQuads(QuadContainerIndex, &QuadItem, 1); } else @@ -133,7 +132,7 @@ void CRenderTools::QuadContainerAddSprite(int QuadContainerIndex, float Size, bo { if(DoSpriteScale) { - IGraphics::CQuadItem QuadItem(-(Size*gs_SpriteWScale) / 2.f, -(Size*gs_SpriteHScale) / 2.f, (Size*gs_SpriteWScale), (Size*gs_SpriteHScale)); + IGraphics::CQuadItem QuadItem(-(Size * gs_SpriteWScale) / 2.f, -(Size * gs_SpriteHScale) / 2.f, (Size * gs_SpriteWScale), (Size * gs_SpriteHScale)); Graphics()->QuadContainerAddQuads(QuadContainerIndex, &QuadItem, 1); } else @@ -154,11 +153,11 @@ void CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, IGraphics::CFreeformItem ArrayF[32]; int NumItems = 0; int Num = 8; - for(int i = 0; i < Num; i+=2) + for(int i = 0; i < Num; i += 2) { - float a1 = i/(float)Num * pi/2; - float a2 = (i+1)/(float)Num * pi/2; - float a3 = (i+2)/(float)Num * pi/2; + float a1 = i / (float)Num * pi / 2; + float a2 = (i + 1) / (float)Num * pi / 2; + float a3 = (i + 2) / (float)Num * pi / 2; float Ca1 = cosf(a1); float Ca2 = cosf(a2); float Ca3 = cosf(a3); @@ -166,48 +165,52 @@ void CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, float Sa2 = sinf(a2); float Sa3 = sinf(a3); - if(Corners&1) // TL - ArrayF[NumItems++] = IGraphics::CFreeformItem( - x+r, y+r, - x+(1-Ca1)*r, y+(1-Sa1)*r, - x+(1-Ca3)*r, y+(1-Sa3)*r, - x+(1-Ca2)*r, y+(1-Sa2)*r); + if(Corners & 1) // TL + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x + r, y + r, + x + (1 - Ca1) * r, y + (1 - Sa1) * r, + x + (1 - Ca3) * r, y + (1 - Sa3) * r, + x + (1 - Ca2) * r, y + (1 - Sa2) * r); - if(Corners&2) // TR - ArrayF[NumItems++] = IGraphics::CFreeformItem( - x+w-r, y+r, - x+w-r+Ca1*r, y+(1-Sa1)*r, - x+w-r+Ca3*r, y+(1-Sa3)*r, - x+w-r+Ca2*r, y+(1-Sa2)*r); + if(Corners & 2) // TR + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x + w - r, y + r, + x + w - r + Ca1 * r, y + (1 - Sa1) * r, + x + w - r + Ca3 * r, y + (1 - Sa3) * r, + x + w - r + Ca2 * r, y + (1 - Sa2) * r); - if(Corners&4) // BL - ArrayF[NumItems++] = IGraphics::CFreeformItem( - x+r, y+h-r, - x+(1-Ca1)*r, y+h-r+Sa1*r, - x+(1-Ca3)*r, y+h-r+Sa3*r, - x+(1-Ca2)*r, y+h-r+Sa2*r); + if(Corners & 4) // BL + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x + r, y + h - r, + x + (1 - Ca1) * r, y + h - r + Sa1 * r, + x + (1 - Ca3) * r, y + h - r + Sa3 * r, + x + (1 - Ca2) * r, y + h - r + Sa2 * r); - if(Corners&8) // BR - ArrayF[NumItems++] = IGraphics::CFreeformItem( - x+w-r, y+h-r, - x+w-r+Ca1*r, y+h-r+Sa1*r, - x+w-r+Ca3*r, y+h-r+Sa3*r, - x+w-r+Ca2*r, y+h-r+Sa2*r); + if(Corners & 8) // BR + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x + w - r, y + h - r, + x + w - r + Ca1 * r, y + h - r + Sa1 * r, + x + w - r + Ca3 * r, y + h - r + Sa3 * r, + x + w - r + Ca2 * r, y + h - r + Sa2 * r); } Graphics()->QuadsDrawFreeform(ArrayF, NumItems); IGraphics::CQuadItem ArrayQ[9]; NumItems = 0; - ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center - ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top - ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom - ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left - ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + r, y + r, w - r * 2, h - r * 2); // center + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + r, y, w - r * 2, r); // top + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + r, y + h - r, w - r * 2, r); // bottom + ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y + r, r, h - r * 2); // left + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w - r, y + r, r, h - r * 2); // right - if(!(Corners&1)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL - if(!(Corners&2)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y, -r, r); // TR - if(!(Corners&4)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+h, r, -r); // BL - if(!(Corners&8)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR + if(!(Corners & 1)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL + if(!(Corners & 2)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y, -r, r); // TR + if(!(Corners & 4)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y + h, r, -r); // BL + if(!(Corners & 8)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y + h, -r, -r); // BR Graphics()->QuadsDrawTL(ArrayQ, NumItems); } @@ -380,23 +383,23 @@ int CRenderTools::CreateRoundRectQuadContainer(float x, float y, float w, float if(Corners & 1) // TL ArrayF[NumItems++] = IGraphics::CFreeformItem( x + r, y + r, - x + (1 - Ca1)*r, y + (1 - Sa1)*r, - x + (1 - Ca3)*r, y + (1 - Sa3)*r, - x + (1 - Ca2)*r, y + (1 - Sa2)*r); + x + (1 - Ca1) * r, y + (1 - Sa1) * r, + x + (1 - Ca3) * r, y + (1 - Sa3) * r, + x + (1 - Ca2) * r, y + (1 - Sa2) * r); if(Corners & 2) // TR ArrayF[NumItems++] = IGraphics::CFreeformItem( x + w - r, y + r, - x + w - r + Ca1 * r, y + (1 - Sa1)*r, - x + w - r + Ca3 * r, y + (1 - Sa3)*r, - x + w - r + Ca2 * r, y + (1 - Sa2)*r); + x + w - r + Ca1 * r, y + (1 - Sa1) * r, + x + w - r + Ca3 * r, y + (1 - Sa3) * r, + x + w - r + Ca2 * r, y + (1 - Sa2) * r); if(Corners & 4) // BL ArrayF[NumItems++] = IGraphics::CFreeformItem( x + r, y + h - r, - x + (1 - Ca1)*r, y + h - r + Sa1 * r, - x + (1 - Ca3)*r, y + h - r + Sa3 * r, - x + (1 - Ca2)*r, y + h - r + Sa2 * r); + x + (1 - Ca1) * r, y + h - r + Sa1 * r, + x + (1 - Ca3) * r, y + h - r + Sa3 * r, + x + (1 - Ca2) * r, y + h - r + Sa2 * r); if(Corners & 8) // BR ArrayF[NumItems++] = IGraphics::CFreeformItem( @@ -415,10 +418,14 @@ int CRenderTools::CreateRoundRectQuadContainer(float x, float y, float w, float ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y + r, r, h - r * 2); // left ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w - r, y + r, r, h - r * 2); // right - if(!(Corners & 1)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL - if(!(Corners & 2)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y, -r, r); // TR - if(!(Corners & 4)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y + h, r, -r); // BL - if(!(Corners & 8)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y + h, -r, -r); // BR + if(!(Corners & 1)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL + if(!(Corners & 2)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y, -r, r); // TR + if(!(Corners & 4)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y + h, r, -r); // BL + if(!(Corners & 8)) + ArrayQ[NumItems++] = IGraphics::CQuadItem(x + w, y + h, -r, -r); // BR Graphics()->QuadContainerAddQuads(ContainerIndex, ArrayQ, NumItems); @@ -427,7 +434,7 @@ int CRenderTools::CreateRoundRectQuadContainer(float x, float y, float w, float void CRenderTools::DrawRoundRect(float x, float y, float w, float h, float r) { - DrawRoundRectExt(x,y,w,h,r,0xf); + DrawRoundRectExt(x, y, w, h, r, 0xf); } void CRenderTools::DrawUIRect(const CUIRect *r, ColorRGBA Color, int Corners, float Rounding) @@ -437,7 +444,7 @@ void CRenderTools::DrawUIRect(const CUIRect *r, ColorRGBA Color, int Corners, fl // TODO: FIX US Graphics()->QuadsBegin(); Graphics()->SetColor(Color); - DrawRoundRectExt(r->x,r->y,r->w,r->h,Rounding*UI()->Scale(), Corners); + DrawRoundRectExt(r->x, r->y, r->w, r->h, Rounding * UI()->Scale(), Corners); Graphics()->QuadsEnd(); } @@ -455,11 +462,11 @@ void CRenderTools::DrawCircle(float x, float y, float r, int Segments) IGraphics::CFreeformItem Array[32]; int NumItems = 0; float FSegments = (float)Segments; - for(int i = 0; i < Segments; i+=2) + for(int i = 0; i < Segments; i += 2) { - float a1 = i/FSegments * 2*pi; - float a2 = (i+1)/FSegments * 2*pi; - float a3 = (i+2)/FSegments * 2*pi; + float a1 = i / FSegments * 2 * pi; + float a2 = (i + 1) / FSegments * 2 * pi; + float a3 = (i + 2) / FSegments * 2 * pi; float Ca1 = cosf(a1); float Ca2 = cosf(a2); float Ca3 = cosf(a3); @@ -469,9 +476,9 @@ void CRenderTools::DrawCircle(float x, float y, float r, int Segments) Array[NumItems++] = IGraphics::CFreeformItem( x, y, - x+Ca1*r, y+Sa1*r, - x+Ca3*r, y+Sa3*r, - x+Ca2*r, y+Sa2*r); + x + Ca1 * r, y + Sa1 * r, + x + Ca3 * r, y + Sa3 * r, + x + Ca2 * r, y + Sa2 * r); if(NumItems == 32) { Graphics()->QuadsDrawFreeform(Array, 32); @@ -494,19 +501,19 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote // second pass we draw the filling for(int p = 0; p < 2; p++) { - int OutLine = p==0 ? 1 : 0; + int OutLine = p == 0 ? 1 : 0; for(int f = 0; f < 2; f++) { - float AnimScale = pInfo->m_Size * 1.0f/64.0f; + float AnimScale = pInfo->m_Size * 1.0f / 64.0f; float BaseSize = pInfo->m_Size; if(f == 1) { - Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); + Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle * pi * 2); // draw body Graphics()->SetColor(pInfo->m_ColorBody.r, pInfo->m_ColorBody.g, pInfo->m_ColorBody.b, Alpha); - vec2 BodyPos = Position + vec2(pAnim->GetBody()->m_X, pAnim->GetBody()->m_Y)*AnimScale; + vec2 BodyPos = Position + vec2(pAnim->GetBody()->m_X, pAnim->GetBody()->m_Y) * AnimScale; float BodySize = g_Config.m_ClFatSkins ? BaseSize * 1.3f : BaseSize; Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, OutLine, BodyPos.x, BodyPos.y, BodySize / 64.f, BodySize / 64.f); @@ -515,32 +522,32 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote { int QuadOffset = 2; int EyeQuadOffset = 0; - switch (Emote) + switch(Emote) { - case EMOTE_PAIN: - EyeQuadOffset = 0; - break; - case EMOTE_HAPPY: - EyeQuadOffset = 1; - break; - case EMOTE_SURPRISE: - EyeQuadOffset = 2; - break; - case EMOTE_ANGRY: - EyeQuadOffset = 3; - break; - default: - EyeQuadOffset = 4; - break; + case EMOTE_PAIN: + EyeQuadOffset = 0; + break; + case EMOTE_HAPPY: + EyeQuadOffset = 1; + break; + case EMOTE_SURPRISE: + EyeQuadOffset = 2; + break; + case EMOTE_ANGRY: + EyeQuadOffset = 3; + break; + default: + EyeQuadOffset = 4; + break; } - float EyeScale = BaseSize*0.40f; - float h = Emote == EMOTE_BLINK ? BaseSize*0.15f : EyeScale; - float EyeSeparation = (0.075f - 0.010f*absolute(Direction.x))*BaseSize; - vec2 Offset = vec2(Direction.x*0.125f, -0.05f+Direction.y*0.10f)*BaseSize; + float EyeScale = BaseSize * 0.40f; + float h = Emote == EMOTE_BLINK ? BaseSize * 0.15f : EyeScale; + float EyeSeparation = (0.075f - 0.010f * absolute(Direction.x)) * BaseSize; + vec2 Offset = vec2(Direction.x * 0.125f, -0.05f + Direction.y * 0.10f) * BaseSize; - Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset + EyeQuadOffset, BodyPos.x - EyeSeparation + Offset.x, BodyPos.y + Offset.y, EyeScale / (64.f*0.4f), h / (64.f*0.4f)); - Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset + EyeQuadOffset, BodyPos.x + EyeSeparation + Offset.x, BodyPos.y + Offset.y, -EyeScale / (64.f*0.4f), h / (64.f*0.4f)); + Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset + EyeQuadOffset, BodyPos.x - EyeSeparation + Offset.x, BodyPos.y + Offset.y, EyeScale / (64.f * 0.4f), h / (64.f * 0.4f)); + Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset + EyeQuadOffset, BodyPos.x + EyeSeparation + Offset.x, BodyPos.y + Offset.y, -EyeScale / (64.f * 0.4f), h / (64.f * 0.4f)); } } @@ -548,11 +555,11 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote CAnimKeyframe *pFoot = f ? pAnim->GetFrontFoot() : pAnim->GetBackFoot(); float w = BaseSize; - float h = BaseSize/2; + float h = BaseSize / 2; int QuadOffset = 7; - Graphics()->QuadsSetRotation(pFoot->m_Angle*pi*2); + Graphics()->QuadsSetRotation(pFoot->m_Angle * pi * 2); bool Indicate = !pInfo->m_GotAirJump && g_Config.m_ClAirjumpindicator; float cs = 1.0f; // color scale @@ -564,15 +571,14 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote cs = 0.5f; } - Graphics()->SetColor(pInfo->m_ColorFeet.r*cs, pInfo->m_ColorFeet.g*cs, pInfo->m_ColorFeet.b*cs, Alpha); + Graphics()->SetColor(pInfo->m_ColorFeet.r * cs, pInfo->m_ColorFeet.g * cs, pInfo->m_ColorFeet.b * cs, Alpha); - Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset, Position.x + pFoot->m_X*AnimScale, Position.y + pFoot->m_Y*AnimScale, w / 64.f, h / 32.f); + Graphics()->RenderQuadContainerAsSprite(m_TeeQuadContainerIndex, QuadOffset, Position.x + pFoot->m_X * AnimScale, Position.y + pFoot->m_Y * AnimScale, w / 64.f, h / 32.f); } } Graphics()->SetColor(1.f, 1.f, 1.f, 1.f); Graphics()->QuadsSetRotation(0); - } void CRenderTools::CalcScreenParams(float Aspect, float Zoom, float *w, float *h) @@ -582,20 +588,20 @@ void CRenderTools::CalcScreenParams(float Aspect, float Zoom, float *w, float *h const float HMax = 1050; float f = sqrtf(Amount) / sqrtf(Aspect); - *w = f*Aspect; + *w = f * Aspect; *h = f; // limit the view if(*w > WMax) { *w = WMax; - *h = *w/Aspect; + *h = *w / Aspect; } if(*h > HMax) { *h = HMax; - *w = *h*Aspect; + *w = *h * Aspect; } *w *= Zoom; @@ -607,12 +613,12 @@ void CRenderTools::MapscreenToWorld(float CenterX, float CenterY, float Parallax { float Width, Height; CalcScreenParams(Aspect, Zoom, &Width, &Height); - CenterX *= ParallaxX/100.0f; - CenterY *= ParallaxY/100.0f; - pPoints[0] = OffsetX+CenterX-Width/2; - pPoints[1] = OffsetY+CenterY-Height/2; - pPoints[2] = pPoints[0]+Width; - pPoints[3] = pPoints[1]+Height; + CenterX *= ParallaxX / 100.0f; + CenterY *= ParallaxY / 100.0f; + pPoints[0] = OffsetX + CenterX - Width / 2; + pPoints[1] = OffsetY + CenterY - Height / 2; + pPoints[2] = pPoints[0] + Width; + pPoints[3] = pPoints[1] + Height; } void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) @@ -623,7 +629,7 @@ void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer + l); if(pLayer->m_Type == LAYERTYPE_TILES) { @@ -634,13 +640,13 @@ void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) for(int x = 1; x < pTmap->m_Width;) { int sx; - for(sx = 1; x+sx < pTmap->m_Width && sx < 255; sx++) + for(sx = 1; x + sx < pTmap->m_Width && sx < 255; sx++) { - if(pTiles[y*pTmap->m_Width+x+sx].m_Index) + if(pTiles[y * pTmap->m_Width + x + sx].m_Index) break; } - pTiles[y*pTmap->m_Width+x].m_Skip = sx-1; + pTiles[y * pTmap->m_Width + x].m_Skip = sx - 1; x += sx; } } diff --git a/src/game/client/render.h b/src/game/client/render.h index ac1ab6a0a..1b3838329 100644 --- a/src/game/client/render.h +++ b/src/game/client/render.h @@ -3,19 +3,19 @@ #ifndef GAME_CLIENT_RENDER_H #define GAME_CLIENT_RENDER_H -#include -#include -#include -#include #include "ui.h" +#include +#include +#include +#include class CTeeRenderInfo { public: CTeeRenderInfo() { - m_ColorBody = ColorRGBA(1,1,1); - m_ColorFeet = ColorRGBA(1,1,1); + m_ColorBody = ColorRGBA(1, 1, 1); + m_ColorFeet = ColorRGBA(1, 1, 1); m_Size = 1.0f; m_GotAirJump = 1; }; @@ -30,13 +30,13 @@ public: // sprite renderings enum { - SPRITE_FLAG_FLIP_Y=1, - SPRITE_FLAG_FLIP_X=2, + SPRITE_FLAG_FLIP_Y = 1, + SPRITE_FLAG_FLIP_X = 2, - LAYERRENDERFLAG_OPAQUE=1, - LAYERRENDERFLAG_TRANSPARENT=2, + LAYERRENDERFLAG_OPAQUE = 1, + LAYERRENDERFLAG_TRANSPARENT = 2, - TILERENDERFLAG_EXTEND=4, + TILERENDERFLAG_EXTEND = 4, }; typedef void (*ENVELOPE_EVAL)(float TimeOffset, int Env, float *pChannels, void *pUser); @@ -44,6 +44,7 @@ typedef void (*ENVELOPE_EVAL)(float TimeOffset, int Env, float *pChannels, void class CRenderTools { int m_TeeQuadContainerIndex; + public: class IGraphics *m_pGraphics; class CUI *m_pUI; @@ -55,8 +56,8 @@ public: //typedef struct SPRITE; - void SelectSprite(struct CDataSprite *pSprite, int Flags=0, int sx=0, int sy=0); - void SelectSprite(int id, int Flags=0, int sx=0, int sy=0); + void SelectSprite(struct CDataSprite *pSprite, int Flags = 0, int sx = 0, int sy = 0); + void SelectSprite(int id, int Flags = 0, int sx = 0, int sy = 0); void DrawSprite(float x, float y, float size); void QuadContainerAddSprite(int QuadContainerIndex, float x, float y, float size, bool DoSpriteScale = true); @@ -98,10 +99,10 @@ public: // DDRace - void RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale, float Alpha=1.0f); - void RenderSpeedupOverlay(CSpeedupTile *pTele, int w, int h, float Scale, float Alpha=1.0f); - void RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float Scale, float Alpha=1.0f); - void RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale, float Alpha=1.0f); + void RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale, float Alpha = 1.0f); + void RenderSpeedupOverlay(CSpeedupTile *pTele, int w, int h, float Scale, float Alpha = 1.0f); + void RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float Scale, float Alpha = 1.0f); + void RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale, float Alpha = 1.0f); void RenderTelemap(CTeleTile *pTele, int w, int h, float Scale, ColorRGBA Color, int RenderFlags); void RenderSpeedupmap(CSpeedupTile *pTele, int w, int h, float Scale, ColorRGBA Color, int RenderFlags); void RenderSwitchmap(CSwitchTile *pSwitch, int w, int h, float Scale, ColorRGBA Color, int RenderFlags); diff --git a/src/game/client/render_map.cpp b/src/game/client/render_map.cpp index 28ec0e345..c098109ae 100644 --- a/src/game/client/render_map.cpp +++ b/src/game/client/render_map.cpp @@ -1,15 +1,15 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include #include +#include #include "render.h" -#include #include -#include +#include #include +#include void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult) { @@ -31,25 +31,24 @@ void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Cha return; } - Time = fmod(Time, pPoints[NumPoints-1].m_Time/1000.0f)*1000.0f; - for(int i = 0; i < NumPoints-1; i++) + Time = fmod(Time, pPoints[NumPoints - 1].m_Time / 1000.0f) * 1000.0f; + for(int i = 0; i < NumPoints - 1; i++) { - if(Time >= pPoints[i].m_Time && Time <= pPoints[i+1].m_Time) + if(Time >= pPoints[i].m_Time && Time <= pPoints[i + 1].m_Time) { - float Delta = pPoints[i+1].m_Time-pPoints[i].m_Time; - float a = (Time-pPoints[i].m_Time)/Delta; - + float Delta = pPoints[i + 1].m_Time - pPoints[i].m_Time; + float a = (Time - pPoints[i].m_Time) / Delta; if(pPoints[i].m_Curvetype == CURVETYPE_SMOOTH) - a = -2*a*a*a + 3*a*a; // second hermite basis + a = -2 * a * a * a + 3 * a * a; // second hermite basis else if(pPoints[i].m_Curvetype == CURVETYPE_SLOW) - a = a*a*a; + a = a * a * a; else if(pPoints[i].m_Curvetype == CURVETYPE_FAST) { - a = 1-a; - a = 1-a*a*a; + a = 1 - a; + a = 1 - a * a * a; } - else if (pPoints[i].m_Curvetype == CURVETYPE_STEP) + else if(pPoints[i].m_Curvetype == CURVETYPE_STEP) a = 0; else { @@ -59,22 +58,21 @@ void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Cha for(int c = 0; c < Channels; c++) { float v0 = fx2f(pPoints[i].m_aValues[c]); - float v1 = fx2f(pPoints[i+1].m_aValues[c]); - pResult[c] = v0 + (v1-v0) * a; + float v1 = fx2f(pPoints[i + 1].m_aValues[c]); + pResult[c] = v0 + (v1 - v0) * a; } return; } } - pResult[0] = fx2f(pPoints[NumPoints-1].m_aValues[0]); - pResult[1] = fx2f(pPoints[NumPoints-1].m_aValues[1]); - pResult[2] = fx2f(pPoints[NumPoints-1].m_aValues[2]); - pResult[3] = fx2f(pPoints[NumPoints-1].m_aValues[3]); + pResult[0] = fx2f(pPoints[NumPoints - 1].m_aValues[0]); + pResult[1] = fx2f(pPoints[NumPoints - 1].m_aValues[1]); + pResult[2] = fx2f(pPoints[NumPoints - 1].m_aValues[2]); + pResult[3] = fx2f(pPoints[NumPoints - 1].m_aValues[3]); return; } - static void Rotate(CPoint *pCenter, CPoint *pPoint, float Rotation) { int x = pPoint->x - pCenter->x; @@ -88,23 +86,23 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENV if(!g_Config.m_ClShowQuads || g_Config.m_ClOverlayEntities == 100) return; - ForceRenderQuads(pQuads, NumQuads, RenderFlags, pfnEval, pUser, (100-g_Config.m_ClOverlayEntities)/100.0f); + ForceRenderQuads(pQuads, NumQuads, RenderFlags, pfnEval, pUser, (100 - g_Config.m_ClOverlayEntities) / 100.0f); } void CRenderTools::ForceRenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, float Alpha) { Graphics()->QuadsBegin(); - float Conv = 1/255.0f; + float Conv = 1 / 255.0f; for(int i = 0; i < NumQuads; i++) { CQuad *q = &pQuads[i]; - float r=1, g=1, b=1, a=1; + float r = 1, g = 1, b = 1, a = 1; if(q->m_ColorEnv >= 0) { float aChannels[4]; - pfnEval(q->m_ColorEnvOffset/1000.0f, q->m_ColorEnv, aChannels, pUser); + pfnEval(q->m_ColorEnvOffset / 1000.0f, q->m_ColorEnv, aChannels, pUser); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; @@ -116,17 +114,16 @@ void CRenderTools::ForceRenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags if(a < 0.01f || (q->m_aColors[0].a < 0.01f && q->m_aColors[1].a < 0.01f && q->m_aColors[2].a < 0.01f && q->m_aColors[3].a < 0.01f)) Opaque = true; */ - if(Opaque && !(RenderFlags&LAYERRENDERFLAG_OPAQUE)) + if(Opaque && !(RenderFlags & LAYERRENDERFLAG_OPAQUE)) continue; - if(!Opaque && !(RenderFlags&LAYERRENDERFLAG_TRANSPARENT)) + if(!Opaque && !(RenderFlags & LAYERRENDERFLAG_TRANSPARENT)) continue; Graphics()->QuadsSetSubsetFree( fx2f(q->m_aTexcoords[0].x), fx2f(q->m_aTexcoords[0].y), fx2f(q->m_aTexcoords[1].x), fx2f(q->m_aTexcoords[1].y), fx2f(q->m_aTexcoords[2].x), fx2f(q->m_aTexcoords[2].y), - fx2f(q->m_aTexcoords[3].x), fx2f(q->m_aTexcoords[3].y) - ); + fx2f(q->m_aTexcoords[3].x), fx2f(q->m_aTexcoords[3].y)); float OffsetX = 0; float OffsetY = 0; @@ -136,17 +133,17 @@ void CRenderTools::ForceRenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags if(q->m_PosEnv >= 0) { float aChannels[4]; - pfnEval(q->m_PosEnvOffset/1000.0f, q->m_PosEnv, aChannels, pUser); + pfnEval(q->m_PosEnvOffset / 1000.0f, q->m_PosEnv, aChannels, pUser); OffsetX = aChannels[0]; OffsetY = aChannels[1]; - Rot = aChannels[2]/360.0f*pi*2; + Rot = aChannels[2] / 360.0f * pi * 2; } IGraphics::CColorVertex Array[4] = { - IGraphics::CColorVertex(0, q->m_aColors[0].r*Conv*r, q->m_aColors[0].g*Conv*g, q->m_aColors[0].b*Conv*b, q->m_aColors[0].a*Conv*a*Alpha), - IGraphics::CColorVertex(1, q->m_aColors[1].r*Conv*r, q->m_aColors[1].g*Conv*g, q->m_aColors[1].b*Conv*b, q->m_aColors[1].a*Conv*a*Alpha), - IGraphics::CColorVertex(2, q->m_aColors[2].r*Conv*r, q->m_aColors[2].g*Conv*g, q->m_aColors[2].b*Conv*b, q->m_aColors[2].a*Conv*a*Alpha), - IGraphics::CColorVertex(3, q->m_aColors[3].r*Conv*r, q->m_aColors[3].g*Conv*g, q->m_aColors[3].b*Conv*b, q->m_aColors[3].a*Conv*a*Alpha)}; + IGraphics::CColorVertex(0, q->m_aColors[0].r * Conv * r, q->m_aColors[0].g * Conv * g, q->m_aColors[0].b * Conv * b, q->m_aColors[0].a * Conv * a * Alpha), + IGraphics::CColorVertex(1, q->m_aColors[1].r * Conv * r, q->m_aColors[1].g * Conv * g, q->m_aColors[1].b * Conv * b, q->m_aColors[1].a * Conv * a * Alpha), + IGraphics::CColorVertex(2, q->m_aColors[2].r * Conv * r, q->m_aColors[2].g * Conv * g, q->m_aColors[2].b * Conv * b, q->m_aColors[2].a * Conv * a * Alpha), + IGraphics::CColorVertex(3, q->m_aColors[3].r * Conv * r, q->m_aColors[3].g * Conv * g, q->m_aColors[3].b * Conv * b, q->m_aColors[3].a * Conv * a * Alpha)}; Graphics()->SetColorVertex(Array, 4); CPoint *pPoints = q->m_aPoints; @@ -167,33 +164,33 @@ void CRenderTools::ForceRenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags } IGraphics::CFreeformItem Freeform( - fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, - fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, - fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, - fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); + fx2f(pPoints[0].x) + OffsetX, fx2f(pPoints[0].y) + OffsetY, + fx2f(pPoints[1].x) + OffsetX, fx2f(pPoints[1].y) + OffsetY, + fx2f(pPoints[2].x) + OffsetX, fx2f(pPoints[2].y) + OffsetY, + fx2f(pPoints[3].x) + OffsetX, fx2f(pPoints[3].y) + OffsetY); Graphics()->QuadsDrawFreeform(&Freeform, 1); } Graphics()->QuadsEnd(); } void CRenderTools::RenderTileRectangle(int RectX, int RectY, int RectW, int RectH, - unsigned char IndexIn, unsigned char IndexOut, - float Scale, ColorRGBA Color, int RenderFlags, - ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset) + unsigned char IndexIn, unsigned char IndexOut, + float Scale, ColorRGBA Color, int RenderFlags, + ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset) { float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; - float r=1, g=1, b=1, a=1; + float r = 1, g = 1, b = 1, a = 1; if(ColorEnv >= 0) { float aChannels[4]; - pfnEval(ColorEnvOffset/1000.0f, ColorEnv, aChannels, pUser); + pfnEval(ColorEnvOffset / 1000.0f, ColorEnv, aChannels, pUser); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; @@ -201,49 +198,49 @@ void CRenderTools::RenderTileRectangle(int RectX, int RectY, int RectW, int Rect } Graphics()->QuadsBegin(); - Graphics()->SetColor(Color.r*r, Color.g*g, Color.b*b, Color.a*a); + Graphics()->SetColor(Color.r * r, Color.g * g, Color.b * b, Color.a * a); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) { for(int x = StartX; x < EndX; x++) { - unsigned char Index = (x>=RectX && x=RectY && y= RectX && x < RectX + RectW && y >= RectY && y < RectY + RectH) ? IndexIn : IndexOut; if(Index) { bool Render = false; - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; if(Render) { - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); - IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + IGraphics::CQuadItem QuadItem(x * Scale, y * Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } @@ -261,15 +258,15 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; - float r=1, g=1, b=1, a=1; + float r = 1, g = 1, b = 1, a = 1; if(ColorEnv >= 0) { float aChannels[4]; - pfnEval(ColorEnvOffset/1000.0f, ColorEnv, aChannels, pUser); + pfnEval(ColorEnvOffset / 1000.0f, ColorEnv, aChannels, pUser); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; @@ -282,15 +279,15 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color Graphics()->QuadsBegin(); Graphics()->SetColor(Color.r * r, Color.g * g, Color.b * b, Color.a * a); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) { @@ -299,30 +296,30 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color int mx = x; int my = y; - if(RenderFlags&TILERENDERFLAG_EXTEND) + if(RenderFlags & TILERENDERFLAG_EXTEND) { - if(mx<0) + if(mx < 0) mx = 0; - if(mx>=w) - mx = w-1; - if(my<0) + if(mx >= w) + mx = w - 1; + if(my < 0) my = 0; - if(my>=h) - my = h-1; + if(my >= h) + my = h - 1; } else { - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; } - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pTiles[c].m_Index; if(Index) @@ -330,34 +327,34 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color unsigned char Flags = pTiles[c].m_Flags; bool Render = false; - if(Flags&TILEFLAG_OPAQUE && Color.a*a > 254.0f/255.0f) + if(Flags & TILEFLAG_OPAQUE && Color.a * a > 254.0f / 255.0f) { - if(RenderFlags&LAYERRENDERFLAG_OPAQUE) + if(RenderFlags & LAYERRENDERFLAG_OPAQUE) Render = true; } else { - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; } if(Render) { - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; if(Graphics()->IsTileBufferingEnabled()) { @@ -379,7 +376,7 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color x3 = x0; } - if(Flags&TILEFLAG_HFLIP) + if(Flags & TILEFLAG_HFLIP) { y0 = y3; y2 = y1; @@ -387,7 +384,7 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color y1 = y0; } - if(Flags&TILEFLAG_ROTATE) + if(Flags & TILEFLAG_ROTATE) { float Tmp = x0; x0 = x3; @@ -429,21 +426,21 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, Color void CRenderTools::RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale, float Alpha) { if(!g_Config.m_ClTextEntities) - return; + return; float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; if(EndX - StartX > Graphics()->ScreenWidth() / g_Config.m_GfxTextOverlay || EndY - StartY > Graphics()->ScreenHeight() / g_Config.m_GfxTextOverlay) return; // its useless to render text at this distance - float Size = g_Config.m_ClTextEntitiesSize/100.f; - float ToCenterOffset = (1-Size)/2.f; + float Size = g_Config.m_ClTextEntitiesSize / 100.f; + float ToCenterOffset = (1 - Size) / 2.f; for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -451,17 +448,16 @@ void CRenderTools::RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale int mx = x; int my = y; - - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pTele[c].m_Number; if(Index && pTele[c].m_Type != TILE_TELECHECKIN && pTele[c].m_Type != TILE_TELECHECKINEVIL) @@ -469,7 +465,7 @@ void CRenderTools::RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Index); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale - 3.f, (my+ToCenterOffset)*Scale, Size*Scale, aBuf, -1.0f); + UI()->TextRender()->Text(0, mx * Scale - 3.f, (my + ToCenterOffset) * Scale, Size * Scale, aBuf, -1.0f); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } @@ -482,16 +478,16 @@ void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, fl float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; if(EndX - StartX > Graphics()->ScreenWidth() / g_Config.m_GfxTextOverlay || EndY - StartY > Graphics()->ScreenHeight() / g_Config.m_GfxTextOverlay) return; // its useless to render text at this distance float Size = g_Config.m_ClTextEntitiesSize / 100.f; - float ToCenterOffset = (1-Size)/2.f; + float ToCenterOffset = (1 - Size) / 2.f; for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -499,16 +495,16 @@ void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, fl int mx = x; int my = y; - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; - int c = mx + my*w; + int c = mx + my * w; int Force = (int)pSpeedup[c].m_Force; int MaxSpeed = (int)pSpeedup[c].m_MaxSpeed; @@ -520,8 +516,8 @@ void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, fl Graphics()->SetColor(255.0f, 255.0f, 255.0f, Alpha); SelectSprite(SPRITE_SPEEDUP_ARROW); - Graphics()->QuadsSetRotation(pSpeedup[c].m_Angle*(3.14159265f/180.0f)); - DrawSprite(mx*Scale+16, my*Scale+16, 35.0f); + Graphics()->QuadsSetRotation(pSpeedup[c].m_Angle * (3.14159265f / 180.0f)); + DrawSprite(mx * Scale + 16, my * Scale + 16, 35.0f); Graphics()->QuadsEnd(); @@ -531,13 +527,13 @@ void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, fl char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Force); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale, (my+0.5f+ToCenterOffset/2)*Scale, Size*Scale/2.f, aBuf, -1.0f); + UI()->TextRender()->Text(0, mx * Scale, (my + 0.5f + ToCenterOffset / 2) * Scale, Size * Scale / 2.f, aBuf, -1.0f); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); if(MaxSpeed) { str_format(aBuf, sizeof(aBuf), "%d", MaxSpeed); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale, (my+ToCenterOffset/2)*Scale, Size*Scale/2.f, aBuf, -1.0f); + UI()->TextRender()->Text(0, mx * Scale, (my + ToCenterOffset / 2) * Scale, Size * Scale / 2.f, aBuf, -1.0f); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } @@ -549,21 +545,21 @@ void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, fl void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float Scale, float Alpha) { if(!g_Config.m_ClTextEntities) - return; + return; float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; if(EndX - StartX > Graphics()->ScreenWidth() / g_Config.m_GfxTextOverlay || EndY - StartY > Graphics()->ScreenHeight() / g_Config.m_GfxTextOverlay) return; // its useless to render text at this distance - float Size = g_Config.m_ClTextEntitiesSize/100.f; - float ToCenterOffset = (1-Size)/2.f; + float Size = g_Config.m_ClTextEntitiesSize / 100.f; + float ToCenterOffset = (1 - Size) / 2.f; for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -571,17 +567,16 @@ void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float int mx = x; int my = y; - - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pSwitch[c].m_Number; if(Index) @@ -589,7 +584,7 @@ void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Index); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale, (my+ToCenterOffset/2)*Scale, Size*Scale/2.f, aBuf, -1.0f); + UI()->TextRender()->Text(0, mx * Scale, (my + ToCenterOffset / 2) * Scale, Size * Scale / 2.f, aBuf, -1.0f); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } @@ -599,7 +594,7 @@ void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Delay); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale, (my+0.5f+ToCenterOffset/2)* Scale, Size*Scale/2.f, aBuf, -1.0f); + UI()->TextRender()->Text(0, mx * Scale, (my + 0.5f + ToCenterOffset / 2) * Scale, Size * Scale / 2.f, aBuf, -1.0f); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } @@ -610,20 +605,20 @@ void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float void CRenderTools::RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale, float Alpha) { if(!g_Config.m_ClTextEntities) - return; + return; float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; if(EndX - StartX > Graphics()->ScreenWidth() / g_Config.m_GfxTextOverlay || EndY - StartY > Graphics()->ScreenHeight() / g_Config.m_GfxTextOverlay) return; // its useless to render text at this distance - float Size = g_Config.m_ClTextEntitiesSize/100.f; + float Size = g_Config.m_ClTextEntitiesSize / 100.f; for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -631,17 +626,16 @@ void CRenderTools::RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale int mx = x; int my = y; - - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pTune[c].m_Number; if(Index) @@ -649,7 +643,7 @@ void CRenderTools::RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Index); UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); - UI()->TextRender()->Text(0, mx*Scale+11.f, my*Scale+6.f, Size*Scale/1.5f-5.f, aBuf, -1.0f); // numbers shouldn't be too big and in the center of the tile + UI()->TextRender()->Text(0, mx * Scale + 11.f, my * Scale + 6.f, Size * Scale / 1.5f - 5.f, aBuf, -1.0f); // numbers shouldn't be too big and in the center of the tile UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } @@ -663,22 +657,22 @@ void CRenderTools::RenderTelemap(CTeleTile *pTele, int w, int h, float Scale, Co Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; Graphics()->QuadsBegin(); Graphics()->SetColor(Color); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -686,59 +680,58 @@ void CRenderTools::RenderTelemap(CTeleTile *pTele, int w, int h, float Scale, Co int mx = x; int my = y; - if(RenderFlags&TILERENDERFLAG_EXTEND) + if(RenderFlags & TILERENDERFLAG_EXTEND) { - if(mx<0) + if(mx < 0) mx = 0; - if(mx>=w) - mx = w-1; - if(my<0) + if(mx >= w) + mx = w - 1; + if(my < 0) my = 0; - if(my>=h) - my = h-1; + if(my >= h) + my = h - 1; } else { - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; } - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pTele[c].m_Type; if(Index) { bool Render = false; - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; if(Render) { + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; - - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); - IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + IGraphics::CQuadItem QuadItem(x * Scale, y * Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } @@ -756,22 +749,22 @@ void CRenderTools::RenderSpeedupmap(CSpeedupTile *pSpeedupTile, int w, int h, fl //Graphics()->MapScreen(screen_x0-50, screen_y0-50, screen_x1+50, screen_y1+50); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; Graphics()->QuadsBegin(); Graphics()->SetColor(Color); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -779,59 +772,58 @@ void CRenderTools::RenderSpeedupmap(CSpeedupTile *pSpeedupTile, int w, int h, fl int mx = x; int my = y; - if(RenderFlags&TILERENDERFLAG_EXTEND) + if(RenderFlags & TILERENDERFLAG_EXTEND) { - if(mx<0) + if(mx < 0) mx = 0; - if(mx>=w) - mx = w-1; - if(my<0) + if(mx >= w) + mx = w - 1; + if(my < 0) my = 0; - if(my>=h) - my = h-1; + if(my >= h) + my = h - 1; } else { - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; } - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pSpeedupTile[c].m_Type; if(Index) { bool Render = false; - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; if(Render) { + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; - - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); - IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + IGraphics::CQuadItem QuadItem(x * Scale, y * Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } @@ -849,22 +841,22 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float //Graphics()->MapScreen(screen_x0-50, screen_y0-50, screen_x1+50, screen_y1+50); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; Graphics()->QuadsBegin(); Graphics()->SetColor(Color); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -872,30 +864,30 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float int mx = x; int my = y; - if(RenderFlags&TILERENDERFLAG_EXTEND) + if(RenderFlags & TILERENDERFLAG_EXTEND) { - if(mx<0) + if(mx < 0) mx = 0; - if(mx>=w) - mx = w-1; - if(my<0) + if(mx >= w) + mx = w - 1; + if(my < 0) my = 0; - if(my>=h) - my = h-1; + if(my >= h) + my = h - 1; } else { - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; } - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pSwitchTile[c].m_Type; if(Index) @@ -906,37 +898,36 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float unsigned char Flags = pSwitchTile[c].m_Flags; bool Render = false; - if(Flags&TILEFLAG_OPAQUE) + if(Flags & TILEFLAG_OPAQUE) { - if(RenderFlags&LAYERRENDERFLAG_OPAQUE) + if(RenderFlags & LAYERRENDERFLAG_OPAQUE) Render = true; } else { - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; } if(Render) { + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; - - if(Flags&TILEFLAG_VFLIP) + if(Flags & TILEFLAG_VFLIP) { x0 = x2; x1 = x3; @@ -944,7 +935,7 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float x3 = x0; } - if(Flags&TILEFLAG_HFLIP) + if(Flags & TILEFLAG_HFLIP) { y0 = y3; y2 = y1; @@ -952,7 +943,7 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float y1 = y0; } - if(Flags&TILEFLAG_ROTATE) + if(Flags & TILEFLAG_ROTATE) { float Tmp = x0; x0 = x3; @@ -967,7 +958,7 @@ void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float } Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); - IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + IGraphics::CQuadItem QuadItem(x * Scale, y * Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } @@ -983,22 +974,22 @@ void CRenderTools::RenderTunemap(CTuneTile *pTune, int w, int h, float Scale, Co Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); // calculate the final pixelsize for the tiles - float TilePixelSize = 1024/32.0f; - float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); - float FinalTilesetScale = FinalTileSize/TilePixelSize; + float TilePixelSize = 1024 / 32.0f; + float FinalTileSize = Scale / (ScreenX1 - ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize / TilePixelSize; Graphics()->QuadsBegin(); Graphics()->SetColor(Color); - int StartY = (int)(ScreenY0/Scale)-1; - int StartX = (int)(ScreenX0/Scale)-1; - int EndY = (int)(ScreenY1/Scale)+1; - int EndX = (int)(ScreenX1/Scale)+1; + int StartY = (int)(ScreenY0 / Scale) - 1; + int StartX = (int)(ScreenX0 / Scale) - 1; + int EndY = (int)(ScreenY1 / Scale) + 1; + int EndX = (int)(ScreenX1 / Scale) + 1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; - float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); - float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + float Frac = (1.25f / TexSize) * (1 / FinalTilesetScale); + float Nudge = (0.5f / TexSize) * (1 / FinalTilesetScale); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) @@ -1006,59 +997,58 @@ void CRenderTools::RenderTunemap(CTuneTile *pTune, int w, int h, float Scale, Co int mx = x; int my = y; - if(RenderFlags&TILERENDERFLAG_EXTEND) + if(RenderFlags & TILERENDERFLAG_EXTEND) { - if(mx<0) + if(mx < 0) mx = 0; - if(mx>=w) - mx = w-1; - if(my<0) + if(mx >= w) + mx = w - 1; + if(my < 0) my = 0; - if(my>=h) - my = h-1; + if(my >= h) + my = h - 1; } else { - if(mx<0) + if(mx < 0) continue; // mx = 0; - if(mx>=w) + if(mx >= w) continue; // mx = w-1; - if(my<0) + if(my < 0) continue; // my = 0; - if(my>=h) + if(my >= h) continue; // my = h-1; } - int c = mx + my*w; + int c = mx + my * w; unsigned char Index = pTune[c].m_Type; if(Index) { bool Render = false; - if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) + if(RenderFlags & LAYERRENDERFLAG_TRANSPARENT) Render = true; if(Render) { + int tx = Index % 16; + int ty = Index / 16; + int Px0 = tx * (1024 / 16); + int Py0 = ty * (1024 / 16); + int Px1 = Px0 + (1024 / 16) - 1; + int Py1 = Py0 + (1024 / 16) - 1; - int tx = Index%16; - int ty = Index/16; - int Px0 = tx*(1024/16); - int Py0 = ty*(1024/16); - int Px1 = Px0+(1024/16)-1; - int Py1 = Py0+(1024/16)-1; - - float x0 = Nudge + Px0/TexSize+Frac; - float y0 = Nudge + Py0/TexSize+Frac; - float x1 = Nudge + Px1/TexSize-Frac; - float y1 = Nudge + Py0/TexSize+Frac; - float x2 = Nudge + Px1/TexSize-Frac; - float y2 = Nudge + Py1/TexSize-Frac; - float x3 = Nudge + Px0/TexSize+Frac; - float y3 = Nudge + Py1/TexSize-Frac; + float x0 = Nudge + Px0 / TexSize + Frac; + float y0 = Nudge + Py0 / TexSize + Frac; + float x1 = Nudge + Px1 / TexSize - Frac; + float y1 = Nudge + Py0 / TexSize + Frac; + float x2 = Nudge + Px1 / TexSize - Frac; + float y2 = Nudge + Py1 / TexSize - Frac; + float x3 = Nudge + Px0 / TexSize + Frac; + float y3 = Nudge + Py1 / TexSize - Frac; Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); - IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + IGraphics::CQuadItem QuadItem(x * Scale, y * Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } diff --git a/src/game/client/ui.cpp b/src/game/client/ui.cpp index e8535c6a2..6dc1280d6 100644 --- a/src/game/client/ui.cpp +++ b/src/game/client/ui.cpp @@ -1,12 +1,12 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include -#include -#include -#include #include "ui.h" +#include +#include +#include /******************************************************** UI @@ -56,9 +56,9 @@ int CUI::MouseInside(const CUIRect *r) void CUI::ConvertMouseMove(float *x, float *y) { - float Fac = (float)(g_Config.m_UiMousesens)/g_Config.m_InpMousesens; - *x = *x*Fac; - *y = *y*Fac; + float Fac = (float)(g_Config.m_UiMousesens) / g_Config.m_InpMousesens; + *x = *x * Fac; + *y = *y * Fac; } CUIRect *CUI::Screen() @@ -67,7 +67,7 @@ CUIRect *CUI::Screen() float w, h; h = 600; - w = Aspect*h; + w = Aspect * h; m_Screen.w = w; m_Screen.h = h; @@ -77,29 +77,29 @@ CUIRect *CUI::Screen() float CUI::PixelSize() { - return Screen()->w/Graphics()->ScreenWidth(); + return Screen()->w / Graphics()->ScreenWidth(); } void CUI::SetScale(float s) { - g_Config.m_UiScale = (int)(s*100.0f); + g_Config.m_UiScale = (int)(s * 100.0f); } float CUI::Scale() { - return g_Config.m_UiScale/100.0f; + return g_Config.m_UiScale / 100.0f; } float CUIRect::Scale() const { - return g_Config.m_UiScale/100.0f; + return g_Config.m_UiScale / 100.0f; } void CUI::ClipEnable(const CUIRect *r) { - float XScale = Graphics()->ScreenWidth()/Screen()->w; - float YScale = Graphics()->ScreenHeight()/Screen()->h; - Graphics()->ClipEnable((int)(r->x*XScale), (int)(r->y*YScale), (int)(r->w*XScale), (int)(r->h*YScale)); + float XScale = Graphics()->ScreenWidth() / Screen()->w; + float YScale = Graphics()->ScreenHeight() / Screen()->h; + Graphics()->ClipEnable((int)(r->x * XScale), (int)(r->y * YScale), (int)(r->w * XScale), (int)(r->h * YScale)); } void CUI::ClipDisable() @@ -110,7 +110,7 @@ void CUI::ClipDisable() void CUIRect::HSplitMid(CUIRect *pTop, CUIRect *pBottom) const { CUIRect r = *this; - float Cut = r.h/2; + float Cut = r.h / 2; if(pTop) { @@ -173,12 +173,11 @@ void CUIRect::HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const } } - void CUIRect::VSplitMid(CUIRect *pLeft, CUIRect *pRight) const { CUIRect r = *this; - float Cut = r.w/2; -// Cut *= Scale(); + float Cut = r.w / 2; + // Cut *= Scale(); if(pLeft) { @@ -248,8 +247,8 @@ void CUIRect::Margin(float Cut, CUIRect *pOtherRect) const pOtherRect->x = r.x + Cut; pOtherRect->y = r.y + Cut; - pOtherRect->w = r.w - 2*Cut; - pOtherRect->h = r.h - 2*Cut; + pOtherRect->w = r.w - 2 * Cut; + pOtherRect->h = r.h - 2 * Cut; } void CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const @@ -259,7 +258,7 @@ void CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const pOtherRect->x = r.x + Cut; pOtherRect->y = r.y; - pOtherRect->w = r.w - 2*Cut; + pOtherRect->w = r.w - 2 * Cut; pOtherRect->h = r.h; } @@ -271,7 +270,7 @@ void CUIRect::HMargin(float Cut, CUIRect *pOtherRect) const pOtherRect->x = r.x; pOtherRect->y = r.y + Cut; pOtherRect->w = r.w; - pOtherRect->h = r.h - 2*Cut; + pOtherRect->h = r.h - 2 * Cut; } int CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CUIRect *pRect) @@ -286,7 +285,7 @@ int CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CU if(!MouseButton(ButtonUsed)) { if(Inside && Checked >= 0) - ReturnValue = 1+ButtonUsed; + ReturnValue = 1 + ButtonUsed; SetActiveItem(0); } } @@ -394,11 +393,11 @@ void CUI::DoLabel(const CUIRect *r, const char *pText, float Size, int Align, in { float AlignedSize = 0; float tw = TextRender()->TextWidth(0, Size, pText, -1, MaxWidth, &AlignedSize); - TextRender()->Text(0, r->x + r->w-tw, r->y + (r->h - AlignedSize) / 2.f, Size, pText, MaxWidth); + TextRender()->Text(0, r->x + r->w - tw, r->y + (r->h - AlignedSize) / 2.f, Size, pText, MaxWidth); } } void CUI::DoLabelScaled(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) { - DoLabel(r, pText, Size*Scale(), Align, MaxWidth); + DoLabel(r, pText, Size * Scale(), Align, MaxWidth); } diff --git a/src/game/client/ui.h b/src/game/client/ui.h index 97a5907cc..6afb3d866 100644 --- a/src/game/client/ui.h +++ b/src/game/client/ui.h @@ -7,6 +7,7 @@ class CUIRect { // TODO: Refactor: Redo UI scaling float Scale() const; + public: float x, y, w, h; @@ -94,7 +95,6 @@ public: * @param pOtherRect The CUIRect to place inside *this* CUIRect */ void HMargin(float Cut, CUIRect *pOtherRect) const; - }; class CUI @@ -114,7 +114,11 @@ class CUI public: // TODO: Refactor: Fill this in - void SetGraphics(class IGraphics *pGraphics, class ITextRender *pTextRender) { m_pGraphics = pGraphics; m_pTextRender = pTextRender;} + void SetGraphics(class IGraphics *pGraphics, class ITextRender *pTextRender) + { + m_pGraphics = pGraphics; + m_pTextRender = pTextRender; + } class IGraphics *Graphics() { return m_pGraphics; } class ITextRender *TextRender() { return m_pTextRender; } @@ -122,17 +126,17 @@ public: enum { - CORNER_TL=1, - CORNER_TR=2, - CORNER_BL=4, - CORNER_BR=8, + CORNER_TL = 1, + CORNER_TR = 2, + CORNER_BL = 4, + CORNER_BR = 8, - CORNER_T=CORNER_TL|CORNER_TR, - CORNER_B=CORNER_BL|CORNER_BR, - CORNER_R=CORNER_TR|CORNER_BR, - CORNER_L=CORNER_TL|CORNER_BL, + CORNER_T = CORNER_TL | CORNER_TR, + CORNER_B = CORNER_BL | CORNER_BR, + CORNER_R = CORNER_TR | CORNER_BR, + CORNER_L = CORNER_TL | CORNER_BL, - CORNER_ALL=CORNER_T|CORNER_B + CORNER_ALL = CORNER_T | CORNER_B }; int Update(float mx, float my, float Mwx, float Mwy, int m_Buttons); @@ -141,11 +145,16 @@ public: float MouseY() const { return m_MouseY; } float MouseWorldX() const { return m_MouseWorldX; } float MouseWorldY() const { return m_MouseWorldY; } - int MouseButton(int Index) const { return (m_MouseButtons>>Index)&1; } - int MouseButtonClicked(int Index) { return MouseButton(Index) && !((m_LastMouseButtons>>Index)&1) ; } + int MouseButton(int Index) const { return (m_MouseButtons >> Index) & 1; } + int MouseButtonClicked(int Index) { return MouseButton(Index) && !((m_LastMouseButtons >> Index) & 1); } void SetHotItem(const void *pID) { m_pBecommingHotItem = pID; } - void SetActiveItem(const void *pID) { m_pActiveItem = pID; if (pID) m_pLastActiveItem = pID; } + void SetActiveItem(const void *pID) + { + m_pActiveItem = pID; + if(pID) + m_pLastActiveItem = pID; + } void ClearLastActiveItem() { m_pLastActiveItem = 0; } const void *HotItem() const { return m_pHotItem; } const void *NextHotItem() const { return m_pBecommingHotItem; } @@ -172,5 +181,4 @@ public: void DoLabelScaled(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1); }; - #endif diff --git a/src/game/collision.cpp b/src/game/collision.cpp index 6991cc019..da7bd1f65 100644 --- a/src/game/collision.cpp +++ b/src/game/collision.cpp @@ -1,36 +1,36 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include #include #include -#include -#include #include +#include +#include -#include -#include #include +#include +#include #include vec2 ClampVel(int MoveRestriction, vec2 Vel) { - if(Vel.x > 0 && (MoveRestriction&CANTMOVE_RIGHT)) + if(Vel.x > 0 && (MoveRestriction & CANTMOVE_RIGHT)) { Vel.x = 0; } - if(Vel.x < 0 && (MoveRestriction&CANTMOVE_LEFT)) + if(Vel.x < 0 && (MoveRestriction & CANTMOVE_LEFT)) { Vel.x = 0; } - if(Vel.y > 0 && (MoveRestriction&CANTMOVE_DOWN)) + if(Vel.y > 0 && (MoveRestriction & CANTMOVE_DOWN)) { Vel.y = 0; } - if(Vel.y < 0 && (MoveRestriction&CANTMOVE_UP)) + if(Vel.y < 0 && (MoveRestriction & CANTMOVE_UP)) { Vel.y = 0; } @@ -70,24 +70,24 @@ void CCollision::Init(class CLayers *pLayers) if(m_pLayers->TeleLayer()) { unsigned int Size = m_pLayers->Map()->GetDataSize(m_pLayers->TeleLayer()->m_Tele); - if (Size >= m_Width*m_Height*sizeof(CTeleTile)) + if(Size >= m_Width * m_Height * sizeof(CTeleTile)) m_pTele = static_cast(m_pLayers->Map()->GetData(m_pLayers->TeleLayer()->m_Tele)); } if(m_pLayers->SpeedupLayer()) { unsigned int Size = m_pLayers->Map()->GetDataSize(m_pLayers->SpeedupLayer()->m_Speedup); - if (Size >= m_Width*m_Height*sizeof(CSpeedupTile)) + if(Size >= m_Width * m_Height * sizeof(CSpeedupTile)) m_pSpeedup = static_cast(m_pLayers->Map()->GetData(m_pLayers->SpeedupLayer()->m_Speedup)); } if(m_pLayers->SwitchLayer()) { unsigned int Size = m_pLayers->Map()->GetDataSize(m_pLayers->SwitchLayer()->m_Switch); - if (Size >= m_Width*m_Height*sizeof(CSwitchTile)) + if(Size >= m_Width * m_Height * sizeof(CSwitchTile)) m_pSwitch = static_cast(m_pLayers->Map()->GetData(m_pLayers->SwitchLayer()->m_Switch)); - m_pDoor = new CDoorTile[m_Width*m_Height]; + m_pDoor = new CDoorTile[m_Width * m_Height]; mem_zero(m_pDoor, m_Width * m_Height * sizeof(CDoorTile)); } else @@ -99,18 +99,18 @@ void CCollision::Init(class CLayers *pLayers) if(m_pLayers->TuneLayer()) { unsigned int Size = m_pLayers->Map()->GetDataSize(m_pLayers->TuneLayer()->m_Tune); - if (Size >= m_Width*m_Height*sizeof(CTuneTile)) + if(Size >= m_Width * m_Height * sizeof(CTuneTile)) m_pTune = static_cast(m_pLayers->Map()->GetData(m_pLayers->TuneLayer()->m_Tune)); } if(m_pLayers->FrontLayer()) { unsigned int Size = m_pLayers->Map()->GetDataSize(m_pLayers->FrontLayer()->m_Front); - if (Size >= m_Width*m_Height*sizeof(CTile)) + if(Size >= m_Width * m_Height * sizeof(CTile)) m_pFront = static_cast(m_pLayers->Map()->GetData(m_pLayers->FrontLayer()->m_Front)); } - for(int i = 0; i < m_Width*m_Height; i++) + for(int i = 0; i < m_Width * m_Height; i++) { int Index; if(m_pSwitch) @@ -137,12 +137,12 @@ void CCollision::Init(class CLayers *pLayers) if(m_NumSwitchers) { - m_pSwitchers = new SSwitchers[m_NumSwitchers+1]; + m_pSwitchers = new SSwitchers[m_NumSwitchers + 1]; - for (int i = 0; i < m_NumSwitchers+1; ++i) + for(int i = 0; i < m_NumSwitchers + 1; ++i) { m_pSwitchers[i].m_Initial = true; - for (int j = 0; j < MAX_CLIENTS; ++j) + for(int j = 0; j < MAX_CLIENTS; ++j) { m_pSwitchers[i].m_Status[j] = true; m_pSwitchers[i].m_EndTick[j] = 0; @@ -169,7 +169,7 @@ void CCollision::FillAntibot(CAntibotMapData *pMapData) enum { - MR_DIR_HERE=0, + MR_DIR_HERE = 0, MR_DIR_RIGHT, MR_DIR_DOWN, MR_DIR_LEFT, @@ -179,7 +179,7 @@ enum static int GetMoveRestrictionsRaw(int Direction, int Tile, int Flags) { - Flags = Flags&(TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE); + Flags = Flags & (TILEFLAG_VFLIP | TILEFLAG_HFLIP | TILEFLAG_ROTATE); switch(Tile) { case TILE_STOP: @@ -190,10 +190,10 @@ static int GetMoveRestrictionsRaw(int Direction, int Tile, int Flags) case ROTATION_180: return CANTMOVE_UP; case ROTATION_270: return CANTMOVE_RIGHT; - case TILEFLAG_HFLIP^ROTATION_0: return CANTMOVE_UP; - case TILEFLAG_HFLIP^ROTATION_90: return CANTMOVE_RIGHT; - case TILEFLAG_HFLIP^ROTATION_180: return CANTMOVE_DOWN; - case TILEFLAG_HFLIP^ROTATION_270: return CANTMOVE_LEFT; + case TILEFLAG_HFLIP ^ ROTATION_0: return CANTMOVE_UP; + case TILEFLAG_HFLIP ^ ROTATION_90: return CANTMOVE_RIGHT; + case TILEFLAG_HFLIP ^ ROTATION_180: return CANTMOVE_DOWN; + case TILEFLAG_HFLIP ^ ROTATION_270: return CANTMOVE_LEFT; } break; case TILE_STOPS: @@ -201,18 +201,18 @@ static int GetMoveRestrictionsRaw(int Direction, int Tile, int Flags) { case ROTATION_0: case ROTATION_180: - case TILEFLAG_HFLIP^ROTATION_0: - case TILEFLAG_HFLIP^ROTATION_180: - return CANTMOVE_DOWN|CANTMOVE_UP; + case TILEFLAG_HFLIP ^ ROTATION_0: + case TILEFLAG_HFLIP ^ ROTATION_180: + return CANTMOVE_DOWN | CANTMOVE_UP; case ROTATION_90: case ROTATION_270: - case TILEFLAG_HFLIP^ROTATION_90: - case TILEFLAG_HFLIP^ROTATION_270: - return CANTMOVE_LEFT|CANTMOVE_RIGHT; + case TILEFLAG_HFLIP ^ ROTATION_90: + case TILEFLAG_HFLIP ^ ROTATION_270: + return CANTMOVE_LEFT | CANTMOVE_RIGHT; } break; case TILE_STOPA: - return CANTMOVE_LEFT|CANTMOVE_RIGHT|CANTMOVE_UP|CANTMOVE_DOWN; + return CANTMOVE_LEFT | CANTMOVE_RIGHT | CANTMOVE_UP | CANTMOVE_DOWN; } return 0; } @@ -241,19 +241,18 @@ static int GetMoveRestrictions(int Direction, int Tile, int Flags) { return Result; } - return Result&GetMoveRestrictionsMask(Direction); + return Result & GetMoveRestrictionsMask(Direction); } int CCollision::GetMoveRestrictions(CALLBACK_SWITCHACTIVE pfnSwitchActive, void *pUser, vec2 Pos, float Distance, int OverrideCenterTileIndex) { static const vec2 DIRECTIONS[NUM_MR_DIRS] = - { - vec2(0, 0), - vec2(1, 0), - vec2(0, 1), - vec2(-1, 0), - vec2(0, -1) - }; + { + vec2(0, 0), + vec2(1, 0), + vec2(0, 1), + vec2(-1, 0), + vec2(0, -1)}; dbg_assert(0.0f <= Distance && Distance <= 32.0f, "invalid distance"); int Restrictions = 0; for(int d = 0; d < NUM_MR_DIRS; d++) @@ -299,8 +298,8 @@ int CCollision::GetTile(int x, int y) if(!m_pTiles) return 0; - int Nx = clamp(x/32, 0, m_Width-1); - int Ny = clamp(y/32, 0, m_Height-1); + int Nx = clamp(x / 32, 0, m_Width - 1); + int Ny = clamp(y / 32, 0, m_Height - 1); int pos = Ny * m_Width + Nx; if(m_pTiles[pos].m_Index >= TILE_SOLID && m_pTiles[pos].m_Index <= TILE_NOLASER) @@ -312,12 +311,12 @@ int CCollision::GetTile(int x, int y) int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) { float Distance = distance(Pos0, Pos1); - int End(Distance+1); + int End(Distance + 1); vec2 Last = Pos0; int ix = 0, iy = 0; // Temporary position for checking collision for(int i = 0; i <= End; i++) { - float a = i/(float)End; + float a = i / (float)End; vec2 Pos = mix(Pos0, Pos1, a); ix = round_to_int(Pos.x); iy = round_to_int(Pos.y); @@ -343,20 +342,20 @@ int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *p int CCollision::IntersectLineTeleHook(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr) { float Distance = distance(Pos0, Pos1); - int End(Distance+1); + int End(Distance + 1); vec2 Last = Pos0; int ix = 0, iy = 0; // Temporary position for checking collision int dx = 0, dy = 0; // Offset for checking the "through" tile ThroughOffset(Pos0, Pos1, &dx, &dy); for(int i = 0; i <= End; i++) { - float a = i/(float)End; + float a = i / (float)End; vec2 Pos = mix(Pos0, Pos1, a); ix = round_to_int(Pos.x); iy = round_to_int(Pos.y); int Index = GetPureMapIndex(Pos); - if (g_Config.m_SvOldTeleportHook) + if(g_Config.m_SvOldTeleportHook) *pTeleNr = IsTeleport(Index); else *pTeleNr = IsTeleportHook(Index); @@ -400,18 +399,18 @@ int CCollision::IntersectLineTeleHook(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, int CCollision::IntersectLineTeleWeapon(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr) { float Distance = distance(Pos0, Pos1); - int End(Distance+1); + int End(Distance + 1); vec2 Last = Pos0; int ix = 0, iy = 0; // Temporary position for checking collision for(int i = 0; i <= End; i++) { - float a = i/(float)End; + float a = i / (float)End; vec2 Pos = mix(Pos0, Pos1, a); ix = round_to_int(Pos.x); iy = round_to_int(Pos.y); int Index = GetPureMapIndex(Pos); - if (g_Config.m_SvOldTeleportWeapons) + if(g_Config.m_SvOldTeleportWeapons) *pTeleNr = IsTeleport(Index); else *pTeleNr = IsTeleportWeapon(Index); @@ -484,13 +483,13 @@ void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, i bool CCollision::TestBox(vec2 Pos, vec2 Size) { Size *= 0.5f; - if(CheckPoint(Pos.x-Size.x, Pos.y-Size.y)) + if(CheckPoint(Pos.x - Size.x, Pos.y - Size.y)) return true; - if(CheckPoint(Pos.x+Size.x, Pos.y-Size.y)) + if(CheckPoint(Pos.x + Size.x, Pos.y - Size.y)) return true; - if(CheckPoint(Pos.x-Size.x, Pos.y+Size.y)) + if(CheckPoint(Pos.x - Size.x, Pos.y + Size.y)) return true; - if(CheckPoint(Pos.x+Size.x, Pos.y+Size.y)) + if(CheckPoint(Pos.x + Size.x, Pos.y + Size.y)) return true; return false; } @@ -506,7 +505,7 @@ void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elas if(Distance > 0.00001f) { - float Fraction = 1.0f/(float)(Max+1); + float Fraction = 1.0f / (float)(Max + 1); for(int i = 0; i <= Max; i++) { // Early break as optimization to stop checking for collisions for @@ -517,7 +516,7 @@ void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elas break; } - vec2 NewPos = Pos + Vel*Fraction; // TODO: this row is not nice + vec2 NewPos = Pos + Vel * Fraction; // TODO: this row is not nice // Fraction can be very small and thus the calculation has no effect, no // reason to continue calculating. @@ -586,7 +585,7 @@ void CCollision::Dest() int CCollision::IsSolid(int x, int y) { - int index = GetTile(x,y); + int index = GetTile(x, y); return index == TILE_SOLID || index == TILE_NOHOOK; } @@ -595,13 +594,9 @@ bool CCollision::IsThrough(int x, int y, int xoff, int yoff, vec2 pos0, vec2 pos int pos = GetPureMapIndex(x, y); if(m_pFront && (m_pFront[pos].m_Index == TILE_THROUGH_ALL || m_pFront[pos].m_Index == TILE_THROUGH_CUT)) return true; - if(m_pFront && m_pFront[pos].m_Index == TILE_THROUGH_DIR && ( - (m_pFront[pos].m_Flags == ROTATION_0 && pos0.y > pos1.y) || - (m_pFront[pos].m_Flags == ROTATION_90 && pos0.x < pos1.x) || - (m_pFront[pos].m_Flags == ROTATION_180 && pos0.y < pos1.y) || - (m_pFront[pos].m_Flags == ROTATION_270 && pos0.x > pos1.x) )) + if(m_pFront && m_pFront[pos].m_Index == TILE_THROUGH_DIR && ((m_pFront[pos].m_Flags == ROTATION_0 && pos0.y > pos1.y) || (m_pFront[pos].m_Flags == ROTATION_90 && pos0.x < pos1.x) || (m_pFront[pos].m_Flags == ROTATION_180 && pos0.y < pos1.y) || (m_pFront[pos].m_Flags == ROTATION_270 && pos0.x > pos1.x))) return true; - int offpos = GetPureMapIndex(x+xoff, y+yoff); + int offpos = GetPureMapIndex(x + xoff, y + yoff); if(m_pTiles[offpos].m_Index == TILE_THROUGH || (m_pFront && m_pFront[offpos].m_Index == TILE_THROUGH)) return true; return false; @@ -612,17 +607,12 @@ bool CCollision::IsHookBlocker(int x, int y, vec2 pos0, vec2 pos1) int pos = GetPureMapIndex(x, y); if(m_pTiles[pos].m_Index == TILE_THROUGH_ALL || (m_pFront && m_pFront[pos].m_Index == TILE_THROUGH_ALL)) return true; - if(m_pTiles[pos].m_Index == TILE_THROUGH_DIR && ( - (m_pTiles[pos].m_Flags == ROTATION_0 && pos0.y < pos1.y) || - (m_pTiles[pos].m_Flags == ROTATION_90 && pos0.x > pos1.x) || - (m_pTiles[pos].m_Flags == ROTATION_180 && pos0.y > pos1.y) || - (m_pTiles[pos].m_Flags == ROTATION_270 && pos0.x < pos1.x) )) + if(m_pTiles[pos].m_Index == TILE_THROUGH_DIR && ((m_pTiles[pos].m_Flags == ROTATION_0 && pos0.y < pos1.y) || + (m_pTiles[pos].m_Flags == ROTATION_90 && pos0.x > pos1.x) || + (m_pTiles[pos].m_Flags == ROTATION_180 && pos0.y > pos1.y) || + (m_pTiles[pos].m_Flags == ROTATION_270 && pos0.x < pos1.x))) return true; - if(m_pFront && m_pFront[pos].m_Index == TILE_THROUGH_DIR && ( - (m_pFront[pos].m_Flags == ROTATION_0 && pos0.y < pos1.y) || - (m_pFront[pos].m_Flags == ROTATION_90 && pos0.x > pos1.x) || - (m_pFront[pos].m_Flags == ROTATION_180 && pos0.y > pos1.y) || - (m_pFront[pos].m_Flags == ROTATION_270 && pos0.x < pos1.x) )) + if(m_pFront && m_pFront[pos].m_Index == TILE_THROUGH_DIR && ((m_pFront[pos].m_Flags == ROTATION_0 && pos0.y < pos1.y) || (m_pFront[pos].m_Flags == ROTATION_90 && pos0.x > pos1.x) || (m_pFront[pos].m_Flags == ROTATION_180 && pos0.y > pos1.y) || (m_pFront[pos].m_Flags == ROTATION_270 && pos0.x < pos1.x))) return true; return false; } @@ -637,12 +627,12 @@ int CCollision::IsWallJump(int Index) int CCollision::IsNoLaser(int x, int y) { - return (CCollision::GetTile(x,y) == TILE_NOLASER); + return (CCollision::GetTile(x, y) == TILE_NOLASER); } int CCollision::IsFNoLaser(int x, int y) { - return (CCollision::GetFTile(x,y) == TILE_NOLASER); + return (CCollision::GetFTile(x, y) == TILE_NOLASER); } int CCollision::IsTeleport(int Index) @@ -731,7 +721,6 @@ int CCollision::IsTeleportHook(int Index) return 0; } - int CCollision::IsSpeedup(int Index) { if(Index < 0 || !m_pSpeedup) @@ -800,13 +789,13 @@ int CCollision::GetSwitchDelay(int Index) int CCollision::IsMover(int x, int y, int *pFlags) { - int Nx = clamp(x/32, 0, m_Width-1); - int Ny = clamp(y/32, 0, m_Height-1); - int Index = m_pTiles[Ny*m_Width+Nx].m_Index; - *pFlags = m_pTiles[Ny*m_Width+Nx].m_Flags; + int Nx = clamp(x / 32, 0, m_Width - 1); + int Ny = clamp(y / 32, 0, m_Height - 1); + int Index = m_pTiles[Ny * m_Width + Nx].m_Index; + *pFlags = m_pTiles[Ny * m_Width + Nx].m_Flags; if(Index < 0) return 0; - if (Index == TILE_CP || Index == TILE_CP_F) + if(Index == TILE_CP || Index == TILE_CP_F) return Index; else return 0; @@ -815,41 +804,41 @@ int CCollision::IsMover(int x, int y, int *pFlags) vec2 CCollision::CpSpeed(int Index, int Flags) { if(Index < 0) - return vec2(0,0); + return vec2(0, 0); vec2 target; if(Index == TILE_CP || Index == TILE_CP_F) switch(Flags) { case ROTATION_0: - target.x=0; - target.y=-4; + target.x = 0; + target.y = -4; break; case ROTATION_90: - target.x=4; - target.y=0; + target.x = 4; + target.y = 0; break; case ROTATION_180: - target.x=0; - target.y=4; + target.x = 0; + target.y = 4; break; case ROTATION_270: - target.x=-4; - target.y=0; + target.x = -4; + target.y = 0; break; default: - target=vec2(0,0); + target = vec2(0, 0); break; } if(Index == TILE_CP_F) - target*=4; + target *= 4; return target; } int CCollision::GetPureMapIndex(float x, float y) { - int Nx = clamp(round_to_int(x)/32, 0, m_Width-1); - int Ny = clamp(round_to_int(y)/32, 0, m_Height-1); - return Ny*m_Width+Nx; + int Nx = clamp(round_to_int(x) / 32, 0, m_Width - 1); + int Ny = clamp(round_to_int(y) / 32, 0, m_Height - 1); + return Ny * m_Width + Nx; } bool CCollision::TileExists(int Index) @@ -859,9 +848,9 @@ bool CCollision::TileExists(int Index) if(m_pTiles[Index].m_Index >= TILE_FREEZE && m_pTiles[Index].m_Index <= TILE_TELE_LASER_DISABLE) return true; - if(m_pFront && m_pFront[Index].m_Index >= TILE_FREEZE && m_pFront[Index].m_Index <= TILE_TELE_LASER_DISABLE) + if(m_pFront && m_pFront[Index].m_Index >= TILE_FREEZE && m_pFront[Index].m_Index <= TILE_TELE_LASER_DISABLE) return true; - if(m_pTele && (m_pTele[Index].m_Type == TILE_TELEIN || m_pTele[Index].m_Type == TILE_TELEINEVIL || m_pTele[Index].m_Type == TILE_TELECHECKINEVIL ||m_pTele[Index].m_Type == TILE_TELECHECK || m_pTele[Index].m_Type == TILE_TELECHECKIN)) + if(m_pTele && (m_pTele[Index].m_Type == TILE_TELEIN || m_pTele[Index].m_Type == TILE_TELEINEVIL || m_pTele[Index].m_Type == TILE_TELECHECKINEVIL || m_pTele[Index].m_Type == TILE_TELECHECK || m_pTele[Index].m_Type == TILE_TELECHECKIN)) return true; if(m_pSpeedup && m_pSpeedup[Index].m_Force > 0) return true; @@ -870,7 +859,7 @@ bool CCollision::TileExists(int Index) if(m_pSwitch && m_pSwitch[Index].m_Type) return true; if(m_pTune && m_pTune[Index].m_Type) - return true; + return true; return TileExistsNext(Index); } @@ -889,13 +878,13 @@ bool CCollision::TileExistsNext(int Index) return true; if(m_pTiles[TileOnTheRight].m_Index == TILE_STOPA || m_pTiles[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pTiles[TileOnTheRight].m_Index == TILE_STOPS || m_pTiles[TileOnTheLeft].m_Index == TILE_STOPS))) return true; - if(m_pTiles[TileBelow].m_Index == TILE_STOPA || m_pTiles[TileAbove].m_Index == TILE_STOPA || ((m_pTiles[TileBelow].m_Index == TILE_STOPS || m_pTiles[TileAbove].m_Index == TILE_STOPS) && m_pTiles[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + if(m_pTiles[TileBelow].m_Index == TILE_STOPA || m_pTiles[TileAbove].m_Index == TILE_STOPA || ((m_pTiles[TileBelow].m_Index == TILE_STOPS || m_pTiles[TileAbove].m_Index == TILE_STOPS) && m_pTiles[TileBelow].m_Flags | ROTATION_180 | ROTATION_0)) return true; if(m_pFront) { if(m_pFront[TileOnTheRight].m_Index == TILE_STOPA || m_pFront[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pFront[TileOnTheRight].m_Index == TILE_STOPS || m_pFront[TileOnTheLeft].m_Index == TILE_STOPS))) return true; - if(m_pFront[TileBelow].m_Index == TILE_STOPA || m_pFront[TileAbove].m_Index == TILE_STOPA || ((m_pFront[TileBelow].m_Index == TILE_STOPS || m_pFront[TileAbove].m_Index == TILE_STOPS) && m_pFront[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + if(m_pFront[TileBelow].m_Index == TILE_STOPA || m_pFront[TileAbove].m_Index == TILE_STOPA || ((m_pFront[TileBelow].m_Index == TILE_STOPS || m_pFront[TileAbove].m_Index == TILE_STOPS) && m_pFront[TileBelow].m_Flags | ROTATION_180 | ROTATION_0)) return true; if((m_pFront[TileOnTheRight].m_Index == TILE_STOP && m_pFront[TileOnTheRight].m_Flags == ROTATION_270) || (m_pFront[TileOnTheLeft].m_Index == TILE_STOP && m_pFront[TileOnTheLeft].m_Flags == ROTATION_90)) return true; @@ -906,7 +895,7 @@ bool CCollision::TileExistsNext(int Index) { if(m_pDoor[TileOnTheRight].m_Index == TILE_STOPA || m_pDoor[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pDoor[TileOnTheRight].m_Index == TILE_STOPS || m_pDoor[TileOnTheLeft].m_Index == TILE_STOPS))) return true; - if(m_pDoor[TileBelow].m_Index == TILE_STOPA || m_pDoor[TileAbove].m_Index == TILE_STOPA || ((m_pDoor[TileBelow].m_Index == TILE_STOPS || m_pDoor[TileAbove].m_Index == TILE_STOPS) && m_pDoor[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + if(m_pDoor[TileBelow].m_Index == TILE_STOPA || m_pDoor[TileAbove].m_Index == TILE_STOPA || ((m_pDoor[TileBelow].m_Index == TILE_STOPS || m_pDoor[TileAbove].m_Index == TILE_STOPS) && m_pDoor[TileBelow].m_Flags | ROTATION_180 | ROTATION_0)) return true; if((m_pDoor[TileOnTheRight].m_Index == TILE_STOP && m_pDoor[TileOnTheRight].m_Flags == ROTATION_270) || (m_pDoor[TileOnTheLeft].m_Index == TILE_STOP && m_pDoor[TileOnTheLeft].m_Flags == ROTATION_90)) return true; @@ -920,7 +909,7 @@ int CCollision::GetMapIndex(vec2 Pos) { int Nx = clamp((int)Pos.x / 32, 0, m_Width - 1); int Ny = clamp((int)Pos.y / 32, 0, m_Height - 1); - int Index = Ny*m_Width+Nx; + int Index = Ny * m_Width + Nx; if(TileExists(Index)) return Index; @@ -930,7 +919,7 @@ int CCollision::GetMapIndex(vec2 Pos) std::list CCollision::GetMapIndices(vec2 PrevPos, vec2 Pos, unsigned MaxIndices) { - std::list< int > Indices; + std::list Indices; float d = distance(PrevPos, Pos); int End(d + 1); if(!d) @@ -953,10 +942,10 @@ std::list CCollision::GetMapIndices(vec2 PrevPos, vec2 Pos, unsigned MaxInd vec2 Tmp = vec2(0, 0); int Nx = 0; int Ny = 0; - int Index,LastIndex = 0; + int Index, LastIndex = 0; for(int i = 0; i < End; i++) { - a = i/d; + a = i / d; Tmp = mix(PrevPos, Pos, a); Nx = clamp((int)Tmp.x / 32, 0, m_Width - 1); Ny = clamp((int)Tmp.y / 32, 0, m_Height - 1); @@ -977,11 +966,11 @@ std::list CCollision::GetMapIndices(vec2 PrevPos, vec2 Pos, unsigned MaxInd vec2 CCollision::GetPos(int Index) { if(Index < 0) - return vec2(0,0); + return vec2(0, 0); - int x = Index%m_Width; - int y = Index/m_Width; - return vec2(x*32+16, y*32+16); + int x = Index % m_Width; + int y = Index / m_Width; + return vec2(x * 32 + 16, y * 32 + 16); } int CCollision::GetTileIndex(int Index) @@ -1014,7 +1003,7 @@ int CCollision::GetFTileFlags(int Index) int CCollision::GetIndex(int Nx, int Ny) { - return m_pTiles[Ny*m_Width+Nx].m_Index; + return m_pTiles[Ny * m_Width + Nx].m_Index; } int CCollision::GetIndex(vec2 PrevPos, vec2 Pos) @@ -1023,13 +1012,13 @@ int CCollision::GetIndex(vec2 PrevPos, vec2 Pos) if(!Distance) { - int Nx = clamp((int)Pos.x/32, 0, m_Width-1); - int Ny = clamp((int)Pos.y/32, 0, m_Height-1); + int Nx = clamp((int)Pos.x / 32, 0, m_Width - 1); + int Ny = clamp((int)Pos.y / 32, 0, m_Height - 1); - if ((m_pTele) || - (m_pSpeedup && m_pSpeedup[Ny*m_Width+Nx].m_Force > 0)) + if((m_pTele) || + (m_pSpeedup && m_pSpeedup[Ny * m_Width + Nx].m_Force > 0)) { - return Ny*m_Width+Nx; + return Ny * m_Width + Nx; } } @@ -1040,14 +1029,14 @@ int CCollision::GetIndex(vec2 PrevPos, vec2 Pos) for(float f = 0; f < Distance; f++) { - a = f/Distance; + a = f / Distance; Tmp = mix(PrevPos, Pos, a); - Nx = clamp((int)Tmp.x/32, 0, m_Width-1); - Ny = clamp((int)Tmp.y/32, 0, m_Height-1); - if ((m_pTele) || - (m_pSpeedup && m_pSpeedup[Ny*m_Width+Nx].m_Force > 0)) + Nx = clamp((int)Tmp.x / 32, 0, m_Width - 1); + Ny = clamp((int)Tmp.y / 32, 0, m_Height - 1); + if((m_pTele) || + (m_pSpeedup && m_pSpeedup[Ny * m_Width + Nx].m_Force > 0)) { - return Ny*m_Width+Nx; + return Ny * m_Width + Nx; } } @@ -1056,19 +1045,19 @@ int CCollision::GetIndex(vec2 PrevPos, vec2 Pos) int CCollision::GetFIndex(int Nx, int Ny) { - if(!m_pFront) return 0; - return m_pFront[Ny*m_Width+Nx].m_Index; + if(!m_pFront) + return 0; + return m_pFront[Ny * m_Width + Nx].m_Index; } int CCollision::GetFTile(int x, int y) { if(!m_pFront) - return 0; - int Nx = clamp(x/32, 0, m_Width-1); - int Ny = clamp(y/32, 0, m_Height-1); - if(m_pFront[Ny*m_Width+Nx].m_Index == TILE_DEATH - || m_pFront[Ny*m_Width+Nx].m_Index == TILE_NOLASER) - return m_pFront[Ny*m_Width+Nx].m_Index; + return 0; + int Nx = clamp(x / 32, 0, m_Width - 1); + int Ny = clamp(y / 32, 0, m_Height - 1); + if(m_pFront[Ny * m_Width + Nx].m_Index == TILE_DEATH || m_pFront[Ny * m_Width + Nx].m_Index == TILE_NOLASER) + return m_pFront[Ny * m_Width + Nx].m_Index; else return 0; } @@ -1078,56 +1067,56 @@ int CCollision::Entity(int x, int y, int Layer) if((0 > x || x >= m_Width) || (0 > y || y >= m_Height)) { char aBuf[12]; - switch (Layer) + switch(Layer) { - case LAYER_GAME: - str_format(aBuf,sizeof(aBuf), "Game"); - break; - case LAYER_FRONT: - str_format(aBuf,sizeof(aBuf), "Front"); - break; - case LAYER_SWITCH: - str_format(aBuf,sizeof(aBuf), "Switch"); - break; - case LAYER_TELE: - str_format(aBuf,sizeof(aBuf), "Tele"); - break; - case LAYER_SPEEDUP: - str_format(aBuf,sizeof(aBuf), "Speedup"); - break; - case LAYER_TUNE: - str_format(aBuf,sizeof(aBuf), "Tune"); - break; - default: - str_format(aBuf,sizeof(aBuf), "Unknown"); + case LAYER_GAME: + str_format(aBuf, sizeof(aBuf), "Game"); + break; + case LAYER_FRONT: + str_format(aBuf, sizeof(aBuf), "Front"); + break; + case LAYER_SWITCH: + str_format(aBuf, sizeof(aBuf), "Switch"); + break; + case LAYER_TELE: + str_format(aBuf, sizeof(aBuf), "Tele"); + break; + case LAYER_SPEEDUP: + str_format(aBuf, sizeof(aBuf), "Speedup"); + break; + case LAYER_TUNE: + str_format(aBuf, sizeof(aBuf), "Tune"); + break; + default: + str_format(aBuf, sizeof(aBuf), "Unknown"); } - dbg_msg("collision","something is VERY wrong with the %s layer please report this at https://github.com/ddnet/ddnet, you will need to post the map as well and any steps that u think may have led to this", aBuf); + dbg_msg("collision", "something is VERY wrong with the %s layer please report this at https://github.com/ddnet/ddnet, you will need to post the map as well and any steps that u think may have led to this", aBuf); return 0; } - switch (Layer) + switch(Layer) { - case LAYER_GAME: - return m_pTiles[y*m_Width+x].m_Index - ENTITY_OFFSET; - case LAYER_FRONT: - return m_pFront[y*m_Width+x].m_Index - ENTITY_OFFSET; - case LAYER_SWITCH: - return m_pSwitch[y*m_Width+x].m_Type - ENTITY_OFFSET; - case LAYER_TELE: - return m_pTele[y*m_Width+x].m_Type - ENTITY_OFFSET; - case LAYER_SPEEDUP: - return m_pSpeedup[y*m_Width+x].m_Type - ENTITY_OFFSET; - case LAYER_TUNE: - return m_pTune[y*m_Width+x].m_Type - ENTITY_OFFSET; - default: - return 0; - break; + case LAYER_GAME: + return m_pTiles[y * m_Width + x].m_Index - ENTITY_OFFSET; + case LAYER_FRONT: + return m_pFront[y * m_Width + x].m_Index - ENTITY_OFFSET; + case LAYER_SWITCH: + return m_pSwitch[y * m_Width + x].m_Type - ENTITY_OFFSET; + case LAYER_TELE: + return m_pTele[y * m_Width + x].m_Type - ENTITY_OFFSET; + case LAYER_SPEEDUP: + return m_pSpeedup[y * m_Width + x].m_Type - ENTITY_OFFSET; + case LAYER_TUNE: + return m_pTune[y * m_Width + x].m_Type - ENTITY_OFFSET; + default: + return 0; + break; } } void CCollision::SetCollisionAt(float x, float y, int id) { - int Nx = clamp(round_to_int(x)/32, 0, m_Width-1); - int Ny = clamp(round_to_int(y)/32, 0, m_Height-1); + int Nx = clamp(round_to_int(x) / 32, 0, m_Width - 1); + int Ny = clamp(round_to_int(y) / 32, 0, m_Height - 1); m_pTiles[Ny * m_Width + Nx].m_Index = id; } @@ -1136,8 +1125,8 @@ void CCollision::SetDCollisionAt(float x, float y, int Type, int Flags, int Numb { if(!m_pDoor) return; - int Nx = clamp(round_to_int(x)/32, 0, m_Width-1); - int Ny = clamp(round_to_int(y)/32, 0, m_Height-1); + int Nx = clamp(round_to_int(x) / 32, 0, m_Width - 1); + int Ny = clamp(round_to_int(y) / 32, 0, m_Height - 1); m_pDoor[Ny * m_Width + Nx].m_Index = Type; m_pDoor[Ny * m_Width + Nx].m_Flags = Flags; @@ -1155,7 +1144,8 @@ int CCollision::GetDTileNumber(int Index) { if(!m_pDoor || Index < 0 || !m_pDoor[Index].m_Index) return 0; - if(m_pDoor[Index].m_Number) return m_pDoor[Index].m_Number; + if(m_pDoor[Index].m_Number) + return m_pDoor[Index].m_Number; return 0; } @@ -1170,9 +1160,9 @@ void ThroughOffset(vec2 Pos0, vec2 Pos1, int *Ox, int *Oy) { float x = Pos0.x - Pos1.x; float y = Pos0.y - Pos1.y; - if (fabs(x) > fabs(y)) + if(fabs(x) > fabs(y)) { - if (x < 0) + if(x < 0) { *Ox = -32; *Oy = 0; @@ -1185,7 +1175,7 @@ void ThroughOffset(vec2 Pos0, vec2 Pos1, int *Ox, int *Oy) } else { - if (y < 0) + if(y < 0) { *Ox = 0; *Oy = -32; @@ -1205,22 +1195,20 @@ int CCollision::IntersectNoLaser(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 for(float f = 0; f < d; f++) { - float a = f/d; + float a = f / d; vec2 Pos = mix(Pos0, Pos1, a); - int Nx = clamp(round_to_int(Pos.x)/32, 0, m_Width-1); - int Ny = clamp(round_to_int(Pos.y)/32, 0, m_Height-1); - if(GetIndex(Nx, Ny) == TILE_SOLID - || GetIndex(Nx, Ny) == TILE_NOHOOK - || GetIndex(Nx, Ny) == TILE_NOLASER - || GetFIndex(Nx, Ny) == TILE_NOLASER) + int Nx = clamp(round_to_int(Pos.x) / 32, 0, m_Width - 1); + int Ny = clamp(round_to_int(Pos.y) / 32, 0, m_Height - 1); + if(GetIndex(Nx, Ny) == TILE_SOLID || GetIndex(Nx, Ny) == TILE_NOHOOK || GetIndex(Nx, Ny) == TILE_NOLASER || GetFIndex(Nx, Ny) == TILE_NOLASER) { if(pOutCollision) *pOutCollision = Pos; if(pOutBeforeCollision) *pOutBeforeCollision = Last; - if (GetFIndex(Nx, Ny) == TILE_NOLASER) return GetFCollisionAt(Pos.x, Pos.y); - else return GetCollisionAt(Pos.x, Pos.y); - + if(GetFIndex(Nx, Ny) == TILE_NOLASER) + return GetFCollisionAt(Pos.x, Pos.y); + else + return GetCollisionAt(Pos.x, Pos.y); } Last = Pos; } @@ -1238,7 +1226,7 @@ int CCollision::IntersectNoLaserNW(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, ve for(float f = 0; f < d; f++) { - float a = f/d; + float a = f / d; vec2 Pos = mix(Pos0, Pos1, a); if(IsNoLaser(round_to_int(Pos.x), round_to_int(Pos.y)) || IsFNoLaser(round_to_int(Pos.x), round_to_int(Pos.y))) { @@ -1246,8 +1234,10 @@ int CCollision::IntersectNoLaserNW(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, ve *pOutCollision = Pos; if(pOutBeforeCollision) *pOutBeforeCollision = Last; - if(IsNoLaser(round_to_int(Pos.x), round_to_int(Pos.y))) return GetCollisionAt(Pos.x, Pos.y); - else return GetFCollisionAt(Pos.x, Pos.y); + if(IsNoLaser(round_to_int(Pos.x), round_to_int(Pos.y))) + return GetCollisionAt(Pos.x, Pos.y); + else + return GetFCollisionAt(Pos.x, Pos.y); } Last = Pos; } @@ -1265,7 +1255,7 @@ int CCollision::IntersectAir(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pO for(float f = 0; f < d; f++) { - float a = f/d; + float a = f / d; vec2 Pos = mix(Pos0, Pos1, a); if(IsSolid(round_to_int(Pos.x), round_to_int(Pos.y)) || (!GetTile(round_to_int(Pos.x), round_to_int(Pos.y)) && !GetFTile(round_to_int(Pos.x), round_to_int(Pos.y)))) { @@ -1275,9 +1265,10 @@ int CCollision::IntersectAir(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pO *pOutBeforeCollision = Last; if(!GetTile(round_to_int(Pos.x), round_to_int(Pos.y)) && !GetFTile(round_to_int(Pos.x), round_to_int(Pos.y))) return -1; + else if(!GetTile(round_to_int(Pos.x), round_to_int(Pos.y))) + return GetTile(round_to_int(Pos.x), round_to_int(Pos.y)); else - if (!GetTile(round_to_int(Pos.x), round_to_int(Pos.y))) return GetTile(round_to_int(Pos.x), round_to_int(Pos.y)); - else return GetFTile(round_to_int(Pos.x), round_to_int(Pos.y)); + return GetFTile(round_to_int(Pos.x), round_to_int(Pos.y)); } Last = Pos; } @@ -1306,6 +1297,6 @@ int CCollision::IsFCheckpoint(int Index) int z = m_pFront[Index].m_Index; if(z >= 35 && z <= 59) - return z-35; + return z - 35; return -1; } diff --git a/src/game/collision.h b/src/game/collision.h index 689fb4e20..b832ae90f 100644 --- a/src/game/collision.h +++ b/src/game/collision.h @@ -10,10 +10,10 @@ enum { - CANTMOVE_LEFT=1<<0, - CANTMOVE_RIGHT=1<<1, - CANTMOVE_UP=1<<2, - CANTMOVE_DOWN=1<<3, + CANTMOVE_LEFT = 1 << 0, + CANTMOVE_RIGHT = 1 << 1, + CANTMOVE_UP = 1 << 2, + CANTMOVE_DOWN = 1 << 3, }; vec2 ClampVel(int MoveRestriction, vec2 Vel); @@ -117,7 +117,6 @@ public: int m_NumSwitchers; private: - class CTeleTile *m_pTele; class CSpeedupTile *m_pSpeedup; class CTile *m_pFront; @@ -133,7 +132,6 @@ private: }; public: - SSwitchers *m_pSwitchers; }; diff --git a/src/game/ddracecommands.h b/src/game/ddracecommands.h index 93d593c2f..18be97bc4 100644 --- a/src/game/ddracecommands.h +++ b/src/game/ddracecommands.h @@ -7,35 +7,35 @@ #endif CONSOLE_COMMAND("kill_pl", "v[id]", CFGFLAG_SERVER, ConKillPlayer, this, "Kills player v and announces the kill") -CONSOLE_COMMAND("totele", "i[number]", CFGFLAG_SERVER|CMDFLAG_TEST, ConToTeleporter, this, "Teleports you to teleporter v") -CONSOLE_COMMAND("totelecp", "i[number]", CFGFLAG_SERVER|CMDFLAG_TEST, ConToCheckTeleporter, this, "Teleports you to checkpoint teleporter v") -CONSOLE_COMMAND("tele", "?i[id] ?i[id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConTeleport, this, "Teleports player i (or you) to player i (or you to where you look at)") -CONSOLE_COMMAND("addweapon", "i[weapon-id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConAddWeapon, this, "Gives weapon with id i to you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)") -CONSOLE_COMMAND("removeweapon", "i[weapon-id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConRemoveWeapon, this, "removes weapon with id i from you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)") -CONSOLE_COMMAND("shotgun", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConShotgun, this, "Gives a shotgun to you") -CONSOLE_COMMAND("grenade", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGrenade, this, "Gives a grenade launcher to you") -CONSOLE_COMMAND("laser", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConLaser, this, "Gives a laser to you") -CONSOLE_COMMAND("rifle", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConLaser, this, "Gives a laser to you") -CONSOLE_COMMAND("jetpack","", CFGFLAG_SERVER|CMDFLAG_TEST, ConJetpack, this, "Gives jetpack to you") -CONSOLE_COMMAND("weapons", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConWeapons, this, "Gives all weapons to you") -CONSOLE_COMMAND("unshotgun", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnShotgun, this, "Removes the shotgun from you") -CONSOLE_COMMAND("ungrenade", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnGrenade, this, "Removes the grenade launcher from you") -CONSOLE_COMMAND("unlaser", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnLaser, this, "Removes the laser from you") -CONSOLE_COMMAND("unrifle", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnLaser, this, "Removes the laser from you") -CONSOLE_COMMAND("unjetpack", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnJetpack, this, "Removes the jetpack from you") -CONSOLE_COMMAND("unweapons", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnWeapons, this, "Removes all weapons from you") -CONSOLE_COMMAND("ninja", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConNinja, this, "Makes you a ninja") -CONSOLE_COMMAND("super", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConSuper, this, "Makes you super") -CONSOLE_COMMAND("unsuper", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnSuper, this, "Removes super from you") -CONSOLE_COMMAND("unsolo", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnSolo, this, "Puts you out of solo part") -CONSOLE_COMMAND("undeep", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnDeep, this, "Puts you out of deep freeze") -CONSOLE_COMMAND("left", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoLeft, this, "Makes you move 1 tile left") -CONSOLE_COMMAND("right", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoRight, this, "Makes you move 1 tile right") -CONSOLE_COMMAND("up", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoUp, this, "Makes you move 1 tile up") -CONSOLE_COMMAND("down", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoDown, this, "Makes you move 1 tile down") +CONSOLE_COMMAND("totele", "i[number]", CFGFLAG_SERVER | CMDFLAG_TEST, ConToTeleporter, this, "Teleports you to teleporter v") +CONSOLE_COMMAND("totelecp", "i[number]", CFGFLAG_SERVER | CMDFLAG_TEST, ConToCheckTeleporter, this, "Teleports you to checkpoint teleporter v") +CONSOLE_COMMAND("tele", "?i[id] ?i[id]", CFGFLAG_SERVER | CMDFLAG_TEST, ConTeleport, this, "Teleports player i (or you) to player i (or you to where you look at)") +CONSOLE_COMMAND("addweapon", "i[weapon-id]", CFGFLAG_SERVER | CMDFLAG_TEST, ConAddWeapon, this, "Gives weapon with id i to you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)") +CONSOLE_COMMAND("removeweapon", "i[weapon-id]", CFGFLAG_SERVER | CMDFLAG_TEST, ConRemoveWeapon, this, "removes weapon with id i from you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, laser = 4, ninja = 5)") +CONSOLE_COMMAND("shotgun", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConShotgun, this, "Gives a shotgun to you") +CONSOLE_COMMAND("grenade", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConGrenade, this, "Gives a grenade launcher to you") +CONSOLE_COMMAND("laser", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConLaser, this, "Gives a laser to you") +CONSOLE_COMMAND("rifle", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConLaser, this, "Gives a laser to you") +CONSOLE_COMMAND("jetpack", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConJetpack, this, "Gives jetpack to you") +CONSOLE_COMMAND("weapons", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConWeapons, this, "Gives all weapons to you") +CONSOLE_COMMAND("unshotgun", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnShotgun, this, "Removes the shotgun from you") +CONSOLE_COMMAND("ungrenade", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnGrenade, this, "Removes the grenade launcher from you") +CONSOLE_COMMAND("unlaser", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnLaser, this, "Removes the laser from you") +CONSOLE_COMMAND("unrifle", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnLaser, this, "Removes the laser from you") +CONSOLE_COMMAND("unjetpack", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnJetpack, this, "Removes the jetpack from you") +CONSOLE_COMMAND("unweapons", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnWeapons, this, "Removes all weapons from you") +CONSOLE_COMMAND("ninja", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConNinja, this, "Makes you a ninja") +CONSOLE_COMMAND("super", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConSuper, this, "Makes you super") +CONSOLE_COMMAND("unsuper", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnSuper, this, "Removes super from you") +CONSOLE_COMMAND("unsolo", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnSolo, this, "Puts you out of solo part") +CONSOLE_COMMAND("undeep", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnDeep, this, "Puts you out of deep freeze") +CONSOLE_COMMAND("left", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConGoLeft, this, "Makes you move 1 tile left") +CONSOLE_COMMAND("right", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConGoRight, this, "Makes you move 1 tile right") +CONSOLE_COMMAND("up", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConGoUp, this, "Makes you move 1 tile up") +CONSOLE_COMMAND("down", "", CFGFLAG_SERVER | CMDFLAG_TEST, ConGoDown, this, "Makes you move 1 tile down") -CONSOLE_COMMAND("move", "i[x] i[y]", CFGFLAG_SERVER|CMDFLAG_TEST, ConMove, this, "Moves to the tile with x/y-number ii") -CONSOLE_COMMAND("move_raw", "i[x] i[y]", CFGFLAG_SERVER|CMDFLAG_TEST, ConMoveRaw, this, "Moves to the point with x/y-coordinates ii") +CONSOLE_COMMAND("move", "i[x] i[y]", CFGFLAG_SERVER | CMDFLAG_TEST, ConMove, this, "Moves to the tile with x/y-number ii") +CONSOLE_COMMAND("move_raw", "i[x] i[y]", CFGFLAG_SERVER | CMDFLAG_TEST, ConMoveRaw, this, "Moves to the point with x/y-coordinates ii") CONSOLE_COMMAND("force_pause", "v[id] i[seconds]", CFGFLAG_SERVER, ConForcePause, this, "Force i to pause for i seconds") CONSOLE_COMMAND("force_unpause", "v[id]", CFGFLAG_SERVER, ConForcePause, this, "Set force-pause timer of i to 0.") @@ -54,6 +54,6 @@ CONSOLE_COMMAND("moderate", "", CFGFLAG_SERVER, ConModerate, this, "Enables/disa CONSOLE_COMMAND("vote_no", "", CFGFLAG_SERVER, ConVoteNo, this, "Same as \"vote no\"") CONSOLE_COMMAND("save_dry", "", CFGFLAG_SERVER, ConDrySave, this, "Dump the current savestring") -CONSOLE_COMMAND("freezehammer", "v[id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConFreezeHammer, this, "Gives a player Freeze Hammer") -CONSOLE_COMMAND("unfreezehammer", "v[id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnFreezeHammer, this, "Removes Freeze Hammer from a player") +CONSOLE_COMMAND("freezehammer", "v[id]", CFGFLAG_SERVER | CMDFLAG_TEST, ConFreezeHammer, this, "Gives a player Freeze Hammer") +CONSOLE_COMMAND("unfreezehammer", "v[id]", CFGFLAG_SERVER | CMDFLAG_TEST, ConUnFreezeHammer, this, "Removes Freeze Hammer from a player") #undef CONSOLE_COMMAND diff --git a/src/game/editor/auto_map.cpp b/src/game/editor/auto_map.cpp index 115238944..8666c18cb 100644 --- a/src/game/editor/auto_map.cpp +++ b/src/game/editor/auto_map.cpp @@ -1,9 +1,9 @@ -#include // sscanf #include +#include // sscanf #include -#include #include +#include #include "auto_map.h" #include "editor.h" @@ -43,7 +43,7 @@ CAutoMapper::CAutoMapper(CEditor *pEditor) m_FileLoaded = false; } -void CAutoMapper::Load(const char* pTileName) +void CAutoMapper::Load(const char *pTileName) { char aPath[256]; str_format(aPath, sizeof(aPath), "editor/%s.rules", pTileName); @@ -64,10 +64,9 @@ void CAutoMapper::Load(const char* pTileName) while(char *pLine = LineReader.Get()) { // skip blank/empty lines as well as comments - if(str_length(pLine) > 0 && pLine[0] != '#' && pLine[0] != '\n' && pLine[0] != '\r' - && pLine[0] != '\t' && pLine[0] != '\v' && pLine[0] != ' ') + if(str_length(pLine) > 0 && pLine[0] != '#' && pLine[0] != '\n' && pLine[0] != '\r' && pLine[0] != '\t' && pLine[0] != '\v' && pLine[0] != ' ') { - if(pLine[0]== '[') + if(pLine[0] == '[') { // new configuration, get the name pLine++; @@ -178,7 +177,8 @@ void CAutoMapper::Load(const char* pTileName) Value = CPosRule::NOTINDEX; int pWord = 4; - while(true) { + while(true) + { int ID = 0; char aOrientation1[128] = ""; char aOrientation2[128] = ""; @@ -191,11 +191,14 @@ void CAutoMapper::Load(const char* pTileName) NewIndexInfo.m_Flag = 0; NewIndexInfo.m_TestFlag = false; - if(!str_comp(aOrientation1, "OR")) { + if(!str_comp(aOrientation1, "OR")) + { NewIndexList.add(NewIndexInfo); pWord += 2; continue; - } else if(str_length(aOrientation1) > 0) { + } + else if(str_length(aOrientation1) > 0) + { NewIndexInfo.m_TestFlag = true; if(!str_comp(aOrientation1, "XFLIP")) NewIndexInfo.m_Flag = TILEFLAG_VFLIP; @@ -207,55 +210,71 @@ void CAutoMapper::Load(const char* pTileName) NewIndexInfo.m_Flag = 0; else NewIndexInfo.m_TestFlag = false; - } else { + } + else + { NewIndexList.add(NewIndexInfo); break; } - if(!str_comp(aOrientation2, "OR")) { + if(!str_comp(aOrientation2, "OR")) + { NewIndexList.add(NewIndexInfo); pWord += 3; continue; - } else if(str_length(aOrientation2) > 0 && NewIndexInfo.m_Flag != 0) { + } + else if(str_length(aOrientation2) > 0 && NewIndexInfo.m_Flag != 0) + { if(!str_comp(aOrientation2, "XFLIP")) NewIndexInfo.m_Flag |= TILEFLAG_VFLIP; else if(!str_comp(aOrientation2, "YFLIP")) NewIndexInfo.m_Flag |= TILEFLAG_HFLIP; else if(!str_comp(aOrientation2, "ROTATE")) NewIndexInfo.m_Flag |= TILEFLAG_ROTATE; - } else { + } + else + { NewIndexList.add(NewIndexInfo); break; } - if(!str_comp(aOrientation3, "OR")) { + if(!str_comp(aOrientation3, "OR")) + { NewIndexList.add(NewIndexInfo); pWord += 4; continue; - } else if(str_length(aOrientation3) > 0 && NewIndexInfo.m_Flag != 0) { + } + else if(str_length(aOrientation3) > 0 && NewIndexInfo.m_Flag != 0) + { if(!str_comp(aOrientation3, "XFLIP")) NewIndexInfo.m_Flag |= TILEFLAG_VFLIP; else if(!str_comp(aOrientation3, "YFLIP")) NewIndexInfo.m_Flag |= TILEFLAG_HFLIP; else if(!str_comp(aOrientation3, "ROTATE")) NewIndexInfo.m_Flag |= TILEFLAG_ROTATE; - } else { + } + else + { NewIndexList.add(NewIndexInfo); break; } - if(!str_comp(aOrientation4, "OR")) { + if(!str_comp(aOrientation4, "OR")) + { NewIndexList.add(NewIndexInfo); pWord += 5; continue; - } else { + } + else + { NewIndexList.add(NewIndexInfo); break; } } } - if(Value != CPosRule::NORULE) { + if(Value != CPosRule::NORULE) + { CPosRule NewPosRule = {x, y, Value, NewIndexList}; pCurrentIndex->m_aRules.add(NewPosRule); @@ -264,7 +283,8 @@ void CAutoMapper::Load(const char* pTileName) pCurrentConf->m_EndX = maximum(pCurrentConf->m_EndX, NewPosRule.m_X); pCurrentConf->m_EndY = maximum(pCurrentConf->m_EndY, NewPosRule.m_Y); - if(x == 0 && y == 0) { + if(x == 0 && y == 0) + { for(int i = 0; i < NewIndexList.size(); ++i) { if(Value == CPosRule::INDEX && NewIndexList[i].m_ID == 0) @@ -301,9 +321,9 @@ void CAutoMapper::Load(const char* pTileName) } // add default rule for Pos 0 0 if there is none - for (int g = 0; g < m_lConfigs.size(); ++g) + for(int g = 0; g < m_lConfigs.size(); ++g) { - for (int h = 0; h < m_lConfigs[g].m_aRuns.size(); ++h) + for(int h = 0; h < m_lConfigs[g].m_aRuns.size(); ++h) { for(int i = 0; i < m_lConfigs[g].m_aRuns[h].m_aIndexRules.size(); ++i) { @@ -340,13 +360,13 @@ void CAutoMapper::Load(const char* pTileName) io_close(RulesFile); - str_format(aBuf, sizeof(aBuf),"loaded %s", aPath); + str_format(aBuf, sizeof(aBuf), "loaded %s", aPath); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); m_FileLoaded = true; } -const char* CAutoMapper::GetConfigName(int Index) +const char *CAutoMapper::GetConfigName(int Index) { if(Index < 0 || Index >= m_lConfigs.size()) return ""; @@ -378,15 +398,16 @@ void CAutoMapper::ProceedLocalized(CLayerTiles *pLayer, int ConfigID, int Seed, int UpdateToY = clamp(Y + Height + 3 * pConf->m_EndY, 0, pLayer->m_Height); CLayerTiles *pUpdateLayer; - if (UpdateFromX != 0 || UpdateFromY != 0 || UpdateToX != pLayer->m_Width || UpdateToY != pLayer->m_Width) + if(UpdateFromX != 0 || UpdateFromY != 0 || UpdateToX != pLayer->m_Width || UpdateToY != pLayer->m_Width) { // Needs a layer to work on pUpdateLayer = new CLayerTiles(UpdateToX - UpdateFromX, UpdateToY - UpdateFromY); - for(int y = UpdateFromY; y < UpdateToY; y++) { + for(int y = UpdateFromY; y < UpdateToY; y++) + { for(int x = UpdateFromX; x < UpdateToX; x++) { - CTile *in = &pLayer->m_pTiles[y*pLayer->m_Width+x]; - CTile *out = &pUpdateLayer->m_pTiles[(y-UpdateFromY)*pUpdateLayer->m_Width+x-UpdateFromX]; + CTile *in = &pLayer->m_pTiles[y * pLayer->m_Width + x]; + CTile *out = &pUpdateLayer->m_pTiles[(y - UpdateFromY) * pUpdateLayer->m_Width + x - UpdateFromX]; out->m_Index = in->m_Index; out->m_Flags = in->m_Flags; } @@ -399,11 +420,12 @@ void CAutoMapper::ProceedLocalized(CLayerTiles *pLayer, int ConfigID, int Seed, Proceed(pUpdateLayer, ConfigID, Seed, UpdateFromX, UpdateFromY); - for(int y = CommitFromY; y < CommitToY; y++) { + for(int y = CommitFromY; y < CommitToY; y++) + { for(int x = CommitFromX; x < CommitToX; x++) { - CTile *in = &pUpdateLayer->m_pTiles[(y-UpdateFromY)*pUpdateLayer->m_Width+x-UpdateFromX]; - CTile *out = &pLayer->m_pTiles[y*pLayer->m_Width+x]; + CTile *in = &pUpdateLayer->m_pTiles[(y - UpdateFromY) * pUpdateLayer->m_Width + x - UpdateFromX]; + CTile *out = &pLayer->m_pTiles[y * pLayer->m_Width + x]; out->m_Index = in->m_Index; out->m_Flags = in->m_Flags; } @@ -421,7 +443,8 @@ void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Seed, int SeedO CConfiguration *pConf = &m_lConfigs[ConfigID]; // for every run: copy tiles, automap, overwrite tiles - for(int h = 0; h < pConf->m_aRuns.size(); ++h) { + for(int h = 0; h < pConf->m_aRuns.size(); ++h) + { CRun *pRun = &pConf->m_aRuns[h]; // don't make copy if it's requested @@ -430,11 +453,12 @@ void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Seed, int SeedO { pReadLayer = new CLayerTiles(pLayer->m_Width, pLayer->m_Height); - for(int y = 0; y < pLayer->m_Height; y++) { + for(int y = 0; y < pLayer->m_Height; y++) + { for(int x = 0; x < pLayer->m_Width; x++) { - CTile *in = &pLayer->m_pTiles[y*pLayer->m_Width+x]; - CTile *out = &pReadLayer->m_pTiles[y*pLayer->m_Width+x]; + CTile *in = &pLayer->m_pTiles[y * pLayer->m_Width + x]; + CTile *out = &pReadLayer->m_pTiles[y * pLayer->m_Width + x]; out->m_Index = in->m_Index; out->m_Flags = in->m_Flags; } @@ -446,10 +470,11 @@ void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Seed, int SeedO } // auto map - for(int y = 0; y < pLayer->m_Height; y++) { + for(int y = 0; y < pLayer->m_Height; y++) + { for(int x = 0; x < pLayer->m_Width; x++) { - CTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]); + CTile *pTile = &(pLayer->m_pTiles[y * pLayer->m_Width + x]); m_pEditor->m_Map.m_Modified = true; for(int i = 0; i < pRun->m_aIndexRules.size(); ++i) @@ -468,19 +493,23 @@ void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Seed, int SeedO int CheckIndex, CheckFlags; int CheckX = x + pRule->m_X; int CheckY = y + pRule->m_Y; - if(CheckX >= 0 && CheckX < pLayer->m_Width && CheckY >= 0 && CheckY < pLayer->m_Height) { + if(CheckX >= 0 && CheckX < pLayer->m_Width && CheckY >= 0 && CheckY < pLayer->m_Height) + { int CheckTile = CheckY * pLayer->m_Width + CheckX; CheckIndex = pReadLayer->m_pTiles[CheckTile].m_Index; CheckFlags = pReadLayer->m_pTiles[CheckTile].m_Flags & (TILEFLAG_ROTATE | TILEFLAG_VFLIP | TILEFLAG_HFLIP); - } else { + } + else + { CheckIndex = -1; CheckFlags = 0; } - if(pRule->m_Value == CPosRule::INDEX) + if(pRule->m_Value == CPosRule::INDEX) { RespectRules = false; - for(int i = 0; i < pRule->m_aIndexList.size(); ++i) { + for(int i = 0; i < pRule->m_aIndexList.size(); ++i) + { if(CheckIndex == pRule->m_aIndexList[i].m_ID && (!pRule->m_aIndexList[i].m_TestFlag || CheckFlags == pRule->m_aIndexList[i].m_Flag)) { RespectRules = true; @@ -488,9 +517,10 @@ void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Seed, int SeedO } } } - else if(pRule->m_Value == CPosRule::NOTINDEX) + else if(pRule->m_Value == CPosRule::NOTINDEX) { - for(int i = 0; i < pRule->m_aIndexList.size(); ++i) { + for(int i = 0; i < pRule->m_aIndexList.size(); ++i) + { if(CheckIndex == pRule->m_aIndexList[i].m_ID && (!pRule->m_aIndexList[i].m_TestFlag || CheckFlags == pRule->m_aIndexList[i].m_Flag)) { RespectRules = false; diff --git a/src/game/editor/auto_map.h b/src/game/editor/auto_map.h index 845a93e7e..b9748dd57 100644 --- a/src/game/editor/auto_map.h +++ b/src/game/editor/auto_map.h @@ -21,7 +21,7 @@ class CAutoMapper enum { - NORULE=0, + NORULE = 0, INDEX, NOTINDEX }; @@ -55,22 +55,21 @@ class CAutoMapper }; public: - CAutoMapper(class CEditor *pEditor); - void Load(const char* pTileName); - void ProceedLocalized(class CLayerTiles *pLayer, int ConfigID, int Seed=0, int X=0, int Y=0, int Width=-1, int Height=-1); - void Proceed(class CLayerTiles *pLayer, int ConfigID, int Seed=0, int SeedOffsetX=0, int SeedOffsetY=0); + void Load(const char *pTileName); + void ProceedLocalized(class CLayerTiles *pLayer, int ConfigID, int Seed = 0, int X = 0, int Y = 0, int Width = -1, int Height = -1); + void Proceed(class CLayerTiles *pLayer, int ConfigID, int Seed = 0, int SeedOffsetX = 0, int SeedOffsetY = 0); int ConfigNamesNum() const { return m_lConfigs.size(); } - const char* GetConfigName(int Index); + const char *GetConfigName(int Index); bool IsLoaded() const { return m_FileLoaded; } + private: array m_lConfigs; class CEditor *m_pEditor; bool m_FileLoaded; }; - #endif diff --git a/src/game/editor/editor.cpp b/src/game/editor/editor.cpp index 65373c16c..5dee92292 100644 --- a/src/game/editor/editor.cpp +++ b/src/game/editor/editor.cpp @@ -3,39 +3,38 @@ #include -#include -#include #include +#include +#include #if defined(CONF_FAMILY_UNIX) #include #endif -#include -#include #include #include #include #include #include +#include +#include #include #include -#include #include -#include -#include +#include #include #include #include +#include #include +#include #include #include "auto_map.h" #include "editor.h" - static const char *VANILLA_IMAGES[] = { "bg_cloud1", "bg_cloud2", @@ -64,8 +63,7 @@ static const char *VANILLA_IMAGES[] = { "winter_main", "winter_mountains", "winter_mountains2", - "winter_mountains3" -}; + "winter_mountains3"}; static bool IsVanillaImage(const char *pImage) { @@ -79,16 +77,15 @@ static bool IsVanillaImage(const char *pImage) return false; } -const void* CEditor::ms_pUiGotContext; +const void *CEditor::ms_pUiGotContext; ColorHSVA CEditor::ms_PickerColor; int CEditor::ms_SVPicker; int CEditor::ms_HuePicker; - enum { - BUTTON_CONTEXT=1, + BUTTON_CONTEXT = 1, }; CEditorImage::~CEditorImage() @@ -169,13 +166,13 @@ void CLayerGroup::Render() { float aPoints[4]; m_pMap->m_pGameGroup->Mapping(aPoints); - float x0 = (m_ClipX - aPoints[0]) / (aPoints[2]-aPoints[0]); - float y0 = (m_ClipY - aPoints[1]) / (aPoints[3]-aPoints[1]); - float x1 = ((m_ClipX+m_ClipW) - aPoints[0]) / (aPoints[2]-aPoints[0]); - float y1 = ((m_ClipY+m_ClipH) - aPoints[1]) / (aPoints[3]-aPoints[1]); + float x0 = (m_ClipX - aPoints[0]) / (aPoints[2] - aPoints[0]); + float y0 = (m_ClipY - aPoints[1]) / (aPoints[3] - aPoints[1]); + float x1 = ((m_ClipX + m_ClipW) - aPoints[0]) / (aPoints[2] - aPoints[0]); + float y1 = ((m_ClipY + m_ClipH) - aPoints[1]) / (aPoints[3] - aPoints[1]); - pGraphics->ClipEnable((int)(x0*pGraphics->ScreenWidth()), (int)(y0*pGraphics->ScreenHeight()), - (int)((x1-x0)*pGraphics->ScreenWidth()), (int)((y1-y0)*pGraphics->ScreenHeight())); + pGraphics->ClipEnable((int)(x0 * pGraphics->ScreenWidth()), (int)(y0 * pGraphics->ScreenHeight()), + (int)((x1 - x0) * pGraphics->ScreenWidth()), (int)((y1 - y0) * pGraphics->ScreenHeight())); } for(int i = 0; i < m_lLayers.size(); i++) @@ -188,16 +185,14 @@ void CLayerGroup::Render() if(pTiles->m_Game || pTiles->m_Front || pTiles->m_Tele || pTiles->m_Speedup || pTiles->m_Tune || pTiles->m_Switch) continue; } - if(m_pMap->m_pEditor->m_ShowDetail || !(m_lLayers[i]->m_Flags&LAYERFLAG_DETAIL)) + if(m_pMap->m_pEditor->m_ShowDetail || !(m_lLayers[i]->m_Flags & LAYERFLAG_DETAIL)) m_lLayers[i]->Render(); } } for(int i = 0; i < m_lLayers.size(); i++) { - if(m_lLayers[i]->m_Visible && m_lLayers[i]->m_Type == LAYERTYPE_TILES && m_lLayers[i] != m_pMap->m_pGameLayer - && m_lLayers[i] != m_pMap->m_pFrontLayer && m_lLayers[i] != m_pMap->m_pTeleLayer - && m_lLayers[i] != m_pMap->m_pSpeedupLayer && m_lLayers[i] != m_pMap->m_pSwitchLayer && m_lLayers[i] != m_pMap->m_pTuneLayer) + if(m_lLayers[i]->m_Visible && m_lLayers[i]->m_Type == LAYERTYPE_TILES && m_lLayers[i] != m_pMap->m_pGameLayer && m_lLayers[i] != m_pMap->m_pFrontLayer && m_lLayers[i] != m_pMap->m_pTeleLayer && m_lLayers[i] != m_pMap->m_pSpeedupLayer && m_lLayers[i] != m_pMap->m_pSwitchLayer && m_lLayers[i] != m_pMap->m_pTuneLayer) { CLayerTiles *pTiles = static_cast(m_lLayers[i]); if(pTiles->m_Game || pTiles->m_Front || pTiles->m_Tele || pTiles->m_Speedup || pTiles->m_Tune || pTiles->m_Switch) @@ -218,7 +213,8 @@ void CLayerGroup::AddLayer(CLayer *l) void CLayerGroup::DeleteLayer(int Index) { - if(Index < 0 || Index >= m_lLayers.size()) return; + if(Index < 0 || Index >= m_lLayers.size()) + return; delete m_lLayers[Index]; m_lLayers.remove_index(Index); m_pMap->m_Modified = true; @@ -227,7 +223,8 @@ void CLayerGroup::DeleteLayer(int Index) void CLayerGroup::GetSize(float *w, float *h) { - *w = 0; *h = 0; + *w = 0; + *h = 0; for(int i = 0; i < m_lLayers.size(); i++) { float lw, lh; @@ -239,9 +236,12 @@ void CLayerGroup::GetSize(float *w, float *h) int CLayerGroup::SwapLayers(int Index0, int Index1) { - if(Index0 < 0 || Index0 >= m_lLayers.size()) return Index0; - if(Index1 < 0 || Index1 >= m_lLayers.size()) return Index0; - if(Index0 == Index1) return Index0; + if(Index0 < 0 || Index0 >= m_lLayers.size()) + return Index0; + if(Index1 < 0 || Index1 >= m_lLayers.size()) + return Index0; + if(Index0 == Index1) + return Index0; m_pMap->m_Modified = true; m_pMap->m_UndoModified++; swap(m_lLayers[Index0], m_lLayers[Index1]); @@ -252,9 +252,9 @@ void CEditorImage::AnalyseTileFlags() { mem_zero(m_aTileFlags, sizeof(m_aTileFlags)); - int tw = m_Width/16; // tilesizes - int th = m_Height/16; - if( tw == th && m_Format == CImageInfo::FORMAT_RGBA ) + int tw = m_Width / 16; // tilesizes + int th = m_Height / 16; + if(tw == th && m_Format == CImageInfo::FORMAT_RGBA) { unsigned char *pPixelData = (unsigned char *)m_pData; @@ -266,8 +266,8 @@ void CEditorImage::AnalyseTileFlags() for(int x = 0; x < tw; x++) for(int y = 0; y < th; y++) { - int p = (ty*tw+y)*m_Width + tx*tw+x; - if(pPixelData[p*4+3] < 250) + int p = (ty * tw + y) * m_Width + tx * tw + x; + if(pPixelData[p * 4 + 3] < 250) { Opaque = false; break; @@ -278,7 +278,6 @@ void CEditorImage::AnalyseTileFlags() m_aTileFlags[TileID] |= TILEFLAG_OPAQUE; } } - } void CEditor::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser) @@ -294,7 +293,7 @@ void CEditor::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pU } CEnvelope *e = pThis->m_Map.m_lEnvelopes[Env]; - float t = pThis->m_AnimateTime+TimeOffset; + float t = pThis->m_AnimateTime + TimeOffset; t *= pThis->m_AnimateSpeed; e->Eval(t, pChannels); } @@ -346,15 +345,15 @@ int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned Str else if(s_DoScroll) { // do scrolling - if(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f) + if(UI()->MouseX() < pRect->x && s_ScrollStart - UI()->MouseX() > 10.0f) { - s_AtIndex = maximum(0, s_AtIndex-1); + s_AtIndex = maximum(0, s_AtIndex - 1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } - else if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f) + else if(UI()->MouseX() > pRect->x + pRect->w && UI()->MouseX() - s_ScrollStart > 10.0f) { - s_AtIndex = minimum(Len, s_AtIndex+1); + s_AtIndex = minimum(Len, s_AtIndex + 1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } @@ -420,7 +419,7 @@ int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned Str { unsigned s = str_length(pStr); if(s >= sizeof(aStars)) - s = sizeof(aStars)-1; + s = sizeof(aStars) - 1; for(unsigned int i = 0; i < s; ++i) aStars[i] = '*'; aStars[s] = 0; @@ -431,24 +430,22 @@ int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned Str if(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || Input()->NumEvents())) { float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex, -1.0f); - if(w-*Offset > Textbox.w) + if(w - *Offset > Textbox.w) { // move to the left float wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1, -1.0f); do { - *Offset += minimum(wt-*Offset-Textbox.w, Textbox.w/3); - } - while(w-*Offset > Textbox.w); + *Offset += minimum(wt - *Offset - Textbox.w, Textbox.w / 3); + } while(w - *Offset > Textbox.w); } - else if(w-*Offset < 0.0f) + else if(w - *Offset < 0.0f) { // move to the right do { - *Offset = maximum(0.0f, *Offset-Textbox.w/3); - } - while(w-*Offset < 0.0f); + *Offset = maximum(0.0f, *Offset - Textbox.w / 3); + } while(w - *Offset < 0.0f); } } UI()->ClipEnable(pRect); @@ -462,9 +459,9 @@ int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned Str float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex, -1.0f); Textbox = *pRect; Textbox.VSplitLeft(2.0f, 0, &Textbox); - Textbox.x += (w-*Offset-TextRender()->TextWidth(0, FontSize, "|", -1, -1.0f)/2); + Textbox.x += (w - *Offset - TextRender()->TextWidth(0, FontSize, "|", -1, -1.0f) / 2); - if((2*time_get()/time_freq()) % 2) // make it blink + if((2 * time_get() / time_freq()) % 2) // make it blink UI()->DoLabel(&Textbox, "|", FontSize, -1); } UI()->ClipDisable(); @@ -487,7 +484,7 @@ float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Curre static float s_OffsetY; pRect->HSplitTop(33, &Handle, 0); - Handle.y += (pRect->h-Handle.h)*Current; + Handle.y += (pRect->h - Handle.h) * Current; // logic float Ret = Current; @@ -499,18 +496,20 @@ float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Curre UI()->SetActiveItem(0); float Min = pRect->y; - float Max = pRect->h-Handle.h; - float Cur = UI()->MouseY()-s_OffsetY; - Ret = (Cur-Min)/Max; - if(Ret < 0.0f) Ret = 0.0f; - if(Ret > 1.0f) Ret = 1.0f; + float Max = pRect->h - Handle.h; + float Cur = UI()->MouseY() - s_OffsetY; + Ret = (Cur - Min) / Max; + if(Ret < 0.0f) + Ret = 0.0f; + if(Ret > 1.0f) + Ret = 1.0f; } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { UI()->SetActiveItem(pID); - s_OffsetY = UI()->MouseY()-Handle.y; + s_OffsetY = UI()->MouseY() - Handle.y; } } @@ -520,17 +519,17 @@ float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Curre // render CUIRect Rail; pRect->VMargin(5.0f, &Rail); - RenderTools()->DrawUIRect(&Rail, ColorRGBA(1,1,1,0.25f), 0, 0.0f); + RenderTools()->DrawUIRect(&Rail, ColorRGBA(1, 1, 1, 0.25f), 0, 0.0f); CUIRect Slider = Handle; - Slider.w = Rail.x-Slider.x; - RenderTools()->DrawUIRect(&Slider, ColorRGBA(1,1,1,0.25f), CUI::CORNER_L, 2.5f); - Slider.x = Rail.x+Rail.w; - RenderTools()->DrawUIRect(&Slider, ColorRGBA(1,1,1,0.25f), CUI::CORNER_R, 2.5f); + Slider.w = Rail.x - Slider.x; + RenderTools()->DrawUIRect(&Slider, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_L, 2.5f); + Slider.x = Rail.x + Rail.w; + RenderTools()->DrawUIRect(&Slider, ColorRGBA(1, 1, 1, 0.25f), CUI::CORNER_R, 2.5f); Slider = Handle; Slider.Margin(5.0f, &Slider); - RenderTools()->DrawUIRect(&Slider, ColorRGBA(1,1,1,0.25f * ButtonColorMul(pID)), CUI::CORNER_ALL, 2.5f); + RenderTools()->DrawUIRect(&Slider, ColorRGBA(1, 1, 1, 0.25f * ButtonColorMul(pID)), CUI::CORNER_ALL, 2.5f); return Ret; } @@ -538,49 +537,49 @@ float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Curre ColorRGBA CEditor::GetButtonColor(const void *pID, int Checked) { if(Checked < 0) - return ColorRGBA(0,0,0,0.5f); + return ColorRGBA(0, 0, 0, 0.5f); switch(Checked) { case 7: // selected + game layers if(UI()->HotItem() == pID) - return ColorRGBA(1,0,0,0.4f); - return ColorRGBA(1,0,0,0.2f); + return ColorRGBA(1, 0, 0, 0.4f); + return ColorRGBA(1, 0, 0, 0.2f); case 6: // game layers if(UI()->HotItem() == pID) - return ColorRGBA(1,1,1,0.4f); - return ColorRGBA(1,1,1,0.2f); + return ColorRGBA(1, 1, 1, 0.4f); + return ColorRGBA(1, 1, 1, 0.2f); case 5: // selected + image/sound should be embedded if(UI()->HotItem() == pID) - return ColorRGBA(1,0,0,0.75f); - return ColorRGBA(1,0,0,0.5f); + return ColorRGBA(1, 0, 0, 0.75f); + return ColorRGBA(1, 0, 0, 0.5f); case 4: // image/sound should be embedded if(UI()->HotItem() == pID) - return ColorRGBA(1,0,0,1.0f); - return ColorRGBA(1,0,0,0.875f); + return ColorRGBA(1, 0, 0, 1.0f); + return ColorRGBA(1, 0, 0, 0.875f); case 3: // selected + unused image/sound if(UI()->HotItem() == pID) - return ColorRGBA(1,0,1,0.75f); - return ColorRGBA(1,0,1,0.5f); + return ColorRGBA(1, 0, 1, 0.75f); + return ColorRGBA(1, 0, 1, 0.5f); case 2: // unused image/sound if(UI()->HotItem() == pID) - return ColorRGBA(0,0,1,0.75f); - return ColorRGBA(0,0,1,0.5f); + return ColorRGBA(0, 0, 1, 0.75f); + return ColorRGBA(0, 0, 1, 0.5f); case 1: // selected if(UI()->HotItem() == pID) - return ColorRGBA(1,0,0,0.75f); - return ColorRGBA(1,0,0,0.5f); + return ColorRGBA(1, 0, 0, 0.75f); + return ColorRGBA(1, 0, 0, 0.5f); default: // regular if(UI()->HotItem() == pID) - return ColorRGBA(1,1,1,0.75f); - return ColorRGBA(1,1,1,0.5f); + return ColorRGBA(1, 1, 1, 0.75f); + return ColorRGBA(1, 1, 1, 0.5f); } } @@ -588,7 +587,7 @@ int CEditor::DoButton_Editor_Common(const void *pID, const char *pText, int Chec { if(UI()->MouseInside(pRect)) { - if(Flags&BUTTON_CONTEXT) + if(Flags & BUTTON_CONTEXT) ms_pUiGotContext = pID; if(m_pTooltip) m_pTooltip = pToolTip; @@ -603,7 +602,6 @@ int CEditor::DoButton_Editor_Common(const void *pID, const char *pText, int Chec //return UI()->DoButton(id, text, checked, r, draw_func, 0); } - int CEditor::DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); @@ -617,7 +615,7 @@ int CEditor::DoButton_Env(const void *pID, const char *pText, int Checked, const { float Bright = Checked ? 1.0f : 0.5f; float Alpha = UI()->HotItem() == pID ? 1.0f : 0.75f; - ColorRGBA Color = ColorRGBA(BaseColor.r*Bright, BaseColor.g*Bright, BaseColor.b*Bright, Alpha); + ColorRGBA Color = ColorRGBA(BaseColor.r * Bright, BaseColor.g * Bright, BaseColor.b * Bright, Alpha); RenderTools()->DrawUIRect(pRect, Color, CUI::CORNER_ALL, 3.0f); UI()->DoLabel(pRect, pText, 10.f, 0, -1); @@ -677,14 +675,14 @@ int CEditor::DoButton_Ex(const void *pID, const char *pText, int Checked, const int CEditor::DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_R, 3.0f); - UI()->DoLabel(pRect, pText?pText:"+", 10, 0, -1); + UI()->DoLabel(pRect, pText ? pText : "+", 10, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_L, 3.0f); - UI()->DoLabel(pRect, pText?pText:"-", 10, 0, -1); + UI()->DoLabel(pRect, pText ? pText : "-", 10, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } @@ -707,8 +705,8 @@ void CEditor::RenderGrid(CLayerGroup *pGroup) int LineDistance = GetLineDistance(); - int XOffset = aGroupPoints[0]/LineDistance; - int YOffset = aGroupPoints[1]/LineDistance; + int XOffset = aGroupPoints[0] / LineDistance; + int YOffset = aGroupPoints[1] / LineDistance; int XGridOffset = XOffset % m_GridFactor; int YGridOffset = YOffset % m_GridFactor; @@ -717,20 +715,20 @@ void CEditor::RenderGrid(CLayerGroup *pGroup) for(int i = 0; i < (int)w; i++) { - if((i+YGridOffset) % m_GridFactor == 0) + if((i + YGridOffset) % m_GridFactor == 0) Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); else Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); - IGraphics::CLineItem Line = IGraphics::CLineItem(LineDistance*XOffset, LineDistance*i+LineDistance*YOffset, w+aGroupPoints[2], LineDistance*i+LineDistance*YOffset); + IGraphics::CLineItem Line = IGraphics::CLineItem(LineDistance * XOffset, LineDistance * i + LineDistance * YOffset, w + aGroupPoints[2], LineDistance * i + LineDistance * YOffset); Graphics()->LinesDraw(&Line, 1); - if((i+XGridOffset) % m_GridFactor == 0) + if((i + XGridOffset) % m_GridFactor == 0) Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); else Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); - Line = IGraphics::CLineItem(LineDistance*i+LineDistance*XOffset, LineDistance*YOffset, LineDistance*i+LineDistance*XOffset, h+aGroupPoints[3]); + Line = IGraphics::CLineItem(LineDistance * i + LineDistance * XOffset, LineDistance * YOffset, LineDistance * i + LineDistance * XOffset, h + aGroupPoints[3]); Graphics()->LinesDraw(&Line, 1); } Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); @@ -743,19 +741,19 @@ void CEditor::RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, Graphics()->BlendNormal(); Graphics()->QuadsBegin(); Graphics()->SetColor(Brightness, Brightness, Brightness, 1.0f); - Graphics()->QuadsSetSubset(0,0, View.w/Size, View.h/Size); + Graphics()->QuadsSetSubset(0, 0, View.w / Size, View.h / Size); IGraphics::CQuadItem QuadItem(View.x, View.y, View.w, View.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } -int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip, bool IsDegree, bool IsHex, int Corners, ColorRGBA* Color) +int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip, bool IsDegree, bool IsHex, int Corners, ColorRGBA *Color) { // logic static float s_Value; static char s_NumStr[64]; static bool s_TextMode = false; - static void* s_LastTextpID = pID; + static void *s_LastTextpID = pID; int Inside = UI()->MouseInside(pRect); if(UI()->MouseButton(1) && UI()->HotItem() == pID) @@ -788,7 +786,7 @@ int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, in UI()->SetActiveItem(&s_NumberBoxID); if(Input()->KeyIsPressed(KEY_RETURN) || Input()->KeyIsPressed(KEY_KP_ENTER) || - ((UI()->MouseButton(1) || UI()->MouseButton(0)) && !Inside)) + ((UI()->MouseButton(1) || UI()->MouseButton(0)) && !Inside)) { if(IsHex) Current = clamp(str_toint_base(s_NumStr, 16), Min, Max); @@ -813,15 +811,15 @@ int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, in if(UI()->MouseButton(0)) { if(Input()->KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) - s_Value += m_MouseDeltaX*0.05f; + s_Value += m_MouseDeltaX * 0.05f; else s_Value += m_MouseDeltaX; if(absolute(s_Value) > Scale) { - int Count = (int)(s_Value/Scale); + int Count = (int)(s_Value / Scale); s_Value = fmod(s_Value, Scale); - Current += Step*Count; + Current += Step * Count; Current = clamp(Current, Min, Max); // Constrain to discrete steps @@ -852,13 +850,13 @@ int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, in // render char aBuf[128]; if(pLabel[0] != '\0') - str_format(aBuf, sizeof(aBuf),"%s %d", pLabel, Current); + str_format(aBuf, sizeof(aBuf), "%s %d", pLabel, Current); else if(IsDegree) - str_format(aBuf, sizeof(aBuf),"%d°", Current); + str_format(aBuf, sizeof(aBuf), "%d°", Current); else if(IsHex) - str_format(aBuf, sizeof(aBuf),"#%06X", Current); + str_format(aBuf, sizeof(aBuf), "#%06X", Current); else - str_format(aBuf, sizeof(aBuf),"%d", Current); + str_format(aBuf, sizeof(aBuf), "%d", Current); RenderTools()->DrawUIRect(pRect, Color ? *Color : GetButtonColor(pID, 0), Corners, 5.0f); UI()->DoLabel(pRect, aBuf, 10, 0, -1); } @@ -921,7 +919,7 @@ CSoundSource *CEditor::GetSelectedSource() void CEditor::SelectLayer(int LayerIndex, int GroupIndex) { - if (GroupIndex != -1) + if(GroupIndex != -1) m_SelectedGroup = GroupIndex; m_lSelectedLayers.clear(); @@ -943,7 +941,7 @@ void CEditor::DeleteSelectedQuads() for(int i = 0; i < m_lSelectedQuads.size(); ++i) { pLayer->m_lQuads.remove_index(m_lSelectedQuads[i]); - for(int j = i+1; j < m_lSelectedQuads.size(); ++j) + for(int j = i + 1; j < m_lSelectedQuads.size(); ++j) if(m_lSelectedQuads[j] > m_lSelectedQuads[i]) m_lSelectedQuads[j]--; @@ -969,7 +967,7 @@ int CEditor::FindSelectedQuadIndex(int Index) void CEditor::CallbackOpenMap(const char *pFileName, int StorageType, void *pUser) { - CEditor *pEditor = (CEditor*)pUser; + CEditor *pEditor = (CEditor *)pUser; if(pEditor->Load(pFileName, StorageType)) { pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder; @@ -979,7 +977,7 @@ void CEditor::CallbackOpenMap(const char *pFileName, int StorageType, void *pUse void CEditor::CallbackAppendMap(const char *pFileName, int StorageType, void *pUser) { - CEditor *pEditor = (CEditor*)pUser; + CEditor *pEditor = (CEditor *)pUser; if(pEditor->Append(pFileName, StorageType)) pEditor->m_aFileName[0] = 0; else @@ -990,7 +988,7 @@ void CEditor::CallbackAppendMap(const char *pFileName, int StorageType, void *pU void CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUser) { - CEditor *pEditor = static_cast(pUser); + CEditor *pEditor = static_cast(pUser); char aBuf[1024]; // add map extension if(!str_endswith(pFileName, ".map")) @@ -1013,7 +1011,7 @@ void CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUse void CEditor::CallbackSaveCopyMap(const char *pFileName, int StorageType, void *pUser) { - CEditor *pEditor = static_cast(pUser); + CEditor *pEditor = static_cast(pUser); char aBuf[1024]; // add map extension if(!str_endswith(pFileName, ".map")) @@ -1032,9 +1030,11 @@ void CEditor::CallbackSaveCopyMap(const char *pFileName, int StorageType, void * pEditor->m_Dialog = DIALOG_NONE; } -static int EntitiesListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) { - CEditor *pEditor = (CEditor*)pUser; - if (!IsDir && str_endswith(pName, ".png")) { +static int EntitiesListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + if(!IsDir && str_endswith(pName, ".png")) + { std::string Name = pName; pEditor->m_SelectEntitiesFiles.push_back(Name.substr(0, Name.length() - 4)); } @@ -1049,7 +1049,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) CUIRect TB_Top, TB_Bottom; CUIRect Button; - ToolBar.HSplitTop(ToolBar.h/2.0f, &TB_Top, &TB_Bottom); + ToolBar.HSplitTop(ToolBar.h / 2.0f, &TB_Top, &TB_Bottom); TB_Top.HSplitBottom(2.5f, &TB_Top, 0); TB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom); @@ -1134,14 +1134,15 @@ void CEditor::DoToolbar(CUIRect ToolBar) TB_Top.VSplitLeft(5.0f, 0, &TB_Top); TB_Top.VSplitLeft(45.0f, &Button, &TB_Top); - if(DoButton_Editor(&Button, "Entities", 0, &Button, 0, "Choose game layer entities image for different gametypes")) { + if(DoButton_Editor(&Button, "Entities", 0, &Button, 0, "Choose game layer entities image for different gametypes")) + { m_SelectEntitiesFiles.clear(); Storage()->ListDirectory(IStorage::TYPE_ALL, "editor/entities", EntitiesListdirCallback, this); std::sort(m_SelectEntitiesFiles.begin(), m_SelectEntitiesFiles.end()); static int s_EntitiesPopupID = 0; - UiInvokePopupMenu(&s_EntitiesPopupID, 0, Button.x, Button.y+18.0f, - 250, m_SelectEntitiesFiles.size()*14 + 10, PopupEntities); + UiInvokePopupMenu(&s_EntitiesPopupID, 0, Button.x, Button.y + 18.0f, + 250, m_SelectEntitiesFiles.size() * 14 + 10, PopupEntities); } TB_Top.VSplitLeft(5.0f, 0, &TB_Top); @@ -1198,7 +1199,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) { TileLayer = true; - s_RotationAmount = maximum(90, (s_RotationAmount/90)*90); + s_RotationAmount = maximum(90, (s_RotationAmount / 90) * 90); break; } s_RotationAmount = UiDoValueSelector(&s_RotationAmount, &Button, "", s_RotationAmount, TileLayer ? 90 : 1, 359, TileLayer ? 90 : 1, TileLayer ? 10.0f : 2.0f, "Rotation of the brush in degrees. Use left mouse button to drag and change the value. Hold shift to be more precise.", true); @@ -1208,7 +1209,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) if(DoButton_Ex(&s_CcwButton, "CCW", Enabled, &Button, 0, "[R] Rotates the brush counter clockwise", CUI::CORNER_L) || (Input()->KeyPress(KEY_R) && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) - m_Brush.m_lLayers[i]->BrushRotate(-s_RotationAmount/360.0f*pi*2); + m_Brush.m_lLayers[i]->BrushRotate(-s_RotationAmount / 360.0f * pi * 2); } TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); @@ -1216,7 +1217,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) if(DoButton_Ex(&s_CwButton, "CW", Enabled, &Button, 0, "[T] Rotates the brush clockwise", CUI::CORNER_R) || (Input()->KeyPress(KEY_T) && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) - m_Brush.m_lLayers[i]->BrushRotate(s_RotationAmount/360.0f*pi*2); + m_Brush.m_lLayers[i]->BrushRotate(s_RotationAmount / 360.0f * pi * 2); } TB_Top.VSplitLeft(5.0f, &Button, &TB_Top); @@ -1280,7 +1281,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) { TB_Bottom.VSplitLeft(45.0f, &Button, &TB_Bottom); static int s_RefocusButton = 0; - if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX&&m_WorldOffsetY ? 0 : -1, &Button, 0, "[HOME] Restore map focus") || (m_EditBoxActive == 0 && Input()->KeyPress(KEY_HOME))) + if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX && m_WorldOffsetY ? 0 : -1, &Button, 0, "[HOME] Restore map focus") || (m_EditBoxActive == 0 && Input()->KeyPress(KEY_HOME))) { m_WorldOffsetX = 0; m_WorldOffsetY = 0; @@ -1308,10 +1309,9 @@ void CEditor::DoToolbar(CUIRect ToolBar) TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); } - // do tele/tune/switch/speedup button { - int (*pPopupFunc)(CEditor *peditor, CUIRect View, void *pContext) = NULL; + int (*pPopupFunc)(CEditor * peditor, CUIRect View, void *pContext) = NULL; const char *aButtonName = 0; float Height = 0.0f; CLayerTiles *pS = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); @@ -1349,8 +1349,7 @@ void CEditor::DoToolbar(CUIRect ToolBar) TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); static int s_ModifierButton = 0; - if(DoButton_Ex(&s_ModifierButton, aButtonName, 0, &Button, 0, aBuf, CUI::CORNER_ALL) - || (CtrlPressed && Input()->KeyPress(KEY_A))) + if(DoButton_Ex(&s_ModifierButton, aButtonName, 0, &Button, 0, aBuf, CUI::CORNER_ALL) || (CtrlPressed && Input()->KeyPress(KEY_A))) { static int s_ModifierPopupID = 0; if(!UiPopupExists(&s_ModifierPopupID)) @@ -1376,12 +1375,12 @@ void CEditor::DoToolbar(CUIRect ToolBar) if(pLayer->m_Type == LAYERTYPE_QUADS) { Invoked = DoButton_Editor(&s_AddItemButton, "Add Quad", 0, &Button, 0, "[ctrl+q] Add a new quad") || - (Input()->KeyPress(KEY_Q) && CtrlPressed); + (Input()->KeyPress(KEY_Q) && CtrlPressed); } else if(pLayer->m_Type == LAYERTYPE_SOUNDS) { Invoked = DoButton_Editor(&s_AddItemButton, "Add Sound", 0, &Button, 0, "[ctrl+q] Add a new sound source") || - (Input()->KeyPress(KEY_Q) && CtrlPressed); + (Input()->KeyPress(KEY_Q) && CtrlPressed); } if(Invoked) @@ -1390,12 +1389,12 @@ void CEditor::DoToolbar(CUIRect ToolBar) float Mapping[4]; pGroup->Mapping(Mapping); - int x = Mapping[0] + (Mapping[2]-Mapping[0]) / 2; - int y = Mapping[1] + (Mapping[3]-Mapping[1]) / 2; + int x = Mapping[0] + (Mapping[2] - Mapping[0]) / 2; + int y = Mapping[1] + (Mapping[3] - Mapping[1]) / 2; if(Input()->KeyPress(KEY_Q) && CtrlPressed) { - x += UI()->MouseWorldX() - (m_WorldOffsetX*pGroup->m_ParallaxX/100) - pGroup->m_OffsetX; - y += UI()->MouseWorldY() - (m_WorldOffsetY*pGroup->m_ParallaxY/100) - pGroup->m_OffsetY; + x += UI()->MouseWorldX() - (m_WorldOffsetX * pGroup->m_ParallaxX / 100) - pGroup->m_OffsetX; + y += UI()->MouseWorldY() - (m_WorldOffsetY * pGroup->m_ParallaxY / 100) - pGroup->m_OffsetY; } if(pLayer->m_Type == LAYERTYPE_QUADS) @@ -1421,7 +1420,6 @@ void CEditor::DoToolbar(CUIRect ToolBar) TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); } - // Brush draw mode button { TB_Bottom.VSplitLeft(65.0f, &Button, &TB_Bottom); @@ -1446,7 +1444,7 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) { enum { - OP_NONE=0, + OP_NONE = 0, OP_MOVE, OP_CONTEXT_MENU, }; @@ -1461,9 +1459,9 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) float CenterX = fx2f(pSource->m_Position.x); float CenterY = fx2f(pSource->m_Position.y); - float dx = (CenterX - wx)/m_WorldZoom; - float dy = (CenterY - wy)/m_WorldZoom; - if(dx*dx+dy*dy < 50) + float dx = (CenterX - wx) / m_WorldZoom; + float dy = (CenterY - wy) / m_WorldZoom; + if(dx * dx + dy * dy < 50) UI()->SetHotItem(pID); bool IgnoreGrid; @@ -1474,7 +1472,7 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) if(UI()->ActiveItem() == pID) { - if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.05f) + if(m_MouseDeltaWx * m_MouseDeltaWx + m_MouseDeltaWy * m_MouseDeltaWy > 0.05f) { if(s_Operation == OP_MOVE) { @@ -1485,13 +1483,13 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) float x = 0.0f; float y = 0.0f; if(wx >= 0) - x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); if(wy >= 0) - y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); pSource->m_Position.x = f2fx(x); pSource->m_Position.y = f2fx(y); @@ -1535,13 +1533,13 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) } } - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); } else if(UI()->HotItem() == pID) { ms_pUiGotContext = pID; - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); m_pTooltip = "Left mouse button to move. Hold alt to ignore grid."; if(UI()->MouseButton(0)) @@ -1561,10 +1559,10 @@ void CEditor::DoSoundSource(CSoundSource *pSource, int Index) } else { - Graphics()->SetColor(0,1,0,1); + Graphics()->SetColor(0, 1, 0, 1); } - IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f * m_WorldZoom, 5.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } @@ -1572,7 +1570,7 @@ void CEditor::DoQuad(CQuad *q, int Index) { enum { - OP_NONE=0, + OP_NONE = 0, OP_MOVE_ALL, OP_MOVE_PIVOT, OP_ROTATE, @@ -1592,9 +1590,9 @@ void CEditor::DoQuad(CQuad *q, int Index) float CenterX = fx2f(q->m_aPoints[4].x); float CenterY = fx2f(q->m_aPoints[4].y); - float dx = (CenterX - wx)/m_WorldZoom; - float dy = (CenterY - wy)/m_WorldZoom; - if(dx*dx+dy*dy < 50) + float dx = (CenterX - wx) / m_WorldZoom; + float dy = (CenterY - wy) / m_WorldZoom; + if(dx * dx + dy * dy < 50) UI()->SetHotItem(pID); bool IgnoreGrid; @@ -1606,14 +1604,14 @@ void CEditor::DoQuad(CQuad *q, int Index) // draw selection background if(IsQuadSelected(Index)) { - Graphics()->SetColor(0,0,0,1); - IGraphics::CQuadItem QuadItem(CenterX, CenterY, 7.0f*m_WorldZoom, 7.0f*m_WorldZoom); + Graphics()->SetColor(0, 0, 0, 1); + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 7.0f * m_WorldZoom, 7.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } if(UI()->ActiveItem() == pID) { - if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.05f) + if(m_MouseDeltaWx * m_MouseDeltaWx + m_MouseDeltaWy * m_MouseDeltaWy > 0.05f) { // check if we only should move pivot if(s_Operation == OP_MOVE_PIVOT) @@ -1625,13 +1623,13 @@ void CEditor::DoQuad(CQuad *q, int Index) float x = 0.0f; float y = 0.0f; if(wx >= 0) - x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); if(wy >= 0) - y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); q->m_aPoints[4].x = f2fx(x); q->m_aPoints[4].y = f2fx(y); @@ -1653,13 +1651,13 @@ void CEditor::DoQuad(CQuad *q, int Index) float x = 0.0f; float y = 0.0f; if(wx >= 0) - x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); if(wy >= 0) - y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); int OffsetX = f2fx(x) - q->m_aPoints[4].x; int OffsetY = f2fx(y) - q->m_aPoints[4].y; @@ -1705,7 +1703,7 @@ void CEditor::DoQuad(CQuad *q, int Index) } } - s_RotateAngle += (m_MouseDeltaX) * 0.002f; + s_RotateAngle += (m_MouseDeltaX)*0.002f; if(s_Operation == OP_CONTEXT_MENU) { @@ -1755,13 +1753,13 @@ void CEditor::DoQuad(CQuad *q, int Index) } } - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); } else if(UI()->HotItem() == pID) { ms_pUiGotContext = pID; - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); m_pTooltip = "Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate. Hold alt to ignore grid. Hold shift and right click to delete."; if(UI()->MouseButton(0)) @@ -1829,9 +1827,9 @@ void CEditor::DoQuad(CQuad *q, int Index) } } else - Graphics()->SetColor(0,1,0,1); + Graphics()->SetColor(0, 1, 0, 1); - IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f * m_WorldZoom, 5.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } @@ -1845,22 +1843,22 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) float px = fx2f(pQuad->m_aPoints[V].x); float py = fx2f(pQuad->m_aPoints[V].y); - float dx = (px - wx)/m_WorldZoom; - float dy = (py - wy)/m_WorldZoom; - if(dx*dx+dy*dy < 50) + float dx = (px - wx) / m_WorldZoom; + float dy = (py - wy) / m_WorldZoom; + if(dx * dx + dy * dy < 50) UI()->SetHotItem(pID); // draw selection background - if(IsQuadSelected(QuadIndex) && m_SelectedPoints&(1<SetColor(0,0,0,1); - IGraphics::CQuadItem QuadItem(px, py, 7.0f*m_WorldZoom, 7.0f*m_WorldZoom); + Graphics()->SetColor(0, 0, 0, 1); + IGraphics::CQuadItem QuadItem(px, py, 7.0f * m_WorldZoom, 7.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } enum { - OP_NONE=0, + OP_NONE = 0, OP_MOVEPOINT, OP_MOVEUV, OP_CONTEXT_MENU @@ -1879,7 +1877,7 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) { if(!s_Moved) { - if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.05f) + if(m_MouseDeltaWx * m_MouseDeltaWx + m_MouseDeltaWy * m_MouseDeltaWy > 0.05f) s_Moved = true; } @@ -1895,13 +1893,13 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) float x = 0.0f; float y = 0.0f; if(wx >= 0) - x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); if(wy >= 0) - y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); int OffsetX = f2fx(x) - pQuad->m_aPoints[V].x; int OffsetY = f2fx(y) - pQuad->m_aPoints[V].y; @@ -1910,7 +1908,7 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) { CQuad *pCurrentQuad = &pLayer->m_lQuads[m_lSelectedQuads[i]]; for(int m = 0; m < 4; m++) - if(m_SelectedPoints&(1<m_aPoints[m].x += OffsetX; pCurrentQuad->m_aPoints[m].y += OffsetY; @@ -1926,7 +1924,7 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) { CQuad *pCurrentQuad = &pLayer->m_lQuads[m_lSelectedQuads[i]]; for(int m = 0; m < 4; m++) - if(m_SelectedPoints&(1<m_aPoints[m].x += OffsetX; pCurrentQuad->m_aPoints[m].y += OffsetY; @@ -1941,16 +1939,16 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) { CQuad *pCurrentQuad = &pLayer->m_lQuads[m_lSelectedQuads[i]]; for(int m = 0; m < 4; m++) - if(m_SelectedPoints&(1<m_aTexcoords[m].x += f2fx(m_MouseDeltaWx*0.001f); - pCurrentQuad->m_aTexcoords[(m+2)%4].x += f2fx(m_MouseDeltaWx*0.001f); + pCurrentQuad->m_aTexcoords[m].x += f2fx(m_MouseDeltaWx * 0.001f); + pCurrentQuad->m_aTexcoords[(m + 2) % 4].x += f2fx(m_MouseDeltaWx * 0.001f); - pCurrentQuad->m_aTexcoords[m].y += f2fx(m_MouseDeltaWy*0.001f); - pCurrentQuad->m_aTexcoords[m^1].y += f2fx(m_MouseDeltaWy*0.001f); + pCurrentQuad->m_aTexcoords[m].y += f2fx(m_MouseDeltaWy * 0.001f); + pCurrentQuad->m_aTexcoords[m ^ 1].y += f2fx(m_MouseDeltaWy * 0.001f); } } } @@ -1980,9 +1978,9 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) if(!s_Moved) { if(Input()->KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) - m_SelectedPoints ^= 1<SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); } else if(UI()->HotItem() == pID) { ms_pUiGotContext = pID; - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); m_pTooltip = "Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid."; if(UI()->MouseButton(0)) @@ -2014,12 +2012,12 @@ void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) else s_Operation = OP_MOVEPOINT; - if(!(m_SelectedPoints&(1<KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) - m_SelectedPoints |= 1<SetActiveItem(pID); - if(!(m_SelectedPoints&(1<KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) - m_SelectedPoints |= 1<SetColor(1,0,0,1); + Graphics()->SetColor(1, 0, 0, 1); - IGraphics::CQuadItem QuadItem(px, py, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + IGraphics::CQuadItem QuadItem(px, py, 5.0f * m_WorldZoom, 5.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHandle Texture) { int Num = lQuads.size(); - CEnvelope **apEnvelope = new CEnvelope*[Num]; - mem_zero(apEnvelope, sizeof(CEnvelope*)*Num); + CEnvelope **apEnvelope = new CEnvelope *[Num]; + mem_zero(apEnvelope, sizeof(CEnvelope *) * Num); for(int i = 0; i < Num; i++) { if((m_ShowEnvelopePreview == 1 && lQuads[i].m_PosEnv == m_SelectedEnvelope) || m_ShowEnvelopePreview == 2) @@ -2066,7 +2064,7 @@ void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHan //Draw Lines Graphics()->TextureClear(); Graphics()->LinesBegin(); - Graphics()->SetColor(80.0f/255, 150.0f/255, 230.f/255, 0.5f); + Graphics()->SetColor(80.0f / 255, 150.0f / 255, 230.f / 255, 0.5f); for(int j = 0; j < Num; j++) { if(!apEnvelope[j]) @@ -2074,15 +2072,15 @@ void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHan //QuadParams const CPoint *pPoints = lQuads[j].m_aPoints; - for(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++) + for(int i = 0; i < apEnvelope[j]->m_lPoints.size() - 1; i++) { - float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); + float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); - vec2 Pos0 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); + vec2 Pos0 = vec2(fx2f(pPoints[4].x) + OffsetX, fx2f(pPoints[4].y) + OffsetY); - OffsetX = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[0]); - OffsetY = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[1]); - vec2 Pos1 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); + OffsetX = fx2f(apEnvelope[j]->m_lPoints[i + 1].m_aValues[0]); + OffsetY = fx2f(apEnvelope[j]->m_lPoints[i + 1].m_aValues[1]); + vec2 Pos1 = vec2(fx2f(pPoints[4].x) + OffsetX, fx2f(pPoints[4].y) + OffsetY); IGraphics::CLineItem Line = IGraphics::CLineItem(Pos0.x, Pos0.y, Pos1.x, Pos1.y); Graphics()->LinesDraw(&Line, 1); @@ -2106,9 +2104,9 @@ void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHan for(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++) { //Calc Env Position - float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); + float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); - float Rot = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[2])/360.0f*pi*2; + float Rot = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[2]) / 360.0f * pi * 2; //Set Colours float Alpha = (m_SelectedQuadEnvelope == lQuads[j].m_PosEnv && m_SelectedEnvelopePoint == i) ? 0.65f : 0.35f; @@ -2140,15 +2138,14 @@ void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHan fx2f(lQuads[j].m_aTexcoords[0].x), fx2f(lQuads[j].m_aTexcoords[0].y), fx2f(lQuads[j].m_aTexcoords[1].x), fx2f(lQuads[j].m_aTexcoords[1].y), fx2f(lQuads[j].m_aTexcoords[2].x), fx2f(lQuads[j].m_aTexcoords[2].y), - fx2f(lQuads[j].m_aTexcoords[3].x), fx2f(lQuads[j].m_aTexcoords[3].y) - ); + fx2f(lQuads[j].m_aTexcoords[3].x), fx2f(lQuads[j].m_aTexcoords[3].y)); //Set Quad Coords & Draw IGraphics::CFreeformItem Freeform( - fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, - fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, - fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, - fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); + fx2f(pPoints[0].x) + OffsetX, fx2f(pPoints[0].y) + OffsetY, + fx2f(pPoints[1].x) + OffsetX, fx2f(pPoints[1].y) + OffsetY, + fx2f(pPoints[2].x) + OffsetX, fx2f(pPoints[2].y) + OffsetY, + fx2f(pPoints[3].x) + OffsetX, fx2f(pPoints[3].y) + OffsetY); Graphics()->QuadsDrawFreeform(&Freeform, 1); } } @@ -2163,7 +2160,7 @@ void CEditor::DoQuadEnvelopes(const array &lQuads, IGraphics::CTextureHan continue; //QuadParams - for(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++) + for(int i = 0; i < apEnvelope[j]->m_lPoints.size() - 1; i++) DoQuadEnvPoint(&lQuads[j], j, i); } Graphics()->QuadsEnd(); @@ -2174,7 +2171,7 @@ void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) { enum { - OP_NONE=0, + OP_NONE = 0, OP_MOVE, OP_ROTATE, }; @@ -2188,12 +2185,12 @@ void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) static int s_ActQIndex = -1; // get pivot - float CenterX = fx2f(pQuad->m_aPoints[4].x)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]); - float CenterY = fx2f(pQuad->m_aPoints[4].y)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]); + float CenterX = fx2f(pQuad->m_aPoints[4].x) + fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]); + float CenterY = fx2f(pQuad->m_aPoints[4].y) + fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]); - float dx = (CenterX - wx)/m_WorldZoom; - float dy = (CenterY - wy)/m_WorldZoom; - if(dx*dx+dy*dy < 50.0f && UI()->ActiveItem() == 0) + float dx = (CenterX - wx) / m_WorldZoom; + float dy = (CenterY - wy) / m_WorldZoom; + if(dx * dx + dy * dy < 50.0f && UI()->ActiveItem() == 0) { UI()->SetHotItem(pID); s_ActQIndex = QIndex; @@ -2216,16 +2213,16 @@ void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) float x = 0.0f; float y = 0.0f; if(wx >= 0) - x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + x = (int)((wx - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); if(wy >= 0) - y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy + (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); else - y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + y = (int)((wy - (LineDistance / 2) * m_GridFactor) / (LineDistance * m_GridFactor)) * (LineDistance * m_GridFactor); - pEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x)-pQuad->m_aPoints[4].x; - pEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y)-pQuad->m_aPoints[4].y; + pEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x) - pQuad->m_aPoints[4].x; + pEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y) - pQuad->m_aPoints[4].y; } else { @@ -2234,7 +2231,7 @@ void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) } } else if(s_Operation == OP_ROTATE) - pEnvelope->m_lPoints[PIndex].m_aValues[2] += 10*m_MouseDeltaX; + pEnvelope->m_lPoints[PIndex].m_aValues[2] += 10 * m_MouseDeltaX; if(!UI()->MouseButton(0)) { @@ -2282,7 +2279,7 @@ void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) else Graphics()->SetColor(0.0f, 1.0f, 0.0f, 1.0f); - IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f * m_WorldZoom, 5.0f * m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } @@ -2292,14 +2289,13 @@ void CEditor::DoMapEditor(CUIRect View) if(!m_ShowPicker) { for(int g = 0; g < m_Map.m_lGroups.size(); g++) - {// don't render the front, tele, speedup and switch layer now we will do it later to make them on top of others + { // don't render the front, tele, speedup and switch layer now we will do it later to make them on top of others if( - m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pFrontLayer || - m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTeleLayer || - m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSpeedupLayer || - m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSwitchLayer || - m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTuneLayer - ) + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pFrontLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTeleLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSpeedupLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSwitchLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTuneLayer) continue; if(m_Map.m_lGroups[g]->m_Visible) m_Map.m_lGroups[g]->Render(); @@ -2312,18 +2308,14 @@ void CEditor::DoMapEditor(CUIRect View) m_Map.m_pGameGroup->MapScreen(); for(int i = 0; i < m_Map.m_pGameGroup->m_lLayers.size(); i++) { - if - ( - m_Map.m_pGameGroup->m_lLayers[i]->m_Visible && - ( - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pGameLayer || - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pFrontLayer || - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTeleLayer || - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSpeedupLayer || - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSwitchLayer || - m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTuneLayer - ) - ) + if( + m_Map.m_pGameGroup->m_lLayers[i]->m_Visible && + (m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pGameLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pFrontLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTeleLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSpeedupLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSwitchLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTuneLayer)) m_Map.m_pGameGroup->m_lLayers[i]->Render(); } } @@ -2356,7 +2348,7 @@ void CEditor::DoMapEditor(CUIRect View) enum { - OP_NONE=0, + OP_NONE = 0, OP_BRUSH_GRAB, OP_BRUSH_DRAW, OP_BRUSH_PAINT, @@ -2368,20 +2360,20 @@ void CEditor::DoMapEditor(CUIRect View) if(m_ShowPicker) { CUIRect Screen = *UI()->Screen(); - float Size = 32.0*16.0f; - float w = Size*(Screen.w/View.w); - float h = Size*(Screen.h/View.h); - float x = -(View.x/Screen.w)*w; - float y = -(View.y/Screen.h)*h; - wx = x+w*mx/Screen.w; - wy = y+h*my/Screen.h; + float Size = 32.0 * 16.0f; + float w = Size * (Screen.w / View.w); + float h = Size * (Screen.h / View.h); + float x = -(View.x / Screen.w) * w; + float y = -(View.y / Screen.h) * h; + wx = x + w * mx / Screen.w; + wy = y + h * my / Screen.h; CLayerTiles *t = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); if(t) { - Graphics()->MapScreen(x, y, x+w, y+h); + Graphics()->MapScreen(x, y, x + w, y + h); m_TilesetPicker.m_Image = t->m_Image; m_TilesetPicker.m_Texture = t->m_Texture; - if (m_BrushColorEnabled) + if(m_BrushColorEnabled) { m_TilesetPicker.m_Color = t->m_Color; m_TilesetPicker.m_Color.a = 255; @@ -2444,7 +2436,7 @@ void CEditor::DoMapEditor(CUIRect View) { // pick a type of layers to edit, prefering Tiles layers. int EditingType = -1; - for (int i = 0; i < m_lSelectedLayers.size(); i++) + for(int i = 0; i < m_lSelectedLayers.size(); i++) { CLayer *Layer = GetSelectedLayer(i); if(Layer && (EditingType == -1 || Layer->m_Type == LAYERTYPE_TILES)) @@ -2454,7 +2446,7 @@ void CEditor::DoMapEditor(CUIRect View) break; } } - for (int i = 0; i < m_lSelectedLayers.size() && NumEditLayers < 128; i++) + for(int i = 0; i < m_lSelectedLayers.size() && NumEditLayers < 128; i++) { pEditLayers[NumEditLayers] = GetSelectedLayerType(i, EditingType); if(pEditLayers[NumEditLayers]) @@ -2545,8 +2537,8 @@ void CEditor::DoMapEditor(CUIRect View) CUIRect r; r.x = s_StartWx; r.y = s_StartWy; - r.w = wx-s_StartWx; - r.h = wy-s_StartWy; + r.w = wx - s_StartWx; + r.h = wy - s_StartWy; if(r.w < 0) { r.x += r.w; @@ -2569,7 +2561,7 @@ void CEditor::DoMapEditor(CUIRect View) int BrushIndex = k % m_Brush.m_lLayers.size(); if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[BrushIndex]->m_Type) { - if (pEditLayers[k]->m_Type == LAYERTYPE_TILES) + if(pEditLayers[k]->m_Type == LAYERTYPE_TILES) { CLayerTiles *l = (CLayerTiles *)pEditLayers[k]; CLayerTiles *b = (CLayerTiles *)m_Brush.m_lLayers[BrushIndex]; @@ -2600,7 +2592,7 @@ void CEditor::DoMapEditor(CUIRect View) float px = fx2f(q->m_aPoints[4].x); float py = fx2f(q->m_aPoints[4].y); - if(px > r.x && px < r.x+r.w && py > r.y && py < r.y+r.h) + if(px > r.x && px < r.x + r.w && py > r.y && py < r.y + r.h) if(!IsQuadSelected(i)) m_lSelectedQuads.add(i); } @@ -2610,7 +2602,7 @@ void CEditor::DoMapEditor(CUIRect View) { // grab brush char aBuf[256]; - str_format(aBuf, sizeof(aBuf),"grabbing %f %f %f %f", r.x, r.y, r.w, r.h); + str_format(aBuf, sizeof(aBuf), "grabbing %f %f %f %f", r.x, r.y, r.w, r.h); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); // TODO: do all layers @@ -2642,7 +2634,8 @@ void CEditor::DoMapEditor(CUIRect View) for(int k = 0; k < NumEditLayers; k++) { int BrushIndex = k; - if(m_Brush.m_lLayers.size() != NumEditLayers) BrushIndex = 0; + if(m_Brush.m_lLayers.size() != NumEditLayers) + BrushIndex = 0; pEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[BrushIndex], r); } } @@ -2679,14 +2672,14 @@ void CEditor::DoMapEditor(CUIRect View) for(int k = 0; k < NumEditLayers; k++) { int BrushIndex = k; - if(m_Brush.m_lLayers.size() != NumEditLayers) BrushIndex = 0; + if(m_Brush.m_lLayers.size() != NumEditLayers) + BrushIndex = 0; if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[BrushIndex]->m_Type) pEditLayers[k]->BrushPlace(m_Brush.m_lLayers[BrushIndex], wx, wy); } - } - CLayerTiles *pLayer = (CLayerTiles*)GetSelectedLayerType(0, LAYERTYPE_TILES); + CLayerTiles *pLayer = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); if((Input()->KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) && pLayer) s_Operation = OP_BRUSH_PAINT; } @@ -2699,8 +2692,8 @@ void CEditor::DoMapEditor(CUIRect View) { if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) { - m_Brush.m_OffsetX = -(int)(wx/32.0f)*32; - m_Brush.m_OffsetY = -(int)(wy/32.0f)*32; + m_Brush.m_OffsetX = -(int)(wx / 32.0f) * 32; + m_Brush.m_OffsetY = -(int)(wy / 32.0f) * 32; break; } } @@ -2783,13 +2776,13 @@ void CEditor::DoMapEditor(CUIRect View) { if(s_Operation == OP_PAN_WORLD) { - m_WorldOffsetX -= m_MouseDeltaX*m_WorldZoom; - m_WorldOffsetY -= m_MouseDeltaY*m_WorldZoom; + m_WorldOffsetX -= m_MouseDeltaX * m_WorldZoom; + m_WorldOffsetY -= m_MouseDeltaY * m_WorldZoom; } else if(s_Operation == OP_PAN_EDITOR) { - m_EditorOffsetX -= m_MouseDeltaX*m_WorldZoom; - m_EditorOffsetY -= m_MouseDeltaY*m_WorldZoom; + m_EditorOffsetX -= m_MouseDeltaX * m_WorldZoom; + m_EditorOffsetY -= m_MouseDeltaY * m_WorldZoom; } // release mouse @@ -2802,8 +2795,6 @@ void CEditor::DoMapEditor(CUIRect View) UI()->SetActiveItem(0); } } - - } else if(UI()->ActiveItem() == s_pEditorID) { @@ -2823,19 +2814,19 @@ void CEditor::DoMapEditor(CUIRect View) Graphics()->TextureClear(); Graphics()->LinesBegin(); - CUIRect r; - r.x = GetSelectedGroup()->m_ClipX; - r.y = GetSelectedGroup()->m_ClipY; - r.w = GetSelectedGroup()->m_ClipW; - r.h = GetSelectedGroup()->m_ClipH; + CUIRect r; + r.x = GetSelectedGroup()->m_ClipX; + r.y = GetSelectedGroup()->m_ClipY; + r.w = GetSelectedGroup()->m_ClipW; + r.h = GetSelectedGroup()->m_ClipH; - IGraphics::CLineItem Array[4] = { - IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), - IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), - IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), - IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; - Graphics()->SetColor(1,0,0,1); - Graphics()->LinesDraw(Array, 4); + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(r.x, r.y, r.x + r.w, r.y), + IGraphics::CLineItem(r.x + r.w, r.y, r.x + r.w, r.y + r.h), + IGraphics::CLineItem(r.x + r.w, r.y + r.h, r.x, r.y + r.h), + IGraphics::CLineItem(r.x, r.y + r.h, r.x, r.y)}; + Graphics()->SetColor(1, 0, 0, 1); + Graphics()->LinesDraw(Array, 4); Graphics()->LinesEnd(); } @@ -2852,12 +2843,12 @@ void CEditor::DoMapEditor(CUIRect View) // possible screen sizes (white border) float aLastPoints[4]; float Start = 1.0f; //9.0f/16.0f; - float End = 16.0f/9.0f; + float End = 16.0f / 9.0f; const int NumSteps = 20; for(int i = 0; i <= NumSteps; i++) { float aPoints[4]; - float Aspect = Start + (End-Start)*(i/(float)NumSteps); + float Aspect = Start + (End - Start) * (i / (float)NumSteps); RenderTools()->MapscreenToWorld( m_WorldOffsetX, m_WorldOffsetY, @@ -2894,11 +2885,11 @@ void CEditor::DoMapEditor(CUIRect View) // two screen sizes (green and red border) { - Graphics()->SetColor(1,0,0,1); + Graphics()->SetColor(1, 0, 0, 1); for(int i = 0; i < 2; i++) { float aPoints[4]; - float aAspects[] = {4.0f/3.0f, 16.0f/10.0f, 5.0f/4.0f, 16.0f/9.0f}; + float aAspects[] = {4.0f / 3.0f, 16.0f / 10.0f, 5.0f / 4.0f, 16.0f / 9.0f}; float Aspect = aAspects[i]; RenderTools()->MapscreenToWorld( @@ -2908,16 +2899,16 @@ void CEditor::DoMapEditor(CUIRect View) CUIRect r; r.x = aPoints[0]; r.y = aPoints[1]; - r.w = aPoints[2]-aPoints[0]; - r.h = aPoints[3]-aPoints[1]; + r.w = aPoints[2] - aPoints[0]; + r.h = aPoints[3] - aPoints[1]; IGraphics::CLineItem Array[4] = { - IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), - IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), - IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), - IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; + IGraphics::CLineItem(r.x, r.y, r.x + r.w, r.y), + IGraphics::CLineItem(r.x + r.w, r.y, r.x + r.w, r.y + r.h), + IGraphics::CLineItem(r.x + r.w, r.y + r.h, r.x, r.y + r.h), + IGraphics::CLineItem(r.x, r.y + r.h, r.x, r.y)}; Graphics()->LinesDraw(Array, 4); - Graphics()->SetColor(0,1,0,1); + Graphics()->SetColor(0, 1, 0, 1); } } Graphics()->LinesEnd(); @@ -2926,8 +2917,8 @@ void CEditor::DoMapEditor(CUIRect View) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); - Graphics()->SetColor(0,0,1,0.3f); - RenderTools()->DrawCircle(m_WorldOffsetX, m_WorldOffsetY-3.0f, 20.0f, 32); + Graphics()->SetColor(0, 0, 1, 0.3f); + RenderTools()->DrawCircle(m_WorldOffsetX, m_WorldOffsetY - 3.0f, 20.0f, 32); Graphics()->QuadsEnd(); } } @@ -2936,7 +2927,7 @@ void CEditor::DoMapEditor(CUIRect View) { GetSelectedGroup()->MapScreen(); - CLayerQuads *pLayer = (CLayerQuads*)GetSelectedLayer(0); + CLayerQuads *pLayer = (CLayerQuads *)GetSelectedLayer(0); IGraphics::CTextureHandle Texture; if(pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size()) Texture = m_Map.m_lImages[pLayer->m_Image]->m_Texture; @@ -2949,7 +2940,6 @@ void CEditor::DoMapEditor(CUIRect View) //UI()->ClipDisable(); } - int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int *pNewVal, ColorRGBA Color) { int Change = -1; @@ -2970,21 +2960,21 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * Shifter.VSplitRight(10.0f, &Shifter, &Inc); Shifter.VSplitLeft(10.0f, &Dec, &Shifter); - str_format(aBuf, sizeof(aBuf),"%d", pProps[i].m_Value); - int NewValue = UiDoValueSelector((char *) &pIDs[i], &Shifter, "", pProps[i].m_Value, pProps[i].m_Min, pProps[i].m_Max, 1, 1.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise. Rightclick to edit as text.", false, false, 0, &Color); + str_format(aBuf, sizeof(aBuf), "%d", pProps[i].m_Value); + int NewValue = UiDoValueSelector((char *)&pIDs[i], &Shifter, "", pProps[i].m_Value, pProps[i].m_Min, pProps[i].m_Max, 1, 1.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise. Rightclick to edit as text.", false, false, 0, &Color); if(NewValue != pProps[i].m_Value) { *pNewVal = NewValue; Change = i; } - if(DoButton_ButtonDec((char *) &pIDs[i] +1, 0, 0, &Dec, 0, "Decrease")) + if(DoButton_ButtonDec((char *)&pIDs[i] + 1, 0, 0, &Dec, 0, "Decrease")) { - *pNewVal = pProps[i].m_Value-1; + *pNewVal = pProps[i].m_Value - 1; Change = i; } - if(DoButton_ButtonInc(((char *)&pIDs[i])+2, 0, 0, &Inc, 0, "Increase")) + if(DoButton_ButtonInc(((char *)&pIDs[i]) + 2, 0, 0, &Inc, 0, "Increase")) { - *pNewVal = pProps[i].m_Value+1; + *pNewVal = pProps[i].m_Value + 1; Change = i; } } @@ -2997,7 +2987,7 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * *pNewVal = 0; Change = i; } - if(DoButton_ButtonInc(((char *)&pIDs[i])+1, "Yes", pProps[i].m_Value, &Yes, 0, "")) + if(DoButton_ButtonInc(((char *)&pIDs[i]) + 1, "Yes", pProps[i].m_Value, &Yes, 0, "")) { *pNewVal = 1; Change = i; @@ -3022,13 +3012,13 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * int Value = pProps[i].m_Value; int NewValue = UiDoValueSelector(&pIDs[i], &Shifter, "", Value, pProps[i].m_Min, pProps[i].m_Max, Shift ? 1 : 45, Shift ? 1.0f : 10.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise. Rightclick to edit as text.", false, false, 0); - if(DoButton_ButtonDec(&pIDs[i]+1, 0, 0, &Dec, 0, "Decrease")) + if(DoButton_ButtonDec(&pIDs[i] + 1, 0, 0, &Dec, 0, "Decrease")) { NewValue = (round_ceil((pProps[i].m_Value / (float)Step)) - 1) * Step; if(NewValue < 0) NewValue += 360; } - if(DoButton_ButtonInc(&pIDs[i]+ 2, 0, 0, &Inc, 0, "Increase")) + if(DoButton_ButtonInc(&pIDs[i] + 2, 0, 0, &Inc, 0, "Increase")) NewValue = (pProps[i].m_Value + Step) / Step * Step; if(NewValue != pProps[i].m_Value) @@ -3046,15 +3036,15 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * // extra space CUIRect ColorBox, ColorSlots; - pToolBox->HSplitTop(3.0f*13.0f, &Slot, pToolBox); + pToolBox->HSplitTop(3.0f * 13.0f, &Slot, pToolBox); Slot.VSplitMid(&ColorBox, &ColorSlots); ColorBox.HMargin(1.0f, &ColorBox); ColorBox.VMargin(6.0f, &ColorBox); for(int c = 0; c < 4; c++) { - int v = (pProps[i].m_Value >> s_aShift[c])&0xff; - NewColor |= UiDoValueSelector(((char *)&pIDs[i])+c, &Shifter, s_paTexts[c], v, 0, 255, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.")<> s_aShift[c]) & 0xff; + NewColor |= UiDoValueSelector(((char *)&pIDs[i]) + c, &Shifter, s_paTexts[c], v, 0, 255, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.") << s_aShift[c]; if(c != 3) { @@ -3068,14 +3058,14 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * Slot.VSplitMid(0x0, &Shifter); Shifter.HMargin(1.0f, &Shifter); - int NewColorHex = pProps[i].m_Value&0xff; - NewColorHex |= UiDoValueSelector(((char *)&pIDs[i]-1), &Shifter, "", (pProps[i].m_Value >> 8)&0xFFFFFF, 0, 0xFFFFFF, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.", false, true) << 8; + int NewColorHex = pProps[i].m_Value & 0xff; + NewColorHex |= UiDoValueSelector(((char *)&pIDs[i] - 1), &Shifter, "", (pProps[i].m_Value >> 8) & 0xFFFFFF, 0, 0xFFFFFF, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.", false, true) << 8; // color picker ColorRGBA Color = ColorRGBA( - ((pProps[i].m_Value >> s_aShift[0])&0xff)/255.0f, - ((pProps[i].m_Value >> s_aShift[1])&0xff)/255.0f, - ((pProps[i].m_Value >> s_aShift[2])&0xff)/255.0f, + ((pProps[i].m_Value >> s_aShift[0]) & 0xff) / 255.0f, + ((pProps[i].m_Value >> s_aShift[1]) & 0xff) / 255.0f, + ((pProps[i].m_Value >> s_aShift[2]) & 0xff) / 255.0f, 1.0f); static int s_ColorPicker, s_ColorPickerID; @@ -3088,7 +3078,7 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * if(UI()->HotItem() == &ms_SVPicker || UI()->HotItem() == &ms_HuePicker) { ColorRGBA c = color_cast(ms_PickerColor); - NewColor = ((int)(c.r * 255.0f)&0xff) << 24 | ((int)(c.g * 255.0f)&0xff) << 16 | ((int)(c.b * 255.0f)&0xff) << 8 | (pProps[i].m_Value&0xff); + NewColor = ((int)(c.r * 255.0f) & 0xff) << 24 | ((int)(c.g * 255.0f) & 0xff) << 16 | ((int)(c.b * 255.0f) & 0xff) << 8 | (pProps[i].m_Value & 0xff); } // @@ -3145,28 +3135,28 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * Up.VSplitLeft(1.0f, 0, &Up); Left.VSplitLeft(10.0f, &Left, &Shifter); Shifter.VSplitRight(10.0f, &Shifter, &Right); - RenderTools()->DrawUIRect(&Shifter, ColorRGBA(1,1,1,0.5f), 0, 0.0f); + RenderTools()->DrawUIRect(&Shifter, ColorRGBA(1, 1, 1, 0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, "X", 10.0f, 0, -1); Up.VSplitLeft(10.0f, &Up, &Shifter); Shifter.VSplitRight(10.0f, &Shifter, &Down); - RenderTools()->DrawUIRect(&Shifter, ColorRGBA(1,1,1,0.5f), 0, 0.0f); + RenderTools()->DrawUIRect(&Shifter, ColorRGBA(1, 1, 1, 0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, "Y", 10.0f, 0, -1); if(DoButton_ButtonDec(&pIDs[i], "-", 0, &Left, 0, "Left")) { *pNewVal = 1; Change = i; } - if(DoButton_ButtonInc(((char *)&pIDs[i])+3, "+", 0, &Right, 0, "Right")) + if(DoButton_ButtonInc(((char *)&pIDs[i]) + 3, "+", 0, &Right, 0, "Right")) { *pNewVal = 2; Change = i; } - if(DoButton_ButtonDec(((char *)&pIDs[i])+1, "-", 0, &Up, 0, "Up")) + if(DoButton_ButtonDec(((char *)&pIDs[i]) + 1, "-", 0, &Up, 0, "Up")) { *pNewVal = 4; Change = i; } - if(DoButton_ButtonInc(((char *)&pIDs[i])+2, "+", 0, &Down, 0, "Down")) + if(DoButton_ButtonInc(((char *)&pIDs[i]) + 2, "+", 0, &Down, 0, "Down")) { *pNewVal = 8; Change = i; @@ -3212,7 +3202,7 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * if(pProps[i].m_Value < 0 || pProps[i].m_Min < 0 || pProps[i].m_Min >= m_Map.m_lImages.size()) str_copy(aBuf, "None", sizeof(aBuf)); else - str_format(aBuf, sizeof(aBuf),"%s", m_Map.m_lImages[pProps[i].m_Min]->m_AutoMapper.GetConfigName(pProps[i].m_Value)); + str_format(aBuf, sizeof(aBuf), "%s", m_Map.m_lImages[pProps[i].m_Min]->m_AutoMapper.GetConfigName(pProps[i].m_Value)); if(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0)) PopupSelectConfigAutoMapInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY()); @@ -3260,14 +3250,14 @@ int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int * RenderTools()->DrawUIRect(&Shifter, Color, 0, 5.0f); UI()->DoLabel(&Shifter, aBuf, FontSize, 0, -1); - if(DoButton_ButtonDec((char *) &pIDs[i] +1, 0, 0, &Dec, 0, "Previous Envelope")) + if(DoButton_ButtonDec((char *)&pIDs[i] + 1, 0, 0, &Dec, 0, "Previous Envelope")) { - *pNewVal = pProps[i].m_Value-1; + *pNewVal = pProps[i].m_Value - 1; Change = i; } - if(DoButton_ButtonInc(((char *)&pIDs[i])+2, 0, 0, &Inc, 0, "Next Envelope")) + if(DoButton_ButtonInc(((char *)&pIDs[i]) + 2, 0, 0, &Inc, 0, "Next Envelope")) { - *pNewVal = pProps[i].m_Value+1; + *pNewVal = pProps[i].m_Value + 1; Change = i; } } @@ -3286,7 +3276,7 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) CUIRect Slot, Button; char aBuf[64]; - float LayersHeight = 12.0f; // Height of AddGroup button + float LayersHeight = 12.0f; // Height of AddGroup button static int s_ScrollBar = 0; static float s_ScrollValue = 0; @@ -3301,23 +3291,23 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) float ScrollDifference = LayersHeight - LayersBox.h; - if(LayersHeight > LayersBox.h) // Do we even need a scrollbar? + if(LayersHeight > LayersBox.h) // Do we even need a scrollbar? { CUIRect Scroll; LayersBox.VSplitRight(15.0f, &LayersBox, &Scroll); - LayersBox.VSplitRight(3.0f, &LayersBox, 0); // extra spacing + LayersBox.VSplitRight(3.0f, &LayersBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&LayersBox)) { - int ScrollNum = (int)((LayersHeight-LayersBox.h)/15.0f)+1; + int ScrollNum = (int)((LayersHeight - LayersBox.h) / 15.0f) + 1; if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } } } @@ -3346,17 +3336,17 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) { LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); Slot.VSplitLeft(12, &VisibleToggle, &Slot); - if(DoButton_Ex(&m_Map.m_lGroups[g]->m_Visible, m_Map.m_lGroups[g]->m_Visible?"V":"H", m_Map.m_lGroups[g]->m_Collapse ? 1 : 0, &VisibleToggle, 0, "Toggle group visibility", CUI::CORNER_L)) + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_Visible, m_Map.m_lGroups[g]->m_Visible ? "V" : "H", m_Map.m_lGroups[g]->m_Collapse ? 1 : 0, &VisibleToggle, 0, "Toggle group visibility", CUI::CORNER_L)) m_Map.m_lGroups[g]->m_Visible = !m_Map.m_lGroups[g]->m_Visible; - str_format(aBuf, sizeof(aBuf),"#%d %s", g, m_Map.m_lGroups[g]->m_aName); + str_format(aBuf, sizeof(aBuf), "#%d %s", g, m_Map.m_lGroups[g]->m_aName); float FontSize = 10.0f; while(TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f) > Slot.w) FontSize--; - if(int Result = DoButton_Ex(&m_Map.m_lGroups[g], aBuf, g==m_SelectedGroup, &Slot, - BUTTON_CONTEXT, m_Map.m_lGroups[g]->m_Collapse ? "Select group. Shift click to select all layers. Double click to expand." : "Select group. Shift click to select all layers. Double click to collapse.", CUI::CORNER_R, FontSize)) + if(int Result = DoButton_Ex(&m_Map.m_lGroups[g], aBuf, g == m_SelectedGroup, &Slot, + BUTTON_CONTEXT, m_Map.m_lGroups[g]->m_Collapse ? "Select group. Shift click to select all layers. Double click to expand." : "Select group. Shift click to select all layers. Double click to collapse.", CUI::CORNER_R, FontSize)) { - if (g != m_SelectedGroup) + if(g != m_SelectedGroup) SelectLayer(0, g); if((Input()->KeyIsPressed(KEY_LSHIFT) || Input()->KeyIsPressed(KEY_RSHIFT)) && m_SelectedGroup == g) @@ -3396,7 +3386,7 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) Slot.VSplitLeft(12.0f, 0, &Button); Button.VSplitLeft(15, &VisibleToggle, &Button); - if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible, m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible?"V":"H", 0, &VisibleToggle, 0, "Toggle layer visibility", CUI::CORNER_L)) + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible, m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible ? "V" : "H", 0, &VisibleToggle, 0, "Toggle layer visibility", CUI::CORNER_L)) m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible = !m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible; if(m_Map.m_lGroups[g]->m_lLayers[i]->m_aName[0]) @@ -3426,11 +3416,11 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) while(TextRender()->TextWidth(0, FontSize, aBuf, -1, -1.0f) > Button.w) FontSize--; int Checked = 0; - if (g == m_SelectedGroup) + if(g == m_SelectedGroup) { for(int j = 0; j < m_lSelectedLayers.size(); j++) { - if (m_lSelectedLayers[j] == i) + if(m_lSelectedLayers[j] == i) { Checked = 1; break; @@ -3448,7 +3438,7 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) Checked += 6; } if(int Result = DoButton_Ex(m_Map.m_lGroups[g]->m_lLayers[i], aBuf, Checked, &Button, - BUTTON_CONTEXT, "Select layer. Shift click to select multiple.", CUI::CORNER_R, FontSize)) + BUTTON_CONTEXT, "Select layer. Shift click to select multiple.", CUI::CORNER_R, FontSize)) { static CLayerPopupContext s_LayerPopupContext = {}; if(Result == 1) @@ -3467,11 +3457,11 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) { bool IsLayerSelected = false; - if (m_SelectedGroup == g) + if(m_SelectedGroup == g) { - for (int x = 0; x < m_lSelectedLayers.size(); x++) + for(int x = 0; x < m_lSelectedLayers.size(); x++) { - if (m_lSelectedLayers[x] == i) + if(m_lSelectedLayers[x] == i) { IsLayerSelected = true; break; @@ -3586,7 +3576,7 @@ void CEditor::RenderLayers(CUIRect ToolBox, CUIRect View) if(DoButton_Editor(&s_NewGroupButton, "Add group", 0, &Slot, CUI::CORNER_R, "Adds a new group")) { m_Map.NewGroup(); - m_SelectedGroup = m_Map.m_lGroups.size()-1; + m_SelectedGroup = m_Map.m_lGroups.size() - 1; } } } @@ -3729,20 +3719,20 @@ void CEditor::AddSound(const char *pFileName, int StorageType, void *pUser) return; } - void *pData = malloc((unsigned) DataSize); - io_read(SoundFile, pData, (unsigned) DataSize); + void *pData = malloc((unsigned)DataSize); + io_read(SoundFile, pData, (unsigned)DataSize); io_close(SoundFile); // load sound - int SoundId = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned) DataSize, true); + int SoundId = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned)DataSize, true); if(SoundId == -1) return; // add sound CEditorSound *pSound = new CEditorSound(pEditor); pSound->m_SoundID = SoundId; - pSound->m_External = 1; // external by default - pSound->m_DataSize = (unsigned) DataSize; + pSound->m_External = 1; // external by default + pSound->m_DataSize = (unsigned)DataSize; pSound->m_pData = pData; str_copy(pSound->m_aName, aBuf, sizeof(pSound->m_aName)); pEditor->m_Map.m_lSounds.add(pSound); @@ -3782,8 +3772,8 @@ void CEditor::ReplaceSound(const char *pFileName, int StorageType, void *pUser) return; } - void *pData = malloc((unsigned) DataSize); - io_read(SoundFile, pData, (unsigned) DataSize); + void *pData = malloc((unsigned)DataSize); + io_read(SoundFile, pData, (unsigned)DataSize); io_close(SoundFile); CEditorSound *pSound = pEditor->m_Map.m_lSounds[pEditor->m_SelectedSound]; @@ -3800,14 +3790,13 @@ void CEditor::ReplaceSound(const char *pFileName, int StorageType, void *pUser) // replace sound pSound->m_External = External; IStorage::StripPathAndExtension(pFileName, pSound->m_aName, sizeof(pSound->m_aName)); - pSound->m_SoundID = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned) DataSize, true); + pSound->m_SoundID = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned)DataSize, true); pSound->m_pData = pData; pSound->m_DataSize = DataSize; pEditor->m_Dialog = DIALOG_NONE; } - static int gs_ModifyIndexDeletedIndex; static void ModifyIndexDeleted(int *pIndex) { @@ -3895,7 +3884,6 @@ int CEditor::PopupSound(CEditor *pEditor, CUIRect View, void *pContext) } } - View.HSplitTop(5.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_ReplaceButton, "Replace", 0, &Slot, 0, "Replaces the sound with a new one")) @@ -3935,8 +3923,8 @@ void CEditor::SelectGameLayer() static int CompareImageName(const void *pObject1, const void *pObject2) { - CEditorImage *pImage1 = *(CEditorImage**)pObject1; - CEditorImage *pImage2 = *(CEditorImage**)pObject2; + CEditorImage *pImage1 = *(CEditorImage **)pObject1; + CEditorImage *pImage2 = *(CEditorImage **)pObject2; return str_comp(pImage1->m_aName, pImage2->m_aName); } @@ -3952,7 +3940,7 @@ void CEditor::SortImages() { bool Sorted = true; for(int i = 1; i < m_Map.m_lImages.size(); i++) - if( str_comp(m_Map.m_lImages[i]->m_aName, m_Map.m_lImages[i-1]->m_aName) < 0 ) + if(str_comp(m_Map.m_lImages[i]->m_aName, m_Map.m_lImages[i - 1]->m_aName) < 0) { Sorted = false; break; @@ -3960,10 +3948,10 @@ void CEditor::SortImages() if(!Sorted) { - array lTemp = m_Map.m_lImages; + array lTemp = m_Map.m_lImages; gs_pSortedIndex = new int[lTemp.size()]; - qsort(m_Map.m_lImages.base_ptr(), m_Map.m_lImages.size(), sizeof(CEditorImage*), CompareImageName); + qsort(m_Map.m_lImages.base_ptr(), m_Map.m_lImages.size(), sizeof(CEditorImage *), CompareImageName); for(int OldIndex = 0; OldIndex < lTemp.size(); OldIndex++) for(int NewIndex = 0; NewIndex < m_Map.m_lImages.size(); NewIndex++) @@ -3972,12 +3960,11 @@ void CEditor::SortImages() m_Map.ModifyImageIndex(ModifySortedIndex); - delete [] gs_pSortedIndex; + delete[] gs_pSortedIndex; gs_pSortedIndex = 0; } } - void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) { static int s_ScrollBar = 0; @@ -3988,23 +3975,23 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) if(!m_GuiActive) return; - if(ImagesHeight > ToolBox.h) // Do we even need a scrollbar? + if(ImagesHeight > ToolBox.h) // Do we even need a scrollbar? { CUIRect Scroll; ToolBox.VSplitRight(15.0f, &ToolBox, &Scroll); - ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing + ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox)) { - int ScrollNum = (int)((ImagesHeight-ToolBox.h)/14.0f)+1; + int ScrollNum = (int)((ImagesHeight - ToolBox.h) / 14.0f) + 1; if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } } } @@ -4024,7 +4011,6 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) break; else if(ImageCur >= ImageStartAt) { - ToolBox.HSplitTop(15.0f, &Slot, &ToolBox); if(e == 0) UI()->DoLabel(&Slot, "Embedded", 12.0f, 0); @@ -4072,7 +4058,7 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) } Selected += 2; // Image is unused - done: + done: if(Selected < 2 && e == 1) { if(!IsVanillaImage(m_Map.m_lImages[i]->m_aName)) @@ -4086,7 +4072,7 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) FontSize--; if(int Result = DoButton_Ex(&m_Map.m_lImages[i], aBuf, Selected, &Slot, - BUTTON_CONTEXT, "Select image.", 0, FontSize)) + BUTTON_CONTEXT, "Select image.", 0, FontSize)) { m_SelectedImage = i; @@ -4101,7 +4087,7 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) // separator ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); ImageCur += 5.0f; - IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2); + IGraphics::CLineItem LineItem(Slot.x, Slot.y + Slot.h / 2, Slot.x + Slot.w, Slot.y + Slot.h / 2); Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(&LineItem, 1); @@ -4168,8 +4154,8 @@ void CEditor::RenderImages(CUIRect ToolBox, CUIRect View) else r.h = r.w; float Max = (float)(maximum(m_Map.m_lImages[i]->m_Width, m_Map.m_lImages[i]->m_Height)); - r.w *= m_Map.m_lImages[i]->m_Width/Max; - r.h *= m_Map.m_lImages[i]->m_Height/Max; + r.w *= m_Map.m_lImages[i]->m_Width / Max; + r.h *= m_Map.m_lImages[i]->m_Height / Max; Graphics()->TextureSet(m_Map.m_lImages[i]->m_Texture); Graphics()->BlendNormal(); Graphics()->WrapClamp(); @@ -4202,23 +4188,23 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) if(!m_GuiActive) return; - if(SoundsHeight > ToolBox.h) // Do we even need a scrollbar? + if(SoundsHeight > ToolBox.h) // Do we even need a scrollbar? { CUIRect Scroll; ToolBox.VSplitRight(15.0f, &ToolBox, &Scroll); - ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing + ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox)) { - int ScrollNum = (int)((SoundsHeight-ToolBox.h)/14.0f)+1; + int ScrollNum = (int)((SoundsHeight - ToolBox.h) / 14.0f) + 1; if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } } } @@ -4238,7 +4224,6 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) break; else if(SoundCur >= SoundStartAt) { - ToolBox.HSplitTop(15.0f, &Slot, &ToolBox); if(e == 0) UI()->DoLabel(&Slot, "Embedded", 12.0f, 0); @@ -4268,7 +4253,6 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) str_copy(aBuf, m_Map.m_lSounds[i]->m_aName, sizeof(aBuf)); ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); - int Selected = m_SelectedSound == i; for(int x = 0; x < m_Map.m_lGroups.size(); ++x) for(int j = 0; j < m_Map.m_lGroups[x]->m_lLayers.size(); ++j) @@ -4280,7 +4264,7 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) } Selected += 2; // Sound is unused - done: + done: if(Selected < 2 && e == 1) Selected += 4; // Sound should be embedded @@ -4289,7 +4273,7 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) FontSize--; if(int Result = DoButton_Ex(&m_Map.m_lSounds[i], aBuf, Selected, &Slot, - BUTTON_CONTEXT, "Select sound.", 0, FontSize)) + BUTTON_CONTEXT, "Select sound.", 0, FontSize)) { m_SelectedSound = i; @@ -4304,7 +4288,7 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) // separator ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); SoundCur += 5.0f; - IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2); + IGraphics::CLineItem LineItem(Slot.x, Slot.y + Slot.h / 2, Slot.x + Slot.w, Slot.y + Slot.h / 2); Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(&LineItem, 1); @@ -4370,16 +4354,15 @@ void CEditor::RenderSounds(CUIRect ToolBox, CUIRect View) InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_SOUND, "Add Sound", "Add", "mapres", "", AddSound, this); } - static int EditorListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) { - CEditor *pEditor = (CEditor*)pUser; + CEditor *pEditor = (CEditor *)pUser; int Length = str_length(pName); if((pName[0] == '.' && (pName[1] == 0 || - (pName[1] == '.' && pName[2] == 0 && (!str_comp(pEditor->m_pFileDialogPath, "maps") || !str_comp(pEditor->m_pFileDialogPath, "mapres"))))) || + (pName[1] == '.' && pName[2] == 0 && (!str_comp(pEditor->m_pFileDialogPath, "maps") || !str_comp(pEditor->m_pFileDialogPath, "mapres"))))) || (!IsDir && ((pEditor->m_FileDialogFileType == CEditor::FILETYPE_MAP && !str_endswith(pName, ".map")) || - (pEditor->m_FileDialogFileType == CEditor::FILETYPE_IMG && !str_endswith(pName, ".png")) || - (pEditor->m_FileDialogFileType == CEditor::FILETYPE_SOUND && !str_endswith(pName, ".opus"))))) + (pEditor->m_FileDialogFileType == CEditor::FILETYPE_IMG && !str_endswith(pName, ".png")) || + (pEditor->m_FileDialogFileType == CEditor::FILETYPE_SOUND && !str_endswith(pName, ".opus"))))) return 0; CEditor::CFilelistItem Item; @@ -4389,9 +4372,9 @@ static int EditorListdirCallback(const char *pName, int IsDir, int StorageType, else { if(pEditor->m_FileDialogFileType == CEditor::FILETYPE_SOUND) - str_copy(Item.m_aName, pName, minimum(static_cast(sizeof(Item.m_aName)), Length-4)); + str_copy(Item.m_aName, pName, minimum(static_cast(sizeof(Item.m_aName)), Length - 4)); else - str_copy(Item.m_aName, pName, minimum(static_cast(sizeof(Item.m_aName)), Length-3)); + str_copy(Item.m_aName, pName, minimum(static_cast(sizeof(Item.m_aName)), Length - 3)); } Item.m_IsDir = IsDir != 0; Item.m_IsLink = false; @@ -4404,7 +4387,7 @@ static int EditorListdirCallback(const char *pName, int IsDir, int StorageType, void CEditor::AddFileDialogEntry(int Index, CUIRect *pView) { m_FilesCur++; - if(m_FilesCur-1 < m_FilesStartAt || m_FilesCur >= m_FilesStopAt) + if(m_FilesCur - 1 < m_FilesStartAt || m_FilesCur >= m_FilesStopAt) return; CUIRect Button, FileIcon; @@ -4415,7 +4398,7 @@ void CEditor::AddFileDialogEntry(int Index, CUIRect *pView) Graphics()->TextureSet(g_pData->m_aImages[IMAGE_FILEICONS].m_Id); Graphics()->QuadsBegin(); - RenderTools()->SelectSprite(m_FileList[Index].m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_MAP2); + RenderTools()->SelectSprite(m_FileList[Index].m_IsDir ? SPRITE_FILE_FOLDER : SPRITE_FILE_MAP2); IGraphics::CQuadItem QuadItem(FileIcon.x, FileIcon.y, FileIcon.w, FileIcon.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); @@ -4442,10 +4425,10 @@ void CEditor::RenderFileDialog() CUIRect Preview; float Width = View.w, Height = View.h; - RenderTools()->DrawUIRect(&View, ColorRGBA(0,0,0,0.25f), 0, 0); + RenderTools()->DrawUIRect(&View, ColorRGBA(0, 0, 0, 0.25f), 0, 0); View.VMargin(150.0f, &View); View.HMargin(50.0f, &View); - RenderTools()->DrawUIRect(&View, ColorRGBA(0,0,0,0.75f), CUI::CORNER_ALL, 5.0f); + RenderTools()->DrawUIRect(&View, ColorRGBA(0, 0, 0, 0.75f), CUI::CORNER_ALL, 5.0f); View.Margin(10.0f, &View); CUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll, PathBox; @@ -4486,7 +4469,7 @@ void CEditor::RenderFileDialog() // remove '/' and '\' for(int i = 0; m_aFileDialogFileName[i]; ++i) if(m_aFileDialogFileName[i] == '/' || m_aFileDialogFileName[i] == '\\') - str_copy(&m_aFileDialogFileName[i], &m_aFileDialogFileName[i+1], (int)(sizeof(m_aFileDialogFileName))-i); + str_copy(&m_aFileDialogFileName[i], &m_aFileDialogFileName[i + 1], (int)(sizeof(m_aFileDialogFileName)) - i); m_FilesSelectedIndex = -1; } } @@ -4500,14 +4483,14 @@ void CEditor::RenderFileDialog() static float s_SearchBoxID = 0; UI()->DoLabel(&FileBoxLabel, "Search:", 10.0f, -1, -1); str_copy(m_aFileDialogPrevSearchText, m_aFileDialogSearchText, sizeof(m_aFileDialogPrevSearchText)); - DoEditBox(&s_SearchBoxID, &FileBox, m_aFileDialogSearchText, sizeof(m_aFileDialogSearchText), 10.0f, &s_SearchBoxID,false,CUI::CORNER_L); + DoEditBox(&s_SearchBoxID, &FileBox, m_aFileDialogSearchText, sizeof(m_aFileDialogSearchText), 10.0f, &s_SearchBoxID, false, CUI::CORNER_L); if(m_FileDialogOpening) UI()->SetActiveItem(&s_SearchBoxID); // clearSearchbox button { static int s_ClearButton = 0; - RenderTools()->DrawUIRect(&ClearBox, ColorRGBA(1, 1, 1, 0.33f*ButtonColorMul(&s_ClearButton)), CUI::CORNER_R, 3.0f); + RenderTools()->DrawUIRect(&ClearBox, ColorRGBA(1, 1, 1, 0.33f * ButtonColorMul(&s_ClearButton)), CUI::CORNER_R, 3.0f); UI()->DoLabel(&ClearBox, "×", 10.0f, 0); if(UI()->DoButtonLogic(&s_ClearButton, "×", 0, &ClearBox)) { @@ -4522,7 +4505,7 @@ void CEditor::RenderFileDialog() m_FileDialogOpening = false; - int Num = (int)(View.h/17.0f)+1; + int Num = (int)(View.h / 17.0f) + 1; static int ScrollBar = 0; Scroll.HMargin(5.0f, &Scroll); m_FileDialogScrollValue = UiDoScrollbarV(&ScrollBar, &Scroll, m_FileDialogScrollValue); @@ -4543,9 +4526,9 @@ void CEditor::RenderFileDialog() if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - m_FileDialogScrollValue -= 3.0f/ScrollNum; + m_FileDialogScrollValue -= 3.0f / ScrollNum; if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - m_FileDialogScrollValue += 3.0f/ScrollNum; + m_FileDialogScrollValue += 3.0f / ScrollNum; } else ScrollNum = 0; @@ -4560,7 +4543,7 @@ void CEditor::RenderFileDialog() for(int i = 0; i < Input()->NumEvents(); i++) { int NewIndex = -1; - if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) + if(Input()->GetEvent(i).m_Flags & IInput::FLAG_PRESS) { if(Input()->GetEvent(i).m_Key == KEY_DOWN) { @@ -4582,14 +4565,14 @@ void CEditor::RenderFileDialog() if(NewIndex > -1 && NewIndex < m_FileList.size()) { //scroll - float IndexY = View.y - m_FileDialogScrollValue*ScrollNum*17.0f + NewIndex*17.0f; - int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+17.0f ? 1 : 0; + float IndexY = View.y - m_FileDialogScrollValue * ScrollNum * 17.0f + NewIndex * 17.0f; + int Scroll = View.y > IndexY ? -1 : View.y + View.h < IndexY + 17.0f ? 1 : 0; if(Scroll) { if(Scroll < 0) - m_FileDialogScrollValue = ((float)(NewIndex)+0.5f)/ScrollNum; + m_FileDialogScrollValue = ((float)(NewIndex) + 0.5f) / ScrollNum; else - m_FileDialogScrollValue = ((float)(NewIndex-Num)+2.5f)/ScrollNum; + m_FileDialogScrollValue = ((float)(NewIndex - Num) + 2.5f) / ScrollNum; } if(!m_FileList[NewIndex].m_IsDir) @@ -4642,21 +4625,23 @@ void CEditor::RenderFileDialog() for(int i = 0; i < Input()->NumEvents(); i++) { - if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) + if(Input()->GetEvent(i).m_Flags & IInput::FLAG_PRESS) { if(Input()->GetEvent(i).m_Key == KEY_RETURN || Input()->GetEvent(i).m_Key == KEY_KP_ENTER) m_FileDialogActivate = true; } } - if(m_FileDialogScrollValue < 0) m_FileDialogScrollValue = 0; - if(m_FileDialogScrollValue > 1) m_FileDialogScrollValue = 1; + if(m_FileDialogScrollValue < 0) + m_FileDialogScrollValue = 0; + if(m_FileDialogScrollValue > 1) + m_FileDialogScrollValue = 1; - m_FilesStartAt = (int)(ScrollNum*m_FileDialogScrollValue); + m_FilesStartAt = (int)(ScrollNum * m_FileDialogScrollValue); if(m_FilesStartAt < 0) m_FilesStartAt = 0; - m_FilesStopAt = m_FilesStartAt+Num; + m_FilesStopAt = m_FilesStartAt + Num; m_FilesCur = 0; @@ -4678,18 +4663,18 @@ void CEditor::RenderFileDialog() if(DoButton_Editor(&s_OkButton, IsDir ? "Open" : m_pFileDialogButtonText, 0, &Button, 0, 0) || m_FileDialogActivate) { m_FileDialogActivate = false; - if(IsDir) // folder + if(IsDir) // folder { - if(str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename, "..") == 0) // parent folder + if(str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename, "..") == 0) // parent folder { if(fs_parent_dir(m_pFileDialogPath)) - m_pFileDialogPath = m_aFileDialogCurrentFolder; // leave the link + m_pFileDialogPath = m_aFileDialogCurrentFolder; // leave the link } - else // sub folder + else // sub folder { if(m_FileList[m_FilesSelectedIndex].m_IsLink) { - m_pFileDialogPath = m_aFileDialogCurrentLink; // follow the link + m_pFileDialogPath = m_aFileDialogCurrentLink; // follow the link str_copy(m_aFileDialogCurrentLink, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogCurrentLink)); } else @@ -4700,7 +4685,7 @@ void CEditor::RenderFileDialog() } } FilelistPopulate(!str_comp(m_pFileDialogPath, "maps") || !str_comp(m_pFileDialogPath, "mapres") ? m_FileDialogStorageType : - m_FileList[m_FilesSelectedIndex].m_StorageType); + m_FileList[m_FilesSelectedIndex].m_StorageType); if(m_FilesSelectedIndex >= 0 && !m_FileList[m_FilesSelectedIndex].m_IsDir) str_copy(m_aFileDialogFileName, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogFileName)); else @@ -4718,13 +4703,11 @@ void CEditor::RenderFileDialog() m_PopupEventType = POPEVENT_SAVE; m_PopupEventActivated = true; } - else - if(m_pfnFileDialogFunc) - m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); - } - else - if(m_pfnFileDialogFunc) + else if(m_pfnFileDialogFunc) m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); + } + else if(m_pfnFileDialogFunc) + m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); } } @@ -4741,7 +4724,7 @@ void CEditor::RenderFileDialog() m_FileDialogNewFolderName[0] = 0; m_FileDialogErrString[0] = 0; static int s_NewFolderPopupID = 0; - UiInvokePopupMenu(&s_NewFolderPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupNewFolder); + UiInvokePopupMenu(&s_NewFolderPopupID, 0, Width / 2.0f - 200.0f, Height / 2.0f - 100.0f, 400.0f, 200.0f, PopupNewFolder); UI()->SetActiveItem(0); } } @@ -4757,7 +4740,7 @@ void CEditor::RenderFileDialog() str_copy(m_Map.m_MapInfo.m_aCreditsTmp, m_Map.m_MapInfo.m_aCredits, sizeof(m_Map.m_MapInfo.m_aCreditsTmp)); str_copy(m_Map.m_MapInfo.m_aLicenseTmp, m_Map.m_MapInfo.m_aLicense, sizeof(m_Map.m_MapInfo.m_aLicenseTmp)); static int s_MapInfoPopupID = 0; - UiInvokePopupMenu(&s_MapInfoPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupMapInfo); + UiInvokePopupMenu(&s_MapInfoPopupID, 0, Width / 2.0f - 200.0f, Height / 2.0f - 100.0f, 400.0f, 200.0f, PopupMapInfo); UI()->SetActiveItem(0); } } @@ -4817,8 +4800,6 @@ void CEditor::InvokeFileDialog(int StorageType, int FileType, const char *pTitle m_Dialog = DIALOG_FILE; } - - void CEditor::RenderModebar(CUIRect View) { CUIRect Button; @@ -4868,9 +4849,9 @@ void CEditor::RenderStatusbar(CUIRect View) static int s_EnvelopeButton = 0; int MouseButton = DoButton_Editor(&s_EnvelopeButton, "Envelopes", m_ShowEnvelopeEditor, &Button, 0, "Toggles the envelope editor."); if(MouseButton == 2) - m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+3)%4; + m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor + 3) % 4; else if(MouseButton == 1) - m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+1)%4; + m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor + 1) % 4; if(MouseButton) { @@ -4940,7 +4921,7 @@ void CEditor::RenderUndoList(CUIRect View) int ScrollNum = m_lUndoSteps.size() - List.h / 17.0f; if(ScrollNum < 0) ScrollNum = 0; - List.y -= m_UndoScrollValue*ScrollNum*17.0f; + List.y -= m_UndoScrollValue * ScrollNum * 17.0f; for(int i = 0; i < m_lUndoSteps.size(); i++) { List.HSplitTop(17.0f, &Button, &List); @@ -4994,8 +4975,7 @@ bool CEditor::IsEnvelopeUsed(int EnvelopeIndex) CLayerQuads *pQuadLayer = (CLayerQuads *)m_Map.m_lGroups[i]->m_lLayers[j]; for(int k = 0; k < pQuadLayer->m_lQuads.size(); k++) { - if(pQuadLayer->m_lQuads[k].m_PosEnv == EnvelopeIndex - || pQuadLayer->m_lQuads[k].m_ColorEnv == EnvelopeIndex) + if(pQuadLayer->m_lQuads[k].m_PosEnv == EnvelopeIndex || pQuadLayer->m_lQuads[k].m_ColorEnv == EnvelopeIndex) { return true; } @@ -5006,8 +4986,7 @@ bool CEditor::IsEnvelopeUsed(int EnvelopeIndex) CLayerSounds *pSoundLayer = (CLayerSounds *)m_Map.m_lGroups[i]->m_lLayers[j]; for(int k = 0; k < pSoundLayer->m_lSources.size(); k++) { - if(pSoundLayer->m_lSources[k].m_PosEnv == EnvelopeIndex - || pSoundLayer->m_lSources[k].m_SoundEnv == EnvelopeIndex) + if(pSoundLayer->m_lSources[k].m_PosEnv == EnvelopeIndex || pSoundLayer->m_lSources[k].m_SoundEnv == EnvelopeIndex) { return true; } @@ -5026,8 +5005,10 @@ bool CEditor::IsEnvelopeUsed(int EnvelopeIndex) void CEditor::RenderEnvelopeEditor(CUIRect View) { - if(m_SelectedEnvelope < 0) m_SelectedEnvelope = 0; - if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; + if(m_SelectedEnvelope < 0) + m_SelectedEnvelope = 0; + if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) + m_SelectedEnvelope = m_Map.m_lEnvelopes.size() - 1; CEnvelope *pEnvelope = 0; if(m_SelectedEnvelope >= 0 && m_SelectedEnvelope < m_Map.m_lEnvelopes.size()) @@ -5046,7 +5027,6 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) CUIRect Button; CEnvelope *pNewEnv = 0; - ToolBar.VSplitRight(50.0f, &ToolBar, &Button); static int s_NewSoundButton = 0; if(DoButton_Editor(&s_NewSoundButton, "Sound+", 0, &Button, 0, "Creates a new sound envelope")) @@ -5088,7 +5068,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) m_Map.m_UndoModified++; m_Map.DeleteEnvelope(m_SelectedEnvelope); if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) - m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; + m_SelectedEnvelope = m_Map.m_lEnvelopes.size() - 1; pEnvelope = m_SelectedEnvelope >= 0 ? m_Map.m_lEnvelopes[m_SelectedEnvelope] : 0; } } @@ -5112,14 +5092,14 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) Shifter.VSplitRight(15.0f, &Shifter, &Inc); Shifter.VSplitLeft(15.0f, &Dec, &Shifter); char aBuf[512]; - str_format(aBuf, sizeof(aBuf),"%d/%d", m_SelectedEnvelope+1, m_Map.m_lEnvelopes.size()); + str_format(aBuf, sizeof(aBuf), "%d/%d", m_SelectedEnvelope + 1, m_Map.m_lEnvelopes.size()); ColorRGBA EnvColor = ColorRGBA(1, 1, 1, 0.5f); if(m_Map.m_lEnvelopes.size()) { EnvColor = IsEnvelopeUsed(m_SelectedEnvelope) ? - ColorRGBA(1, 0.7f, 0.7f, 0.5f) : - ColorRGBA(0.7f, 1, 0.7f, 0.5f); + ColorRGBA(1, 0.7f, 0.7f, 0.5f) : + ColorRGBA(0.7f, 1, 0.7f, 0.5f); } RenderTools()->DrawUIRect(&Shifter, EnvColor, 0, 0.0f); @@ -5177,7 +5157,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) static int sEnvelopeEditorID = 0; static int s_ActiveChannels = 0xf; - ColorRGBA aColors[] = {ColorRGBA(1,0.2f,0.2f), ColorRGBA(0.2f,1,0.2f), ColorRGBA(0.2f,0.2f,1), ColorRGBA(1,1,0.2f)}; + ColorRGBA aColors[] = {ColorRGBA(1, 0.2f, 0.2f), ColorRGBA(0.2f, 1, 0.2f), ColorRGBA(0.2f, 0.2f, 1), ColorRGBA(1, 1, 0.2f)}; if(pEnvelope) { @@ -5203,14 +5183,14 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) int Bit = 1; //ui_draw_button_func draw_func; - for(int i = 0; i < pEnvelope->m_Channels; i++, Bit<<=1) + for(int i = 0; i < pEnvelope->m_Channels; i++, Bit <<= 1) { ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); /*if(i == 0) draw_func = draw_editor_button_l; else if(i == envelope->channels-1) draw_func = draw_editor_button_r; else draw_func = draw_editor_button_m;*/ - if(DoButton_Env(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels-1][i], s_ActiveChannels&Bit, &Button, paDescriptions[pEnvelope->m_Channels-1][i], aColors[i])) + if(DoButton_Env(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels - 1][i], s_ActiveChannels & Bit, &Button, paDescriptions[pEnvelope->m_Channels - 1][i], aColors[i])) s_ActiveChannels ^= Bit; } @@ -5218,7 +5198,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); ToolBar.VSplitLeft(12.0f, &Button, &ToolBar); static int s_SyncButton; - if(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized?"X":"", 0, &Button, 0, "Synchronize envelope animation to game time (restarts when you touch the start line)")) + if(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized ? "X" : "", 0, &Button, 0, "Synchronize envelope animation to game time (restarts when you touch the start line)")) pEnvelope->m_Synchronized = !pEnvelope->m_Synchronized; ToolBar.VSplitLeft(4.0f, &Button, &ToolBar); @@ -5239,8 +5219,8 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) if(Bottom >= 0) Bottom = 0; - float TimeScale = EndTime/View.w; - float ValueScale = (Top-Bottom)/View.h; + float TimeScale = EndTime / View.w; + float ValueScale = (Top - Bottom) / View.h; if(UI()->MouseInside(&View)) UI()->SetHotItem(&sEnvelopeEditorID); @@ -5253,7 +5233,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) if(UI()->MouseButtonClicked(1)) { // add point - int Time = (int)(((UI()->MouseX()-View.x)*TimeScale)*1000.0f); + int Time = (int)(((UI()->MouseX() - View.x) * TimeScale) * 1000.0f); //float env_y = (UI()->MouseY()-view.y)/TimeScale; float aChannels[4]; pEnvelope->Eval(Time / 1000.0f, aChannels); @@ -5276,25 +5256,25 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) Graphics()->LinesBegin(); for(int c = 0; c < pEnvelope->m_Channels; c++) { - if(s_ActiveChannels&(1<SetColor(aColors[c].r,aColors[c].g,aColors[c].b,1); + if(s_ActiveChannels & (1 << c)) + Graphics()->SetColor(aColors[c].r, aColors[c].g, aColors[c].b, 1); else - Graphics()->SetColor(aColors[c].r*0.5f,aColors[c].g*0.5f,aColors[c].b*0.5f,1); + Graphics()->SetColor(aColors[c].r * 0.5f, aColors[c].g * 0.5f, aColors[c].b * 0.5f, 1); float PrevX = 0; float aResults[4]; pEnvelope->Eval(0.000001f, aResults); float PrevValue = aResults[c]; - int Steps = (int)((View.w/UI()->Screen()->w) * Graphics()->ScreenWidth()); + int Steps = (int)((View.w / UI()->Screen()->w) * Graphics()->ScreenWidth()); for(int i = 1; i <= Steps; i++) { - float a = i/(float)Steps; - pEnvelope->Eval(a*EndTime, aResults); + float a = i / (float)Steps; + pEnvelope->Eval(a * EndTime, aResults); float v = aResults[c]; - v = (v-Bottom)/(Top-Bottom); + v = (v - Bottom) / (Top - Bottom); - IGraphics::CLineItem LineItem(View.x + PrevX*View.w, View.y+View.h - PrevValue*View.h, View.x + a*View.w, View.y+View.h - v*View.h); + IGraphics::CLineItem LineItem(View.x + PrevX * View.w, View.y + View.h - PrevValue * View.h, View.x + a * View.w, View.y + View.h - v * View.h); Graphics()->LinesDraw(&LineItem, 1); PrevX = a; PrevValue = v; @@ -5306,29 +5286,27 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) // render curve options { - for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) + for(int i = 0; i < pEnvelope->m_lPoints.size() - 1; i++) { - float t0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; - float t1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; + float t0 = pEnvelope->m_lPoints[i].m_Time / 1000.0f / EndTime; + float t1 = pEnvelope->m_lPoints[i + 1].m_Time / 1000.0f / EndTime; //dbg_msg("", "%f", end_time); CUIRect v; - v.x = CurveBar.x + (t0+(t1-t0)*0.5f) * CurveBar.w; + v.x = CurveBar.x + (t0 + (t1 - t0) * 0.5f) * CurveBar.w; v.y = CurveBar.y; v.h = CurveBar.h; v.w = CurveBar.h; - v.x -= v.w/2; + v.x -= v.w / 2; void *pID = &pEnvelope->m_lPoints[i].m_Curvetype; const char *paTypeName[] = { - "N", "L", "S", "F", "M" - }; + "N", "L", "S", "F", "M"}; const char *pTypeName = "Invalid"; - if(0 <= pEnvelope->m_lPoints[i].m_Curvetype - && pEnvelope->m_lPoints[i].m_Curvetype < (int)(sizeof(paTypeName)/sizeof(const char *))) + if(0 <= pEnvelope->m_lPoints[i].m_Curvetype && pEnvelope->m_lPoints[i].m_Curvetype < (int)(sizeof(paTypeName) / sizeof(const char *))) pTypeName = paTypeName[pEnvelope->m_lPoints[i].m_Curvetype]; if(DoButton_Editor(pID, pTypeName, 0, &v, 0, "Switch curve type")) - pEnvelope->m_lPoints[i].m_Curvetype = (pEnvelope->m_lPoints[i].m_Curvetype+1)%NUM_CURVETYPES; + pEnvelope->m_lPoints[i].m_Curvetype = (pEnvelope->m_lPoints[i].m_Curvetype + 1) % NUM_CURVETYPES; } } @@ -5337,31 +5315,31 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); - for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) + for(int i = 0; i < pEnvelope->m_lPoints.size() - 1; i++) { float r0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[0]); float g0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]); float b0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[2]); float a0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[3]); - float r1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[0]); - float g1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[1]); - float b1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[2]); - float a1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[3]); + float r1 = fx2f(pEnvelope->m_lPoints[i + 1].m_aValues[0]); + float g1 = fx2f(pEnvelope->m_lPoints[i + 1].m_aValues[1]); + float b1 = fx2f(pEnvelope->m_lPoints[i + 1].m_aValues[2]); + float a1 = fx2f(pEnvelope->m_lPoints[i + 1].m_aValues[3]); IGraphics::CColorVertex Array[4] = {IGraphics::CColorVertex(0, r0, g0, b0, a0), - IGraphics::CColorVertex(1, r1, g1, b1, a1), - IGraphics::CColorVertex(2, r1, g1, b1, a1), - IGraphics::CColorVertex(3, r0, g0, b0, a0)}; + IGraphics::CColorVertex(1, r1, g1, b1, a1), + IGraphics::CColorVertex(2, r1, g1, b1, a1), + IGraphics::CColorVertex(3, r0, g0, b0, a0)}; Graphics()->SetColorVertex(Array, 4); - float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; -// float y0 = (fx2f(envelope->points[i].values[c])-bottom)/(top-bottom); - float x1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; + float x0 = pEnvelope->m_lPoints[i].m_Time / 1000.0f / EndTime; + // float y0 = (fx2f(envelope->points[i].values[c])-bottom)/(top-bottom); + float x1 = pEnvelope->m_lPoints[i + 1].m_Time / 1000.0f / EndTime; //float y1 = (fx2f(envelope->points[i+1].values[c])-bottom)/(top-bottom); CUIRect v; - v.x = ColorBar.x + x0*ColorBar.w; + v.x = ColorBar.x + x0 * ColorBar.w; v.y = ColorBar.y; - v.w = (x1-x0)*ColorBar.w; + v.w = (x1 - x0) * ColorBar.w; v.h = ColorBar.h; IGraphics::CQuadItem QuadItem(v.x, v.y, v.w, v.h); @@ -5373,7 +5351,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) // render handles // keep track of last Env - static void* s_pID = 0; + static void *s_pID = 0; // chars for textinput static char s_aStrCurTime[32] = "0.000"; @@ -5395,16 +5373,16 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) Graphics()->QuadsBegin(); for(int c = 0; c < pEnvelope->m_Channels; c++) { - if(!(s_ActiveChannels&(1<m_lPoints.size(); i++) { - float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; - float y0 = (fx2f(pEnvelope->m_lPoints[i].m_aValues[c])-Bottom)/(Top-Bottom); + float x0 = pEnvelope->m_lPoints[i].m_Time / 1000.0f / EndTime; + float y0 = (fx2f(pEnvelope->m_lPoints[i].m_aValues[c]) - Bottom) / (Top - Bottom); CUIRect Final; - Final.x = View.x + x0*View.w; - Final.y = View.y+View.h - y0*View.h; + Final.x = View.x + x0 * View.w; + Final.y = View.y + View.h - y0 * View.h; Final.x -= 2.0f; Final.y -= 2.0f; Final.w = 4.0f; @@ -5435,19 +5413,19 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) if((Input()->KeyIsPressed(KEY_LCTRL) || Input()->KeyIsPressed(KEY_RCTRL))) pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX)); else - pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX*TimeScale)*1000.0f); - if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time) - pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1; - if(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time) - pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1; + pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX * TimeScale) * 1000.0f); + if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i - 1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i - 1].m_Time + 1; + if(i + 1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i + 1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i + 1].m_Time - 1; } } else { if((Input()->KeyIsPressed(KEY_LCTRL) || Input()->KeyIsPressed(KEY_RCTRL))) - pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*0.001f); + pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY * 0.001f); else - pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*ValueScale); + pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY * ValueScale); } if(m_SelectedEnvelopePoint != i) @@ -5460,7 +5438,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) } ColorMod = 100.0f; - Graphics()->SetColor(1,1,1,1); + Graphics()->SetColor(1, 1, 1, 1); } else if(UI()->HotItem() == pID) { @@ -5492,7 +5470,7 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) m_ShowEnvelopePreview = 1; ColorMod = 100.0f; - Graphics()->SetColor(1,0.75f,0.75f,1); + Graphics()->SetColor(1, 0.75f, 0.75f, 1); m_pTooltip = "Left mouse to drag. Hold ctrl to be more precise. Hold shift to alter time point as well. Right click to delete."; } @@ -5502,33 +5480,33 @@ void CEditor::RenderEnvelopeEditor(CUIRect View) { pEnvelope->m_lPoints[i].m_Time = str_tofloat(s_aStrCurTime) * 1000.0f; - if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time) - pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1; - if(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time) - pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1; + if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i - 1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i - 1].m_Time + 1; + if(i + 1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i + 1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i + 1].m_Time - 1; } else pEnvelope->m_lPoints[i].m_Time = 0.0f; - str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", pEnvelope->m_lPoints[i].m_Time/1000.0f); + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", pEnvelope->m_lPoints[i].m_Time / 1000.0f); pEnvelope->m_lPoints[i].m_aValues[c] = f2fx(str_tofloat(s_aStrCurValue)); } - if(UI()->ActiveItem() == pID/* || UI()->HotItem() == pID*/) + if(UI()->ActiveItem() == pID /* || UI()->HotItem() == pID*/) { CurrentTime = pEnvelope->m_lPoints[i].m_Time; CurrentValue = pEnvelope->m_lPoints[i].m_aValues[c]; // update displayed text - str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", CurrentTime/1000.0f); + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", CurrentTime / 1000.0f); str_format(s_aStrCurValue, sizeof(s_aStrCurValue), "%.3f", fx2f(CurrentValue)); } if(m_SelectedQuadEnvelope == m_SelectedEnvelope && m_SelectedEnvelopePoint == i) Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); else - Graphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f); + Graphics()->SetColor(aColors[c].r * ColorMod, aColors[c].g * ColorMod, aColors[c].b * ColorMod, 1.0f); IGraphics::CQuadItem QuadItem(Final.x, Final.y, Final.w, Final.h); Graphics()->QuadsDrawTL(&QuadItem, 1); } @@ -5586,8 +5564,7 @@ void CEditor::RenderServerSettingsEditor(CUIRect View) // buttons ToolBar.VSplitRight(50.0f, &ToolBar, &Button); static int s_AddButton = 0; - if(DoButton_Editor(&s_AddButton, "Add", 0, &Button, 0, "Add a command to command list.") - || ((Input()->KeyPress(KEY_RETURN) || Input()->KeyPress(KEY_KP_ENTER)) && UI()->LastActiveItem() == &m_CommandBox)) + if(DoButton_Editor(&s_AddButton, "Add", 0, &Button, 0, "Add a command to command list.") || ((Input()->KeyPress(KEY_RETURN) || Input()->KeyPress(KEY_KP_ENTER)) && UI()->LastActiveItem() == &m_CommandBox)) { if(m_aSettingsCommand[0] != 0 && str_find(m_aSettingsCommand, " ")) { @@ -5613,8 +5590,7 @@ void CEditor::RenderServerSettingsEditor(CUIRect View) ToolBar.VSplitRight(50.0f, &ToolBar, &Button); Button.VSplitRight(5.0f, &Button, 0); static int s_DelButton = 0; - if(DoButton_Editor(&s_DelButton, "Del", 0, &Button, 0, "Delete a command from the command list.") - || (Input()->KeyPress(KEY_DELETE) && UI()->LastActiveItem() != &m_CommandBox)) + if(DoButton_Editor(&s_DelButton, "Del", 0, &Button, 0, "Delete a command from the command list.") || (Input()->KeyPress(KEY_DELETE) && UI()->LastActiveItem() != &m_CommandBox)) if(s_CommandSelectedIndex > -1 && s_CommandSelectedIndex < m_Map.m_lSettings.size()) m_Map.m_lSettings.remove_index(s_CommandSelectedIndex); } @@ -5632,23 +5608,23 @@ void CEditor::RenderServerSettingsEditor(CUIRect View) float ScrollDifference = ListHeight - ListBox.h; - if(ListHeight > ListBox.h) // Do we even need a scrollbar? + if(ListHeight > ListBox.h) // Do we even need a scrollbar? { CUIRect Scroll; ListBox.VSplitRight(15.0f, &ListBox, &Scroll); - ListBox.VSplitRight(3.0f, &ListBox, 0); // extra spacing + ListBox.VSplitRight(3.0f, &ListBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ListBox)) { - int ScrollNum = (int)((ListHeight-ListBox.h)/17.0f)+1; + int ScrollNum = (int)((ListHeight - ListBox.h) / 17.0f) + 1; if(ScrollNum > 0) { if(Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } else ScrollNum = 0; @@ -5804,7 +5780,7 @@ void CEditor::RenderMenubar(CUIRect MenuBar) MenuBar.VSplitLeft(60.0f, &s_File, &MenuBar); if(DoButton_Menu(&s_File, "File", 0, &s_File, 0, 0)) - UiInvokePopupMenu(&s_File, 1, s_File.x, s_File.y+s_File.h-1.0f, 120, 160, PopupMenuFile, this); + UiInvokePopupMenu(&s_File, 1, s_File.x, s_File.y + s_File.h - 1.0f, 120, 160, PopupMenuFile, this); /* menubar.VSplitLeft(5.0f, 0, &menubar); @@ -5822,7 +5798,7 @@ void CEditor::RenderMenubar(CUIRect MenuBar) MenuBar.VSplitLeft(40.0f, 0, &MenuBar); MenuBar.VSplitRight(20.0f, &MenuBar, &Close); Close.VSplitLeft(5.0f, 0, &Close); - MenuBar.VSplitLeft(MenuBar.w*0.75f, &MenuBar, &Info); + MenuBar.VSplitLeft(MenuBar.w * 0.75f, &MenuBar, &Info); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "File: %s", m_aFileName); UI()->DoLabel(&MenuBar, aBuf, 10.0f, -1, -1); @@ -5830,7 +5806,7 @@ void CEditor::RenderMenubar(CUIRect MenuBar) char aTimeStr[6]; str_timestamp_format(aTimeStr, sizeof(aTimeStr), "%H:%M"); - str_format(aBuf, sizeof(aBuf), "X: %i, Y: %i, Z: %i, A: %.1f, G: %i %s", (int)UI()->MouseWorldX()/32, (int)UI()->MouseWorldY()/32, m_ZoomLevel, m_AnimateSpeed, m_GridFactor, aTimeStr); + str_format(aBuf, sizeof(aBuf), "X: %i, Y: %i, Z: %i, A: %.1f, G: %i %s", (int)UI()->MouseWorldX() / 32, (int)UI()->MouseWorldY() / 32, m_ZoomLevel, m_AnimateSpeed, m_GridFactor, aTimeStr); UI()->DoLabel(&Info, aBuf, 10.0f, 1, -1); static int s_CloseButton = 0; @@ -5954,7 +5930,7 @@ void CEditor::Render() if(m_GuiActive) { - RenderBackground(MenuBar, m_BackgroundTexture, 128.0f, Brightness*0); + RenderBackground(MenuBar, m_BackgroundTexture, 128.0f, Brightness * 0); MenuBar.Margin(2.0f, &MenuBar); RenderBackground(ToolBox, m_BackgroundTexture, 128.0f, Brightness); @@ -6002,19 +5978,19 @@ void CEditor::Render() // ctrl+n to create new map if(Input()->KeyPress(KEY_N) && CtrlPressed) { - if(HasUnsavedData()) + if(HasUnsavedData()) + { + if(!m_PopupEventWasActivated) { - if(!m_PopupEventWasActivated) - { - m_PopupEventType = POPEVENT_NEW; - m_PopupEventActivated = true; - } - } - else - { - Reset(); - m_aFileName[0] = 0; + m_PopupEventType = POPEVENT_NEW; + m_PopupEventActivated = true; } + } + else + { + Reset(); + m_aFileName[0] = 0; + } } // ctrl+a to append map if(Input()->KeyPress(KEY_A) && CtrlPressed) @@ -6132,12 +6108,11 @@ void CEditor::Render() if(m_PopupEventActivated) { static int s_PopupID = 0; - UiInvokePopupMenu(&s_PopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupEvent); + UiInvokePopupMenu(&s_PopupID, 0, Width / 2.0f - 200.0f, Height / 2.0f - 100.0f, 400.0f, 200.0f, PopupEvent); m_PopupEventActivated = false; m_PopupEventWasActivated = true; } - UiDoPopupMenu(); if(m_Dialog == DIALOG_NONE && !m_MouseInsidePopup && UI()->MouseInside(&View)) @@ -6169,7 +6144,7 @@ void CEditor::Render() { Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); CTextCursor Cursor; - TextRender()->SetCursor(&Cursor, View.x+10, View.y+View.h-24-10, 24.0f, TEXTFLAG_RENDER); + TextRender()->SetCursor(&Cursor, View.x + 10, View.y + View.h - 24 - 10, 24.0f, TEXTFLAG_RENDER); int NKeys = 0; for(int i = 0; i < KEY_LAST; i++) @@ -6193,8 +6168,8 @@ void CEditor::Render() Graphics()->TextureSet(m_CursorTexture); Graphics()->QuadsBegin(); if(ms_pUiGotContext == UI()->HotItem()) - Graphics()->SetColor(1,0,0,1); - IGraphics::CQuadItem QuadItem(mx,my, 16.0f, 16.0f); + Graphics()->SetColor(1, 0, 0, 1); + IGraphics::CQuadItem QuadItem(mx, my, 16.0f, 16.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); Graphics()->WrapNormal(); @@ -6293,15 +6268,15 @@ void CEditor::ZoomMouseTarget(float ZoomFactor) m_WorldOffsetX, m_WorldOffsetY, 100.0f, 100.0f, 0.0f, 0.0f, Graphics()->ScreenAspect(), m_WorldZoom, aPoints); - float WorldWidth = aPoints[2]-aPoints[0]; - float WorldHeight = aPoints[3]-aPoints[1]; + float WorldWidth = aPoints[2] - aPoints[0]; + float WorldHeight = aPoints[3] - aPoints[1]; - float Mwx = aPoints[0] + WorldWidth * (UI()->MouseX()/UI()->Screen()->w); - float Mwy = aPoints[1] + WorldHeight * (UI()->MouseY()/UI()->Screen()->h); + float Mwx = aPoints[0] + WorldWidth * (UI()->MouseX() / UI()->Screen()->w); + float Mwy = aPoints[1] + WorldHeight * (UI()->MouseY() / UI()->Screen()->h); // adjust camera - m_WorldOffsetX += (Mwx-m_WorldOffsetX) * (1-ZoomFactor); - m_WorldOffsetY += (Mwy-m_WorldOffsetY) * (1-ZoomFactor); + m_WorldOffsetX += (Mwx - m_WorldOffsetX) * (1 - ZoomFactor); + m_WorldOffsetY += (Mwy - m_WorldOffsetY) * (1 - ZoomFactor); } void CEditorMap::DeleteEnvelope(int Index) @@ -6356,8 +6331,6 @@ void CEditorMap::MakeGameGroup(CLayerGroup *pGroup) str_copy(m_pGameGroup->m_aName, "Game", sizeof(m_pGameGroup->m_aName)); } - - void CEditorMap::Clean() { for(int i = 0; i < m_lGroups.size(); i++) @@ -6461,16 +6434,16 @@ void CEditor::PlaceBorderTiles() { CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); - for(int i = 0; i < pT->m_Width*2; ++i) + for(int i = 0; i < pT->m_Width * 2; ++i) pT->m_pTiles[i].m_Index = 1; - for(int i = 0; i < pT->m_Width*pT->m_Height; ++i) + for(int i = 0; i < pT->m_Width * pT->m_Height; ++i) { - if(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3) + if(i % pT->m_Width < 2 || i % pT->m_Width > pT->m_Width - 3) pT->m_pTiles[i].m_Index = 1; } - for(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i) + for(int i = (pT->m_Width * (pT->m_Height - 2)); i < pT->m_Width * pT->m_Height; ++i) pT->m_pTiles[i].m_Index = 1; } @@ -6508,7 +6481,7 @@ void CEditor::UpdateAndRender() static float s_MouseY = 0.0f; if(m_Animate) - m_AnimateTime = (time_get()-m_AnimateStart)/(float)time_freq(); + m_AnimateTime = (time_get() - m_AnimateStart) / (float)time_freq(); else m_AnimateTime = 0; ms_pUiGotContext = 0; @@ -6546,21 +6519,24 @@ void CEditor::UpdateAndRender() float aPoints[4]; g->Mapping(aPoints); - float WorldWidth = aPoints[2]-aPoints[0]; - float WorldHeight = aPoints[3]-aPoints[1]; + float WorldWidth = aPoints[2] - aPoints[0]; + float WorldHeight = aPoints[3] - aPoints[1]; - Mwx = aPoints[0] + WorldWidth * (s_MouseX/UI()->Screen()->w); - Mwy = aPoints[1] + WorldHeight * (s_MouseY/UI()->Screen()->h); - m_MouseDeltaWx = m_MouseDeltaX*(WorldWidth / UI()->Screen()->w); - m_MouseDeltaWy = m_MouseDeltaY*(WorldHeight / UI()->Screen()->h); + Mwx = aPoints[0] + WorldWidth * (s_MouseX / UI()->Screen()->w); + Mwy = aPoints[1] + WorldHeight * (s_MouseY / UI()->Screen()->h); + m_MouseDeltaWx = m_MouseDeltaX * (WorldWidth / UI()->Screen()->w); + m_MouseDeltaWy = m_MouseDeltaY * (WorldHeight / UI()->Screen()->h); } int Buttons = 0; - if(Input()->KeyIsPressed(KEY_MOUSE_1)) Buttons |= 1; - if(Input()->KeyIsPressed(KEY_MOUSE_2)) Buttons |= 2; - if(Input()->KeyIsPressed(KEY_MOUSE_3)) Buttons |= 4; + if(Input()->KeyIsPressed(KEY_MOUSE_1)) + Buttons |= 1; + if(Input()->KeyIsPressed(KEY_MOUSE_2)) + Buttons |= 2; + if(Input()->KeyIsPressed(KEY_MOUSE_3)) + Buttons |= 4; - UI()->Update(mx,my,Mwx,Mwy,Buttons); + UI()->Update(mx, my, Mwx, Mwy, Buttons); } // toggle gui @@ -6573,8 +6549,7 @@ void CEditor::UpdateAndRender() if(g_Config.m_ClEditorUndo) { // Screenshot at most every 5 seconds, at least every 60 - if((m_LastUndoUpdateTime + time_freq() * 60 < time_get() && m_Map.m_UndoModified) - || (m_LastUndoUpdateTime + time_freq() * 5 < time_get() && m_Map.m_UndoModified >= 10)) + if((m_LastUndoUpdateTime + time_freq() * 60 < time_get() && m_Map.m_UndoModified) || (m_LastUndoUpdateTime + time_freq() * 5 < time_get() && m_Map.m_UndoModified >= 10)) { m_Map.m_UndoModified = 0; m_LastUndoUpdateTime = time_get(); @@ -6602,7 +6577,7 @@ void CEditor::LoadCurrentMap() Load(m_pClient->GetCurrentMapPath(), IStorage::TYPE_ALL); m_ValidSaveFilename = true; - CGameClient *pGameClient = (CGameClient*)Kernel()->RequestInterface(); + CGameClient *pGameClient = (CGameClient *)Kernel()->RequestInterface(); vec2 Center = pGameClient->m_pCamera->m_Center; m_WorldOffsetX = Center.x; diff --git a/src/game/editor/editor.h b/src/game/editor/editor.h index 7476748cb..3774e5eba 100644 --- a/src/game/editor/editor.h +++ b/src/game/editor/editor.h @@ -3,9 +3,9 @@ #ifndef GAME_EDITOR_EDITOR_H #define GAME_EDITOR_EDITOR_H -#include -#include #include +#include +#include #include #include @@ -15,14 +15,14 @@ #include #include +#include #include #include -#include -#include -#include #include #include +#include +#include #include #include @@ -35,11 +35,11 @@ typedef void (*INDEX_MODIFY_FUNC)(int *pIndex); // CEditor SPECIFIC enum { - MODE_LAYERS=0, + MODE_LAYERS = 0, MODE_IMAGES, MODE_SOUNDS, - DIALOG_NONE=0, + DIALOG_NONE = 0, DIALOG_FILE, }; @@ -75,11 +75,13 @@ public: { for(int c = 0; c < m_Channels; c++) { - if(ChannelMask&(1< m_Top) m_Top = v; - if(v < m_Bottom) m_Bottom = v; + if(v > m_Top) + m_Top = v; + if(v < m_Bottom) + m_Bottom = v; } } } @@ -91,7 +93,7 @@ public: return m_Channels; } - void AddPoint(int Time, int v0, int v1=0, int v2=0, int v3=0) + void AddPoint(int Time, int v0, int v1 = 0, int v2 = 0, int v3 = 0) { CEnvPoint p; p.m_Time = Time; @@ -107,12 +109,11 @@ public: float EndTime() { if(m_lPoints.size()) - return m_lPoints[m_lPoints.size()-1].m_Time*(1.0f/1000.0f); + return m_lPoints[m_lPoints.size() - 1].m_Time * (1.0f / 1000.0f); return 0; } }; - class CLayer; class CLayerGroup; class CEditorMap; @@ -139,7 +140,6 @@ public: { } - virtual void BrushSelecting(CUIRect Rect) {} virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { return 0; } virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) {} @@ -156,7 +156,11 @@ public: virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) {} virtual void ModifySoundIndex(INDEX_MODIFY_FUNC pfnFunc) {} - virtual void GetSize(float *w, float *h) { *w = 0; *h = 0;} + virtual void GetSize(float *w, float *h) + { + *w = 0; + *h = 0; + } char m_aName[12]; int m_Type; @@ -173,7 +177,7 @@ class CLayerGroup public: class CEditorMap *m_pMap; - array m_lLayers; + array m_lLayers; int m_OffsetX; int m_OffsetY; @@ -277,8 +281,8 @@ class CEditorImage : public CImageInfo public: CEditor *m_pEditor; - CEditorImage(CEditor *pEditor) - : m_AutoMapper(pEditor) + CEditorImage(CEditor *pEditor) : + m_AutoMapper(pEditor) { m_pEditor = pEditor; m_aName[0] = 0; @@ -330,6 +334,7 @@ class CEditorMap { void MakeGameGroup(CLayerGroup *pGroup); void MakeGameLayer(CLayer *pLayer); + public: CEditor *m_pEditor; bool m_Modified; @@ -345,10 +350,10 @@ public: Clean(); } - array m_lGroups; - array m_lImages; - array m_lEnvelopes; - array m_lSounds; + array m_lGroups; + array m_lImages; + array m_lEnvelopes; + array m_lSounds; class CMapInfo { @@ -410,9 +415,12 @@ public: int SwapGroups(int Index0, int Index1) { - if(Index0 < 0 || Index0 >= m_lGroups.size()) return Index0; - if(Index1 < 0 || Index1 >= m_lGroups.size()) return Index0; - if(Index0 == Index1) return Index0; + if(Index0 < 0 || Index0 >= m_lGroups.size()) + return Index0; + if(Index1 < 0 || Index1 >= m_lGroups.size()) + return Index0; + if(Index0 == Index1) + return Index0; m_Modified = true; m_UndoModified++; swap(m_lGroups[Index0], m_lGroups[Index1]); @@ -421,7 +429,8 @@ public: void DeleteGroup(int Index) { - if(Index < 0 || Index >= m_lGroups.size()) return; + if(Index < 0 || Index >= m_lGroups.size()) + return; m_Modified = true; m_UndoModified++; delete m_lGroups[Index]; @@ -473,7 +482,6 @@ public: void MakeTuneLayer(CLayer *pLayer); }; - struct CProperty { const char *m_pName; @@ -485,7 +493,7 @@ struct CProperty enum { - PROPTYPE_NULL=0, + PROPTYPE_NULL = 0, PROPTYPE_BOOL, PROPTYPE_INT_STEP, PROPTYPE_INT_SCROLL, @@ -537,7 +545,8 @@ public: virtual void ShowInfo(); virtual int RenderProperties(CUIRect *pToolbox); - struct SCommonPropState { + struct SCommonPropState + { bool Modified = false; int Width = -1; int Height = -1; @@ -550,7 +559,11 @@ public: void PrepareForSave(); - void GetSize(float *w, float *h) { *w = m_Width*32.0f; *h = m_Height*32.0f; } + void GetSize(float *w, float *h) + { + *w = m_Width * 32.0f; + *h = m_Height * 32.0f; + } void FlagModified(int x, int y, int w, int h); @@ -627,6 +640,7 @@ class CEditor : public IEditor class IStorage *m_pStorage; CRenderTools m_RenderTools; CUI m_UI; + public: class IInput *Input() { return m_pInput; }; class IClient *Client() { return m_pClient; }; @@ -638,7 +652,8 @@ public: CUI *UI() { return &m_UI; } CRenderTools *RenderTools() { return &m_RenderTools; } - CEditor() : m_TilesetPicker(16, 16) + CEditor() : + m_TilesetPicker(16, 16) { m_pInput = 0; m_pClient = 0; @@ -768,7 +783,7 @@ public: const char *pBasepath, const char *pDefaultName, void (*pfnFunc)(const char *pFilename, int StorageType, void *pUser), void *pUser); - void Reset(bool CreateDefault=true); + void Reset(bool CreateDefault = true); virtual int Save(const char *pFilename); virtual int Load(const char *pFilename, int StorageType); int Append(const char *pFilename, int StorageType); @@ -786,7 +801,7 @@ public: bool IsQuadSelected(int Index); int FindSelectedQuadIndex(int Index); - int DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal, ColorRGBA Color = ColorRGBA(1,1,1,0.5f)); + int DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal, ColorRGBA Color = ColorRGBA(1, 1, 1, 0.5f)); int m_Mode; int m_Dialog; @@ -856,7 +871,6 @@ public: CImageInfo m_FilePreviewImageInfo; bool m_FileDialogOpening; - struct CFilelistItem { char m_aFilename[128]; @@ -866,9 +880,7 @@ public: int m_StorageType; bool m_IsVisible; - bool operator<(const CFilelistItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : - m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : - str_comp_nocase(m_aFilename, Other.m_aFilename) < 0; } + bool operator<(const CFilelistItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : str_comp_nocase(m_aFilename, Other.m_aFilename) < 0; } }; sorted_array m_FileList; int m_FilesStartAt; @@ -943,29 +955,29 @@ public: int DoButton_Env(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pToolTip, ColorRGBA Color); int DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); - int DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize=10.0f); + int DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize = 10.0f); int DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); - int DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags=0, const char *pToolTip=0); + int DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags = 0, const char *pToolTip = 0); - int DoButton_ColorPicker(const void *pID, const CUIRect *pRect, ColorRGBA *pColor, const char *pToolTip=0); + int DoButton_ColorPicker(const void *pID, const CUIRect *pRect, ColorRGBA *pColor, const char *pToolTip = 0); - int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden=false, int Corners=CUI::CORNER_ALL); + int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden = false, int Corners = CUI::CORNER_ALL); void RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, float Size, float Brightness); void RenderGrid(CLayerGroup *pGroup); - void UiInvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect, void *pContext), void *pExtra=0); + void UiInvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect, void *pContext), void *pExtra = 0); void UiDoPopupMenu(); bool UiPopupExists(void *pID); bool UiPopupOpen(); - int UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip, bool IsDegree=false, bool IsHex=false, int corners=CUI::CORNER_ALL, ColorRGBA* Color=0); + int UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip, bool IsDegree = false, bool IsHex = false, int corners = CUI::CORNER_ALL, ColorRGBA *Color = 0); static int PopupGroup(CEditor *pEditor, CUIRect View, void *pContext); @@ -1194,5 +1206,4 @@ public: array m_lSources; }; - #endif diff --git a/src/game/editor/io.cpp b/src/game/editor/io.cpp index 43daaf814..5f1d68b01 100644 --- a/src/game/editor/io.cpp +++ b/src/game/editor/io.cpp @@ -3,6 +3,7 @@ #include +#include "editor.h" #include #include #include @@ -10,11 +11,12 @@ #include #include #include -#include "editor.h" template static int MakeVersion(int i, const T &v) -{ return (i<<16)+sizeof(T); } +{ + return (i << 16) + sizeof(T); +} // backwards compatibility /* @@ -243,19 +245,19 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_Version = 1; if(m_MapInfo.m_aAuthor[0]) - Item.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor)+1, m_MapInfo.m_aAuthor); + Item.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor) + 1, m_MapInfo.m_aAuthor); else Item.m_Author = -1; if(m_MapInfo.m_aVersion[0]) - Item.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion)+1, m_MapInfo.m_aVersion); + Item.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion) + 1, m_MapInfo.m_aVersion); else Item.m_MapVersion = -1; if(m_MapInfo.m_aCredits[0]) - Item.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits)+1, m_MapInfo.m_aCredits); + Item.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits) + 1, m_MapInfo.m_aCredits); else Item.m_Credits = -1; if(m_MapInfo.m_aLicense[0]) - Item.m_License = df.AddData(str_length(m_MapInfo.m_aLicense)+1, m_MapInfo.m_aLicense); + Item.m_License = df.AddData(str_length(m_MapInfo.m_aLicense) + 1, m_MapInfo.m_aLicense); else Item.m_License = -1; @@ -298,7 +300,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_Width = pImg->m_Width; Item.m_Height = pImg->m_Height; Item.m_External = pImg->m_External; - Item.m_ImageName = df.AddData(str_length(pImg->m_aName)+1, pImg->m_aName); + Item.m_ImageName = df.AddData(str_length(pImg->m_aName) + 1, pImg->m_aName); if(pImg->m_External) Item.m_ImageData = -1; else @@ -308,20 +310,19 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) // Convert to RGBA unsigned char *pDataRGBA = (unsigned char *)malloc(Item.m_Width * Item.m_Height * 4); unsigned char *pDataRGB = (unsigned char *)pImg->m_pData; - for(int i = 0; i < Item.m_Width*Item.m_Height; i++) + for(int i = 0; i < Item.m_Width * Item.m_Height; i++) { - - pDataRGBA[i*4] = pDataRGB[i*3]; - pDataRGBA[i*4+1] = pDataRGB[i*3+1]; - pDataRGBA[i*4+2] = pDataRGB[i*3+2]; - pDataRGBA[i*4+3] = 255; + pDataRGBA[i * 4] = pDataRGB[i * 3]; + pDataRGBA[i * 4 + 1] = pDataRGB[i * 3 + 1]; + pDataRGBA[i * 4 + 2] = pDataRGB[i * 3 + 2]; + pDataRGBA[i * 4 + 3] = 255; } - Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*4, pDataRGBA); + Item.m_ImageData = df.AddData(Item.m_Width * Item.m_Height * 4, pDataRGBA); free(pDataRGBA); } else { - Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*4, pImg->m_pData); + Item.m_ImageData = df.AddData(Item.m_Width * Item.m_Height * 4, pImg->m_pData); } } df.AddItem(MAPITEMTYPE_IMAGE, i, sizeof(Item), &Item); @@ -336,7 +337,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_Version = 1; Item.m_External = pSound->m_External; - Item.m_SoundName = df.AddData(str_length(pSound->m_aName)+1, pSound->m_aName); + Item.m_SoundName = df.AddData(str_length(pSound->m_aName) + 1, pSound->m_aName); if(pSound->m_External) { Item.m_SoundDataSize = 0; @@ -373,7 +374,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) GItem.m_NumLayers = 0; // save group name - StrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), pGroup->m_aName); + StrToInts(GItem.m_aName, sizeof(GItem.m_aName) / sizeof(int), pGroup->m_aName); for(int l = 0; l < pGroup->m_lLayers.size(); l++) { @@ -412,29 +413,29 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_Image = pLayer->m_Image; - if (Item.m_Flags && !(pLayer->m_Game)) + if(Item.m_Flags && !(pLayer->m_Game)) { - CTile *pEmptyTiles = (CTile *)calloc(pLayer->m_Width*pLayer->m_Height, sizeof(CTile)); - mem_zero(pEmptyTiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); - Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pEmptyTiles); + CTile *pEmptyTiles = (CTile *)calloc(pLayer->m_Width * pLayer->m_Height, sizeof(CTile)); + mem_zero(pEmptyTiles, pLayer->m_Width * pLayer->m_Height * sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CTile), pEmptyTiles); free(pEmptyTiles); if(pLayer->m_Tele) - Item.m_Tele = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTeleTile), ((CLayerTele *)pLayer)->m_pTeleTile); + Item.m_Tele = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CTeleTile), ((CLayerTele *)pLayer)->m_pTeleTile); else if(pLayer->m_Speedup) - Item.m_Speedup = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CSpeedupTile), ((CLayerSpeedup *)pLayer)->m_pSpeedupTile); + Item.m_Speedup = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CSpeedupTile), ((CLayerSpeedup *)pLayer)->m_pSpeedupTile); else if(pLayer->m_Front) - Item.m_Front = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); + Item.m_Front = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CTile), pLayer->m_pTiles); else if(pLayer->m_Switch) - Item.m_Switch = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CSwitchTile), ((CLayerSwitch *)pLayer)->m_pSwitchTile); + Item.m_Switch = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CSwitchTile), ((CLayerSwitch *)pLayer)->m_pSwitchTile); else if(pLayer->m_Tune) - Item.m_Tune = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTuneTile), ((CLayerTune *)pLayer)->m_pTuneTile); + Item.m_Tune = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CTuneTile), ((CLayerTune *)pLayer)->m_pTuneTile); } else - Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); + Item.m_Data = df.AddData(pLayer->m_Width * pLayer->m_Height * sizeof(CTile), pLayer->m_pTiles); // save layer name - StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + StrToInts(Item.m_aName, sizeof(Item.m_aName) / sizeof(int), pLayer->m_aName); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); @@ -445,7 +446,8 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) ItemAutomapper.m_AutomapperConfig = pLayer->m_AutoMapperConfig; ItemAutomapper.m_AutomapperSeed = pLayer->m_Seed; ItemAutomapper.m_Flags = 0; - if (pLayer->m_AutoAutoMap) ItemAutomapper.m_Flags |= CMapItemAutoMapperConfig::FLAG_AUTOMATIC; + if(pLayer->m_AutoAutoMap) + ItemAutomapper.m_Flags |= CMapItemAutoMapperConfig::FLAG_AUTOMATIC; df.AddItem(MAPITEMTYPE_AUTOMAPPER_CONFIG, AutomapperCount, sizeof(ItemAutomapper), &ItemAutomapper); AutomapperCount++; @@ -467,10 +469,10 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) // add the data Item.m_NumQuads = pLayer->m_lQuads.size(); - Item.m_Data = df.AddDataSwapped(pLayer->m_lQuads.size()*sizeof(CQuad), pLayer->m_lQuads.base_ptr()); + Item.m_Data = df.AddDataSwapped(pLayer->m_lQuads.size() * sizeof(CQuad), pLayer->m_lQuads.base_ptr()); // save layer name - StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + StrToInts(Item.m_aName, sizeof(Item.m_aName) / sizeof(int), pLayer->m_aName); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); @@ -495,10 +497,10 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) // add the data Item.m_NumSources = pLayer->m_lSources.size(); - Item.m_Data = df.AddDataSwapped(pLayer->m_lSources.size()*sizeof(CSoundSource), pLayer->m_lSources.base_ptr()); + Item.m_Data = df.AddDataSwapped(pLayer->m_lSources.size() * sizeof(CSoundSource), pLayer->m_lSources.base_ptr()); // save layer name - StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + StrToInts(Item.m_aName, sizeof(Item.m_aName) / sizeof(int), pLayer->m_aName); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); GItem.m_NumLayers++; @@ -520,7 +522,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_StartPoint = PointCount; Item.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size(); Item.m_Synchronized = m_lEnvelopes[e]->m_Synchronized; - StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), m_lEnvelopes[e]->m_aName); + StrToInts(Item.m_aName, sizeof(Item.m_aName) / sizeof(int), m_lEnvelopes[e]->m_aName); df.AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(Item), &Item); PointCount += Item.m_NumPoints; @@ -534,7 +536,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) for(int e = 0; e < m_lEnvelopes.size(); e++) { int Count = m_lEnvelopes[e]->m_lPoints.size(); - mem_copy(&pPoints[PointCount], m_lEnvelopes[e]->m_lPoints.base_ptr(), sizeof(CEnvPoint)*Count); + mem_copy(&pPoints[PointCount], m_lEnvelopes[e]->m_lPoints.base_ptr(), sizeof(CEnvPoint) * Count); PointCount += Count; } @@ -550,12 +552,11 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) { CServerInfo CurrentServerInfo; m_pEditor->Client()->GetServerInfo(&CurrentServerInfo); - const unsigned char ipv4Localhost[16] = {127,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}; - const unsigned char ipv6Localhost[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; + const unsigned char ipv4Localhost[16] = {127, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + const unsigned char ipv6Localhost[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; // and if we're on localhost - if(!mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv4Localhost, sizeof(ipv4Localhost)) - || !mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv6Localhost, sizeof(ipv6Localhost))) + if(!mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv4Localhost, sizeof(ipv4Localhost)) || !mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv6Localhost, sizeof(ipv6Localhost))) { char aMapName[128]; IStorage::StripPathAndExtension(pFileName, aMapName, sizeof(aMapName)); @@ -571,7 +572,7 @@ int CEditor::Load(const char *pFileName, int StorageType) { Reset(); int result = m_Map.Load(Kernel()->RequestInterface(), pFileName, StorageType); - if (result) + if(result) { str_copy(m_aFileName, pFileName, 512); SortImages(); @@ -653,10 +654,10 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load images { int Start, Num; - DataFile.GetType( MAPITEMTYPE_IMAGE, &Start, &Num); + DataFile.GetType(MAPITEMTYPE_IMAGE, &Start, &Num); for(int i = 0; i < Num; i++) { - CMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start+i, 0, 0); + CMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start + i, 0, 0); char *pName = (char *)DataFile.GetData(pItem->m_ImageName); // copy base info @@ -666,7 +667,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag if(pItem->m_External) { char aBuf[256]; - str_format(aBuf, sizeof(aBuf),"mapres/%s.png", pName); + str_format(aBuf, sizeof(aBuf), "mapres/%s.png", pName); // load external CEditorImage ImgInfo(m_pEditor); @@ -715,10 +716,10 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load sounds { int Start, Num; - DataFile.GetType( MAPITEMTYPE_SOUND, &Start, &Num); + DataFile.GetType(MAPITEMTYPE_SOUND, &Start, &Num); for(int i = 0; i < Num; i++) { - CMapItemSound *pItem = (CMapItemSound *)DataFile.GetItem(Start+i, 0, 0); + CMapItemSound *pItem = (CMapItemSound *)DataFile.GetItem(Start + i, 0, 0); char *pName = (char *)DataFile.GetData(pItem->m_SoundName); // copy base info @@ -728,7 +729,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag if(pItem->m_External) { char aBuf[256]; - str_format(aBuf, sizeof(aBuf),"mapres/%s.opus", pName); + str_format(aBuf, sizeof(aBuf), "mapres/%s.opus", pName); // load external IOHANDLE SoundFile = pStorage->OpenFile(pName, IOFLAG_READ, IStorage::TYPE_ALL); @@ -781,7 +782,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag DataFile.GetType(MAPITEMTYPE_GROUP, &Start, &Num); for(int g = 0; g < Num; g++) { - CMapItemGroup *pGItem = (CMapItemGroup *)DataFile.GetItem(Start+g, 0, 0); + CMapItemGroup *pGItem = (CMapItemGroup *)DataFile.GetItem(Start + g, 0, 0); if(pGItem->m_Version < 1 || pGItem->m_Version > CMapItemGroup::CURRENT_VERSION) continue; @@ -803,12 +804,12 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load group name if(pGItem->m_Version >= 3) - IntsToStr(pGItem->m_aName, sizeof(pGroup->m_aName)/sizeof(int), pGroup->m_aName); + IntsToStr(pGItem->m_aName, sizeof(pGroup->m_aName) / sizeof(int), pGroup->m_aName); for(int l = 0; l < pGItem->m_NumLayers; l++) { CLayer *pLayer = 0; - CMapItemLayer *pLayerItem = (CMapItemLayer *)DataFile.GetItem(LayersStart+pGItem->m_StartLayer+l, 0, 0); + CMapItemLayer *pLayerItem = (CMapItemLayer *)DataFile.GetItem(LayersStart + pGItem->m_StartLayer + l, 0, 0); if(!pLayerItem) continue; @@ -817,48 +818,48 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag CMapItemLayerTilemap *pTilemapItem = (CMapItemLayerTilemap *)pLayerItem; CLayerTiles *pTiles = 0; - if(pTilemapItem->m_Flags&TILESLAYERFLAG_GAME) + if(pTilemapItem->m_Flags & TILESLAYERFLAG_GAME) { pTiles = new CLayerGame(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeGameLayer(pTiles); MakeGameGroup(pGroup); } - else if(pTilemapItem->m_Flags&TILESLAYERFLAG_TELE) + else if(pTilemapItem->m_Flags & TILESLAYERFLAG_TELE) { if(pTilemapItem->m_Version <= 2) - pTilemapItem->m_Tele = *((int*)(pTilemapItem) + 15); + pTilemapItem->m_Tele = *((int *)(pTilemapItem) + 15); pTiles = new CLayerTele(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeTeleLayer(pTiles); } - else if(pTilemapItem->m_Flags&TILESLAYERFLAG_SPEEDUP) + else if(pTilemapItem->m_Flags & TILESLAYERFLAG_SPEEDUP) { if(pTilemapItem->m_Version <= 2) - pTilemapItem->m_Speedup = *((int*)(pTilemapItem) + 16); + pTilemapItem->m_Speedup = *((int *)(pTilemapItem) + 16); pTiles = new CLayerSpeedup(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeSpeedupLayer(pTiles); } - else if(pTilemapItem->m_Flags&TILESLAYERFLAG_FRONT) + else if(pTilemapItem->m_Flags & TILESLAYERFLAG_FRONT) { if(pTilemapItem->m_Version <= 2) - pTilemapItem->m_Front = *((int*)(pTilemapItem) + 17); + pTilemapItem->m_Front = *((int *)(pTilemapItem) + 17); pTiles = new CLayerFront(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeFrontLayer(pTiles); } - else if(pTilemapItem->m_Flags&TILESLAYERFLAG_SWITCH) + else if(pTilemapItem->m_Flags & TILESLAYERFLAG_SWITCH) { if(pTilemapItem->m_Version <= 2) - pTilemapItem->m_Switch = *((int*)(pTilemapItem) + 18); + pTilemapItem->m_Switch = *((int *)(pTilemapItem) + 18); pTiles = new CLayerSwitch(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeSwitchLayer(pTiles); } - else if(pTilemapItem->m_Flags&TILESLAYERFLAG_TUNE) + else if(pTilemapItem->m_Flags & TILESLAYERFLAG_TUNE) { if(pTilemapItem->m_Version <= 2) - pTilemapItem->m_Tune = *((int*)(pTilemapItem) + 19); + pTilemapItem->m_Tune = *((int *)(pTilemapItem) + 19); pTiles = new CLayerTune(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeTuneLayer(pTiles); @@ -878,17 +879,17 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag void *pData = DataFile.GetData(pTilemapItem->m_Data); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Data); pTiles->m_Image = pTilemapItem->m_Image; - pTiles->m_Game = pTilemapItem->m_Flags&TILESLAYERFLAG_GAME; + pTiles->m_Game = pTilemapItem->m_Flags & TILESLAYERFLAG_GAME; // load layer name if(pTilemapItem->m_Version >= 3) - IntsToStr(pTilemapItem->m_aName, sizeof(pTiles->m_aName)/sizeof(int), pTiles->m_aName); + IntsToStr(pTilemapItem->m_aName, sizeof(pTiles->m_aName) / sizeof(int), pTiles->m_aName); if(pTiles->m_Tele) { void *pTeleData = DataFile.GetData(pTilemapItem->m_Tele); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Tele); - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTeleTile)) + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CTeleTile)) { static const int s_aTilesRep[] = { TILE_TELEIN, @@ -899,16 +900,15 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag TILE_TELECHECKINEVIL, TILE_TELECHECKOUT, TILE_TELEINWEAPON, - TILE_TELEINHOOK - }; - mem_copy(((CLayerTele *)pTiles)->m_pTeleTile, pTeleData, pTiles->m_Width*pTiles->m_Height*sizeof(CTeleTile)); + TILE_TELEINHOOK}; + mem_copy(((CLayerTele *)pTiles)->m_pTeleTile, pTeleData, pTiles->m_Width * pTiles->m_Height * sizeof(CTeleTile)); - for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + for(int i = 0; i < pTiles->m_Width * pTiles->m_Height; i++) { pTiles->m_pTiles[i].m_Index = 0; - for (unsigned e = 0; e < sizeof(s_aTilesRep) / sizeof(s_aTilesRep[0]); e++) + for(unsigned e = 0; e < sizeof(s_aTilesRep) / sizeof(s_aTilesRep[0]); e++) { - if (((CLayerTele *)pTiles)->m_pTeleTile[i].m_Type == s_aTilesRep[e]) + if(((CLayerTele *)pTiles)->m_pTeleTile[i].m_Type == s_aTilesRep[e]) pTiles->m_pTiles[i].m_Index = s_aTilesRep[e]; } } @@ -920,13 +920,13 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag void *pSpeedupData = DataFile.GetData(pTilemapItem->m_Speedup); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Speedup); - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CSpeedupTile)) + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CSpeedupTile)) { - mem_copy(((CLayerSpeedup*)pTiles)->m_pSpeedupTile, pSpeedupData, pTiles->m_Width*pTiles->m_Height*sizeof(CSpeedupTile)); + mem_copy(((CLayerSpeedup *)pTiles)->m_pSpeedupTile, pSpeedupData, pTiles->m_Width * pTiles->m_Height * sizeof(CSpeedupTile)); - for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + for(int i = 0; i < pTiles->m_Width * pTiles->m_Height; i++) { - if(((CLayerSpeedup*)pTiles)->m_pSpeedupTile[i].m_Force > 0) + if(((CLayerSpeedup *)pTiles)->m_pSpeedupTile[i].m_Force > 0) pTiles->m_pTiles[i].m_Index = TILE_BOOST; else pTiles->m_pTiles[i].m_Index = 0; @@ -939,8 +939,8 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag { void *pFrontData = DataFile.GetData(pTilemapItem->m_Front); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Front); - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTile)) - mem_copy(((CLayerFront*)pTiles)->m_pTiles, pFrontData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile)); + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CTile)) + mem_copy(((CLayerFront *)pTiles)->m_pTiles, pFrontData, pTiles->m_Width * pTiles->m_Height * sizeof(CTile)); DataFile.UnloadData(pTilemapItem->m_Front); } @@ -948,7 +948,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag { void *pSwitchData = DataFile.GetData(pTilemapItem->m_Switch); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Switch); - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CSwitchTile)) + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CSwitchTile)) { const int s_aTilesComp[] = { TILE_SWITCHTIMEDOPEN, @@ -966,11 +966,11 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag TILE_ALLOW_TELE_GUN, TILE_ALLOW_BLUE_TELE_GUN}; CSwitchTile *pLayerSwitchTiles = ((CLayerSwitch *)pTiles)->m_pSwitchTile; - mem_copy(((CLayerSwitch *)pTiles)->m_pSwitchTile, pSwitchData, pTiles->m_Width*pTiles->m_Height*sizeof(CSwitchTile)); + mem_copy(((CLayerSwitch *)pTiles)->m_pSwitchTile, pSwitchData, pTiles->m_Width * pTiles->m_Height * sizeof(CSwitchTile)); - for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + for(int i = 0; i < pTiles->m_Width * pTiles->m_Height; i++) { - if(((pLayerSwitchTiles[i].m_Type > (ENTITY_CRAZY_SHOTGUN + ENTITY_OFFSET) && ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type < (ENTITY_DRAGGER_WEAK + ENTITY_OFFSET)) || ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == (ENTITY_LASER_O_FAST + 1 + ENTITY_OFFSET))) + if(((pLayerSwitchTiles[i].m_Type > (ENTITY_CRAZY_SHOTGUN + ENTITY_OFFSET) && ((CLayerSwitch *)pTiles)->m_pSwitchTile[i].m_Type < (ENTITY_DRAGGER_WEAK + ENTITY_OFFSET)) || ((CLayerSwitch *)pTiles)->m_pSwitchTile[i].m_Type == (ENTITY_LASER_O_FAST + 1 + ENTITY_OFFSET))) continue; else if(pLayerSwitchTiles[i].m_Type >= (ENTITY_ARMOR_1 + ENTITY_OFFSET) && pLayerSwitchTiles[i].m_Type <= (ENTITY_DOOR + ENTITY_OFFSET)) { @@ -979,7 +979,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag continue; } - for (unsigned e = 0; e < sizeof(s_aTilesComp) / sizeof(s_aTilesComp[0]); e++) + for(unsigned e = 0; e < sizeof(s_aTilesComp) / sizeof(s_aTilesComp[0]); e++) { if(pLayerSwitchTiles[i].m_Type == s_aTilesComp[e]) { @@ -995,12 +995,12 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag { void *pTuneData = DataFile.GetData(pTilemapItem->m_Tune); unsigned int Size = DataFile.GetDataSize(pTilemapItem->m_Tune); - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTuneTile)) + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CTuneTile)) { CTuneTile *pLayerTuneTiles = ((CLayerTune *)pTiles)->m_pTuneTile; - mem_copy(((CLayerTune *)pTiles)->m_pTuneTile, pTuneData, pTiles->m_Width*pTiles->m_Height*sizeof(CTuneTile)); + mem_copy(((CLayerTune *)pTiles)->m_pTuneTile, pTuneData, pTiles->m_Width * pTiles->m_Height * sizeof(CTuneTile)); - for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + for(int i = 0; i < pTiles->m_Width * pTiles->m_Height; i++) { if(pLayerTuneTiles[i].m_Type == TILE_TUNE) pTiles->m_pTiles[i].m_Index = TILE_TUNE; @@ -1012,13 +1012,13 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag } else // regular tile layer or game layer { - if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTile)) + if(Size >= pTiles->m_Width * pTiles->m_Height * sizeof(CTile)) { - mem_copy(pTiles->m_pTiles, pData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile)); + mem_copy(pTiles->m_pTiles, pData, pTiles->m_Width * pTiles->m_Height * sizeof(CTile)); if(pTiles->m_Game && pTilemapItem->m_Version == MakeVersion(1, *pTilemapItem)) { - for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + for(int i = 0; i < pTiles->m_Width * pTiles->m_Height; i++) { if(pTiles->m_pTiles[i].m_Index) pTiles->m_pTiles[i].m_Index += ENTITY_OFFSET; @@ -1143,7 +1143,6 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag } } }*/ - } else if(pLayerItem->m_Type == LAYERTYPE_QUADS) { @@ -1157,12 +1156,12 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load layer name if(pQuadsItem->m_Version >= 2) - IntsToStr(pQuadsItem->m_aName, sizeof(pQuads->m_aName)/sizeof(int), pQuads->m_aName); + IntsToStr(pQuadsItem->m_aName, sizeof(pQuads->m_aName) / sizeof(int), pQuads->m_aName); void *pData = DataFile.GetDataSwapped(pQuadsItem->m_Data); pGroup->AddLayer(pQuads); pQuads->m_lQuads.set_size(pQuadsItem->m_NumQuads); - mem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad)*pQuadsItem->m_NumQuads); + mem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad) * pQuadsItem->m_NumQuads); DataFile.UnloadData(pQuadsItem->m_Data); } else if(pLayerItem->m_Type == LAYERTYPE_SOUNDS) @@ -1182,13 +1181,13 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load layer name if(pSoundsItem->m_Version >= 1) - IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName)/sizeof(int), pSounds->m_aName); + IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName) / sizeof(int), pSounds->m_aName); // load data void *pData = DataFile.GetDataSwapped(pSoundsItem->m_Data); pGroup->AddLayer(pSounds); pSounds->m_lSources.set_size(pSoundsItem->m_NumSources); - mem_copy(pSounds->m_lSources.base_ptr(), pData, sizeof(CSoundSource)*pSoundsItem->m_NumSources); + mem_copy(pSounds->m_lSources.base_ptr(), pData, sizeof(CSoundSource) * pSoundsItem->m_NumSources); DataFile.UnloadData(pSoundsItem->m_Data); } else if(pLayerItem->m_Type == LAYERTYPE_SOUNDS_DEPRECATED) @@ -1209,7 +1208,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag // load layer name if(pSoundsItem->m_Version >= 1) - IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName)/sizeof(int), pSounds->m_aName); + IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName) / sizeof(int), pSounds->m_aName); // load data CSoundSource_DEPRECATED *pData = (CSoundSource_DEPRECATED *)DataFile.GetDataSwapped(pSoundsItem->m_Data); @@ -1260,12 +1259,12 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag DataFile.GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); for(int e = 0; e < Num; e++) { - CMapItemEnvelope *pItem = (CMapItemEnvelope *)DataFile.GetItem(Start+e, 0, 0); + CMapItemEnvelope *pItem = (CMapItemEnvelope *)DataFile.GetItem(Start + e, 0, 0); CEnvelope *pEnv = new CEnvelope(pItem->m_Channels); pEnv->m_lPoints.set_size(pItem->m_NumPoints); - mem_copy(pEnv->m_lPoints.base_ptr(), &pPoints[pItem->m_StartPoint], sizeof(CEnvPoint)*pItem->m_NumPoints); - if(pItem->m_aName[0] != -1) // compatibility with old maps - IntsToStr(pItem->m_aName, sizeof(pItem->m_aName)/sizeof(int), pEnv->m_aName); + mem_copy(pEnv->m_lPoints.base_ptr(), &pPoints[pItem->m_StartPoint], sizeof(CEnvPoint) * pItem->m_NumPoints); + if(pItem->m_aName[0] != -1) // compatibility with old maps + IntsToStr(pItem->m_aName, sizeof(pItem->m_aName) / sizeof(int), pEnv->m_aName); m_lEnvelopes.add(pEnv); if(pItem->m_Version >= 2) pEnv->m_Synchronized = pItem->m_Synchronized; @@ -1277,12 +1276,13 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag DataFile.GetType(MAPITEMTYPE_AUTOMAPPER_CONFIG, &Start, &Num); for(int i = 0; i < Num; i++) { - CMapItemAutoMapperConfig *pItem = (CMapItemAutoMapperConfig *)DataFile.GetItem(Start+i, 0, 0); - if (pItem->m_Version == CMapItemAutoMapperConfig::CURRENT_VERSION) { - if (pItem->m_GroupId >= 0 && pItem->m_GroupId < m_lGroups.size() && + CMapItemAutoMapperConfig *pItem = (CMapItemAutoMapperConfig *)DataFile.GetItem(Start + i, 0, 0); + if(pItem->m_Version == CMapItemAutoMapperConfig::CURRENT_VERSION) + { + if(pItem->m_GroupId >= 0 && pItem->m_GroupId < m_lGroups.size() && pItem->m_LayerId >= 0 && pItem->m_LayerId < m_lGroups[pItem->m_GroupId]->m_lLayers.size() && - m_lGroups[pItem->m_GroupId]->m_lLayers[pItem->m_LayerId]->m_Type == LAYERTYPE_TILES) { - + m_lGroups[pItem->m_GroupId]->m_lLayers[pItem->m_LayerId]->m_Type == LAYERTYPE_TILES) + { CLayerTiles *pLayer = (CLayerTiles *)m_lGroups[pItem->m_GroupId]->m_lLayers[pItem->m_LayerId]; pLayer->m_AutoMapperConfig = pItem->m_AutomapperConfig; pLayer->m_Seed = pItem->m_AutomapperSeed; diff --git a/src/game/editor/layer_game.cpp b/src/game/editor/layer_game.cpp index afc1f7aa7..9e4cd1b44 100644 --- a/src/game/editor/layer_game.cpp +++ b/src/game/editor/layer_game.cpp @@ -2,9 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "editor.h" - -CLayerGame::CLayerGame(int w, int h) -: CLayerTiles(w, h) +CLayerGame::CLayerGame(int w, int h) : + CLayerTiles(w, h) { str_copy(m_aName, "Game", sizeof(m_aName)); m_Game = 1; @@ -16,18 +15,23 @@ CLayerGame::~CLayerGame() CTile CLayerGame::GetTile(int x, int y) { - if(m_pEditor->m_Map.m_pFrontLayer && m_pEditor->m_Map.m_pFrontLayer->GetTile(x, y).m_Index == TILE_THROUGH_CUT) { + if(m_pEditor->m_Map.m_pFrontLayer && m_pEditor->m_Map.m_pFrontLayer->GetTile(x, y).m_Index == TILE_THROUGH_CUT) + { CTile through_cut = {TILE_THROUGH_CUT}; return through_cut; - } else { + } + else + { return CLayerTiles::GetTile(x, y); } } void CLayerGame::SetTile(int x, int y, CTile tile) { - if(tile.m_Index == TILE_THROUGH_CUT) { - if(!m_pEditor->m_Map.m_pFrontLayer) { + if(tile.m_Index == TILE_THROUGH_CUT) + { + if(!m_pEditor->m_Map.m_pFrontLayer) + { CLayer *l = new CLayerFront(m_Width, m_Height); m_pEditor->m_Map.MakeFrontLayer(l); m_pEditor->m_Map.m_pGameGroup->AddLayer(l); @@ -36,17 +40,24 @@ void CLayerGame::SetTile(int x, int y, CTile tile) CLayerTiles::SetTile(x, y, nohook); CTile through_cut = {TILE_THROUGH_CUT}; m_pEditor->m_Map.m_pFrontLayer->CLayerTiles::SetTile(x, y, through_cut); - } else { - if(m_pEditor->m_Map.m_pFrontLayer && m_pEditor->m_Map.m_pFrontLayer->GetTile(x, y).m_Index == TILE_THROUGH_CUT) { + } + else + { + if(m_pEditor->m_Map.m_pFrontLayer && m_pEditor->m_Map.m_pFrontLayer->GetTile(x, y).m_Index == TILE_THROUGH_CUT) + { CTile air = {TILE_AIR}; m_pEditor->m_Map.m_pFrontLayer->CLayerTiles::SetTile(x, y, air); } - if(m_pEditor->m_AllowPlaceUnusedTiles || IsValidGameTile(tile.m_Index)) { + if(m_pEditor->m_AllowPlaceUnusedTiles || IsValidGameTile(tile.m_Index)) + { CLayerTiles::SetTile(x, y, tile); - } else { + } + else + { CTile air = {TILE_AIR}; CLayerTiles::SetTile(x, y, air); - if(!m_pEditor->m_PreventUnusedTilesWasWarned) { + if(!m_pEditor->m_PreventUnusedTilesWasWarned) + { m_pEditor->m_PopupEventType = m_pEditor->POPEVENT_PREVENTUNUSEDTILES; m_pEditor->m_PopupEventActivated = true; m_pEditor->m_PreventUnusedTilesWasWarned = true; diff --git a/src/game/editor/layer_quads.cpp b/src/game/editor/layer_quads.cpp index 19b99192e..830d97bd8 100644 --- a/src/game/editor/layer_quads.cpp +++ b/src/game/editor/layer_quads.cpp @@ -6,8 +6,8 @@ #include #include "editor.h" -#include #include +#include #include CLayerQuads::CLayerQuads() @@ -70,10 +70,22 @@ CQuad *CLayerQuads::NewQuad(int x, int y, int Width, int Height) q->m_aTexcoords[3].x = i2fx(1); q->m_aTexcoords[3].y = i2fx(1); - q->m_aColors[0].r = 255; q->m_aColors[0].g = 255; q->m_aColors[0].b = 255; q->m_aColors[0].a = 255; - q->m_aColors[1].r = 255; q->m_aColors[1].g = 255; q->m_aColors[1].b = 255; q->m_aColors[1].a = 255; - q->m_aColors[2].r = 255; q->m_aColors[2].g = 255; q->m_aColors[2].b = 255; q->m_aColors[2].a = 255; - q->m_aColors[3].r = 255; q->m_aColors[3].g = 255; q->m_aColors[3].b = 255; q->m_aColors[3].a = 255; + q->m_aColors[0].r = 255; + q->m_aColors[0].g = 255; + q->m_aColors[0].b = 255; + q->m_aColors[0].a = 255; + q->m_aColors[1].r = 255; + q->m_aColors[1].g = 255; + q->m_aColors[1].b = 255; + q->m_aColors[1].a = 255; + q->m_aColors[2].r = 255; + q->m_aColors[2].g = 255; + q->m_aColors[2].b = 255; + q->m_aColors[2].a = 255; + q->m_aColors[3].r = 255; + q->m_aColors[3].g = 255; + q->m_aColors[3].b = 255; + q->m_aColors[3].a = 255; return q; } @@ -82,10 +94,10 @@ void CLayerQuads::BrushSelecting(CUIRect Rect) { // draw selection rectangle IGraphics::CLineItem Array[4] = { - IGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y), - IGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h), - IGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h), - IGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)}; + IGraphics::CLineItem(Rect.x, Rect.y, Rect.x + Rect.w, Rect.y), + IGraphics::CLineItem(Rect.x + Rect.w, Rect.y, Rect.x + Rect.w, Rect.y + Rect.h), + IGraphics::CLineItem(Rect.x + Rect.w, Rect.y + Rect.h, Rect.x, Rect.y + Rect.h), + IGraphics::CLineItem(Rect.x, Rect.y + Rect.h, Rect.x, Rect.y)}; Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(Array, 4); @@ -107,7 +119,7 @@ int CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) float px = fx2f(q->m_aPoints[4].x); float py = fx2f(q->m_aPoints[4].y); - if(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h) + if(px > Rect.x && px < Rect.x + Rect.w && py > Rect.y && py < Rect.y + Rect.h) { CQuad n; n = *q; @@ -122,7 +134,7 @@ int CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) } } - return pGrabbed->m_lQuads.size()?1:0; + return pGrabbed->m_lQuads.size() ? 1 : 0; } void CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy) @@ -143,7 +155,7 @@ void CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy) m_pEditor->m_Map.m_Modified = true; } -void Swap(CPoint& a, CPoint& b) +void Swap(CPoint &a, CPoint &b) { CPoint Tmp; Tmp.x = a.x; @@ -211,7 +223,8 @@ void CLayerQuads::BrushRotate(float Amount) void CLayerQuads::GetSize(float *w, float *h) { - *w = 0; *h = 0; + *w = 0; + *h = 0; for(int i = 0; i < m_lQuads.size(); i++) { @@ -228,7 +241,7 @@ int CLayerQuads::RenderProperties(CUIRect *pToolBox) // layer props enum { - PROP_IMAGE=0, + PROP_IMAGE = 0, NUM_PROPS, }; @@ -246,7 +259,7 @@ int CLayerQuads::RenderProperties(CUIRect *pToolBox) if(Prop == PROP_IMAGE) { if(NewVal >= 0) - m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); + m_Image = NewVal % m_pEditor->m_Map.m_lImages.size(); else m_Image = -1; } @@ -254,7 +267,6 @@ int CLayerQuads::RenderProperties(CUIRect *pToolBox) return 0; } - void CLayerQuads::ModifyImageIndex(INDEX_MODIFY_FUNC Func) { Func(&m_Image); diff --git a/src/game/editor/layer_sounds.cpp b/src/game/editor/layer_sounds.cpp index ba0fac1b8..c9805858f 100644 --- a/src/game/editor/layer_sounds.cpp +++ b/src/game/editor/layer_sounds.cpp @@ -35,7 +35,7 @@ void CLayerSounds::Render(bool Tileset) if(pSource->m_PosEnv >= 0) { float aChannels[4]; - m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset/1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); + m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset / 1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); OffsetX = aChannels[0]; OffsetY = aChannels[1]; } @@ -43,35 +43,34 @@ void CLayerSounds::Render(bool Tileset) switch(pSource->m_Shape.m_Type) { case CSoundShape::SHAPE_CIRCLE: - { - m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, - pSource->m_Shape.m_Circle.m_Radius, 32); + { + m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x) + OffsetX, fx2f(pSource->m_Position.y) + OffsetY, + pSource->m_Shape.m_Circle.m_Radius, 32); - float Falloff = ((float)pSource->m_Falloff/255.0f); - if(Falloff > 0.0f) - m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, - pSource->m_Shape.m_Circle.m_Radius*Falloff, 32); - break; - } + float Falloff = ((float)pSource->m_Falloff / 255.0f); + if(Falloff > 0.0f) + m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x) + OffsetX, fx2f(pSource->m_Position.y) + OffsetY, + pSource->m_Shape.m_Circle.m_Radius * Falloff, 32); + break; + } case CSoundShape::SHAPE_RECTANGLE: - { - float Width = fx2f(pSource->m_Shape.m_Rectangle.m_Width); - float Height = fx2f(pSource->m_Shape.m_Rectangle.m_Height); - m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x)+OffsetX - Width/2, fx2f(pSource->m_Position.y)+OffsetY - Height/2, - Width, Height, 0.0f); + { + float Width = fx2f(pSource->m_Shape.m_Rectangle.m_Width); + float Height = fx2f(pSource->m_Shape.m_Rectangle.m_Height); + m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x) + OffsetX - Width / 2, fx2f(pSource->m_Position.y) + OffsetY - Height / 2, + Width, Height, 0.0f); - float Falloff = ((float)pSource->m_Falloff/255.0f); - if(Falloff > 0.0f) - m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x)+OffsetX - Falloff*Width/2, fx2f(pSource->m_Position.y)+OffsetY - Falloff*Height/2, - Width*Falloff, Height*Falloff, 0.0f); - break; - } + float Falloff = ((float)pSource->m_Falloff / 255.0f); + if(Falloff > 0.0f) + m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x) + OffsetX - Falloff * Width / 2, fx2f(pSource->m_Position.y) + OffsetY - Falloff * Height / 2, + Width * Falloff, Height * Falloff, 0.0f); + break; + } } } Graphics()->QuadsEnd(); - // draw handles Graphics()->TextureSet(g_pData->m_aImages[IMAGE_AUDIO_SOURCE].m_Id); Graphics()->QuadsBegin(); @@ -88,12 +87,12 @@ void CLayerSounds::Render(bool Tileset) if(pSource->m_PosEnv >= 0) { float aChannels[4]; - m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset/1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); + m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset / 1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); OffsetX = aChannels[0]; OffsetY = aChannels[1]; } - m_pEditor->RenderTools()->DrawSprite(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, s_SourceVisualSize*m_pEditor->m_WorldZoom); + m_pEditor->RenderTools()->DrawSprite(fx2f(pSource->m_Position.x) + OffsetX, fx2f(pSource->m_Position.y) + OffsetY, s_SourceVisualSize * m_pEditor->m_WorldZoom); } Graphics()->QuadsEnd(); @@ -135,10 +134,10 @@ void CLayerSounds::BrushSelecting(CUIRect Rect) { // draw selection rectangle IGraphics::CLineItem Array[4] = { - IGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y), - IGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h), - IGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h), - IGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)}; + IGraphics::CLineItem(Rect.x, Rect.y, Rect.x + Rect.w, Rect.y), + IGraphics::CLineItem(Rect.x + Rect.w, Rect.y, Rect.x + Rect.w, Rect.y + Rect.h), + IGraphics::CLineItem(Rect.x + Rect.w, Rect.y + Rect.h, Rect.x, Rect.y + Rect.h), + IGraphics::CLineItem(Rect.x, Rect.y + Rect.h, Rect.x, Rect.y)}; Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(Array, 4); @@ -159,7 +158,7 @@ int CLayerSounds::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) float px = fx2f(pSource->m_Position.x); float py = fx2f(pSource->m_Position.y); - if(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h) + if(px > Rect.x && px < Rect.x + Rect.w && py > Rect.y && py < Rect.y + Rect.h) { CSoundSource n; n = *pSource; @@ -171,7 +170,7 @@ int CLayerSounds::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) } } - return pGrabbed->m_lSources.size()?1:0; + return pGrabbed->m_lSources.size() ? 1 : 0; } void CLayerSounds::BrushPlace(CLayer *pBrush, float wx, float wy) @@ -194,7 +193,7 @@ int CLayerSounds::RenderProperties(CUIRect *pToolBox) // enum { - PROP_SOUND=0, + PROP_SOUND = 0, NUM_PROPS, }; @@ -212,7 +211,7 @@ int CLayerSounds::RenderProperties(CUIRect *pToolBox) if(Prop == PROP_SOUND) { if(NewVal >= 0) - m_Sound = NewVal%m_pEditor->m_Map.m_lSounds.size(); + m_Sound = NewVal % m_pEditor->m_Map.m_lSounds.size(); else m_Sound = -1; } diff --git a/src/game/editor/layer_tiles.cpp b/src/game/editor/layer_tiles.cpp index 16218241a..12c65d3fc 100644 --- a/src/game/editor/layer_tiles.cpp +++ b/src/game/editor/layer_tiles.cpp @@ -7,9 +7,9 @@ #include #include -#include -#include #include "editor.h" +#include +#include #include @@ -40,36 +40,36 @@ CLayerTiles::CLayerTiles(int w, int h) m_Seed = 0; m_AutoAutoMap = false; - m_pTiles = new CTile[m_Width*m_Height]; - mem_zero(m_pTiles, m_Width*m_Height*sizeof(CTile)); + m_pTiles = new CTile[m_Width * m_Height]; + mem_zero(m_pTiles, m_Width * m_Height * sizeof(CTile)); } CLayerTiles::~CLayerTiles() { - delete [] m_pTiles; + delete[] m_pTiles; } CTile CLayerTiles::GetTile(int x, int y) { - return m_pTiles[y*m_Width+x]; + return m_pTiles[y * m_Width + x]; } void CLayerTiles::SetTile(int x, int y, CTile tile) { - m_pTiles[y*m_Width+x] = tile; + m_pTiles[y * m_Width + x] = tile; } void CLayerTiles::PrepareForSave() { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - m_pTiles[y*m_Width+x].m_Flags &= TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE; + m_pTiles[y * m_Width + x].m_Flags &= TILEFLAG_VFLIP | TILEFLAG_HFLIP | TILEFLAG_ROTATE; if(m_Image != -1 && m_Color.a == 255) { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - m_pTiles[y*m_Width+x].m_Flags |= m_pEditor->m_Map.m_lImages[m_Image]->m_aTileFlags[m_pTiles[y*m_Width+x].m_Index]; + m_pTiles[y * m_Width + x].m_Flags |= m_pEditor->m_Map.m_lImages[m_Image]->m_aTileFlags[m_pTiles[y * m_Width + x].m_Index]; } } @@ -77,7 +77,7 @@ void CLayerTiles::MakePalette() { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - m_pTiles[y*m_Width+x].m_Index = y*16+x; + m_pTiles[y * m_Width + x].m_Index = y * 16 + x; } void CLayerTiles::Render(bool Tileset) @@ -85,47 +85,47 @@ void CLayerTiles::Render(bool Tileset) if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size()) m_Texture = m_pEditor->m_Map.m_lImages[m_Image]->m_Texture; Graphics()->TextureSet(m_Texture); - ColorRGBA Color = ColorRGBA(m_Color.r/255.0f, m_Color.g/255.0f, m_Color.b/255.0f, m_Color.a/255.0f); + ColorRGBA Color = ColorRGBA(m_Color.r / 255.0f, m_Color.g / 255.0f, m_Color.b / 255.0f, m_Color.a / 255.0f); Graphics()->BlendNone(); m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_OPAQUE, - m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); + m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); Graphics()->BlendNormal(); m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_TRANSPARENT, - m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); + m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); // Render DDRace Layers if(!Tileset) { if(m_Tele) - m_pEditor->RenderTools()->RenderTeleOverlay(((CLayerTele*)this)->m_pTeleTile, m_Width, m_Height, 32.0f); + m_pEditor->RenderTools()->RenderTeleOverlay(((CLayerTele *)this)->m_pTeleTile, m_Width, m_Height, 32.0f); if(m_Speedup) - m_pEditor->RenderTools()->RenderSpeedupOverlay(((CLayerSpeedup*)this)->m_pSpeedupTile, m_Width, m_Height, 32.0f); + m_pEditor->RenderTools()->RenderSpeedupOverlay(((CLayerSpeedup *)this)->m_pSpeedupTile, m_Width, m_Height, 32.0f); if(m_Switch) - m_pEditor->RenderTools()->RenderSwitchOverlay(((CLayerSwitch*)this)->m_pSwitchTile, m_Width, m_Height, 32.0f); + m_pEditor->RenderTools()->RenderSwitchOverlay(((CLayerSwitch *)this)->m_pSwitchTile, m_Width, m_Height, 32.0f); if(m_Tune) - m_pEditor->RenderTools()->RenderTuneOverlay(((CLayerTune*)this)->m_pTuneTile, m_Width, m_Height, 32.0f); + m_pEditor->RenderTools()->RenderTuneOverlay(((CLayerTune *)this)->m_pTuneTile, m_Width, m_Height, 32.0f); } } -int CLayerTiles::ConvertX(float x) const { return (int)(x/32.0f); } -int CLayerTiles::ConvertY(float y) const { return (int)(y/32.0f); } +int CLayerTiles::ConvertX(float x) const { return (int)(x / 32.0f); } +int CLayerTiles::ConvertY(float y) const { return (int)(y / 32.0f); } void CLayerTiles::Convert(CUIRect Rect, RECTi *pOut) { pOut->x = ConvertX(Rect.x); pOut->y = ConvertY(Rect.y); - pOut->w = ConvertX(Rect.x+Rect.w+31) - pOut->x; - pOut->h = ConvertY(Rect.y+Rect.h+31) - pOut->y; + pOut->w = ConvertX(Rect.x + Rect.w + 31) - pOut->x; + pOut->h = ConvertY(Rect.y + Rect.h + 31) - pOut->y; } void CLayerTiles::Snap(CUIRect *pRect) { RECTi Out; Convert(*pRect, &Out); - pRect->x = Out.x*32.0f; - pRect->y = Out.y*32.0f; - pRect->w = Out.w*32.0f; - pRect->h = Out.h*32.0f; + pRect->x = Out.x * 32.0f; + pRect->y = Out.y * 32.0f; + pRect->w = Out.w * 32.0f; + pRect->h = Out.h * 32.0f; } void CLayerTiles::Clamp(RECTi *pRect) @@ -142,10 +142,10 @@ void CLayerTiles::Clamp(RECTi *pRect) pRect->y = 0; } - if(pRect->x+pRect->w > m_Width) + if(pRect->x + pRect->w > m_Width) pRect->w = m_Width - pRect->x; - if(pRect->y+pRect->h > m_Height) + if(pRect->y + pRect->h > m_Height) pRect->h = m_Height - pRect->y; if(pRect->h < 0) @@ -191,7 +191,7 @@ void CLayerTiles::BrushSelecting(CUIRect Rect) m_pEditor->Graphics()->QuadsEnd(); char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d,%d", ConvertX(Rect.w), ConvertY(Rect.h)); - TextRender()->Text(0, Rect.x+3.0f, Rect.y+3.0f, m_pEditor->m_ShowPicker?15.0f:15.0f*m_pEditor->m_WorldZoom, aBuf, -1.0f); + TextRender()->Text(0, Rect.x + 3.0f, Rect.y + 3.0f, m_pEditor->m_ShowPicker ? 15.0f : 15.0f * m_pEditor->m_WorldZoom, aBuf, -1.0f); } int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) @@ -211,7 +211,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -222,25 +222,21 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); // copy the tele data if(!m_pEditor->Input()->KeyIsPressed(KEY_SPACE)) for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) { - pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x] = ((CLayerTele*)this)->m_pTeleTile[(r.y+y)*m_Width+(r.x+x)]; - if(pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEIN - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEOUT - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINEVIL - // || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKINEVIL - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECK - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKOUT - // || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKIN - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINWEAPON - || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINHOOK) + pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x] = ((CLayerTele *)this)->m_pTeleTile[(r.y + y) * m_Width + (r.x + x)]; + if(pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELEIN || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELEOUT || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELEINEVIL + // || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKINEVIL + || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELECHECK || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELECHECKOUT + // || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKIN + || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELEINWEAPON || pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Type == TILE_TELEINHOOK) { - m_pEditor->m_TeleNumber = pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Number; + m_pEditor->m_TeleNumber = pGrabbed->m_pTeleTile[y * pGrabbed->m_Width + x].m_Number; } } pGrabbed->m_TeleNum = m_pEditor->m_TeleNumber; @@ -253,7 +249,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -264,19 +260,19 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); // copy the speedup data if(!m_pEditor->Input()->KeyIsPressed(KEY_SPACE)) for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) { - pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x] = ((CLayerSpeedup*)this)->m_pSpeedupTile[(r.y+y)*m_Width+(r.x+x)]; - if(pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Type == TILE_BOOST) + pGrabbed->m_pSpeedupTile[y * pGrabbed->m_Width + x] = ((CLayerSpeedup *)this)->m_pSpeedupTile[(r.y + y) * m_Width + (r.x + x)]; + if(pGrabbed->m_pSpeedupTile[y * pGrabbed->m_Width + x].m_Type == TILE_BOOST) { - m_pEditor->m_SpeedupAngle = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Angle; - m_pEditor->m_SpeedupForce = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Force; - m_pEditor->m_SpeedupMaxSpeed = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_MaxSpeed; + m_pEditor->m_SpeedupAngle = pGrabbed->m_pSpeedupTile[y * pGrabbed->m_Width + x].m_Angle; + m_pEditor->m_SpeedupForce = pGrabbed->m_pSpeedupTile[y * pGrabbed->m_Width + x].m_Force; + m_pEditor->m_SpeedupMaxSpeed = pGrabbed->m_pSpeedupTile[y * pGrabbed->m_Width + x].m_MaxSpeed; } } pGrabbed->m_SpeedupForce = m_pEditor->m_SpeedupForce; @@ -291,7 +287,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -302,7 +298,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); // copy the switch data if(!m_pEditor->Input()->KeyIsPressed(KEY_SPACE)) @@ -326,8 +322,8 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_pSwitchTile[y * pGrabbed->m_Width + x].m_Type == TILE_ALLOW_TELE_GUN || pGrabbed->m_pSwitchTile[y * pGrabbed->m_Width + x].m_Type == TILE_ALLOW_BLUE_TELE_GUN) { - m_pEditor->m_SwitchNum = pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Number; - m_pEditor->m_SwitchDelay = pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Delay; + m_pEditor->m_SwitchNum = pGrabbed->m_pSwitchTile[y * pGrabbed->m_Width + x].m_Number; + m_pEditor->m_SwitchDelay = pGrabbed->m_pSwitchTile[y * pGrabbed->m_Width + x].m_Delay; } } pGrabbed->m_SwitchNumber = m_pEditor->m_SwitchNum; @@ -342,7 +338,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -353,7 +349,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); // copy the tiles if(!m_pEditor->Input()->KeyIsPressed(KEY_SPACE)) @@ -363,7 +359,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_pTuneTile[y * pGrabbed->m_Width + x] = ((CLayerTune *)this)->m_pTuneTile[(r.y + y) * m_Width + (r.x + x)]; if(pGrabbed->m_pTuneTile[y * pGrabbed->m_Width + x].m_Type == TILE_TUNE) { - m_pEditor->m_TuningNum = pGrabbed->m_pTuneTile[y*pGrabbed->m_Width+x].m_Number; + m_pEditor->m_TuningNum = pGrabbed->m_pTuneTile[y * pGrabbed->m_Width + x].m_Number; } } pGrabbed->m_TuningNumber = m_pEditor->m_TuningNum; @@ -376,7 +372,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -387,7 +383,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); } else @@ -397,7 +393,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; - if (m_pEditor->m_BrushColorEnabled) + if(m_pEditor->m_BrushColorEnabled) { pGrabbed->m_Color = m_Color; pGrabbed->m_Color.a = 255; @@ -408,7 +404,7 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) - pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = GetTile(r.x+x, r.y+y); + pGrabbed->m_pTiles[y * pGrabbed->m_Width + x] = GetTile(r.x + x, r.y + y); str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); } @@ -427,7 +423,7 @@ void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); - CLayerTiles *pLt = static_cast(pBrush); + CLayerTiles *pLt = static_cast(pBrush); bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); @@ -435,8 +431,8 @@ void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { for(int x = 0; x < w; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; @@ -458,9 +454,9 @@ void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) continue; if(Empty) - m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; else - SetTile(fx, fy, pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]); + SetTile(fx, fy, pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]); } } FlagModified(sx, sy, w, h); @@ -481,10 +477,10 @@ void CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy) for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; - if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; bool HasTile = GetTile(fx, fy).m_Index; @@ -512,11 +508,11 @@ void CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy) void CLayerTiles::BrushFlipX() { for(int y = 0; y < m_Height; y++) - for(int x = 0; x < m_Width/2; x++) + for(int x = 0; x < m_Width / 2; x++) { - CTile Tmp = m_pTiles[y*m_Width+x]; - m_pTiles[y*m_Width+x] = m_pTiles[y*m_Width+m_Width-1-x]; - m_pTiles[y*m_Width+m_Width-1-x] = Tmp; + CTile Tmp = m_pTiles[y * m_Width + x]; + m_pTiles[y * m_Width + x] = m_pTiles[y * m_Width + m_Width - 1 - x]; + m_pTiles[y * m_Width + m_Width - 1 - x] = Tmp; } if(m_Tele || m_Speedup || m_Tune) @@ -525,20 +521,20 @@ void CLayerTiles::BrushFlipX() bool Rotate = !(m_Game || m_Front || m_Switch) || m_pEditor->m_AllowPlaceUnusedTiles; for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - if(!Rotate && !IsRotatableTile(m_pTiles[y*m_Width+x].m_Index)) - m_pTiles[y*m_Width+x].m_Flags = 0; + if(!Rotate && !IsRotatableTile(m_pTiles[y * m_Width + x].m_Index)) + m_pTiles[y * m_Width + x].m_Flags = 0; else - m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP; + m_pTiles[y * m_Width + x].m_Flags ^= m_pTiles[y * m_Width + x].m_Flags & TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP; } void CLayerTiles::BrushFlipY() { - for(int y = 0; y < m_Height/2; y++) + for(int y = 0; y < m_Height / 2; y++) for(int x = 0; x < m_Width; x++) { - CTile Tmp = m_pTiles[y*m_Width+x]; - m_pTiles[y*m_Width+x] = m_pTiles[(m_Height-1-y)*m_Width+x]; - m_pTiles[(m_Height-1-y)*m_Width+x] = Tmp; + CTile Tmp = m_pTiles[y * m_Width + x]; + m_pTiles[y * m_Width + x] = m_pTiles[(m_Height - 1 - y) * m_Width + x]; + m_pTiles[(m_Height - 1 - y) * m_Width + x] = Tmp; } if(m_Tele || m_Speedup || m_Tune) @@ -547,35 +543,35 @@ void CLayerTiles::BrushFlipY() bool Rotate = !(m_Game || m_Front || m_Switch) || m_pEditor->m_AllowPlaceUnusedTiles; for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) - if(!Rotate && !IsRotatableTile(m_pTiles[y*m_Width+x].m_Index)) - m_pTiles[y*m_Width+x].m_Flags = 0; + if(!Rotate && !IsRotatableTile(m_pTiles[y * m_Width + x].m_Index)) + m_pTiles[y * m_Width + x].m_Flags = 0; else - m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP; + m_pTiles[y * m_Width + x].m_Flags ^= m_pTiles[y * m_Width + x].m_Flags & TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP; } void CLayerTiles::BrushRotate(float Amount) { - int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + int Rotation = (round_to_int(360.0f * Amount / (pi * 2)) / 90) % 4; // 0=0°, 1=90°, 2=180°, 3=270° if(Rotation < 0) - Rotation +=4; + Rotation += 4; if(Rotation == 1 || Rotation == 3) { // 90° rotation - CTile *pTempData = new CTile[m_Width*m_Height]; - mem_copy(pTempData, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTile *pTempData = new CTile[m_Width * m_Height]; + mem_copy(pTempData, m_pTiles, m_Width * m_Height * sizeof(CTile)); CTile *pDst = m_pTiles; bool Rotate = !(m_Game || m_Front) || m_pEditor->m_AllowPlaceUnusedTiles; for(int x = 0; x < m_Width; ++x) - for(int y = m_Height-1; y >= 0; --y, ++pDst) + for(int y = m_Height - 1; y >= 0; --y, ++pDst) { - *pDst = pTempData[y*m_Width+x]; + *pDst = pTempData[y * m_Width + x]; if(!Rotate && !IsRotatableTile(pDst->m_Index)) pDst->m_Flags = 0; else { - if(pDst->m_Flags&TILEFLAG_ROTATE) - pDst->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP); + if(pDst->m_Flags & TILEFLAG_ROTATE) + pDst->m_Flags ^= (TILEFLAG_HFLIP | TILEFLAG_VFLIP); pDst->m_Flags ^= TILEFLAG_ROTATE; } } @@ -595,15 +591,15 @@ void CLayerTiles::BrushRotate(float Amount) void CLayerTiles::Resize(int NewW, int NewH) { - CTile *pNewData = new CTile[NewW*NewH]; - mem_zero(pNewData, NewW*NewH*sizeof(CTile)); + CTile *pNewData = new CTile[NewW * NewH]; + mem_zero(pNewData, NewW * NewH * sizeof(CTile)); // copy old data for(int y = 0; y < minimum(NewH, m_Height); y++) - mem_copy(&pNewData[y*NewW], &m_pTiles[y*m_Width], minimum(m_Width, NewW)*sizeof(CTile)); + mem_copy(&pNewData[y * NewW], &m_pTiles[y * m_Width], minimum(m_Width, NewW) * sizeof(CTile)); // replace old - delete [] m_pTiles; + delete[] m_pTiles; m_pTiles = pNewData; m_Width = NewW; m_Height = NewH; @@ -636,45 +632,45 @@ void CLayerTiles::Shift(int Direction) switch(Direction) { case 1: + { + // left + for(int y = 0; y < m_Height; ++y) { - // left - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTiles[y*m_Width], &m_pTiles[y*m_Width+o], (m_Width-o)*sizeof(CTile)); - mem_zero(&m_pTiles[y*m_Width + (m_Width-o)], o*sizeof(CTile)); - } + mem_move(&m_pTiles[y * m_Width], &m_pTiles[y * m_Width + o], (m_Width - o) * sizeof(CTile)); + mem_zero(&m_pTiles[y * m_Width + (m_Width - o)], o * sizeof(CTile)); } - break; + } + break; case 2: + { + // right + for(int y = 0; y < m_Height; ++y) { - // right - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTiles[y*m_Width+o], &m_pTiles[y*m_Width], (m_Width-o)*sizeof(CTile)); - mem_zero(&m_pTiles[y*m_Width], o*sizeof(CTile)); - } + mem_move(&m_pTiles[y * m_Width + o], &m_pTiles[y * m_Width], (m_Width - o) * sizeof(CTile)); + mem_zero(&m_pTiles[y * m_Width], o * sizeof(CTile)); } - break; + } + break; case 4: + { + // up + for(int y = 0; y < m_Height - o; ++y) { - // up - for(int y = 0; y < m_Height-o; ++y) - { - mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y+o)*m_Width], m_Width*sizeof(CTile)); - mem_zero(&m_pTiles[(y+o)*m_Width], m_Width*sizeof(CTile)); - } + mem_copy(&m_pTiles[y * m_Width], &m_pTiles[(y + o) * m_Width], m_Width * sizeof(CTile)); + mem_zero(&m_pTiles[(y + o) * m_Width], m_Width * sizeof(CTile)); } - break; + } + break; case 8: + { + // down + for(int y = m_Height - 1; y >= o; --y) { - // down - for(int y = m_Height-1; y >= o; --y) - { - mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y-o)*m_Width], m_Width*sizeof(CTile)); - mem_zero(&m_pTiles[(y-o)*m_Width], m_Width*sizeof(CTile)); - } + mem_copy(&m_pTiles[y * m_Width], &m_pTiles[(y - o) * m_Width], m_Width * sizeof(CTile)); + mem_zero(&m_pTiles[(y - o) * m_Width], m_Width * sizeof(CTile)); } } + } } void CLayerTiles::ShowInfo() @@ -684,26 +680,26 @@ void CLayerTiles::ShowInfo() Graphics()->TextureSet(m_pEditor->Client()->GetDebugFont()); Graphics()->QuadsBegin(); - int StartY = maximum(0, (int)(ScreenY0/32.0f)-1); - int StartX = maximum(0, (int)(ScreenX0/32.0f)-1); - int EndY = minimum((int)(ScreenY1/32.0f)+1, m_Height); - int EndX = minimum((int)(ScreenX1/32.0f)+1, m_Width); + int StartY = maximum(0, (int)(ScreenY0 / 32.0f) - 1); + int StartX = maximum(0, (int)(ScreenX0 / 32.0f) - 1); + int EndY = minimum((int)(ScreenY1 / 32.0f) + 1, m_Height); + int EndX = minimum((int)(ScreenX1 / 32.0f) + 1, m_Width); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) { - int c = x + y*m_Width; + int c = x + y * m_Width; if(m_pTiles[c].m_Index) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%i", m_pTiles[c].m_Index); - m_pEditor->Graphics()->QuadsText(x*32, y*32, 16.0f, aBuf); + m_pEditor->Graphics()->QuadsText(x * 32, y * 32, 16.0f, aBuf); - char aFlags[4] = { m_pTiles[c].m_Flags&TILEFLAG_VFLIP ? 'V' : ' ', - m_pTiles[c].m_Flags&TILEFLAG_HFLIP ? 'H' : ' ', - m_pTiles[c].m_Flags&TILEFLAG_ROTATE? 'R' : ' ', - 0}; - m_pEditor->Graphics()->QuadsText(x*32, y*32+16, 16.0f, aFlags); + char aFlags[4] = {m_pTiles[c].m_Flags & TILEFLAG_VFLIP ? 'V' : ' ', + m_pTiles[c].m_Flags & TILEFLAG_HFLIP ? 'H' : ' ', + m_pTiles[c].m_Flags & TILEFLAG_ROTATE ? 'R' : ' ', + 0}; + m_pEditor->Graphics()->QuadsText(x * 32, y * 32 + 16, 16.0f, aFlags); } x += m_pTiles[c].m_Skip; } @@ -716,14 +712,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) { CUIRect Button; - bool IsGameLayer = ( - m_pEditor->m_Map.m_pGameLayer == this - || m_pEditor->m_Map.m_pTeleLayer == this - || m_pEditor->m_Map.m_pSpeedupLayer == this - || m_pEditor->m_Map.m_pFrontLayer == this - || m_pEditor->m_Map.m_pSwitchLayer == this - || m_pEditor->m_Map.m_pTuneLayer == this - ); + bool IsGameLayer = (m_pEditor->m_Map.m_pGameLayer == this || m_pEditor->m_Map.m_pTeleLayer == this || m_pEditor->m_Map.m_pSpeedupLayer == this || m_pEditor->m_Map.m_pFrontLayer == this || m_pEditor->m_Map.m_pSwitchLayer == this || m_pEditor->m_Map.m_pTuneLayer == this); CLayerGroup *pGroup = m_pEditor->m_Map.m_lGroups[m_pEditor->m_SelectedGroup]; @@ -738,28 +727,28 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) int Result = m_pEditor->PopupSelectGameTileOpResult(); switch(Result) { - case 4: - Result = TILE_THROUGH_CUT; - break; - case 5: - Result = TILE_FREEZE; - break; - case 6: - Result = TILE_UNFREEZE; - break; - case 7: - Result = TILE_DFREEZE; - break; - case 8: - Result = TILE_DUNFREEZE; - break; - case 9: - Result = TILE_TELECHECKIN; - break; - case 10: - Result = TILE_TELECHECKINEVIL; - default: - break; + case 4: + Result = TILE_THROUGH_CUT; + break; + case 5: + Result = TILE_FREEZE; + break; + case 6: + Result = TILE_UNFREEZE; + break; + case 7: + Result = TILE_DFREEZE; + break; + case 8: + Result = TILE_DUNFREEZE; + break; + case 9: + Result = TILE_TELECHECKIN; + break; + case 10: + Result = TILE_TELECHECKINEVIL; + default: + break; } if(Result > -1) { @@ -807,9 +796,9 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) for(int x = OffsetX < 0 ? -OffsetX : 0; x < m_Width; x++) if(GetTile(x, y).m_Index) { - pTLayer->m_pTiles[(y+OffsetY)*pTLayer->m_Width+x+OffsetX].m_Index = TILE_AIR+Result; - pTLayer->m_pTeleTile[(y+OffsetY)*pTLayer->m_Width+x+OffsetX].m_Number = 1; - pTLayer->m_pTeleTile[(y+OffsetY)*pTLayer->m_Width+x+OffsetX].m_Type = TILE_AIR+Result; + pTLayer->m_pTiles[(y + OffsetY) * pTLayer->m_Width + x + OffsetX].m_Index = TILE_AIR + Result; + pTLayer->m_pTeleTile[(y + OffsetY) * pTLayer->m_Width + x + OffsetX].m_Number = 1; + pTLayer->m_pTeleTile[(y + OffsetY) * pTLayer->m_Width + x + OffsetX].m_Type = TILE_AIR + Result; } } @@ -826,7 +815,8 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) static int s_AutoMapperButtonAuto = 0; pToolBox->HSplitBottom(2.0f, pToolBox, 0); pToolBox->HSplitBottom(12.0f, pToolBox, &Button); - if(m_Seed != 0) { + if(m_Seed != 0) + { CUIRect ButtonAuto; Button.VSplitRight(16.0f, &Button, &ButtonAuto); Button.VSplitRight(2.0f, &Button, 0); @@ -846,7 +836,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) enum { - PROP_WIDTH=0, + PROP_WIDTH = 0, PROP_HEIGHT, PROP_SHIFT, PROP_SHIFT_BY, @@ -860,9 +850,9 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) }; int Color = 0; - Color |= m_Color.r<<24; - Color |= m_Color.g<<16; - Color |= m_Color.b<<8; + Color |= m_Color.r << 24; + Color |= m_Color.g << 16; + Color |= m_Color.b << 8; Color |= m_Color.a; CProperty aProps[] = { @@ -872,7 +862,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) {"Shift by", m_pEditor->m_ShiftBy, PROPTYPE_INT_SCROLL, 1, 100000}, {"Image", m_Image, PROPTYPE_IMAGE, 0, 0}, {"Color", Color, PROPTYPE_COLOR, 0, 0}, - {"Color Env", m_ColorEnv+1, PROPTYPE_ENVELOPE, 0, 0}, + {"Color Env", m_ColorEnv + 1, PROPTYPE_ENVELOPE, 0, 0}, {"Color TO", m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Auto Rule", m_AutoMapperConfig, PROPTYPE_AUTOMAPPER, m_Image, 0}, {"Seed", m_Seed, PROPTYPE_INT_SCROLL, 0, 1000000000}, @@ -922,14 +912,14 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) else if(Prop == PROP_IMAGE) { m_Image = NewVal; - if (NewVal == -1) + if(NewVal == -1) { m_Texture = IGraphics::CTextureHandle(); m_Image = -1; } else { - m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); + m_Image = NewVal % m_pEditor->m_Map.m_lImages.size(); m_AutoMapperConfig = -1; if(m_pEditor->m_Map.m_lImages[m_Image]->m_Width % 16 != 0 || m_pEditor->m_Map.m_lImages[m_Image]->m_Height % 16 != 0) @@ -944,15 +934,15 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) } else if(Prop == PROP_COLOR) { - m_Color.r = (NewVal>>24)&0xff; - m_Color.g = (NewVal>>16)&0xff; - m_Color.b = (NewVal>>8)&0xff; - m_Color.a = NewVal&0xff; + m_Color.r = (NewVal >> 24) & 0xff; + m_Color.g = (NewVal >> 16) & 0xff; + m_Color.b = (NewVal >> 8) & 0xff; + m_Color.a = NewVal & 0xff; } if(Prop == PROP_COLOR_ENV) { - int Index = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1); - int Step = (Index-m_ColorEnv)%2; + int Index = clamp(NewVal - 1, -1, m_pEditor->m_Map.m_lEnvelopes.size() - 1); + int Step = (Index - m_ColorEnv) % 2; if(Step != 0) { for(; Index >= -1 && Index < m_pEditor->m_Map.m_lEnvelopes.size(); Index += Step) @@ -969,12 +959,13 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) m_Seed = NewVal; else if(Prop == PROP_AUTOMAPPER) { - if (m_Image >= 0 && m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.ConfigNamesNum() > 0 && NewVal >= 0) - m_AutoMapperConfig = NewVal%m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.ConfigNamesNum(); + if(m_Image >= 0 && m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.ConfigNamesNum() > 0 && NewVal >= 0) + m_AutoMapperConfig = NewVal % m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.ConfigNamesNum(); else m_AutoMapperConfig = -1; } - if(Prop != -1) { + if(Prop != -1) + { FlagModified(0, 0, m_Width, m_Height); } @@ -991,23 +982,22 @@ int CLayerTiles::RenderCommonProperties(SCommonPropState &State, CEditor *pEdito if(pEditor->DoButton_Editor(&s_CommitButton, "Commit", 0, &Commit, 0, "Applies the changes")) { dbg_msg("editor", "applying changes"); - for_each(pLayers.all(), [&State](CLayerTiles *pLayer){ + for_each(pLayers.all(), [&State](CLayerTiles *pLayer) { pLayer->Resize(State.Width, State.Height); - pLayer->m_Color.r = (State.Color>>24)&0xff; - pLayer->m_Color.g = (State.Color>>16)&0xff; - pLayer->m_Color.b = (State.Color>>8)&0xff; - pLayer->m_Color.a = State.Color&0xff; + pLayer->m_Color.r = (State.Color >> 24) & 0xff; + pLayer->m_Color.g = (State.Color >> 16) & 0xff; + pLayer->m_Color.b = (State.Color >> 8) & 0xff; + pLayer->m_Color.a = State.Color & 0xff; pLayer->FlagModified(0, 0, pLayer->m_Width, pLayer->m_Height); }); State.Modified = false; } - } else { - for_each(pLayers.all(), [&State](CLayerTiles *pLayer){ + for_each(pLayers.all(), [&State](CLayerTiles *pLayer) { if(pLayer->m_Width > State.Width) State.Width = pLayer->m_Width; if(pLayer->m_Height > State.Height) @@ -1028,7 +1018,7 @@ int CLayerTiles::RenderCommonProperties(SCommonPropState &State, CEditor *pEdito enum { - PROP_WIDTH=0, + PROP_WIDTH = 0, PROP_HEIGHT, PROP_SHIFT, PROP_SHIFT_BY, @@ -1071,7 +1061,7 @@ int CLayerTiles::RenderCommonProperties(SCommonPropState &State, CEditor *pEdito } else if(Prop == PROP_SHIFT) { - for_each(pLayers.all(), [NewVal](CLayerTiles *pLayer){ + for_each(pLayers.all(), [NewVal](CLayerTiles *pLayer) { pLayer->Shift(NewVal); }); } @@ -1093,12 +1083,12 @@ int CLayerTiles::RenderCommonProperties(SCommonPropState &State, CEditor *pEdito void CLayerTiles::FlagModified(int x, int y, int w, int h) { m_pEditor->m_Map.m_Modified = true; - if (m_Seed != 0 && m_AutoMapperConfig != -1 && m_AutoAutoMap) { + if(m_Seed != 0 && m_AutoMapperConfig != -1 && m_AutoAutoMap) + { m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.ProceedLocalized(this, m_AutoMapperConfig, m_Seed, x, y, w, h); } } - void CLayerTiles::ModifyImageIndex(INDEX_MODIFY_FUNC Func) { Func(&m_Image); @@ -1109,15 +1099,15 @@ void CLayerTiles::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) Func(&m_ColorEnv); } -CLayerTele::CLayerTele(int w, int h) -: CLayerTiles(w, h) +CLayerTele::CLayerTele(int w, int h) : + CLayerTiles(w, h) { //m_Type = LAYERTYPE_TELE; str_copy(m_aName, "Tele", sizeof(m_aName)); m_Tele = 1; - m_pTeleTile = new CTeleTile[w*h]; - mem_zero(m_pTeleTile, w*h*sizeof(CTeleTile)); + m_pTeleTile = new CTeleTile[w * h]; + mem_zero(m_pTeleTile, w * h * sizeof(CTeleTile)); } CLayerTele::~CLayerTele() @@ -1128,15 +1118,15 @@ CLayerTele::~CLayerTele() void CLayerTele::Resize(int NewW, int NewH) { // resize tele data - CTeleTile *pNewTeleData = new CTeleTile[NewW*NewH]; - mem_zero(pNewTeleData, NewW*NewH*sizeof(CTeleTile)); + CTeleTile *pNewTeleData = new CTeleTile[NewW * NewH]; + mem_zero(pNewTeleData, NewW * NewH * sizeof(CTeleTile)); // copy old data for(int y = 0; y < minimum(NewH, m_Height); y++) - mem_copy(&pNewTeleData[y*NewW], &m_pTeleTile[y*m_Width], minimum(m_Width, NewW)*sizeof(CTeleTile)); + mem_copy(&pNewTeleData[y * NewW], &m_pTeleTile[y * m_Width], minimum(m_Width, NewW) * sizeof(CTeleTile)); // replace old - delete [] m_pTeleTile; + delete[] m_pTeleTile; m_pTeleTile = pNewTeleData; // resize tile data @@ -1155,45 +1145,45 @@ void CLayerTele::Shift(int Direction) switch(Direction) { case 1: + { + // left + for(int y = 0; y < m_Height; ++y) { - // left - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTeleTile[y*m_Width], &m_pTeleTile[y*m_Width+o], (m_Width-o)*sizeof(CTeleTile)); - mem_zero(&m_pTeleTile[y*m_Width + (m_Width-o)], o*sizeof(CTeleTile)); - } + mem_move(&m_pTeleTile[y * m_Width], &m_pTeleTile[y * m_Width + o], (m_Width - o) * sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[y * m_Width + (m_Width - o)], o * sizeof(CTeleTile)); } - break; + } + break; case 2: + { + // right + for(int y = 0; y < m_Height; ++y) { - // right - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTeleTile[y*m_Width+o], &m_pTeleTile[y*m_Width], (m_Width-o)*sizeof(CTeleTile)); - mem_zero(&m_pTeleTile[y*m_Width], o*sizeof(CTeleTile)); - } + mem_move(&m_pTeleTile[y * m_Width + o], &m_pTeleTile[y * m_Width], (m_Width - o) * sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[y * m_Width], o * sizeof(CTeleTile)); } - break; + } + break; case 4: + { + // up + for(int y = 0; y < m_Height - o; ++y) { - // up - for(int y = 0; y < m_Height-o; ++y) - { - mem_copy(&m_pTeleTile[y*m_Width], &m_pTeleTile[(y+o)*m_Width], m_Width*sizeof(CTeleTile)); - mem_zero(&m_pTeleTile[(y+o)*m_Width], m_Width*sizeof(CTeleTile)); - } + mem_copy(&m_pTeleTile[y * m_Width], &m_pTeleTile[(y + o) * m_Width], m_Width * sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[(y + o) * m_Width], m_Width * sizeof(CTeleTile)); } - break; + } + break; case 8: + { + // down + for(int y = m_Height - 1; y >= o; --y) { - // down - for(int y = m_Height-1; y >= o; --y) - { - mem_copy(&m_pTeleTile[y*m_Width], &m_pTeleTile[(y-o)*m_Width], m_Width*sizeof(CTeleTile)); - mem_zero(&m_pTeleTile[(y-o)*m_Width], m_Width*sizeof(CTeleTile)); - } + mem_copy(&m_pTeleTile[y * m_Width], &m_pTeleTile[(y - o) * m_Width], m_Width * sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[(y - o) * m_Width], m_Width * sizeof(CTeleTile)); } } + } } bool CLayerTele::IsEmpty(CLayerTiles *pLayer) @@ -1222,44 +1212,44 @@ void CLayerTele::BrushDraw(CLayer *pBrush, float wx, float wy) for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; - if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(IsValidTeleTile(l->m_pTiles[y*l->m_Width+x].m_Index)) + if(IsValidTeleTile(l->m_pTiles[y * l->m_Width + x].m_Index)) { if(m_pEditor->m_TeleNumber != l->m_TeleNum) { - m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + m_pTeleTile[fy * m_Width + fx].m_Number = m_pEditor->m_TeleNumber; } - else if(l->m_pTeleTile[y*l->m_Width+x].m_Number) - m_pTeleTile[fy*m_Width+fx].m_Number = l->m_pTeleTile[y*l->m_Width+x].m_Number; + else if(l->m_pTeleTile[y * l->m_Width + x].m_Number) + m_pTeleTile[fy * m_Width + fx].m_Number = l->m_pTeleTile[y * l->m_Width + x].m_Number; else { if(!m_pEditor->m_TeleNumber) { - m_pTeleTile[fy*m_Width+fx].m_Number = 0; - m_pTeleTile[fy*m_Width+fx].m_Type = 0; - m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pTeleTile[fy * m_Width + fx].m_Number = 0; + m_pTeleTile[fy * m_Width + fx].m_Type = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; continue; } else - m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + m_pTeleTile[fy * m_Width + fx].m_Number = m_pEditor->m_TeleNumber; } - m_pTeleTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTeleTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; } else { - m_pTeleTile[fy*m_Width+fx].m_Number = 0; - m_pTeleTile[fy*m_Width+fx].m_Type = 0; - m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pTeleTile[fy * m_Width + fx].m_Number = 0; + m_pTeleTile[fy * m_Width + fx].m_Type = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; } } FlagModified(sx, sy, l->m_Width, l->m_Height); @@ -1270,11 +1260,11 @@ void CLayerTele::BrushFlipX() CLayerTiles::BrushFlipX(); for(int y = 0; y < m_Height; y++) - for(int x = 0; x < m_Width/2; x++) + for(int x = 0; x < m_Width / 2; x++) { - CTeleTile Tmp = m_pTeleTile[y*m_Width+x]; - m_pTeleTile[y*m_Width+x] = m_pTeleTile[y*m_Width+m_Width-1-x]; - m_pTeleTile[y*m_Width+m_Width-1-x] = Tmp; + CTeleTile Tmp = m_pTeleTile[y * m_Width + x]; + m_pTeleTile[y * m_Width + x] = m_pTeleTile[y * m_Width + m_Width - 1 - x]; + m_pTeleTile[y * m_Width + m_Width - 1 - x] = Tmp; } } @@ -1282,35 +1272,35 @@ void CLayerTele::BrushFlipY() { CLayerTiles::BrushFlipY(); - for(int y = 0; y < m_Height/2; y++) + for(int y = 0; y < m_Height / 2; y++) for(int x = 0; x < m_Width; x++) { - CTeleTile Tmp = m_pTeleTile[y*m_Width+x]; - m_pTeleTile[y*m_Width+x] = m_pTeleTile[(m_Height-1-y)*m_Width+x]; - m_pTeleTile[(m_Height-1-y)*m_Width+x] = Tmp; + CTeleTile Tmp = m_pTeleTile[y * m_Width + x]; + m_pTeleTile[y * m_Width + x] = m_pTeleTile[(m_Height - 1 - y) * m_Width + x]; + m_pTeleTile[(m_Height - 1 - y) * m_Width + x] = Tmp; } } void CLayerTele::BrushRotate(float Amount) { - int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + int Rotation = (round_to_int(360.0f * Amount / (pi * 2)) / 90) % 4; // 0=0°, 1=90°, 2=180°, 3=270° if(Rotation < 0) - Rotation +=4; + Rotation += 4; if(Rotation == 1 || Rotation == 3) { // 90° rotation - CTeleTile *pTempData1 = new CTeleTile[m_Width*m_Height]; - CTile *pTempData2 = new CTile[m_Width*m_Height]; - mem_copy(pTempData1, m_pTeleTile, m_Width*m_Height*sizeof(CTeleTile)); - mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTeleTile *pTempData1 = new CTeleTile[m_Width * m_Height]; + CTile *pTempData2 = new CTile[m_Width * m_Height]; + mem_copy(pTempData1, m_pTeleTile, m_Width * m_Height * sizeof(CTeleTile)); + mem_copy(pTempData2, m_pTiles, m_Width * m_Height * sizeof(CTile)); CTeleTile *pDst1 = m_pTeleTile; CTile *pDst2 = m_pTiles; for(int x = 0; x < m_Width; ++x) - for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + for(int y = m_Height - 1; y >= 0; --y, ++pDst1, ++pDst2) { - *pDst1 = pTempData1[y*m_Width+x]; - *pDst2 = pTempData2[y*m_Width+x]; + *pDst1 = pTempData1[y * m_Width + x]; + *pDst2 = pTempData2[y * m_Width + x]; } int Temp = m_Width; @@ -1341,7 +1331,7 @@ void CLayerTele::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); - CLayerTele *pLt = static_cast(pBrush); + CLayerTele *pLt = static_cast(pBrush); bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); @@ -1349,8 +1339,8 @@ void CLayerTele::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { for(int x = 0; x < w; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; @@ -1358,22 +1348,22 @@ void CLayerTele::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(Empty || !IsValidTeleTile((pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index)) + if(Empty || !IsValidTeleTile((pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]).m_Index)) { - m_pTiles[fy*m_Width+fx].m_Index = 0; - m_pTeleTile[fy*m_Width+fx].m_Type = 0; - m_pTeleTile[fy*m_Width+fx].m_Number = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; + m_pTeleTile[fy * m_Width + fx].m_Type = 0; + m_pTeleTile[fy * m_Width + fx].m_Number = 0; } else { - m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; - if(pLt->m_Tele && m_pTiles[fy*m_Width+fx].m_Index > 0) + m_pTiles[fy * m_Width + fx] = pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]; + if(pLt->m_Tele && m_pTiles[fy * m_Width + fx].m_Index > 0) { - if((!pLt->m_pTeleTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number && m_pEditor->m_TeleNumber) || m_pEditor->m_TeleNumber != pLt->m_TeleNum) - m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + if((!pLt->m_pTeleTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number && m_pEditor->m_TeleNumber) || m_pEditor->m_TeleNumber != pLt->m_TeleNum) + m_pTeleTile[fy * m_Width + fx].m_Number = m_pEditor->m_TeleNumber; else - m_pTeleTile[fy*m_Width+fx].m_Number = pLt->m_pTeleTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; - m_pTeleTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + m_pTeleTile[fy * m_Width + fx].m_Number = pLt->m_pTeleTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number; + m_pTeleTile[fy * m_Width + fx].m_Type = m_pTiles[fy * m_Width + fx].m_Index; } } } @@ -1387,7 +1377,7 @@ bool CLayerTele::ContainsElementWithId(int Id) { for(int x = 0; x < m_Width; ++x) { - if(m_pTeleTile[y*m_Width+x].m_Number == Id) + if(m_pTeleTile[y * m_Width + x].m_Number == Id) { return true; } @@ -1397,15 +1387,15 @@ bool CLayerTele::ContainsElementWithId(int Id) return false; } -CLayerSpeedup::CLayerSpeedup(int w, int h) -: CLayerTiles(w, h) +CLayerSpeedup::CLayerSpeedup(int w, int h) : + CLayerTiles(w, h) { //m_Type = LAYERTYPE_SPEEDUP; str_copy(m_aName, "Speedup", sizeof(m_aName)); m_Speedup = 1; - m_pSpeedupTile = new CSpeedupTile[w*h]; - mem_zero(m_pSpeedupTile, w*h*sizeof(CSpeedupTile)); + m_pSpeedupTile = new CSpeedupTile[w * h]; + mem_zero(m_pSpeedupTile, w * h * sizeof(CSpeedupTile)); } CLayerSpeedup::~CLayerSpeedup() @@ -1416,15 +1406,15 @@ CLayerSpeedup::~CLayerSpeedup() void CLayerSpeedup::Resize(int NewW, int NewH) { // resize speedup data - CSpeedupTile *pNewSpeedupData = new CSpeedupTile[NewW*NewH]; - mem_zero(pNewSpeedupData, NewW*NewH*sizeof(CSpeedupTile)); + CSpeedupTile *pNewSpeedupData = new CSpeedupTile[NewW * NewH]; + mem_zero(pNewSpeedupData, NewW * NewH * sizeof(CSpeedupTile)); // copy old data for(int y = 0; y < minimum(NewH, m_Height); y++) - mem_copy(&pNewSpeedupData[y*NewW], &m_pSpeedupTile[y*m_Width], minimum(m_Width, NewW)*sizeof(CSpeedupTile)); + mem_copy(&pNewSpeedupData[y * NewW], &m_pSpeedupTile[y * m_Width], minimum(m_Width, NewW) * sizeof(CSpeedupTile)); // replace old - delete [] m_pSpeedupTile; + delete[] m_pSpeedupTile; m_pSpeedupTile = pNewSpeedupData; // resize tile data @@ -1443,45 +1433,45 @@ void CLayerSpeedup::Shift(int Direction) switch(Direction) { case 1: + { + // left + for(int y = 0; y < m_Height; ++y) { - // left - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[y*m_Width+o], (m_Width-o)*sizeof(CSpeedupTile)); - mem_zero(&m_pSpeedupTile[y*m_Width + (m_Width-o)], o*sizeof(CSpeedupTile)); - } + mem_move(&m_pSpeedupTile[y * m_Width], &m_pSpeedupTile[y * m_Width + o], (m_Width - o) * sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[y * m_Width + (m_Width - o)], o * sizeof(CSpeedupTile)); } - break; + } + break; case 2: + { + // right + for(int y = 0; y < m_Height; ++y) { - // right - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pSpeedupTile[y*m_Width+o], &m_pSpeedupTile[y*m_Width], (m_Width-o)*sizeof(CSpeedupTile)); - mem_zero(&m_pSpeedupTile[y*m_Width], o*sizeof(CSpeedupTile)); - } + mem_move(&m_pSpeedupTile[y * m_Width + o], &m_pSpeedupTile[y * m_Width], (m_Width - o) * sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[y * m_Width], o * sizeof(CSpeedupTile)); } - break; + } + break; case 4: + { + // up + for(int y = 0; y < m_Height - o; ++y) { - // up - for(int y = 0; y < m_Height-o; ++y) - { - mem_copy(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[(y+o)*m_Width], m_Width*sizeof(CSpeedupTile)); - mem_zero(&m_pSpeedupTile[(y+o)*m_Width], m_Width*sizeof(CSpeedupTile)); - } + mem_copy(&m_pSpeedupTile[y * m_Width], &m_pSpeedupTile[(y + o) * m_Width], m_Width * sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[(y + o) * m_Width], m_Width * sizeof(CSpeedupTile)); } - break; + } + break; case 8: + { + // down + for(int y = m_Height - 1; y >= o; --y) { - // down - for(int y = m_Height-1; y >= o; --y) - { - mem_copy(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[(y-o)*m_Width], m_Width*sizeof(CSpeedupTile)); - mem_zero(&m_pSpeedupTile[(y-o)*m_Width], m_Width*sizeof(CSpeedupTile)); - } + mem_copy(&m_pSpeedupTile[y * m_Width], &m_pSpeedupTile[(y - o) * m_Width], m_Width * sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[(y - o) * m_Width], m_Width * sizeof(CSpeedupTile)); } } + } } bool CLayerSpeedup::IsEmpty(CLayerTiles *pLayer) @@ -1514,40 +1504,40 @@ void CLayerSpeedup::BrushDraw(CLayer *pBrush, float wx, float wy) for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; - if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(IsValidSpeedupTile(l->m_pTiles[y*l->m_Width+x].m_Index)) + if(IsValidSpeedupTile(l->m_pTiles[y * l->m_Width + x].m_Index)) { if(m_pEditor->m_SpeedupAngle != l->m_SpeedupAngle || m_pEditor->m_SpeedupForce != l->m_SpeedupForce || m_pEditor->m_SpeedupMaxSpeed != l->m_SpeedupMaxSpeed) { - m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; - m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; - m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; - m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pSpeedupTile[fy * m_Width + fx].m_Force = m_pEditor->m_SpeedupForce; + m_pSpeedupTile[fy * m_Width + fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + m_pSpeedupTile[fy * m_Width + fx].m_Angle = m_pEditor->m_SpeedupAngle; + m_pSpeedupTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; } - else if(l->m_pSpeedupTile[y*l->m_Width+x].m_Force) + else if(l->m_pSpeedupTile[y * l->m_Width + x].m_Force) { - m_pSpeedupTile[fy*m_Width+fx].m_Force = l->m_pSpeedupTile[y*l->m_Width+x].m_Force; - m_pSpeedupTile[fy*m_Width+fx].m_Angle = l->m_pSpeedupTile[y*l->m_Width+x].m_Angle; - m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = l->m_pSpeedupTile[y*l->m_Width+x].m_MaxSpeed; - m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pSpeedupTile[fy * m_Width + fx].m_Force = l->m_pSpeedupTile[y * l->m_Width + x].m_Force; + m_pSpeedupTile[fy * m_Width + fx].m_Angle = l->m_pSpeedupTile[y * l->m_Width + x].m_Angle; + m_pSpeedupTile[fy * m_Width + fx].m_MaxSpeed = l->m_pSpeedupTile[y * l->m_Width + x].m_MaxSpeed; + m_pSpeedupTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; } else if(m_pEditor->m_SpeedupForce) { - m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; - m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; - m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; - m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pSpeedupTile[fy * m_Width + fx].m_Force = m_pEditor->m_SpeedupForce; + m_pSpeedupTile[fy * m_Width + fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + m_pSpeedupTile[fy * m_Width + fx].m_Angle = m_pEditor->m_SpeedupAngle; + m_pSpeedupTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; } else { @@ -1575,11 +1565,11 @@ void CLayerSpeedup::BrushFlipX() CLayerTiles::BrushFlipX(); for(int y = 0; y < m_Height; y++) - for(int x = 0; x < m_Width/2; x++) + for(int x = 0; x < m_Width / 2; x++) { - CSpeedupTile Tmp = m_pSpeedupTile[y*m_Width+x]; - m_pSpeedupTile[y*m_Width+x] = m_pSpeedupTile[y*m_Width+m_Width-1-x]; - m_pSpeedupTile[y*m_Width+m_Width-1-x] = Tmp; + CSpeedupTile Tmp = m_pSpeedupTile[y * m_Width + x]; + m_pSpeedupTile[y * m_Width + x] = m_pSpeedupTile[y * m_Width + m_Width - 1 - x]; + m_pSpeedupTile[y * m_Width + m_Width - 1 - x] = Tmp; } } @@ -1587,35 +1577,35 @@ void CLayerSpeedup::BrushFlipY() { CLayerTiles::BrushFlipY(); - for(int y = 0; y < m_Height/2; y++) + for(int y = 0; y < m_Height / 2; y++) for(int x = 0; x < m_Width; x++) { - CSpeedupTile Tmp = m_pSpeedupTile[y*m_Width+x]; - m_pSpeedupTile[y*m_Width+x] = m_pSpeedupTile[(m_Height-1-y)*m_Width+x]; - m_pSpeedupTile[(m_Height-1-y)*m_Width+x] = Tmp; + CSpeedupTile Tmp = m_pSpeedupTile[y * m_Width + x]; + m_pSpeedupTile[y * m_Width + x] = m_pSpeedupTile[(m_Height - 1 - y) * m_Width + x]; + m_pSpeedupTile[(m_Height - 1 - y) * m_Width + x] = Tmp; } } void CLayerSpeedup::BrushRotate(float Amount) { - int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + int Rotation = (round_to_int(360.0f * Amount / (pi * 2)) / 90) % 4; // 0=0°, 1=90°, 2=180°, 3=270° if(Rotation < 0) - Rotation +=4; + Rotation += 4; if(Rotation == 1 || Rotation == 3) { // 90° rotation - CSpeedupTile *pTempData1 = new CSpeedupTile[m_Width*m_Height]; - CTile *pTempData2 = new CTile[m_Width*m_Height]; - mem_copy(pTempData1, m_pSpeedupTile, m_Width*m_Height*sizeof(CSpeedupTile)); - mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CSpeedupTile *pTempData1 = new CSpeedupTile[m_Width * m_Height]; + CTile *pTempData2 = new CTile[m_Width * m_Height]; + mem_copy(pTempData1, m_pSpeedupTile, m_Width * m_Height * sizeof(CSpeedupTile)); + mem_copy(pTempData2, m_pTiles, m_Width * m_Height * sizeof(CTile)); CSpeedupTile *pDst1 = m_pSpeedupTile; CTile *pDst2 = m_pTiles; for(int x = 0; x < m_Width; ++x) - for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + for(int y = m_Height - 1; y >= 0; --y, ++pDst1, ++pDst2) { - *pDst1 = pTempData1[y*m_Width+x]; - *pDst2 = pTempData2[y*m_Width+x]; + *pDst1 = pTempData1[y * m_Width + x]; + *pDst2 = pTempData2[y * m_Width + x]; } int Temp = m_Width; @@ -1646,7 +1636,7 @@ void CLayerSpeedup::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); - CLayerSpeedup *pLt = static_cast(pBrush); + CLayerSpeedup *pLt = static_cast(pBrush); bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); @@ -1654,8 +1644,8 @@ void CLayerSpeedup::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { for(int x = 0; x < w; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; @@ -1663,30 +1653,30 @@ void CLayerSpeedup::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(Empty || !IsValidSpeedupTile((pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index)) // no speed up tile chosen: reset + if(Empty || !IsValidSpeedupTile((pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]).m_Index)) // no speed up tile chosen: reset { - m_pTiles[fy*m_Width+fx].m_Index = 0; - m_pSpeedupTile[fy*m_Width+fx].m_Force = 0; - m_pSpeedupTile[fy*m_Width+fx].m_Angle = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; + m_pSpeedupTile[fy * m_Width + fx].m_Force = 0; + m_pSpeedupTile[fy * m_Width + fx].m_Angle = 0; } else { - m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; - if(pLt->m_Speedup && m_pTiles[fy*m_Width+fx].m_Index > 0) + m_pTiles[fy * m_Width + fx] = pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]; + if(pLt->m_Speedup && m_pTiles[fy * m_Width + fx].m_Index > 0) { - if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Force && m_pEditor->m_SpeedupForce) || m_pEditor->m_SpeedupForce != pLt->m_SpeedupForce) - m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; + if((!pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Force && m_pEditor->m_SpeedupForce) || m_pEditor->m_SpeedupForce != pLt->m_SpeedupForce) + m_pSpeedupTile[fy * m_Width + fx].m_Force = m_pEditor->m_SpeedupForce; else - m_pSpeedupTile[fy*m_Width+fx].m_Force = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Force; - if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Angle && m_pEditor->m_SpeedupAngle) || m_pEditor->m_SpeedupAngle != pLt->m_SpeedupAngle) - m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; + m_pSpeedupTile[fy * m_Width + fx].m_Force = pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Force; + if((!pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Angle && m_pEditor->m_SpeedupAngle) || m_pEditor->m_SpeedupAngle != pLt->m_SpeedupAngle) + m_pSpeedupTile[fy * m_Width + fx].m_Angle = m_pEditor->m_SpeedupAngle; else - m_pSpeedupTile[fy*m_Width+fx].m_Angle = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Angle; - if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_MaxSpeed && m_pEditor->m_SpeedupMaxSpeed) || m_pEditor->m_SpeedupMaxSpeed != pLt->m_SpeedupMaxSpeed) - m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + m_pSpeedupTile[fy * m_Width + fx].m_Angle = pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Angle; + if((!pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_MaxSpeed && m_pEditor->m_SpeedupMaxSpeed) || m_pEditor->m_SpeedupMaxSpeed != pLt->m_SpeedupMaxSpeed) + m_pSpeedupTile[fy * m_Width + fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; else - m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_MaxSpeed; - m_pSpeedupTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + m_pSpeedupTile[fy * m_Width + fx].m_MaxSpeed = pLt->m_pSpeedupTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_MaxSpeed; + m_pSpeedupTile[fy * m_Width + fx].m_Type = m_pTiles[fy * m_Width + fx].m_Index; } } } @@ -1694,8 +1684,8 @@ void CLayerSpeedup::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) FlagModified(sx, sy, w, h); } -CLayerFront::CLayerFront(int w, int h) -: CLayerTiles(w, h) +CLayerFront::CLayerFront(int w, int h) : + CLayerTiles(w, h) { //m_Type = LAYERTYPE_FRONT; str_copy(m_aName, "Front", sizeof(m_aName)); @@ -1704,19 +1694,26 @@ CLayerFront::CLayerFront(int w, int h) void CLayerFront::SetTile(int x, int y, CTile tile) { - if(tile.m_Index == TILE_THROUGH_CUT) { + if(tile.m_Index == TILE_THROUGH_CUT) + { CTile nohook = {TILE_NOHOOK}; m_pEditor->m_Map.m_pGameLayer->CLayerTiles::SetTile(x, y, nohook); - } else if(tile.m_Index == TILE_AIR && CLayerTiles::GetTile(x, y).m_Index == TILE_THROUGH_CUT) { + } + else if(tile.m_Index == TILE_AIR && CLayerTiles::GetTile(x, y).m_Index == TILE_THROUGH_CUT) + { CTile air = {TILE_AIR}; m_pEditor->m_Map.m_pGameLayer->CLayerTiles::SetTile(x, y, air); } - if(m_pEditor->m_AllowPlaceUnusedTiles || IsValidFrontTile(tile.m_Index)) { + if(m_pEditor->m_AllowPlaceUnusedTiles || IsValidFrontTile(tile.m_Index)) + { CLayerTiles::SetTile(x, y, tile); - } else { + } + else + { CTile air = {TILE_AIR}; CLayerTiles::SetTile(x, y, air); - if(!m_pEditor->m_PreventUnusedTilesWasWarned) { + if(!m_pEditor->m_PreventUnusedTilesWasWarned) + { m_pEditor->m_PopupEventType = m_pEditor->POPEVENT_PREVENTUNUSEDTILES; m_pEditor->m_PopupEventActivated = true; m_pEditor->m_PreventUnusedTilesWasWarned = true; @@ -1734,15 +1731,15 @@ void CLayerFront::Resize(int NewW, int NewH) m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); } -CLayerSwitch::CLayerSwitch(int w, int h) -: CLayerTiles(w, h) +CLayerSwitch::CLayerSwitch(int w, int h) : + CLayerTiles(w, h) { //m_Type = LAYERTYPE_SWITCH; str_copy(m_aName, "Switch", sizeof(m_aName)); m_Switch = 1; - m_pSwitchTile = new CSwitchTile[w*h]; - mem_zero(m_pSwitchTile, w*h*sizeof(CSwitchTile)); + m_pSwitchTile = new CSwitchTile[w * h]; + mem_zero(m_pSwitchTile, w * h * sizeof(CSwitchTile)); } CLayerSwitch::~CLayerSwitch() @@ -1753,15 +1750,15 @@ CLayerSwitch::~CLayerSwitch() void CLayerSwitch::Resize(int NewW, int NewH) { // resize switch data - CSwitchTile *pNewSwitchData = new CSwitchTile[NewW*NewH]; - mem_zero(pNewSwitchData, NewW*NewH*sizeof(CSwitchTile)); + CSwitchTile *pNewSwitchData = new CSwitchTile[NewW * NewH]; + mem_zero(pNewSwitchData, NewW * NewH * sizeof(CSwitchTile)); // copy old data for(int y = 0; y < minimum(NewH, m_Height); y++) - mem_copy(&pNewSwitchData[y*NewW], &m_pSwitchTile[y*m_Width], minimum(m_Width, NewW)*sizeof(CSwitchTile)); + mem_copy(&pNewSwitchData[y * NewW], &m_pSwitchTile[y * m_Width], minimum(m_Width, NewW) * sizeof(CSwitchTile)); // replace old - delete [] m_pSwitchTile; + delete[] m_pSwitchTile; m_pSwitchTile = pNewSwitchData; // resize tile data @@ -1780,45 +1777,45 @@ void CLayerSwitch::Shift(int Direction) switch(Direction) { case 1: + { + // left + for(int y = 0; y < m_Height; ++y) { - // left - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[y*m_Width+o], (m_Width-o)*sizeof(CSwitchTile)); - mem_zero(&m_pSwitchTile[y*m_Width + (m_Width-o)], o*sizeof(CSwitchTile)); - } + mem_move(&m_pSwitchTile[y * m_Width], &m_pSwitchTile[y * m_Width + o], (m_Width - o) * sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[y * m_Width + (m_Width - o)], o * sizeof(CSwitchTile)); } - break; + } + break; case 2: + { + // right + for(int y = 0; y < m_Height; ++y) { - // right - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pSwitchTile[y*m_Width+o], &m_pSwitchTile[y*m_Width], (m_Width-o)*sizeof(CSwitchTile)); - mem_zero(&m_pSwitchTile[y*m_Width], o*sizeof(CSwitchTile)); - } + mem_move(&m_pSwitchTile[y * m_Width + o], &m_pSwitchTile[y * m_Width], (m_Width - o) * sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[y * m_Width], o * sizeof(CSwitchTile)); } - break; + } + break; case 4: + { + // up + for(int y = 0; y < m_Height - o; ++y) { - // up - for(int y = 0; y < m_Height-o; ++y) - { - mem_copy(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[(y+o)*m_Width], m_Width*sizeof(CSwitchTile)); - mem_zero(&m_pSwitchTile[(y+o)*m_Width], m_Width*sizeof(CSwitchTile)); - } + mem_copy(&m_pSwitchTile[y * m_Width], &m_pSwitchTile[(y + o) * m_Width], m_Width * sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[(y + o) * m_Width], m_Width * sizeof(CSwitchTile)); } - break; + } + break; case 8: + { + // down + for(int y = m_Height - 1; y >= o; --y) { - // down - for(int y = m_Height-1; y >= o; --y) - { - mem_copy(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[(y-o)*m_Width], m_Width*sizeof(CSwitchTile)); - mem_zero(&m_pSwitchTile[(y-o)*m_Width], m_Width*sizeof(CSwitchTile)); - } + mem_copy(&m_pSwitchTile[y * m_Width], &m_pSwitchTile[(y - o) * m_Width], m_Width * sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[(y - o) * m_Width], m_Width * sizeof(CSwitchTile)); } } + } } bool CLayerSwitch::IsEmpty(CLayerTiles *pLayer) @@ -1850,55 +1847,55 @@ void CLayerSwitch::BrushDraw(CLayer *pBrush, float wx, float wy) for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; - if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(IsValidSwitchTile(l->m_pTiles[y*l->m_Width+x].m_Index)) + if(IsValidSwitchTile(l->m_pTiles[y * l->m_Width + x].m_Index)) { if(m_pEditor->m_SwitchNum != l->m_SwitchNumber || m_pEditor->m_SwitchDelay != l->m_SwitchDelay) { - m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; - m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + m_pSwitchTile[fy * m_Width + fx].m_Number = m_pEditor->m_SwitchNum; + m_pSwitchTile[fy * m_Width + fx].m_Delay = m_pEditor->m_SwitchDelay; } - else if(l->m_pSwitchTile[y*l->m_Width+x].m_Number) + else if(l->m_pSwitchTile[y * l->m_Width + x].m_Number) { - m_pSwitchTile[fy*m_Width+fx].m_Number = l->m_pSwitchTile[y*l->m_Width+x].m_Number; - m_pSwitchTile[fy*m_Width+fx].m_Delay = l->m_pSwitchTile[y*l->m_Width+x].m_Delay; + m_pSwitchTile[fy * m_Width + fx].m_Number = l->m_pSwitchTile[y * l->m_Width + x].m_Number; + m_pSwitchTile[fy * m_Width + fx].m_Delay = l->m_pSwitchTile[y * l->m_Width + x].m_Delay; } else { - m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; - m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + m_pSwitchTile[fy * m_Width + fx].m_Number = m_pEditor->m_SwitchNum; + m_pSwitchTile[fy * m_Width + fx].m_Delay = m_pEditor->m_SwitchDelay; } - m_pSwitchTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pSwitchTile[fy*m_Width+fx].m_Flags = l->m_pTiles[y*l->m_Width+x].m_Flags; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Flags = l->m_pTiles[y*l->m_Width+x].m_Flags; + m_pSwitchTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pSwitchTile[fy * m_Width + fx].m_Flags = l->m_pTiles[y * l->m_Width + x].m_Flags; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Flags = l->m_pTiles[y * l->m_Width + x].m_Flags; } else { - m_pSwitchTile[fy*m_Width+fx].m_Number = 0; - m_pSwitchTile[fy*m_Width+fx].m_Type = 0; - m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; - m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; - m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pSwitchTile[fy * m_Width + fx].m_Number = 0; + m_pSwitchTile[fy * m_Width + fx].m_Type = 0; + m_pSwitchTile[fy * m_Width + fx].m_Flags = 0; + m_pSwitchTile[fy * m_Width + fx].m_Delay = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; } - if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_FREEZE) + if(l->m_pTiles[y * l->m_Width + x].m_Index == TILE_FREEZE) { - m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; + m_pSwitchTile[fy * m_Width + fx].m_Flags = 0; } - else if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DFREEZE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DUNFREEZE) + else if(l->m_pTiles[y * l->m_Width + x].m_Index == TILE_DFREEZE || l->m_pTiles[y * l->m_Width + x].m_Index == TILE_DUNFREEZE) { - m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; - m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; + m_pSwitchTile[fy * m_Width + fx].m_Flags = 0; + m_pSwitchTile[fy * m_Width + fx].m_Delay = 0; } } FlagModified(sx, sy, l->m_Width, l->m_Height); @@ -1909,11 +1906,11 @@ void CLayerSwitch::BrushFlipX() CLayerTiles::BrushFlipX(); for(int y = 0; y < m_Height; y++) - for(int x = 0; x < m_Width/2; x++) + for(int x = 0; x < m_Width / 2; x++) { - CSwitchTile Tmp = m_pSwitchTile[y*m_Width+x]; - m_pSwitchTile[y*m_Width+x] = m_pSwitchTile[y*m_Width+m_Width-1-x]; - m_pSwitchTile[y*m_Width+m_Width-1-x] = Tmp; + CSwitchTile Tmp = m_pSwitchTile[y * m_Width + x]; + m_pSwitchTile[y * m_Width + x] = m_pSwitchTile[y * m_Width + m_Width - 1 - x]; + m_pSwitchTile[y * m_Width + m_Width - 1 - x] = Tmp; } } @@ -1921,39 +1918,39 @@ void CLayerSwitch::BrushFlipY() { CLayerTiles::BrushFlipY(); - for(int y = 0; y < m_Height/2; y++) + for(int y = 0; y < m_Height / 2; y++) for(int x = 0; x < m_Width; x++) { - CSwitchTile Tmp = m_pSwitchTile[y*m_Width+x]; - m_pSwitchTile[y*m_Width+x] = m_pSwitchTile[(m_Height-1-y)*m_Width+x]; - m_pSwitchTile[(m_Height-1-y)*m_Width+x] = Tmp; + CSwitchTile Tmp = m_pSwitchTile[y * m_Width + x]; + m_pSwitchTile[y * m_Width + x] = m_pSwitchTile[(m_Height - 1 - y) * m_Width + x]; + m_pSwitchTile[(m_Height - 1 - y) * m_Width + x] = Tmp; } } void CLayerSwitch::BrushRotate(float Amount) { - int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + int Rotation = (round_to_int(360.0f * Amount / (pi * 2)) / 90) % 4; // 0=0°, 1=90°, 2=180°, 3=270° if(Rotation < 0) - Rotation +=4; + Rotation += 4; if(Rotation == 1 || Rotation == 3) { // 90° rotation - CSwitchTile *pTempData1 = new CSwitchTile[m_Width*m_Height]; - CTile *pTempData2 = new CTile[m_Width*m_Height]; - mem_copy(pTempData1, m_pSwitchTile, m_Width*m_Height*sizeof(CSwitchTile)); - mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CSwitchTile *pTempData1 = new CSwitchTile[m_Width * m_Height]; + CTile *pTempData2 = new CTile[m_Width * m_Height]; + mem_copy(pTempData1, m_pSwitchTile, m_Width * m_Height * sizeof(CSwitchTile)); + mem_copy(pTempData2, m_pTiles, m_Width * m_Height * sizeof(CTile)); CSwitchTile *pDst1 = m_pSwitchTile; CTile *pDst2 = m_pTiles; for(int x = 0; x < m_Width; ++x) - for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + for(int y = m_Height - 1; y >= 0; --y, ++pDst1, ++pDst2) { - *pDst1 = pTempData1[y*m_Width+x]; - *pDst2 = pTempData2[y*m_Width+x]; + *pDst1 = pTempData1[y * m_Width + x]; + *pDst2 = pTempData2[y * m_Width + x]; if(IsRotatableTile(pDst2->m_Index)) { - if(pDst2->m_Flags&TILEFLAG_ROTATE) - pDst2->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP); + if(pDst2->m_Flags & TILEFLAG_ROTATE) + pDst2->m_Flags ^= (TILEFLAG_HFLIP | TILEFLAG_VFLIP); pDst2->m_Flags ^= TILEFLAG_ROTATE; } } @@ -1986,7 +1983,7 @@ void CLayerSwitch::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); - CLayerSwitch *pLt = static_cast(pBrush); + CLayerSwitch *pLt = static_cast(pBrush); bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); @@ -1994,8 +1991,8 @@ void CLayerSwitch::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { for(int x = 0; x < w; x++) { - int fx = x+sx; - int fy = y+sy; + int fx = x + sx; + int fy = y + sy; if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; @@ -2003,28 +2000,28 @@ void CLayerSwitch::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) if(!Destructive && GetTile(fx, fy).m_Index) continue; - if(Empty || !IsValidSwitchTile((pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index)) + if(Empty || !IsValidSwitchTile((pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]).m_Index)) { - m_pTiles[fy*m_Width+fx].m_Index = 0; - m_pSwitchTile[fy*m_Width+fx].m_Type = 0; - m_pSwitchTile[fy*m_Width+fx].m_Number = 0; - m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; + m_pSwitchTile[fy * m_Width + fx].m_Type = 0; + m_pSwitchTile[fy * m_Width + fx].m_Number = 0; + m_pSwitchTile[fy * m_Width + fx].m_Delay = 0; } else { - m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; - m_pSwitchTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; - if(pLt->m_Switch && m_pEditor->m_SwitchNum && m_pTiles[fy*m_Width+fx].m_Index > 0) + m_pTiles[fy * m_Width + fx] = pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]; + m_pSwitchTile[fy * m_Width + fx].m_Type = m_pTiles[fy * m_Width + fx].m_Index; + if(pLt->m_Switch && m_pEditor->m_SwitchNum && m_pTiles[fy * m_Width + fx].m_Index > 0) { - if((!pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number) || m_pEditor->m_SwitchNum != pLt->m_SwitchNumber) - m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; + if((!pLt->m_pSwitchTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number) || m_pEditor->m_SwitchNum != pLt->m_SwitchNumber) + m_pSwitchTile[fy * m_Width + fx].m_Number = m_pEditor->m_SwitchNum; else - m_pSwitchTile[fy*m_Width+fx].m_Number = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; - if((!pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Delay) || m_pEditor->m_SwitchDelay != pLt->m_SwitchDelay) - m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + m_pSwitchTile[fy * m_Width + fx].m_Number = pLt->m_pSwitchTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number; + if((!pLt->m_pSwitchTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Delay) || m_pEditor->m_SwitchDelay != pLt->m_SwitchDelay) + m_pSwitchTile[fy * m_Width + fx].m_Delay = m_pEditor->m_SwitchDelay; else - m_pSwitchTile[fy*m_Width+fx].m_Delay = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Delay; - m_pSwitchTile[fy*m_Width+fx].m_Flags = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Flags; + m_pSwitchTile[fy * m_Width + fx].m_Delay = pLt->m_pSwitchTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Delay; + m_pSwitchTile[fy * m_Width + fx].m_Flags = pLt->m_pSwitchTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Flags; } } } @@ -2038,7 +2035,7 @@ bool CLayerSwitch::ContainsElementWithId(int Id) { for(int x = 0; x < m_Width; ++x) { - if(m_pSwitchTile[y*m_Width+x].m_Number == Id) + if(m_pSwitchTile[y * m_Width + x].m_Number == Id) { return true; } @@ -2050,15 +2047,15 @@ bool CLayerSwitch::ContainsElementWithId(int Id) //------------------------------------------------------ -CLayerTune::CLayerTune(int w, int h) -: CLayerTiles(w, h) +CLayerTune::CLayerTune(int w, int h) : + CLayerTiles(w, h) { //m_Type = LAYERTYPE_TUNE; str_copy(m_aName, "Tune", sizeof(m_aName)); m_Tune = 1; - m_pTuneTile = new CTuneTile[w*h]; - mem_zero(m_pTuneTile, w*h*sizeof(CTuneTile)); + m_pTuneTile = new CTuneTile[w * h]; + mem_zero(m_pTuneTile, w * h * sizeof(CTuneTile)); } CLayerTune::~CLayerTune() @@ -2069,15 +2066,15 @@ CLayerTune::~CLayerTune() void CLayerTune::Resize(int NewW, int NewH) { // resize Tune data - CTuneTile *pNewTuneData = new CTuneTile[NewW*NewH]; - mem_zero(pNewTuneData, NewW*NewH*sizeof(CTuneTile)); + CTuneTile *pNewTuneData = new CTuneTile[NewW * NewH]; + mem_zero(pNewTuneData, NewW * NewH * sizeof(CTuneTile)); // copy old data for(int y = 0; y < minimum(NewH, m_Height); y++) - mem_copy(&pNewTuneData[y*NewW], &m_pTuneTile[y*m_Width], minimum(m_Width, NewW)*sizeof(CTuneTile)); + mem_copy(&pNewTuneData[y * NewW], &m_pTuneTile[y * m_Width], minimum(m_Width, NewW) * sizeof(CTuneTile)); // replace old - delete [] m_pTuneTile; + delete[] m_pTuneTile; m_pTuneTile = pNewTuneData; // resize tile data @@ -2096,45 +2093,45 @@ void CLayerTune::Shift(int Direction) switch(Direction) { case 1: + { + // left + for(int y = 0; y < m_Height; ++y) { - // left - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTuneTile[y*m_Width], &m_pTuneTile[y*m_Width+o], (m_Width-o)*sizeof(CTuneTile)); - mem_zero(&m_pTuneTile[y*m_Width + (m_Width-o)], o*sizeof(CTuneTile)); - } + mem_move(&m_pTuneTile[y * m_Width], &m_pTuneTile[y * m_Width + o], (m_Width - o) * sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[y * m_Width + (m_Width - o)], o * sizeof(CTuneTile)); } - break; + } + break; case 2: + { + // right + for(int y = 0; y < m_Height; ++y) { - // right - for(int y = 0; y < m_Height; ++y) - { - mem_move(&m_pTuneTile[y*m_Width+o], &m_pTuneTile[y*m_Width], (m_Width-o)*sizeof(CTuneTile)); - mem_zero(&m_pTuneTile[y*m_Width], o*sizeof(CTuneTile)); - } + mem_move(&m_pTuneTile[y * m_Width + o], &m_pTuneTile[y * m_Width], (m_Width - o) * sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[y * m_Width], o * sizeof(CTuneTile)); } - break; + } + break; case 4: + { + // up + for(int y = 0; y < m_Height - o; ++y) { - // up - for(int y = 0; y < m_Height-o; ++y) - { - mem_copy(&m_pTuneTile[y*m_Width], &m_pTuneTile[(y+o)*m_Width], m_Width*sizeof(CTuneTile)); - mem_zero(&m_pTuneTile[(y+o)*m_Width], m_Width*sizeof(CTuneTile)); - } + mem_copy(&m_pTuneTile[y * m_Width], &m_pTuneTile[(y + o) * m_Width], m_Width * sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[(y + o) * m_Width], m_Width * sizeof(CTuneTile)); } - break; + } + break; case 8: + { + // down + for(int y = m_Height - 1; y >= o; --y) { - // down - for(int y = m_Height-1; y >= o; --y) - { - mem_copy(&m_pTuneTile[y*m_Width], &m_pTuneTile[(y-o)*m_Width], m_Width*sizeof(CTuneTile)); - mem_zero(&m_pTuneTile[(y-o)*m_Width], m_Width*sizeof(CTuneTile)); - } + mem_copy(&m_pTuneTile[y * m_Width], &m_pTuneTile[(y - o) * m_Width], m_Width * sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[(y - o) * m_Width], m_Width * sizeof(CTuneTile)); } } + } } bool CLayerTune::IsEmpty(CLayerTiles *pLayer) @@ -2163,62 +2160,61 @@ void CLayerTune::BrushDraw(CLayer *pBrush, float wx, float wy) bool Destructive = m_pEditor->m_BrushDrawDestructive || IsEmpty(l); for(int y = 0; y < l->m_Height; y++) - for(int x = 0; x < l->m_Width; x++) + for(int x = 0; x < l->m_Width; x++) + { + int fx = x + sx; + int fy = y + sy; + + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if(!Destructive && GetTile(fx, fy).m_Index) + continue; + + if(IsValidTuneTile(l->m_pTiles[y * l->m_Width + x].m_Index)) { - int fx = x+sx; - int fy = y+sy; - - if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) - continue; - - if(!Destructive && GetTile(fx, fy).m_Index) - continue; - - if(IsValidTuneTile(l->m_pTiles[y*l->m_Width+x].m_Index)) + if(m_pEditor->m_TuningNum != l->m_TuningNumber) { - if(m_pEditor->m_TuningNum != l->m_TuningNumber) - { - m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; - } - else if(l->m_pTuneTile[y*l->m_Width+x].m_Number) - m_pTuneTile[fy*m_Width+fx].m_Number = l->m_pTuneTile[y*l->m_Width+x].m_Number; - else - { - if(!m_pEditor->m_TuningNum) - { - m_pTuneTile[fy*m_Width+fx].m_Number = 0; - m_pTuneTile[fy*m_Width+fx].m_Type = 0; - m_pTiles[fy*m_Width+fx].m_Index = 0; - continue; - } - else - m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; - } - - m_pTuneTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; - m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTuneTile[fy * m_Width + fx].m_Number = m_pEditor->m_TuningNum; } + else if(l->m_pTuneTile[y * l->m_Width + x].m_Number) + m_pTuneTile[fy * m_Width + fx].m_Number = l->m_pTuneTile[y * l->m_Width + x].m_Number; else { - m_pTuneTile[fy*m_Width+fx].m_Number = 0; - m_pTuneTile[fy*m_Width+fx].m_Type = 0; - m_pTiles[fy*m_Width+fx].m_Index = 0; + if(!m_pEditor->m_TuningNum) + { + m_pTuneTile[fy * m_Width + fx].m_Number = 0; + m_pTuneTile[fy * m_Width + fx].m_Type = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; + continue; + } + else + m_pTuneTile[fy * m_Width + fx].m_Number = m_pEditor->m_TuningNum; } + + m_pTuneTile[fy * m_Width + fx].m_Type = l->m_pTiles[y * l->m_Width + x].m_Index; + m_pTiles[fy * m_Width + fx].m_Index = l->m_pTiles[y * l->m_Width + x].m_Index; } + else + { + m_pTuneTile[fy * m_Width + fx].m_Number = 0; + m_pTuneTile[fy * m_Width + fx].m_Type = 0; + m_pTiles[fy * m_Width + fx].m_Index = 0; + } + } FlagModified(sx, sy, l->m_Width, l->m_Height); } - void CLayerTune::BrushFlipX() { CLayerTiles::BrushFlipX(); for(int y = 0; y < m_Height; y++) - for(int x = 0; x < m_Width/2; x++) + for(int x = 0; x < m_Width / 2; x++) { - CTuneTile Tmp = m_pTuneTile[y*m_Width+x]; - m_pTuneTile[y*m_Width+x] = m_pTuneTile[y*m_Width+m_Width-1-x]; - m_pTuneTile[y*m_Width+m_Width-1-x] = Tmp; + CTuneTile Tmp = m_pTuneTile[y * m_Width + x]; + m_pTuneTile[y * m_Width + x] = m_pTuneTile[y * m_Width + m_Width - 1 - x]; + m_pTuneTile[y * m_Width + m_Width - 1 - x] = Tmp; } } @@ -2226,35 +2222,35 @@ void CLayerTune::BrushFlipY() { CLayerTiles::BrushFlipY(); - for(int y = 0; y < m_Height/2; y++) + for(int y = 0; y < m_Height / 2; y++) for(int x = 0; x < m_Width; x++) { - CTuneTile Tmp = m_pTuneTile[y*m_Width+x]; - m_pTuneTile[y*m_Width+x] = m_pTuneTile[(m_Height-1-y)*m_Width+x]; - m_pTuneTile[(m_Height-1-y)*m_Width+x] = Tmp; + CTuneTile Tmp = m_pTuneTile[y * m_Width + x]; + m_pTuneTile[y * m_Width + x] = m_pTuneTile[(m_Height - 1 - y) * m_Width + x]; + m_pTuneTile[(m_Height - 1 - y) * m_Width + x] = Tmp; } } void CLayerTune::BrushRotate(float Amount) { - int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + int Rotation = (round_to_int(360.0f * Amount / (pi * 2)) / 90) % 4; // 0=0°, 1=90°, 2=180°, 3=270° if(Rotation < 0) - Rotation +=4; + Rotation += 4; if(Rotation == 1 || Rotation == 3) { // 90° rotation - CTuneTile *pTempData1 = new CTuneTile[m_Width*m_Height]; - CTile *pTempData2 = new CTile[m_Width*m_Height]; - mem_copy(pTempData1, m_pTuneTile, m_Width*m_Height*sizeof(CTuneTile)); - mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTuneTile *pTempData1 = new CTuneTile[m_Width * m_Height]; + CTile *pTempData2 = new CTile[m_Width * m_Height]; + mem_copy(pTempData1, m_pTuneTile, m_Width * m_Height * sizeof(CTuneTile)); + mem_copy(pTempData2, m_pTiles, m_Width * m_Height * sizeof(CTile)); CTuneTile *pDst1 = m_pTuneTile; CTile *pDst2 = m_pTiles; for(int x = 0; x < m_Width; ++x) - for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + for(int y = m_Height - 1; y >= 0; --y, ++pDst1, ++pDst2) { - *pDst1 = pTempData1[y*m_Width+x]; - *pDst2 = pTempData2[y*m_Width+x]; + *pDst1 = pTempData1[y * m_Width + x]; + *pDst2 = pTempData2[y * m_Width + x]; } int Temp = m_Width; @@ -2271,7 +2267,6 @@ void CLayerTune::BrushRotate(float Amount) } } - void CLayerTune::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { if(m_Readonly || (!Empty && pBrush->m_Type != LAYERTYPE_TILES)) @@ -2279,48 +2274,48 @@ void CLayerTune::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) Snap(&Rect); // corrects Rect; no need of <= - int sx = ConvertX(Rect.x); - int sy = ConvertY(Rect.y); - int w = ConvertX(Rect.w); - int h = ConvertY(Rect.h); + int sx = ConvertX(Rect.x); + int sy = ConvertY(Rect.y); + int w = ConvertX(Rect.w); + int h = ConvertY(Rect.h); - CLayerTune *pLt = static_cast(pBrush); + CLayerTune *pLt = static_cast(pBrush); - bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); + bool Destructive = m_pEditor->m_BrushDrawDestructive || Empty || IsEmpty(pLt); - for(int y = 0; y < h; y++) + for(int y = 0; y < h; y++) + { + for(int x = 0; x < w; x++) { - for(int x = 0; x < w; x++) + int fx = x + sx; + int fy = y + sy; + + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if(!Destructive && GetTile(fx, fy).m_Index) + continue; + + if(Empty || !IsValidTuneTile((pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]).m_Index)) // \o/ this fixes editor bug; TODO: use IsUsedInThisLayer here { - int fx = x+sx; - int fy = y+sy; - - if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) - continue; - - if(!Destructive && GetTile(fx, fy).m_Index) - continue; - - if(Empty || !IsValidTuneTile((pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index)) // \o/ this fixes editor bug; TODO: use IsUsedInThisLayer here + m_pTiles[fy * m_Width + fx].m_Index = 0; + m_pTuneTile[fy * m_Width + fx].m_Type = 0; + m_pTuneTile[fy * m_Width + fx].m_Number = 0; + } + else + { + m_pTiles[fy * m_Width + fx] = pLt->m_pTiles[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)]; + if(pLt->m_Tune && m_pTiles[fy * m_Width + fx].m_Index > 0) { - m_pTiles[fy*m_Width+fx].m_Index = 0; - m_pTuneTile[fy*m_Width+fx].m_Type = 0; - m_pTuneTile[fy*m_Width+fx].m_Number = 0; - } - else - { - m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; - if(pLt->m_Tune && m_pTiles[fy*m_Width+fx].m_Index > 0) - { - if((!pLt->m_pTuneTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number && m_pEditor->m_TuningNum) || m_pEditor->m_TuningNum != pLt->m_TuningNumber) - m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; - else - m_pTuneTile[fy*m_Width+fx].m_Number = pLt->m_pTuneTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; - m_pTuneTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; - } + if((!pLt->m_pTuneTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number && m_pEditor->m_TuningNum) || m_pEditor->m_TuningNum != pLt->m_TuningNumber) + m_pTuneTile[fy * m_Width + fx].m_Number = m_pEditor->m_TuningNum; + else + m_pTuneTile[fy * m_Width + fx].m_Number = pLt->m_pTuneTile[(y * pLt->m_Width + x % pLt->m_Width) % (pLt->m_Width * pLt->m_Height)].m_Number; + m_pTuneTile[fy * m_Width + fx].m_Type = m_pTiles[fy * m_Width + fx].m_Index; } } } + } FlagModified(sx, sy, w, h); } diff --git a/src/game/editor/popups.cpp b/src/game/editor/popups.cpp index 6d531c527..4a31e7bce 100644 --- a/src/game/editor/popups.cpp +++ b/src/game/editor/popups.cpp @@ -12,7 +12,6 @@ #include "editor.h" - // popup menu handling static struct { @@ -75,12 +74,12 @@ void CEditor::UiDoPopupMenu() int Corners = CUI::CORNER_ALL; if(s_UiPopups[i].m_IsMenu) - Corners = CUI::CORNER_R|CUI::CORNER_B; + Corners = CUI::CORNER_R | CUI::CORNER_B; CUIRect r = s_UiPopups[i].m_Rect; - RenderTools()->DrawUIRect(&r, ColorRGBA(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f); + RenderTools()->DrawUIRect(&r, ColorRGBA(0.5f, 0.5f, 0.5f, 0.75f), Corners, 3.0f); r.Margin(1.0f, &r); - RenderTools()->DrawUIRect(&r, ColorRGBA(0,0,0,0.75f), Corners, 3.0f); + RenderTools()->DrawUIRect(&r, ColorRGBA(0, 0, 0, 0.75f), Corners, 3.0f); r.Margin(4.0f, &r); if(s_UiPopups[i].m_pfnFunc(this, r, s_UiPopups[i].m_pContext)) @@ -130,7 +129,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete group", 0, &Button, 0, "Delete group")) { pEditor->m_Map.DeleteGroup(pEditor->m_SelectedGroup); - pEditor->m_SelectedGroup = maximum(0, pEditor->m_SelectedGroup-1); + pEditor->m_SelectedGroup = maximum(0, pEditor->m_SelectedGroup - 1); return 1; } } @@ -139,7 +138,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) if(pEditor->DoButton_Editor(&s_DeleteButton, "Clean up game tiles", 0, &Button, 0, "Removes game tiles that aren't based on a layer")) { // gather all tile layers - array Layers; + array Layers; for(int i = 0; i < pEditor->m_Map.m_pGameGroup->m_lLayers.size(); ++i) { if(pEditor->m_Map.m_pGameGroup->m_lLayers[i] != pEditor->m_Map.m_pGameLayer && pEditor->m_Map.m_pGameGroup->m_lLayers[i]->m_Type == LAYERTYPE_TILES) @@ -151,13 +150,13 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) for(int y = 0; y < gl->m_Height; ++y) for(int x = 0; x < gl->m_Width; ++x) { - if(gl->m_pTiles[y*gl->m_Width+x].m_Index > static_cast(TILE_NOHOOK)) + if(gl->m_pTiles[y * gl->m_Width + x].m_Index > static_cast(TILE_NOHOOK)) continue; bool Found = false; for(int i = 0; i < Layers.size(); ++i) { - if(x < Layers[i]->m_Width && y < Layers[i]->m_Height && Layers[i]->m_pTiles[y*Layers[i]->m_Width+x].m_Index) + if(x < Layers[i]->m_Width && y < Layers[i]->m_Height && Layers[i]->m_pTiles[y * Layers[i]->m_Width + x].m_Index) { Found = true; break; @@ -166,7 +165,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) if(!Found) { - gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR; + gl->m_pTiles[y * gl->m_Width + x].m_Index = TILE_AIR; pEditor->m_Map.m_Modified = true; } } @@ -186,7 +185,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerTele(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); pEditor->m_Map.MakeTeleLayer(l); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Brush.Clear(); return 1; } @@ -203,28 +202,28 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerSpeedup(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); pEditor->m_Map.MakeSpeedupLayer(l); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Brush.Clear(); return 1; } } if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pTuneLayer) + { + // new tune layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewTuneLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewTuneLayerButton, "Add tune layer", 0, &Button, 0, "Creates a new tuning layer")) { - // new tune layer - View.HSplitBottom(5.0f, &View, &Button); - View.HSplitBottom(12.0f, &View, &Button); - static int s_NewTuneLayerButton = 0; - if(pEditor->DoButton_Editor(&s_NewTuneLayerButton, "Add tune layer", 0, &Button, 0, "Creates a new tuning layer")) - { - CLayer *l = new CLayerTune(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); - pEditor->m_Map.MakeTuneLayer(l); - pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); - pEditor->m_Brush.Clear(); - return 1; - } + CLayer *l = new CLayerTune(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeTuneLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); + pEditor->m_Brush.Clear(); + return 1; } + } if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pFrontLayer) { @@ -237,7 +236,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerFront(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); pEditor->m_Map.MakeFrontLayer(l); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Brush.Clear(); return 1; } @@ -254,7 +253,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerSwitch(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); pEditor->m_Map.MakeSwitchLayer(l); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Brush.Clear(); return 1; } @@ -269,7 +268,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerQuads; l->m_pEditor = pEditor; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; return 1; } @@ -283,7 +282,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerTiles(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); l->m_pEditor = pEditor; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; return 1; } @@ -297,7 +296,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) CLayer *l = new CLayerSounds; l->m_pEditor = pEditor; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size() - 1); pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; return 1; } @@ -316,7 +315,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) enum { - PROP_ORDER=0, + PROP_ORDER = 0, PROP_POS_X, PROP_POS_Y, PROP_PARA_X, @@ -330,7 +329,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) }; CProperty aProps[] = { - {"Order", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, + {"Order", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size() - 1}, {"Pos X", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Para X", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, @@ -361,15 +360,24 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View, void *pContext) // these can not be changed on the game group if(!pEditor->GetSelectedGroup()->m_GameGroup) { - if(Prop == PROP_PARA_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX = NewVal; - else if(Prop == PROP_PARA_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY = NewVal; - else if(Prop == PROP_POS_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX = -NewVal; - else if(Prop == PROP_POS_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY = -NewVal; - else if(Prop == PROP_USE_CLIPPING) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping = NewVal; - else if(Prop == PROP_CLIP_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX = NewVal; - else if(Prop == PROP_CLIP_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY = NewVal; - else if(Prop == PROP_CLIP_W) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW = NewVal; - else if(Prop == PROP_CLIP_H) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH = NewVal; + if(Prop == PROP_PARA_X) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX = NewVal; + else if(Prop == PROP_PARA_Y) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY = NewVal; + else if(Prop == PROP_POS_X) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX = -NewVal; + else if(Prop == PROP_POS_Y) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY = -NewVal; + else if(Prop == PROP_USE_CLIPPING) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping = NewVal; + else if(Prop == PROP_CLIP_X) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX = NewVal; + else if(Prop == PROP_CLIP_Y) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY = NewVal; + else if(Prop == PROP_CLIP_W) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW = NewVal; + else if(Prop == PROP_CLIP_H) + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH = NewVal; } return 0; @@ -427,16 +435,16 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View, void *pContext) enum { - PROP_GROUP=0, + PROP_GROUP = 0, PROP_ORDER, PROP_HQ, NUM_PROPS, }; CProperty aProps[] = { - {"Group", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, + {"Group", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size() - 1}, {"Order", pEditor->m_lSelectedLayers[0], PROPTYPE_INT_STEP, 0, pCurrentGroup->m_lLayers.size()}, - {"Detail", pCurrentLayer && pCurrentLayer->m_Flags&LAYERFLAG_DETAIL, PROPTYPE_BOOL, 0, 1}, + {"Detail", pCurrentLayer && pCurrentLayer->m_Flags & LAYERFLAG_DETAIL, PROPTYPE_BOOL, 0, 1}, {0}, }; @@ -462,7 +470,7 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View, void *pContext) pCurrentGroup->m_lLayers.remove(pCurrentLayer); pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.add(pCurrentLayer); pEditor->m_SelectedGroup = NewVal; - pEditor->SelectLayer(pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.size()-1); + pEditor->SelectLayer(pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.size() - 1); } } else if(Prop == PROP_HQ && pCurrentLayer) @@ -472,7 +480,7 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View, void *pContext) pCurrentLayer->m_Flags |= LAYERFLAG_DETAIL; } - if (!pCurrentLayer) + if(!pCurrentLayer) return true; return pCurrentLayer->RenderProperties(&View); } @@ -515,17 +523,24 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View, void *pContext) for(int k = 1; k < 4; k++) { - if(lQuads[i]->m_aPoints[k].y < Top) Top = lQuads[i]->m_aPoints[k].y; - if(lQuads[i]->m_aPoints[k].x < Left) Left = lQuads[i]->m_aPoints[k].x; - if(lQuads[i]->m_aPoints[k].x > Right) Right = lQuads[i]->m_aPoints[k].x; + if(lQuads[i]->m_aPoints[k].y < Top) + Top = lQuads[i]->m_aPoints[k].y; + if(lQuads[i]->m_aPoints[k].x < Left) + Left = lQuads[i]->m_aPoints[k].x; + if(lQuads[i]->m_aPoints[k].x > Right) + Right = lQuads[i]->m_aPoints[k].x; } - int Height = (Right-Left)*pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height/pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width; + int Height = (Right - Left) * pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height / pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width; - lQuads[i]->m_aPoints[0].x = Left; lQuads[i]->m_aPoints[0].y = Top; - lQuads[i]->m_aPoints[1].x = Right; lQuads[i]->m_aPoints[1].y = Top; - lQuads[i]->m_aPoints[2].x = Left; lQuads[i]->m_aPoints[2].y = Top+Height; - lQuads[i]->m_aPoints[3].x = Right; lQuads[i]->m_aPoints[3].y = Top+Height; + lQuads[i]->m_aPoints[0].x = Left; + lQuads[i]->m_aPoints[0].y = Top; + lQuads[i]->m_aPoints[1].x = Right; + lQuads[i]->m_aPoints[1].y = Top; + lQuads[i]->m_aPoints[2].x = Left; + lQuads[i]->m_aPoints[2].y = Top + Height; + lQuads[i]->m_aPoints[3].x = Right; + lQuads[i]->m_aPoints[3].y = Top + Height; pEditor->m_Map.m_Modified = true; } return 1; @@ -565,25 +580,32 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View, void *pContext) for(int k = 1; k < 4; k++) { - if(lQuads[i]->m_aPoints[k].y < Top) Top = lQuads[i]->m_aPoints[k].y; - if(lQuads[i]->m_aPoints[k].x < Left) Left = lQuads[i]->m_aPoints[k].x; - if(lQuads[i]->m_aPoints[k].y > Bottom) Bottom = lQuads[i]->m_aPoints[k].y; - if(lQuads[i]->m_aPoints[k].x > Right) Right = lQuads[i]->m_aPoints[k].x; + if(lQuads[i]->m_aPoints[k].y < Top) + Top = lQuads[i]->m_aPoints[k].y; + if(lQuads[i]->m_aPoints[k].x < Left) + Left = lQuads[i]->m_aPoints[k].x; + if(lQuads[i]->m_aPoints[k].y > Bottom) + Bottom = lQuads[i]->m_aPoints[k].y; + if(lQuads[i]->m_aPoints[k].x > Right) + Right = lQuads[i]->m_aPoints[k].x; } - lQuads[i]->m_aPoints[0].x = Left; lQuads[i]->m_aPoints[0].y = Top; - lQuads[i]->m_aPoints[1].x = Right; lQuads[i]->m_aPoints[1].y = Top; - lQuads[i]->m_aPoints[2].x = Left; lQuads[i]->m_aPoints[2].y = Bottom; - lQuads[i]->m_aPoints[3].x = Right; lQuads[i]->m_aPoints[3].y = Bottom; + lQuads[i]->m_aPoints[0].x = Left; + lQuads[i]->m_aPoints[0].y = Top; + lQuads[i]->m_aPoints[1].x = Right; + lQuads[i]->m_aPoints[1].y = Top; + lQuads[i]->m_aPoints[2].x = Left; + lQuads[i]->m_aPoints[2].y = Bottom; + lQuads[i]->m_aPoints[3].x = Right; + lQuads[i]->m_aPoints[3].y = Bottom; pEditor->m_Map.m_Modified = true; } return 1; } - enum { - PROP_POS_X=0, + PROP_POS_X = 0, PROP_POS_Y, PROP_POS_ENV, PROP_POS_ENV_OFFSET, @@ -626,8 +648,8 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View, void *pContext) } if(Prop == PROP_POS_ENV) { - int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); - int Step = (Index-lQuads[i]->m_PosEnv)%2; + int Index = clamp(NewVal - 1, -1, pEditor->m_Map.m_lEnvelopes.size() - 1); + int Step = (Index - lQuads[i]->m_PosEnv) % 2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) @@ -638,11 +660,12 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View, void *pContext) } } } - if(Prop == PROP_POS_ENV_OFFSET) lQuads[i]->m_PosEnvOffset = NewVal; + if(Prop == PROP_POS_ENV_OFFSET) + lQuads[i]->m_PosEnvOffset = NewVal; if(Prop == PROP_COLOR_ENV) { - int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); - int Step = (Index-lQuads[i]->m_ColorEnv)%2; + int Index = clamp(NewVal - 1, -1, pEditor->m_Map.m_lEnvelopes.size() - 1); + int Step = (Index - lQuads[i]->m_ColorEnv) % 2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) @@ -653,7 +676,8 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View, void *pContext) } } } - if(Prop == PROP_COLOR_ENV_OFFSET) lQuads[i]->m_ColorEnvOffset = NewVal; + if(Prop == PROP_COLOR_ENV_OFFSET) + lQuads[i]->m_ColorEnvOffset = NewVal; } return 0; @@ -688,36 +712,34 @@ int CEditor::PopupSource(CEditor *pEditor, CUIRect View, void *pContext) static const char *s_aShapeNames[] = { "Rectangle", - "Circle" - }; + "Circle"}; - pSource->m_Shape.m_Type = pSource->m_Shape.m_Type%CSoundShape::NUM_SHAPES; // prevent out of array errors + pSource->m_Shape.m_Type = pSource->m_Shape.m_Type % CSoundShape::NUM_SHAPES; // prevent out of array errors if(pEditor->DoButton_Editor(&s_ShapeTypeButton, s_aShapeNames[pSource->m_Shape.m_Type], 0, &ShapeButton, 0, "Change shape")) { - pSource->m_Shape.m_Type = (pSource->m_Shape.m_Type+1)%CSoundShape::NUM_SHAPES; + pSource->m_Shape.m_Type = (pSource->m_Shape.m_Type + 1) % CSoundShape::NUM_SHAPES; // set default values switch(pSource->m_Shape.m_Type) { case CSoundShape::SHAPE_CIRCLE: - { - pSource->m_Shape.m_Circle.m_Radius = 1000.0f; - break; - } + { + pSource->m_Shape.m_Circle.m_Radius = 1000.0f; + break; + } case CSoundShape::SHAPE_RECTANGLE: - { - pSource->m_Shape.m_Rectangle.m_Width = f2fx(1000.0f); - pSource->m_Shape.m_Rectangle.m_Height = f2fx(800.0f); - break; - } + { + pSource->m_Shape.m_Rectangle.m_Width = f2fx(1000.0f); + pSource->m_Shape.m_Rectangle.m_Height = f2fx(800.0f); + break; + } } } - enum { - PROP_POS_X=0, + PROP_POS_X = 0, PROP_POS_Y, PROP_LOOP, PROP_PAN, @@ -751,16 +773,22 @@ int CEditor::PopupSource(CEditor *pEditor, CUIRect View, void *pContext) if(Prop != -1) pEditor->m_Map.m_Modified = true; - if(Prop == PROP_POS_X) pSource->m_Position.x = NewVal*1000; - if(Prop == PROP_POS_Y) pSource->m_Position.y = NewVal*1000; - if(Prop == PROP_LOOP) pSource->m_Loop = NewVal; - if(Prop == PROP_PAN) pSource->m_Pan = NewVal; - if(Prop == PROP_TIME_DELAY) pSource->m_TimeDelay = NewVal; - if(Prop == PROP_FALLOFF) pSource->m_Falloff = NewVal; + if(Prop == PROP_POS_X) + pSource->m_Position.x = NewVal * 1000; + if(Prop == PROP_POS_Y) + pSource->m_Position.y = NewVal * 1000; + if(Prop == PROP_LOOP) + pSource->m_Loop = NewVal; + if(Prop == PROP_PAN) + pSource->m_Pan = NewVal; + if(Prop == PROP_TIME_DELAY) + pSource->m_TimeDelay = NewVal; + if(Prop == PROP_FALLOFF) + pSource->m_Falloff = NewVal; if(Prop == PROP_POS_ENV) { - int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); - int Step = (Index-pSource->m_PosEnv)%2; + int Index = clamp(NewVal - 1, -1, pEditor->m_Map.m_lEnvelopes.size() - 1); + int Step = (Index - pSource->m_PosEnv) % 2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) @@ -771,11 +799,12 @@ int CEditor::PopupSource(CEditor *pEditor, CUIRect View, void *pContext) } } } - if(Prop == PROP_POS_ENV_OFFSET) pSource->m_PosEnvOffset = NewVal; + if(Prop == PROP_POS_ENV_OFFSET) + pSource->m_PosEnvOffset = NewVal; if(Prop == PROP_SOUND_ENV) { - int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); - int Step = (Index-pSource->m_SoundEnv)%2; + int Index = clamp(NewVal - 1, -1, pEditor->m_Map.m_lEnvelopes.size() - 1); + int Step = (Index - pSource->m_SoundEnv) % 2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) @@ -786,67 +815,70 @@ int CEditor::PopupSource(CEditor *pEditor, CUIRect View, void *pContext) } } } - if(Prop == PROP_SOUND_ENV_OFFSET) pSource->m_SoundEnvOffset = NewVal; + if(Prop == PROP_SOUND_ENV_OFFSET) + pSource->m_SoundEnvOffset = NewVal; // source shape properties switch(pSource->m_Shape.m_Type) { case CSoundShape::SHAPE_CIRCLE: + { + enum { - enum - { - PROP_CIRCLE_RADIUS=0, - NUM_CIRCLE_PROPS, - }; + PROP_CIRCLE_RADIUS = 0, + NUM_CIRCLE_PROPS, + }; - CProperty aCircleProps[] = { - {"Radius", pSource->m_Shape.m_Circle.m_Radius, PROPTYPE_INT_SCROLL, 0, 1000000}, + CProperty aCircleProps[] = { + {"Radius", pSource->m_Shape.m_Circle.m_Radius, PROPTYPE_INT_SCROLL, 0, 1000000}, - {0}, - }; + {0}, + }; - static int s_aCircleIds[NUM_CIRCLE_PROPS] = {0}; + static int s_aCircleIds[NUM_CIRCLE_PROPS] = {0}; - NewVal = 0; - Prop = pEditor->DoProperties(&View, aCircleProps, s_aCircleIds, &NewVal); - if(Prop != -1) - pEditor->m_Map.m_Modified = true; + NewVal = 0; + Prop = pEditor->DoProperties(&View, aCircleProps, s_aCircleIds, &NewVal); + if(Prop != -1) + pEditor->m_Map.m_Modified = true; - if(Prop == PROP_CIRCLE_RADIUS) pSource->m_Shape.m_Circle.m_Radius = NewVal; + if(Prop == PROP_CIRCLE_RADIUS) + pSource->m_Shape.m_Circle.m_Radius = NewVal; - break; - } - - case CSoundShape::SHAPE_RECTANGLE: - { - enum - { - PROP_RECTANGLE_WIDTH=0, - PROP_RECTANGLE_HEIGHT, - NUM_RECTANGLE_PROPS, - }; - - CProperty aRectangleProps[] = { - {"Width", pSource->m_Shape.m_Rectangle.m_Width/1024, PROPTYPE_INT_SCROLL, 0, 1000000}, - {"Height", pSource->m_Shape.m_Rectangle.m_Height/1024, PROPTYPE_INT_SCROLL, 0, 1000000}, - - {0}, - }; - - static int s_aRectangleIds[NUM_RECTANGLE_PROPS] = {0}; - - NewVal = 0; - Prop = pEditor->DoProperties(&View, aRectangleProps, s_aRectangleIds, &NewVal); - if(Prop != -1) - pEditor->m_Map.m_Modified = true; - - if(Prop == PROP_RECTANGLE_WIDTH) pSource->m_Shape.m_Rectangle.m_Width = NewVal*1024; - if(Prop == PROP_RECTANGLE_HEIGHT) pSource->m_Shape.m_Rectangle.m_Height = NewVal*1024; - - break; - } + break; } + case CSoundShape::SHAPE_RECTANGLE: + { + enum + { + PROP_RECTANGLE_WIDTH = 0, + PROP_RECTANGLE_HEIGHT, + NUM_RECTANGLE_PROPS, + }; + + CProperty aRectangleProps[] = { + {"Width", pSource->m_Shape.m_Rectangle.m_Width / 1024, PROPTYPE_INT_SCROLL, 0, 1000000}, + {"Height", pSource->m_Shape.m_Rectangle.m_Height / 1024, PROPTYPE_INT_SCROLL, 0, 1000000}, + + {0}, + }; + + static int s_aRectangleIds[NUM_RECTANGLE_PROPS] = {0}; + + NewVal = 0; + Prop = pEditor->DoProperties(&View, aRectangleProps, s_aRectangleIds, &NewVal); + if(Prop != -1) + pEditor->m_Map.m_Modified = true; + + if(Prop == PROP_RECTANGLE_WIDTH) + pSource->m_Shape.m_Rectangle.m_Width = NewVal * 1024; + if(Prop == PROP_RECTANGLE_HEIGHT) + pSource->m_Shape.m_Rectangle.m_Height = NewVal * 1024; + + break; + } + } return 0; } @@ -858,7 +890,7 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View, void *pContext) enum { - PROP_POS_X=0, + PROP_POS_X = 0, PROP_POS_Y, PROP_COLOR, PROP_TEX_U, @@ -867,9 +899,9 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View, void *pContext) }; int Color = 0; - Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].r<<24; - Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].g<<16; - Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].b<<8; + Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].r << 24; + Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].g << 16; + Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].b << 8; Color |= pCurrentQuad->m_aColors[pEditor->m_SelectedQuadPoint].a; int x = fx2i(pCurrentQuad->m_aPoints[pEditor->m_SelectedQuadPoint].x); @@ -910,12 +942,12 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View, void *pContext) { for(int v = 0; v < 4; v++) { - if(pEditor->m_SelectedPoints&(1<m_SelectedPoints & (1 << v)) { - lQuads[i]->m_aColors[v].r = (NewVal>>24)&0xff; - lQuads[i]->m_aColors[v].g = (NewVal>>16)&0xff; - lQuads[i]->m_aColors[v].b = (NewVal>>8)&0xff; - lQuads[i]->m_aColors[v].a = NewVal&0xff; + lQuads[i]->m_aColors[v].r = (NewVal >> 24) & 0xff; + lQuads[i]->m_aColors[v].g = (NewVal >> 16) & 0xff; + lQuads[i]->m_aColors[v].b = (NewVal >> 8) & 0xff; + lQuads[i]->m_aColors[v].a = NewVal & 0xff; } } } @@ -996,7 +1028,7 @@ int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View, void *pContext) pEditor->UI()->DoLabel(&Label, "Unable to create the folder", 10.0f, -1, View.w); // button - ButtonBar.VMargin(ButtonBar.w/2.0f-55.0f, &ButtonBar); + ButtonBar.VMargin(ButtonBar.w / 2.0f - 55.0f, &ButtonBar); static int s_CreateButton = 0; if(pEditor->DoButton_Editor(&s_CreateButton, "Ok", 0, &ButtonBar, 0, 0)) return 1; @@ -1107,18 +1139,17 @@ int CEditor::PopupEvent(CEditor *pEditor, CUIRect View, void *pContext) View.VMargin(40.0f, &View); View.HSplitTop(20.0f, &Label, &View); if(pEditor->m_PopupEventType == POPEVENT_EXIT) - pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you exit the editor.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); - else if((pEditor->m_PopupEventType == POPEVENT_LOAD) - ||(pEditor->m_PopupEventType == POPEVENT_LOADCURRENT)) - pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you load a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you exit the editor.\nContinue anyway?", 10.0f, -1, Label.w - 10.0f); + else if((pEditor->m_PopupEventType == POPEVENT_LOAD) || (pEditor->m_PopupEventType == POPEVENT_LOADCURRENT)) + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you load a new map.\nContinue anyway?", 10.0f, -1, Label.w - 10.0f); else if(pEditor->m_PopupEventType == POPEVENT_NEW) - pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you create a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you create a new map.\nContinue anyway?", 10.0f, -1, Label.w - 10.0f); else if(pEditor->m_PopupEventType == POPEVENT_SAVE) pEditor->UI()->DoLabel(&Label, "The file already exists.\nDo you want to overwrite the map?", 10.0f, -1); else if(pEditor->m_PopupEventType == POPEVENT_LARGELAYER) - pEditor->UI()->DoLabel(&Label, "You are trying to set the height or width of a layer to more than 1000 tiles. This is actually possible, but only rarely necessary. It may cause the editor to work slower, larger file size as well as higher memory usage for client and server.", 10.0f, -1, Label.w-10.0f); + pEditor->UI()->DoLabel(&Label, "You are trying to set the height or width of a layer to more than 1000 tiles. This is actually possible, but only rarely necessary. It may cause the editor to work slower, larger file size as well as higher memory usage for client and server.", 10.0f, -1, Label.w - 10.0f); else if(pEditor->m_PopupEventType == POPEVENT_PREVENTUNUSEDTILES) - pEditor->UI()->DoLabel(&Label, "Unused tiles can't be placed by default because they could get a use later and then destroy your map.\nActivate the 'Unused' switch to be able to place every tile.", 10.0f, -1, Label.w-10.0f); + pEditor->UI()->DoLabel(&Label, "Unused tiles can't be placed by default because they could get a use later and then destroy your map.\nActivate the 'Unused' switch to be able to place every tile.", 10.0f, -1, Label.w - 10.0f); else if(pEditor->m_PopupEventType == POPEVENT_IMAGEDIV16) pEditor->UI()->DoLabel(&Label, "The width or height of this image is not divisible by 16. This is required for images used in tile layers.", 10.0f, -1, Label.w - 10.0f); else if(pEditor->m_PopupEventType == POPEVENT_IMAGE_MAX) @@ -1165,7 +1196,6 @@ int CEditor::PopupEvent(CEditor *pEditor, CUIRect View, void *pContext) return 0; } - static int g_SelectImageSelected = -100; static int g_SelectImageCurrent = -100; @@ -1186,19 +1216,19 @@ int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View, void *pContext) { CUIRect Scroll; ButtonBar.VSplitRight(15.0f, &ButtonBar, &Scroll); - ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing + ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = pEditor->UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(pEditor->UI()->MouseInside(&Scroll) || pEditor->UI()->MouseInside(&ButtonBar)) { - int ScrollNum = (int)((ImagesHeight-ButtonBar.h)/14.0f)+1; + int ScrollNum = (int)((ImagesHeight - ButtonBar.h) / 14.0f) + 1; if(ScrollNum > 0) { if(pEditor->Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(pEditor->Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } } } @@ -1228,12 +1258,12 @@ int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View, void *pContext) if(i == -1) { - if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], "None", i==g_SelectImageCurrent, &Button)) + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], "None", i == g_SelectImageCurrent, &Button)) g_SelectImageSelected = -1; } else { - if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], pEditor->m_Map.m_lImages[i]->m_aName, i==g_SelectImageCurrent, &Button)) + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], pEditor->m_Map.m_lImages[i]->m_aName, i == g_SelectImageCurrent, &Button)) g_SelectImageSelected = i; } } @@ -1245,8 +1275,8 @@ int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View, void *pContext) else ImageView.h = ImageView.w; float Max = (float)(maximum(pEditor->m_Map.m_lImages[ShowImage]->m_Width, pEditor->m_Map.m_lImages[ShowImage]->m_Height)); - ImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width/Max; - ImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height/Max; + ImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width / Max; + ImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height / Max; pEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_Texture); pEditor->Graphics()->BlendNormal(); pEditor->Graphics()->WrapClamp(); @@ -1287,7 +1317,6 @@ int CEditor::PopupSelectSound(CEditor *pEditor, CUIRect View, void *pContext) View.VSplitLeft(80.0f, &ButtonBar, &View); View.Margin(10.0f, &SoundView); - static int s_ScrollBar = 0; static float s_ScrollValue = 0; float SoundsHeight = pEditor->m_Map.m_lSounds.size() * 14; @@ -1297,19 +1326,19 @@ int CEditor::PopupSelectSound(CEditor *pEditor, CUIRect View, void *pContext) { CUIRect Scroll; ButtonBar.VSplitRight(15.0f, &ButtonBar, &Scroll); - ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing + ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = pEditor->UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(pEditor->UI()->MouseInside(&Scroll) || pEditor->UI()->MouseInside(&ButtonBar)) { - int ScrollNum = (int)((SoundsHeight-ButtonBar.h)/14.0f)+1; + int ScrollNum = (int)((SoundsHeight - ButtonBar.h) / 14.0f) + 1; if(ScrollNum > 0) { if(pEditor->Input()->KeyPress(KEY_MOUSE_WHEEL_UP)) - s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue - 1.0f / ScrollNum, 0.0f, 1.0f); if(pEditor->Input()->KeyPress(KEY_MOUSE_WHEEL_DOWN)) - s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + s_ScrollValue = clamp(s_ScrollValue + 1.0f / ScrollNum, 0.0f, 1.0f); } } } @@ -1339,12 +1368,12 @@ int CEditor::PopupSelectSound(CEditor *pEditor, CUIRect View, void *pContext) if(i == -1) { - if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], "None", i==g_SelectSoundCurrent, &Button)) + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], "None", i == g_SelectSoundCurrent, &Button)) g_SelectSoundSelected = -1; } else { - if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], pEditor->m_Map.m_lSounds[i]->m_aName, i==g_SelectSoundCurrent, &Button)) + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], pEditor->m_Map.m_lSounds[i]->m_aName, i == g_SelectSoundCurrent, &Button)) g_SelectSoundSelected = i; } } @@ -1374,8 +1403,8 @@ static int s_GametileOpSelected = -1; int CEditor::PopupSelectGametileOp(CEditor *pEditor, CUIRect View, void *pContext) { - static const char *s_pButtonNames[] = { "Air", "Hookable", "Death", "Unhookable", "Hookthrough", "Freeze", "Unfreeze", "Deep Freeze", "Deep Unfreeze", "Blue Check-Tele", "Red Check-Tele" }; - static unsigned s_NumButtons = sizeof(s_pButtonNames) / sizeof(char*); + static const char *s_pButtonNames[] = {"Air", "Hookable", "Death", "Unhookable", "Hookthrough", "Freeze", "Unfreeze", "Deep Freeze", "Deep Unfreeze", "Blue Check-Tele", "Red Check-Tele"}; + static unsigned s_NumButtons = sizeof(s_pButtonNames) / sizeof(char *); CUIRect Button; for(unsigned i = 0; i < s_NumButtons; ++i) @@ -1519,8 +1548,7 @@ int CEditor::PopupTele(CEditor *pEditor, CUIRect View, void *pContext) // find empty number button { static int s_EmptySlotPid = 0; - if(pEditor->DoButton_Editor(&s_EmptySlotPid, "F", 0, &FindEmptySlot, 0, "[ctrl+f] Find empty slot") - || pEditor->Input()->KeyPress(KEY_F)) + if(pEditor->DoButton_Editor(&s_EmptySlotPid, "F", 0, &FindEmptySlot, 0, "[ctrl+f] Find empty slot") || pEditor->Input()->KeyPress(KEY_F)) { int number = -1; for(int i = 1; i <= 255; i++) @@ -1564,9 +1592,7 @@ int CEditor::PopupTele(CEditor *pEditor, CUIRect View, void *pContext) if(s_PreviousNumber == 1 || s_PreviousNumber != pEditor->m_TeleNumber) { - s_Color = pEditor->m_Map.m_pTeleLayer->ContainsElementWithId(pEditor->m_TeleNumber) - ? ColorRGBA(1, 0.5f, 0.5f, 0.5f) - : ColorRGBA(0.5f, 1, 0.5f, 0.5f); + s_Color = pEditor->m_Map.m_pTeleLayer->ContainsElementWithId(pEditor->m_TeleNumber) ? ColorRGBA(1, 0.5f, 0.5f, 0.5f) : ColorRGBA(0.5f, 1, 0.5f, 0.5f); } } @@ -1582,7 +1608,7 @@ int CEditor::PopupSpeedup(CEditor *pEditor, CUIRect View, void *pContext) enum { - PROP_FORCE=0, + PROP_FORCE = 0, PROP_MAXSPEED, PROP_ANGLE, NUM_PROPS @@ -1625,8 +1651,7 @@ int CEditor::PopupSwitch(CEditor *pEditor, CUIRect View, void *pContext) // find empty number button { static int s_EmptySlotPid = 0; - if(pEditor->DoButton_Editor(&s_EmptySlotPid, "F", 0, &FindEmptySlot, 0, "[ctrl+f] Find empty slot") - || pEditor->Input()->KeyPress(KEY_F)) + if(pEditor->DoButton_Editor(&s_EmptySlotPid, "F", 0, &FindEmptySlot, 0, "[ctrl+f] Find empty slot") || pEditor->Input()->KeyPress(KEY_F)) { int number = -1; for(int i = 1; i <= 255; i++) @@ -1677,9 +1702,7 @@ int CEditor::PopupSwitch(CEditor *pEditor, CUIRect View, void *pContext) if(s_PreviousNumber == 1 || s_PreviousNumber != pEditor->m_SwitchNum) { - s_Color = pEditor->m_Map.m_pSwitchLayer->ContainsElementWithId(pEditor->m_SwitchNum) - ? ColorRGBA(1, 0.5f, 0.5f, 0.5f) - : ColorRGBA(0.5f, 1, 0.5f, 0.5f); + s_Color = pEditor->m_Map.m_pSwitchLayer->ContainsElementWithId(pEditor->m_SwitchNum) ? ColorRGBA(1, 0.5f, 0.5f, 0.5f) : ColorRGBA(0.5f, 1, 0.5f, 0.5f); } } @@ -1694,7 +1717,7 @@ int CEditor::PopupTune(CEditor *pEditor, CUIRect View, void *pContext) enum { - PROP_TUNE=0, + PROP_TUNE = 0, NUM_PROPS, }; @@ -1753,12 +1776,12 @@ int CEditor::PopupColorPicker(CEditor *pEditor, CUIRect View, void *pContext) pEditor->Graphics()->QuadsEnd(); // marker - vec2 Marker = vec2(hsv.y*pEditor->UI()->Scale(), (1.0f - hsv.z)*pEditor->UI()->Scale()) * vec2(SVPicker.w, SVPicker.h); + vec2 Marker = vec2(hsv.y * pEditor->UI()->Scale(), (1.0f - hsv.z) * pEditor->UI()->Scale()) * vec2(SVPicker.w, SVPicker.h); pEditor->Graphics()->QuadsBegin(); pEditor->Graphics()->SetColor(0.5f, 0.5f, 0.5f, 1.0f); IGraphics::CQuadItem aMarker[2]; - aMarker[0] = IGraphics::CQuadItem(SVPicker.x+Marker.x, SVPicker.y+Marker.y - 5.0f*pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize(), 11.0f*pEditor->UI()->PixelSize()); - aMarker[1] = IGraphics::CQuadItem(SVPicker.x+Marker.x - 5.0f*pEditor->UI()->PixelSize(), SVPicker.y+Marker.y, 11.0f*pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize()); + aMarker[0] = IGraphics::CQuadItem(SVPicker.x + Marker.x, SVPicker.y + Marker.y - 5.0f * pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize(), 11.0f * pEditor->UI()->PixelSize()); + aMarker[1] = IGraphics::CQuadItem(SVPicker.x + Marker.x - 5.0f * pEditor->UI()->PixelSize(), SVPicker.y + Marker.y, 11.0f * pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize()); pEditor->Graphics()->QuadsDrawTL(aMarker, 2); pEditor->Graphics()->QuadsEnd(); @@ -1766,35 +1789,35 @@ int CEditor::PopupColorPicker(CEditor *pEditor, CUIRect View, void *pContext) float X, Y; if(pEditor->UI()->DoPickerLogic(&pEditor->ms_SVPicker, &SVPicker, &X, &Y)) { - hsv.y = X/SVPicker.w; - hsv.z = 1.0f - Y/SVPicker.h; + hsv.y = X / SVPicker.w; + hsv.z = 1.0f - Y / SVPicker.h; } // hue slider static const float s_aColorIndices[7][3] = { {1.0f, 0.0f, 0.0f}, // red - {1.0f, 0.0f, 1.0f}, // magenta + {1.0f, 0.0f, 1.0f}, // magenta {0.0f, 0.0f, 1.0f}, // blue {0.0f, 1.0f, 1.0f}, // cyan {0.0f, 1.0f, 0.0f}, // green {1.0f, 1.0f, 0.0f}, // yellow - {1.0f, 0.0f, 0.0f} // red + {1.0f, 0.0f, 0.0f} // red }; pEditor->Graphics()->QuadsBegin(); ColorRGBA ColorTop, ColorBottom; - float Offset = HuePicker.h/6.0f; + float Offset = HuePicker.h / 6.0f; for(int j = 0; j < 6; j++) { ColorTop = ColorRGBA(s_aColorIndices[j][0], s_aColorIndices[j][1], s_aColorIndices[j][2], 1.0f); - ColorBottom = ColorRGBA(s_aColorIndices[j+1][0], s_aColorIndices[j+1][1], s_aColorIndices[j+1][2], 1.0f); + ColorBottom = ColorRGBA(s_aColorIndices[j + 1][0], s_aColorIndices[j + 1][1], s_aColorIndices[j + 1][2], 1.0f); ColorArray[0] = IGraphics::CColorVertex(0, ColorTop.r, ColorTop.g, ColorTop.b, ColorTop.a); ColorArray[1] = IGraphics::CColorVertex(1, ColorTop.r, ColorTop.g, ColorTop.b, ColorTop.a); ColorArray[2] = IGraphics::CColorVertex(2, ColorBottom.r, ColorBottom.g, ColorBottom.b, ColorBottom.a); ColorArray[3] = IGraphics::CColorVertex(3, ColorBottom.r, ColorBottom.g, ColorBottom.b, ColorBottom.a); pEditor->Graphics()->SetColorVertex(ColorArray, 4); - IGraphics::CQuadItem QuadItem(HuePicker.x, HuePicker.y+Offset*j, HuePicker.w, Offset); + IGraphics::CQuadItem QuadItem(HuePicker.x, HuePicker.y + Offset * j, HuePicker.w, Offset); pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); } @@ -1807,7 +1830,7 @@ int CEditor::PopupColorPicker(CEditor *pEditor, CUIRect View, void *pContext) if(pEditor->UI()->DoPickerLogic(&pEditor->ms_HuePicker, &HuePicker, &X, &Y)) { - hsv.x = 1.0f - Y/HuePicker.h; + hsv.x = 1.0f - Y / HuePicker.h; } pEditor->ms_PickerColor = hsv; @@ -1824,8 +1847,10 @@ int CEditor::PopupEntities(CEditor *pEditor, CUIRect View, void *pContext) const char *Name = pEditor->m_SelectEntitiesFiles[i].c_str(); - if(pEditor->DoButton_MenuItem(Name, Name, pEditor->m_SelectEntitiesFiles[i] == pEditor->m_SelectEntitiesImage, &Button)) { - if (pEditor->m_SelectEntitiesFiles[i] != pEditor->m_SelectEntitiesImage) { + if(pEditor->DoButton_MenuItem(Name, Name, pEditor->m_SelectEntitiesFiles[i] == pEditor->m_SelectEntitiesImage, &Button)) + { + if(pEditor->m_SelectEntitiesFiles[i] != pEditor->m_SelectEntitiesImage) + { pEditor->m_SelectEntitiesImage = pEditor->m_SelectEntitiesFiles[i]; pEditor->m_AllowPlaceUnusedTiles = pEditor->m_SelectEntitiesImage == "DDNet" ? 0 : -1; pEditor->m_PreventUnusedTilesWasWarned = false; diff --git a/src/game/extrainfo.cpp b/src/game/extrainfo.cpp index d9f88e324..097476ed2 100644 --- a/src/game/extrainfo.cpp +++ b/src/game/extrainfo.cpp @@ -1,14 +1,14 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "extrainfo.h" +#include #include #include -#include -#include "extrainfo.h" bool UseExtraInfo(const CNetObj_Projectile *pProj) { - bool ExtraInfoFlag = ((abs(pProj->m_VelY) & (1<<9)) != 0); + bool ExtraInfoFlag = ((abs(pProj->m_VelY) & (1 << 9)) != 0); return ExtraInfoFlag; } @@ -18,14 +18,14 @@ void ExtractInfo(const CNetObj_Projectile *pProj, vec2 *StartPos, vec2 *StartVel { StartPos->x = pProj->m_X; StartPos->y = pProj->m_Y; - StartVel->x = pProj->m_VelX/100.0f; - StartVel->y = pProj->m_VelY/100.0f; + StartVel->x = pProj->m_VelX / 100.0f; + StartVel->y = pProj->m_VelY / 100.0f; } else { - StartPos->x = pProj->m_X/100.0f; - StartPos->y = pProj->m_Y/100.0f; - float Angle = pProj->m_VelX/1000000.0f; + StartPos->x = pProj->m_X / 100.0f; + StartPos->y = pProj->m_Y / 100.0f; + float Angle = pProj->m_VelX / 1000000.0f; StartVel->x = sin(-Angle); StartVel->y = cos(-Angle); } @@ -37,26 +37,26 @@ void ExtractExtraInfo(const CNetObj_Projectile *pProj, int *Owner, bool *Explosi if(Owner) { *Owner = Data & 255; - if((Data>>8) & 1) + if((Data >> 8) & 1) *Owner = -(*Owner); } if(Bouncing) - *Bouncing = (Data>>10) & 3; + *Bouncing = (Data >> 10) & 3; if(Explosive) - *Explosive = (Data>>12) & 1; + *Explosive = (Data >> 12) & 1; if(Freeze) - *Freeze = (Data>>13) & 1; + *Freeze = (Data >> 13) & 1; } void SnapshotRemoveExtraInfo(unsigned char *pData) { - CSnapshot *pSnap = (CSnapshot*) pData; + CSnapshot *pSnap = (CSnapshot *)pData; for(int Index = 0; Index < pSnap->NumItems(); Index++) { CSnapshotItem *pItem = pSnap->GetItem(Index); if(pItem->Type() == NETOBJTYPE_PROJECTILE) { - CNetObj_Projectile *pProj = (CNetObj_Projectile*) ((void*)pItem->Data()); + CNetObj_Projectile *pProj = (CNetObj_Projectile *)((void *)pItem->Data()); if(UseExtraInfo(pProj)) { vec2 Pos; @@ -64,8 +64,8 @@ void SnapshotRemoveExtraInfo(unsigned char *pData) ExtractInfo(pProj, &Pos, &Vel); pProj->m_X = Pos.x; pProj->m_Y = Pos.y; - pProj->m_VelX = (int)(Vel.x*100.0f); - pProj->m_VelY = (int)(Vel.y*100.0f); + pProj->m_VelX = (int)(Vel.x * 100.0f); + pProj->m_VelY = (int)(Vel.y * 100.0f); } } } diff --git a/src/game/gamecore.cpp b/src/game/gamecore.cpp index 233be8ba9..3c5098478 100644 --- a/src/game/gamecore.cpp +++ b/src/game/gamecore.cpp @@ -5,13 +5,12 @@ #include const char *CTuningParams::ms_apNames[] = -{ - #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) #ScriptName, - #include "tuning.h" - #undef MACRO_TUNING_PARAM + { +#define MACRO_TUNING_PARAM(Name, ScriptName, Value, Description) #ScriptName, +#include "tuning.h" +#undef MACRO_TUNING_PARAM }; - bool CTuningParams::Set(int Index, float Value) { if(Index < 0 || Index >= Num()) @@ -47,14 +46,14 @@ bool CTuningParams::Get(const char *pName, float *pValue) float HermiteBasis1(float v) { - return 2*v*v*v - 3*v*v+1; + return 2 * v * v * v - 3 * v * v + 1; } float VelocityRamp(float Value, float Start, float Range, float Curvature) { if(Value < Start) return 1.0f; - return 1.0f/powf(Curvature, (Value-Start)/Range); + return 1.0f / powf(Curvature, (Value - Start) / Range); } void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams) @@ -71,7 +70,7 @@ void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore m_Jumps = 2; } -void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams, std::map > *pTeleOuts) +void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams, std::map> *pTeleOuts) { m_pWorld = pWorld; m_pCollision = pCollision; @@ -87,11 +86,11 @@ void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore void CCharacterCore::Reset() { - m_Pos = vec2(0,0); - m_Vel = vec2(0,0); + m_Pos = vec2(0, 0); + m_Vel = vec2(0, 0); m_NewHook = false; - m_HookPos = vec2(0,0); - m_HookDir = vec2(0,0); + m_HookPos = vec2(0, 0); + m_HookDir = vec2(0, 0); m_HookTick = 0; m_HookState = HOOK_IDLE; m_HookedPlayer = -1; @@ -129,9 +128,9 @@ void CCharacterCore::Tick(bool UseInput) // get ground state bool Grounded = false; - if(m_pCollision->CheckPoint(m_Pos.x+PhysSize/2, m_Pos.y+PhysSize/2+5)) + if(m_pCollision->CheckPoint(m_Pos.x + PhysSize / 2, m_Pos.y + PhysSize / 2 + 5)) Grounded = true; - if(m_pCollision->CheckPoint(m_Pos.x-PhysSize/2, m_Pos.y+PhysSize/2+5)) + if(m_pCollision->CheckPoint(m_Pos.x - PhysSize / 2, m_Pos.y + PhysSize / 2 + 5)) Grounded = true; vec2 TargetDirection = normalize(vec2(m_Input.m_TargetX, m_Input.m_TargetY)); @@ -152,17 +151,17 @@ void CCharacterCore::Tick(bool UseInput) if(m_Input.m_TargetX == 0) a = atanf((float)m_Input.m_TargetY); else - a = atanf((float)m_Input.m_TargetY/(float)m_Input.m_TargetX); + a = atanf((float)m_Input.m_TargetY / (float)m_Input.m_TargetX); if(m_Input.m_TargetX < 0) - a = a+pi; + a = a + pi; - m_Angle = (int)(a*256.0f); + m_Angle = (int)(a * 256.0f); // handle jump if(m_Input.m_Jump) { - if(!(m_Jumped&1)) + if(!(m_Jumped & 1)) { if(Grounded) { @@ -171,7 +170,7 @@ void CCharacterCore::Tick(bool UseInput) m_Jumped |= 1; m_JumpedTotal = 1; } - else if(!(m_Jumped&2)) + else if(!(m_Jumped & 2)) { m_TriggeredEvents |= COREEVENT_AIR_JUMP; m_Vel.y = -m_pWorld->m_Tuning[g_Config.m_ClDummy].m_AirJumpImpulse; @@ -189,7 +188,7 @@ void CCharacterCore::Tick(bool UseInput) if(m_HookState == HOOK_IDLE) { m_HookState = HOOK_FLYING; - m_HookPos = m_Pos+TargetDirection*PhysSize*1.5f; + m_HookPos = m_Pos + TargetDirection * PhysSize * 1.5f; m_HookDir = TargetDirection; m_HookedPlayer = -1; m_HookTick = SERVER_TICK_SPEED * (1.25f - m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDuration); @@ -240,12 +239,11 @@ void CCharacterCore::Tick(bool UseInput) } else if(m_HookState == HOOK_FLYING) { - vec2 NewPos = m_HookPos+m_HookDir*m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookFireSpeed; - if((!m_NewHook && distance(m_Pos, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength) - || (m_NewHook && distance(m_HookTeleBase, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength)) + vec2 NewPos = m_HookPos + m_HookDir * m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookFireSpeed; + if((!m_NewHook && distance(m_Pos, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength) || (m_NewHook && distance(m_HookTeleBase, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength)) { m_HookState = HOOK_RETRACT_START; - NewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength; + NewPos = m_Pos + normalize(NewPos - m_Pos) * m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength; m_pReset = true; } @@ -262,7 +260,7 @@ void CCharacterCore::Tick(bool UseInput) { if(Hit == TILE_NOHOOK) GoingToRetract = true; - else if (Hit == TILE_TELEINHOOK) + else if(Hit == TILE_TELEINHOOK) GoingThroughTele = true; else GoingToHitGround = true; @@ -280,9 +278,9 @@ void CCharacterCore::Tick(bool UseInput) continue; vec2 ClosestPoint = closest_point_on_line(m_HookPos, NewPos, pCharCore->m_Pos); - if(distance(pCharCore->m_Pos, ClosestPoint) < PhysSize+2.0f) + if(distance(pCharCore->m_Pos, ClosestPoint) < PhysSize + 2.0f) { - if (m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance) + if(m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance) { m_TriggeredEvents |= COREEVENT_HOOK_ATTACH_PLAYER; m_HookState = HOOK_GRABBED; @@ -307,14 +305,14 @@ void CCharacterCore::Tick(bool UseInput) m_HookState = HOOK_RETRACT_START; } - if(GoingThroughTele && m_pTeleOuts && m_pTeleOuts->size() && (*m_pTeleOuts)[teleNr-1].size()) + if(GoingThroughTele && m_pTeleOuts && m_pTeleOuts->size() && (*m_pTeleOuts)[teleNr - 1].size()) { m_TriggeredEvents = 0; m_HookedPlayer = -1; m_NewHook = true; - int RandomOut = m_pWorld->RandomOr0((*m_pTeleOuts)[teleNr-1].size()); - m_HookPos = (*m_pTeleOuts)[teleNr-1][RandomOut]+TargetDirection*PhysSize*1.5f; + int RandomOut = m_pWorld->RandomOr0((*m_pTeleOuts)[teleNr - 1].size()); + m_HookPos = (*m_pTeleOuts)[teleNr - 1][RandomOut] + TargetDirection * PhysSize * 1.5f; m_HookDir = TargetDirection; m_HookTeleBase = m_HookPos; } @@ -342,13 +340,13 @@ void CCharacterCore::Tick(bool UseInput) // keep players hooked for a max of 1.5sec //if(Server()->Tick() > hook_tick+(Server()->TickSpeed()*3)/2) - //release_hooked(); + //release_hooked(); } // don't do this hook rutine when we are hook to a player if(m_HookedPlayer == -1 && distance(m_HookPos, m_Pos) > 46.0f) { - vec2 HookVel = normalize(m_HookPos-m_Pos)*m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel; + vec2 HookVel = normalize(m_HookPos - m_Pos) * m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel; // the hook as more power to drag you up then down. // this makes it easier to get on top of an platform if(HookVel.y > 0) @@ -361,17 +359,16 @@ void CCharacterCore::Tick(bool UseInput) else HookVel.x *= 0.75f; - vec2 NewVel = m_Vel+HookVel; + vec2 NewVel = m_Vel + HookVel; // check if we are under the legal limit for the hook if(length(NewVel) < m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragSpeed || length(NewVel) < length(m_Vel)) m_Vel = NewVel; // no problem. apply - } // release hook (max default hook time is 1.25 s) m_HookTick++; - if(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED+SERVER_TICK_SPEED/5 || !m_pWorld->m_apCharacters[m_HookedPlayer])) + if(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED + SERVER_TICK_SPEED / 5 || !m_pWorld->m_apCharacters[m_HookedPlayer])) { m_HookedPlayer = -1; m_HookState = HOOK_RETRACTED; @@ -400,48 +397,44 @@ void CCharacterCore::Tick(bool UseInput) float Distance = distance(m_Pos, pCharCore->m_Pos); vec2 Dir = normalize(m_Pos - pCharCore->m_Pos); - bool CanCollide = (m_Super || pCharCore->m_Super) - || (pCharCore->m_Collision && m_Collision - && !m_NoCollision && !pCharCore->m_NoCollision - && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision - ); + bool CanCollide = (m_Super || pCharCore->m_Super) || (pCharCore->m_Collision && m_Collision && !m_NoCollision && !pCharCore->m_NoCollision && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision); - if(CanCollide && Distance < PhysSize*1.25f && Distance > 0.0f) + if(CanCollide && Distance < PhysSize * 1.25f && Distance > 0.0f) { - float a = (PhysSize*1.45f - Distance); + float a = (PhysSize * 1.45f - Distance); float Velocity = 0.5f; // make sure that we don't add excess force by checking the // direction against the current velocity. if not zero. - if (length(m_Vel) > 0.0001) - Velocity = 1-(dot(normalize(m_Vel), Dir)+1)/2; + if(length(m_Vel) > 0.0001) + Velocity = 1 - (dot(normalize(m_Vel), Dir) + 1) / 2; - m_Vel += Dir*a*(Velocity*0.75f); + m_Vel += Dir * a * (Velocity * 0.75f); m_Vel *= 0.85f; } // handle hook influence if(m_Hook && m_HookedPlayer == i && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking) { - if(Distance > PhysSize*1.50f) // TODO: fix tweakable variable + if(Distance > PhysSize * 1.50f) // TODO: fix tweakable variable { - float Accel = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel * (Distance/m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength); + float Accel = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel * (Distance / m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength); float DragSpeed = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragSpeed; vec2 Temp; // add force to the hooked player - Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel*Dir.x*1.5f); - Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel*Dir.y*1.5f); + Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel * Dir.x * 1.5f); + Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel * Dir.y * 1.5f); pCharCore->m_Vel = ClampVel(pCharCore->m_MoveRestrictions, Temp); // add a little bit force to the guy who has the grip - Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, -Accel*Dir.x*0.25f); - Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, -Accel*Dir.y*0.25f); + Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, -Accel * Dir.x * 0.25f); + Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, -Accel * Dir.y * 0.25f); m_Vel = ClampVel(m_MoveRestrictions, Temp); } } } - if (m_HookState != HOOK_FLYING) + if(m_HookState != HOOK_FLYING) { m_NewHook = false; } @@ -454,9 +447,9 @@ void CCharacterCore::Tick(bool UseInput) void CCharacterCore::Move() { - float RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); + float RampValue = VelocityRamp(length(m_Vel) * 50, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); - m_Vel.x = m_Vel.x*RampValue; + m_Vel.x = m_Vel.x * RampValue; vec2 NewPos = m_Pos; @@ -474,22 +467,22 @@ void CCharacterCore::Move() else m_LeftWall = true; - m_Vel.x = m_Vel.x*(1.0f/RampValue); + m_Vel.x = m_Vel.x * (1.0f / RampValue); if(m_pWorld && (m_Super || (m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision && m_Collision && !m_NoCollision && !m_Solo))) { // check player collision float Distance = distance(m_Pos, NewPos); - int End = Distance+1; + int End = Distance + 1; vec2 LastPos = m_Pos; for(int i = 0; i < End; i++) { - float a = i/Distance; + float a = i / Distance; vec2 Pos = mix(m_Pos, NewPos, a); for(int p = 0; p < MAX_CLIENTS; p++) { CCharacterCore *pCharCore = m_pWorld->m_apCharacters[p]; - if(!pCharCore || pCharCore == this ) + if(!pCharCore || pCharCore == this) continue; if((!(pCharCore->m_Super || m_Super) && (m_Solo || pCharCore->m_Solo || !pCharCore->m_Collision || pCharCore->m_NoCollision || (m_Id != -1 && !m_pTeams->CanCollide(m_Id, p))))) continue; @@ -515,14 +508,14 @@ void CCharacterCore::Write(CNetObj_CharacterCore *pObjCore) pObjCore->m_X = round_to_int(m_Pos.x); pObjCore->m_Y = round_to_int(m_Pos.y); - pObjCore->m_VelX = round_to_int(m_Vel.x*256.0f); - pObjCore->m_VelY = round_to_int(m_Vel.y*256.0f); + pObjCore->m_VelX = round_to_int(m_Vel.x * 256.0f); + pObjCore->m_VelY = round_to_int(m_Vel.y * 256.0f); pObjCore->m_HookState = m_HookState; pObjCore->m_HookTick = m_HookTick; pObjCore->m_HookX = round_to_int(m_HookPos.x); pObjCore->m_HookY = round_to_int(m_HookPos.y); - pObjCore->m_HookDx = round_to_int(m_HookDir.x*256.0f); - pObjCore->m_HookDy = round_to_int(m_HookDir.y*256.0f); + pObjCore->m_HookDx = round_to_int(m_HookDir.x * 256.0f); + pObjCore->m_HookDy = round_to_int(m_HookDir.y * 256.0f); pObjCore->m_HookedPlayer = m_HookedPlayer; pObjCore->m_Jumped = m_Jumped; pObjCore->m_Direction = m_Direction; @@ -533,14 +526,14 @@ void CCharacterCore::Read(const CNetObj_CharacterCore *pObjCore) { m_Pos.x = pObjCore->m_X; m_Pos.y = pObjCore->m_Y; - m_Vel.x = pObjCore->m_VelX/256.0f; - m_Vel.y = pObjCore->m_VelY/256.0f; + m_Vel.x = pObjCore->m_VelX / 256.0f; + m_Vel.y = pObjCore->m_VelY / 256.0f; m_HookState = pObjCore->m_HookState; m_HookTick = pObjCore->m_HookTick; m_HookPos.x = pObjCore->m_HookX; m_HookPos.y = pObjCore->m_HookY; - m_HookDir.x = pObjCore->m_HookDx/256.0f; - m_HookDir.y = pObjCore->m_HookDy/256.0f; + m_HookDir.x = pObjCore->m_HookDx / 256.0f; + m_HookDir.y = pObjCore->m_HookDy / 256.0f; m_HookedPlayer = pObjCore->m_HookedPlayer; m_Jumped = pObjCore->m_Jumped; m_Direction = pObjCore->m_Direction; diff --git a/src/game/gamecore.h b/src/game/gamecore.h index 277401389..ebedfd85d 100644 --- a/src/game/gamecore.h +++ b/src/game/gamecore.h @@ -3,31 +3,39 @@ #ifndef GAME_GAMECORE_H #define GAME_GAMECORE_H -#include #include +#include #include #include -#include #include "collision.h" #include #include +#include +#include "mapitems.h" #include "prng.h" #include "teamscore.h" -#include "mapitems.h" - class CTuneParam { int m_Value; + public: void Set(int v) { m_Value = v; } int Get() const { return m_Value; } - CTuneParam &operator = (int v) { m_Value = (int)(v*100.0f); return *this; } - CTuneParam &operator = (float v) { m_Value = (int)(v*100.0f); return *this; } - operator float() const { return m_Value/100.0f; } + CTuneParam &operator=(int v) + { + m_Value = (int)(v * 100.0f); + return *this; + } + CTuneParam &operator=(float v) + { + m_Value = (int)(v * 100.0f); + return *this; + } + operator float() const { return m_Value / 100.0f; } }; class CTuningParams @@ -36,28 +44,30 @@ public: CTuningParams() { const float TicksPerSecond = 50.0f; - #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) m_##Name.Set((int)(Value*100.0f)); - #include "tuning.h" - #undef MACRO_TUNING_PARAM +#define MACRO_TUNING_PARAM(Name, ScriptName, Value, Description) m_##Name.Set((int)(Value * 100.0f)); +#include "tuning.h" +#undef MACRO_TUNING_PARAM } static const char *ms_apNames[]; - #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) CTuneParam m_##Name; - #include "tuning.h" - #undef MACRO_TUNING_PARAM +#define MACRO_TUNING_PARAM(Name, ScriptName, Value, Description) CTuneParam m_##Name; +#include "tuning.h" +#undef MACRO_TUNING_PARAM - static int Num() { return sizeof(CTuningParams)/sizeof(int); } + static int Num() + { + return sizeof(CTuningParams) / sizeof(int); + } bool Set(int Index, float Value); bool Set(const char *pName, float Value); bool Get(int Index, float *pValue); bool Get(const char *pName, float *pValue); }; - inline vec2 GetDirection(int Angle) { - float a = Angle/256.0f; + float a = Angle / 256.0f; return vec2(cosf(a), sinf(a)); } @@ -70,9 +80,9 @@ inline float GetAngle(vec2 Dir) { if(Dir.x == 0 && Dir.y == 0) return 0.0f; - float a = atanf(Dir.y/Dir.x); + float a = atanf(Dir.y / Dir.x); if(Dir.x < 0) - a = a+pi; + a = a + pi; return a; } @@ -81,7 +91,7 @@ inline void StrToInts(int *pInts, int Num, const char *pStr) int Index = 0; while(Num) { - char aBuf[4] = {0,0,0,0}; + char aBuf[4] = {0, 0, 0, 0}; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" // false positive @@ -91,7 +101,7 @@ inline void StrToInts(int *pInts, int Num, const char *pStr) #ifdef __GNUC__ #pragma GCC diagnostic pop #endif - *pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128); + *pInts = ((aBuf[0] + 128) << 24) | ((aBuf[1] + 128) << 16) | ((aBuf[2] + 128) << 8) | (aBuf[3] + 128); pInts++; Num--; } @@ -104,10 +114,10 @@ inline void IntsToStr(const int *pInts, int Num, char *pStr) { while(Num) { - pStr[0] = (((*pInts)>>24)&0xff)-128; - pStr[1] = (((*pInts)>>16)&0xff)-128; - pStr[2] = (((*pInts)>>8)&0xff)-128; - pStr[3] = ((*pInts)&0xff)-128; + pStr[0] = (((*pInts) >> 24) & 0xff) - 128; + pStr[1] = (((*pInts) >> 16) & 0xff) - 128; + pStr[2] = (((*pInts) >> 8) & 0xff) - 128; + pStr[3] = ((*pInts) & 0xff) - 128; pStr += 4; pInts++; Num--; @@ -124,18 +134,15 @@ inline void IntsToStr(const int *pInts, int Num, char *pStr) #endif } - - inline vec2 CalcPos(vec2 Pos, vec2 Velocity, float Curvature, float Speed, float Time) { vec2 n; Time *= Speed; - n.x = Pos.x + Velocity.x*Time; - n.y = Pos.y + Velocity.y*Time + Curvature/10000*(Time*Time); + n.x = Pos.x + Velocity.x * Time; + n.y = Pos.y + Velocity.y * Time + Curvature / 10000 * (Time * Time); return n; } - template inline T SaturatedAdd(T Min, T Max, T Current, T Modifier) { @@ -159,26 +166,25 @@ inline T SaturatedAdd(T Min, T Max, T Current, T Modifier) } } - float VelocityRamp(float Value, float Start, float Range, float Curvature); // hooking stuff enum { - HOOK_RETRACTED=-1, - HOOK_IDLE=0, - HOOK_RETRACT_START=1, - HOOK_RETRACT_END=3, + HOOK_RETRACTED = -1, + HOOK_IDLE = 0, + HOOK_RETRACT_START = 1, + HOOK_RETRACT_END = 3, HOOK_FLYING, HOOK_GRABBED, - COREEVENT_GROUND_JUMP=0x01, - COREEVENT_AIR_JUMP=0x02, - COREEVENT_HOOK_LAUNCH=0x04, - COREEVENT_HOOK_ATTACH_PLAYER=0x08, - COREEVENT_HOOK_ATTACH_GROUND=0x10, - COREEVENT_HOOK_HIT_NOHOOK=0x20, - COREEVENT_HOOK_RETRACT=0x40, + COREEVENT_GROUND_JUMP = 0x01, + COREEVENT_AIR_JUMP = 0x02, + COREEVENT_HOOK_LAUNCH = 0x04, + COREEVENT_HOOK_ATTACH_PLAYER = 0x08, + COREEVENT_HOOK_ATTACH_GROUND = 0x10, + COREEVENT_HOOK_HIT_NOHOOK = 0x20, + COREEVENT_HOOK_RETRACT = 0x40, //COREEVENT_HOOK_TELE=0x80, }; @@ -213,7 +219,8 @@ class CCharacterCore friend class CCharacter; CWorldCore *m_pWorld; CCollision *m_pCollision; - std::map > *m_pTeleOuts; + std::map> *m_pTeleOuts; + public: vec2 m_Pos; vec2 m_Vel; @@ -241,7 +248,7 @@ public: int m_TriggeredEvents; void Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams); - void Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams, std::map > *pTeleOuts); + void Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore *pTeams, std::map> *pTeleOuts); void Reset(); void Tick(bool UseInput); void Move(); @@ -280,7 +287,6 @@ public: bool m_DeepFrozen; private: - CTeamsCore *m_pTeams; int m_MoveRestrictions; static bool IsSwitchActiveCb(int Number, void *pUser); @@ -302,8 +308,8 @@ inline CInputCount CountInput(int Prev, int Cur) while(i != Cur) { - i = (i+1)&INPUT_STATE_MASK; - if(i&1) + i = (i + 1) & INPUT_STATE_MASK; + if(i & 1) c.m_Presses++; else c.m_Releases++; diff --git a/src/game/layers.cpp b/src/game/layers.cpp index 49280180f..6d833a076 100644 --- a/src/game/layers.cpp +++ b/src/game/layers.cpp @@ -36,13 +36,13 @@ void CLayers::Init(class IKernel *pKernel) CMapItemGroup *pGroup = GetGroup(g); for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer + l); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemap = reinterpret_cast(pLayer); - if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) + if(pTilemap->m_Flags & TILESLAYERFLAG_GAME) { m_pGameLayer = pTilemap; m_pGameGroup = pGroup; @@ -64,43 +64,43 @@ void CLayers::Init(class IKernel *pKernel) //break; } - if(pTilemap->m_Flags&TILESLAYERFLAG_TELE) + if(pTilemap->m_Flags & TILESLAYERFLAG_TELE) { if(pTilemap->m_Version <= 2) { - pTilemap->m_Tele = *((int*)(pTilemap) + 15); + pTilemap->m_Tele = *((int *)(pTilemap) + 15); } m_pTeleLayer = pTilemap; } - if(pTilemap->m_Flags&TILESLAYERFLAG_SPEEDUP) + if(pTilemap->m_Flags & TILESLAYERFLAG_SPEEDUP) { if(pTilemap->m_Version <= 2) { - pTilemap->m_Speedup = *((int*)(pTilemap) + 16); + pTilemap->m_Speedup = *((int *)(pTilemap) + 16); } m_pSpeedupLayer = pTilemap; } - if(pTilemap->m_Flags&TILESLAYERFLAG_FRONT) + if(pTilemap->m_Flags & TILESLAYERFLAG_FRONT) { if(pTilemap->m_Version <= 2) { - pTilemap->m_Front = *((int*)(pTilemap) + 17); + pTilemap->m_Front = *((int *)(pTilemap) + 17); } m_pFrontLayer = pTilemap; } - if(pTilemap->m_Flags&TILESLAYERFLAG_SWITCH) + if(pTilemap->m_Flags & TILESLAYERFLAG_SWITCH) { if(pTilemap->m_Version <= 2) { - pTilemap->m_Switch = *((int*)(pTilemap) + 18); + pTilemap->m_Switch = *((int *)(pTilemap) + 18); } m_pSwitchLayer = pTilemap; } - if(pTilemap->m_Flags&TILESLAYERFLAG_TUNE) + if(pTilemap->m_Flags & TILESLAYERFLAG_TUNE) { if(pTilemap->m_Version <= 2) { - pTilemap->m_Tune = *((int*)(pTilemap) + 19); + pTilemap->m_Tune = *((int *)(pTilemap) + 19); } m_pTuneLayer = pTilemap; } @@ -127,13 +127,13 @@ void CLayers::InitBackground(class IMap *pMap) CMapItemGroup *pGroup = GetGroup(g); for(int l = 0; l < pGroup->m_NumLayers; l++) { - CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); + CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer + l); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemap = reinterpret_cast(pLayer); - if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) + if(pTilemap->m_Flags & TILESLAYERFLAG_GAME) { m_pGameLayer = pTilemap; m_pGameGroup = pGroup; @@ -161,11 +161,10 @@ void CLayers::InitBackground(class IMap *pMap) CMapItemGroup *CLayers::GetGroup(int Index) const { - return static_cast(m_pMap->GetItem(m_GroupsStart+Index, 0, 0)); + return static_cast(m_pMap->GetItem(m_GroupsStart + Index, 0, 0)); } CMapItemLayer *CLayers::GetLayer(int Index) const { - return static_cast(m_pMap->GetItem(m_LayersStart+Index, 0, 0)); + return static_cast(m_pMap->GetItem(m_LayersStart + Index, 0, 0)); } - diff --git a/src/game/layers.h b/src/game/layers.h index 7bc964d49..fa8d6ac93 100644 --- a/src/game/layers.h +++ b/src/game/layers.h @@ -36,7 +36,6 @@ public: CMapItemLayerTilemap *TuneLayer() const { return m_pTuneLayer; }; private: - CMapItemLayerTilemap *m_pTeleLayer; CMapItemLayerTilemap *m_pSpeedupLayer; CMapItemLayerTilemap *m_pFrontLayer; diff --git a/src/game/localization.cpp b/src/game/localization.cpp index 1dc0d9419..2dcb4f939 100644 --- a/src/game/localization.cpp +++ b/src/game/localization.cpp @@ -4,8 +4,8 @@ #include "localization.h" #include -#include #include +#include #include const char *Localize(const char *pStr, const char *pContext) diff --git a/src/game/localization.h b/src/game/localization.h index 834ccadda..010c5748c 100644 --- a/src/game/localization.h +++ b/src/game/localization.h @@ -2,8 +2,8 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_LOCALIZATION_H #define GAME_LOCALIZATION_H -#include #include +#include class CLocalizationDatabase { diff --git a/src/game/mapbugs.cpp b/src/game/mapbugs.cpp index e33b8fa72..8f1e4f99e 100644 --- a/src/game/mapbugs.cpp +++ b/src/game/mapbugs.cpp @@ -12,8 +12,8 @@ struct CMapDescription bool operator==(const CMapDescription &Other) const { return str_comp(m_pName, Other.m_pName) == 0 && - m_Size == Other.m_Size && - m_Crc == Other.m_Crc; + m_Size == Other.m_Size && + m_Crc == Other.m_Crc; } }; @@ -43,9 +43,8 @@ static SHA256_DIGEST s(const char *pSha256) } static CMapBugsInternal MAP_BUGS[] = -{ - {{"Binary", 2022597, s("65b410e197fd2298ec270e89a84b762f6739d1d18089529f8ef6cf2104d3d600"), 0x0ae3a3d5}, BugToFlag(BUG_GRENADE_DOUBLEEXPLOSION)} -}; + { + {{"Binary", 2022597, s("65b410e197fd2298ec270e89a84b762f6739d1d18089529f8ef6cf2104d3d600"), 0x0ae3a3d5}, BugToFlag(BUG_GRENADE_DOUBLEEXPLOSION)}}; CMapBugs GetMapBugs(const char *pName, int Size, SHA256_DIGEST Sha256, int Crc) { @@ -79,7 +78,8 @@ int CMapBugs::Update(const char *pBug) CMapBugsInternal *pInternal = (CMapBugsInternal *)m_pData; int Bug = -1; if(false) {} -#define MAPBUG(constname, string) else if(str_comp(pBug, string) == 0) { Bug = constname; } +#define MAPBUG(constname, string) \ + else if(str_comp(pBug, string) == 0) { Bug = constname; } #include "mapbugs_list.h" #undef MAPBUG if(Bug == -1) diff --git a/src/game/mapitems.h b/src/game/mapitems.h index bc8eea4e3..10f6d9b8d 100644 --- a/src/game/mapitems.h +++ b/src/game/mapitems.h @@ -245,12 +245,12 @@ struct CMapItemInfo int m_MapVersion; int m_Credits; int m_License; -} ; +}; struct CMapItemInfoSettings : CMapItemInfo { int m_Settings; -} ; +}; struct CMapItemImage { @@ -260,7 +260,7 @@ struct CMapItemImage int m_External; int m_ImageName; int m_ImageData; -} ; +}; struct CMapItemGroup_v1 { @@ -272,12 +272,14 @@ struct CMapItemGroup_v1 int m_StartLayer; int m_NumLayers; -} ; - +}; struct CMapItemGroup : public CMapItemGroup_v1 { - enum { CURRENT_VERSION=3 }; + enum + { + CURRENT_VERSION = 3 + }; int m_UseClipping; int m_ClipX; @@ -286,14 +288,14 @@ struct CMapItemGroup : public CMapItemGroup_v1 int m_ClipH; int m_aName[3]; -} ; +}; struct CMapItemLayer { int m_Version; int m_Type; int m_Flags; -} ; +}; struct CMapItemLayerTilemap { @@ -320,7 +322,7 @@ struct CMapItemLayerTilemap int m_Front; int m_Switch; int m_Tune; -} ; +}; struct CMapItemLayerQuads { @@ -332,12 +334,12 @@ struct CMapItemLayerQuads int m_Image; int m_aName[3]; -} ; +}; struct CMapItemVersion { int m_Version; -} ; +}; struct CEnvPoint { @@ -346,7 +348,7 @@ struct CEnvPoint int m_aValues[4]; // 1-4 depending on envelope (22.10 fixed point) bool operator<(const CEnvPoint &Other) { return m_Time < Other.m_Time; } -} ; +}; struct CMapItemEnvelope_v1 { @@ -355,11 +357,14 @@ struct CMapItemEnvelope_v1 int m_StartPoint; int m_NumPoints; int m_aName[8]; -} ; +}; struct CMapItemEnvelope : public CMapItemEnvelope_v1 { - enum { CURRENT_VERSION=2 }; + enum + { + CURRENT_VERSION = 2 + }; int m_Synchronized; }; @@ -409,7 +414,10 @@ struct CSoundSource struct CMapItemLayerSounds { - enum { CURRENT_VERSION=2 }; + enum + { + CURRENT_VERSION = 2 + }; CMapItemLayer m_Layer; int m_Version; @@ -430,7 +438,7 @@ struct CMapItemSound int m_SoundName; int m_SoundData; int m_SoundDataSize; -} ; +}; // DDRace @@ -474,7 +482,6 @@ public: unsigned char m_Type; }; - bool IsValidGameTile(int Index); bool IsValidFrontTile(int Index); bool IsValidTeleTile(int Index); diff --git a/src/game/mapitems_ex.cpp b/src/game/mapitems_ex.cpp index 72df3c87f..68c29a3e2 100644 --- a/src/game/mapitems_ex.cpp +++ b/src/game/mapitems_ex.cpp @@ -4,7 +4,7 @@ void RegisterMapItemTypeUuids(CUuidManager *pManager) { - #define UUID(id, name) pManager->RegisterName(id, name); - #include "mapitems_ex_types.h" - #undef UUID +#define UUID(id, name) pManager->RegisterName(id, name); +#include "mapitems_ex_types.h" +#undef UUID } diff --git a/src/game/mapitems_ex.h b/src/game/mapitems_ex.h index 739917117..c67b36218 100644 --- a/src/game/mapitems_ex.h +++ b/src/game/mapitems_ex.h @@ -4,27 +4,36 @@ enum { - __MAPITEMTYPE_UUID_HELPER=OFFSET_MAPITEMTYPE_UUID-1, - #define UUID(id, name) id, - #include "mapitems_ex_types.h" - #undef UUID + __MAPITEMTYPE_UUID_HELPER = OFFSET_MAPITEMTYPE_UUID - 1, +#define UUID(id, name) id, +#include "mapitems_ex_types.h" +#undef UUID END_MAPITEMTYPES_UUID, }; struct CMapItemTest { - enum { CURRENT_VERSION=1 }; + enum + { + CURRENT_VERSION = 1 + }; int m_Version; int m_aFields[2]; int m_Field3; int m_Field4; -} ; +}; struct CMapItemAutoMapperConfig { - enum { CURRENT_VERSION=1 }; - enum { FLAG_AUTOMATIC=1 }; + enum + { + CURRENT_VERSION = 1 + }; + enum + { + FLAG_AUTOMATIC = 1 + }; int m_Version; int m_GroupId; @@ -32,9 +41,7 @@ struct CMapItemAutoMapperConfig int m_AutomapperConfig; int m_AutomapperSeed; int m_Flags; -} ; - - +}; void RegisterMapItemTypeUuids(class CUuidManager *pManager); #endif // GAME_MAPITEMS_EX_H diff --git a/src/game/mapitems_ex_types.h b/src/game/mapitems_ex_types.h index 594036cf6..116f9da97 100644 --- a/src/game/mapitems_ex_types.h +++ b/src/game/mapitems_ex_types.h @@ -1,4 +1,4 @@ // This file can be included several times. -UUID(MAPITEMTYPE_TEST, "mapitemtype-test@ddnet.tw") +UUID(MAPITEMTYPE_TEST, "mapitemtype-test@ddnet.tw") UUID(MAPITEMTYPE_AUTOMAPPER_CONFIG, "mapitemtype-automapper-config@ddnet.tw") diff --git a/src/game/prng.cpp b/src/game/prng.cpp index f1fd53865..bfa4cc68f 100644 --- a/src/game/prng.cpp +++ b/src/game/prng.cpp @@ -12,7 +12,6 @@ CPrng::CPrng() : { } - const char *CPrng::Description() const { if(!m_Seeded) diff --git a/src/game/server/ddracechat.cpp b/src/game/server/ddracechat.cpp index 280bc831a..a50d06cbc 100644 --- a/src/game/server/ddracechat.cpp +++ b/src/game/server/ddracechat.cpp @@ -3,15 +3,15 @@ #include #include #include -#include #include +#include #include bool CheckClientID(int ClientID); void CGameContext::ConCredits(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credits", "DDNet is run by the DDNet staff (DDNet.tw/staff)"); @@ -45,9 +45,9 @@ void CGameContext::ConCredits(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConInfo(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", - "DDraceNetwork Mod. Version: " GAME_VERSION); + "DDraceNetwork Mod. Version: " GAME_VERSION); if(GIT_SHORTREV_HASH) { char aBuf[64]; @@ -55,18 +55,19 @@ void CGameContext::ConInfo(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", aBuf); } pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", - "Official site: DDNet.tw"); + "Official site: DDNet.tw"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", - "For more info: /cmdlist"); + "For more info: /cmdlist"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", - "Or visit DDNet.tw"); + "Or visit DDNet.tw"); } void CGameContext::ConList(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; int ClientID = pResult->m_ClientID; - if(!CheckClientID(ClientID)) return; + if(!CheckClientID(ClientID)) + return; char zerochar = 0; if(pResult->NumArguments() > 0) @@ -77,54 +78,54 @@ void CGameContext::ConList(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConHelp(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; - if (pResult->NumArguments() == 0) + if(pResult->NumArguments() == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", - "/cmdlist will show a list of all chat commands"); + "/cmdlist will show a list of all chat commands"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", - "/help + any command will show you the help for this command"); + "/help + any command will show you the help for this command"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", - "Example /help settings will display the help about /settings"); + "Example /help settings will display the help about /settings"); } else { const char *pArg = pResult->GetString(0); const IConsole::CCommandInfo *pCmdInfo = - pSelf->Console()->GetCommandInfo(pArg, CFGFLAG_SERVER, false); - if (pCmdInfo) + pSelf->Console()->GetCommandInfo(pArg, CFGFLAG_SERVER, false); + if(pCmdInfo) { - if (pCmdInfo->m_pParams) + if(pCmdInfo->m_pParams) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Usage: %s %s", pCmdInfo->m_pName, pCmdInfo->m_pParams); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", aBuf); } - if (pCmdInfo->m_pHelp) + if(pCmdInfo->m_pHelp) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", pCmdInfo->m_pHelp); } else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "help", - "Command is either unknown or you have given a blank command without any parameters."); + IConsole::OUTPUT_LEVEL_STANDARD, + "help", + "Command is either unknown or you have given a blank command without any parameters."); } } void CGameContext::ConSettings(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; - if (pResult->NumArguments() == 0) + if(pResult->NumArguments() == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", - "to check a server setting say /settings and setting's name, setting names are:"); + "to check a server setting say /settings and setting's name, setting names are:"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", - "teams, cheats, collision, hooking, endlesshooking, me, "); + "teams, cheats, collision, hooking, endlesshooking, me, "); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", - "hitting, oldlaser, timeout, votes, pause and scores"); + "hitting, oldlaser, timeout, votes, pause and scores"); } else { @@ -134,124 +135,132 @@ void CGameContext::ConSettings(IConsole::IResult *pResult, void *pUserData) float HookTemp; pSelf->m_Tuning.Get("player_collision", &ColTemp); pSelf->m_Tuning.Get("player_hooking", &HookTemp); - if (str_comp(pArg, "teams") == 0) + if(str_comp(pArg, "teams") == 0) { str_format(aBuf, sizeof(aBuf), "%s %s", - g_Config.m_SvTeam == 1 ? - "Teams are available on this server" : - (g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) ? - "Teams are not available on this server" : - "You have to be in a team to play on this server", /*g_Config.m_SvTeamStrict ? "and if you die in a team all of you die" : */ - "and all of your team will die if the team is locked"); + g_Config.m_SvTeam == 1 ? + "Teams are available on this server" : + (g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) ? + "Teams are not available on this server" : + "You have to be in a team to play on this server", /*g_Config.m_SvTeamStrict ? "and if you die in a team all of you die" : */ + "and all of your team will die if the team is locked"); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", aBuf); } - else if (str_comp(pArg, "cheats") == 0) + else if(str_comp(pArg, "cheats") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvTestingCommands ? - "Cheats are enabled on this server" : - "Cheats are disabled on this server"); + "Cheats are enabled on this server" : + "Cheats are disabled on this server"); } - else if (str_comp(pArg, "collision") == 0) + else if(str_comp(pArg, "collision") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", ColTemp ? - "Players can collide on this server" : - "Players can't collide on this server"); + "Players can collide on this server" : + "Players can't collide on this server"); } - else if (str_comp(pArg, "hooking") == 0) + else if(str_comp(pArg, "hooking") == 0) { - pSelf->Console()->Print( IConsole::OUTPUT_LEVEL_STANDARD, "settings", + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", HookTemp ? - "Players can hook each other on this server" : - "Players can't hook each other on this server"); + "Players can hook each other on this server" : + "Players can't hook each other on this server"); } - else if (str_comp(pArg, "endlesshooking") == 0) + else if(str_comp(pArg, "endlesshooking") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvEndlessDrag ? - "Players hook time is unlimited" : - "Players hook time is limited"); + "Players hook time is unlimited" : + "Players hook time is limited"); } - else if (str_comp(pArg, "hitting") == 0) + else if(str_comp(pArg, "hitting") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvHit ? - "Players weapons affect others" : - "Players weapons has no affect on others"); + "Players weapons affect others" : + "Players weapons has no affect on others"); } - else if (str_comp(pArg, "oldlaser") == 0) + else if(str_comp(pArg, "oldlaser") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvOldLaser ? - "Lasers can hit you if you shot them and they pull you towards the bounce origin (Like DDRace Beta)" : - "Lasers can't hit you if you shot them, and they pull others towards the shooter"); + "Lasers can hit you if you shot them and they pull you towards the bounce origin (Like DDRace Beta)" : + "Lasers can't hit you if you shot them, and they pull others towards the shooter"); } - else if (str_comp(pArg, "me") == 0) + else if(str_comp(pArg, "me") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvSlashMe ? - "Players can use /me commands the famous IRC Command" : - "Players can't use the /me command"); + "Players can use /me commands the famous IRC Command" : + "Players can't use the /me command"); } - else if (str_comp(pArg, "timeout") == 0) + else if(str_comp(pArg, "timeout") == 0) { str_format(aBuf, sizeof(aBuf), "The Server Timeout is currently set to %d seconds", g_Config.m_ConnTimeout); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", aBuf); } - else if (str_comp(pArg, "votes") == 0) + else if(str_comp(pArg, "votes") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvVoteKick ? - "Players can use Callvote menu tab to kick offenders" : - "Players can't use the Callvote menu tab to kick offenders"); - if (g_Config.m_SvVoteKick) + "Players can use Callvote menu tab to kick offenders" : + "Players can't use the Callvote menu tab to kick offenders"); + if(g_Config.m_SvVoteKick) { str_format(aBuf, sizeof(aBuf), - "Players are banned for %d minute(s) if they get voted off", g_Config.m_SvVoteKickBantime); + "Players are banned for %d minute(s) if they get voted off", g_Config.m_SvVoteKickBantime); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", - g_Config.m_SvVoteKickBantime ? - aBuf : - "Players are just kicked and not banned if they get voted off"); + g_Config.m_SvVoteKickBantime ? + aBuf : + "Players are just kicked and not banned if they get voted off"); } } - else if (str_comp(pArg, "pause") == 0) + else if(str_comp(pArg, "pause") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvPauseable ? - "/spec will pause you and your tee will vanish" : - "/spec will pause you but your tee will not vanish"); + "/spec will pause you and your tee will vanish" : + "/spec will pause you but your tee will not vanish"); } - else if (str_comp(pArg, "scores") == 0) + else if(str_comp(pArg, "scores") == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", g_Config.m_SvHideScore ? - "Scores are private on this server" : - "Scores are public on this server"); + "Scores are private on this server" : + "Scores are public on this server"); } else { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", - "no matching settings found, type /settings to view them"); + "no matching settings found, type /settings to view them"); } } } void CGameContext::ConRules(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; bool Printed = false; - if (g_Config.m_SvDDRaceRules) + if(g_Config.m_SvDDRaceRules) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", - "Be nice."); + "Be nice."); Printed = true; } - #define _RL(n) g_Config.m_SvRulesLine ## n +#define _RL(n) g_Config.m_SvRulesLine##n char *pRuleLines[] = { - _RL(1), _RL(2), _RL(3), _RL(4), _RL(5), - _RL(6), _RL(7), _RL(8), _RL(9), _RL(10), + _RL(1), + _RL(2), + _RL(3), + _RL(4), + _RL(5), + _RL(6), + _RL(7), + _RL(8), + _RL(9), + _RL(10), }; for(unsigned i = 0; i < sizeof(pRuleLines) / sizeof(pRuleLines[0]); i++) { @@ -262,10 +271,10 @@ void CGameContext::ConRules(IConsole::IResult *pResult, void *pUserData) Printed = true; } } - if (!Printed) + if(!Printed) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", - "No Rules Defined, Kill em all!!"); + "No Rules Defined, Kill em all!!"); } } @@ -274,8 +283,8 @@ void ToggleSpecPause(IConsole::IResult *pResult, void *pUserData, int PauseType) if(!CheckClientID(pResult->m_ClientID)) return; - CGameContext *pSelf = (CGameContext *) pUserData; - IServer* pServ = pSelf->Server(); + CGameContext *pSelf = (CGameContext *)pUserData; + IServer *pServ = pSelf->Server(); CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; if(!pPlayer) return; @@ -314,7 +323,7 @@ void ToggleSpecPauseVoted(IConsole::IResult *pResult, void *pUserData, int Pause if(!CheckClientID(pResult->m_ClientID)) return; - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; if(!pPlayer) return; @@ -322,7 +331,7 @@ void ToggleSpecPauseVoted(IConsole::IResult *pResult, void *pUserData, int Pause int PauseState = pPlayer->IsPaused(); if(PauseState > 0) { - IServer* pServ = pSelf->Server(); + IServer *pServ = pSelf->Server(); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "You are force-paused for %d seconds.", (PauseState - pServ->Tick()) / pServ->TickSpeed()); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "spec", aBuf); @@ -330,8 +339,8 @@ void ToggleSpecPauseVoted(IConsole::IResult *pResult, void *pUserData, int Pause } bool IsPlayerBeingVoted = pSelf->m_VoteCloseTime && - (pSelf->IsKickVote() || pSelf->IsSpecVote()) && - pResult->m_ClientID != pSelf->m_VoteVictim; + (pSelf->IsKickVote() || pSelf->IsSpecVote()) && + pResult->m_ClientID != pSelf->m_VoteVictim; if((!IsPlayerBeingVoted && -PauseState == PauseType) || (IsPlayerBeingVoted && PauseState && pPlayer->m_SpectatorID == pSelf->m_VoteVictim)) { @@ -367,18 +376,18 @@ void CGameContext::ConTogglePauseVoted(IConsole::IResult *pResult, void *pUserDa void CGameContext::ConTeamTop5(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (g_Config.m_SvHideScore) + if(g_Config.m_SvHideScore) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "teamtop5", - "Showing the team top 5 is not allowed on this server."); + "Showing the team top 5 is not allowed on this server."); return; } - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) pSelf->Score()->ShowTeamTop5(pResult->m_ClientID, pResult->GetInteger(0)); else pSelf->Score()->ShowTeamTop5(pResult->m_ClientID); @@ -386,18 +395,18 @@ void CGameContext::ConTeamTop5(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConTop5(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (g_Config.m_SvHideScore) + if(g_Config.m_SvHideScore) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "top5", - "Showing the top 5 is not allowed on this server."); + "Showing the top 5 is not allowed on this server."); return; } - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) pSelf->Score()->ShowTop5(pResult->m_ClientID, pResult->GetInteger(0)); else pSelf->Score()->ShowTop5(pResult->m_ClientID); @@ -422,14 +431,16 @@ void CGameContext::ConTimes(IConsole::IResult *pResult, void *pUserData) else { const char *pRequestedName = (str_comp(pResult->GetString(0), "me") == 0) ? - pSelf->Server()->ClientName(pResult->m_ClientID) : pResult->GetString(0); + pSelf->Server()->ClientName(pResult->m_ClientID) : + pResult->GetString(0); pSelf->Score()->ShowTimes(pResult->m_ClientID, pRequestedName, pResult->GetInteger(1)); } } else if(pResult->NumArguments() == 2 && pResult->GetInteger(1) != 0) { const char *pRequestedName = (str_comp(pResult->GetString(0), "me") == 0) ? - pSelf->Server()->ClientName(pResult->m_ClientID) : pResult->GetString(0); + pSelf->Server()->ClientName(pResult->m_ClientID) : + pResult->GetString(0); pSelf->Score()->ShowTimes(pResult->m_ClientID, pRequestedName, pResult->GetInteger(1)); } else @@ -443,7 +454,8 @@ void CGameContext::ConTimes(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConDND(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - if(!CheckClientID(pResult->m_ClientID)) return; + if(!CheckClientID(pResult->m_ClientID)) + return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; if(!pPlayer) @@ -463,25 +475,25 @@ void CGameContext::ConDND(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConMap(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (g_Config.m_SvMapVote == 0) + if(g_Config.m_SvMapVote == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "map", - "/map is disabled"); + "/map is disabled"); return; } - if (pResult->NumArguments() <= 0) + if(pResult->NumArguments() <= 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "map", "Example: /map adr3 to call vote for Adrenaline 3. This means that the map name must start with 'a' and contain the characters 'd', 'r' and '3' in that order"); return; } CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; if(pSelf->RateLimitPlayerVote(pResult->m_ClientID) || pSelf->RateLimitPlayerMapVote(pResult->m_ClientID)) @@ -492,43 +504,45 @@ void CGameContext::ConMap(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConMapInfo(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) pSelf->Score()->MapInfo(pResult->m_ClientID, pResult->GetString(0)); else pSelf->Score()->MapInfo(pResult->m_ClientID, g_Config.m_SvMap); - } void CGameContext::ConTimeout(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - const char* pTimeout = pResult->NumArguments() > 0 ? pResult->GetString(0) : pPlayer->m_TimeoutCode; + const char *pTimeout = pResult->NumArguments() > 0 ? pResult->GetString(0) : pPlayer->m_TimeoutCode; if(!pSelf->Server()->IsSixup(pResult->m_ClientID)) { for(int i = 0; i < pSelf->Server()->MaxClients(); i++) { - if (i == pResult->m_ClientID) continue; - if (!pSelf->m_apPlayers[i]) continue; - if (str_comp(pSelf->m_apPlayers[i]->m_TimeoutCode, pTimeout)) continue; - if (pSelf->Server()->SetTimedOut(i, pResult->m_ClientID)) + if(i == pResult->m_ClientID) + continue; + if(!pSelf->m_apPlayers[i]) + continue; + if(str_comp(pSelf->m_apPlayers[i]->m_TimeoutCode, pTimeout)) + continue; + if(pSelf->Server()->SetTimedOut(i, pResult->m_ClientID)) { - if (pSelf->m_apPlayers[i]->GetCharacter()) + if(pSelf->m_apPlayers[i]->GetCharacter()) pSelf->SendTuningParams(i, pSelf->m_apPlayers[i]->GetCharacter()->m_TuneZone); /*if(pSelf->Server()->IsSixup(i)) pSelf->SendClientInfo(i, i);*/ @@ -548,7 +562,7 @@ void CGameContext::ConTimeout(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConPractice(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; if(!CheckClientID(pResult->m_ClientID)) return; @@ -562,31 +576,31 @@ void CGameContext::ConPractice(IConsole::IResult *pResult, void *pUserData) if(!g_Config.m_SvPractice) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "print", - "Practice mode is disabled"); + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "Practice mode is disabled"); return; } - CGameTeams &Teams = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams; + CGameTeams &Teams = ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams; int Team = Teams.m_Core.Team(pResult->m_ClientID); if(Team < TEAM_FLOCK || (Team == TEAM_FLOCK && g_Config.m_SvTeam != 3) || Team >= TEAM_SUPER) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "print", - "Join a team to enable practice mode, which means you can use /r, but can't earn a rank."); + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "Join a team to enable practice mode, which means you can use /r, but can't earn a rank."); return; } if(Teams.IsPractice(Team)) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "print", - "Team is already in practice mode"); + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "Team is already in practice mode"); return; } @@ -628,13 +642,12 @@ void CGameContext::ConPractice(IConsole::IResult *pResult, void *pUserData) if(Teams.m_Core.Team(i) == Team) pSelf->SendChatTarget(i, "Practice mode enabled for your team, happy practicing!"); } - } void CGameContext::ConSave(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; if(!g_Config.m_SvSaveGames) @@ -643,7 +656,7 @@ void CGameContext::ConSave(IConsole::IResult *pResult, void *pUserData) return; } - const char* pCode = ""; + const char *pCode = ""; if(pResult->NumArguments() > 0) pCode = pResult->GetString(0); @@ -652,8 +665,8 @@ void CGameContext::ConSave(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConLoad(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; if(!g_Config.m_SvSaveGames) @@ -670,72 +683,72 @@ void CGameContext::ConLoad(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConTeamRank(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) { - if (!g_Config.m_SvHideScore) + if(!g_Config.m_SvHideScore) pSelf->Score()->ShowTeamRank(pResult->m_ClientID, pResult->GetString(0)); else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "teamrank", - "Showing the team rank of other players is not allowed on this server."); + IConsole::OUTPUT_LEVEL_STANDARD, + "teamrank", + "Showing the team rank of other players is not allowed on this server."); } else pSelf->Score()->ShowTeamRank(pResult->m_ClientID, - pSelf->Server()->ClientName(pResult->m_ClientID)); + pSelf->Server()->ClientName(pResult->m_ClientID)); } void CGameContext::ConRank(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) { - if (!g_Config.m_SvHideScore) + if(!g_Config.m_SvHideScore) pSelf->Score()->ShowRank(pResult->m_ClientID, pResult->GetString(0)); else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "rank", - "Showing the rank of other players is not allowed on this server."); + IConsole::OUTPUT_LEVEL_STANDARD, + "rank", + "Showing the rank of other players is not allowed on this server."); } else pSelf->Score()->ShowRank(pResult->m_ClientID, - pSelf->Server()->ClientName(pResult->m_ClientID)); + pSelf->Server()->ClientName(pResult->m_ClientID)); } void CGameContext::ConLockTeam(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; if(g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "lock", - "Teams are disabled"); + "Teams are disabled"); return; } - int Team = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); + int Team = ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); - bool Lock = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.TeamLocked(Team); + bool Lock = ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.TeamLocked(Team); - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) Lock = !pResult->GetInteger(0); if(Team <= TEAM_FLOCK || Team >= TEAM_SUPER) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "print", - "This team can't be locked"); + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "This team can't be locked"); return; } @@ -749,30 +762,30 @@ void CGameContext::ConLockTeam(IConsole::IResult *pResult, void *pUserData) } else { - ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.SetTeamLock(Team, true); + ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.SetTeamLock(Team, true); str_format(aBuf, sizeof(aBuf), "'%s' locked your team. After the race started killing will kill everyone in your team.", pSelf->Server()->ClientName(pResult->m_ClientID)); - for (int i = 0; i < MAX_CLIENTS; i++) - if (((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) + for(int i = 0; i < MAX_CLIENTS; i++) + if(((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) pSelf->SendChatTarget(i, aBuf); } } void CGameContext::ConUnlockTeam(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; if(g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "unlock", - "Teams are disabled"); + "Teams are disabled"); return; } - int Team = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); + int Team = ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); if(Team <= TEAM_FLOCK || Team >= TEAM_SUPER) return; @@ -785,13 +798,13 @@ void CGameContext::ConUnlockTeam(IConsole::IResult *pResult, void *pUserData) void CGameContext::UnlockTeam(int ClientID, int Team) { - ((CGameControllerDDRace*) m_pController)->m_Teams.SetTeamLock(Team, false); + ((CGameControllerDDRace *)m_pController)->m_Teams.SetTeamLock(Team, false); char aBuf[512]; str_format(aBuf, sizeof(aBuf), "'%s' unlocked your team.", Server()->ClientName(ClientID)); - for (int i = 0; i < MAX_CLIENTS; i++) - if (((CGameControllerDDRace*) m_pController)->m_Teams.m_Core.Team(i) == Team) + for(int i = 0; i < MAX_CLIENTS; i++) + if(((CGameControllerDDRace *)m_pController)->m_Teams.m_Core.Team(i) == Team) SendChatTarget(i, aBuf); } @@ -804,7 +817,7 @@ void CGameContext::ConInviteTeam(IConsole::IResult *pResult, void *pUserData) if(g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "Teams are disabled"); + "Teams are disabled"); return; } @@ -852,9 +865,10 @@ void CGameContext::ConInviteTeam(IConsole::IResult *pResult, void *pUserData) str_format(aBuf, sizeof aBuf, "'%s' invited you to team %d.", pSelf->Server()->ClientName(pResult->m_ClientID), Team); pSelf->SendChatTarget(Target, aBuf); - str_format(aBuf, sizeof aBuf, "'%s' invited '%s' to your team.", pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Target));; - for (int i = 0; i < MAX_CLIENTS; i++) - if (((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) + str_format(aBuf, sizeof aBuf, "'%s' invited '%s' to your team.", pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Target)); + ; + for(int i = 0; i < MAX_CLIENTS; i++) + if(((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) pSelf->SendChatTarget(i, aBuf); } else @@ -863,44 +877,44 @@ void CGameContext::ConInviteTeam(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConJoinTeam(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; CGameControllerDDRace *pController = (CGameControllerDDRace *)pSelf->m_pController; - if (!CheckClientID(pResult->m_ClientID)) + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pSelf->m_VoteCloseTime && pSelf->m_VoteCreator == pResult->m_ClientID && (pSelf->IsKickVote() || pSelf->IsSpecVote())) + if(pSelf->m_VoteCloseTime && pSelf->m_VoteCreator == pResult->m_ClientID && (pSelf->IsKickVote() || pSelf->IsSpecVote())) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "join", - "You are running a vote please try again after the vote is done!"); + IConsole::OUTPUT_LEVEL_STANDARD, + "join", + "You are running a vote please try again after the vote is done!"); return; } - else if (g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) + else if(g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "Teams are disabled"); + "Teams are disabled"); return; } - else if (g_Config.m_SvTeam == 2 && pResult->GetInteger(0) == 0 && pPlayer->GetCharacter() && pPlayer->GetCharacter()->m_LastStartWarning < pSelf->Server()->Tick() - 3 * pSelf->Server()->TickSpeed()) + else if(g_Config.m_SvTeam == 2 && pResult->GetInteger(0) == 0 && pPlayer->GetCharacter() && pPlayer->GetCharacter()->m_LastStartWarning < pSelf->Server()->Tick() - 3 * pSelf->Server()->TickSpeed()) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "join", - "You must join a team and play with somebody or else you can\'t play"); + IConsole::OUTPUT_LEVEL_STANDARD, + "join", + "You must join a team and play with somebody or else you can\'t play"); pPlayer->GetCharacter()->m_LastStartWarning = pSelf->Server()->Tick(); } - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) { - if (pPlayer->GetCharacter() == 0) + if(pPlayer->GetCharacter() == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "You can't change teams while you are dead/a spectator."); + "You can't change teams while you are dead/a spectator."); } else { @@ -915,12 +929,12 @@ void CGameContext::ConJoinTeam(IConsole::IResult *pResult, void *pUserData) else if(pPlayer->m_Last_Team + pSelf->Server()->TickSpeed() * g_Config.m_SvTeamChangeDelay > pSelf->Server()->Tick()) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "You can\'t change teams that fast!"); + "You can\'t change teams that fast!"); } else if(Team > 0 && Team < MAX_CLIENTS && pController->m_Teams.TeamLocked(Team) && !pController->m_Teams.IsInvited(Team, pResult->m_ClientID)) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - g_Config.m_SvInvite ? + g_Config.m_SvInvite ? "This team is locked using /lock. Only members of the team can unlock it using /lock." : "This team is locked using /lock. Only members of the team can invite you or unlock it using /lock."); } @@ -934,8 +948,8 @@ void CGameContext::ConJoinTeam(IConsole::IResult *pResult, void *pUserData) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s joined team %d", - pSelf->Server()->ClientName(pPlayer->GetCID()), - Team); + pSelf->Server()->ClientName(pPlayer->GetCID()), + Team); pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); pPlayer->m_Last_Team = pSelf->Server()->Tick(); @@ -945,52 +959,51 @@ void CGameContext::ConJoinTeam(IConsole::IResult *pResult, void *pUserData) else { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "You cannot join this team at this time"); + "You cannot join this team at this time"); } } } else { char aBuf[512]; - if (!pPlayer->IsPlaying()) + if(!pPlayer->IsPlaying()) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "join", - "You can't check your team while you are dead/a spectator."); + IConsole::OUTPUT_LEVEL_STANDARD, + "join", + "You can't check your team while you are dead/a spectator."); } else { str_format( - aBuf, - sizeof(aBuf), - "You are in team %d", - ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team( - pResult->m_ClientID)); + aBuf, + sizeof(aBuf), + "You are in team %d", + ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID)); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - aBuf); + aBuf); } } } void CGameContext::ConMe(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; char aBuf[256 + 24]; str_format(aBuf, 256 + 24, "'%s' %s", - pSelf->Server()->ClientName(pResult->m_ClientID), - pResult->GetString(0)); - if (g_Config.m_SvSlashMe) + pSelf->Server()->ClientName(pResult->m_ClientID), + pResult->GetString(0)); + if(g_Config.m_SvSlashMe) pSelf->SendChat(-2, CGameContext::CHAT_ALL, aBuf, pResult->m_ClientID); else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "me", - "/me is disabled on this server"); + IConsole::OUTPUT_LEVEL_STANDARD, + "me", + "/me is disabled on this server"); } void CGameContext::ConConverse(IConsole::IResult *pResult, void *pUserData) @@ -1004,22 +1017,23 @@ void CGameContext::ConWhisper(IConsole::IResult *pResult, void *pUserData) } void CGameContext::ConSetEyeEmote(IConsole::IResult *pResult, - void *pUserData) + void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if(pResult->NumArguments() == 0) { + if(pResult->NumArguments() == 0) + { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "emote", - (pPlayer->m_EyeEmote) ? - "You can now use the preset eye emotes." : - "You don't have any eye emotes, remember to bind some. (until you die)"); + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + (pPlayer->m_EyeEmote) ? + "You can now use the preset eye emotes." : + "You don't have any eye emotes, remember to bind some. (until you die)"); return; } else if(str_comp_nocase(pResult->GetString(0), "on") == 0) @@ -1029,84 +1043,83 @@ void CGameContext::ConSetEyeEmote(IConsole::IResult *pResult, else if(str_comp_nocase(pResult->GetString(0), "toggle") == 0) pPlayer->m_EyeEmote = !pPlayer->m_EyeEmote; pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "emote", - (pPlayer->m_EyeEmote) ? - "You can now use the preset eye emotes." : - "You don't have any eye emotes, remember to bind some. (until you die)"); + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + (pPlayer->m_EyeEmote) ? + "You can now use the preset eye emotes." : + "You don't have any eye emotes, remember to bind some. (until you die)"); } void CGameContext::ConEyeEmote(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (g_Config.m_SvEmotionalTees == -1) + CGameContext *pSelf = (CGameContext *)pUserData; + if(g_Config.m_SvEmotionalTees == -1) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "emote", - "Emotes are disabled."); + "Emotes are disabled."); return; } - if (!CheckClientID(pResult->m_ClientID)) + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pResult->NumArguments() == 0) + if(pResult->NumArguments() == 0) { pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "emote", - "Emote commands are: /emote surprise /emote blink /emote close /emote angry /emote happy /emote pain"); + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + "Emote commands are: /emote surprise /emote blink /emote close /emote angry /emote happy /emote pain"); pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "emote", - "Example: /emote surprise 10 for 10 seconds or /emote surprise (default 1 second)"); + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + "Example: /emote surprise 10 for 10 seconds or /emote surprise (default 1 second)"); } else { - if(pPlayer->m_LastEyeEmote + g_Config.m_SvEyeEmoteChangeDelay * pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) - return; + if(pPlayer->m_LastEyeEmote + g_Config.m_SvEyeEmoteChangeDelay * pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; - if (!str_comp(pResult->GetString(0), "angry")) - pPlayer->m_DefEmote = EMOTE_ANGRY; - else if (!str_comp(pResult->GetString(0), "blink")) - pPlayer->m_DefEmote = EMOTE_BLINK; - else if (!str_comp(pResult->GetString(0), "close")) - pPlayer->m_DefEmote = EMOTE_BLINK; - else if (!str_comp(pResult->GetString(0), "happy")) - pPlayer->m_DefEmote = EMOTE_HAPPY; - else if (!str_comp(pResult->GetString(0), "pain")) - pPlayer->m_DefEmote = EMOTE_PAIN; - else if (!str_comp(pResult->GetString(0), "surprise")) - pPlayer->m_DefEmote = EMOTE_SURPRISE; - else if (!str_comp(pResult->GetString(0), "normal")) - pPlayer->m_DefEmote = EMOTE_NORMAL; - else - pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, - "emote", "Unknown emote... Say /emote"); + if(!str_comp(pResult->GetString(0), "angry")) + pPlayer->m_DefEmote = EMOTE_ANGRY; + else if(!str_comp(pResult->GetString(0), "blink")) + pPlayer->m_DefEmote = EMOTE_BLINK; + else if(!str_comp(pResult->GetString(0), "close")) + pPlayer->m_DefEmote = EMOTE_BLINK; + else if(!str_comp(pResult->GetString(0), "happy")) + pPlayer->m_DefEmote = EMOTE_HAPPY; + else if(!str_comp(pResult->GetString(0), "pain")) + pPlayer->m_DefEmote = EMOTE_PAIN; + else if(!str_comp(pResult->GetString(0), "surprise")) + pPlayer->m_DefEmote = EMOTE_SURPRISE; + else if(!str_comp(pResult->GetString(0), "normal")) + pPlayer->m_DefEmote = EMOTE_NORMAL; + else + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, + "emote", "Unknown emote... Say /emote"); - int Duration = 1; - if (pResult->NumArguments() > 1) - Duration = pResult->GetInteger(1); + int Duration = 1; + if(pResult->NumArguments() > 1) + Duration = pResult->GetInteger(1); - pPlayer->m_DefEmoteReset = pSelf->Server()->Tick() - + Duration * pSelf->Server()->TickSpeed(); - pPlayer->m_LastEyeEmote = pSelf->Server()->Tick(); + pPlayer->m_DefEmoteReset = pSelf->Server()->Tick() + Duration * pSelf->Server()->TickSpeed(); + pPlayer->m_LastEyeEmote = pSelf->Server()->Tick(); } } void CGameContext::ConNinjaJetpack(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pResult->NumArguments()) + if(pResult->NumArguments()) pPlayer->m_NinjaJetpack = pResult->GetInteger(0); else pPlayer->m_NinjaJetpack = !pPlayer->m_NinjaJetpack; @@ -1114,40 +1127,40 @@ void CGameContext::ConNinjaJetpack(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConShowOthers(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (g_Config.m_SvShowOthers) + if(g_Config.m_SvShowOthers) { - if (pResult->NumArguments()) + if(pResult->NumArguments()) pPlayer->m_ShowOthers = pResult->GetInteger(0); else pPlayer->m_ShowOthers = !pPlayer->m_ShowOthers; } else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "showotherschat", - "Showing players from other teams is disabled"); + IConsole::OUTPUT_LEVEL_STANDARD, + "showotherschat", + "Showing players from other teams is disabled"); } void CGameContext::ConShowAll(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pResult->NumArguments()) + if(pResult->NumArguments()) { - if (pPlayer->m_ShowAll == (bool)pResult->GetInteger(0)) + if(pPlayer->m_ShowAll == (bool)pResult->GetInteger(0)) return; pPlayer->m_ShowAll = pResult->GetInteger(0); @@ -1157,7 +1170,7 @@ void CGameContext::ConShowAll(IConsole::IResult *pResult, void *pUserData) pPlayer->m_ShowAll = !pPlayer->m_ShowAll; } - if (pPlayer->m_ShowAll) + if(pPlayer->m_ShowAll) pSelf->SendChatTarget(pResult->m_ClientID, "You will now see all tees on this server, no matter the distance"); else pSelf->SendChatTarget(pResult->m_ClientID, "You will no longer see all tees on this server"); @@ -1165,15 +1178,15 @@ void CGameContext::ConShowAll(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConSpecTeam(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - if (pResult->NumArguments()) + if(pResult->NumArguments()) pPlayer->m_SpecTeam = pResult->GetInteger(0); else pPlayer->m_SpecTeam = !pPlayer->m_SpecTeam; @@ -1181,24 +1194,24 @@ void CGameContext::ConSpecTeam(IConsole::IResult *pResult, void *pUserData) bool CheckClientID(int ClientID) { - if (ClientID < 0 || ClientID >= MAX_CLIENTS) + if(ClientID < 0 || ClientID >= MAX_CLIENTS) return false; return true; } void CGameContext::ConSayTime(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; int ClientID; char aBufname[MAX_NAME_LENGTH]; - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) { for(ClientID = 0; ClientID < MAX_CLIENTS; ClientID++) - if (str_comp(pResult->GetString(0), pSelf->Server()->ClientName(ClientID)) == 0) + if(str_comp(pResult->GetString(0), pSelf->Server()->ClientName(ClientID)) == 0) break; if(ClientID == MAX_CLIENTS) @@ -1213,69 +1226,66 @@ void CGameContext::ConSayTime(IConsole::IResult *pResult, void *pUserData) } CPlayer *pPlayer = pSelf->m_apPlayers[ClientID]; - if (!pPlayer) + if(!pPlayer) return; - CCharacter* pChr = pPlayer->GetCharacter(); - if (!pChr) + CCharacter *pChr = pPlayer->GetCharacter(); + if(!pChr) return; if(pChr->m_DDRaceState != DDRACE_STARTED) return; char aBuftime[64]; - int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) - / ((float)pSelf->Server()->TickSpeed())); + int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) / ((float)pSelf->Server()->TickSpeed())); str_format(aBuftime, sizeof(aBuftime), "%s time is %s%d:%s%d", - aBufname, - ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, - ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + aBufname, + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "time", aBuftime); } void CGameContext::ConSayTimeAll(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - CCharacter* pChr = pPlayer->GetCharacter(); - if (!pChr) + CCharacter *pChr = pPlayer->GetCharacter(); + if(!pChr) return; if(pChr->m_DDRaceState != DDRACE_STARTED) return; char aBuftime[64]; - int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) - / ((float)pSelf->Server()->TickSpeed())); + int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) / ((float)pSelf->Server()->TickSpeed())); str_format(aBuftime, sizeof(aBuftime), - "%s\'s current race time is %s%d:%s%d", - pSelf->Server()->ClientName(pResult->m_ClientID), - ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, - ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + "%s\'s current race time is %s%d:%s%d", + pSelf->Server()->ClientName(pResult->m_ClientID), + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuftime, pResult->m_ClientID); } void CGameContext::ConTime(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - CCharacter* pChr = pPlayer->GetCharacter(); - if (!pChr) + CCharacter *pChr = pPlayer->GetCharacter(); + if(!pChr) return; char aBuftime[64]; - int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) - / ((float)pSelf->Server()->TickSpeed())); + int IntTime = (int)((float)(pSelf->Server()->Tick() - pChr->m_StartTime) / ((float)pSelf->Server()->TickSpeed())); str_format(aBuftime, sizeof(aBuftime), "Your time is %s%d:%s%d", - ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, - ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); pSelf->SendBroadcast(aBuftime, pResult->m_ClientID); } @@ -1283,13 +1293,13 @@ static const char s_aaMsg[4][128] = {"game/round timer.", "broadcast.", "both ga void CGameContext::ConSetTimerType(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; - if (!CheckClientID(pResult->m_ClientID)) + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; char aBuf[128]; @@ -1335,19 +1345,20 @@ void CGameContext::ConSetTimerType(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConRescue(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - CCharacter* pChr = pPlayer->GetCharacter(); - if (!pChr) + CCharacter *pChr = pPlayer->GetCharacter(); + if(!pChr) return; - CGameTeams &Teams = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams; + CGameTeams &Teams = ((CGameControllerDDRace *)pSelf->m_pController)->m_Teams; int Team = Teams.m_Core.Team(pResult->m_ClientID); - if (!g_Config.m_SvRescue && !Teams.IsPractice(Team)) { + if(!g_Config.m_SvRescue && !Teams.IsPractice(Team)) + { pSelf->SendChatTarget(pPlayer->GetCID(), "Rescue is not enabled on this server and you're not in a team with /practice turned on. Note that you can't earn a rank with practice enabled."); return; } @@ -1357,66 +1368,65 @@ void CGameContext::ConRescue(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConProtectedKill(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer) + if(!pPlayer) return; - CCharacter* pChr = pPlayer->GetCharacter(); - if (!pChr) + CCharacter *pChr = pPlayer->GetCharacter(); + if(!pChr) return; int CurrTime = (pSelf->Server()->Tick() - pChr->m_StartTime) / pSelf->Server()->TickSpeed(); if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == DDRACE_STARTED) { - pPlayer->KillCharacter(WEAPON_SELF); + pPlayer->KillCharacter(WEAPON_SELF); - //char aBuf[64]; - //str_format(aBuf, sizeof(aBuf), "You killed yourself in: %s%d:%s%d", - // ((CurrTime / 60) > 9) ? "" : "0", CurrTime / 60, - // ((CurrTime % 60) > 9) ? "" : "0", CurrTime % 60); - //pSelf->SendChatTarget(pResult->m_ClientID, aBuf); + //char aBuf[64]; + //str_format(aBuf, sizeof(aBuf), "You killed yourself in: %s%d:%s%d", + // ((CurrTime / 60) > 9) ? "" : "0", CurrTime / 60, + // ((CurrTime % 60) > 9) ? "" : "0", CurrTime % 60); + //pSelf->SendChatTarget(pResult->m_ClientID, aBuf); } } void CGameContext::ConPoints(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) { - if (!g_Config.m_SvHideScore) + if(!g_Config.m_SvHideScore) pSelf->Score()->ShowPoints(pResult->m_ClientID, pResult->GetString(0)); else pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "points", - "Showing the global points of other players is not allowed on this server."); + IConsole::OUTPUT_LEVEL_STANDARD, + "points", + "Showing the global points of other players is not allowed on this server."); } else pSelf->Score()->ShowPoints(pResult->m_ClientID, - pSelf->Server()->ClientName(pResult->m_ClientID)); + pSelf->Server()->ClientName(pResult->m_ClientID)); } void CGameContext::ConTopPoints(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - if (g_Config.m_SvHideScore) + if(g_Config.m_SvHideScore) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "toppoints", - "Showing the global top points is not allowed on this server."); + "Showing the global top points is not allowed on this server."); return; } - if (pResult->NumArguments() > 0) + if(pResult->NumArguments() > 0) pSelf->Score()->ShowTopPoints(pResult->m_ClientID, pResult->GetInteger(0)); else pSelf->Score()->ShowTopPoints(pResult->m_ClientID); - } diff --git a/src/game/server/ddracechat.h b/src/game/server/ddracechat.h index 77068621e..d9d84c7d8 100644 --- a/src/game/server/ddracechat.h +++ b/src/game/server/ddracechat.h @@ -6,13 +6,13 @@ #define CHAT_COMMAND(name, params, flags, callback, userdata, help) #endif -CHAT_COMMAND("credits", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConCredits, this, "Shows the credits of the DDNet mod") -CHAT_COMMAND("rules", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConRules, this, "Shows the server rules") -CHAT_COMMAND("emote", "?s[emote name] i[duration in seconds]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConEyeEmote, this, "Sets your tee's eye emote") -CHAT_COMMAND("eyeemote", "?s['on'|'off'|'toggle']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSetEyeEmote, this, "Toggles use of standard eye-emotes on/off, eyeemote s, where s = on for on, off for off, toggle for toggle and nothing to show current status") -CHAT_COMMAND("settings", "?s[configname]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSettings, this, "Shows gameplay information for this server") -CHAT_COMMAND("help", "?r[command]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConHelp, this, "Shows help to command r, general help if left blank") -CHAT_COMMAND("info", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConInfo, this, "Shows info about this server") +CHAT_COMMAND("credits", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConCredits, this, "Shows the credits of the DDNet mod") +CHAT_COMMAND("rules", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConRules, this, "Shows the server rules") +CHAT_COMMAND("emote", "?s[emote name] i[duration in seconds]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConEyeEmote, this, "Sets your tee's eye emote") +CHAT_COMMAND("eyeemote", "?s['on'|'off'|'toggle']", CFGFLAG_CHAT | CFGFLAG_SERVER, ConSetEyeEmote, this, "Toggles use of standard eye-emotes on/off, eyeemote s, where s = on for on, off for off, toggle for toggle and nothing to show current status") +CHAT_COMMAND("settings", "?s[configname]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConSettings, this, "Shows gameplay information for this server") +CHAT_COMMAND("help", "?r[command]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConHelp, this, "Shows help to command r, general help if left blank") +CHAT_COMMAND("info", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConInfo, this, "Shows info about this server") CHAT_COMMAND("list", "?s[filter]", CFGFLAG_CHAT, ConList, this, "List connected players with optional case-insensitive substring matching filter") CHAT_COMMAND("me", "r[message]", CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConMe, this, "Like the famous irc command '/me says hi' will display ' says hi'") CHAT_COMMAND("w", "s[player name] r[message]", CFGFLAG_CHAT | CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, ConWhisper, this, "Whisper something to someone (private message)") @@ -40,10 +40,10 @@ CHAT_COMMAND("times", "?s[player name] ?i[number of times to skip]", CFGFLAG_CHA CHAT_COMMAND("points", "?r[player name]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConPoints, this, "Shows the global points of a player beginning with name r (your rank by default)") CHAT_COMMAND("top5points", "?i[number]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConTopPoints, this, "Shows five points of the global point ladder beginning with rank i (1 by default, -1 for worst)") -CHAT_COMMAND("team", "?i[id]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConJoinTeam, this, "Lets you join team i (shows your team if left blank)") -CHAT_COMMAND("lock", "?i['0'|'1']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConLockTeam, this, "Toggle team lock so no one else can join and so the team restarts when a player dies. /lock 0 to unlock, /lock 1 to lock.") -CHAT_COMMAND("unlock", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConUnlockTeam, this, "Unlock a team") -CHAT_COMMAND("invite", "r[player name]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConInviteTeam, this, "Invite a person to a locked team") +CHAT_COMMAND("team", "?i[id]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConJoinTeam, this, "Lets you join team i (shows your team if left blank)") +CHAT_COMMAND("lock", "?i['0'|'1']", CFGFLAG_CHAT | CFGFLAG_SERVER, ConLockTeam, this, "Toggle team lock so no one else can join and so the team restarts when a player dies. /lock 0 to unlock, /lock 1 to lock.") +CHAT_COMMAND("unlock", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConUnlockTeam, this, "Unlock a team") +CHAT_COMMAND("invite", "r[player name]", CFGFLAG_CHAT | CFGFLAG_SERVER, ConInviteTeam, this, "Invite a person to a locked team") CHAT_COMMAND("showothers", "?i['0'|'1'|'2']", CFGFLAG_CHAT | CFGFLAG_SERVER, ConShowOthers, this, "Whether to show players from other teams or not (off by default), optional i = 0 for off, i = 1 for on, i = 2 for own team only") CHAT_COMMAND("showall", "?i['0'|'1']", CFGFLAG_CHAT | CFGFLAG_SERVER, ConShowAll, this, "Whether to show players at any distance (off by default), optional i = 0 for off else for on") @@ -56,6 +56,6 @@ CHAT_COMMAND("timer", "?s['gametimer'|'broadcast'|'both'|'none'|'cycle']", CFGFL CHAT_COMMAND("r", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConRescue, this, "Teleport yourself out of freeze (use sv_rescue 1 to enable this feature)") CHAT_COMMAND("rescue", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConRescue, this, "Teleport yourself out of freeze (use sv_rescue 1 to enable this feature)") -CHAT_COMMAND("kill", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConProtectedKill, this, "Kill yourself when kill-protected during a long game (use f1, kill for regular kill)") +CHAT_COMMAND("kill", "", CFGFLAG_CHAT | CFGFLAG_SERVER, ConProtectedKill, this, "Kill yourself when kill-protected during a long game (use f1, kill for regular kill)") #undef CHAT_COMMAND diff --git a/src/game/server/ddracecommands.cpp b/src/game/server/ddracecommands.cpp index a472dd4af..0a34d706e 100644 --- a/src/game/server/ddracecommands.cpp +++ b/src/game/server/ddracecommands.cpp @@ -1,68 +1,68 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ #include "gamecontext.h" #include -#include #include #include +#include #include bool CheckClientID(int ClientID); void CGameContext::ConGoLeft(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, -1, 0); } void CGameContext::ConGoRight(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, 1, 0); } void CGameContext::ConGoDown(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, 0, 1); } void CGameContext::ConGoUp(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, 0, -1); } void CGameContext::ConMove(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, pResult->GetInteger(0), - pResult->GetInteger(1)); + pResult->GetInteger(1)); } void CGameContext::ConMoveRaw(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; pSelf->MoveCharacter(pResult->m_ClientID, pResult->GetInteger(0), - pResult->GetInteger(1), true); + pResult->GetInteger(1), true); } void CGameContext::MoveCharacter(int ClientID, int X, int Y, bool Raw) { - CCharacter* pChr = GetPlayerChar(ClientID); + CCharacter *pChr = GetPlayerChar(ClientID); - if (!pChr) + if(!pChr) return; pChr->Core()->m_Pos.x += ((Raw) ? 1 : 32) * X; @@ -72,35 +72,35 @@ void CGameContext::MoveCharacter(int ClientID, int X, int Y, bool Raw) void CGameContext::ConKillPlayer(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; int Victim = pResult->GetVictim(); - if (pSelf->m_apPlayers[Victim]) + if(pSelf->m_apPlayers[Victim]) { pSelf->m_apPlayers[Victim]->KillCharacter(WEAPON_GAME); char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s was killed by %s", - pSelf->Server()->ClientName(Victim), - pSelf->Server()->ClientName(pResult->m_ClientID)); + pSelf->Server()->ClientName(Victim), + pSelf->Server()->ClientName(pResult->m_ClientID)); pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); } } void CGameContext::ConNinja(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_NINJA, false); } void CGameContext::ConSuper(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr && !pChr->m_Super) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr && !pChr->m_Super) { pChr->m_Super = true; pChr->Core()->m_Super = true; @@ -113,131 +113,131 @@ void CGameContext::ConSuper(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConUnSuper(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr && pChr->m_Super) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr && pChr->m_Super) { pChr->m_Super = false; pChr->Core()->m_Super = false; pChr->Teams()->SetForceCharacterTeam(pResult->m_ClientID, - pChr->m_TeamBeforeSuper); + pChr->m_TeamBeforeSuper); } } void CGameContext::ConUnSolo(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr) pChr->SetSolo(false); } void CGameContext::ConUnDeep(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr) pChr->m_DeepFreeze = false; } void CGameContext::ConShotgun(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_SHOTGUN, false); } void CGameContext::ConGrenade(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_GRENADE, false); } void CGameContext::ConLaser(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_LASER, false); } void CGameContext::ConJetpack(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr) pChr->m_Jetpack = true; } void CGameContext::ConWeapons(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, -1, false); } void CGameContext::ConUnShotgun(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_SHOTGUN, true); } void CGameContext::ConUnGrenade(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_GRENADE, true); } void CGameContext::ConUnLaser(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, WEAPON_LASER, true); } void CGameContext::ConUnJetpack(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); - if (pChr) + CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if(pChr) pChr->m_Jetpack = false; } void CGameContext::ConUnWeapons(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, -1, true); } void CGameContext::ConAddWeapon(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, pResult->GetInteger(0), false); } void CGameContext::ConRemoveWeapon(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->ModifyWeapons(pResult, pUserData, pResult->GetInteger(0), true); } void CGameContext::ModifyWeapons(IConsole::IResult *pResult, void *pUserData, - int Weapon, bool Remove) + int Weapon, bool Remove) { CGameContext *pSelf = (CGameContext *)pUserData; - CCharacter* pChr = GetPlayerChar(pResult->m_ClientID); - if (!pChr) + CCharacter *pChr = GetPlayerChar(pResult->m_ClientID); + if(!pChr) return; - if (clamp(Weapon, -1, NUM_WEAPONS - 1) != Weapon) + if(clamp(Weapon, -1, NUM_WEAPONS - 1) != Weapon) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", - "invalid weapon id"); + "invalid weapon id"); return; } - if (Weapon == -1) + if(Weapon == -1) { pChr->GiveWeapon(WEAPON_SHOTGUN, Remove); pChr->GiveWeapon(WEAPON_GRENADE, Remove); @@ -253,17 +253,17 @@ void CGameContext::ModifyWeapons(IConsole::IResult *pResult, void *pUserData, void CGameContext::ConToTeleporter(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; unsigned int TeleTo = pResult->GetInteger(0); CGameControllerDDRace *pGameControllerDDRace = (CGameControllerDDRace *)pSelf->m_pController; - if(pGameControllerDDRace->m_TeleOuts[TeleTo-1].size()) + if(pGameControllerDDRace->m_TeleOuts[TeleTo - 1].size()) { CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); if(pChr) { - int TeleOut = pSelf->m_World.m_Core.RandomOr0(pGameControllerDDRace->m_TeleOuts[TeleTo-1].size()); - vec2 TelePos = pGameControllerDDRace->m_TeleOuts[TeleTo-1][TeleOut]; + int TeleOut = pSelf->m_World.m_Core.RandomOr0(pGameControllerDDRace->m_TeleOuts[TeleTo - 1].size()); + vec2 TelePos = pGameControllerDDRace->m_TeleOuts[TeleTo - 1][TeleOut]; pChr->Core()->m_Pos = TelePos; pChr->m_Pos = TelePos; pChr->m_PrevPos = TelePos; @@ -274,17 +274,17 @@ void CGameContext::ConToTeleporter(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConToCheckTeleporter(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; unsigned int TeleTo = pResult->GetInteger(0); CGameControllerDDRace *pGameControllerDDRace = (CGameControllerDDRace *)pSelf->m_pController; - if(pGameControllerDDRace->m_TeleCheckOuts[TeleTo-1].size()) + if(pGameControllerDDRace->m_TeleCheckOuts[TeleTo - 1].size()) { CCharacter *pChr = pSelf->GetPlayerChar(pResult->m_ClientID); if(pChr) { - int TeleOut = pSelf->m_World.m_Core.RandomOr0(pGameControllerDDRace->m_TeleCheckOuts[TeleTo-1].size()); - vec2 TelePos = pGameControllerDDRace->m_TeleCheckOuts[TeleTo-1][TeleOut]; + int TeleOut = pSelf->m_World.m_Core.RandomOr0(pGameControllerDDRace->m_TeleCheckOuts[TeleTo - 1].size()); + vec2 TelePos = pGameControllerDDRace->m_TeleCheckOuts[TeleTo - 1][TeleOut]; pChr->Core()->m_Pos = TelePos; pChr->m_Pos = TelePos; pChr->m_PrevPos = TelePos; @@ -296,7 +296,7 @@ void CGameContext::ConToCheckTeleporter(IConsole::IResult *pResult, void *pUserD void CGameContext::ConTeleport(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; int Tele = pResult->NumArguments() == 2 ? pResult->GetInteger(0) : pResult->m_ClientID; int TeleTo = pResult->NumArguments() ? pResult->GetInteger(pResult->NumArguments() - 1) : pResult->m_ClientID; int AuthLevel = pSelf->Server()->GetAuthedState(pResult->m_ClientID); @@ -319,17 +319,12 @@ void CGameContext::ConTeleport(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConKill(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; - if (!CheckClientID(pResult->m_ClientID)) + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; - if (!pPlayer - || (pPlayer->m_LastKill - && pPlayer->m_LastKill - + pSelf->Server()->TickSpeed() - * g_Config.m_SvKillDelay - > pSelf->Server()->Tick())) + if(!pPlayer || (pPlayer->m_LastKill && pPlayer->m_LastKill + pSelf->Server()->TickSpeed() * g_Config.m_SvKillDelay > pSelf->Server()->Tick())) return; pPlayer->m_LastKill = pSelf->Server()->Tick(); @@ -342,11 +337,11 @@ void CGameContext::ConForcePause(IConsole::IResult *pResult, void *pUserData) CGameContext *pSelf = (CGameContext *)pUserData; int Victim = pResult->GetVictim(); int Seconds = 0; - if (pResult->NumArguments() > 1) + if(pResult->NumArguments() > 1) Seconds = clamp(pResult->GetInteger(1), 0, 360); CPlayer *pPlayer = pSelf->m_apPlayers[Victim]; - if (!pPlayer) + if(!pPlayer) return; pPlayer->ForcePause(Seconds); @@ -359,8 +354,7 @@ bool CGameContext::TryVoteMute(const NETADDR *pAddr, int Secs) { if(net_addr_comp_noport(&m_aVoteMutes[i].m_Addr, pAddr) == 0) { - m_aVoteMutes[i].m_Expire = Server()->Tick() - + Secs * Server()->TickSpeed(); + m_aVoteMutes[i].m_Expire = Server()->Tick() + Secs * Server()->TickSpeed(); return true; } } @@ -369,8 +363,7 @@ bool CGameContext::TryVoteMute(const NETADDR *pAddr, int Secs) if(m_NumVoteMutes < MAX_VOTE_MUTES) { m_aVoteMutes[m_NumVoteMutes].m_Addr = *pAddr; - m_aVoteMutes[m_NumVoteMutes].m_Expire = Server()->Tick() - + Secs * Server()->TickSpeed(); + m_aVoteMutes[m_NumVoteMutes].m_Expire = Server()->Tick() + Secs * Server()->TickSpeed(); m_NumVoteMutes++; return true; } @@ -381,7 +374,7 @@ bool CGameContext::TryVoteMute(const NETADDR *pAddr, int Secs) bool CGameContext::VoteMute(const NETADDR *pAddr, int Secs, const char *pDisplayName, int AuthedID) { - if (!TryVoteMute(pAddr, Secs)) + if(!TryVoteMute(pAddr, Secs)) return false; if(!pDisplayName) @@ -406,7 +399,7 @@ bool CGameContext::VoteUnmute(const NETADDR *pAddr, const char *pDisplayName, in { char aBuf[128]; str_format(aBuf, sizeof aBuf, "'%s' unbanned '%s' from voting.", - Server()->ClientName(AuthedID), pDisplayName); + Server()->ClientName(AuthedID), pDisplayName); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "voteunmute", aBuf); } return true; @@ -422,8 +415,7 @@ bool CGameContext::TryMute(const NETADDR *pAddr, int Secs, const char *pReason) { if(net_addr_comp_noport(&m_aMutes[i].m_Addr, pAddr) == 0) { - m_aMutes[i].m_Expire = Server()->Tick() - + Secs * Server()->TickSpeed(); + m_aMutes[i].m_Expire = Server()->Tick() + Secs * Server()->TickSpeed(); str_copy(m_aMutes[i].m_aReason, pReason, sizeof(m_aMutes[i].m_aReason)); return true; } @@ -433,8 +425,7 @@ bool CGameContext::TryMute(const NETADDR *pAddr, int Secs, const char *pReason) if(m_NumMutes < MAX_MUTES) { m_aMutes[m_NumMutes].m_Addr = *pAddr; - m_aMutes[m_NumMutes].m_Expire = Server()->Tick() - + Secs * Server()->TickSpeed(); + m_aMutes[m_NumMutes].m_Expire = Server()->Tick() + Secs * Server()->TickSpeed(); str_copy(m_aMutes[m_NumMutes].m_aReason, pReason, sizeof(m_aMutes[m_NumMutes].m_aReason)); m_NumMutes++; return true; @@ -446,14 +437,14 @@ bool CGameContext::TryMute(const NETADDR *pAddr, int Secs, const char *pReason) void CGameContext::Mute(const NETADDR *pAddr, int Secs, const char *pDisplayName, const char *pReason) { - if (!TryMute(pAddr, Secs, pReason)) + if(!TryMute(pAddr, Secs, pReason)) return; if(!pDisplayName) return; char aBuf[128]; - if (pReason[0]) + if(pReason[0]) str_format(aBuf, sizeof aBuf, "'%s' has been muted for %d seconds (%s)", pDisplayName, Secs, pReason); else str_format(aBuf, sizeof aBuf, "'%s' has been muted for %d seconds", pDisplayName, Secs); @@ -481,7 +472,7 @@ void CGameContext::ConVoteMute(IConsole::IResult *pResult, void *pUserData) { char aBuf[128]; str_format(aBuf, sizeof aBuf, "'%s' banned '%s' for %d seconds from voting.", - pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Victim), Seconds); + pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Victim), Seconds); pSelf->SendChat(-1, 0, aBuf); } } @@ -505,53 +496,53 @@ void CGameContext::ConVoteUnmute(IConsole::IResult *pResult, void *pUserData) { char aBuf[128]; str_format(aBuf, sizeof aBuf, "'%s' unbanned '%s' from voting.", - pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Victim)); + pSelf->Server()->ClientName(pResult->m_ClientID), pSelf->Server()->ClientName(Victim)); pSelf->SendChat(-1, 0, aBuf); } } void CGameContext::ConVoteMutes(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; - if (pSelf->m_NumVoteMutes <= 0) + if(pSelf->m_NumVoteMutes <= 0) { // Just to make sure. pSelf->m_NumVoteMutes = 0; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "votemutes", - "There are no active vote mutes."); + "There are no active vote mutes."); return; } char aIpBuf[64]; char aBuf[128]; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "votemutes", - "Active vote mutes:"); - for (int i = 0; i < pSelf->m_NumVoteMutes; i++) + "Active vote mutes:"); + for(int i = 0; i < pSelf->m_NumVoteMutes; i++) { net_addr_str(&pSelf->m_aVoteMutes[i].m_Addr, aIpBuf, sizeof(aIpBuf), false); str_format(aBuf, sizeof aBuf, "%d: \"%s\", %d seconds left", i, - aIpBuf, (pSelf->m_aVoteMutes[i].m_Expire - pSelf->Server()->Tick()) / pSelf->Server()->TickSpeed()); + aIpBuf, (pSelf->m_aVoteMutes[i].m_Expire - pSelf->Server()->Tick()) / pSelf->Server()->TickSpeed()); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "votemutes", aBuf); } } void CGameContext::ConMute(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; pSelf->Console()->Print( - IConsole::OUTPUT_LEVEL_STANDARD, - "mutes", - "Use either 'muteid ' or 'muteip '"); + IConsole::OUTPUT_LEVEL_STANDARD, + "mutes", + "Use either 'muteid ' or 'muteip '"); } // mute through client id void CGameContext::ConMuteID(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; int Victim = pResult->GetVictim(); - if (Victim < 0 || Victim > MAX_CLIENTS || !pSelf->m_apPlayers[Victim]) + if(Victim < 0 || Victim > MAX_CLIENTS || !pSelf->m_apPlayers[Victim]) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "muteid", "Client id not found."); return; @@ -563,18 +554,18 @@ void CGameContext::ConMuteID(IConsole::IResult *pResult, void *pUserData) const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(2) : ""; pSelf->Mute(&Addr, clamp(pResult->GetInteger(1), 1, 86400), - pSelf->Server()->ClientName(Victim), pReason); + pSelf->Server()->ClientName(Victim), pReason); } // mute through ip, arguments reversed to workaround parsing void CGameContext::ConMuteIP(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; NETADDR Addr; - if (net_addr_from_str(&Addr, pResult->GetString(0))) + if(net_addr_from_str(&Addr, pResult->GetString(0))) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", - "Invalid network address to mute"); + "Invalid network address to mute"); } const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(2) : ""; pSelf->Mute(&Addr, clamp(pResult->GetInteger(1), 1, 86400), NULL, pReason); @@ -583,12 +574,12 @@ void CGameContext::ConMuteIP(IConsole::IResult *pResult, void *pUserData) // unmute by mute list index void CGameContext::ConUnmute(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; char aIpBuf[64]; char aBuf[64]; int Victim = pResult->GetVictim(); - if (Victim < 0 || Victim >= pSelf->m_NumMutes) + if(Victim < 0 || Victim >= pSelf->m_NumMutes) return; pSelf->m_NumMutes--; @@ -602,9 +593,9 @@ void CGameContext::ConUnmute(IConsole::IResult *pResult, void *pUserData) // list mutes void CGameContext::ConMutes(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; - if (pSelf->m_NumMutes <= 0) + if(pSelf->m_NumMutes <= 0) { // Just to make sure. pSelf->m_NumMutes = 0; @@ -616,12 +607,12 @@ void CGameContext::ConMutes(IConsole::IResult *pResult, void *pUserData) char aIpBuf[64]; char aBuf[128]; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", - "Active mutes:"); - for (int i = 0; i < pSelf->m_NumMutes; i++) + "Active mutes:"); + for(int i = 0; i < pSelf->m_NumMutes; i++) { net_addr_str(&pSelf->m_aMutes[i].m_Addr, aIpBuf, sizeof(aIpBuf), false); str_format(aBuf, sizeof aBuf, "%d: \"%s\", %d seconds left (%s)", i, aIpBuf, - (pSelf->m_aMutes[i].m_Expire - pSelf->Server()->Tick()) / pSelf->Server()->TickSpeed(), pSelf->m_aMutes[i].m_aReason); + (pSelf->m_aMutes[i].m_Expire - pSelf->Server()->Tick()) / pSelf->Server()->TickSpeed(), pSelf->m_aMutes[i].m_aReason); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", aBuf); } } @@ -629,7 +620,7 @@ void CGameContext::ConMutes(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConModerate(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - if (!CheckClientID(pResult->m_ClientID)) + if(!CheckClientID(pResult->m_ClientID)) return; bool HadModerator = pSelf->PlayerModerating(); @@ -661,17 +652,17 @@ void CGameContext::ConSetDDRTeam(IConsole::IResult *pResult, void *pUserData) if(g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "join", - "Teams are disabled"); + "Teams are disabled"); return; } int Target = pResult->GetVictim(); int Team = pResult->GetInteger(1); - if (Team < TEAM_FLOCK || Team >= TEAM_SUPER) + if(Team < TEAM_FLOCK || Team >= TEAM_SUPER) return; - CCharacter* pChr = pSelf->GetPlayerChar(Target); + CCharacter *pChr = pSelf->GetPlayerChar(Target); if((pController->m_Teams.m_Core.Team(Target) && pController->m_Teams.GetDDRaceState(pSelf->m_apPlayers[Target]) == DDRACE_STARTED) || (pChr && pController->m_Teams.IsPractice(pChr->Team()))) pSelf->m_apPlayers[Target]->KillCharacter(WEAPON_SELF); @@ -689,17 +680,17 @@ void CGameContext::ConUninvite(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConFreezeHammer(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; int Victim = pResult->GetVictim(); - CCharacter* pChr = pSelf->GetPlayerChar(Victim); + CCharacter *pChr = pSelf->GetPlayerChar(Victim); - if (!pChr) + if(!pChr) return; char aBuf[128]; str_format(aBuf, sizeof aBuf, "'%s' got freeze hammer!", - pSelf->Server()->ClientName(Victim)); + pSelf->Server()->ClientName(Victim)); pSelf->SendChat(-1, CHAT_ALL, aBuf); pChr->m_FreezeHammer = true; @@ -707,17 +698,17 @@ void CGameContext::ConFreezeHammer(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConUnFreezeHammer(IConsole::IResult *pResult, void *pUserData) { - CGameContext *pSelf = (CGameContext *) pUserData; + CGameContext *pSelf = (CGameContext *)pUserData; int Victim = pResult->GetVictim(); - CCharacter* pChr = pSelf->GetPlayerChar(Victim); + CCharacter *pChr = pSelf->GetPlayerChar(Victim); - if (!pChr) + if(!pChr) return; char aBuf[128]; str_format(aBuf, sizeof aBuf, "'%s' lost freeze hammer!", - pSelf->Server()->ClientName(Victim)); + pSelf->Server()->ClientName(Victim)); pSelf->SendChat(-1, CHAT_ALL, aBuf); pChr->m_FreezeHammer = false; diff --git a/src/game/server/entities/character.cpp b/src/game/server/entities/character.cpp index efd7f5e75..b96f52ba0 100644 --- a/src/game/server/entities/character.cpp +++ b/src/game/server/entities/character.cpp @@ -1,24 +1,24 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include #include -#include #include +#include +#include #include "character.h" #include "laser.h" #include "projectile.h" +#include "light.h" #include #include -#include "light.h" MACRO_ALLOC_POOL_ID_IMPL(CCharacter, MAX_CLIENTS) // Character, "physical" player's part -CCharacter::CCharacter(CGameWorld *pWorld) -: CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER) +CCharacter::CCharacter(CGameWorld *pWorld) : + CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER) { m_ProximityRadius = ms_PhysSize; m_Health = 0; @@ -55,7 +55,7 @@ bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) Antibot()->OnSpawn(m_pPlayer->GetCID()); m_Core.Reset(); - m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision(), &((CGameControllerDDRace*)GameServer()->m_pController)->m_Teams.m_Core, &((CGameControllerDDRace*)GameServer()->m_pController)->m_TeleOuts); + m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision(), &((CGameControllerDDRace *)GameServer()->m_pController)->m_Teams.m_Core, &((CGameControllerDDRace *)GameServer()->m_pController)->m_TeleOuts); m_Core.m_ActiveWeapon = WEAPON_GUN; m_Core.m_Pos = m_Pos; GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; @@ -121,13 +121,13 @@ void CCharacter::SetSolo(bool Solo) bool CCharacter::IsGrounded() { - if(GameServer()->Collision()->CheckPoint(m_Pos.x+m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + if(GameServer()->Collision()->CheckPoint(m_Pos.x + m_ProximityRadius / 2, m_Pos.y + m_ProximityRadius / 2 + 5)) return true; - if(GameServer()->Collision()->CheckPoint(m_Pos.x-m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + if(GameServer()->Collision()->CheckPoint(m_Pos.x - m_ProximityRadius / 2, m_Pos.y + m_ProximityRadius / 2 + 5)) return true; int MoveRestrictionsBelow = GameServer()->Collision()->GetMoveRestrictions(m_Pos + vec2(0, m_ProximityRadius / 2 + 4), 0.0f); - if(MoveRestrictionsBelow&CANTMOVE_DOWN) + if(MoveRestrictionsBelow & CANTMOVE_DOWN) { return true; } @@ -142,7 +142,7 @@ void CCharacter::HandleJetpack() bool FullAuto = false; if(m_Core.m_ActiveWeapon == WEAPON_GRENADE || m_Core.m_ActiveWeapon == WEAPON_SHOTGUN || m_Core.m_ActiveWeapon == WEAPON_LASER) FullAuto = true; - if (m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) + if(m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) FullAuto = true; // check if we gonna fire @@ -150,7 +150,7 @@ void CCharacter::HandleJetpack() if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; - if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + if(FullAuto && (m_LatestInput.m_Fire & 1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) WillFire = true; if(!WillFire) @@ -164,19 +164,19 @@ void CCharacter::HandleJetpack() switch(m_Core.m_ActiveWeapon) { - case WEAPON_GUN: + case WEAPON_GUN: + { + if(m_Jetpack) { - if (m_Jetpack) - { - float Strength; - if (!m_TuneZone) - Strength = GameServer()->Tuning()->m_JetpackStrength; - else - Strength = GameServer()->TuningList()[m_TuneZone].m_JetpackStrength; - TakeDamage(Direction * -1.0f * (Strength / 100.0f / 6.11f), 0, m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); - } + float Strength; + if(!m_TuneZone) + Strength = GameServer()->Tuning()->m_JetpackStrength; + else + Strength = GameServer()->TuningList()[m_TuneZone].m_JetpackStrength; + TakeDamage(Direction * -1.0f * (Strength / 100.0f / 6.11f), 0, m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); } } + } } void CCharacter::HandleNinja() @@ -184,7 +184,7 @@ void CCharacter::HandleNinja() if(m_Core.m_ActiveWeapon != WEAPON_NINJA) return; - if ((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) + if((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) { // time's up, return RemoveNinja(); @@ -193,7 +193,7 @@ void CCharacter::HandleNinja() int NinjaTime = m_Ninja.m_ActivationTick + (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000) - Server()->Tick(); - if (NinjaTime % Server()->TickSpeed() == 0 && NinjaTime / Server()->TickSpeed() <= 5) + if(NinjaTime % Server()->TickSpeed() == 0 && NinjaTime / Server()->TickSpeed() <= 5) { GameServer()->CreateDamageInd(m_Pos, 0, NinjaTime / Server()->TickSpeed(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); } @@ -205,13 +205,13 @@ void CCharacter::HandleNinja() m_Ninja.m_CurrentMoveTime--; - if (m_Ninja.m_CurrentMoveTime == 0) + if(m_Ninja.m_CurrentMoveTime == 0) { // reset velocity - m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; + m_Core.m_Vel = m_Ninja.m_ActivationDir * m_Ninja.m_OldVelAmount; } - if (m_Ninja.m_CurrentMoveTime > 0) + if(m_Ninja.m_CurrentMoveTime > 0) { // Set velocity m_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity; @@ -227,37 +227,37 @@ void CCharacter::HandleNinja() vec2 Dir = m_Pos - OldPos; float Radius = m_ProximityRadius * 2.0f; vec2 Center = OldPos + Dir * 0.5f; - int Num = GameServer()->m_World.FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + int Num = GameServer()->m_World.FindEntities(Center, Radius, (CEntity **)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); // check that we're not in solo part - if (Teams()->m_Core.GetSolo(m_pPlayer->GetCID())) + if(Teams()->m_Core.GetSolo(m_pPlayer->GetCID())) return; - for (int i = 0; i < Num; ++i) + for(int i = 0; i < Num; ++i) { - if (aEnts[i] == this) + if(aEnts[i] == this) continue; // Don't hit players in other teams - if (Team() != aEnts[i]->Team()) + if(Team() != aEnts[i]->Team()) continue; // Don't hit players in solo parts - if (Teams()->m_Core.GetSolo(aEnts[i]->m_pPlayer->GetCID())) + if(Teams()->m_Core.GetSolo(aEnts[i]->m_pPlayer->GetCID())) return; // make sure we haven't Hit this object before bool bAlreadyHit = false; - for (int j = 0; j < m_NumObjectsHit; j++) + for(int j = 0; j < m_NumObjectsHit; j++) { - if (m_apHitObjects[j] == aEnts[i]) + if(m_apHitObjects[j] == aEnts[i]) bAlreadyHit = true; } - if (bAlreadyHit) + if(bAlreadyHit) continue; // check so we are sufficiently close - if (distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) + if(distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) continue; // Hit a player, give him damage and stuffs... @@ -276,7 +276,6 @@ void CCharacter::HandleNinja() return; } - void CCharacter::DoWeaponSwitch() { // make sure we can switch @@ -294,11 +293,11 @@ void CCharacter::HandleWeaponSwitch() WantedWeapon = m_QueuedWeapon; bool Anything = false; - for(int i = 0; i < NUM_WEAPONS - 1; ++i) - if(m_aWeapons[i].m_Got) - Anything = true; - if(!Anything) - return; + for(int i = 0; i < NUM_WEAPONS - 1; ++i) + if(m_aWeapons[i].m_Got) + Anything = true; + if(!Anything) + return; // select Weapon int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses; int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses; @@ -307,7 +306,7 @@ void CCharacter::HandleWeaponSwitch() { while(Next) // Next Weapon selection { - WantedWeapon = (WantedWeapon+1)%NUM_WEAPONS; + WantedWeapon = (WantedWeapon + 1) % NUM_WEAPONS; if(m_aWeapons[WantedWeapon].m_Got) Next--; } @@ -317,7 +316,7 @@ void CCharacter::HandleWeaponSwitch() { while(Prev) // Prev Weapon selection { - WantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1; + WantedWeapon = (WantedWeapon - 1) < 0 ? NUM_WEAPONS - 1 : WantedWeapon - 1; if(m_aWeapons[WantedWeapon].m_Got) Prev--; } @@ -325,7 +324,7 @@ void CCharacter::HandleWeaponSwitch() // Direct Weapon selection if(m_LatestInput.m_WantedWeapon) - WantedWeapon = m_Input.m_WantedWeapon-1; + WantedWeapon = m_Input.m_WantedWeapon - 1; // check for insane values if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_Core.m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) @@ -338,7 +337,7 @@ void CCharacter::FireWeapon() { if(m_ReloadTimer != 0) { - if(m_LatestInput.m_Fire&1) + if(m_LatestInput.m_Fire & 1) { Antibot()->OnHammerFireReloading(m_pPlayer->GetCID()); } @@ -367,16 +366,16 @@ void CCharacter::FireWeapon() if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; - if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + if(FullAuto && (m_LatestInput.m_Fire & 1) && m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) WillFire = true; if(!WillFire) return; - if (m_FreezeTime) + if(m_FreezeTime) { // Timer stuff to avoid shrieking orchestra caused by unfreeze-plasma - if(m_PainSoundTimer<=0 && !(m_LatestPrevInput.m_Fire&1)) + if(m_PainSoundTimer <= 0 && !(m_LatestPrevInput.m_Fire & 1)) { m_PainSoundTimer = 1 * Server()->TickSpeed(); GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); @@ -393,116 +392,116 @@ void CCharacter::FireWeapon() return; } - vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f; + vec2 ProjStartPos = m_Pos + Direction * m_ProximityRadius * 0.75f; switch(m_Core.m_ActiveWeapon) { - case WEAPON_HAMMER: + case WEAPON_HAMMER: + { + // reset objects Hit + m_NumObjectsHit = 0; + GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + + Antibot()->OnHammerFire(m_pPlayer->GetCID()); + + if(m_Hit & DISABLE_HIT_HAMMER) + break; + + CCharacter *apEnts[MAX_CLIENTS]; + int Hits = 0; + int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius * 0.5f, (CEntity **)apEnts, + MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + for(int i = 0; i < Num; ++i) { - // reset objects Hit - m_NumObjectsHit = 0; - GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + CCharacter *pTarget = apEnts[i]; - Antibot()->OnHammerFire(m_pPlayer->GetCID()); + //if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL)) + if((pTarget == this || (pTarget->IsAlive() && !CanCollide(pTarget->GetPlayer()->GetCID())))) + continue; - if (m_Hit&DISABLE_HIT_HAMMER) break; + // set his velocity to fast upward (for now) + if(length(pTarget->m_Pos - ProjStartPos) > 0.0f) + GameServer()->CreateHammerHit(pTarget->m_Pos - normalize(pTarget->m_Pos - ProjStartPos) * m_ProximityRadius * 0.5f, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + else + GameServer()->CreateHammerHit(ProjStartPos, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - CCharacter *apEnts[MAX_CLIENTS]; - int Hits = 0; - int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts, - MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); - - for (int i = 0; i < Num; ++i) - { - CCharacter *pTarget = apEnts[i]; - - //if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL)) - if((pTarget == this || (pTarget->IsAlive() && !CanCollide(pTarget->GetPlayer()->GetCID())))) - continue; - - // set his velocity to fast upward (for now) - if(length(pTarget->m_Pos-ProjStartPos) > 0.0f) - GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - else - GameServer()->CreateHammerHit(ProjStartPos, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - - vec2 Dir; - if (length(pTarget->m_Pos - m_Pos) > 0.0f) - Dir = normalize(pTarget->m_Pos - m_Pos); - else - Dir = vec2(0.f, -1.f); - /*pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, + vec2 Dir; + if(length(pTarget->m_Pos - m_Pos) > 0.0f) + Dir = normalize(pTarget->m_Pos - m_Pos); + else + Dir = vec2(0.f, -1.f); + /*pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, m_pPlayer->GetCID(), m_Core.m_ActiveWeapon);*/ - float Strength; - if (!m_TuneZone) - Strength = GameServer()->Tuning()->m_HammerStrength; - else - Strength = GameServer()->TuningList()[m_TuneZone].m_HammerStrength; + float Strength; + if(!m_TuneZone) + Strength = GameServer()->Tuning()->m_HammerStrength; + else + Strength = GameServer()->TuningList()[m_TuneZone].m_HammerStrength; - vec2 Temp = pTarget->m_Core.m_Vel + normalize(Dir + vec2(0.f, - -1.1f)) * 10.0f; - Temp = ClampVel(pTarget->m_MoveRestrictions, Temp); - Temp -= pTarget->m_Core.m_Vel; - pTarget->TakeDamage((vec2(0.f, -1.0f) + Temp) * Strength, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, - m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); - pTarget->UnFreeze(); + vec2 Temp = pTarget->m_Core.m_Vel + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f; + Temp = ClampVel(pTarget->m_MoveRestrictions, Temp); + Temp -= pTarget->m_Core.m_Vel; + pTarget->TakeDamage((vec2(0.f, -1.0f) + Temp) * Strength, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, + m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); + pTarget->UnFreeze(); - if(m_FreezeHammer) - pTarget->Freeze(); + if(m_FreezeHammer) + pTarget->Freeze(); - Antibot()->OnHammerHit(m_pPlayer->GetCID()); + Antibot()->OnHammerHit(m_pPlayer->GetCID()); - Hits++; - } + Hits++; + } - // if we Hit anything, we have to wait for the reload - if(Hits) - m_ReloadTimer = Server()->TickSpeed()/3; + // if we Hit anything, we have to wait for the reload + if(Hits) + m_ReloadTimer = Server()->TickSpeed() / 3; + } + break; - } break; - - case WEAPON_GUN: + case WEAPON_GUN: + { + if(!m_Jetpack || !m_pPlayer->m_NinjaJetpack) { - if (!m_Jetpack || !m_pPlayer->m_NinjaJetpack) - { - int Lifetime; - if (!m_TuneZone) - Lifetime = (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime); - else - Lifetime = (int)(Server()->TickSpeed()*GameServer()->TuningList()[m_TuneZone].m_GunLifetime); + int Lifetime; + if(!m_TuneZone) + Lifetime = (int)(Server()->TickSpeed() * GameServer()->Tuning()->m_GunLifetime); + else + Lifetime = (int)(Server()->TickSpeed() * GameServer()->TuningList()[m_TuneZone].m_GunLifetime); - CProjectile *pProj = new CProjectile - ( - GameWorld(), - WEAPON_GUN,//Type - m_pPlayer->GetCID(),//Owner - ProjStartPos,//Pos - Direction,//Dir - Lifetime,//Span - 0,//Freeze - 0,//Explosive - 0,//Force - -1//SoundImpact - ); + CProjectile *pProj = new CProjectile( + GameWorld(), + WEAPON_GUN, //Type + m_pPlayer->GetCID(), //Owner + ProjStartPos, //Pos + Direction, //Dir + Lifetime, //Span + 0, //Freeze + 0, //Explosive + 0, //Force + -1 //SoundImpact + ); - // pack the Projectile and send it to the client Directly - CNetObj_Projectile p; - pProj->FillInfo(&p); + // pack the Projectile and send it to the client Directly + CNetObj_Projectile p; + pProj->FillInfo(&p); - CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); - Msg.AddInt(1); - for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) - Msg.AddInt(((int *)&p)[i]); + CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); + Msg.AddInt(1); + for(unsigned i = 0; i < sizeof(CNetObj_Projectile) / sizeof(int); i++) + Msg.AddInt(((int *)&p)[i]); - Server()->SendMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); - GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - } - } break; + Server()->SendMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); + GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + } + break; - case WEAPON_SHOTGUN: - { - /*int ShotSpread = 2; + case WEAPON_SHOTGUN: + { + /*int ShotSpread = 2; CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(ShotSpread*2+1); @@ -532,75 +531,77 @@ void CCharacter::FireWeapon() Server()->SendMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);*/ - float LaserReach; - if (!m_TuneZone) - LaserReach = GameServer()->Tuning()->m_LaserReach; - else - LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; + float LaserReach; + if(!m_TuneZone) + LaserReach = GameServer()->Tuning()->m_LaserReach; + else + LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; - new CLaser(&GameServer()->m_World, m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_SHOTGUN); - GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - } break; + new CLaser(&GameServer()->m_World, m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_SHOTGUN); + GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + break; - case WEAPON_GRENADE: - { - int Lifetime; - if (!m_TuneZone) - Lifetime = (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime); - else - Lifetime = (int)(Server()->TickSpeed()*GameServer()->TuningList()[m_TuneZone].m_GrenadeLifetime); + case WEAPON_GRENADE: + { + int Lifetime; + if(!m_TuneZone) + Lifetime = (int)(Server()->TickSpeed() * GameServer()->Tuning()->m_GrenadeLifetime); + else + Lifetime = (int)(Server()->TickSpeed() * GameServer()->TuningList()[m_TuneZone].m_GrenadeLifetime); - CProjectile *pProj = new CProjectile - ( - GameWorld(), - WEAPON_GRENADE,//Type - m_pPlayer->GetCID(),//Owner - ProjStartPos,//Pos - Direction,//Dir - Lifetime,//Span - 0,//Freeze - true,//Explosive - 0,//Force - SOUND_GRENADE_EXPLODE//SoundImpact - );//SoundImpact + CProjectile *pProj = new CProjectile( + GameWorld(), + WEAPON_GRENADE, //Type + m_pPlayer->GetCID(), //Owner + ProjStartPos, //Pos + Direction, //Dir + Lifetime, //Span + 0, //Freeze + true, //Explosive + 0, //Force + SOUND_GRENADE_EXPLODE //SoundImpact + ); //SoundImpact - // pack the Projectile and send it to the client Directly - CNetObj_Projectile p; - pProj->FillInfo(&p); + // pack the Projectile and send it to the client Directly + CNetObj_Projectile p; + pProj->FillInfo(&p); - CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); - Msg.AddInt(1); - for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) - Msg.AddInt(((int *)&p)[i]); - Server()->SendMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); + CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); + Msg.AddInt(1); + for(unsigned i = 0; i < sizeof(CNetObj_Projectile) / sizeof(int); i++) + Msg.AddInt(((int *)&p)[i]); + Server()->SendMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); - GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - } break; + GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + break; - case WEAPON_LASER: - { - float LaserReach; - if (!m_TuneZone) - LaserReach = GameServer()->Tuning()->m_LaserReach; - else - LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; + case WEAPON_LASER: + { + float LaserReach; + if(!m_TuneZone) + LaserReach = GameServer()->Tuning()->m_LaserReach; + else + LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; - new CLaser(GameWorld(), m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_LASER); - GameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - } break; + new CLaser(GameWorld(), m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_LASER); + GameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + break; - case WEAPON_NINJA: - { - // reset Hit objects - m_NumObjectsHit = 0; + case WEAPON_NINJA: + { + // reset Hit objects + m_NumObjectsHit = 0; - m_Ninja.m_ActivationDir = Direction; - m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000; - m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); - - GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); - } break; + m_Ninja.m_ActivationDir = Direction; + m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000; + m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); + GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + break; } m_AttackTick = Server()->Tick(); @@ -611,7 +612,7 @@ void CCharacter::FireWeapon() if(!m_ReloadTimer) { float FireDelay; - if (!m_TuneZone) + if(!m_TuneZone) GameServer()->Tuning()->Get(38 + m_Core.m_ActiveWeapon, &FireDelay); else GameServer()->TuningList()[m_TuneZone].Get(38 + m_Core.m_ActiveWeapon, &FireDelay); @@ -637,7 +638,7 @@ void CCharacter::HandleWeapons() // fire Weapon, if wanted FireWeapon(); -/* + /* // ammo regen int AmmoRegenTime = g_pData->m_Weapons.m_aId[m_Core.m_ActiveWeapon].m_Ammoregentime; if(AmmoRegenTime) @@ -669,7 +670,7 @@ void CCharacter::GiveNinja() m_Ninja.m_ActivationTick = Server()->Tick(); m_aWeapons[WEAPON_NINJA].m_Got = true; m_aWeapons[WEAPON_NINJA].m_Ammo = -1; - if (m_Core.m_ActiveWeapon != WEAPON_NINJA) + if(m_Core.m_ActiveWeapon != WEAPON_NINJA) m_LastWeapon = m_Core.m_ActiveWeapon; m_Core.m_ActiveWeapon = WEAPON_NINJA; @@ -683,7 +684,7 @@ void CCharacter::RemoveNinja() m_aWeapons[WEAPON_NINJA].m_Got = false; m_Core.m_ActiveWeapon = m_LastWeapon; - SetWeapon(m_Core.m_ActiveWeapon); + SetWeapon(m_Core.m_ActiveWeapon); } void CCharacter::SetEmote(int Emote, int Tick) @@ -735,7 +736,7 @@ void CCharacter::ResetInput() m_Input.m_Direction = 0; //m_Input.m_Hook = 0; // simulate releasing the fire button - if((m_Input.m_Fire&1) != 0) + if((m_Input.m_Fire & 1) != 0) m_Input.m_Fire++; m_Input.m_Fire &= INPUT_STATE_MASK; m_Input.m_Jump = 0; @@ -770,8 +771,7 @@ void CCharacter::Tick() m_Core.m_Input = m_Input; m_Core.Tick(true); - if(!m_PrevInput.m_Hook && m_Input.m_Hook - && !(m_Core.m_TriggeredEvents&COREEVENT_HOOK_ATTACH_PLAYER)) + if(!m_PrevInput.m_Hook && m_Input.m_Hook && !(m_Core.m_TriggeredEvents & COREEVENT_HOOK_ATTACH_PLAYER)) { Antibot()->OnHookAttach(m_pPlayer->GetCID(), false); } @@ -781,10 +781,9 @@ void CCharacter::Tick() DDRacePostCoreTick(); - if(m_Core.m_TriggeredEvents&COREEVENT_HOOK_ATTACH_PLAYER) + if(m_Core.m_TriggeredEvents & COREEVENT_HOOK_ATTACH_PLAYER) { - if(m_Core.m_HookedPlayer != -1 - && GameServer()->m_apPlayers[m_Core.m_HookedPlayer]->GetTeam() != -1) + if(m_Core.m_HookedPlayer != -1 && GameServer()->m_apPlayers[m_Core.m_HookedPlayer]->GetTeam() != -1) { Antibot()->OnHookAttach(m_pPlayer->GetCID(), true); } @@ -802,7 +801,7 @@ void CCharacter::TickDefered() // advance the dummy { CWorldCore TempWorld; - m_ReckoningCore.Init(&TempWorld, GameServer()->Collision(), &Teams()->m_Core, &((CGameControllerDDRace*)GameServer()->m_pController)->m_TeleOuts); + m_ReckoningCore.Init(&TempWorld, GameServer()->Collision(), &Teams()->m_Core, &((CGameControllerDDRace *)GameServer()->m_pController)->m_TeleOuts); m_ReckoningCore.m_Id = m_pPlayer->GetCID(); m_ReckoningCore.Tick(false); m_ReckoningCore.Move(); @@ -828,7 +827,7 @@ void CCharacter::TickDefered() { float f; unsigned u; - }StartPosX, StartPosY, StartVelX, StartVelY; + } StartPosX, StartPosY, StartVelX, StartVelY; StartPosX.f = StartPos.x; StartPosY.f = StartPos.y; @@ -856,24 +855,21 @@ void CCharacter::TickDefered() // so we need to avoid duplicating them int64 TeamMaskExceptSelf = Teams()->TeamMask(Team(), CID, CID); // Some are triggered client-side but only on Sixup - int64 TeamMaskExceptSelfIfSixup = Server()->IsSixup(CID) - ? TeamMaskExceptSelf - : TeamMask; + int64 TeamMaskExceptSelfIfSixup = Server()->IsSixup(CID) ? TeamMaskExceptSelf : TeamMask; - if(Events&COREEVENT_GROUND_JUMP) + if(Events & COREEVENT_GROUND_JUMP) GameServer()->CreateSound(m_Pos, SOUND_PLAYER_JUMP, TeamMaskExceptSelf); - if(Events&COREEVENT_HOOK_ATTACH_PLAYER) + if(Events & COREEVENT_HOOK_ATTACH_PLAYER) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_PLAYER, TeamMaskExceptSelfIfSixup); - if(Events&COREEVENT_HOOK_ATTACH_GROUND) + if(Events & COREEVENT_HOOK_ATTACH_GROUND) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_GROUND, TeamMaskExceptSelf); - if(Events&COREEVENT_HOOK_HIT_NOHOOK) + if(Events & COREEVENT_HOOK_HIT_NOHOOK) GameServer()->CreateSound(m_Pos, SOUND_HOOK_NOATTACH, TeamMaskExceptSelf); } - if(m_pPlayer->GetTeam() == TEAM_SPECTATORS) { m_Pos.x = m_Input.m_TargetX; @@ -890,7 +886,7 @@ void CCharacter::TickDefered() m_Core.Write(&Current); // only allow dead reackoning for a top of 3 seconds - if(m_Core.m_pReset || m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) + if(m_Core.m_pReset || m_ReckoningTick + Server()->TickSpeed() * 3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) { m_ReckoningTick = Server()->Tick(); m_SendCore = m_Core; @@ -918,7 +914,7 @@ bool CCharacter::IncreaseHealth(int Amount) { if(m_Health >= 10) return false; - m_Health = clamp(m_Health+Amount, 0, 10); + m_Health = clamp(m_Health + Amount, 0, 10); return true; } @@ -926,7 +922,7 @@ bool CCharacter::IncreaseArmor(int Amount) { if(m_Armor >= 10) return false; - m_Armor = clamp(m_Armor+Amount, 0, 10); + m_Armor = clamp(m_Armor + Amount, 0, 10); return true; } @@ -1055,7 +1051,7 @@ bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) else GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT);*/ - if (Dmg) + if(Dmg) { m_EmoteType = EMOTE_PAIN; m_EmoteStop = Server()->Tick() + 500 * Server()->TickSpeed() / 1000; @@ -1072,7 +1068,7 @@ void CCharacter::SnapCharacter(int SnappingClient, int ID) { CCharacterCore *pCore; int Tick, Emote = m_EmoteType, Weapon = m_Core.m_ActiveWeapon, AmmoCount = 0, - Health = 0, Armor = 0; + Health = 0, Armor = 0; if(!m_ReckoningTick || GameServer()->m_World.m_Paused) { Tick = 0; @@ -1130,7 +1126,7 @@ void CCharacter::SnapCharacter(int SnappingClient, int ID) Health = m_Health; Armor = m_Armor; if(m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo > 0) - AmmoCount = (!m_FreezeTime)?m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo:0; + AmmoCount = (!m_FreezeTime) ? m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo : 0; } if(GetPlayer()->m_Afk || GetPlayer()->IsPaused()) @@ -1143,13 +1139,13 @@ void CCharacter::SnapCharacter(int SnappingClient, int ID) if(Emote == EMOTE_NORMAL) { - if(250 - ((Server()->Tick() - m_LastAction)%(250)) < 5) + if(250 - ((Server()->Tick() - m_LastAction) % (250)) < 5) Emote = EMOTE_BLINK; } if(m_pPlayer->m_Halloween) { - if(1200 - ((Server()->Tick() - m_LastAction)%(1200)) < 5) + if(1200 - ((Server()->Tick() - m_LastAction) % (1200)) < 5) { GameServer()->SendEmoticon(m_pPlayer->GetCID(), EMOTICON_GHOST); } @@ -1195,7 +1191,7 @@ void CCharacter::SnapCharacter(int SnappingClient, int ID) pCharacter->m_Weapon = Weapon; pCharacter->m_AmmoCount = AmmoCount; - if (m_FreezeTime > 0 || m_FreezeTime == -1 || m_DeepFreeze) + if(m_FreezeTime > 0 || m_FreezeTime == -1 || m_DeepFreeze) pCharacter->m_AmmoCount = m_FreezeTick + g_Config.m_SvFreezeDelay * Server()->TickSpeed(); else if(Weapon == WEAPON_NINJA) pCharacter->m_AmmoCount = m_Ninja.m_ActivationTick + g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000; @@ -1232,7 +1228,7 @@ void CCharacter::Snap(int SnappingClient) return; } - if (m_Paused) + if(m_Paused) return; SnapCharacter(SnappingClient, ID); @@ -1256,13 +1252,13 @@ void CCharacter::Snap(int SnappingClient) pDDNetCharacter->m_Flags |= CHARACTERFLAG_ENDLESS_JUMP; if(m_Jetpack || m_NinjaJetpack) pDDNetCharacter->m_Flags |= CHARACTERFLAG_JETPACK; - if(m_Hit&DISABLE_HIT_GRENADE) + if(m_Hit & DISABLE_HIT_GRENADE) pDDNetCharacter->m_Flags |= CHARACTERFLAG_NO_GRENADE_HIT; - if(m_Hit&DISABLE_HIT_HAMMER) + if(m_Hit & DISABLE_HIT_HAMMER) pDDNetCharacter->m_Flags |= CHARACTERFLAG_NO_HAMMER_HIT; - if(m_Hit&DISABLE_HIT_LASER) + if(m_Hit & DISABLE_HIT_LASER) pDDNetCharacter->m_Flags |= CHARACTERFLAG_NO_LASER_HIT; - if(m_Hit&DISABLE_HIT_SHOTGUN) + if(m_Hit & DISABLE_HIT_SHOTGUN) pDDNetCharacter->m_Flags |= CHARACTERFLAG_NO_SHOTGUN_HIT; if(m_Core.m_HasTelegunGun) pDDNetCharacter->m_Flags |= CHARACTERFLAG_TELEGUN_GUN; @@ -1299,11 +1295,11 @@ int CCharacter::NetworkClipped(int SnappingClient, vec2 CheckPos) if(SnappingClient == -1 || GameServer()->m_apPlayers[SnappingClient]->m_ShowAll) return 0; - float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x; + float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x - CheckPos.x; if(absolute(dx) > GameServer()->m_apPlayers[SnappingClient]->m_ShowDistance.x) return 1; - float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y; + float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y - CheckPos.y; if(absolute(dy) > GameServer()->m_apPlayers[SnappingClient]->m_ShowDistance.y) return 1; @@ -1326,9 +1322,9 @@ int CCharacter::Team() return Teams()->m_Core.Team(m_pPlayer->GetCID()); } -CGameTeams* CCharacter::Teams() +CGameTeams *CCharacter::Teams() { - return &((CGameControllerDDRace*)GameServer()->m_pController)->m_Teams; + return &((CGameControllerDDRace *)GameServer()->m_pController)->m_Teams; } void CCharacter::FillAntibot(CAntibotCharacterData *pData) @@ -1352,8 +1348,8 @@ void CCharacter::HandleBroadcast() CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); if(m_DDRaceState == DDRACE_STARTED && m_CpLastBroadcast != m_CpActive && - m_CpActive > -1 && m_CpTick > Server()->Tick() && m_pPlayer->GetClientVersion() == VERSION_VANILLA && - pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) + m_CpActive > -1 && m_CpTick > Server()->Tick() && m_pPlayer->GetClientVersion() == VERSION_VANILLA && + pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) { char aBroadcast[128]; float Diff = m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive]; @@ -1362,11 +1358,11 @@ void CCharacter::HandleBroadcast() m_CpLastBroadcast = m_CpActive; m_LastBroadcast = Server()->Tick(); } - else if ((m_pPlayer->m_TimerType == CPlayer::TIMERTYPE_BROADCAST || m_pPlayer->m_TimerType == CPlayer::TIMERTYPE_GAMETIMER_AND_BROADCAST) && m_DDRaceState == DDRACE_STARTED && m_LastBroadcast + Server()->TickSpeed() * g_Config.m_SvTimeInBroadcastInterval <= Server()->Tick()) + else if((m_pPlayer->m_TimerType == CPlayer::TIMERTYPE_BROADCAST || m_pPlayer->m_TimerType == CPlayer::TIMERTYPE_GAMETIMER_AND_BROADCAST) && m_DDRaceState == DDRACE_STARTED && m_LastBroadcast + Server()->TickSpeed() * g_Config.m_SvTimeInBroadcastInterval <= Server()->Tick()) { char aBuftime[64]; int IntTime = (int)((float)(Server()->Tick() - m_StartTime) / ((float)Server()->TickSpeed())); - str_format(aBuftime, sizeof(aBuftime), "%s%d:%s%d", ((IntTime/60) > 9)?"":"0", IntTime/60, ((IntTime%60) > 9)?"":"0", IntTime%60); + str_format(aBuftime, sizeof(aBuftime), "%s%d:%s%d", ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); GameServer()->SendBroadcast(aBuftime, m_pPlayer->GetCID(), false); m_CpLastBroadcast = m_CpActive; m_LastBroadcast = Server()->Tick(); @@ -1376,20 +1372,20 @@ void CCharacter::HandleBroadcast() void CCharacter::HandleSkippableTiles(int Index) { // handle death-tiles and leaving gamelayer - if((GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f) == TILE_DEATH || - GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f) == TILE_DEATH || - GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f) == TILE_DEATH || - GameServer()->Collision()->GetFCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f) == TILE_DEATH|| - GameServer()->Collision()->GetFCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f) == TILE_DEATH || - GameServer()->Collision()->GetFCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f) == TILE_DEATH || - GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f) == TILE_DEATH) && - !m_Super && !(Team() && Teams()->TeeFinished(m_pPlayer->GetCID()))) + if((GameServer()->Collision()->GetCollisionAt(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetCollisionAt(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y + m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetCollisionAt(m_Pos.x - m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetFCollisionAt(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetFCollisionAt(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y + m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetFCollisionAt(m_Pos.x - m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f) == TILE_DEATH || + GameServer()->Collision()->GetCollisionAt(m_Pos.x - m_ProximityRadius / 3.f, m_Pos.y + m_ProximityRadius / 3.f) == TILE_DEATH) && + !m_Super && !(Team() && Teams()->TeeFinished(m_pPlayer->GetCID()))) { Die(m_pPlayer->GetCID(), WEAPON_WORLD); return; } - if (GameLayerClipped(m_Pos)) + if(GameLayerClipped(m_Pos)) { Die(m_pPlayer->GetCID(), WEAPON_WORLD); return; @@ -1407,11 +1403,12 @@ void CCharacter::HandleSkippableTiles(int Index) GameServer()->Collision()->GetSpeedup(Index, &Direction, &Force, &MaxSpeed); if(Force == 255 && MaxSpeed) { - m_Core.m_Vel = Direction * (MaxSpeed/5); + m_Core.m_Vel = Direction * (MaxSpeed / 5); } else { - if(MaxSpeed > 0 && MaxSpeed < 5) MaxSpeed = 5; + if(MaxSpeed > 0 && MaxSpeed < 5) + MaxSpeed = 5; if(MaxSpeed > 0) { if(Direction.x > 0.0000001f) @@ -1466,7 +1463,7 @@ bool CCharacter::IsSwitchActiveCb(int Number, void *pUser) void CCharacter::HandleTiles(int Index) { - CGameControllerDDRace* Controller = (CGameControllerDDRace*)GameServer()->m_pController; + CGameControllerDDRace *Controller = (CGameControllerDDRace *)GameServer()->m_pController; int MapIndex = Index; //int PureMapIndex = GameServer()->Collision()->GetPureMapIndex(m_Pos); m_TileIndex = GameServer()->Collision()->GetTileIndex(MapIndex); @@ -1498,7 +1495,8 @@ void CCharacter::HandleTiles(int Index) m_CpActive = cp; m_CpCurrent[cp] = m_Time; m_CpTick = Server()->Tick() + Server()->TickSpeed() * 2; - if(m_pPlayer->GetClientVersion() >= VERSION_DDRACE) { + if(m_pPlayer->GetClientVersion() >= VERSION_DDRACE) + { CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); CNetMsg_Sv_DDRaceTime Msg; Msg.m_Time = (int)m_Time; @@ -1509,7 +1507,7 @@ void CCharacter::HandleTiles(int Index) { if(pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) { - float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive])*100; + float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive]) * 100; Msg.m_Check = (int)Diff; } } @@ -1522,8 +1520,9 @@ void CCharacter::HandleTiles(int Index) { m_CpActive = cpf; m_CpCurrent[cpf] = m_Time; - m_CpTick = Server()->Tick() + Server()->TickSpeed()*2; - if(m_pPlayer->GetClientVersion() >= VERSION_DDRACE) { + m_CpTick = Server()->Tick() + Server()->TickSpeed() * 2; + if(m_pPlayer->GetClientVersion() >= VERSION_DDRACE) + { CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); CNetMsg_Sv_DDRaceTime Msg; Msg.m_Time = (int)m_Time; @@ -1534,7 +1533,7 @@ void CCharacter::HandleTiles(int Index) { if(pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) { - float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive])*100; + float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive]) * 100; Msg.m_Check = (int)Diff; } } @@ -1571,7 +1570,7 @@ void CCharacter::HandleTiles(int Index) } if(g_Config.m_SvResetPickups) { - for (int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; ++i) + for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; ++i) { m_aWeapons[i].m_Got = false; if(m_Core.m_ActiveWeapon == i) @@ -1617,7 +1616,7 @@ void CCharacter::HandleTiles(int Index) if(((m_TileIndex == TILE_HIT_DISABLE) || (m_TileFIndex == TILE_HIT_DISABLE)) && m_Hit != (DISABLE_HIT_GRENADE | DISABLE_HIT_HAMMER | DISABLE_HIT_LASER | DISABLE_HIT_SHOTGUN)) { GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't hit others"); - m_Hit = DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_LASER|DISABLE_HIT_SHOTGUN; + m_Hit = DISABLE_HIT_GRENADE | DISABLE_HIT_HAMMER | DISABLE_HIT_LASER | DISABLE_HIT_SHOTGUN; m_Core.m_NoShotgunHit = true; m_Core.m_NoGrenadeHit = true; m_Core.m_NoHammerHit = true; @@ -1648,7 +1647,7 @@ void CCharacter::HandleTiles(int Index) } else if(((m_TileIndex == TILE_NPC_ENABLE) || (m_TileFIndex == TILE_NPC_ENABLE)) && !m_Core.m_Collision) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can collide with others"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can collide with others"); m_Core.m_Collision = true; m_Core.m_NoCollision = false; m_NeededFaketuning &= ~FAKETUNE_NOCOLL; @@ -1666,7 +1665,7 @@ void CCharacter::HandleTiles(int Index) } else if(((m_TileIndex == TILE_NPH_ENABLE) || (m_TileFIndex == TILE_NPH_ENABLE)) && !m_Core.m_Hook) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can hook others"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can hook others"); m_Core.m_Hook = true; m_Core.m_NoHookHit = false; m_NeededFaketuning &= ~FAKETUNE_NOHOOK; @@ -1676,10 +1675,10 @@ void CCharacter::HandleTiles(int Index) // unlimited air jumps if(((m_TileIndex == TILE_UNLIMITED_JUMPS_ENABLE) || (m_TileFIndex == TILE_UNLIMITED_JUMPS_ENABLE)) && !m_SuperJump) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You have unlimited air jumps"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You have unlimited air jumps"); m_SuperJump = true; m_Core.m_EndlessJump = true; - if (m_Core.m_Jumps == 0) + if(m_Core.m_Jumps == 0) { m_NeededFaketuning &= ~FAKETUNE_NOJUMP; GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings @@ -1690,7 +1689,7 @@ void CCharacter::HandleTiles(int Index) GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You don't have unlimited air jumps"); m_SuperJump = false; m_Core.m_EndlessJump = false; - if (m_Core.m_Jumps == 0) + if(m_Core.m_Jumps == 0) { m_NeededFaketuning |= FAKETUNE_NOJUMP; GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings @@ -1711,7 +1710,7 @@ void CCharacter::HandleTiles(int Index) // jetpack gun if(((m_TileIndex == TILE_JETPACK_ENABLE) || (m_TileFIndex == TILE_JETPACK_ENABLE)) && !m_Jetpack) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You have a jetpack gun"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You have a jetpack gun"); m_Jetpack = true; m_Core.m_Jetpack = true; } @@ -1757,41 +1756,41 @@ void CCharacter::HandleTiles(int Index) } // Teleport gun - if (((m_TileIndex == TILE_TELE_GUN_ENABLE) || (m_TileFIndex == TILE_TELE_GUN_ENABLE)) && !m_Core.m_HasTelegunGun) + if(((m_TileIndex == TILE_TELE_GUN_ENABLE) || (m_TileFIndex == TILE_TELE_GUN_ENABLE)) && !m_Core.m_HasTelegunGun) { m_Core.m_HasTelegunGun = true; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport gun enabled"); } - else if (((m_TileIndex == TILE_TELE_GUN_DISABLE) || (m_TileFIndex == TILE_TELE_GUN_DISABLE)) && m_Core.m_HasTelegunGun) + else if(((m_TileIndex == TILE_TELE_GUN_DISABLE) || (m_TileFIndex == TILE_TELE_GUN_DISABLE)) && m_Core.m_HasTelegunGun) { m_Core.m_HasTelegunGun = false; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport gun disabled"); } - if (((m_TileIndex == TILE_TELE_GRENADE_ENABLE) || (m_TileFIndex == TILE_TELE_GRENADE_ENABLE)) && !m_Core.m_HasTelegunGrenade) + if(((m_TileIndex == TILE_TELE_GRENADE_ENABLE) || (m_TileFIndex == TILE_TELE_GRENADE_ENABLE)) && !m_Core.m_HasTelegunGrenade) { m_Core.m_HasTelegunGrenade = true; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport grenade enabled"); } - else if (((m_TileIndex == TILE_TELE_GRENADE_DISABLE) || (m_TileFIndex == TILE_TELE_GRENADE_DISABLE)) && m_Core.m_HasTelegunGrenade) + else if(((m_TileIndex == TILE_TELE_GRENADE_DISABLE) || (m_TileFIndex == TILE_TELE_GRENADE_DISABLE)) && m_Core.m_HasTelegunGrenade) { m_Core.m_HasTelegunGrenade = false; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport grenade disabled"); } - if (((m_TileIndex == TILE_TELE_LASER_ENABLE) || (m_TileFIndex == TILE_TELE_LASER_ENABLE)) && !m_Core.m_HasTelegunLaser) + if(((m_TileIndex == TILE_TELE_LASER_ENABLE) || (m_TileFIndex == TILE_TELE_LASER_ENABLE)) && !m_Core.m_HasTelegunLaser) { m_Core.m_HasTelegunLaser = true; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport laser enabled"); } - else if (((m_TileIndex == TILE_TELE_LASER_DISABLE) || (m_TileFIndex == TILE_TELE_LASER_DISABLE)) && m_Core.m_HasTelegunLaser) + else if(((m_TileIndex == TILE_TELE_LASER_DISABLE) || (m_TileFIndex == TILE_TELE_LASER_DISABLE)) && m_Core.m_HasTelegunLaser) { m_Core.m_HasTelegunLaser = false; GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Teleport laser disabled"); } // stopper - if(m_Core.m_Vel.y > 0 && (m_MoveRestrictions&CANTMOVE_DOWN)) + if(m_Core.m_Vel.y > 0 && (m_MoveRestrictions & CANTMOVE_DOWN)) { m_Core.m_Jumped = 0; m_Core.m_JumpedTotal = 0; @@ -1808,13 +1807,13 @@ void CCharacter::HandleTiles(int Index) else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDOPEN && Team() != TEAM_SUPER && GameServer()->Collision()->GetSwitchNumber(MapIndex) > 0) { GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = true; - GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex)*Server()->TickSpeed() ; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex) * Server()->TickSpeed(); GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDOPEN; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDCLOSE && Team() != TEAM_SUPER && GameServer()->Collision()->GetSwitchNumber(MapIndex) > 0) { GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = false; - GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex)*Server()->TickSpeed(); + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex) * Server()->TickSpeed(); GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDCLOSE; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHCLOSE && Team() != TEAM_SUPER && GameServer()->Collision()->GetSwitchNumber(MapIndex) > 0) @@ -1840,7 +1839,7 @@ void CCharacter::HandleTiles(int Index) } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_ENABLE && m_Hit & DISABLE_HIT_HAMMER && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_HAMMER) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can hammer hit others"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can hammer hit others"); m_Hit &= ~DISABLE_HIT_HAMMER; m_NeededFaketuning &= ~FAKETUNE_NOHAMMER; m_Core.m_NoHammerHit = false; @@ -1848,7 +1847,7 @@ void CCharacter::HandleTiles(int Index) } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_DISABLE && !(m_Hit & DISABLE_HIT_HAMMER) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_HAMMER) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't hammer hit others"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't hammer hit others"); m_Hit |= DISABLE_HIT_HAMMER; m_NeededFaketuning |= FAKETUNE_NOHAMMER; m_Core.m_NoHammerHit = true; @@ -1856,37 +1855,37 @@ void CCharacter::HandleTiles(int Index) } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_ENABLE && m_Hit & DISABLE_HIT_SHOTGUN && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_SHOTGUN) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with shotgun"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can shoot others with shotgun"); m_Hit &= ~DISABLE_HIT_SHOTGUN; m_Core.m_NoShotgunHit = false; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_DISABLE && !(m_Hit & DISABLE_HIT_SHOTGUN) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_SHOTGUN) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with shotgun"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't shoot others with shotgun"); m_Hit |= DISABLE_HIT_SHOTGUN; m_Core.m_NoShotgunHit = true; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_ENABLE && m_Hit & DISABLE_HIT_GRENADE && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_GRENADE) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with grenade"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can shoot others with grenade"); m_Hit &= ~DISABLE_HIT_GRENADE; m_Core.m_NoGrenadeHit = false; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_DISABLE && !(m_Hit & DISABLE_HIT_GRENADE) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_GRENADE) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with grenade"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't shoot others with grenade"); m_Hit |= DISABLE_HIT_GRENADE; m_Core.m_NoGrenadeHit = true; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_ENABLE && m_Hit & DISABLE_HIT_LASER && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_LASER) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with laser"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can shoot others with laser"); m_Hit &= ~DISABLE_HIT_LASER; m_Core.m_NoLaserHit = false; } else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_DISABLE && !(m_Hit & DISABLE_HIT_LASER) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_LASER) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with laser"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't shoot others with laser"); m_Hit |= DISABLE_HIT_LASER; m_Core.m_NoLaserHit = true; } @@ -1894,21 +1893,21 @@ void CCharacter::HandleTiles(int Index) { int newJumps = GameServer()->Collision()->GetSwitchDelay(MapIndex); - if (newJumps != m_Core.m_Jumps) + if(newJumps != m_Core.m_Jumps) { char aBuf[256]; if(newJumps == 1) str_format(aBuf, sizeof(aBuf), "You can jump %d time", newJumps); else str_format(aBuf, sizeof(aBuf), "You can jump %d times", newJumps); - GameServer()->SendChatTarget(GetPlayer()->GetCID(),aBuf); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), aBuf); - if (newJumps == 0 && !m_SuperJump) + if(newJumps == 0 && !m_SuperJump) { m_NeededFaketuning |= FAKETUNE_NOJUMP; GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings } - else if (m_Core.m_Jumps == 0) + else if(m_Core.m_Jumps == 0) { m_NeededFaketuning &= ~FAKETUNE_NOJUMP; GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings @@ -1925,15 +1924,15 @@ void CCharacter::HandleTiles(int Index) m_StartTime -= (min * 60 + sec) * Server()->TickSpeed(); - if ((g_Config.m_SvTeam == 3 || Team != TEAM_FLOCK) && Team != TEAM_SUPER) + if((g_Config.m_SvTeam == 3 || Team != TEAM_FLOCK) && Team != TEAM_SUPER) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(Teams()->m_Core.Team(i) == Team && i != m_Core.m_Id && GameServer()->m_apPlayers[i]) { - CCharacter* pChar = GameServer()->m_apPlayers[i]->GetCharacter(); + CCharacter *pChar = GameServer()->m_apPlayers[i]->GetCharacter(); - if (pChar) + if(pChar) pChar->m_StartTime = m_StartTime; } } @@ -1948,18 +1947,18 @@ void CCharacter::HandleTiles(int Index) int Team = Teams()->m_Core.Team(m_Core.m_Id); m_StartTime += (min * 60 + sec) * Server()->TickSpeed(); - if (m_StartTime > Server()->Tick()) + if(m_StartTime > Server()->Tick()) m_StartTime = Server()->Tick(); - if ((g_Config.m_SvTeam == 3 || Team != TEAM_FLOCK) && Team != TEAM_SUPER) + if((g_Config.m_SvTeam == 3 || Team != TEAM_FLOCK) && Team != TEAM_SUPER) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(Teams()->m_Core.Team(i) == Team && i != m_Core.m_Id && GameServer()->m_apPlayers[i]) { - CCharacter* pChar = GameServer()->m_apPlayers[i]->GetCharacter(); + CCharacter *pChar = GameServer()->m_apPlayers[i]->GetCharacter(); - if (pChar) + if(pChar) pChar->m_StartTime = m_StartTime; } } @@ -1979,12 +1978,12 @@ void CCharacter::HandleTiles(int Index) } int z = GameServer()->Collision()->IsTeleport(MapIndex); - if(!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons && z && Controller->m_TeleOuts[z-1].size()) + if(!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons && z && Controller->m_TeleOuts[z - 1].size()) { - if (m_Super) + if(m_Super) return; - int TeleOut = m_Core.m_pWorld->RandomOr0(Controller->m_TeleOuts[z-1].size()); - m_Core.m_Pos = Controller->m_TeleOuts[z-1][TeleOut]; + int TeleOut = m_Core.m_pWorld->RandomOr0(Controller->m_TeleOuts[z - 1].size()); + m_Core.m_Pos = Controller->m_TeleOuts[z - 1][TeleOut]; if(!g_Config.m_SvTeleportHoldHook) { m_Core.m_HookedPlayer = -1; @@ -1994,21 +1993,21 @@ void CCharacter::HandleTiles(int Index) } if(g_Config.m_SvTeleportLoseWeapons) { - for(int i=WEAPON_SHOTGUN;iCollision()->IsEvilTeleport(MapIndex); - if(evilz && Controller->m_TeleOuts[evilz-1].size()) + if(evilz && Controller->m_TeleOuts[evilz - 1].size()) { - if (m_Super) + if(m_Super) return; - int TeleOut = m_Core.m_pWorld->RandomOr0(Controller->m_TeleOuts[evilz-1].size()); - m_Core.m_Pos = Controller->m_TeleOuts[evilz-1][TeleOut]; - if (!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons) + int TeleOut = m_Core.m_pWorld->RandomOr0(Controller->m_TeleOuts[evilz - 1].size()); + m_Core.m_Pos = Controller->m_TeleOuts[evilz - 1][TeleOut]; + if(!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons) { - m_Core.m_Vel = vec2(0,0); + m_Core.m_Vel = vec2(0, 0); if(!g_Config.m_SvTeleportHoldHook) { @@ -2020,7 +2019,7 @@ void CCharacter::HandleTiles(int Index) } if(g_Config.m_SvTeleportLoseWeapons) { - for(int i=WEAPON_SHOTGUN;iCollision()->IsCheckEvilTeleport(MapIndex)) { - if (m_Super) + if(m_Super) return; // first check if there is a TeleCheckOut for the current recorded checkpoint, if not check previous checkpoints - for(int k=m_TeleCheckpoint-1; k >= 0; k--) + for(int k = m_TeleCheckpoint - 1; k >= 0; k--) { if(Controller->m_TeleCheckOuts[k].size()) { int TeleOut = m_Core.m_pWorld->RandomOr0(Controller->m_TeleCheckOuts[k].size()); m_Core.m_Pos = Controller->m_TeleCheckOuts[k][TeleOut]; - m_Core.m_Vel = vec2(0,0); + m_Core.m_Vel = vec2(0, 0); if(!g_Config.m_SvTeleportHoldHook) { @@ -2056,7 +2055,7 @@ void CCharacter::HandleTiles(int Index) if(GameServer()->m_pController->CanSpawn(m_pPlayer->GetTeam(), &SpawnPos)) { m_Core.m_Pos = SpawnPos; - m_Core.m_Vel = vec2(0,0); + m_Core.m_Vel = vec2(0, 0); if(!g_Config.m_SvTeleportHoldHook) { @@ -2071,10 +2070,10 @@ void CCharacter::HandleTiles(int Index) } if(GameServer()->Collision()->IsCheckTeleport(MapIndex)) { - if (m_Super) + if(m_Super) return; // first check if there is a TeleCheckOut for the current recorded checkpoint, if not check previous checkpoints - for(int k=m_TeleCheckpoint-1; k >= 0; k--) + for(int k = m_TeleCheckpoint - 1; k >= 0; k--) { if(Controller->m_TeleCheckOuts[k].size()) { @@ -2112,7 +2111,6 @@ void CCharacter::HandleTiles(int Index) void CCharacter::HandleTuneLayer() { - m_TuneZoneOld = m_TuneZone; int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_Pos); m_TuneZone = GameServer()->Collision()->IsTune(CurrentIndex); @@ -2122,7 +2120,7 @@ void CCharacter::HandleTuneLayer() else m_Core.m_pWorld->m_Tuning[g_Config.m_ClDummy] = *GameServer()->Tuning(); - if (m_TuneZone != m_TuneZoneOld) // don't send tunigs all the time + if(m_TuneZone != m_TuneZoneOld) // don't send tunigs all the time { // send zone msgs SendZoneMsgs(); @@ -2133,11 +2131,11 @@ void CCharacter::SendZoneMsgs() { // send zone leave msg // (m_TuneZoneOld >= 0: avoid zone leave msgs on spawn) - if (m_TuneZoneOld >= 0 && GameServer()->m_aaZoneLeaveMsg[m_TuneZoneOld]) + if(m_TuneZoneOld >= 0 && GameServer()->m_aaZoneLeaveMsg[m_TuneZoneOld]) { const char *pCur = GameServer()->m_aaZoneLeaveMsg[m_TuneZoneOld]; const char *pPos; - while ((pPos = str_find(pCur, "\\n"))) + while((pPos = str_find(pCur, "\\n"))) { char aBuf[256]; str_copy(aBuf, pCur, pPos - pCur + 1); @@ -2148,11 +2146,11 @@ void CCharacter::SendZoneMsgs() GameServer()->SendChatTarget(m_pPlayer->GetCID(), pCur); } // send zone enter msg - if (GameServer()->m_aaZoneEnterMsg[m_TuneZone]) + if(GameServer()->m_aaZoneEnterMsg[m_TuneZone]) { - const char* pCur = GameServer()->m_aaZoneEnterMsg[m_TuneZone]; - const char* pPos; - while ((pPos = str_find(pCur, "\\n"))) + const char *pCur = GameServer()->m_aaZoneEnterMsg[m_TuneZone]; + const char *pPos; + while((pPos = str_find(pCur, "\\n"))) { char aBuf[256]; str_copy(aBuf, pCur, pPos - pCur + 1); @@ -2178,13 +2176,13 @@ void CCharacter::SetRescue() void CCharacter::DDRaceTick() { mem_copy(&m_Input, &m_SavedInput, sizeof(m_Input)); - m_Armor=(m_FreezeTime >= 0)?10-(m_FreezeTime/15):0; + m_Armor = (m_FreezeTime >= 0) ? 10 - (m_FreezeTime / 15) : 0; if(m_Input.m_Direction != 0 || m_Input.m_Jump != 0) m_LastMove = Server()->Tick(); if(m_FreezeTime > 0 || m_FreezeTime == -1) { - if (m_FreezeTime % Server()->TickSpeed() == Server()->TickSpeed() - 1 || m_FreezeTime == -1) + if(m_FreezeTime % Server()->TickSpeed() == Server()->TickSpeed() - 1 || m_FreezeTime == -1) { GameServer()->CreateDamageInd(m_Pos, 0, (m_FreezeTime + 1) / Server()->TickSpeed(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); } @@ -2195,21 +2193,20 @@ void CCharacter::DDRaceTick() m_Input.m_Direction = 0; m_Input.m_Jump = 0; m_Input.m_Hook = 0; - if (m_FreezeTime == 1) + if(m_FreezeTime == 1) UnFreeze(); } HandleTuneLayer(); // need this before coretick // look for save position for rescue feature - if(g_Config.m_SvRescue - || ((g_Config.m_SvTeam == 3 || Team() > TEAM_FLOCK) - && Team() >= TEAM_FLOCK - && Team() < TEAM_SUPER)) { + if(g_Config.m_SvRescue || ((g_Config.m_SvTeam == 3 || Team() > TEAM_FLOCK) && Team() >= TEAM_FLOCK && Team() < TEAM_SUPER)) + { int index = GameServer()->Collision()->GetPureMapIndex(m_Pos); int tile = GameServer()->Collision()->GetTileIndex(index); int ftile = GameServer()->Collision()->GetFTileIndex(index); - if(IsGrounded() && tile != TILE_FREEZE && tile != TILE_DFREEZE && ftile != TILE_FREEZE && ftile != TILE_DFREEZE && !m_DeepFreeze) { + if(IsGrounded() && tile != TILE_FREEZE && tile != TILE_DFREEZE && ftile != TILE_FREEZE && ftile != TILE_DFREEZE && !m_DeepFreeze) + { SetRescue(); } } @@ -2221,29 +2218,29 @@ void CCharacter::DDRacePostCoreTick() { m_Time = (float)(Server()->Tick() - m_StartTime) / ((float)Server()->TickSpeed()); - if (m_pPlayer->m_DefEmoteReset >= 0 && m_pPlayer->m_DefEmoteReset <= Server()->Tick()) + if(m_pPlayer->m_DefEmoteReset >= 0 && m_pPlayer->m_DefEmoteReset <= Server()->Tick()) { m_pPlayer->m_DefEmoteReset = -1; m_EmoteType = m_pPlayer->m_DefEmote = EMOTE_NORMAL; m_EmoteStop = -1; } - if (m_EndlessHook || (m_Super && g_Config.m_SvEndlessSuperHook)) + if(m_EndlessHook || (m_Super && g_Config.m_SvEndlessSuperHook)) m_Core.m_HookTick = 0; m_FrozenLastTick = false; - if (m_DeepFreeze && !m_Super) + if(m_DeepFreeze && !m_Super) Freeze(); - if (m_Core.m_Jumps == 0 && !m_Super) + if(m_Core.m_Jumps == 0 && !m_Super) m_Core.m_Jumped = 3; - else if (m_Core.m_Jumps == 1 && m_Core.m_Jumped > 0) + else if(m_Core.m_Jumps == 1 && m_Core.m_Jumped > 0) m_Core.m_Jumped = 3; - else if (m_Core.m_JumpedTotal < m_Core.m_Jumps - 1 && m_Core.m_Jumped > 1) + else if(m_Core.m_JumpedTotal < m_Core.m_Jumps - 1 && m_Core.m_Jumped > 1) m_Core.m_Jumped = 1; - if ((m_Super || m_SuperJump) && m_Core.m_Jumped > 1) + if((m_Super || m_SuperJump) && m_Core.m_Jumped > 1) m_Core.m_Jumped = 1; int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_Pos); @@ -2252,10 +2249,10 @@ void CCharacter::DDRacePostCoreTick() return; // handle Anti-Skip tiles - std::list < int > Indices = GameServer()->Collision()->GetMapIndices(m_PrevPos, m_Pos); + std::list Indices = GameServer()->Collision()->GetMapIndices(m_PrevPos, m_Pos); if(!Indices.empty()) { - for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + for(std::list::iterator i = Indices.begin(); i != Indices.end(); i++) { HandleTiles(*i); if(!m_Alive) @@ -2270,7 +2267,7 @@ void CCharacter::DDRacePostCoreTick() } // teleport gun - if (m_TeleGunTeleport) + if(m_TeleGunTeleport) { GameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); m_Core.m_Pos = m_TeleGunPos; @@ -2287,9 +2284,9 @@ void CCharacter::DDRacePostCoreTick() bool CCharacter::Freeze(int Seconds) { - if ((Seconds <= 0 || m_Super || m_FreezeTime == -1 || m_FreezeTime > Seconds * Server()->TickSpeed()) && Seconds != -1) - return false; - if (m_FreezeTick < Server()->Tick() - Server()->TickSpeed() || Seconds == -1) + if((Seconds <= 0 || m_Super || m_FreezeTime == -1 || m_FreezeTime > Seconds * Server()->TickSpeed()) && Seconds != -1) + return false; + if(m_FreezeTick < Server()->Tick() - Server()->TickSpeed() || Seconds == -1) { m_Armor = 0; m_FreezeTime = Seconds == -1 ? Seconds : Seconds * Server()->TickSpeed(); @@ -2306,9 +2303,9 @@ bool CCharacter::Freeze() bool CCharacter::UnFreeze() { - if (m_FreezeTime > 0) + if(m_FreezeTime > 0) { - m_Armor=10; + m_Armor = 10; if(!m_aWeapons[m_Core.m_ActiveWeapon].m_Got) m_Core.m_ActiveWeapon = WEAPON_GUN; m_FreezeTime = 0; @@ -2321,18 +2318,18 @@ bool CCharacter::UnFreeze() void CCharacter::GiveWeapon(int Weapon, bool Remove) { - if (Weapon == WEAPON_NINJA) + if(Weapon == WEAPON_NINJA) { - if (Remove) + if(Remove) RemoveNinja(); else GiveNinja(); return; } - if (Remove) + if(Remove) { - if (GetActiveWeapon()== Weapon) + if(GetActiveWeapon() == Weapon) SetActiveWeapon(WEAPON_GUN); } else @@ -2345,7 +2342,7 @@ void CCharacter::GiveWeapon(int Weapon, bool Remove) void CCharacter::GiveAllWeapons() { - for(int i=WEAPON_GUN;im_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; GameServer()->m_World.RemoveEntity(this); - if (m_Core.m_HookedPlayer != -1) // Keeping hook would allow cheats + if(m_Core.m_HookedPlayer != -1) // Keeping hook would allow cheats { m_Core.m_HookedPlayer = -1; m_Core.m_HookState = HOOK_RETRACTED; @@ -2368,7 +2365,7 @@ void CCharacter::Pause(bool Pause) } else { - m_Core.m_Vel = vec2(0,0); + m_Core.m_Vel = vec2(0, 0); GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; GameServer()->m_World.InsertEntity(this); } @@ -2385,7 +2382,7 @@ void CCharacter::DDRaceInit() m_Core.m_Id = GetPlayer()->GetCID(); m_TeleCheckpoint = 0; m_EndlessHook = g_Config.m_SvEndlessDrag; - m_Hit = g_Config.m_SvHit ? HIT_ALL : DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_LASER|DISABLE_HIT_SHOTGUN; + m_Hit = g_Config.m_SvHit ? HIT_ALL : DISABLE_HIT_GRENADE | DISABLE_HIT_HAMMER | DISABLE_HIT_LASER | DISABLE_HIT_SHOTGUN; m_SuperJump = false; m_Jetpack = false; m_Core.m_Jumps = 2; @@ -2395,13 +2392,13 @@ void CCharacter::DDRaceInit() if(Teams()->TeamLocked(Team)) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(Teams()->m_Core.Team(i) == Team && i != m_Core.m_Id && GameServer()->m_apPlayers[i]) { - CCharacter* pChar = GameServer()->m_apPlayers[i]->GetCharacter(); + CCharacter *pChar = GameServer()->m_apPlayers[i]->GetCharacter(); - if (pChar) + if(pChar) { m_DDRaceState = pChar->m_DDRaceState; m_StartTime = pChar->m_StartTime; @@ -2412,7 +2409,7 @@ void CCharacter::DDRaceInit() if(g_Config.m_SvTeam == 2 && Team == TEAM_FLOCK) { - GameServer()->SendChatTarget(GetPlayer()->GetCID(),"Please join a team before you start"); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Please join a team before you start"); m_LastStartWarning = Server()->Tick(); } } @@ -2438,7 +2435,7 @@ void CCharacter::Rescue() m_SavedInput.m_Direction = 0; m_SavedInput.m_Jump = 0; // simulate releasing the fire button - if((m_SavedInput.m_Fire&1) != 0) + if((m_SavedInput.m_Fire & 1) != 0) m_SavedInput.m_Fire++; m_SavedInput.m_Fire &= INPUT_STATE_MASK; m_SavedInput.m_Hook = 0; diff --git a/src/game/server/entities/character.h b/src/game/server/entities/character.h index 8a7657a9a..4342108df 100644 --- a/src/game/server/entities/character.h +++ b/src/game/server/entities/character.h @@ -4,10 +4,10 @@ #define GAME_SERVER_ENTITIES_CHARACTER_H #include +#include +#include #include #include -#include -#include #include @@ -87,7 +87,7 @@ public: void Rescue(); - int NeededFaketuning() { return m_NeededFaketuning;} + int NeededFaketuning() { return m_NeededFaketuning; } bool IsAlive() const { return m_Alive; } bool IsPaused() const { return m_Paused; } class CPlayer *GetPlayer() { return m_pPlayer; } @@ -184,7 +184,7 @@ private: bool m_Solo; public: - CGameTeams* Teams(); + CGameTeams *Teams(); void FillAntibot(CAntibotCharacterData *pData); void Pause(bool Pause); bool Freeze(int Time); @@ -208,11 +208,11 @@ public: bool m_FreezeHammer; enum { - HIT_ALL=0, - DISABLE_HIT_HAMMER=1, - DISABLE_HIT_SHOTGUN=2, - DISABLE_HIT_GRENADE=4, - DISABLE_HIT_LASER=8 + HIT_ALL = 0, + DISABLE_HIT_HAMMER = 1, + DISABLE_HIT_SHOTGUN = 2, + DISABLE_HIT_GRENADE = 4, + DISABLE_HIT_LASER = 8 }; int m_Hit; int m_TuneZone; @@ -255,7 +255,7 @@ public: void SetArmor(int Armor) { m_Armor = Armor; }; CCharacterCore GetCore() { return m_Core; }; void SetCore(CCharacterCore Core) { m_Core = Core; }; - CCharacterCore* Core() { return &m_Core; }; + CCharacterCore *Core() { return &m_Core; }; bool GetWeaponGot(int Type) { return m_aWeapons[Type].m_Got; }; void SetWeaponGot(int Type, bool Value) { m_aWeapons[Type].m_Got = Value; }; int GetWeaponAmmo(int Type) { return m_aWeapons[Type].m_Ammo; }; diff --git a/src/game/server/entities/door.cpp b/src/game/server/entities/door.cpp index adf6dc3f6..10eaea737 100644 --- a/src/game/server/entities/door.cpp +++ b/src/game/server/entities/door.cpp @@ -1,14 +1,14 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include #include #include -#include #include #include "door.h" CDoor::CDoor(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, - int Number) : - CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) + int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Number = Number; m_Pos = Pos; @@ -28,80 +28,68 @@ void CDoor::Open(int Tick, bool ActivatedTeam[]) void CDoor::ResetCollision() { - for (int i = 0; i < m_Length - 1; i++) + for(int i = 0; i < m_Length - 1; i++) { vec2 CurrentPos(m_Pos.x + (m_Direction.x * i), - m_Pos.y + (m_Direction.y * i)); - if (GameServer()->Collision()->CheckPoint(CurrentPos) - || GameServer()->Collision()->GetTile(m_Pos.x, m_Pos.y) - || GameServer()->Collision()->GetFTile(m_Pos.x, m_Pos.y)) + m_Pos.y + (m_Direction.y * i)); + if(GameServer()->Collision()->CheckPoint(CurrentPos) || GameServer()->Collision()->GetTile(m_Pos.x, m_Pos.y) || GameServer()->Collision()->GetFTile(m_Pos.x, m_Pos.y)) break; else GameServer()->Collision()->SetDCollisionAt( - m_Pos.x + (m_Direction.x * i), - m_Pos.y + (m_Direction.y * i), TILE_STOPA, 0/*Flags*/, - m_Number); + m_Pos.x + (m_Direction.x * i), + m_Pos.y + (m_Direction.y * i), TILE_STOPA, 0 /*Flags*/, + m_Number); } } void CDoor::Open(int Team) { - } void CDoor::Close(int Team) { - } void CDoor::Reset() { - } void CDoor::Tick() { - } void CDoor::Snap(int SnappingClient) { - if (NetworkClipped(SnappingClient, m_Pos) - && NetworkClipped(SnappingClient, m_To)) + if(NetworkClipped(SnappingClient, m_Pos) && NetworkClipped(SnappingClient, m_To)) return; CNetObj_Laser *pObj = static_cast(Server()->SnapNewItem( - NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); - if (!pObj) + if(!pObj) return; pObj->m_X = (int)m_Pos.x; pObj->m_Y = (int)m_Pos.y; - CCharacter * Char = GameServer()->GetPlayerChar(SnappingClient); + CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 - || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) - && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); - if (Char == 0) + if(Char == 0) return; - if (Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] - && (!Tick)) + if(Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] && (!Tick)) return; - if (Char->Team() == TEAM_SUPER) + if(Char->Team() == TEAM_SUPER) { pObj->m_FromX = (int)m_Pos.x; pObj->m_FromY = (int)m_Pos.y; } - else if (Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 - && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + else if(Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) { pObj->m_FromX = (int)m_To.x; pObj->m_FromY = (int)m_To.y; diff --git a/src/game/server/entities/door.h b/src/game/server/entities/door.h index eda76f0af..b8135c6ef 100644 --- a/src/game/server/entities/door.h +++ b/src/game/server/entities/door.h @@ -6,7 +6,7 @@ class CTrigger; -class CDoor: public CEntity +class CDoor : public CEntity { vec2 m_To; int m_EvalTick; @@ -19,7 +19,7 @@ public: void Open(int Team); void Close(int Team); CDoor(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, - int Number); + int Number); virtual void Reset(); virtual void Tick(); diff --git a/src/game/server/entities/dragger.cpp b/src/game/server/entities/dragger.cpp index 8ce5bead1..4b5c3c8a6 100644 --- a/src/game/server/entities/dragger.cpp +++ b/src/game/server/entities/dragger.cpp @@ -1,16 +1,16 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "dragger.h" #include #include #include #include #include -#include #include -#include "dragger.h" +#include CDragger::CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, - int CaughtTeam, int Layer, int Number) : - CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) + int CaughtTeam, int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Layer = Layer; m_Number = Number; @@ -21,7 +21,7 @@ CDragger::CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, m_CaughtTeam = CaughtTeam; GameWorld()->InsertEntity(this); - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { m_SoloIDs[i] = -1; } @@ -29,52 +29,48 @@ CDragger::CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, void CDragger::Move() { - if (m_Target && (!m_Target->IsAlive() || (m_Target->IsAlive() - && (m_Target->m_Super || m_Target->IsPaused() - || (m_Layer == LAYER_SWITCH && m_Number - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[m_Target->Team()]))))) + if(m_Target && (!m_Target->IsAlive() || (m_Target->IsAlive() && (m_Target->m_Super || m_Target->IsPaused() || (m_Layer == LAYER_SWITCH && m_Number && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[m_Target->Team()]))))) m_Target = 0; mem_zero(m_SoloEnts, sizeof(m_SoloEnts)); CCharacter *TempEnts[MAX_CLIENTS]; int Num = GameServer()->m_World.FindEntities(m_Pos, g_Config.m_SvDraggerRange, - (CEntity**) m_SoloEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + (CEntity **)m_SoloEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); mem_copy(TempEnts, m_SoloEnts, sizeof(TempEnts)); int Id = -1; int MinLen = 0; CCharacter *Temp; - for (int i = 0; i < Num; i++) + for(int i = 0; i < Num; i++) { Temp = m_SoloEnts[i]; - if (Temp->Team() != m_CaughtTeam) + if(Temp->Team() != m_CaughtTeam) { m_SoloEnts[i] = 0; continue; } - if (m_Layer == LAYER_SWITCH && m_Number - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Temp->Team()]) + if(m_Layer == LAYER_SWITCH && m_Number && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Temp->Team()]) { m_SoloEnts[i] = 0; continue; } int Res = - m_NW ? GameServer()->Collision()->IntersectNoLaserNW(m_Pos, - Temp->m_Pos, 0, 0) : - GameServer()->Collision()->IntersectNoLaser(m_Pos, - Temp->m_Pos, 0, 0); + m_NW ? GameServer()->Collision()->IntersectNoLaserNW(m_Pos, + Temp->m_Pos, 0, 0) : + GameServer()->Collision()->IntersectNoLaser(m_Pos, + Temp->m_Pos, 0, 0); - if (Res == 0) + if(Res == 0) { int Len = length(Temp->m_Pos - m_Pos); - if (MinLen == 0 || MinLen > Len) + if(MinLen == 0 || MinLen > Len) { MinLen = Len; Id = i; } - if (!Temp->Teams()->m_Core.GetSolo(Temp->GetPlayer()->GetCID())) + if(!Temp->Teams()->m_Core.GetSolo(Temp->GetPlayer()->GetCID())) m_SoloEnts[i] = 0; } else @@ -83,14 +79,14 @@ void CDragger::Move() } } - if (!m_Target) + if(!m_Target) m_Target = Id != -1 ? TempEnts[Id] : 0; - if (m_Target) + if(m_Target) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { - if (m_SoloEnts[i] == m_Target) + if(m_SoloEnts[i] == m_Target) m_SoloEnts[i] = 0; } } @@ -98,34 +94,34 @@ void CDragger::Move() void CDragger::Drag() { - if (m_Target) + if(m_Target) { CCharacter *Target = m_Target; - for (int i = -1; i < MAX_CLIENTS; i++) + for(int i = -1; i < MAX_CLIENTS; i++) { - if (i >= 0) + if(i >= 0) Target = m_SoloEnts[i]; - if (!Target) + if(!Target) continue; int Res = 0; - if (!m_NW) + if(!m_NW) Res = GameServer()->Collision()->IntersectNoLaser(m_Pos, - Target->m_Pos, 0, 0); + Target->m_Pos, 0, 0); else Res = GameServer()->Collision()->IntersectNoLaserNW(m_Pos, - Target->m_Pos, 0, 0); - if (Res || length(m_Pos - Target->m_Pos) > g_Config.m_SvDraggerRange) + Target->m_Pos, 0, 0); + if(Res || length(m_Pos - Target->m_Pos) > g_Config.m_SvDraggerRange) { Target = 0; - if (i == -1) + if(i == -1) m_Target = 0; else m_SoloEnts[i] = 0; } - else if (length(m_Pos - Target->m_Pos) > 28) + else if(length(m_Pos - Target->m_Pos) > 28) { vec2 Temp = Target->Core()->m_Vel + (normalize(m_Pos - Target->m_Pos) * m_Strength); Target->Core()->m_Vel = ClampVel(Target->m_MoveRestrictions, Temp); @@ -141,16 +137,15 @@ void CDragger::Reset() void CDragger::Tick() { - if (((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.GetTeamState( - m_CaughtTeam) == CGameTeams::TEAMSTATE_EMPTY) + if(((CGameControllerDDRace *)GameServer()->m_pController)->m_Teams.GetTeamState(m_CaughtTeam) == CGameTeams::TEAMSTATE_EMPTY) return; - if (Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) + if(Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) { int Flags; m_EvalTick = Server()->Tick(); int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, - &Flags); - if (index) + &Flags); + if(index) { m_Core = GameServer()->Collision()->CpSpeed(index, Flags); } @@ -159,20 +154,18 @@ void CDragger::Tick() } Drag(); return; - } void CDragger::Snap(int SnappingClient) { - if (((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.GetTeamState( - m_CaughtTeam) == CGameTeams::TEAMSTATE_EMPTY) + if(((CGameControllerDDRace *)GameServer()->m_pController)->m_Teams.GetTeamState(m_CaughtTeam) == CGameTeams::TEAMSTATE_EMPTY) return; CCharacter *Target = m_Target; - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { - if (m_SoloIDs[i] == -1) + if(m_SoloIDs[i] == -1) break; Server()->SnapFreeID(m_SoloIDs[i]); @@ -181,47 +174,41 @@ void CDragger::Snap(int SnappingClient) int pos = 0; - for (int i = -1; i < MAX_CLIENTS; i++) + for(int i = -1; i < MAX_CLIENTS; i++) { - if (i >= 0) + if(i >= 0) { Target = m_SoloEnts[i]; - if (!Target) + if(!Target) continue; } - if (Target) + if(Target) { - if (NetworkClipped(SnappingClient, m_Pos) - && NetworkClipped(SnappingClient, Target->m_Pos)) + if(NetworkClipped(SnappingClient, m_Pos) && NetworkClipped(SnappingClient, Target->m_Pos)) continue; } - else if (NetworkClipped(SnappingClient, m_Pos)) + else if(NetworkClipped(SnappingClient, m_Pos)) continue; - CCharacter * Char = GameServer()->GetPlayerChar(SnappingClient); + CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 - || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) - && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; - if (Char && Char->IsAlive() - && (m_Layer == LAYER_SWITCH && m_Number - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] - && (!Tick))) + if(Char && Char->IsAlive() && (m_Layer == LAYER_SWITCH && m_Number && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] && (!Tick))) continue; - if (Char && Char->IsAlive()) + if(Char && Char->IsAlive()) { - if (Char->Team() != m_CaughtTeam) + if(Char->Team() != m_CaughtTeam) continue; } else { // send to spectators only active draggers and some inactive from team 0 - if (!((Target && Target->IsAlive()) || m_CaughtTeam == 0)) + if(!((Target && Target->IsAlive()) || m_CaughtTeam == 0)) continue; } @@ -232,24 +219,24 @@ void CDragger::Snap(int SnappingClient) CNetObj_Laser *obj; - if (i == -1) + if(i == -1) { obj = static_cast(Server()->SnapNewItem( - NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); } else { m_SoloIDs[pos] = Server()->SnapNewID(); obj = static_cast(Server()->SnapNewItem( // TODO: Have to free IDs again? - NETOBJTYPE_LASER, m_SoloIDs[pos], sizeof(CNetObj_Laser))); + NETOBJTYPE_LASER, m_SoloIDs[pos], sizeof(CNetObj_Laser))); pos++; } - if (!obj) + if(!obj) continue; obj->m_X = (int)m_Pos.x; obj->m_Y = (int)m_Pos.y; - if (Target) + if(Target) { obj->m_FromX = (int)Target->m_Pos.x; obj->m_FromY = (int)Target->m_Pos.y; @@ -261,18 +248,18 @@ void CDragger::Snap(int SnappingClient) } int StartTick = m_EvalTick; - if (StartTick < Server()->Tick() - 4) + if(StartTick < Server()->Tick() - 4) StartTick = Server()->Tick() - 4; - else if (StartTick > Server()->Tick()) + else if(StartTick > Server()->Tick()) StartTick = Server()->Tick(); obj->m_StartTick = StartTick; } } CDraggerTeam::CDraggerTeam(CGameWorld *pGameWorld, vec2 Pos, float Strength, - bool NW, int Layer, int Number) + bool NW, int Layer, int Number) { - for (int i = 0; i < MAX_CLIENTS; ++i) + for(int i = 0; i < MAX_CLIENTS; ++i) { m_Draggers[i] = new CDragger(pGameWorld, Pos, Strength, NW, i, Layer, Number); } diff --git a/src/game/server/entities/dragger.h b/src/game/server/entities/dragger.h index d6c4b61e6..87abd0073 100644 --- a/src/game/server/entities/dragger.h +++ b/src/game/server/entities/dragger.h @@ -5,23 +5,23 @@ #include class CCharacter; -class CDragger: public CEntity +class CDragger : public CEntity { vec2 m_Core; float m_Strength; int m_EvalTick; void Move(); void Drag(); - CCharacter * m_Target; + CCharacter *m_Target; bool m_NW; int m_CaughtTeam; - CCharacter * m_SoloEnts[MAX_CLIENTS]; + CCharacter *m_SoloEnts[MAX_CLIENTS]; int m_SoloIDs[MAX_CLIENTS]; -public: +public: CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, - int CaughtTeam, int Layer = 0, int Number = 0); + int CaughtTeam, int Layer = 0, int Number = 0); virtual void Reset(); virtual void Tick(); @@ -30,12 +30,10 @@ public: class CDraggerTeam { - CDragger * m_Draggers[MAX_CLIENTS]; + CDragger *m_Draggers[MAX_CLIENTS]; public: - - CDraggerTeam(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW = - false, int Layer = 0, int Number = 0); + CDraggerTeam(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW = false, int Layer = 0, int Number = 0); //~CDraggerTeam(); }; diff --git a/src/game/server/entities/flag.cpp b/src/game/server/entities/flag.cpp index dfe593970..947c27c7d 100644 --- a/src/game/server/entities/flag.cpp +++ b/src/game/server/entities/flag.cpp @@ -1,8 +1,8 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ /* -#include #include "flag.h" +#include CFlag::CFlag(CGameWorld *pGameWorld, int Team) : CEntity(pGameWorld, CGameWorld::ENTTYPE_FLAG) diff --git a/src/game/server/entities/gun.cpp b/src/game/server/entities/gun.cpp index ade1c8ea2..9def15802 100644 --- a/src/game/server/entities/gun.cpp +++ b/src/game/server/entities/gun.cpp @@ -11,8 +11,8 @@ ////////////////////////////////////////////////// // CGun ////////////////////////////////////////////////// -CGun::CGun(CGameWorld *pGameWorld, vec2 Pos, bool Freeze, bool Explosive, int Layer, int Number) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +CGun::CGun(CGameWorld *pGameWorld, vec2 Pos, bool Freeze, bool Explosive, int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Layer = Layer; m_Number = Number; @@ -25,22 +25,21 @@ CGun::CGun(CGameWorld *pGameWorld, vec2 Pos, bool Freeze, bool Explosive, int La GameWorld()->InsertEntity(this); } - void CGun::Fire() { CCharacter *Ents[MAX_CLIENTS]; int IdInTeam[MAX_CLIENTS]; int LenInTeam[MAX_CLIENTS]; - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { IdInTeam[i] = -1; LenInTeam[i] = 0; } int Num = -1; - Num = GameServer()->m_World.FindEntities(m_Pos, g_Config.m_SvPlasmaRange, (CEntity**)Ents, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + Num = GameServer()->m_World.FindEntities(m_Pos, g_Config.m_SvPlasmaRange, (CEntity **)Ents, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); - for (int i = 0; i < Num; i++) + for(int i = 0; i < Num; i++) { CCharacter *Target = Ents[i]; //now gun doesn't affect on super @@ -48,18 +47,18 @@ void CGun::Fire() continue; if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Target->Team()]) continue; - int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos,0,0); - if (!res) + int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos, 0, 0); + if(!res) { int Len = length(Target->m_Pos - m_Pos); - if (LenInTeam[Target->Team()] == 0 || LenInTeam[Target->Team()] > Len) + if(LenInTeam[Target->Team()] == 0 || LenInTeam[Target->Team()] > Len) { LenInTeam[Target->Team()] = Len; IdInTeam[Target->Team()] = i; } } } - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(IdInTeam[i] != -1) { @@ -68,15 +67,15 @@ void CGun::Fire() m_LastFire = Server()->Tick(); } } - for (int i = 0; i < Num; i++) + for(int i = 0; i < Num; i++) { CCharacter *Target = Ents[i]; - if (Target->IsAlive() && Target->Teams()->m_Core.GetSolo(Target->GetPlayer()->GetCID())) + if(Target->IsAlive() && Target->Teams()->m_Core.GetSolo(Target->GetPlayer()->GetCID())) { - if (IdInTeam[Target->Team()] != i) + if(IdInTeam[Target->Team()] != i) { - int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos,0,0); - if (!res) + int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos, 0, 0); + if(!res) { new CPlasma(&GameServer()->m_World, m_Pos, normalize(Target->m_Pos - m_Pos), m_Freeze, m_Explosive, Target->Team()); m_LastFire = Server()->Tick(); @@ -84,7 +83,6 @@ void CGun::Fire() } } } - } void CGun::Reset() @@ -94,20 +92,19 @@ void CGun::Reset() void CGun::Tick() { - if (Server()->Tick()%int(Server()->TickSpeed()*0.15f)==0) + if(Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) { int Flags; - m_EvalTick=Server()->Tick(); - int index = GameServer()->Collision()->IsMover(m_Pos.x,m_Pos.y, &Flags); - if (index) + m_EvalTick = Server()->Tick(); + int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, &Flags); + if(index) { - m_Core=GameServer()->Collision()->CpSpeed(index, Flags); + m_Core = GameServer()->Collision()->CpSpeed(index, Flags); } - m_Pos+=m_Core; + m_Pos += m_Core; } - if (m_LastFire + Server()->TickSpeed() / g_Config.m_SvPlasmaPerSec <= Server()->Tick()) + if(m_LastFire + Server()->TickSpeed() / g_Config.m_SvPlasmaPerSec <= Server()->Tick()) Fire(); - } void CGun::Snap(int SnappingClient) @@ -117,16 +114,16 @@ void CGun::Snap(int SnappingClient) CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || - GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && - GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && + GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); - int Tick = (Server()->Tick()%Server()->TickSpeed())%11; - if (Char && Char->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) && (!Tick)) return; + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; + if(Char && Char->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) && (!Tick)) + return; CNetObj_Laser *pObj = static_cast(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); - if (!pObj) + if(!pObj) return; pObj->m_X = (int)m_Pos.x; diff --git a/src/game/server/entities/gun.h b/src/game/server/entities/gun.h index 36cdf6f76..daa816e63 100644 --- a/src/game/server/entities/gun.h +++ b/src/game/server/entities/gun.h @@ -3,8 +3,8 @@ #ifndef GAME_SERVER_ENTITIES_GUN_H #define GAME_SERVER_ENTITIES_GUN_H -#include #include +#include class CCharacter; diff --git a/src/game/server/entities/laser.cpp b/src/game/server/entities/laser.cpp index 37384eaca..c1beaea39 100644 --- a/src/game/server/entities/laser.cpp +++ b/src/game/server/entities/laser.cpp @@ -1,15 +1,15 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "laser.h" #include #include #include -#include "laser.h" #include #include -CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Pos = Pos; m_Owner = Owner; @@ -17,7 +17,7 @@ CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEner m_Dir = Direction; m_Bounces = 0; m_EvalTick = 0; - m_TelePos = vec2(0,0); + m_TelePos = vec2(0, 0); m_WasTele = false; m_Type = Type; m_TeleportCancelled = false; @@ -28,7 +28,6 @@ CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEner DoBounce(); } - bool CLaser::HitCharacter(vec2 From, vec2 To) { vec2 At; @@ -36,22 +35,22 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) CCharacter *pHit; bool pDontHitSelf = g_Config.m_SvOldLaser || (m_Bounces == 0 && !m_WasTele); - if(pOwnerChar ? (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) || (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN) && m_Type == WEAPON_SHOTGUN) : g_Config.m_SvHit) + if(pOwnerChar ? (!(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) || (!(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_SHOTGUN) && m_Type == WEAPON_SHOTGUN) : g_Config.m_SvHit) pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner); else pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner, pOwnerChar); - if(!pHit || (pHit == pOwnerChar && g_Config.m_SvOldLaser) || (pHit != pOwnerChar && pOwnerChar ? (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_LASER && m_Type == WEAPON_LASER) || (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN && m_Type == WEAPON_SHOTGUN) : !g_Config.m_SvHit)) + if(!pHit || (pHit == pOwnerChar && g_Config.m_SvOldLaser) || (pHit != pOwnerChar && pOwnerChar ? (pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_LASER && m_Type == WEAPON_LASER) || (pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_SHOTGUN && m_Type == WEAPON_SHOTGUN) : !g_Config.m_SvHit)) return false; m_From = From; m_Pos = At; m_Energy = -1; - if (m_Type == WEAPON_SHOTGUN) + if(m_Type == WEAPON_SHOTGUN) { vec2 Temp; float Strength; - if (!m_TuneZone) + if(!m_TuneZone) Strength = GameServer()->Tuning()->m_ShotgunStrength; else Strength = GameServer()->TuningList()[m_TuneZone].m_ShotgunStrength; @@ -64,7 +63,7 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) Temp = pHit->Core()->m_Vel; pHit->Core()->m_Vel = ClampVel(pHit->m_MoveRestrictions, Temp); } - else if (m_Type == WEAPON_LASER) + else if(m_Type == WEAPON_LASER) { pHit->UnFreeze(); } @@ -86,11 +85,11 @@ void CLaser::DoBounce() int Res; int z; - if (m_WasTele) + if(m_WasTele) { m_PrevPos = m_TelePos; m_Pos = m_TelePos; - m_TelePos = vec2(0,0); + m_TelePos = vec2(0, 0); } vec2 To = m_Pos + m_Dir * m_Energy; @@ -122,16 +121,16 @@ void CLaser::DoBounce() m_Pos = TempPos; m_Dir = normalize(TempDir); - if (!m_TuneZone) + if(!m_TuneZone) m_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost; else m_Energy -= distance(m_From, m_Pos) + GameServer()->TuningList()[m_TuneZone].m_LaserBounceCost; CGameControllerDDRace *pControllerDDRace = (CGameControllerDDRace *)GameServer()->m_pController; - if(Res == TILE_TELEINWEAPON && pControllerDDRace->m_TeleOuts[z-1].size()) + if(Res == TILE_TELEINWEAPON && pControllerDDRace->m_TeleOuts[z - 1].size()) { - int TeleOut = GameServer()->m_World.m_Core.RandomOr0(pControllerDDRace->m_TeleOuts[z-1].size()); - m_TelePos = pControllerDDRace->m_TeleOuts[z-1][TeleOut]; + int TeleOut = GameServer()->m_World.m_Core.RandomOr0(pControllerDDRace->m_TeleOuts[z - 1].size()); + m_TelePos = pControllerDDRace->m_TeleOuts[z - 1][TeleOut]; m_WasTele = true; } else @@ -141,7 +140,7 @@ void CLaser::DoBounce() } int BounceNum = GameServer()->Tuning()->m_LaserBounceNum; - if (m_TuneZone) + if(m_TuneZone) BounceNum = GameServer()->TuningList()[m_TuneZone].m_LaserBounceNum; if(m_Bounces > BounceNum) @@ -161,7 +160,7 @@ void CLaser::DoBounce() } CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner); - if (m_Owner >= 0 && m_Energy <= 0 && m_Pos && !m_TeleportCancelled && pOwnerChar && + if(m_Owner >= 0 && m_Energy <= 0 && m_Pos && !m_TeleportCancelled && pOwnerChar && pOwnerChar->IsAlive() && pOwnerChar->HasTelegunLaser() && m_Type == WEAPON_LASER) { vec2 PossiblePos; @@ -171,17 +170,17 @@ void CLaser::DoBounce() bool pDontHitSelf = g_Config.m_SvOldLaser || (m_Bounces == 0 && !m_WasTele); vec2 At; CCharacter *pHit; - if (pOwnerChar ? (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) : g_Config.m_SvHit) + if(pOwnerChar ? (!(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_LASER) && m_Type == WEAPON_LASER) : g_Config.m_SvHit) pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner); else pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner, pOwnerChar); - if (pHit) + if(pHit) Found = GetNearestAirPosPlayer(pHit->m_Pos, &PossiblePos); else Found = GetNearestAirPos(m_Pos, m_From, &PossiblePos); - if (Found && PossiblePos) + if(Found && PossiblePos) { pOwnerChar->m_TeleGunPos = PossiblePos; pOwnerChar->m_TeleGunTeleport = true; @@ -198,12 +197,14 @@ void CLaser::DoBounce() if(!IsTeleInWeapon) { - if(IsSwitchTeleGun || IsBlueSwitchTeleGun) { + if(IsSwitchTeleGun || IsBlueSwitchTeleGun) + { // Delay specifies which weapon the tile should work for. // Delay = 0 means all. int delay = GameServer()->Collision()->GetSwitchDelay(MapIndex); - if((delay != 3 && delay != 0) && m_Type == WEAPON_LASER) { + if((delay != 3 && delay != 0) && m_Type == WEAPON_LASER) + { IsSwitchTeleGun = IsBlueSwitchTeleGun = false; } } @@ -213,11 +214,7 @@ void CLaser::DoBounce() // Teleport is canceled if the last bounce tile is not a TILE_ALLOW_TELE_GUN. // Teleport also works if laser didn't bounce. m_TeleportCancelled = - m_Type == WEAPON_LASER - && (TileFIndex != TILE_ALLOW_TELE_GUN - && TileFIndex != TILE_ALLOW_BLUE_TELE_GUN - && !IsSwitchTeleGun - && !IsBlueSwitchTeleGun); + m_Type == WEAPON_LASER && (TileFIndex != TILE_ALLOW_TELE_GUN && TileFIndex != TILE_ALLOW_BLUE_TELE_GUN && !IsSwitchTeleGun && !IsBlueSwitchTeleGun); } } @@ -241,12 +238,12 @@ void CLaser::Tick() } float Delay; - if (m_TuneZone) + if(m_TuneZone) Delay = GameServer()->TuningList()[m_TuneZone].m_LaserBounceDelay; else Delay = GameServer()->Tuning()->m_LaserBounceDelay; - if((Server()->Tick() - m_EvalTick) > (Server()->TickSpeed()*Delay/1000.0f)) + if((Server()->Tick() - m_EvalTick) > (Server()->TickSpeed() * Delay / 1000.0f)) DoBounce(); } @@ -259,7 +256,7 @@ void CLaser::Snap(int SnappingClient) { if(NetworkClipped(SnappingClient)) return; - CCharacter * OwnerChar = 0; + CCharacter *OwnerChar = 0; if(m_Owner >= 0) OwnerChar = GameServer()->GetPlayerChar(m_Owner); if(!OwnerChar) @@ -271,8 +268,8 @@ void CLaser::Snap(int SnappingClient) if(m_Owner >= 0) pOwnerChar = GameServer()->GetPlayerChar(m_Owner); - if (pOwnerChar && pOwnerChar->IsAlive()) - TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + if(pOwnerChar && pOwnerChar->IsAlive()) + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); if(!CmaskIsSet(TeamMask, SnappingClient)) return; diff --git a/src/game/server/entities/light.cpp b/src/game/server/entities/light.cpp index 0139b956d..c9b8b0788 100644 --- a/src/game/server/entities/light.cpp +++ b/src/game/server/entities/light.cpp @@ -1,14 +1,14 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "light.h" #include #include #include -#include -#include "light.h" #include +#include CLight::CLight(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, - int Layer, int Number) : - CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) + int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Layer = Layer; m_Number = Number; @@ -24,15 +24,14 @@ CLight::CLight(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, bool CLight::HitCharacter() { std::list HitCharacters = - GameServer()->m_World.IntersectedCharacters(m_Pos, m_To, 0.0f, 0); - if (HitCharacters.empty()) + GameServer()->m_World.IntersectedCharacters(m_Pos, m_To, 0.0f, 0); + if(HitCharacters.empty()) return false; - for (std::list::iterator i = HitCharacters.begin(); - i != HitCharacters.end(); i++) + for(std::list::iterator i = HitCharacters.begin(); + i != HitCharacters.end(); i++) { - CCharacter * Char = *i; - if (m_Layer == LAYER_SWITCH - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + CCharacter *Char = *i; + if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) continue; Char->Freeze(); } @@ -41,19 +40,18 @@ bool CLight::HitCharacter() void CLight::Move() { - if (m_Speed != 0) + if(m_Speed != 0) { - if ((m_CurveLength >= m_Length && m_Speed > 0) - || (m_CurveLength <= 0 && m_Speed < 0)) + if((m_CurveLength >= m_Length && m_Speed > 0) || (m_CurveLength <= 0 && m_Speed < 0)) m_Speed = -m_Speed; m_CurveLength += m_Speed * m_Tick + m_LengthL; m_LengthL = 0; - if (m_CurveLength > m_Length) + if(m_CurveLength > m_Length) { m_LengthL = m_CurveLength - m_Length; m_CurveLength = m_Length; } - else if (m_CurveLength < 0) + else if(m_CurveLength < 0) { m_LengthL = 0 + m_CurveLength; m_CurveLength = 0; @@ -61,9 +59,9 @@ void CLight::Move() } m_Rotation += m_AngularSpeed * m_Tick; - if (m_Rotation > pi * 2) + if(m_Rotation > pi * 2) m_Rotation -= pi * 2; - else if (m_Rotation < 0) + else if(m_Rotation < 0) m_Rotation += pi * 2; } @@ -82,14 +80,13 @@ void CLight::Reset() void CLight::Tick() { - - if (Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) + if(Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) { int Flags; m_EvalTick = Server()->Tick(); int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, - &Flags); - if (index) + &Flags); + if(index) { m_Core = GameServer()->Collision()->CpSpeed(index, Flags); } @@ -99,51 +96,43 @@ void CLight::Tick() HitCharacter(); return; - } void CLight::Snap(int SnappingClient) { - if (NetworkClipped(SnappingClient, m_Pos) - && NetworkClipped(SnappingClient, m_To)) + if(NetworkClipped(SnappingClient, m_Pos) && NetworkClipped(SnappingClient, m_To)) return; CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 - || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) - && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); int Tick = (Server()->Tick() % Server()->TickSpeed()) % 6; - if (Char && Char->IsAlive() - && m_Layer == LAYER_SWITCH - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] - && (Tick)) + if(Char && Char->IsAlive() && m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] && (Tick)) return; CNetObj_Laser *pObj = static_cast(Server()->SnapNewItem( - NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); - if (!pObj) + if(!pObj) return; pObj->m_X = (int)m_Pos.x; pObj->m_Y = (int)m_Pos.y; - if (Char && Char->Team() == TEAM_SUPER) + if(Char && Char->Team() == TEAM_SUPER) { pObj->m_FromX = (int)m_Pos.x; pObj->m_FromY = (int)m_Pos.y; } - else if (Char && m_Layer == LAYER_SWITCH - && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + else if(Char && m_Layer == LAYER_SWITCH && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) { pObj->m_FromX = (int)m_To.x; pObj->m_FromY = (int)m_To.y; } - else if (m_Layer != LAYER_SWITCH) + else if(m_Layer != LAYER_SWITCH) { pObj->m_FromX = (int)m_To.x; pObj->m_FromY = (int)m_To.y; @@ -155,9 +144,9 @@ void CLight::Snap(int SnappingClient) } int StartTick = m_EvalTick; - if (StartTick < Server()->Tick() - 4) + if(StartTick < Server()->Tick() - 4) StartTick = Server()->Tick() - 4; - else if (StartTick > Server()->Tick()) + else if(StartTick > Server()->Tick()) StartTick = Server()->Tick(); pObj->m_StartTick = StartTick; } diff --git a/src/game/server/entities/light.h b/src/game/server/entities/light.h index 1f2df1df9..d87ffa14f 100644 --- a/src/game/server/entities/light.h +++ b/src/game/server/entities/light.h @@ -2,10 +2,9 @@ #ifndef GAME_SERVER_ENTITIES_LIGHT_H #define GAME_SERVER_ENTITIES_LIGHT_H - #include -class CLight: public CEntity +class CLight : public CEntity { float m_Rotation; vec2 m_To; @@ -18,6 +17,7 @@ class CLight: public CEntity bool HitCharacter(); void Move(); void Step(); + public: int m_CurveLength; int m_LengthL; @@ -26,7 +26,7 @@ public: int m_Length; CLight(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, - int Layer = 0, int Number = 0); + int Layer = 0, int Number = 0); virtual void Reset(); virtual void Tick(); diff --git a/src/game/server/entities/pickup.cpp b/src/game/server/entities/pickup.cpp index 201f37907..c75232169 100644 --- a/src/game/server/entities/pickup.cpp +++ b/src/game/server/entities/pickup.cpp @@ -1,13 +1,13 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "pickup.h" #include #include -#include "pickup.h" #include -CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType, int Layer, int Number) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) +CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType, int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) { m_Type = Type; m_Subtype = SubType; @@ -48,81 +48,84 @@ void CPickup::Tick() }*/ // Check if a player intersected us CCharacter *apEnts[MAX_CLIENTS]; - int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); - for(int i = 0; i < Num; ++i) { - CCharacter * pChr = apEnts[i]; + int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity **)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; ++i) + { + CCharacter *pChr = apEnts[i]; if(pChr && pChr->IsAlive()) { - if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) continue; + if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) + continue; bool Sound = false; // player picked us up, is someone was hooking us, let them go - switch (m_Type) + switch(m_Type) { - case POWERUP_HEALTH: - if(pChr->Freeze()) GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH, pChr->Teams()->TeamMask(pChr->Team())); - break; + case POWERUP_HEALTH: + if(pChr->Freeze()) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH, pChr->Teams()->TeamMask(pChr->Team())); + break; - case POWERUP_ARMOR: - if(pChr->Team() == TEAM_SUPER) continue; - for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++) - { - if(pChr->GetWeaponGot(i)) - { - pChr->SetWeaponGot(i, false); - pChr->SetWeaponAmmo(i, 0); - Sound = true; - } - } - pChr->SetNinjaActivationDir(vec2(0,0)); - pChr->SetNinjaActivationTick(-500); - pChr->SetNinjaCurrentMoveTime(0); - if (Sound) - { - pChr->SetLastWeapon(WEAPON_GUN); - GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR, pChr->Teams()->TeamMask(pChr->Team())); - } - if(pChr->GetActiveWeapon() >= WEAPON_SHOTGUN) - pChr->SetActiveWeapon(WEAPON_HAMMER); - break; - - case POWERUP_WEAPON: - - if (m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || pChr->GetWeaponAmmo(m_Subtype) != -1)) - { - pChr->GiveWeapon(m_Subtype); - - //RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; - - if (m_Subtype == WEAPON_GRENADE) - GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE, pChr->Teams()->TeamMask(pChr->Team())); - else if (m_Subtype == WEAPON_SHOTGUN) - GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); - else if (m_Subtype == WEAPON_LASER) - GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); - - if (pChr->GetPlayer()) - GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), m_Subtype); - - } - break; - - case POWERUP_NINJA: + case POWERUP_ARMOR: + if(pChr->Team() == TEAM_SUPER) + continue; + for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++) { - // activate ninja on target player - pChr->GiveNinja(); + if(pChr->GetWeaponGot(i)) + { + pChr->SetWeaponGot(i, false); + pChr->SetWeaponAmmo(i, 0); + Sound = true; + } + } + pChr->SetNinjaActivationDir(vec2(0, 0)); + pChr->SetNinjaActivationTick(-500); + pChr->SetNinjaCurrentMoveTime(0); + if(Sound) + { + pChr->SetLastWeapon(WEAPON_GUN); + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR, pChr->Teams()->TeamMask(pChr->Team())); + } + if(pChr->GetActiveWeapon() >= WEAPON_SHOTGUN) + pChr->SetActiveWeapon(WEAPON_HAMMER); + break; + + case POWERUP_WEAPON: + + if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || pChr->GetWeaponAmmo(m_Subtype) != -1)) + { + pChr->GiveWeapon(m_Subtype); + //RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; - /*// loop through all players, setting their emotes + if(m_Subtype == WEAPON_GRENADE) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE, pChr->Teams()->TeamMask(pChr->Team())); + else if(m_Subtype == WEAPON_SHOTGUN) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); + else if(m_Subtype == WEAPON_LASER) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); + + if(pChr->GetPlayer()) + GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), m_Subtype); + } + break; + + case POWERUP_NINJA: + { + // activate ninja on target player + pChr->GiveNinja(); + //RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; + + /*// loop through all players, setting their emotes CCharacter *pC = static_cast(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); for(; pC; pC = (CCharacter *)pC->TypeNext()) { if (pC != pChr) pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed()); }*/ - break; - } - default: - break; + break; + } + default: + break; }; /*if(RespawnTime >= 0) @@ -150,19 +153,17 @@ void CPickup::Snap(int SnappingClient) CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); - if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 - || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) - && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 || GameServer()->m_apPlayers[SnappingClient]->IsPaused()) && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); - int Tick = (Server()->Tick()%Server()->TickSpeed())%11; - if (Char && Char->IsAlive() && - (m_Layer == LAYER_SWITCH && - !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) - && (!Tick)) + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; + if(Char && Char->IsAlive() && + (m_Layer == LAYER_SWITCH && + !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) && + (!Tick)) return; - int Size = Server()->IsSixup(SnappingClient) ? 3*4 : sizeof(CNetObj_Pickup); + int Size = Server()->IsSixup(SnappingClient) ? 3 * 4 : sizeof(CNetObj_Pickup); CNetObj_Pickup *pP = static_cast(Server()->SnapNewItem(NETOBJTYPE_PICKUP, m_ID, Size)); if(!pP) return; @@ -183,13 +184,13 @@ void CPickup::Snap(int SnappingClient) void CPickup::Move() { - if (Server()->Tick()%int(Server()->TickSpeed() * 0.15f) == 0) + if(Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) { int Flags; - int index = GameServer()->Collision()->IsMover(m_Pos.x,m_Pos.y, &Flags); - if (index) + int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, &Flags); + if(index) { - m_Core=GameServer()->Collision()->CpSpeed(index, Flags); + m_Core = GameServer()->Collision()->CpSpeed(index, Flags); } m_Pos += m_Core; } diff --git a/src/game/server/entities/pickup.h b/src/game/server/entities/pickup.h index 8e5529f6e..c6d1d8641 100644 --- a/src/game/server/entities/pickup.h +++ b/src/game/server/entities/pickup.h @@ -18,7 +18,6 @@ public: virtual void Snap(int SnappingClient); private: - int m_Type; int m_Subtype; //int m_SpawnTick; diff --git a/src/game/server/entities/plasma.cpp b/src/game/server/entities/plasma.cpp index 3673f5726..6509565c2 100644 --- a/src/game/server/entities/plasma.cpp +++ b/src/game/server/entities/plasma.cpp @@ -1,17 +1,17 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ -#include +#include "plasma.h" #include +#include #include #include -#include #include -#include "plasma.h" +#include const float PLASMA_ACCEL = 1.1f; CPlasma::CPlasma(CGameWorld *pGameWorld, vec2 Pos, vec2 Dir, bool Freeze, - bool Explosive, int ResponsibleTeam) : - CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) + bool Explosive, int ResponsibleTeam) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Pos = Pos; m_Core = Dir; @@ -27,16 +27,16 @@ bool CPlasma::HitCharacter() { vec2 To2; CCharacter *Hit = GameServer()->m_World.IntersectCharacter(m_Pos, - m_Pos + m_Core, 0.0f, To2); - if (!Hit) + m_Pos + m_Core, 0.0f, To2); + if(!Hit) return false; - if (Hit->Team() != m_ResponsibleTeam) + if(Hit->Team() != m_ResponsibleTeam) return false; m_Freeze ? Hit->Freeze() : Hit->UnFreeze(); - if (m_Explosive) + if(m_Explosive) GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true, - m_ResponsibleTeam, Hit->Teams()->TeamMask(m_ResponsibleTeam)); + m_ResponsibleTeam, Hit->Teams()->TeamMask(m_ResponsibleTeam)); GameServer()->m_World.DestroyEntity(this); return true; } @@ -54,7 +54,7 @@ void CPlasma::Reset() void CPlasma::Tick() { - if (m_LifeTime == 0) + if(m_LifeTime == 0) { Reset(); return; @@ -65,35 +65,30 @@ void CPlasma::Tick() int Res = 0; Res = GameServer()->Collision()->IntersectNoLaser(m_Pos, m_Pos + m_Core, 0, - 0); - if (Res) + 0); + if(Res) { - if (m_Explosive) + if(m_Explosive) GameServer()->CreateExplosion( - m_Pos, - -1, - WEAPON_GRENADE, - true, - m_ResponsibleTeam, - ((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.TeamMask( - m_ResponsibleTeam)); + m_Pos, + -1, + WEAPON_GRENADE, + true, + m_ResponsibleTeam, + ((CGameControllerDDRace *)GameServer()->m_pController)->m_Teams.TeamMask(m_ResponsibleTeam)); Reset(); } - } void CPlasma::Snap(int SnappingClient) { - if (NetworkClipped(SnappingClient)) + if(NetworkClipped(SnappingClient)) return; - CCharacter* SnapChar = GameServer()->GetPlayerChar(SnappingClient); - CPlayer* SnapPlayer = SnappingClient > -1 ? GameServer()->m_apPlayers[SnappingClient] : 0; + CCharacter *SnapChar = GameServer()->GetPlayerChar(SnappingClient); + CPlayer *SnapPlayer = SnappingClient > -1 ? GameServer()->m_apPlayers[SnappingClient] : 0; int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; - if (SnapChar && SnapChar->IsAlive() - && (m_Layer == LAYER_SWITCH - && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[SnapChar->Team()]) - && (!Tick)) + if(SnapChar && SnapChar->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[SnapChar->Team()]) && (!Tick)) return; if(SnapPlayer && (SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->IsPaused()) && SnapPlayer->m_SpectatorID != -1 && GameServer()->GetPlayerChar(SnapPlayer->m_SpectatorID) && GameServer()->GetPlayerChar(SnapPlayer->m_SpectatorID)->Team() != m_ResponsibleTeam && SnapPlayer->m_ShowOthers != 1) @@ -102,14 +97,11 @@ void CPlasma::Snap(int SnappingClient) if(SnapPlayer && SnapPlayer->GetTeam() != TEAM_SPECTATORS && !SnapPlayer->IsPaused() && SnapChar && SnapChar && SnapChar->Team() != m_ResponsibleTeam && SnapPlayer->m_ShowOthers != 1) return; - if(SnapPlayer && (SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->IsPaused()) && SnapPlayer->m_SpectatorID == -1 - && SnapChar - && SnapChar->Team() != m_ResponsibleTeam - && SnapPlayer->m_SpecTeam) + if(SnapPlayer && (SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->IsPaused()) && SnapPlayer->m_SpectatorID == -1 && SnapChar && SnapChar->Team() != m_ResponsibleTeam && SnapPlayer->m_SpecTeam) return; CNetObj_Laser *pObj = static_cast(Server()->SnapNewItem( - NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); if(!pObj) return; diff --git a/src/game/server/entities/plasma.h b/src/game/server/entities/plasma.h index 471bc9cb8..156ab2acf 100644 --- a/src/game/server/entities/plasma.h +++ b/src/game/server/entities/plasma.h @@ -6,7 +6,7 @@ class CGun; -class CPlasma: public CEntity +class CPlasma : public CEntity { vec2 m_Core; int m_EvalTick; @@ -18,10 +18,10 @@ class CPlasma: public CEntity bool m_Explosive; bool HitCharacter(); void Move(); -public: +public: CPlasma(CGameWorld *pGameWorld, vec2 Pos, vec2 Dir, bool Freeze, - bool Explosive, int ResponsibleTeam); + bool Explosive, int ResponsibleTeam); virtual void Reset(); virtual void Tick(); diff --git a/src/game/server/entities/projectile.cpp b/src/game/server/entities/projectile.cpp index a74025c59..7032c6f56 100644 --- a/src/game/server/entities/projectile.cpp +++ b/src/game/server/entities/projectile.cpp @@ -1,29 +1,27 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "projectile.h" #include #include #include -#include "projectile.h" #include #include -CProjectile::CProjectile - ( - CGameWorld *pGameWorld, - int Type, - int Owner, - vec2 Pos, - vec2 Dir, - int Span, - bool Freeze, - bool Explosive, - float Force, - int SoundImpact, - int Layer, - int Number - ) -: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) +CProjectile::CProjectile( + CGameWorld *pGameWorld, + int Type, + int Owner, + vec2 Pos, + vec2 Dir, + int Span, + bool Freeze, + bool Explosive, + float Force, + int SoundImpact, + int Layer, + int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) { m_Type = Type; m_Pos = Pos; @@ -58,46 +56,46 @@ vec2 CProjectile::GetPos(float Time) switch(m_Type) { - case WEAPON_GRENADE: - if (!m_TuneZone) - { - Curvature = GameServer()->Tuning()->m_GrenadeCurvature; - Speed = GameServer()->Tuning()->m_GrenadeSpeed; - } - else - { - Curvature = GameServer()->TuningList()[m_TuneZone].m_GrenadeCurvature; - Speed = GameServer()->TuningList()[m_TuneZone].m_GrenadeSpeed; - } + case WEAPON_GRENADE: + if(!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_GrenadeCurvature; + Speed = GameServer()->Tuning()->m_GrenadeSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_GrenadeCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_GrenadeSpeed; + } - break; + break; - case WEAPON_SHOTGUN: - if (!m_TuneZone) - { - Curvature = GameServer()->Tuning()->m_ShotgunCurvature; - Speed = GameServer()->Tuning()->m_ShotgunSpeed; - } - else - { - Curvature = GameServer()->TuningList()[m_TuneZone].m_ShotgunCurvature; - Speed = GameServer()->TuningList()[m_TuneZone].m_ShotgunSpeed; - } + case WEAPON_SHOTGUN: + if(!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_ShotgunCurvature; + Speed = GameServer()->Tuning()->m_ShotgunSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_ShotgunCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_ShotgunSpeed; + } - break; + break; - case WEAPON_GUN: - if (!m_TuneZone) - { - Curvature = GameServer()->Tuning()->m_GunCurvature; - Speed = GameServer()->Tuning()->m_GunSpeed; - } - else - { - Curvature = GameServer()->TuningList()[m_TuneZone].m_GunCurvature; - Speed = GameServer()->TuningList()[m_TuneZone].m_GunSpeed; - } - break; + case WEAPON_GUN: + if(!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_GunCurvature; + Speed = GameServer()->Tuning()->m_GunSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_GunCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_GunSpeed; + } + break; } return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); @@ -105,8 +103,8 @@ vec2 CProjectile::GetPos(float Time) void CProjectile::Tick() { - float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed(); - float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + float Pt = (Server()->Tick() - m_StartTick - 1) / (float)Server()->TickSpeed(); + float Ct = (Server()->Tick() - m_StartTick) / (float)Server()->TickSpeed(); vec2 PrevPos = GetPos(Pt); vec2 CurPos = GetPos(Ct); vec2 ColPos; @@ -119,7 +117,7 @@ void CProjectile::Tick() CCharacter *pTargetChr = 0; - if(pOwnerChar ? !(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit) + if(pOwnerChar ? !(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit) pTargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, ColPos, m_Freeze ? 1.0f : 6.0f, ColPos, pOwnerChar, m_Owner); if(m_LifeSpan > -1) @@ -127,30 +125,28 @@ void CProjectile::Tick() int64 TeamMask = -1LL; bool IsWeaponCollide = false; - if - ( - pOwnerChar && - pTargetChr && - pOwnerChar->IsAlive() && - pTargetChr->IsAlive() && - !pTargetChr->CanCollide(m_Owner) - ) + if( + pOwnerChar && + pTargetChr && + pOwnerChar->IsAlive() && + pTargetChr->IsAlive() && + !pTargetChr->CanCollide(m_Owner)) { - IsWeaponCollide = true; + IsWeaponCollide = true; } - if (pOwnerChar && pOwnerChar->IsAlive()) + if(pOwnerChar && pOwnerChar->IsAlive()) { TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); } - else if (m_Owner >= 0 && (m_Type != WEAPON_GRENADE || g_Config.m_SvDestroyBulletsOnDeath)) + else if(m_Owner >= 0 && (m_Type != WEAPON_GRENADE || g_Config.m_SvDestroyBulletsOnDeath)) { GameServer()->m_World.DestroyEntity(this); return; } - if( ((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !IsWeaponCollide) + if(((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit & CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !IsWeaponCollide) { - if(m_Explosive/*??*/ && (!pTargetChr || (pTargetChr && (!m_Freeze || (m_Type == WEAPON_SHOTGUN && Collide))))) + if(m_Explosive /*??*/ && (!pTargetChr || (pTargetChr && (!m_Freeze || (m_Type == WEAPON_SHOTGUN && Collide))))) { int Number = 1; if(GameServer()->EmulateBug(BUG_GRENADE_DOUBLEEXPLOSION) && m_LifeSpan == -1) @@ -160,21 +156,21 @@ void CProjectile::Tick() for(int i = 0; i < Number; i++) { GameServer()->CreateExplosion(ColPos, m_Owner, m_Type, m_Owner == -1, (!pTargetChr ? -1 : pTargetChr->Team()), - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); GameServer()->CreateSound(ColPos, m_SoundImpact, - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); } } else if(m_Freeze) { CCharacter *apEnts[MAX_CLIENTS]; - int Num = GameWorld()->FindEntities(CurPos, 1.0f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + int Num = GameWorld()->FindEntities(CurPos, 1.0f, (CEntity **)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for(int i = 0; i < Num; ++i) if(apEnts[i] && (m_Layer != LAYER_SWITCH || (m_Layer == LAYER_SWITCH && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[apEnts[i]->Team()]))) apEnts[i]->Freeze(); } - if (pOwnerChar && ColPos && !GameLayerClipped(ColPos) && + if(pOwnerChar && ColPos && !GameLayerClipped(ColPos) && ((m_Type == WEAPON_GRENADE && pOwnerChar->HasTelegunGrenade()) || (m_Type == WEAPON_GUN && pOwnerChar->HasTelegunGun()))) { int MapIndex = GameServer()->Collision()->GetPureMapIndex(pTargetChr ? pTargetChr->m_Pos : ColPos); @@ -182,7 +178,8 @@ void CProjectile::Tick() bool IsSwitchTeleGun = GameServer()->Collision()->IsSwitch(MapIndex) == TILE_ALLOW_TELE_GUN; bool IsBlueSwitchTeleGun = GameServer()->Collision()->IsSwitch(MapIndex) == TILE_ALLOW_BLUE_TELE_GUN; - if(IsSwitchTeleGun || IsBlueSwitchTeleGun) { + if(IsSwitchTeleGun || IsBlueSwitchTeleGun) + { // Delay specifies which weapon the tile should work for. // Delay = 0 means all. int delay = GameServer()->Collision()->GetSwitchDelay(MapIndex); @@ -195,21 +192,17 @@ void CProjectile::Tick() IsSwitchTeleGun = IsBlueSwitchTeleGun = false; } - if (TileFIndex == TILE_ALLOW_TELE_GUN - || TileFIndex == TILE_ALLOW_BLUE_TELE_GUN - || IsSwitchTeleGun - || IsBlueSwitchTeleGun - || pTargetChr) + if(TileFIndex == TILE_ALLOW_TELE_GUN || TileFIndex == TILE_ALLOW_BLUE_TELE_GUN || IsSwitchTeleGun || IsBlueSwitchTeleGun || pTargetChr) { bool Found; vec2 PossiblePos; - if (!Collide) + if(!Collide) Found = GetNearestAirPosPlayer(pTargetChr->m_Pos, &PossiblePos); else Found = GetNearestAirPos(NewPos, CurPos, &PossiblePos); - if (Found && PossiblePos) + if(Found && PossiblePos) { pOwnerChar->m_TeleGunPos = PossiblePos; pOwnerChar->m_TeleGunTeleport = true; @@ -221,26 +214,26 @@ void CProjectile::Tick() if(Collide && m_Bouncing != 0) { m_StartTick = Server()->Tick(); - m_Pos = NewPos+(-(m_Direction*4)); - if (m_Bouncing == 1) + m_Pos = NewPos + (-(m_Direction * 4)); + if(m_Bouncing == 1) m_Direction.x = -m_Direction.x; else if(m_Bouncing == 2) m_Direction.y = -m_Direction.y; - if (fabs(m_Direction.x) < 1e-6) + if(fabs(m_Direction.x) < 1e-6) m_Direction.x = 0; - if (fabs(m_Direction.y) < 1e-6) + if(fabs(m_Direction.y) < 1e-6) m_Direction.y = 0; m_Pos += m_Direction; } - else if (m_Type == WEAPON_GUN) + else if(m_Type == WEAPON_GUN) { - GameServer()->CreateDamageInd(CurPos, -atan2(m_Direction.x, m_Direction.y), 10, (m_Owner != -1)? TeamMask : -1LL); + GameServer()->CreateDamageInd(CurPos, -atan2(m_Direction.x, m_Direction.y), 10, (m_Owner != -1) ? TeamMask : -1LL); GameServer()->m_World.DestroyEntity(this); return; } else { - if (!m_Freeze) + if(!m_Freeze) { GameServer()->m_World.DestroyEntity(this); return; @@ -255,15 +248,15 @@ void CProjectile::Tick() pOwnerChar = GameServer()->GetPlayerChar(m_Owner); int64 TeamMask = -1LL; - if (pOwnerChar && pOwnerChar->IsAlive()) + if(pOwnerChar && pOwnerChar->IsAlive()) { - TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); } GameServer()->CreateExplosion(ColPos, m_Owner, m_Type, m_Owner == -1, (!pOwnerChar ? -1 : pOwnerChar->Team()), - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); GameServer()->CreateSound(ColPos, m_SoundImpact, - (m_Owner != -1)? TeamMask : -1LL); + (m_Owner != -1) ? TeamMask : -1LL); } GameServer()->m_World.DestroyEntity(this); return; @@ -271,15 +264,15 @@ void CProjectile::Tick() int x = GameServer()->Collision()->GetIndex(PrevPos, CurPos); int z; - if (g_Config.m_SvOldTeleportWeapons) + if(g_Config.m_SvOldTeleportWeapons) z = GameServer()->Collision()->IsTeleport(x); else z = GameServer()->Collision()->IsTeleportWeapon(x); CGameControllerDDRace *pControllerDDRace = (CGameControllerDDRace *)GameServer()->m_pController; - if (z && pControllerDDRace->m_TeleOuts[z-1].size()) + if(z && pControllerDDRace->m_TeleOuts[z - 1].size()) { - int TeleOut = GameServer()->m_World.m_Core.RandomOr0(pControllerDDRace->m_TeleOuts[z-1].size()); - m_Pos = pControllerDDRace->m_TeleOuts[z-1][TeleOut]; + int TeleOut = GameServer()->m_World.m_Core.RandomOr0(pControllerDDRace->m_TeleOuts[z - 1].size()); + m_Pos = pControllerDDRace->m_TeleOuts[z - 1][TeleOut]; m_StartTick = Server()->Tick(); } } @@ -293,22 +286,22 @@ void CProjectile::FillInfo(CNetObj_Projectile *pProj) { pProj->m_X = (int)m_Pos.x; pProj->m_Y = (int)m_Pos.y; - pProj->m_VelX = (int)(m_Direction.x*100.0f); - pProj->m_VelY = (int)(m_Direction.y*100.0f); + pProj->m_VelX = (int)(m_Direction.x * 100.0f); + pProj->m_VelY = (int)(m_Direction.y * 100.0f); pProj->m_StartTick = m_StartTick; pProj->m_Type = m_Type; } void CProjectile::Snap(int SnappingClient) { - float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + float Ct = (Server()->Tick() - m_StartTick) / (float)Server()->TickSpeed(); if(NetworkClipped(SnappingClient, GetPos(Ct))) return; - CCharacter* pSnapChar = GameServer()->GetPlayerChar(SnappingClient); - int Tick = (Server()->Tick()%Server()->TickSpeed())%((m_Explosive)?6:20); - if (pSnapChar && pSnapChar->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pSnapChar->Team()] && (!Tick))) + CCharacter *pSnapChar = GameServer()->GetPlayerChar(SnappingClient); + int Tick = (Server()->Tick() % Server()->TickSpeed()) % ((m_Explosive) ? 6 : 20); + if(pSnapChar && pSnapChar->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pSnapChar->Team()] && (!Tick))) return; CCharacter *pOwnerChar = 0; @@ -317,8 +310,8 @@ void CProjectile::Snap(int SnappingClient) if(m_Owner >= 0) pOwnerChar = GameServer()->GetPlayerChar(m_Owner); - if (pOwnerChar && pOwnerChar->IsAlive()) - TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + if(pOwnerChar && pOwnerChar->IsAlive()) + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); if(m_Owner != -1 && !CmaskIsSet(TeamMask, SnappingClient)) return; @@ -342,8 +335,8 @@ void CProjectile::SetBouncing(int Value) void CProjectile::FillExtraInfo(CNetObj_Projectile *pProj) { - const int MaxPos = 0x7fffffff/100; - if(abs((int)m_Pos.y)+1 >= MaxPos || abs((int)m_Pos.x)+1 >= MaxPos) + const int MaxPos = 0x7fffffff / 100; + if(abs((int)m_Pos.y) + 1 >= MaxPos || abs((int)m_Pos.x) + 1 >= MaxPos) { //If the modified data would be too large to fit in an integer, send normal data instead FillInfo(pProj); @@ -353,15 +346,15 @@ void CProjectile::FillExtraInfo(CNetObj_Projectile *pProj) float Angle = -atan2f(m_Direction.x, m_Direction.y); int Data = 0; - Data |= (abs(m_Owner) & 255)<<0; + Data |= (abs(m_Owner) & 255) << 0; if(m_Owner < 0) - Data |= 1<<8; - Data |= 1<<9; //This bit tells the client to use the extra info - Data |= (m_Bouncing & 3)<<10; + Data |= 1 << 8; + Data |= 1 << 9; //This bit tells the client to use the extra info + Data |= (m_Bouncing & 3) << 10; if(m_Explosive) - Data |= 1<<12; + Data |= 1 << 12; if(m_Freeze) - Data |= 1<<13; + Data |= 1 << 13; pProj->m_X = (int)(m_Pos.x * 100.0f); pProj->m_Y = (int)(m_Pos.y * 100.0f); diff --git a/src/game/server/entities/projectile.h b/src/game/server/entities/projectile.h index f1d596339..f84e3549f 100644 --- a/src/game/server/entities/projectile.h +++ b/src/game/server/entities/projectile.h @@ -8,8 +8,7 @@ class CProjectile : public CEntity { public: - CProjectile - ( + CProjectile( CGameWorld *pGameWorld, int Type, int Owner, @@ -21,8 +20,7 @@ public: float Force, int SoundImpact, int Layer = 0, - int Number = 0 - ); + int Number = 0); vec2 GetPos(float Time); void FillInfo(CNetObj_Projectile *pProj); @@ -50,7 +48,6 @@ private: int m_TuneZone; public: - void SetBouncing(int Value); void FillExtraInfo(CNetObj_Projectile *pProj); }; diff --git a/src/game/server/entity.cpp b/src/game/server/entity.cpp index 2a95a742b..ff6ad34df 100644 --- a/src/game/server/entity.cpp +++ b/src/game/server/entity.cpp @@ -12,7 +12,7 @@ CEntity::CEntity(CGameWorld *pGameWorld, int ObjType) m_pGameWorld = pGameWorld; m_ObjType = ObjType; - m_Pos = vec2(0,0); + m_Pos = vec2(0, 0); m_ProximityRadius = 0; m_MarkedForDestroy = false; @@ -38,8 +38,8 @@ int CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos) if(SnappingClient == -1) return 0; - float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x; - float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y; + float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x - CheckPos.x; + float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y - CheckPos.y; if(absolute(dx) > 1000.0f || absolute(dy) > 800.0f) return 1; @@ -51,11 +51,13 @@ int CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos) bool CEntity::GameLayerClipped(vec2 CheckPos) { - return round_to_int(CheckPos.x)/32 < -200 || round_to_int(CheckPos.x)/32 > GameServer()->Collision()->GetWidth()+200 || - round_to_int(CheckPos.y)/32 < -200 || round_to_int(CheckPos.y)/32 > GameServer()->Collision()->GetHeight()+200 ? true : false; + return round_to_int(CheckPos.x) / 32 < -200 || round_to_int(CheckPos.x) / 32 > GameServer()->Collision()->GetWidth() + 200 || + round_to_int(CheckPos.y) / 32 < -200 || round_to_int(CheckPos.y) / 32 > GameServer()->Collision()->GetHeight() + 200 ? + true : + false; } -bool CEntity::GetNearestAirPos(vec2 Pos, vec2 PrevPos, vec2* pOutPos) +bool CEntity::GetNearestAirPos(vec2 Pos, vec2 PrevPos, vec2 *pOutPos) { for(int k = 0; k < 16 && GameServer()->Collision()->CheckPoint(Pos); k++) { @@ -66,27 +68,27 @@ bool CEntity::GetNearestAirPos(vec2 Pos, vec2 PrevPos, vec2* pOutPos) vec2 BlockCenter = vec2(round_to_int(Pos.x), round_to_int(Pos.y)) - PosInBlock + vec2(16.0f, 16.0f); *pOutPos = vec2(BlockCenter.x + (PosInBlock.x < 16 ? -2.0f : 1.0f), Pos.y); - if (!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) + if(!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) return true; *pOutPos = vec2(Pos.x, BlockCenter.y + (PosInBlock.y < 16 ? -2.0f : 1.0f)); - if (!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) + if(!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) return true; *pOutPos = vec2(BlockCenter.x + (PosInBlock.x < 16 ? -2.0f : 1.0f), - BlockCenter.y + (PosInBlock.y < 16 ? -2.0f : 1.0f)); - if (!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) + BlockCenter.y + (PosInBlock.y < 16 ? -2.0f : 1.0f)); + if(!GameServer()->Collision()->TestBox(*pOutPos, vec2(28.0f, 28.0f))) return true; return false; } -bool CEntity::GetNearestAirPosPlayer(vec2 PlayerPos, vec2* OutPos) +bool CEntity::GetNearestAirPosPlayer(vec2 PlayerPos, vec2 *OutPos) { - for (int dist = 5; dist >= -1; dist--) + for(int dist = 5; dist >= -1; dist--) { *OutPos = vec2(PlayerPos.x, PlayerPos.y - dist); - if (!GameServer()->Collision()->TestBox(*OutPos, vec2(28.0f, 28.0f))) + if(!GameServer()->Collision()->TestBox(*OutPos, vec2(28.0f, 28.0f))) { return true; } diff --git a/src/game/server/entity.h b/src/game/server/entity.h index a39e11c01..9725bf610 100644 --- a/src/game/server/entity.h +++ b/src/game/server/entity.h @@ -3,12 +3,12 @@ #ifndef GAME_SERVER_ENTITY_H #define GAME_SERVER_ENTITY_H -#include #include #include +#include #define MACRO_ALLOC_HEAP() \ - public: \ +public: \ void *operator new(size_t Size) \ { \ void *p = malloc(Size); \ @@ -19,14 +19,16 @@ { \ free(pPtr); \ } \ - private: +\ +private: #define MACRO_ALLOC_POOL_ID() \ - public: \ +public: \ void *operator new(size_t Size, int id); \ void operator delete(void *p, int id); \ void operator delete(void *p); \ - private: +\ +private: #define MACRO_ALLOC_POOL_ID_IMPL(POOLTYPE, PoolSize) \ static char ms_PoolData##POOLTYPE[PoolSize][sizeof(POOLTYPE)] = {{0}}; \ @@ -43,14 +45,14 @@ void POOLTYPE::operator delete(void *p, int id) \ { \ dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ - dbg_assert(id == (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE, "invalid id"); \ + dbg_assert(id == (POOLTYPE *)p - (POOLTYPE *)ms_PoolData##POOLTYPE, "invalid id"); \ /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ ms_PoolUsed##POOLTYPE[id] = 0; \ mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ } \ void POOLTYPE::operator delete(void *p) \ { \ - int id = (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE; \ + int id = (POOLTYPE *)p - (POOLTYPE *)ms_PoolData##POOLTYPE; \ dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ ms_PoolUsed##POOLTYPE[id] = 0; \ @@ -65,7 +67,7 @@ class CEntity { MACRO_ALLOC_HEAP() - friend class CGameWorld; // entity list handling + friend class CGameWorld; // entity list handling CEntity *m_pPrevTypeEntity; CEntity *m_pNextTypeEntity; @@ -74,6 +76,7 @@ protected: bool m_MarkedForDestroy; int m_ID; int m_ObjType; + public: CEntity(CGameWorld *pGameWorld, int Objtype); virtual ~CEntity(); @@ -82,7 +85,6 @@ public: class CGameContext *GameServer() { return GameWorld()->GameServer(); } class IServer *Server() { return GameWorld()->Server(); } - CEntity *TypeNext() { return m_pNextTypeEntity; } CEntity *TypePrev() { return m_pPrevTypeEntity; } @@ -163,9 +165,9 @@ public: vec2 m_Pos; // DDRace - - bool GetNearestAirPos(vec2 Pos, vec2 ColPos, vec2* pOutPos); - bool GetNearestAirPosPlayer(vec2 PlayerPos, vec2* OutPos); + + bool GetNearestAirPos(vec2 Pos, vec2 ColPos, vec2 *pOutPos); + bool GetNearestAirPosPlayer(vec2 PlayerPos, vec2 *OutPos); int m_Number; int m_Layer; diff --git a/src/game/server/eventhandler.cpp b/src/game/server/eventhandler.cpp index 0cfd5e4f4..5e68b2591 100644 --- a/src/game/server/eventhandler.cpp +++ b/src/game/server/eventhandler.cpp @@ -21,7 +21,7 @@ void *CEventHandler::Create(int Type, int Size, int64 Mask) { if(m_NumEvents == MAX_EVENTS) return 0; - if(m_CurrentOffset+Size >= MAX_DATASIZE) + if(m_CurrentOffset + Size >= MAX_DATASIZE) return 0; void *p = &m_aData[m_CurrentOffset]; diff --git a/src/game/server/eventhandler.h b/src/game/server/eventhandler.h index ec1382df9..79c96ffca 100644 --- a/src/game/server/eventhandler.h +++ b/src/game/server/eventhandler.h @@ -8,7 +8,7 @@ class CEventHandler { static const int MAX_EVENTS = 128; - static const int MAX_DATASIZE = 128*64; + static const int MAX_DATASIZE = 128 * 64; int m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays int m_aOffsets[MAX_EVENTS]; @@ -20,6 +20,7 @@ class CEventHandler int m_CurrentOffset; int m_NumEvents; + public: CGameContext *GameServer() const { return m_pGameServer; } void SetGameServer(CGameContext *pGameServer); diff --git a/src/game/server/gamecontext.cpp b/src/game/server/gamecontext.cpp index f1648b784..26248d18b 100644 --- a/src/game/server/gamecontext.cpp +++ b/src/game/server/gamecontext.cpp @@ -2,22 +2,22 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -#include -#include +#include "gamecontext.h" +#include "teeinfo.h" #include -#include -#include +#include #include #include +#include #include +#include #include #include #include -#include "teeinfo.h" -#include "gamecontext.h" -#include #include #include +#include +#include #include #include @@ -50,7 +50,7 @@ void CGameContext::Construct(int Resetting) m_SqlRandomMapResult = nullptr; - if(Resetting==NO_RESET) + if(Resetting == NO_RESET) { m_pVoteOptionHeap = new CHeap(); m_pScore = 0; @@ -94,7 +94,7 @@ void CGameContext::Clear() m_Resetting = true; this->~CGameContext(); mem_zero(this, sizeof(*this)); - new (this) CGameContext(RESET); + new(this) CGameContext(RESET); m_pVoteOptionHeap = pVoteOptionHeap; m_pVoteOptionFirst = pVoteOptionFirst; @@ -103,7 +103,6 @@ void CGameContext::Clear() m_Tuning = Tuning; } - void CGameContext::TeeHistorianWrite(const void *pData, int DataSize, void *pUser) { CGameContext *pSelf = (CGameContext *)pUser; @@ -177,17 +176,17 @@ void CGameContext::CreateDamageInd(vec2 Pos, float Angle, int Amount, int64 Mask { float a = 3 * 3.14159f / 2 + Angle; //float a = get_angle(dir); - float s = a-pi/3; - float e = a+pi/3; + float s = a - pi / 3; + float e = a + pi / 3; for(int i = 0; i < Amount; i++) { - float f = mix(s, e, float(i+1)/float(Amount+2)); + float f = mix(s, e, float(i + 1) / float(Amount + 2)); CNetEvent_DamageInd *pEvent = (CNetEvent_DamageInd *)m_Events.Create(NETEVENTTYPE_DAMAGEIND, sizeof(CNetEvent_DamageInd), Mask); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; - pEvent->m_Angle = (int)(f*256.0f); + pEvent->m_Angle = (int)(f * 256.0f); } } } @@ -217,39 +216,43 @@ void CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamag CCharacter *apEnts[MAX_CLIENTS]; float Radius = 135.0f; float InnerRadius = 48.0f; - int Num = m_World.FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + int Num = m_World.FindEntities(Pos, Radius, (CEntity **)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); int64 TeamMask = -1; for(int i = 0; i < Num; i++) { vec2 Diff = apEnts[i]->m_Pos - Pos; - vec2 ForceDir(0,1); + vec2 ForceDir(0, 1); float l = length(Diff); if(l) ForceDir = normalize(Diff); - l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); + l = 1 - clamp((l - InnerRadius) / (Radius - InnerRadius), 0.0f, 1.0f); float Strength; - if (Owner == -1 || !m_apPlayers[Owner] || !m_apPlayers[Owner]->m_TuneZone) + if(Owner == -1 || !m_apPlayers[Owner] || !m_apPlayers[Owner]->m_TuneZone) Strength = Tuning()->m_ExplosionStrength; else Strength = TuningList()[m_apPlayers[Owner]->m_TuneZone].m_ExplosionStrength; float Dmg = Strength * l; - if(!(int)Dmg) continue; + if(!(int)Dmg) + continue; - if((GetPlayerChar(Owner) ? !(GetPlayerChar(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || NoDamage) || Owner == apEnts[i]->GetPlayer()->GetCID()) + if((GetPlayerChar(Owner) ? !(GetPlayerChar(Owner)->m_Hit & CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || NoDamage) || Owner == apEnts[i]->GetPlayer()->GetCID()) { - if(Owner != -1 && apEnts[i]->IsAlive() && !apEnts[i]->CanCollide(Owner)) continue; - if(Owner == -1 && ActivatedTeam != -1 && apEnts[i]->IsAlive() && apEnts[i]->Team() != ActivatedTeam) continue; + if(Owner != -1 && apEnts[i]->IsAlive() && !apEnts[i]->CanCollide(Owner)) + continue; + if(Owner == -1 && ActivatedTeam != -1 && apEnts[i]->IsAlive() && apEnts[i]->Team() != ActivatedTeam) + continue; // Explode at most once per team - int PlayerTeam = ((CGameControllerDDRace*)m_pController)->m_Teams.m_Core.Team(apEnts[i]->GetPlayer()->GetCID()); - if(GetPlayerChar(Owner) ? GetPlayerChar(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE : !g_Config.m_SvHit || NoDamage) + int PlayerTeam = ((CGameControllerDDRace *)m_pController)->m_Teams.m_Core.Team(apEnts[i]->GetPlayer()->GetCID()); + if(GetPlayerChar(Owner) ? GetPlayerChar(Owner)->m_Hit & CCharacter::DISABLE_HIT_GRENADE : !g_Config.m_SvHit || NoDamage) { - if(!CmaskIsSet(TeamMask, PlayerTeam)) continue; + if(!CmaskIsSet(TeamMask, PlayerTeam)) + continue; TeamMask = CmaskUnset(TeamMask, PlayerTeam); } - apEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon); + apEnts[i]->TakeDamage(ForceDir * Dmg * 2, (int)Dmg, Owner, Weapon); } } } @@ -279,7 +282,7 @@ void CGameContext::CreateDeath(vec2 Pos, int ClientID, int64 Mask) void CGameContext::CreateSound(vec2 Pos, int Sound, int64 Mask) { - if (Sound < 0) + if(Sound < 0) return; // create a sound @@ -294,7 +297,7 @@ void CGameContext::CreateSound(vec2 Pos, int Sound, int64 Mask) void CGameContext::CreateSoundGlobal(int Sound, int Target) { - if (Sound < 0) + if(Sound < 0) return; CNetMsg_Sv_SoundGlobal Msg; @@ -341,33 +344,33 @@ void CGameContext::SendChatTarget(int To, const char *pText, int Flags) Msg.m_pMessage = pText; if(g_Config.m_SvDemoChat) - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NOSEND, -1); if(To == -1) { for(int i = 0; i < MAX_CLIENTS; i++) { if(!((Server()->IsSixup(i) && (Flags & CHAT_SIXUP)) || - (!Server()->IsSixup(i) && (Flags & CHAT_SIX)))) + (!Server()->IsSixup(i) && (Flags & CHAT_SIX)))) continue; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); } } else { if(!((Server()->IsSixup(To) && (Flags & CHAT_SIXUP)) || - (!Server()->IsSixup(To) && (Flags & CHAT_SIX)))) + (!Server()->IsSixup(To) && (Flags & CHAT_SIX)))) return; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, To); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, To); } } void CGameContext::SendChatTeam(int Team, const char *pText) { - for(int i = 0; im_Teams.m_Core.Team(i) == Team) + for(int i = 0; i < MAX_CLIENTS; i++) + if(((CGameControllerDDRace *)m_pController)->m_Teams.m_Core.Team(i) == Team) SendChatTarget(i, pText); } @@ -389,7 +392,7 @@ void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText, in } else str_format(aBuf, sizeof(aBuf), "*** %s", aText); - Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, Team!=CHAT_ALL?"teamchat":"chat", aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, Team != CHAT_ALL ? "teamchat" : "chat", aBuf); if(Team == CHAT_ALL) { @@ -400,7 +403,7 @@ void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText, in // pack one for the recording only if(g_Config.m_SvDemoChat) - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NOSEND, -1); // send to the clients for(int i = 0; i < MAX_CLIENTS; i++) @@ -408,15 +411,15 @@ void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText, in if(!m_apPlayers[i]) continue; bool Send = (Server()->IsSixup(i) && (Flags & CHAT_SIXUP)) || - (!Server()->IsSixup(i) && (Flags & CHAT_SIX)); + (!Server()->IsSixup(i) && (Flags & CHAT_SIX)); if(!m_apPlayers[i]->m_DND && Send) - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); } } else { - CTeamsCore * Teams = &((CGameControllerDDRace*)m_pController)->m_Teams.m_Core; + CTeamsCore *Teams = &((CGameControllerDDRace *)m_pController)->m_Teams.m_Core; CNetMsg_Sv_Chat Msg; Msg.m_Team = 1; Msg.m_ClientID = ChatterClientID; @@ -424,19 +427,25 @@ void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText, in // pack one for the recording only if(g_Config.m_SvDemoChat) - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NOSEND, -1); // send to the clients for(int i = 0; i < MAX_CLIENTS; i++) { - if(m_apPlayers[i] != 0) { - if(Team == CHAT_SPEC) { - if(m_apPlayers[i]->GetTeam() == CHAT_SPEC) { - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + if(m_apPlayers[i] != 0) + { + if(Team == CHAT_SPEC) + { + if(m_apPlayers[i]->GetTeam() == CHAT_SPEC) + { + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); } - } else { - if(Teams->Team(i) == Team && m_apPlayers[i]->GetTeam() != CHAT_SPEC) { - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + else + { + if(Teams->Team(i) == Team && m_apPlayers[i]->GetTeam() != CHAT_SPEC) + { + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); } } } @@ -459,7 +468,6 @@ void CGameContext::SendWeaponPickup(int ClientID, int Weapon) Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } - void CGameContext::SendBroadcast(const char *pText, int ClientID, bool IsImportant) { CNetMsg_Sv_Broadcast Msg; @@ -516,7 +524,6 @@ void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char m_VoteUpdate = true; } - void CGameContext::EndVote() { m_VoteCloseTime = 0; @@ -531,7 +538,7 @@ void CGameContext::SendVoteSet(int ClientID) Msg7.m_ClientID = m_VoteCreator; if(m_VoteCloseTime) { - Msg6.m_Timeout = Msg7.m_Timeout = (m_VoteCloseTime-time_get())/time_freq(); + Msg6.m_Timeout = Msg7.m_Timeout = (m_VoteCloseTime - time_get()) / time_freq(); Msg6.m_pDescription = m_aVoteDescription; Msg7.m_pDescription = m_aSixupVoteDescription; Msg6.m_pReason = Msg7.m_pReason = m_aVoteReason; @@ -585,7 +592,7 @@ void CGameContext::SendVoteSet(int ClientID) void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) { - if (Total > VANILLA_MAX_CLIENTS && m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetClientVersion() <= VERSION_DDRACE) + if(Total > VANILLA_MAX_CLIENTS && m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetClientVersion() <= VERSION_DDRACE) { Yes = float(Yes) * VANILLA_MAX_CLIENTS / float(Total); No = float(No) * VANILLA_MAX_CLIENTS / float(Total); @@ -596,29 +603,27 @@ void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) Msg.m_Total = Total; Msg.m_Yes = Yes; Msg.m_No = No; - Msg.m_Pass = Total - (Yes+No); + Msg.m_Pass = Total - (Yes + No); Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); - } void CGameContext::AbortVoteKickOnDisconnect(int ClientID) { if(m_VoteCloseTime && ((str_startswith(m_aVoteCommand, "kick ") && str_toint(&m_aVoteCommand[5]) == ClientID) || - (str_startswith(m_aVoteCommand, "set_team ") && str_toint(&m_aVoteCommand[9]) == ClientID))) + (str_startswith(m_aVoteCommand, "set_team ") && str_toint(&m_aVoteCommand[9]) == ClientID))) m_VoteEnforce = VOTE_ENFORCE_ABORT; } - void CGameContext::CheckPureTuning() { // might not be created yet during start up if(!m_pController) return; - if( str_comp(m_pController->m_pGameType, "DM")==0 || - str_comp(m_pController->m_pGameType, "TDM")==0 || - str_comp(m_pController->m_pGameType, "CTF")==0) + if(str_comp(m_pController->m_pGameType, "DM") == 0 || + str_comp(m_pController->m_pGameType, "TDM") == 0 || + str_comp(m_pController->m_pGameType, "CTF") == 0) { CTuningParams p; if(mem_comp(&p, &m_Tuning, sizeof(p)) != 0) @@ -631,18 +636,18 @@ void CGameContext::CheckPureTuning() void CGameContext::SendTuningParams(int ClientID, int Zone) { - if (ClientID == -1) + if(ClientID == -1) { for(int i = 0; i < MAX_CLIENTS; ++i) { - if (m_apPlayers[i]) + if(m_apPlayers[i]) { if(m_apPlayers[i]->GetCharacter()) { - if (m_apPlayers[i]->GetCharacter()->m_TuneZone == Zone) + if(m_apPlayers[i]->GetCharacter()->m_TuneZone == Zone) SendTuningParams(i, Zone); } - else if (m_apPlayers[i]->m_TuneZone == Zone) + else if(m_apPlayers[i]->m_TuneZone == Zone) { SendTuningParams(i, Zone); } @@ -655,12 +660,12 @@ void CGameContext::SendTuningParams(int ClientID, int Zone) CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = 0; - if (Zone == 0) + if(Zone == 0) pParams = (int *)&m_Tuning; else pParams = (int *)&(m_aTuningList[Zone]); - unsigned int Last = sizeof(m_Tuning)/sizeof(int); + unsigned int Last = sizeof(m_Tuning) / sizeof(int); if(m_apPlayers[ClientID]) { int ClientVersion = m_apPlayers[ClientID]->GetClientVersion(); @@ -674,7 +679,7 @@ void CGameContext::SendTuningParams(int ClientID, int Zone) for(unsigned i = 0; i < Last; i++) { - if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetCharacter()) + if(m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetCharacter()) { if((i == 30) // laser_damage is removed from 0.7 && (Server()->IsSixup(ClientID))) @@ -686,24 +691,23 @@ void CGameContext::SendTuningParams(int ClientID, int Zone) { Msg.AddInt(0); } - else if((i==32) // hooking - && (m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_SOLO - || m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHOOK)) + else if((i == 32) // hooking + && (m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_SOLO || m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHOOK)) { Msg.AddInt(0); } - else if((i==3) // ground jump impulse - && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOJUMP) + else if((i == 3) // ground jump impulse + && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOJUMP) { Msg.AddInt(0); } - else if((i==33) // jetpack - && !(m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_JETPACK)) + else if((i == 33) // jetpack + && !(m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_JETPACK)) { Msg.AddInt(0); } - else if((i==36) // hammer hit - && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHAMMER) + else if((i == 36) // hammer hit + && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHAMMER) { Msg.AddInt(0); } @@ -823,8 +827,8 @@ void CGameContext::OnTick() continue; if((IsKickVote() || IsSpecVote()) && (m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || - (GetPlayerChar(m_VoteCreator) && GetPlayerChar(i) && - GetPlayerChar(m_VoteCreator)->Team() != GetPlayerChar(i)->Team()))) + (GetPlayerChar(m_VoteCreator) && GetPlayerChar(i) && + GetPlayerChar(m_VoteCreator)->Team() != GetPlayerChar(i)->Team()))) continue; if(m_apPlayers[i]->m_Afk && i != m_VoteCreator) @@ -835,7 +839,7 @@ void CGameContext::OnTick() continue; // connecting clients with spoofed ips can clog slots without being ingame - if(((CServer*)Server())->m_aClients[i].m_State != CServer::CClient::STATE_INGAME) + if(((CServer *)Server())->m_aClients[i].m_State != CServer::CClient::STATE_INGAME) continue; // don't count votes by blacklisted clients @@ -846,7 +850,7 @@ void CGameContext::OnTick() int ActVotePos = m_apPlayers[i]->m_VotePos; // check for more players with the same ip (only use the vote of the one who voted first) - for(int j = i+1; j < MAX_CLIENTS; ++j) + for(int j = i + 1; j < MAX_CLIENTS; ++j) { if(!m_apPlayers[j] || aVoteChecked[j] || str_comp(aaBuf[j], aaBuf[i])) continue; @@ -870,8 +874,8 @@ void CGameContext::OnTick() !m_apPlayers[i]->m_Afk && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && g_Config.m_SvVoteVetoTime && ((Server()->Tick() - m_apPlayers[i]->m_JoinTick) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime || - (m_apPlayers[i]->GetCharacter() && m_apPlayers[i]->GetCharacter()->m_DDRaceState == DDRACE_STARTED && - (Server()->Tick() - m_apPlayers[i]->GetCharacter()->m_StartTime) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime))) + (m_apPlayers[i]->GetCharacter() && m_apPlayers[i]->GetCharacter()->m_DDRaceState == DDRACE_STARTED && + (Server()->Tick() - m_apPlayers[i]->GetCharacter()->m_StartTime) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime))) { if(ActVote == 0) Veto = true; @@ -881,7 +885,7 @@ void CGameContext::OnTick() } if(g_Config.m_SvVoteMaxTotal && Total > g_Config.m_SvVoteMaxTotal && - (IsKickVote() || IsSpecVote())) + (IsKickVote() || IsSpecVote())) Total = g_Config.m_SvVoteMaxTotal; if((Yes > Total / (100.0f / g_Config.m_SvVoteYesPercentage)) && !Veto) @@ -900,7 +904,7 @@ void CGameContext::OnTick() // / Ensure minimum time for vote to end when moderating. if(m_VoteEnforce == VOTE_ENFORCE_YES && !(PlayerModerating() && - (IsKickVote() || IsSpecVote()) && time_get() < m_VoteCloseTime)) + (IsKickVote() || IsSpecVote()) && time_get() < m_VoteCloseTime)) { Server()->SetRconCID(IServer::RCON_CID_VOTE); Console()->ExecuteLine(m_aVoteCommand); @@ -914,7 +918,7 @@ void CGameContext::OnTick() else if(m_VoteEnforce == VOTE_ENFORCE_YES_ADMIN) { char aBuf[64]; - str_format(aBuf, sizeof(aBuf),"Vote passed enforced by authorized player"); + str_format(aBuf, sizeof(aBuf), "Vote passed enforced by authorized player"); Console()->ExecuteLine(m_aVoteCommand, m_VoteEnforcer); SendChat(-1, CGameContext::CHAT_ALL, aBuf, -1, CHAT_SIX); EndVote(); @@ -922,7 +926,7 @@ void CGameContext::OnTick() else if(m_VoteEnforce == VOTE_ENFORCE_NO_ADMIN) { char aBuf[64]; - str_format(aBuf, sizeof(aBuf),"Vote failed enforced by authorized player"); + str_format(aBuf, sizeof(aBuf), "Vote failed enforced by authorized player"); EndVote(); SendChat(-1, CGameContext::CHAT_ALL, aBuf, -1, CHAT_SIX); } @@ -970,9 +974,9 @@ void CGameContext::OnTick() if(Collision()->m_NumSwitchers > 0) { - for (int i = 0; i < Collision()->m_NumSwitchers+1; ++i) + for(int i = 0; i < Collision()->m_NumSwitchers + 1; ++i) { - for (int j = 0; j < MAX_CLIENTS; ++j) + for(int j = 0; j < MAX_CLIENTS; ++j) { if(Collision()->m_pSwitchers[i].m_EndTick[j] <= Server()->Tick() && Collision()->m_pSwitchers[i].m_Type[j] == TILE_SWITCHTIMEDOPEN) { @@ -1007,11 +1011,11 @@ void CGameContext::OnTick() #ifdef CONF_DEBUG if(g_Config.m_DbgDummies) { - for(int i = 0; i < g_Config.m_DbgDummies ; i++) + for(int i = 0; i < g_Config.m_DbgDummies; i++) { CNetObj_PlayerInput Input = {0}; - Input.m_Direction = (i&1)?-1:1; - m_apPlayers[MAX_CLIENTS-i-1]->OnPredictedInput(&Input); + Input.m_Direction = (i & 1) ? -1 : 1; + m_apPlayers[MAX_CLIENTS - i - 1]->OnPredictedInput(&Input); } } #endif @@ -1050,11 +1054,12 @@ void CGameContext::OnClientPredictedEarlyInput(int ClientID, void *pInput) struct CVoteOptionServer *CGameContext::GetVoteOption(int Index) { CVoteOptionServer *pCurrent; - for (pCurrent = m_pVoteOptionFirst; - Index > 0 && pCurrent; - Index--, pCurrent = pCurrent->m_pNext); + for(pCurrent = m_pVoteOptionFirst; + Index > 0 && pCurrent; + Index--, pCurrent = pCurrent->m_pNext) + ; - if (Index > 0) + if(Index > 0) return 0; return pCurrent; } @@ -1063,16 +1068,16 @@ void CGameContext::ProgressVoteOptions(int ClientID) { CPlayer *pPl = m_apPlayers[ClientID]; - if (pPl->m_SendVoteIndex == -1) + if(pPl->m_SendVoteIndex == -1) return; // we didn't start sending options yet - if (pPl->m_SendVoteIndex > m_NumVoteOptions) + if(pPl->m_SendVoteIndex > m_NumVoteOptions) return; // shouldn't happen / fail silently int VotesLeft = m_NumVoteOptions - pPl->m_SendVoteIndex; int NumVotesToSend = minimum(g_Config.m_SvSendVotesPerTick, VotesLeft); - if (!VotesLeft) + if(!VotesLeft) { // player has up to date vote option list return; @@ -1105,21 +1110,21 @@ void CGameContext::ProgressVoteOptions(int ClientID) { switch(CurIndex) { - case 0: OptionMsg.m_pDescription0 = pCurrent->m_aDescription; break; - case 1: OptionMsg.m_pDescription1 = pCurrent->m_aDescription; break; - case 2: OptionMsg.m_pDescription2 = pCurrent->m_aDescription; break; - case 3: OptionMsg.m_pDescription3 = pCurrent->m_aDescription; break; - case 4: OptionMsg.m_pDescription4 = pCurrent->m_aDescription; break; - case 5: OptionMsg.m_pDescription5 = pCurrent->m_aDescription; break; - case 6: OptionMsg.m_pDescription6 = pCurrent->m_aDescription; break; - case 7: OptionMsg.m_pDescription7 = pCurrent->m_aDescription; break; - case 8: OptionMsg.m_pDescription8 = pCurrent->m_aDescription; break; - case 9: OptionMsg.m_pDescription9 = pCurrent->m_aDescription; break; - case 10: OptionMsg.m_pDescription10 = pCurrent->m_aDescription; break; - case 11: OptionMsg.m_pDescription11 = pCurrent->m_aDescription; break; - case 12: OptionMsg.m_pDescription12 = pCurrent->m_aDescription; break; - case 13: OptionMsg.m_pDescription13 = pCurrent->m_aDescription; break; - case 14: OptionMsg.m_pDescription14 = pCurrent->m_aDescription; break; + case 0: OptionMsg.m_pDescription0 = pCurrent->m_aDescription; break; + case 1: OptionMsg.m_pDescription1 = pCurrent->m_aDescription; break; + case 2: OptionMsg.m_pDescription2 = pCurrent->m_aDescription; break; + case 3: OptionMsg.m_pDescription3 = pCurrent->m_aDescription; break; + case 4: OptionMsg.m_pDescription4 = pCurrent->m_aDescription; break; + case 5: OptionMsg.m_pDescription5 = pCurrent->m_aDescription; break; + case 6: OptionMsg.m_pDescription6 = pCurrent->m_aDescription; break; + case 7: OptionMsg.m_pDescription7 = pCurrent->m_aDescription; break; + case 8: OptionMsg.m_pDescription8 = pCurrent->m_aDescription; break; + case 9: OptionMsg.m_pDescription9 = pCurrent->m_aDescription; break; + case 10: OptionMsg.m_pDescription10 = pCurrent->m_aDescription; break; + case 11: OptionMsg.m_pDescription11 = pCurrent->m_aDescription; break; + case 12: OptionMsg.m_pDescription12 = pCurrent->m_aDescription; break; + case 13: OptionMsg.m_pDescription13 = pCurrent->m_aDescription; break; + case 14: OptionMsg.m_pDescription14 = pCurrent->m_aDescription; break; } CurIndex++; @@ -1154,14 +1159,14 @@ void CGameContext::OnClientEnter(int ClientID) Msg.m_MatchNum = 0; Msg.m_ScoreLimit = 0; Msg.m_TimeLimit = 0; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } // /team is essential { protocol7::CNetMsg_Sv_CommandInfoRemove Msg; Msg.m_Name = "team"; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } for(const IConsole::CCommandInfo *pCmd = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_USER, CFGFLAG_CHAT); @@ -1178,7 +1183,7 @@ void CGameContext::OnClientEnter(int ClientID) Msg.m_Name = pName; Msg.m_ArgsFormat = pCmd->m_pParams; Msg.m_HelpText = pCmd->m_pHelp; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } } @@ -1197,7 +1202,7 @@ void CGameContext::OnClientEnter(int ClientID) Msg.m_ClientID = Empty; Msg.m_pMessage = "Do you know someone who uses a bot? Please report them to the moderators."; m_apPlayers[ClientID]->m_EligibleForFinishCheck = time_get(); - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } if(!Server()->ClientPrevIngame(ClientID)) @@ -1216,15 +1221,15 @@ void CGameContext::OnClientEnter(int ClientID) SendChatTarget(ClientID, "DDraceNetwork Mod. Version: " GAME_VERSION); SendChatTarget(ClientID, "please visit DDNet.tw or say /info and make sure to read our /rules"); - if(g_Config.m_SvWelcome[0]!=0) - SendChatTarget(ClientID,g_Config.m_SvWelcome); + if(g_Config.m_SvWelcome[0] != 0) + SendChatTarget(ClientID, g_Config.m_SvWelcome); str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' team=%d", ClientID, Server()->ClientName(ClientID), m_apPlayers[ClientID]->GetTeam()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); if(g_Config.m_SvShowOthersDefault > 0) { - if (g_Config.m_SvShowOthers) + if(g_Config.m_SvShowOthers) SendChatTarget(ClientID, "You can see other players. To disable this use DDNet client and type /showothers ."); m_apPlayers[ClientID]->m_ShowOthers = g_Config.m_SvShowOthersDefault; @@ -1266,7 +1271,7 @@ void CGameContext::OnClientEnter(int ClientID) CPlayer *pPlayer = m_apPlayers[i]; if(Server()->IsSixup(i)) - Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); if(Server()->IsSixup(ClientID)) { @@ -1287,7 +1292,7 @@ void CGameContext::OnClientEnter(int ClientID) ClientInfoMsg.m_aSkinPartColors[p] = pPlayer->m_TeeInfos.m_aSkinPartColors[p]; } - Server()->SendPackMsg(&ClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&ClientInfoMsg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } } @@ -1295,7 +1300,7 @@ void CGameContext::OnClientEnter(int ClientID) if(Server()->IsSixup(ClientID)) { NewClientInfoMsg.m_Local = 1; - Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } } @@ -1320,15 +1325,15 @@ void CGameContext::OnClientConnected(int ClientID) // Check which team the player should be on const int StartTeam = g_Config.m_SvTournamentMode ? TEAM_SPECTATORS : m_pController->GetAutoTeam(ClientID); - if (!m_apPlayers[ClientID]) + if(!m_apPlayers[ClientID]) m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, StartTeam); else { delete m_apPlayers[ClientID]; m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, StartTeam); - // //m_apPlayers[ClientID]->Reset(); - // //((CServer*)Server())->m_aClients[ClientID].Reset(); - // ((CServer*)Server())->m_aClients[ClientID].m_State = 4; + // //m_apPlayers[ClientID]->Reset(); + // //((CServer*)Server())->m_aClients[ClientID].Reset(); + // ((CServer*)Server())->m_aClients[ClientID].m_State = 4; } //players[client_id].init(client_id); //players[client_id].client_id = client_id; @@ -1336,7 +1341,7 @@ void CGameContext::OnClientConnected(int ClientID) #ifdef CONF_DEBUG if(g_Config.m_DbgDummies) { - if(ClientID >= MAX_CLIENTS-g_Config.m_DbgDummies) + if(ClientID >= MAX_CLIENTS - g_Config.m_DbgDummies) return; } #endif @@ -1356,7 +1361,7 @@ void CGameContext::OnClientConnected(int ClientID) Msg.m_TeamLock = 0; Msg.m_TeamBalance = 0; Msg.m_PlayerSlots = g_Config.m_SvMaxClients - g_Config.m_SvSpectatorSlots; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } Server()->ExpireServerInfo(); @@ -1390,7 +1395,7 @@ void CGameContext::OnClientDrop(int ClientID, const char *pReason) Msg.m_ClientID = ClientID; Msg.m_pReason = pReason; Msg.m_Silent = false; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, -1); Server()->ExpireServerInfo(); } @@ -1512,7 +1517,7 @@ void *CGameContext::PreProcessMsg(int *MsgID, CUnpacker *pUnpacker, int ClientID protocol7::CNetMsg_Cl_SkinChange *pMsg = (protocol7::CNetMsg_Cl_SkinChange *)pRawMsg; if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo + Server()->TickSpeed() * g_Config.m_SvInfoChangeDelay > Server()->Tick()) - return 0; + return 0; pPlayer->m_LastChangeInfo = Server()->Tick(); @@ -1529,7 +1534,7 @@ void *CGameContext::PreProcessMsg(int *MsgID, CUnpacker *pUnpacker, int ClientID Msg.m_aUseCustomColors[p] = pMsg->m_aUseCustomColors[p]; } - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, -1); return 0; } @@ -1686,36 +1691,36 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) *(const_cast(pEnd)) = 0; // drop empty and autocreated spam messages (more than 32 characters per second) - if(Length == 0 || (pMsg->m_pMessage[0]!='/' && (g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat+Server()->TickSpeed()*((31+Length)/32) > Server()->Tick()))) + if(Length == 0 || (pMsg->m_pMessage[0] != '/' && (g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat + Server()->TickSpeed() * ((31 + Length) / 32) > Server()->Tick()))) return; - int GameTeam = ((CGameControllerDDRace*)m_pController)->m_Teams.m_Core.Team(pPlayer->GetCID()); + int GameTeam = ((CGameControllerDDRace *)m_pController)->m_Teams.m_Core.Team(pPlayer->GetCID()); if(Team) Team = ((pPlayer->GetTeam() == -1) ? CHAT_SPEC : GameTeam); else Team = CHAT_ALL; - if(pMsg->m_pMessage[0]=='/') + if(pMsg->m_pMessage[0] == '/') { - if (str_comp_nocase_num(pMsg->m_pMessage+1, "w ", 2) == 0) + if(str_comp_nocase_num(pMsg->m_pMessage + 1, "w ", 2) == 0) { char aWhisperMsg[256]; str_copy(aWhisperMsg, pMsg->m_pMessage + 3, 256); Whisper(pPlayer->GetCID(), aWhisperMsg); } - else if (str_comp_nocase_num(pMsg->m_pMessage+1, "whisper ", 8) == 0) + else if(str_comp_nocase_num(pMsg->m_pMessage + 1, "whisper ", 8) == 0) { char aWhisperMsg[256]; str_copy(aWhisperMsg, pMsg->m_pMessage + 9, 256); Whisper(pPlayer->GetCID(), aWhisperMsg); } - else if (str_comp_nocase_num(pMsg->m_pMessage+1, "c ", 2) == 0) + else if(str_comp_nocase_num(pMsg->m_pMessage + 1, "c ", 2) == 0) { char aWhisperMsg[256]; str_copy(aWhisperMsg, pMsg->m_pMessage + 3, 256); Converse(pPlayer->GetCID(), aWhisperMsg); } - else if (str_comp_nocase_num(pMsg->m_pMessage+1, "converse ", 9) == 0) + else if(str_comp_nocase_num(pMsg->m_pMessage + 1, "converse ", 9) == 0) { char aWhisperMsg[256]; str_copy(aWhisperMsg, pMsg->m_pMessage + 10, 256); @@ -1723,12 +1728,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) } else { - if(g_Config.m_SvSpamprotection && !str_startswith(pMsg->m_pMessage+1, "timeout ") - && pPlayer->m_LastCommands[0] && pPlayer->m_LastCommands[0]+Server()->TickSpeed() > Server()->Tick() - && pPlayer->m_LastCommands[1] && pPlayer->m_LastCommands[1]+Server()->TickSpeed() > Server()->Tick() - && pPlayer->m_LastCommands[2] && pPlayer->m_LastCommands[2]+Server()->TickSpeed() > Server()->Tick() - && pPlayer->m_LastCommands[3] && pPlayer->m_LastCommands[3]+Server()->TickSpeed() > Server()->Tick() - ) + if(g_Config.m_SvSpamprotection && !str_startswith(pMsg->m_pMessage + 1, "timeout ") && pPlayer->m_LastCommands[0] && pPlayer->m_LastCommands[0] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_LastCommands[1] && pPlayer->m_LastCommands[1] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_LastCommands[2] && pPlayer->m_LastCommands[2] + Server()->TickSpeed() > Server()->Tick() && pPlayer->m_LastCommands[3] && pPlayer->m_LastCommands[3] + Server()->TickSpeed() > Server()->Tick()) return; int64 Now = Server()->Tick(); @@ -1778,9 +1778,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) char aCmd[VOTE_CMD_LENGTH] = {0}; char aReason[VOTE_REASON_LENGTH] = "No reason given"; CNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)pRawMsg; - if(!str_utf8_check(pMsg->m_Type) - || !str_utf8_check(pMsg->m_Reason) - || !str_utf8_check(pMsg->m_Value)) + if(!str_utf8_check(pMsg->m_Type) || !str_utf8_check(pMsg->m_Reason) || !str_utf8_check(pMsg->m_Value)) { return; } @@ -1802,17 +1800,13 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "Invalid option"); return; } - if((str_startswith(pOption->m_aCommand, "sv_map ") - || str_startswith(pOption->m_aCommand, "change_map ") - || str_startswith(pOption->m_aCommand, "random_map") - || str_startswith(pOption->m_aCommand, "random_unfinished_map")) - && RateLimitPlayerMapVote(ClientID)) + if((str_startswith(pOption->m_aCommand, "sv_map ") || str_startswith(pOption->m_aCommand, "change_map ") || str_startswith(pOption->m_aCommand, "random_map") || str_startswith(pOption->m_aCommand, "random_unfinished_map")) && RateLimitPlayerMapVote(ClientID)) { return; } str_format(aChatmsg, sizeof(aChatmsg), "'%s' called vote to change server option '%s' (%s)", Server()->ClientName(ClientID), - pOption->m_aDescription, aReason); + pOption->m_aDescription, aReason); str_format(aDesc, sizeof(aDesc), "%s", pOption->m_aDescription); if((str_startswith(pOption->m_aCommand, "random_map") || str_startswith(pOption->m_aCommand, "random_unfinished_map")) && str_length(aReason) == 1 && aReason[0] >= '0' && aReason[0] <= '5') @@ -1834,7 +1828,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) if(!pOption) { - if(Authed != AUTHED_ADMIN) // allow admins to call any vote they want + if(Authed != AUTHED_ADMIN) // allow admins to call any vote they want { str_format(aChatmsg, sizeof(aChatmsg), "'%s' isn't an option on this server", pMsg->m_Value); SendChatTarget(ClientID, aChatmsg); @@ -1858,9 +1852,8 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else if(!Authed && time_get() < m_apPlayers[ClientID]->m_Last_KickVote + (time_freq() * g_Config.m_SvVoteKickDelay)) { str_format(aChatmsg, sizeof(aChatmsg), "There's a %d second wait time between kick votes for each player please wait %d second(s)", - g_Config.m_SvVoteKickDelay, - (int)(((m_apPlayers[ClientID]->m_Last_KickVote + (m_apPlayers[ClientID]->m_Last_KickVote*time_freq()))/time_freq())-(time_get()/time_freq())) - ); + g_Config.m_SvVoteKickDelay, + (int)(((m_apPlayers[ClientID]->m_Last_KickVote + (m_apPlayers[ClientID]->m_Last_KickVote * time_freq())) / time_freq()) - (time_get() / time_freq()))); SendChatTarget(ClientID, aChatmsg); m_apPlayers[ClientID]->m_Last_KickVote = time_get(); return; @@ -1891,7 +1884,6 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) NumPlayers++; for(int j = 0; j < i; j++) { - if(m_apPlayers[j] && m_apPlayers[j]->GetTeam() != TEAM_SPECTATORS && !GetDDRaceTeam(j)) { if(str_comp(aaAddresses[i], aaAddresses[j]) == 0) @@ -1924,7 +1916,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "You can't kick yourself"); return; } - if (!Server()->ReverseTranslate(KickID, ClientID)) + if(!Server()->ReverseTranslate(KickID, ClientID)) { return; } @@ -1951,7 +1943,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) str_format(aSixupDesc, sizeof(aSixupDesc), "%2d: %s", KickID, Server()->ClientName(KickID)); if(!GetDDRaceTeam(ClientID)) { - if (!g_Config.m_SvVoteKickBantime) + if(!g_Config.m_SvVoteKickBantime) { str_format(aCmd, sizeof(aCmd), "kick %d Kicked by vote", KickID); str_format(aDesc, sizeof(aDesc), "Kick '%s'", Server()->ClientName(KickID)); @@ -1993,7 +1985,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "You can't move yourself"); return; } - if (!Server()->ReverseTranslate(SpectateID, ClientID)) + if(!Server()->ReverseTranslate(SpectateID, ClientID)) { return; } @@ -2029,7 +2021,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) if(!m_VoteCloseTime) return; - if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry+Server()->TickSpeed()*3 > Server()->Tick()) + if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry + Server()->TickSpeed() * 3 > Server()->Tick()) return; int64 Now = Server()->Tick(); @@ -2044,7 +2036,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pPlayer->m_VotePos = ++m_VotePos; m_VoteUpdate = true; } - else if (MsgID == NETMSGTYPE_CL_SETTEAM && !m_World.m_Paused) + else if(MsgID == NETMSGTYPE_CL_SETTEAM && !m_World.m_Paused) { CNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)pRawMsg; @@ -2066,9 +2058,9 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) if(pPlayer->m_TeamChangeTick > Server()->Tick()) { pPlayer->m_LastSetTeam = Server()->Tick(); - int TimeLeft = (pPlayer->m_TeamChangeTick - Server()->Tick())/Server()->TickSpeed(); + int TimeLeft = (pPlayer->m_TeamChangeTick - Server()->Tick()) / Server()->TickSpeed(); char aBuf[128]; - str_format(aBuf, sizeof(aBuf), "Time to wait before changing team: %02d:%02d", TimeLeft/60, TimeLeft%60); + str_format(aBuf, sizeof(aBuf), "Time to wait before changing team: %02d:%02d", TimeLeft / 60, TimeLeft % 60); SendBroadcast(aBuf, ClientID); return; } @@ -2077,7 +2069,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) if(m_pController->CanJoinTeam(pMsg->m_Team, ClientID)) { if(pPlayer->IsPaused()) - SendChatTarget(ClientID,"Use /pause first then you can kill"); + SendChatTarget(ClientID, "Use /pause first then you can kill"); else { if(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS) @@ -2089,11 +2081,11 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else { char aBuf[128]; - str_format(aBuf, sizeof(aBuf), "Only %d active players are allowed", Server()->MaxClients()-g_Config.m_SvSpectatorSlots); + str_format(aBuf, sizeof(aBuf), "Only %d active players are allowed", Server()->MaxClients() - g_Config.m_SvSpectatorSlots); SendBroadcast(aBuf, ClientID); } } - else if (MsgID == NETMSGTYPE_CL_ISDDNET) + else if(MsgID == NETMSGTYPE_CL_ISDDNET) { IServer::CClientInfo Info; Server()->GetClientInfo(ClientID, &Info); @@ -2109,7 +2101,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Server()->SetClientDDNetVersion(ClientID, DDNetVersion); OnClientDDNetVersionKnown(ClientID); } - else if (MsgID == NETMSGTYPE_CL_SHOWOTHERSLEGACY) + else if(MsgID == NETMSGTYPE_CL_SHOWOTHERSLEGACY) { if(g_Config.m_SvShowOthers && !g_Config.m_SvShowOthersDefault) { @@ -2117,7 +2109,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pPlayer->m_ShowOthers = pMsg->m_Show; } } - else if (MsgID == NETMSGTYPE_CL_SHOWOTHERS) + else if(MsgID == NETMSGTYPE_CL_SHOWOTHERS) { if(g_Config.m_SvShowOthers && !g_Config.m_SvShowOthersDefault) { @@ -2125,22 +2117,22 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pPlayer->m_ShowOthers = pMsg->m_Show; } } - else if (MsgID == NETMSGTYPE_CL_SHOWDISTANCE) + else if(MsgID == NETMSGTYPE_CL_SHOWDISTANCE) { CNetMsg_Cl_ShowDistance *pMsg = (CNetMsg_Cl_ShowDistance *)pRawMsg; pPlayer->m_ShowDistance = vec2(pMsg->m_X, pMsg->m_Y); } - else if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) + else if(MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) { CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg; - pMsg->m_SpectatorID = clamp(pMsg->m_SpectatorID, (int)SPEC_FOLLOW, MAX_CLIENTS-1); + pMsg->m_SpectatorID = clamp(pMsg->m_SpectatorID, (int)SPEC_FOLLOW, MAX_CLIENTS - 1); if(pMsg->m_SpectatorID >= 0) - if (!Server()->ReverseTranslate(pMsg->m_SpectatorID, ClientID)) + if(!Server()->ReverseTranslate(pMsg->m_SpectatorID, ClientID)) return; - if((g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode+Server()->TickSpeed()/4 > Server()->Tick())) + if((g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode + Server()->TickSpeed() / 4 > Server()->Tick())) return; pPlayer->m_LastSetSpectatorMode = Server()->Tick(); @@ -2149,17 +2141,15 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else pPlayer->m_SpectatorID = pMsg->m_SpectatorID; } - else if (MsgID == NETMSGTYPE_CL_CHANGEINFO) + else if(MsgID == NETMSGTYPE_CL_CHANGEINFO) { - if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo+Server()->TickSpeed()*g_Config.m_SvInfoChangeDelay > Server()->Tick()) + if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo + Server()->TickSpeed() * g_Config.m_SvInfoChangeDelay > Server()->Tick()) return; bool SixupNeedsUpdate = false; CNetMsg_Cl_ChangeInfo *pMsg = (CNetMsg_Cl_ChangeInfo *)pRawMsg; - if(!str_utf8_check(pMsg->m_pName) - || !str_utf8_check(pMsg->m_pClan) - || !str_utf8_check(pMsg->m_pSkin)) + if(!str_utf8_check(pMsg->m_pName) || !str_utf8_check(pMsg->m_pClan) || !str_utf8_check(pMsg->m_pSkin)) { return; } @@ -2225,8 +2215,8 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) { if(i != ClientID) { - Server()->SendPackMsg(&Drop, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); - Server()->SendPackMsg(&Info, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + Server()->SendPackMsg(&Drop, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); + Server()->SendPackMsg(&Info, MSGFLAG_VITAL | MSGFLAG_NORECORD, i); } } } @@ -2241,16 +2231,16 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Msg.m_aUseCustomColors[p] = pPlayer->m_TeeInfos.m_aUseCustomColors[p]; } - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, -1); } Server()->ExpireServerInfo(); } - else if (MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused) + else if(MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused) { CNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)pRawMsg; - if(g_Config.m_SvSpamprotection && pPlayer->m_LastEmote && pPlayer->m_LastEmote+Server()->TickSpeed()*g_Config.m_SvEmoticonDelay > Server()->Tick()) + if(g_Config.m_SvSpamprotection && pPlayer->m_LastEmote && pPlayer->m_LastEmote + Server()->TickSpeed() * g_Config.m_SvEmoticonDelay > Server()->Tick()) return; pPlayer->m_LastEmote = Server()->Tick(); @@ -2265,43 +2255,43 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) case EMOTICON_GHOST: case EMOTICON_QUESTION: case EMOTICON_WTF: - pChr->SetEmoteType(EMOTE_SURPRISE); - break; + pChr->SetEmoteType(EMOTE_SURPRISE); + break; case EMOTICON_DOTDOT: case EMOTICON_DROP: case EMOTICON_ZZZ: - pChr->SetEmoteType(EMOTE_BLINK); - break; + pChr->SetEmoteType(EMOTE_BLINK); + break; case EMOTICON_EYES: case EMOTICON_HEARTS: case EMOTICON_MUSIC: - pChr->SetEmoteType(EMOTE_HAPPY); - break; + pChr->SetEmoteType(EMOTE_HAPPY); + break; case EMOTICON_OOP: case EMOTICON_SORRY: case EMOTICON_SUSHI: - pChr->SetEmoteType(EMOTE_PAIN); - break; + pChr->SetEmoteType(EMOTE_PAIN); + break; case EMOTICON_DEVILTEE: case EMOTICON_SPLATTEE: case EMOTICON_ZOMG: - pChr->SetEmoteType(EMOTE_ANGRY); - break; - default: - pChr->SetEmoteType(EMOTE_NORMAL); - break; + pChr->SetEmoteType(EMOTE_ANGRY); + break; + default: + pChr->SetEmoteType(EMOTE_NORMAL); + break; } pChr->SetEmoteStop(Server()->Tick() + 2 * Server()->TickSpeed()); } } - else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) + else if(MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) { if(m_VoteCloseTime && m_VoteCreator == ClientID && GetDDRaceTeam(ClientID) && (IsKickVote() || IsSpecVote())) { SendChatTarget(ClientID, "You are running a vote please try again after the vote is done!"); return; } - if(pPlayer->m_LastKill && pPlayer->m_LastKill+Server()->TickSpeed()*g_Config.m_SvKillDelay > Server()->Tick()) + if(pPlayer->m_LastKill && pPlayer->m_LastKill + Server()->TickSpeed() * g_Config.m_SvKillDelay > Server()->Tick()) return; if(pPlayer->IsPaused()) return; @@ -2323,7 +2313,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pPlayer->Respawn(); } } - if (MsgID == NETMSGTYPE_CL_STARTINFO) + if(MsgID == NETMSGTYPE_CL_STARTINFO) { if(pPlayer->m_IsReady) return; @@ -2370,11 +2360,11 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendTuningParams(ClientID, pPlayer->m_TuneZone); // client is ready to enter - if (!pPlayer->m_IsReady) + if(!pPlayer->m_IsReady) { pPlayer->m_IsReady = true; CNetMsg_Sv_ReadyToEnter m; - Server()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + Server()->SendPackMsg(&m, MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientID); } Server()->ExpireServerInfo(); @@ -2410,9 +2400,7 @@ void CGameContext::ConToggleTuneParam(IConsole::IResult *pResult, void *pUserDat return; } - float NewValue = fabs(OldValue - pResult->GetFloat(1)) < 0.0001f - ? pResult->GetFloat(2) - : pResult->GetFloat(1); + float NewValue = fabs(OldValue - pResult->GetFloat(1)) < 0.0001f ? pResult->GetFloat(2) : pResult->GetFloat(1); pSelf->Tuning()->Set(pParamName, NewValue); @@ -2453,7 +2441,7 @@ void CGameContext::ConTuneZone(IConsole::IResult *pResult, void *pUserData) const char *pParamName = pResult->GetString(1); float NewValue = pResult->GetFloat(2); - if (List >= 0 && List < NUM_TUNEZONES) + if(List >= 0 && List < NUM_TUNEZONES) { if(pSelf->TuningList()[List].Set(pParamName, NewValue)) { @@ -2472,7 +2460,7 @@ void CGameContext::ConTuneDumpZone(IConsole::IResult *pResult, void *pUserData) CGameContext *pSelf = (CGameContext *)pUserData; int List = pResult->GetInteger(0); char aBuf[256]; - if (List >= 0 && List < NUM_TUNEZONES) + if(List >= 0 && List < NUM_TUNEZONES) { for(int i = 0; i < pSelf->TuningList()[List].Num(); i++) { @@ -2488,10 +2476,10 @@ void CGameContext::ConTuneResetZone(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; CTuningParams TuningParams; - if (pResult->NumArguments()) + if(pResult->NumArguments()) { int List = pResult->GetInteger(0); - if (List >= 0 && List < NUM_TUNEZONES) + if(List >= 0 && List < NUM_TUNEZONES) { pSelf->TuningList()[List] = TuningParams; char aBuf[256]; @@ -2502,9 +2490,9 @@ void CGameContext::ConTuneResetZone(IConsole::IResult *pResult, void *pUserData) } else { - for (int i = 0; i < NUM_TUNEZONES; i++) + for(int i = 0; i < NUM_TUNEZONES; i++) { - *(pSelf->TuningList()+i) = TuningParams; + *(pSelf->TuningList() + i) = TuningParams; pSelf->SendTuningParams(-1, i); } pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "All Tunezones reset"); @@ -2514,10 +2502,10 @@ void CGameContext::ConTuneResetZone(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConTuneSetZoneMsgEnter(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - if (pResult->NumArguments()) + if(pResult->NumArguments()) { int List = pResult->GetInteger(0); - if (List >= 0 && List < NUM_TUNEZONES) + if(List >= 0 && List < NUM_TUNEZONES) { str_copy(pSelf->m_aaZoneEnterMsg[List], pResult->GetString(1), sizeof(pSelf->m_aaZoneEnterMsg[List])); } @@ -2527,10 +2515,10 @@ void CGameContext::ConTuneSetZoneMsgEnter(IConsole::IResult *pResult, void *pUse void CGameContext::ConTuneSetZoneMsgLeave(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - if (pResult->NumArguments()) + if(pResult->NumArguments()) { int List = pResult->GetInteger(0); - if (List >= 0 && List < NUM_TUNEZONES) + if(List >= 0 && List < NUM_TUNEZONES) { str_copy(pSelf->m_aaZoneLeaveMsg[List], pResult->GetString(1), sizeof(pSelf->m_aaZoneLeaveMsg[List])); } @@ -2556,13 +2544,12 @@ void CGameContext::ConMapbug(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapbugs", "map-internal setting overridden by database"); break; case MAPBUGUPDATE_NOTFOUND: - { - char aBuf[64]; - str_format(aBuf, sizeof(aBuf), "unknown map bug '%s', ignoring", pMapBugName); - pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapbugs", aBuf); - - } - break; + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "unknown map bug '%s', ignoring", pMapBugName); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapbugs", aBuf); + } + break; default: dbg_assert(0, "unreachable"); } @@ -2573,7 +2560,7 @@ void CGameContext::ConSwitchOpen(IConsole::IResult *pResult, void *pUserData) CGameContext *pSelf = (CGameContext *)pUserData; int Switch = pResult->GetInteger(0); - if (pSelf->Collision()->m_NumSwitchers > 0 && Switch >= 0 && Switch < pSelf->Collision()->m_NumSwitchers+1) + if(pSelf->Collision()->m_NumSwitchers > 0 && Switch >= 0 && Switch < pSelf->Collision()->m_NumSwitchers + 1) { pSelf->Collision()->m_pSwitchers[Switch].m_Initial = false; char aBuf[256]; @@ -2632,12 +2619,12 @@ void CGameContext::ConBroadcast(IConsole::IResult *pResult, void *pUserData) int i, j; for(i = 0, j = 0; aBuf[i]; i++, j++) { - if(aBuf[i] == '\\' && aBuf[i+1] == 'n') + if(aBuf[i] == '\\' && aBuf[i + 1] == 'n') { aBuf[j] = '\n'; i++; } - else if (i != j) + else if(i != j) { aBuf[j] = aBuf[i]; } @@ -2656,9 +2643,9 @@ void CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData) void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; - int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1); + int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS - 1); int Team = clamp(pResult->GetInteger(1), -1, 1); - int Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0; + int Delay = pResult->NumArguments() > 2 ? pResult->GetInteger(2) : 0; if(!pSelf->m_apPlayers[ClientID]) return; @@ -2667,7 +2654,7 @@ void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); pSelf->m_apPlayers[ClientID]->Pause(CPlayer::PAUSE_NONE, false); // reset /spec and /pause to allow rejoin - pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60; + pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick() + pSelf->Server()->TickSpeed() * Delay * 60; pSelf->m_apPlayers[ClientID]->SetTeam(Team); if(Team == TEAM_SPECTATORS) pSelf->m_apPlayers[ClientID]->Pause(CPlayer::PAUSE_NONE, true); @@ -2745,7 +2732,7 @@ void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) pSelf->m_pVoteOptionFirst = pOption; str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); - mem_copy(pOption->m_aCommand, pCommand, Len+1); + mem_copy(pOption->m_aCommand, pCommand, Len + 1); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "added option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); @@ -2812,7 +2799,7 @@ void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) pVoteOptionFirst = pDst; str_copy(pDst->m_aDescription, pSrc->m_aDescription, sizeof(pDst->m_aDescription)); - mem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len+1); + mem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len + 1); } // clean up @@ -2863,7 +2850,7 @@ void CGameContext::ConForceVote(IConsole::IResult *pResult, void *pUserData) return; } - if (!g_Config.m_SvVoteKickBantime) + if(!g_Config.m_SvVoteKickBantime) { str_format(aBuf, sizeof(aBuf), "kick %d %s", KickID, pReason); pSelf->Console()->ExecuteLine(aBuf); @@ -2945,22 +2932,22 @@ void CGameContext::OnConsoleInit() m_ChatPrintCBIndex = Console()->RegisterPrintCallback(0, SendChatResponse, this); - Console()->Register("tune", "s[tuning] i[value]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneParam, this, "Tune variable to value"); - Console()->Register("toggle_tune", "s[tuning] i[value 1] i[value 2]", CFGFLAG_SERVER|CFGFLAG_GAME, ConToggleTuneParam, this, "Toggle tune variable"); + Console()->Register("tune", "s[tuning] i[value]", CFGFLAG_SERVER | CFGFLAG_GAME, ConTuneParam, this, "Tune variable to value"); + Console()->Register("toggle_tune", "s[tuning] i[value 1] i[value 2]", CFGFLAG_SERVER | CFGFLAG_GAME, ConToggleTuneParam, this, "Toggle tune variable"); Console()->Register("tune_reset", "", CFGFLAG_SERVER, ConTuneReset, this, "Reset tuning"); Console()->Register("tune_dump", "", CFGFLAG_SERVER, ConTuneDump, this, "Dump tuning"); - Console()->Register("tune_zone", "i[zone] s[tuning] i[value]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneZone, this, "Tune in zone a variable to value"); + Console()->Register("tune_zone", "i[zone] s[tuning] i[value]", CFGFLAG_SERVER | CFGFLAG_GAME, ConTuneZone, this, "Tune in zone a variable to value"); Console()->Register("tune_zone_dump", "i[zone]", CFGFLAG_SERVER, ConTuneDumpZone, this, "Dump zone tuning in zone x"); Console()->Register("tune_zone_reset", "?i[zone]", CFGFLAG_SERVER, ConTuneResetZone, this, "reset zone tuning in zone x or in all zones"); - Console()->Register("tune_zone_enter", "i[zone] s[message]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneSetZoneMsgEnter, this, "which message to display on zone enter; use 0 for normal area"); - Console()->Register("tune_zone_leave", "i[zone] s[message]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneSetZoneMsgLeave, this, "which message to display on zone leave; use 0 for normal area"); - Console()->Register("mapbug", "s[mapbug]", CFGFLAG_SERVER|CFGFLAG_GAME, ConMapbug, this, "Enable map compatibility mode using the specified bug (example: grenade-doublexplosion@ddnet.tw)"); - Console()->Register("switch_open", "i[switch]", CFGFLAG_SERVER|CFGFLAG_GAME, ConSwitchOpen, this, "Whether a switch is deactivated by default (otherwise activated)"); + Console()->Register("tune_zone_enter", "i[zone] s[message]", CFGFLAG_SERVER | CFGFLAG_GAME, ConTuneSetZoneMsgEnter, this, "which message to display on zone enter; use 0 for normal area"); + Console()->Register("tune_zone_leave", "i[zone] s[message]", CFGFLAG_SERVER | CFGFLAG_GAME, ConTuneSetZoneMsgLeave, this, "which message to display on zone leave; use 0 for normal area"); + Console()->Register("mapbug", "s[mapbug]", CFGFLAG_SERVER | CFGFLAG_GAME, ConMapbug, this, "Enable map compatibility mode using the specified bug (example: grenade-doublexplosion@ddnet.tw)"); + Console()->Register("switch_open", "i[switch]", CFGFLAG_SERVER | CFGFLAG_GAME, ConSwitchOpen, this, "Whether a switch is deactivated by default (otherwise activated)"); Console()->Register("pause_game", "", CFGFLAG_SERVER, ConPause, this, "Pause/unpause game"); - Console()->Register("change_map", "?r[map]", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, "Change map"); + Console()->Register("change_map", "?r[map]", CFGFLAG_SERVER | CFGFLAG_STORE, ConChangeMap, this, "Change map"); Console()->Register("random_map", "?i[stars]", CFGFLAG_SERVER, ConRandomMap, this, "Random map"); Console()->Register("random_unfinished_map", "?i[stars]", CFGFLAG_SERVER, ConRandomUnfinishedMap, this, "Random unfinished map"); - Console()->Register("restart", "?i[seconds]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (0 = abort)"); + Console()->Register("restart", "?i[seconds]", CFGFLAG_SERVER | CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (0 = abort)"); Console()->Register("broadcast", "r[message]", CFGFLAG_SERVER, ConBroadcast, this, "Broadcast message"); Console()->Register("say", "r[message]", CFGFLAG_SERVER, ConSay, this, "Say in chat"); Console()->Register("set_team", "i[id] i[team-id] ?i[delay in minutes]", CFGFLAG_SERVER, ConSetTeam, this, "Set team of player to team"); @@ -2975,10 +2962,10 @@ void CGameContext::OnConsoleInit() Console()->Chain("sv_motd", ConchainSpecialMotdupdate, this); - #define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); - #include - #define CHAT_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); - #include "ddracechat.h" +#define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); +#include +#define CHAT_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); +#include "ddracechat.h" } void CGameContext::OnInit(/*class IKernel *pKernel*/) @@ -3003,7 +2990,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) DeleteTempfile(); //if(!data) // only load once - //data = load_data_from_memory(internal_data); + //data = load_data_from_memory(internal_data); for(int i = 0; i < NUM_NETOBJTYPES; i++) Server()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); @@ -3024,7 +3011,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) // Reset Tunezones CTuningParams TuningParams; - for (int i = 0; i < NUM_TUNEZONES; i++) + for(int i = 0; i < NUM_TUNEZONES; i++) { TuningList()[i] = TuningParams; TuningList()[i].Set("gun_curvature", 0); @@ -3034,7 +3021,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) TuningList()[i].Set("shotgun_speeddiff", 0); } - for (int i = 0; i < NUM_TUNEZONES; i++) + for(int i = 0; i < NUM_TUNEZONES; i++) { // Send no text by default when changing tune zones. m_aaZoneEnterMsg[i][0] = 0; @@ -3066,7 +3053,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) g_Config.m_SvShowOthersDefault = 0; if(Collision()->m_NumSwitchers > 0) - for (int i = 0; i < Collision()->m_NumSwitchers+1; ++i) + for(int i = 0; i < Collision()->m_NumSwitchers + 1; ++i) Collision()->m_pSwitchers[i].m_Initial = true; } @@ -3084,7 +3071,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) Tuning()->Set("player_collision", 0); Tuning()->Set("player_hooking", 0); - for (int i = 0; i < NUM_TUNEZONES; i++) + for(int i = 0; i < NUM_TUNEZONES; i++) { TuningList()[i].Set("player_collision", 0); TuningList()[i].Set("player_hooking", 0); @@ -3092,7 +3079,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) } m_pController = new CGameControllerDDRace(this); - ((CGameControllerDDRace*)m_pController)->m_Teams.Reset(); + ((CGameControllerDDRace *)m_pController)->m_Teams.Reset(); const char *pCensorFilename = "censorlist.txt"; IOHANDLE File = Storage()->OpenFile(pCensorFilename, IOFLAG_READ, IStorage::TYPE_ALL); @@ -3198,7 +3185,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) { for(int x = 0; x < pTileMap->m_Width; x++) { - int Index = pTiles[y*pTileMap->m_Width+x].m_Index; + int Index = pTiles[y * pTileMap->m_Width + x].m_Index; if(Index == TILE_OLDLASER) { @@ -3228,7 +3215,7 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) if(Index >= ENTITY_OFFSET) { - vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); + vec2 Pos(x * 32.0f + 16.0f, y * 32.0f + 16.0f); //m_pController->OnEntity(Index-ENTITY_OFFSET, Pos); m_pController->OnEntity(Index - ENTITY_OFFSET, Pos, LAYER_GAME, pTiles[y * pTileMap->m_Width + x].m_Flags); } @@ -3263,19 +3250,19 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) } if(Index >= ENTITY_OFFSET) { - vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); - m_pController->OnEntity(Index-ENTITY_OFFSET, Pos, LAYER_FRONT, pFront[y*pTileMap->m_Width+x].m_Flags); + vec2 Pos(x * 32.0f + 16.0f, y * 32.0f + 16.0f); + m_pController->OnEntity(Index - ENTITY_OFFSET, Pos, LAYER_FRONT, pFront[y * pTileMap->m_Width + x].m_Flags); } } if(pSwitch) { - Index = pSwitch[y*pTileMap->m_Width + x].m_Type; + Index = pSwitch[y * pTileMap->m_Width + x].m_Type; // TODO: Add off by default door here // if (Index == TILE_DOOR_OFF) if(Index >= ENTITY_OFFSET) { - vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); - m_pController->OnEntity(Index-ENTITY_OFFSET, Pos, LAYER_SWITCH, pSwitch[y*pTileMap->m_Width+x].m_Flags, pSwitch[y*pTileMap->m_Width+x].m_Number); + vec2 Pos(x * 32.0f + 16.0f, y * 32.0f + 16.0f); + m_pController->OnEntity(Index - ENTITY_OFFSET, Pos, LAYER_SWITCH, pSwitch[y * pTileMap->m_Width + x].m_Flags, pSwitch[y * pTileMap->m_Width + x].m_Number); } } } @@ -3286,9 +3273,9 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) #ifdef CONF_DEBUG if(g_Config.m_DbgDummies) { - for(int i = 0; i < g_Config.m_DbgDummies ; i++) + for(int i = 0; i < g_Config.m_DbgDummies; i++) { - OnClientConnected(MAX_CLIENTS-i-1); + OnClientConnected(MAX_CLIENTS - i - 1); } } #endif @@ -3498,9 +3485,9 @@ void CGameContext::OnSnap(int ClientID) { CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = (int *)&m_Tuning; - for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) + for(unsigned i = 0; i < sizeof(m_Tuning) / sizeof(int); i++) Msg.AddInt(pParams[i]); - Server()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND, ClientID); + Server()->SendMsg(&Msg, MSGFLAG_RECORD | MSGFLAG_NOSEND, ClientID); } m_World.Snap(ClientID); @@ -3515,7 +3502,6 @@ void CGameContext::OnSnap(int ClientID) if(ClientID > -1) m_apPlayers[ClientID]->FakeSnap(); - } void CGameContext::OnPreSnap() {} void CGameContext::OnPostSnap() @@ -3552,9 +3538,9 @@ void CGameContext::SendChatResponseAll(const char *pLine, void *pUser) ReentryGuard++; if(*pLine == '[') - do - pLine++; - while((pLine - 2 < pLineOrig || *(pLine - 2) != ':') && *pLine != 0);//remove the category (e.g. [Console]: No Such Command) + do + pLine++; + while((pLine - 2 < pLineOrig || *(pLine - 2) != ':') && *pLine != 0); //remove the category (e.g. [Console]: No Such Command) pSelf->SendChat(-1, CHAT_ALL, pLine); @@ -3651,8 +3637,7 @@ int CGameContext::ProcessSpamProtection(int ClientID) { if(!m_apPlayers[ClientID]) return 0; - if(g_Config.m_SvSpamprotection && m_apPlayers[ClientID]->m_LastChat - && m_apPlayers[ClientID]->m_LastChat + Server()->TickSpeed() * g_Config.m_SvChatDelay > Server()->Tick()) + if(g_Config.m_SvSpamprotection && m_apPlayers[ClientID]->m_LastChat && m_apPlayers[ClientID]->m_LastChat + Server()->TickSpeed() * g_Config.m_SvChatDelay > Server()->Tick()) return 1; else m_apPlayers[ClientID]->m_LastChat = Server()->Tick(); @@ -3666,7 +3651,7 @@ int CGameContext::ProcessSpamProtection(int ClientID) Muted = (m_aMutes[i].m_Expire - Server()->Tick()) / Server()->TickSpeed(); } - if (Muted > 0) + if(Muted > 0) { char aBuf[128]; str_format(aBuf, sizeof aBuf, "You are not permitted to talk for the next %d seconds.", Muted); @@ -3674,7 +3659,7 @@ int CGameContext::ProcessSpamProtection(int ClientID) return 1; } - if ((m_apPlayers[ClientID]->m_ChatScore += g_Config.m_SvChatPenalty) > g_Config.m_SvChatThreshold) + if((m_apPlayers[ClientID]->m_ChatScore += g_Config.m_SvChatPenalty) > g_Config.m_SvChatThreshold) { Mute(&Addr, g_Config.m_SvSpamMuteDuration, Server()->ClientName(ClientID)); m_apPlayers[ClientID]->m_ChatScore = 0; @@ -3686,7 +3671,7 @@ int CGameContext::ProcessSpamProtection(int ClientID) int CGameContext::GetDDRaceTeam(int ClientID) { - CGameControllerDDRace *pController = (CGameControllerDDRace*)m_pController; + CGameControllerDDRace *pController = (CGameControllerDDRace *)m_pController; return pController->m_Teams.m_Core.Team(ClientID); } @@ -3704,7 +3689,7 @@ void CGameContext::ResetTuning() bool CheckClientID2(int ClientID) { - if (ClientID < 0 || ClientID >= MAX_CLIENTS) + if(ClientID < 0 || ClientID >= MAX_CLIENTS) return false; return true; } @@ -3754,9 +3739,8 @@ void CGameContext::Whisper(int ClientID, char *pStr) pStr++; for(Victim = 0; Victim < MAX_CLIENTS; Victim++) - if (str_comp(pName, Server()->ClientName(Victim)) == 0) + if(str_comp(pName, Server()->ClientName(Victim)) == 0) break; - } else { @@ -3772,12 +3756,12 @@ void CGameContext::Whisper(int ClientID, char *pStr) { pStr[0] = 0; for(Victim = 0; Victim < MAX_CLIENTS; Victim++) - if (str_comp(pName, Server()->ClientName(Victim)) == 0) + if(str_comp(pName, Server()->ClientName(Victim)) == 0) break; pStr[0] = ' '; - if (Victim < MAX_CLIENTS) + if(Victim < MAX_CLIENTS) break; } pStr++; @@ -3796,14 +3780,14 @@ void CGameContext::Whisper(int ClientID, char *pStr) char aBuf[256]; - if (Error) + if(Error) { str_format(aBuf, sizeof(aBuf), "Invalid whisper"); SendChatTarget(ClientID, aBuf); return; } - if (Victim >= MAX_CLIENTS || !CheckClientID2(Victim)) + if(Victim >= MAX_CLIENTS || !CheckClientID2(Victim)) { str_format(aBuf, sizeof(aBuf), "No player with name \"%s\" found", pName); SendChatTarget(ClientID, aBuf); @@ -3837,7 +3821,7 @@ void CGameContext::WhisperID(int ClientID, int VictimID, const char *pMessage) Msg.m_pMessage = aCensoredMessage; Msg.m_TargetID = VictimID; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } else if(GetClientVersion(ClientID) >= VERSION_DDNET_WHISPER) { @@ -3848,7 +3832,7 @@ void CGameContext::WhisperID(int ClientID, int VictimID, const char *pMessage) if(g_Config.m_SvDemoChat) Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); else - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, ClientID); } else { @@ -3864,7 +3848,7 @@ void CGameContext::WhisperID(int ClientID, int VictimID, const char *pMessage) Msg.m_pMessage = aCensoredMessage; Msg.m_TargetID = VictimID; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, VictimID); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, VictimID); } else if(GetClientVersion(VictimID) >= VERSION_DDNET_WHISPER) { @@ -3875,7 +3859,7 @@ void CGameContext::WhisperID(int ClientID, int VictimID, const char *pMessage) if(g_Config.m_SvDemoChat) Server()->SendPackMsg(&Msg2, MSGFLAG_VITAL, VictimID); else - Server()->SendPackMsg(&Msg2, MSGFLAG_VITAL|MSGFLAG_NORECORD, VictimID); + Server()->SendPackMsg(&Msg2, MSGFLAG_VITAL | MSGFLAG_NORECORD, VictimID); } else { @@ -3887,13 +3871,13 @@ void CGameContext::WhisperID(int ClientID, int VictimID, const char *pMessage) void CGameContext::Converse(int ClientID, char *pStr) { CPlayer *pPlayer = m_apPlayers[ClientID]; - if (!pPlayer) + if(!pPlayer) return; if(ProcessSpamProtection(ClientID)) return; - if (pPlayer->m_LastWhisperTo < 0) + if(pPlayer->m_LastWhisperTo < 0) SendChatTarget(ClientID, "You do not have an ongoing conversation. Whisper to someone to start one"); else { @@ -3914,7 +3898,7 @@ void CGameContext::List(int ClientID, const char *pFilter) int Total = 0; char aBuf[256]; int Bufcnt = 0; - if (pFilter[0]) + if(pFilter[0]) str_format(aBuf, sizeof(aBuf), "Listing players with \"%s\" in name:", pFilter); else str_format(aBuf, sizeof(aBuf), "Listing all players:"); @@ -3925,14 +3909,14 @@ void CGameContext::List(int ClientID, const char *pFilter) { Total++; const char *pName = Server()->ClientName(i); - if (str_find_nocase(pName, pFilter) == NULL) + if(str_find_nocase(pName, pFilter) == NULL) continue; - if (Bufcnt + str_length(pName) + 4 > 256) + if(Bufcnt + str_length(pName) + 4 > 256) { SendChatTarget(ClientID, aBuf); Bufcnt = 0; } - if (Bufcnt != 0) + if(Bufcnt != 0) { str_format(&aBuf[Bufcnt], sizeof(aBuf) - Bufcnt, ", %s", pName); Bufcnt += 2 + str_length(pName); @@ -3944,7 +3928,7 @@ void CGameContext::List(int ClientID, const char *pFilter) } } } - if (Bufcnt != 0) + if(Bufcnt != 0) SendChatTarget(ClientID, aBuf); str_format(aBuf, sizeof(aBuf), "%d players online", Total); SendChatTarget(ClientID, aBuf); @@ -4059,7 +4043,7 @@ bool CGameContext::RateLimitPlayerMapVote(int ClientID) { char aChatmsg[512] = {0}; str_format(aChatmsg, sizeof(aChatmsg), "There's a %d second delay between map-votes, please wait %d seconds.", - g_Config.m_SvVoteMapTimeDelay, (int)((m_LastMapVote + g_Config.m_SvVoteMapTimeDelay * time_freq() - time_get())/time_freq())); + g_Config.m_SvVoteMapTimeDelay, (int)((m_LastMapVote + g_Config.m_SvVoteMapTimeDelay * time_freq() - time_get()) / time_freq())); SendChatTarget(ClientID, aChatmsg); return true; } diff --git a/src/game/server/gamecontext.h b/src/game/server/gamecontext.h index a440623d1..70b80a64a 100644 --- a/src/game/server/gamecontext.h +++ b/src/game/server/gamecontext.h @@ -4,8 +4,8 @@ #define GAME_SERVER_GAMECONTEXT_H #include -#include #include +#include #include #include @@ -124,6 +124,7 @@ class CGameContext : public IGameServer void Construct(int Resetting); bool m_Resetting; + public: IServer *Server() const { return m_pServer; } IConsole *Console() { return m_pConsole; } @@ -177,7 +178,7 @@ public: enum { - VOTE_ENFORCE_UNKNOWN=0, + VOTE_ENFORCE_UNKNOWN = 0, VOTE_ENFORCE_NO, VOTE_ENFORCE_YES, VOTE_ENFORCE_ABORT, @@ -187,26 +188,25 @@ public: CVoteOptionServer *m_pVoteOptionLast; // helper functions - void CreateDamageInd(vec2 Pos, float AngleMod, int Amount, int64 Mask=-1); + void CreateDamageInd(vec2 Pos, float AngleMod, int Amount, int64 Mask = -1); void CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, int ActivatedTeam, int64 Mask); - void CreateHammerHit(vec2 Pos, int64 Mask=-1); - void CreatePlayerSpawn(vec2 Pos, int64 Mask=-1); - void CreateDeath(vec2 Pos, int Who, int64 Mask=-1); - void CreateSound(vec2 Pos, int Sound, int64 Mask=-1); - void CreateSoundGlobal(int Sound, int Target=-1); - + void CreateHammerHit(vec2 Pos, int64 Mask = -1); + void CreatePlayerSpawn(vec2 Pos, int64 Mask = -1); + void CreateDeath(vec2 Pos, int Who, int64 Mask = -1); + void CreateSound(vec2 Pos, int Sound, int64 Mask = -1); + void CreateSoundGlobal(int Sound, int Target = -1); enum { - CHAT_ALL=-2, - CHAT_SPEC=-1, - CHAT_RED=0, - CHAT_BLUE=1, - CHAT_WHISPER_SEND=2, - CHAT_WHISPER_RECV=3, + CHAT_ALL = -2, + CHAT_SPEC = -1, + CHAT_RED = 0, + CHAT_BLUE = 1, + CHAT_WHISPER_SEND = 2, + CHAT_WHISPER_RECV = 3, - CHAT_SIX=1<<0, - CHAT_SIXUP=1<<1, + CHAT_SIX = 1 << 0, + CHAT_SIXUP = 1 << 1, }; // network @@ -218,7 +218,7 @@ public: void SendWeaponPickup(int ClientID, int Weapon); void SendBroadcast(const char *pText, int ClientID, bool IsImportant = true); - void List(int ClientID, const char* filter); + void List(int ClientID, const char *filter); // void CheckPureTuning(); @@ -284,7 +284,6 @@ public: std::shared_ptr m_SqlRandomMapResult; private: - bool m_VoteWillPass; class CScore *m_pScore; @@ -392,8 +391,8 @@ private: enum { - MAX_MUTES=32, - MAX_VOTE_MUTES=32, + MAX_MUTES = 32, + MAX_VOTE_MUTES = 32, }; struct CMute { @@ -426,7 +425,7 @@ public: VOTE_ENFORCE_NO_ADMIN = VOTE_ENFORCE_YES + 1, VOTE_ENFORCE_YES_ADMIN, - VOTE_TYPE_UNKNOWN=0, + VOTE_TYPE_UNKNOWN = 0, VOTE_TYPE_OPTION, VOTE_TYPE_KICK, VOTE_TYPE_SPECTATE, @@ -441,7 +440,7 @@ public: void SendRecord(int ClientID); static void SendChatResponse(const char *pLine, void *pUser, bool Highlighted = false); static void SendChatResponseAll(const char *pLine, void *pUser); - virtual void OnSetAuthed(int ClientID,int Level); + virtual void OnSetAuthed(int ClientID, int Level); virtual bool PlayerCollision(); virtual bool PlayerHooking(); virtual float PlayerJetpack(); @@ -453,8 +452,8 @@ public: }; inline int64 CmaskAll() { return -1LL; } -inline int64 CmaskOne(int ClientID) { return 1LL< #include "entities/pickup.h" -#include "gamecontroller.h" #include "gamecontext.h" +#include "gamecontroller.h" -#include "entities/light.h" +#include "entities/door.h" #include "entities/dragger.h" #include "entities/gun.h" -#include "entities/projectile.h" +#include "entities/light.h" #include "entities/plasma.h" -#include "entities/door.h" +#include "entities/projectile.h" #include - IGameController::IGameController(class CGameContext *pGameServer) { m_pGameServer = pGameServer; @@ -59,7 +58,7 @@ float IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) Scoremod = 0.5f; float d = distance(Pos, pC->m_Pos); - Score += Scoremod * (d == 0 ? 1000000000.0f : 1.0f/d); + Score += Scoremod * (d == 0 ? 1000000000.0f : 1.0f / d); } return Score; @@ -72,8 +71,8 @@ void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) { // check if the position is occupado CCharacter *aEnts[MAX_CLIENTS]; - int Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); - vec2 Positions[5] = { vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f) }; // start, left, up, right, down + int Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity **)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + vec2 Positions[5] = {vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f)}; // start, left, up, right, down int Result = -1; for(int Index = 0; Index < 5 && Result == -1; ++Index) { @@ -81,17 +80,17 @@ void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) if(!GameServer()->m_World.m_Core.m_Tuning[0].m_PlayerCollision) break; for(int c = 0; c < Num; ++c) - if(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i]+Positions[Index]) || - distance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i]+Positions[Index]) <= aEnts[c]->m_ProximityRadius) + if(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i] + Positions[Index]) || + distance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i] + Positions[Index]) <= aEnts[c]->m_ProximityRadius) { Result = -1; break; } } if(Result == -1) - continue; // try next spawn point + continue; // try next spawn point - vec2 P = m_aaSpawnPoints[Type][i]+Positions[Result]; + vec2 P = m_aaSpawnPoints[Type][i] + Positions[Result]; float S = EvaluateSpawnPos(pEval, P); if(!pEval->m_Got || pEval->m_Score > S) { @@ -120,24 +119,24 @@ bool IGameController::CanSpawn(int Team, vec2 *pOutPos) bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Number) { - if (Index < 0) + if(Index < 0) return false; int Type = -1; int SubType = 0; - int x,y; - x=(Pos.x-16.0f)/32.0f; - y=(Pos.y-16.0f)/32.0f; + int x, y; + x = (Pos.x - 16.0f) / 32.0f; + y = (Pos.y - 16.0f) / 32.0f; int sides[8]; - sides[0]=GameServer()->Collision()->Entity(x,y+1, Layer); - sides[1]=GameServer()->Collision()->Entity(x+1,y+1, Layer); - sides[2]=GameServer()->Collision()->Entity(x+1,y, Layer); - sides[3]=GameServer()->Collision()->Entity(x+1,y-1, Layer); - sides[4]=GameServer()->Collision()->Entity(x,y-1, Layer); - sides[5]=GameServer()->Collision()->Entity(x-1,y-1, Layer); - sides[6]=GameServer()->Collision()->Entity(x-1,y, Layer); - sides[7]=GameServer()->Collision()->Entity(x-1,y+1, Layer); + sides[0] = GameServer()->Collision()->Entity(x, y + 1, Layer); + sides[1] = GameServer()->Collision()->Entity(x + 1, y + 1, Layer); + sides[2] = GameServer()->Collision()->Entity(x + 1, y, Layer); + sides[3] = GameServer()->Collision()->Entity(x + 1, y - 1, Layer); + sides[4] = GameServer()->Collision()->Entity(x, y - 1, Layer); + sides[5] = GameServer()->Collision()->Entity(x - 1, y - 1, Layer); + sides[6] = GameServer()->Collision()->Entity(x - 1, y, Layer); + sides[7] = GameServer()->Collision()->Entity(x - 1, y + 1, Layer); if(Index == ENTITY_SPAWN) m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos; @@ -148,16 +147,15 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu else if(Index == ENTITY_DOOR) { - for(int i = 0; i < 8;i++) + for(int i = 0; i < 8; i++) { - if (sides[i] >= ENTITY_LASER_SHORT && sides[i] <= ENTITY_LASER_LONG) + if(sides[i] >= ENTITY_LASER_SHORT && sides[i] <= ENTITY_LASER_LONG) { - new CDoor - ( + new CDoor( &GameServer()->m_World, //GameWorld Pos, //Pos pi / 4 * i, //Rotation - 32 * 3 + 32 *(sides[i] - ENTITY_LASER_SHORT) * 3, //Length + 32 * 3 + 32 * (sides[i] - ENTITY_LASER_SHORT) * 3, //Length Number //Number ); } @@ -175,8 +173,7 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu else Dir = 3; float Deg = Dir * (pi / 2); - CProjectile *bullet = new CProjectile - ( + CProjectile *bullet = new CProjectile( &GameServer()->m_World, WEAPON_SHOTGUN, //Type -1, //Owner @@ -186,26 +183,24 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu true, //Freeze true, //Explosive 0, //Force - (g_Config.m_SvShotgunBulletSound)?SOUND_GRENADE_EXPLODE:-1,//SoundImpact + (g_Config.m_SvShotgunBulletSound) ? SOUND_GRENADE_EXPLODE : -1, //SoundImpact Layer, - Number - ); + Number); bullet->SetBouncing(2 - (Dir % 2)); } else if(Index == ENTITY_CRAZY_SHOTGUN) { int Dir; if(!Flags) - Dir=0; + Dir = 0; else if(Flags == (TILEFLAG_ROTATE)) Dir = 1; - else if(Flags == (TILEFLAG_VFLIP|TILEFLAG_HFLIP)) + else if(Flags == (TILEFLAG_VFLIP | TILEFLAG_HFLIP)) Dir = 2; else Dir = 3; - float Deg = Dir * ( pi / 2); - CProjectile *bullet = new CProjectile - ( + float Deg = Dir * (pi / 2); + CProjectile *bullet = new CProjectile( &GameServer()->m_World, WEAPON_SHOTGUN, //Type -1, //Owner @@ -217,8 +212,7 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu 0, SOUND_GRENADE_EXPLODE, Layer, - Number - ); + Number); bullet->SetBouncing(2 - (Dir % 2)); } @@ -249,19 +243,19 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu else if(Index >= ENTITY_LASER_FAST_CCW && Index <= ENTITY_LASER_FAST_CW) { int sides2[8]; - sides2[0]=GameServer()->Collision()->Entity(x, y + 2, Layer); - sides2[1]=GameServer()->Collision()->Entity(x + 2, y + 2, Layer); - sides2[2]=GameServer()->Collision()->Entity(x + 2, y, Layer); - sides2[3]=GameServer()->Collision()->Entity(x + 2, y - 2, Layer); - sides2[4]=GameServer()->Collision()->Entity(x,y - 2, Layer); - sides2[5]=GameServer()->Collision()->Entity(x - 2, y - 2, Layer); - sides2[6]=GameServer()->Collision()->Entity(x - 2, y, Layer); - sides2[7]=GameServer()->Collision()->Entity(x - 2, y + 2, Layer); + sides2[0] = GameServer()->Collision()->Entity(x, y + 2, Layer); + sides2[1] = GameServer()->Collision()->Entity(x + 2, y + 2, Layer); + sides2[2] = GameServer()->Collision()->Entity(x + 2, y, Layer); + sides2[3] = GameServer()->Collision()->Entity(x + 2, y - 2, Layer); + sides2[4] = GameServer()->Collision()->Entity(x, y - 2, Layer); + sides2[5] = GameServer()->Collision()->Entity(x - 2, y - 2, Layer); + sides2[6] = GameServer()->Collision()->Entity(x - 2, y, Layer); + sides2[7] = GameServer()->Collision()->Entity(x - 2, y + 2, Layer); float AngularSpeed = 0.0f; - int Ind=Index-ENTITY_LASER_STOP; + int Ind = Index - ENTITY_LASER_STOP; int M; - if( Ind < 0) + if(Ind < 0) { Ind = -Ind; M = 1; @@ -271,7 +265,6 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu else M = -1; - if(Ind == 0) AngularSpeed = 0.0f; else if(Ind == 1) @@ -282,7 +275,7 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu AngularSpeed = pi / 90; AngularSpeed *= M; - for(int i=0; i<8;i++) + for(int i = 0; i < 8; i++) { if(sides[i] >= ENTITY_LASER_SHORT && sides[i] <= ENTITY_LASER_LONG) { @@ -302,7 +295,6 @@ bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Nu Lgt->m_CurveLength = Lgt->m_Length; } } - } else if(Index >= ENTITY_DRAGGER_WEAK && Index <= ENTITY_DRAGGER_STRONG) { @@ -374,7 +366,7 @@ void IGameController::StartRound() m_ForceBalanced = false; Server()->DemoRecorder_HandleAutoStart(); char aBuf[256]; - str_format(aBuf, sizeof(aBuf), "start round type='%s' teamplay='%d'", m_pGameType, m_GameFlags&GAMEFLAG_TEAMS); + str_format(aBuf, sizeof(aBuf), "start round type='%s' teamplay='%d'", m_pGameType, m_GameFlags & GAMEFLAG_TEAMS); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } @@ -410,7 +402,7 @@ void IGameController::DoWarmup(int Seconds) if(Seconds < 0) m_Warmup = 0; else - m_Warmup = Seconds*Server()->TickSpeed(); + m_Warmup = Seconds * Server()->TickSpeed(); } bool IGameController::IsForceBalanced() @@ -418,7 +410,6 @@ bool IGameController::IsForceBalanced() return false; } - bool IGameController::CanBeMovedOnBalance(int ClientID) { return true; @@ -437,7 +428,7 @@ void IGameController::Tick() if(m_GameOverTick != -1) { // game over.. wait for restart - if(Server()->Tick() > m_GameOverTick+Server()->TickSpeed()*10) + if(Server()->Tick() > m_GameOverTick + Server()->TickSpeed() * 10) { StartRound(); m_RoundCount++; @@ -448,43 +439,43 @@ void IGameController::Tick() { for(int i = 0; i < MAX_CLIENTS; ++i) { - #ifdef CONF_DEBUG +#ifdef CONF_DEBUG if(g_Config.m_DbgDummies) { - if(i >= MAX_CLIENTS-g_Config.m_DbgDummies) + if(i >= MAX_CLIENTS - g_Config.m_DbgDummies) break; } - #endif +#endif if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && Server()->GetAuthedState(i) == AUTHED_NO) { - if(Server()->Tick() > GameServer()->m_apPlayers[i]->m_LastActionTick+g_Config.m_SvInactiveKickTime*Server()->TickSpeed()*60) + if(Server()->Tick() > GameServer()->m_apPlayers[i]->m_LastActionTick + g_Config.m_SvInactiveKickTime * Server()->TickSpeed() * 60) { switch(g_Config.m_SvInactiveKick) { case 0: - { - // move player to spectator - GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); - } - break; + { + // move player to spectator + GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); + } + break; case 1: - { - // move player to spectator if the reserved slots aren't filled yet, kick him otherwise - int Spectators = 0; - for(int j = 0; j < MAX_CLIENTS; ++j) - if(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS) - ++Spectators; - if(Spectators >= g_Config.m_SvSpectatorSlots) - Server()->Kick(i, "Kicked for inactivity"); - else - GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); - } - break; - case 2: - { - // kick the player + { + // move player to spectator if the reserved slots aren't filled yet, kick him otherwise + int Spectators = 0; + for(int j = 0; j < MAX_CLIENTS; ++j) + if(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS) + ++Spectators; + if(Spectators >= g_Config.m_SvSpectatorSlots) Server()->Kick(i, "Kicked for inactivity"); - } + else + GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); + } + break; + case 2: + { + // kick the player + Server()->Kick(i, "Kicked for inactivity"); + } } } } @@ -510,7 +501,7 @@ void IGameController::Snap(int SnappingClient) pGameInfoObj->m_WarmupTimer = m_Warmup; pGameInfoObj->m_RoundNum = 0; - pGameInfoObj->m_RoundCurrent = m_RoundCount+1; + pGameInfoObj->m_RoundCurrent = m_RoundCount + 1; CCharacter *pChr; CPlayer *pPlayer = SnappingClient > -1 ? GameServer()->m_apPlayers[SnappingClient] : 0; @@ -518,9 +509,7 @@ void IGameController::Snap(int SnappingClient) if(pPlayer && (pPlayer->m_TimerType == CPlayer::TIMERTYPE_GAMETIMER || pPlayer->m_TimerType == CPlayer::TIMERTYPE_GAMETIMER_AND_BROADCAST) && pPlayer->GetClientVersion() >= VERSION_DDNET_GAMETICK) { - if((pPlayer->GetTeam() == -1 || pPlayer->IsPaused()) - && pPlayer->m_SpectatorID != SPEC_FREEVIEW - && (pPlayer2 = GameServer()->m_apPlayers[pPlayer->m_SpectatorID])) + if((pPlayer->GetTeam() == -1 || pPlayer->IsPaused()) && pPlayer->m_SpectatorID != SPEC_FREEVIEW && (pPlayer2 = GameServer()->m_apPlayers[pPlayer->m_SpectatorID])) { if((pChr = pPlayer2->GetCharacter()) && pChr->m_DDRaceState == DDRACE_STARTED) { @@ -595,7 +584,7 @@ int IGameController::GetAutoTeam(int NotThisID) return 0; #endif - int aNumplayers[2] = {0,0}; + int aNumplayers[2] = {0, 0}; for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i] && i != NotThisID) @@ -617,7 +606,7 @@ bool IGameController::CanJoinTeam(int Team, int NotThisID) if(Team == TEAM_SPECTATORS || (GameServer()->m_apPlayers[NotThisID] && GameServer()->m_apPlayers[NotThisID]->GetTeam() != TEAM_SPECTATORS)) return true; - int aNumplayers[2] = {0,0}; + int aNumplayers[2] = {0, 0}; for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i] && i != NotThisID) @@ -627,7 +616,7 @@ bool IGameController::CanJoinTeam(int Team, int NotThisID) } } - return (aNumplayers[0] + aNumplayers[1]) < Server()->MaxClients()-g_Config.m_SvSpectatorSlots; + return (aNumplayers[0] + aNumplayers[1]) < Server()->MaxClients() - g_Config.m_SvSpectatorSlots; } int IGameController::ClampTeam(int Team) diff --git a/src/game/server/gamecontroller.h b/src/game/server/gamecontroller.h index 79ef92839..600fdfde1 100644 --- a/src/game/server/gamecontroller.h +++ b/src/game/server/gamecontroller.h @@ -41,7 +41,7 @@ protected: { m_Got = false; m_FriendlyTeam = -1; - m_Pos = vec2(100,100); + m_Pos = vec2(100, 100); } vec2 m_Pos; @@ -57,7 +57,6 @@ protected: char m_aMapWish[MAX_MAP_LENGTH]; - int m_RoundStartTick; int m_GameOverTick; int m_SuddenDeath; @@ -130,7 +129,6 @@ public: */ virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); - // virtual bool CanSpawn(int Team, vec2 *pPos); diff --git a/src/game/server/gamemodes/DDRace.cpp b/src/game/server/gamemodes/DDRace.cpp index 5d70058c9..d6c9e1de5 100644 --- a/src/game/server/gamemodes/DDRace.cpp +++ b/src/game/server/gamemodes/DDRace.cpp @@ -1,16 +1,16 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ /* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +#include "DDRace.h" +#include "gamemode.h" #include #include #include #include -#include #include -#include "DDRace.h" -#include "gamemode.h" +#include CGameControllerDDRace::CGameControllerDDRace(class CGameContext *pGameServer) : - IGameController(pGameServer), m_Teams(pGameServer), m_pInitResult(nullptr) + IGameController(pGameServer), m_Teams(pGameServer), m_pInitResult(nullptr) { m_pGameType = g_Config.m_SvTestingCommands ? TEST_NAME : GAME_NAME; @@ -39,26 +39,26 @@ void CGameControllerDDRace::Tick() void CGameControllerDDRace::InitTeleporter() { - if (!GameServer()->Collision()->Layers()->TeleLayer()) + if(!GameServer()->Collision()->Layers()->TeleLayer()) return; int Width = GameServer()->Collision()->Layers()->TeleLayer()->m_Width; int Height = GameServer()->Collision()->Layers()->TeleLayer()->m_Height; - for (int i = 0; i < Width * Height; i++) + for(int i = 0; i < Width * Height; i++) { int Number = GameServer()->Collision()->TeleLayer()[i].m_Number; int Type = GameServer()->Collision()->TeleLayer()[i].m_Type; - if (Number > 0) + if(Number > 0) { - if (Type == TILE_TELEOUT) + if(Type == TILE_TELEOUT) { m_TeleOuts[Number - 1].push_back( - vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); } - else if (Type == TILE_TELECHECKOUT) + else if(Type == TILE_TELECHECKOUT) { m_TeleCheckOuts[Number - 1].push_back( - vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); } } } diff --git a/src/game/server/gamemodes/DDRace.h b/src/game/server/gamemodes/DDRace.h index 68737a50c..ad3846d79 100644 --- a/src/game/server/gamemodes/DDRace.h +++ b/src/game/server/gamemodes/DDRace.h @@ -1,25 +1,24 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ #ifndef GAME_SERVER_GAMEMODES_DDRACE_H #define GAME_SERVER_GAMEMODES_DDRACE_H +#include #include #include -#include -#include #include +#include struct CScoreInitResult; -class CGameControllerDDRace: public IGameController +class CGameControllerDDRace : public IGameController { public: - CGameControllerDDRace(class CGameContext *pGameServer); ~CGameControllerDDRace(); CGameTeams m_Teams; - std::map > m_TeleOuts; - std::map > m_TeleCheckOuts; + std::map> m_TeleOuts; + std::map> m_TeleCheckOuts; void InitTeleporter(); virtual void Tick(); diff --git a/src/game/server/gameworld.cpp b/src/game/server/gameworld.cpp index 9413a41b9..538b2f2cc 100644 --- a/src/game/server/gameworld.cpp +++ b/src/game/server/gameworld.cpp @@ -5,8 +5,8 @@ #include "entity.h" #include "gamecontext.h" #include -#include #include +#include ////////////////////////////////////////////////// // game world @@ -47,9 +47,9 @@ int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, return 0; int Num = 0; - for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) + for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) { - if(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius) + if(distance(pEnt->m_Pos, Pos) < Radius + pEnt->m_ProximityRadius) { if(ppEnts) ppEnts[Num] = pEnt; @@ -108,7 +108,7 @@ void CGameWorld::RemoveEntity(CEntity *pEnt) void CGameWorld::Snap(int SnappingClient) { for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Snap(SnappingClient); @@ -120,7 +120,7 @@ void CGameWorld::Reset() { // reset all entities for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Reset(); @@ -138,7 +138,7 @@ void CGameWorld::RemoveEntities() { // destroy objects marked for destruction for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; if(pEnt->m_MarkedForDestroy) @@ -150,38 +150,40 @@ void CGameWorld::RemoveEntities() } } -bool distCompare(std::pair a, std::pair b) +bool distCompare(std::pair a, std::pair b) { return (a.first < b.first); } void CGameWorld::UpdatePlayerMaps() { - if (Server()->Tick() % g_Config.m_SvMapUpdateRate != 0) return; + if(Server()->Tick() % g_Config.m_SvMapUpdateRate != 0) + return; - std::pair Dist[MAX_CLIENTS]; - for (int i = 0; i < MAX_CLIENTS; i++) + std::pair Dist[MAX_CLIENTS]; + for(int i = 0; i < MAX_CLIENTS; i++) { - if (!Server()->ClientIngame(i)) continue; + if(!Server()->ClientIngame(i)) + continue; int *pMap = Server()->GetIdMap(i); // compute distances - for (int j = 0; j < MAX_CLIENTS; j++) + for(int j = 0; j < MAX_CLIENTS; j++) { Dist[j].second = j; - if (!Server()->ClientIngame(j) || !GameServer()->m_apPlayers[j]) + if(!Server()->ClientIngame(j) || !GameServer()->m_apPlayers[j]) { Dist[j].first = 1e10; continue; } - CCharacter* ch = GameServer()->m_apPlayers[j]->GetCharacter(); - if (!ch) + CCharacter *ch = GameServer()->m_apPlayers[j]->GetCharacter(); + if(!ch) { Dist[j].first = 1e9; continue; } // copypasted chunk from character.cpp Snap() follows - CCharacter* SnapChar = GameServer()->GetPlayerChar(i); + CCharacter *SnapChar = GameServer()->GetPlayerChar(i); if(SnapChar && !SnapChar->m_Super && !GameServer()->m_apPlayers[i]->IsPaused() && GameServer()->m_apPlayers[i]->GetTeam() != -1 && !ch->CanCollide(i) && @@ -202,35 +204,40 @@ void CGameWorld::UpdatePlayerMaps() // compute reverse map int rMap[MAX_CLIENTS]; - for (int j = 0; j < MAX_CLIENTS; j++) + for(int j = 0; j < MAX_CLIENTS; j++) { rMap[j] = -1; } - for (int j = 0; j < VANILLA_MAX_CLIENTS; j++) + for(int j = 0; j < VANILLA_MAX_CLIENTS; j++) { - if (pMap[j] == -1) continue; - if (Dist[pMap[j]].first > 5e9) pMap[j] = -1; - else rMap[pMap[j]] = j; + if(pMap[j] == -1) + continue; + if(Dist[pMap[j]].first > 5e9) + pMap[j] = -1; + else + rMap[pMap[j]] = j; } std::nth_element(&Dist[0], &Dist[VANILLA_MAX_CLIENTS - 1], &Dist[MAX_CLIENTS], distCompare); int Mapc = 0; int Demand = 0; - for (int j = 0; j < VANILLA_MAX_CLIENTS - 1; j++) + for(int j = 0; j < VANILLA_MAX_CLIENTS - 1; j++) { int k = Dist[j].second; - if (rMap[k] != -1 || Dist[j].first > 5e9) continue; - while (Mapc < VANILLA_MAX_CLIENTS && pMap[Mapc] != -1) Mapc++; - if (Mapc < VANILLA_MAX_CLIENTS - 1) + if(rMap[k] != -1 || Dist[j].first > 5e9) + continue; + while(Mapc < VANILLA_MAX_CLIENTS && pMap[Mapc] != -1) + Mapc++; + if(Mapc < VANILLA_MAX_CLIENTS - 1) pMap[Mapc] = k; else Demand++; } - for (int j = MAX_CLIENTS - 1; j > VANILLA_MAX_CLIENTS - 2; j--) + for(int j = MAX_CLIENTS - 1; j > VANILLA_MAX_CLIENTS - 2; j--) { int k = Dist[j].second; - if (rMap[k] != -1 && Demand-- > 0) + if(rMap[k] != -1 && Demand-- > 0) pMap[rMap[k]] = -1; } pMap[VANILLA_MAX_CLIENTS - 1] = -1; // player with empty name to say chat msgs @@ -248,7 +255,7 @@ void CGameWorld::Tick() GameServer()->SendChat(-1, CGameContext::CHAT_ALL, "Teams have been balanced"); // update all objects for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Tick(); @@ -256,7 +263,7 @@ void CGameWorld::Tick() } for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->TickDefered(); @@ -267,7 +274,7 @@ void CGameWorld::Tick() { // update all objects for(int i = 0; i < NUM_ENTTYPES; i++) - for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt;) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->TickPaused(); @@ -281,7 +288,7 @@ void CGameWorld::Tick() // find the characters' strong/weak id int StrongWeakID = 0; - for(CCharacter *pChar = (CCharacter*) FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter*) pChar->TypeNext()) + for(CCharacter *pChar = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); pChar; pChar = (CCharacter *)pChar->TypeNext()) { pChar->m_StrongWeakID = StrongWeakID; StrongWeakID++; @@ -290,7 +297,7 @@ void CGameWorld::Tick() // TODO: should be more general //CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CEntity *pNotThis) -CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CCharacter *pNotThis, int CollideWith, class CCharacter *pThisOnly) +CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, CCharacter *pNotThis, int CollideWith, class CCharacter *pThisOnly) { // Find other players float ClosestLen = distance(Pos0, Pos1) * 100.0f; @@ -310,7 +317,7 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos); float Len = distance(p->m_Pos, IntersectPos); - if(Len < p->m_ProximityRadius+Radius) + if(Len < p->m_ProximityRadius + Radius) { Len = distance(Pos0, IntersectPos); if(Len < ClosestLen) @@ -325,11 +332,10 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v return pClosest; } - CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotThis) { // Find other players - float ClosestRange = Radius*2; + float ClosestRange = Radius * 2; CCharacter *pClosest = 0; CCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(ENTTYPE_CHARACTER); @@ -339,7 +345,7 @@ CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotTh continue; float Len = distance(Pos, p->m_Pos); - if(Len < p->m_ProximityRadius+Radius) + if(Len < p->m_ProximityRadius + Radius) { if(Len < ClosestRange) { @@ -354,7 +360,7 @@ CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotTh std::list CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, class CEntity *pNotThis) { - std::list< CCharacter * > listOfChars; + std::list listOfChars; CCharacter *pChr = (CCharacter *)FindFirst(CGameWorld::ENTTYPE_CHARACTER); for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) @@ -364,7 +370,7 @@ std::list CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, pChr->m_Pos); float Len = distance(pChr->m_Pos, IntersectPos); - if(Len < pChr->m_ProximityRadius+Radius) + if(Len < pChr->m_ProximityRadius + Radius) { pChr->m_Intersection = IntersectPos; listOfChars.push_back(pChr); @@ -376,15 +382,15 @@ std::list CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 void CGameWorld::ReleaseHooked(int ClientID) { CCharacter *pChr = (CCharacter *)CGameWorld::FindFirst(CGameWorld::ENTTYPE_CHARACTER); - for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) + for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) + { + CCharacterCore *Core = pChr->Core(); + if(Core->m_HookedPlayer == ClientID && !pChr->m_Super) { - CCharacterCore* Core = pChr->Core(); - if(Core->m_HookedPlayer == ClientID && !pChr->m_Super) - { - Core->m_HookedPlayer = -1; - Core->m_HookState = HOOK_RETRACTED; - Core->m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; - Core->m_HookState = HOOK_RETRACTED; - } + Core->m_HookedPlayer = -1; + Core->m_HookState = HOOK_RETRACTED; + Core->m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + Core->m_HookState = HOOK_RETRACTED; } + } } diff --git a/src/game/server/gameworld.h b/src/game/server/gameworld.h index a433e7640..dcb16ee29 100644 --- a/src/game/server/gameworld.h +++ b/src/game/server/gameworld.h @@ -153,7 +153,6 @@ public: std::list IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis); void ReleaseHooked(int ClientID); - /* Function: interserct_CCharacters Finds all CCharacters that intersect the line. diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index c6675598b..5ad172c7f 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -1,15 +1,15 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include -#include #include "player.h" +#include +#include -#include #include "gamecontext.h" -#include -#include -#include #include "gamemodes/DDRace.h" +#include +#include +#include +#include #include MACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS) @@ -48,7 +48,7 @@ void CPlayer::Reset() m_WeakHookSpawn = false; int *pIdMap = Server()->GetIdMap(m_ClientID); - for (int i = 1;i < VANILLA_MAX_CLIENTS;i++) + for(int i = 1; i < VANILLA_MAX_CLIENTS; i++) { pIdMap[i] = -1; } @@ -85,14 +85,14 @@ void CPlayer::Reset() if(g_Config.m_Events) { time_t rawtime; - struct tm* timeinfo; + struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); - if ((timeinfo->tm_mon == 11 && timeinfo->tm_mday == 31) || (timeinfo->tm_mon == 0 && timeinfo->tm_mday == 1)) + if((timeinfo->tm_mon == 11 && timeinfo->tm_mday == 31) || (timeinfo->tm_mon == 0 && timeinfo->tm_mday == 1)) { // New Year m_DefEmote = EMOTE_HAPPY; } - else if ((timeinfo->tm_mon == 9 && timeinfo->tm_mday == 31) || (timeinfo->tm_mon == 10 && timeinfo->tm_mday == 1)) + else if((timeinfo->tm_mon == 9 && timeinfo->tm_mday == 31) || (timeinfo->tm_mon == 10 && timeinfo->tm_mday == 1)) { // Halloween m_DefEmote = EMOTE_ANGRY; m_Halloween = true; @@ -145,9 +145,9 @@ void CPlayer::Reset() static int PlayerFlags_SevenToSix(int Flags) { int Six = 0; - if(Flags&protocol7::PLAYERFLAG_CHATTING) + if(Flags & protocol7::PLAYERFLAG_CHATTING) Six |= PLAYERFLAG_CHATTING; - if(Flags&protocol7::PLAYERFLAG_SCOREBOARD) + if(Flags & protocol7::PLAYERFLAG_SCOREBOARD) Six |= PLAYERFLAG_SCOREBOARD; return Six; @@ -156,9 +156,9 @@ static int PlayerFlags_SevenToSix(int Flags) static int PlayerFlags_SixToSeven(int Flags) { int Seven = 0; - if(Flags&PLAYERFLAG_CHATTING) + if(Flags & PLAYERFLAG_CHATTING) Seven |= protocol7::PLAYERFLAG_CHATTING; - if(Flags&PLAYERFLAG_SCOREBOARD) + if(Flags & PLAYERFLAG_SCOREBOARD) Seven |= protocol7::PLAYERFLAG_SCOREBOARD; return Seven; @@ -167,13 +167,13 @@ static int PlayerFlags_SixToSeven(int Flags) void CPlayer::Tick() { #ifdef CONF_DEBUG - if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS-g_Config.m_DbgDummies) + if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS - g_Config.m_DbgDummies) #endif - if(m_ScoreQueryResult != nullptr && m_ScoreQueryResult.use_count() == 1) - { - ProcessScoreResult(*m_ScoreQueryResult); - m_ScoreQueryResult = nullptr; - } + if(m_ScoreQueryResult != nullptr && m_ScoreQueryResult.use_count() == 1) + { + ProcessScoreResult(*m_ScoreQueryResult); + m_ScoreQueryResult = nullptr; + } if(m_ScoreFinishResult != nullptr && m_ScoreFinishResult.use_count() == 1) { ProcessScoreResult(*m_ScoreFinishResult); @@ -183,17 +183,17 @@ void CPlayer::Tick() if(!Server()->ClientIngame(m_ClientID)) return; - if (m_ChatScore > 0) + if(m_ChatScore > 0) m_ChatScore--; Server()->SetClientScore(m_ClientID, m_Score); - if (m_Moderating && m_Afk) + if(m_Moderating && m_Afk) { m_Moderating = false; GameServer()->SendChatTarget(m_ClientID, "Active moderator mode disabled because you are afk."); - if (!GameServer()->PlayerModerating()) + if(!GameServer()->PlayerModerating()) GameServer()->SendChat(-1, CGameContext::CHAT_ALL, "Server kick/spec votes are no longer actively moderated."); } @@ -207,9 +207,9 @@ void CPlayer::Tick() m_Latency.m_AccumMin = minimum(m_Latency.m_AccumMin, Info.m_Latency); } // each second - if(Server()->Tick()%Server()->TickSpeed() == 0) + if(Server()->Tick() % Server()->TickSpeed() == 0) { - m_Latency.m_Avg = m_Latency.m_Accum/Server()->TickSpeed(); + m_Latency.m_Avg = m_Latency.m_Accum / Server()->TickSpeed(); m_Latency.m_Max = m_Latency.m_AccumMax; m_Latency.m_Min = m_Latency.m_AccumMin; m_Latency.m_Accum = 0; @@ -230,8 +230,8 @@ void CPlayer::Tick() if(!GameServer()->m_World.m_Paused) { - int EarliestRespawnTick = m_PreviousDieTick+Server()->TickSpeed()*3; - int RespawnTick = maximum(m_DieTick, EarliestRespawnTick)+2; + int EarliestRespawnTick = m_PreviousDieTick + Server()->TickSpeed() * 3; + int RespawnTick = maximum(m_DieTick, EarliestRespawnTick) + 2; if(!m_pCharacter && RespawnTick <= Server()->Tick()) m_Spawning = true; @@ -265,7 +265,7 @@ void CPlayer::Tick() int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_ViewPos); m_TuneZone = GameServer()->Collision()->IsTune(CurrentIndex); - if (m_TuneZone != m_TuneZoneOld) // don't send tunings all the time + if(m_TuneZone != m_TuneZoneOld) // don't send tunings all the time { GameServer()->SendTuningParams(m_ClientID, m_TuneZone); } @@ -274,7 +274,7 @@ void CPlayer::Tick() void CPlayer::PostTick() { // update latency value - if(m_PlayerFlags&PLAYERFLAG_SCOREBOARD) + if(m_PlayerFlags & PLAYERFLAG_SCOREBOARD) { for(int i = 0; i < MAX_CLIENTS; ++i) { @@ -291,10 +291,10 @@ void CPlayer::PostTick() void CPlayer::PostPostTick() { #ifdef CONF_DEBUG - if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS-g_Config.m_DbgDummies) + if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS - g_Config.m_DbgDummies) #endif - if(!Server()->ClientIngame(m_ClientID)) - return; + if(!Server()->ClientIngame(m_ClientID)) + return; if(!GameServer()->m_World.m_Paused && !m_pCharacter && m_Spawning && m_WeakHookSpawn) TryRespawn(); @@ -303,10 +303,10 @@ void CPlayer::PostPostTick() void CPlayer::Snap(int SnappingClient) { #ifdef CONF_DEBUG - if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS-g_Config.m_DbgDummies) + if(!g_Config.m_DbgDummies || m_ClientID < MAX_CLIENTS - g_Config.m_DbgDummies) #endif - if(!Server()->ClientIngame(m_ClientID)) - return; + if(!Server()->ClientIngame(m_ClientID)) + return; int id = m_ClientID; if(SnappingClient > -1 && !Server()->Translate(id, SnappingClient)) @@ -485,11 +485,11 @@ void CPlayer::OnDisconnect(const char *pReason) // Set this to false, otherwise PlayerModerating() will return true. m_Moderating = false; - if (!GameServer()->PlayerModerating() && WasModerator) + if(!GameServer()->PlayerModerating() && WasModerator) GameServer()->SendChat(-1, CGameContext::CHAT_ALL, "Server kick/spec votes are no longer actively moderated."); } - CGameControllerDDRace* Controller = (CGameControllerDDRace*)GameServer()->m_pController; + CGameControllerDDRace *Controller = (CGameControllerDDRace *)GameServer()->m_pController; if(g_Config.m_SvTeam != 3) Controller->m_Teams.SetForceCharacterTeam(m_ClientID, TEAM_FLOCK); } @@ -497,7 +497,7 @@ void CPlayer::OnDisconnect(const char *pReason) void CPlayer::OnPredictedInput(CNetObj_PlayerInput *NewInput) { // skip the input if chat is active - if((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)) + if((m_PlayerFlags & PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags & PLAYERFLAG_CHATTING)) return; AfkVoteTimer(NewInput); @@ -529,10 +529,10 @@ void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) if(((!m_pCharacter && m_Team == TEAM_SPECTATORS) || m_Paused) && m_SpectatorID == SPEC_FREEVIEW) m_ViewPos = vec2(NewInput->m_TargetX, NewInput->m_TargetY); - if(NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) + if(NewInput->m_PlayerFlags & PLAYERFLAG_CHATTING) { - // skip the input if chat is active - if(m_PlayerFlags&PLAYERFLAG_CHATTING) + // skip the input if chat is active + if(m_PlayerFlags & PLAYERFLAG_CHATTING) return; // reset input @@ -548,13 +548,13 @@ void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) if(m_pCharacter && m_Paused) m_pCharacter->ResetInput(); - if(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1)) + if(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire & 1)) m_Spawning = true; // check for activity if(NewInput->m_Direction || m_LatestActivity.m_TargetX != NewInput->m_TargetX || m_LatestActivity.m_TargetY != NewInput->m_TargetY || NewInput->m_Jump || - NewInput->m_Fire&1 || NewInput->m_Hook) + NewInput->m_Fire & 1 || NewInput->m_Hook) { m_LatestActivity.m_TargetX = NewInput->m_TargetX; m_LatestActivity.m_TargetY = NewInput->m_TargetY; @@ -565,7 +565,7 @@ void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) void CPlayer::OnPredictedEarlyInput(CNetObj_PlayerInput *NewInput) { // skip the input if chat is active - if((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)) + if((m_PlayerFlags & PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags & PLAYERFLAG_CHATTING)) return; if(m_pCharacter && !m_Paused) @@ -604,7 +604,7 @@ void CPlayer::Respawn(bool WeakHook) } } -CCharacter* CPlayer::ForceSpawn(vec2 Pos) +CCharacter *CPlayer::ForceSpawn(vec2 Pos) { m_Spawning = false; m_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World); @@ -629,7 +629,7 @@ void CPlayer::SetTeam(int Team, bool DoChatMsg) if(Team == TEAM_SPECTATORS) { - CGameControllerDDRace* Controller = (CGameControllerDDRace*)GameServer()->m_pController; + CGameControllerDDRace *Controller = (CGameControllerDDRace *)GameServer()->m_pController; if(g_Config.m_SvTeam != 3) Controller->m_Teams.SetForceCharacterTeam(m_ClientID, TEAM_FLOCK); } @@ -650,7 +650,7 @@ void CPlayer::SetTeam(int Team, bool DoChatMsg) Msg.m_Team = m_Team; Msg.m_Silent = !DoChatMsg; Msg.m_CooldownTick = m_LastSetTeam + Server()->TickSpeed() * g_Config.m_SvTeamChangeDelay; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, -1); if(Team == TEAM_SPECTATORS) { @@ -749,34 +749,31 @@ bool CPlayer::AfkTimer(int NewTargetX, int NewTargetY) m_LastTarget_y = NewTargetY; m_Sent1stAfkWarning = 0; // afk timer's 1st warning after 50% of sv_max_afk_time m_Sent2ndAfkWarning = 0; - } else { if(!m_Paused) { // not playing, check how long - if(m_Sent1stAfkWarning == 0 && m_LastPlaytime < time_get()-time_freq()*(int)(g_Config.m_SvMaxAfkTime*0.5)) + if(m_Sent1stAfkWarning == 0 && m_LastPlaytime < time_get() - time_freq() * (int)(g_Config.m_SvMaxAfkTime * 0.5)) { str_format(m_pAfkMsg, sizeof(m_pAfkMsg), "You have been afk for %d seconds now. Please note that you get kicked after not playing for %d seconds.", - (int)(g_Config.m_SvMaxAfkTime*0.5), - g_Config.m_SvMaxAfkTime - ); + (int)(g_Config.m_SvMaxAfkTime * 0.5), + g_Config.m_SvMaxAfkTime); m_pGameServer->SendChatTarget(m_ClientID, m_pAfkMsg); m_Sent1stAfkWarning = 1; } - else if(m_Sent2ndAfkWarning == 0 && m_LastPlaytime < time_get()-time_freq()*(int)(g_Config.m_SvMaxAfkTime*0.9)) + else if(m_Sent2ndAfkWarning == 0 && m_LastPlaytime < time_get() - time_freq() * (int)(g_Config.m_SvMaxAfkTime * 0.9)) { str_format(m_pAfkMsg, sizeof(m_pAfkMsg), "You have been afk for %d seconds now. Please note that you get kicked after not playing for %d seconds.", - (int)(g_Config.m_SvMaxAfkTime*0.9), - g_Config.m_SvMaxAfkTime - ); + (int)(g_Config.m_SvMaxAfkTime * 0.9), + g_Config.m_SvMaxAfkTime); m_pGameServer->SendChatTarget(m_ClientID, m_pAfkMsg); m_Sent2ndAfkWarning = 1; } - else if(m_LastPlaytime < time_get()-time_freq()*g_Config.m_SvMaxAfkTime) + else if(m_LastPlaytime < time_get() - time_freq() * g_Config.m_SvMaxAfkTime) { m_pGameServer->Server()->Kick(m_ClientID, "Away from keyboard"); return true; @@ -803,7 +800,7 @@ void CPlayer::AfkVoteTimer(CNetObj_PlayerInput *NewTarget) m_LastPlaytime = time_get(); mem_copy(m_pLastTarget, NewTarget, sizeof(CNetObj_PlayerInput)); } - else if(m_LastPlaytime < time_get()-time_freq()*g_Config.m_SvMaxAfkVoteTime) + else if(m_LastPlaytime < time_get() - time_freq() * g_Config.m_SvMaxAfkVoteTime) { m_Afk = true; return; @@ -840,7 +837,8 @@ int CPlayer::Pause(int State, bool Force) if(State != m_Paused) { // Get to wanted state - switch(State){ + switch(State) + { case PAUSE_PAUSED: case PAUSE_NONE: if(m_pCharacter->IsPaused()) // First condition might be unnecessary @@ -874,7 +872,7 @@ int CPlayer::Pause(int State, bool Force) Msg.m_Silent = true; Msg.m_Team = m_Paused ? protocol7::TEAM_SPECTATORS : m_Team; - GameServer()->Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, m_ClientID); + GameServer()->Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, m_ClientID); } return m_Paused; @@ -953,20 +951,17 @@ void CPlayer::ProcessScoreResult(CScorePlayerResult &Result) char aCmd[256]; str_format(aCmd, sizeof(aCmd), - "sv_reset_file types/%s/flexreset.cfg; change_map \"%s\"", - Result.m_Data.m_MapVote.m_Server, Result.m_Data.m_MapVote.m_Map); + "sv_reset_file types/%s/flexreset.cfg; change_map \"%s\"", + Result.m_Data.m_MapVote.m_Server, Result.m_Data.m_MapVote.m_Map); char aChatmsg[512]; str_format(aChatmsg, sizeof(aChatmsg), "'%s' called vote to change server option '%s' (%s)", - Server()->ClientName(m_ClientID), Result.m_Data.m_MapVote.m_Map, "/map"); + Server()->ClientName(m_ClientID), Result.m_Data.m_MapVote.m_Map, "/map"); GameServer()->CallVote(m_ClientID, Result.m_Data.m_MapVote.m_Map, aCmd, "/map", aChatmsg); break; case CScorePlayerResult::PLAYER_INFO: - GameServer()->Score()->PlayerData(m_ClientID)->Set( - Result.m_Data.m_Info.m_Time, - Result.m_Data.m_Info.m_CpTime - ); + GameServer()->Score()->PlayerData(m_ClientID)->Set(Result.m_Data.m_Info.m_Time, Result.m_Data.m_Info.m_CpTime); m_Score = Result.m_Data.m_Info.m_Score; m_HasFinishScore = Result.m_Data.m_Info.m_HasFinishScore; // -9999 stands for no time and isn't displayed in scoreboard, so @@ -980,12 +975,12 @@ void CPlayer::ProcessScoreResult(CScorePlayerResult &Result) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "Happy DDNet birthday to %s for finishing their first map %d year%s ago!", - Server()->ClientName(m_ClientID), Birthday, Birthday > 1 ? "s" : ""); + "Happy DDNet birthday to %s for finishing their first map %d year%s ago!", + Server()->ClientName(m_ClientID), Birthday, Birthday > 1 ? "s" : ""); GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, m_ClientID); str_format(aBuf, sizeof(aBuf), - "Happy DDNet birthday, %s!\nYou have finished your first map exactly %d year%s ago!", - Server()->ClientName(m_ClientID), Birthday, Birthday > 1 ? "s" : ""); + "Happy DDNet birthday, %s!\nYou have finished your first map exactly %d year%s ago!", + Server()->ClientName(m_ClientID), Birthday, Birthday > 1 ? "s" : ""); GameServer()->SendBroadcast(aBuf, m_ClientID); } break; diff --git a/src/game/server/player.h b/src/game/server/player.h index a42af6d0f..9c88af166 100644 --- a/src/game/server/player.h +++ b/src/game/server/player.h @@ -5,9 +5,9 @@ // this include should perhaps be removed #include "entities/character.h" +#include "gamecontext.h" #include "score.h" #include "teeinfo.h" -#include "gamecontext.h" #include // player object @@ -25,8 +25,8 @@ public: void TryRespawn(); void Respawn(bool WeakHook = false); // with WeakHook == true the character will be spawned after all calls of Tick from other Players - CCharacter* ForceSpawn(vec2 Pos); // required for loading savegames - void SetTeam(int Team, bool DoChatMsg=true); + CCharacter *ForceSpawn(vec2 Pos); // required for loading savegames + void SetTeam(int Team, bool DoChatMsg = true); int GetTeam() const { return m_Team; }; int GetCID() const { return m_ClientID; }; int GetClientVersion() const; @@ -134,15 +134,15 @@ private: public: enum { - PAUSE_NONE=0, + PAUSE_NONE = 0, PAUSE_PAUSED, PAUSE_SPEC }; enum { - TIMERTYPE_DEFAULT=-1, - TIMERTYPE_GAMETIMER=0, + TIMERTYPE_DEFAULT = -1, + TIMERTYPE_GAMETIMER = 0, TIMERTYPE_BROADCAST, TIMERTYPE_GAMETIMER_AND_BROADCAST, TIMERTYPE_SIXUP, diff --git a/src/game/server/save.cpp b/src/game/server/save.cpp index 340d1ce43..3f3bf8cf5 100644 --- a/src/game/server/save.cpp +++ b/src/game/server/save.cpp @@ -1,10 +1,10 @@ #include "save.h" -#include #include +#include -#include "teams.h" #include "gamemodes/DDRace.h" +#include "teams.h" #include CSaveTee::CSaveTee() @@ -27,7 +27,7 @@ void CSaveTee::save(CCharacter *pChr) m_TeeFinished = pChr->Teams()->TeeFinished(m_ClientID); m_IsSolo = pChr->m_Solo; - for(int i = 0; i< NUM_WEAPONS; i++) + for(int i = 0; i < NUM_WEAPONS; i++) { m_aWeapons[i].m_AmmoRegenStart = pChr->m_aWeapons[i].m_AmmoRegenStart; m_aWeapons[i].m_Ammo = pChr->m_aWeapons[i].m_Ammo; @@ -101,7 +101,7 @@ void CSaveTee::save(CCharacter *pChr) m_InputFire = pChr->m_SavedInput.m_Fire; m_InputHook = pChr->m_SavedInput.m_Hook; - m_ReloadTimer = pChr->m_ReloadTimer; + m_ReloadTimer = pChr->m_ReloadTimer; FormatUuid(pChr->GameServer()->GameUuid(), m_aGameUuid, sizeof(m_aGameUuid)); } @@ -116,7 +116,7 @@ void CSaveTee::load(CCharacter *pChr, int Team) pChr->Teams()->SetForceCharacterTeam(pChr->m_pPlayer->GetCID(), Team); pChr->Teams()->SetFinished(pChr->m_pPlayer->GetCID(), m_TeeFinished); - for(int i = 0; i< NUM_WEAPONS; i++) + for(int i = 0; i < NUM_WEAPONS; i++) { pChr->m_aWeapons[i].m_AmmoRegenStart = m_aWeapons[i].m_AmmoRegenStart; // m_Ammo not used anymore for tracking freeze following https://github.com/ddnet/ddnet/pull/2086 @@ -153,7 +153,7 @@ void CSaveTee::load(CCharacter *pChr, int Team) if(m_CpTime) pChr->m_CpTick = pChr->Server()->Tick() - m_CpTime; - pChr->m_CpActive = m_CpActive; + pChr->m_CpActive = m_CpActive; pChr->m_CpLastBroadcast = m_CpLastBroadcast; for(int i = 0; i < 25; i++) @@ -205,7 +205,7 @@ void CSaveTee::load(CCharacter *pChr, int Team) pChr->SetRescue(); } -char* CSaveTee::GetString(const CSaveTeam *pTeam) +char *CSaveTee::GetString(const CSaveTeam *pTeam) { // Add time penalty of 60 seconds (only to the database) int Time = m_Time + 60 * SERVER_TICK_SPEED; @@ -224,138 +224,136 @@ char* CSaveTee::GetString(const CSaveTeam *pTeam) } str_format(m_aString, sizeof(m_aString), - "%s\t%d\t%d\t%d\t%d\t%d\t" - // weapons - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t" - // tee stats - "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_SuperJump - "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_DDRaceState - "%d\t%d\t%d\t%d\t" // m_Pos.x - "%d\t%d\t" // m_TeleCheckpoint - "%d\t%d\t%f\t%f\t" // m_CorePos.x - "%d\t%d\t%d\t%d\t" // m_ActiveWeapon - "%d\t%d\t%f\t%f\t" // m_HookPos.x - "%d\t%d\t%d\t%d\t" // m_HookTeleBase.x - // time checkpoints - "%d\t%d\t%d\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%d\t" - "%d\t%d\t%d\t" - "%s\t" - "%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d", - m_aName, m_Alive, m_Paused, m_NeededFaketuning, m_TeeFinished, m_IsSolo, - // weapons - m_aWeapons[0].m_AmmoRegenStart, m_aWeapons[0].m_Ammo, m_aWeapons[0].m_Ammocost, m_aWeapons[0].m_Got, - m_aWeapons[1].m_AmmoRegenStart, m_aWeapons[1].m_Ammo, m_aWeapons[1].m_Ammocost, m_aWeapons[1].m_Got, - m_aWeapons[2].m_AmmoRegenStart, m_aWeapons[2].m_Ammo, m_aWeapons[2].m_Ammocost, m_aWeapons[2].m_Got, - m_aWeapons[3].m_AmmoRegenStart, m_aWeapons[3].m_Ammo, m_aWeapons[3].m_Ammocost, m_aWeapons[3].m_Got, - m_aWeapons[4].m_AmmoRegenStart, m_aWeapons[4].m_Ammo, m_aWeapons[4].m_Ammocost, m_aWeapons[4].m_Got, - m_aWeapons[5].m_AmmoRegenStart, m_aWeapons[5].m_Ammo, m_aWeapons[5].m_Ammocost, m_aWeapons[5].m_Got, - m_LastWeapon, m_QueuedWeapon, - // tee states - m_SuperJump, m_Jetpack, m_NinjaJetpack, m_FreezeTime, m_FreezeTick, m_DeepFreeze, m_EndlessHook, - m_DDRaceState, m_Hit, m_Collision, m_TuneZone, m_TuneZoneOld, m_Hook, Time, - (int)m_Pos.x, (int)m_Pos.y, (int)m_PrevPos.x, (int)m_PrevPos.y, - m_TeleCheckpoint, m_LastPenalty, - (int)m_CorePos.x, (int)m_CorePos.y, m_Vel.x, m_Vel.y, - m_ActiveWeapon, m_Jumped, m_JumpedTotal, m_Jumps, - (int)m_HookPos.x, (int)m_HookPos.y, m_HookDir.x, m_HookDir.y, - (int)m_HookTeleBase.x, (int)m_HookTeleBase.y, m_HookTick, m_HookState, - // time checkpoints - m_CpTime, m_CpActive, m_CpLastBroadcast, - m_aCpCurrent[0], m_aCpCurrent[1], m_aCpCurrent[2], m_aCpCurrent[3], m_aCpCurrent[4], - m_aCpCurrent[5], m_aCpCurrent[6], m_aCpCurrent[7], m_aCpCurrent[8], m_aCpCurrent[9], - m_aCpCurrent[10], m_aCpCurrent[11], m_aCpCurrent[12], m_aCpCurrent[13], m_aCpCurrent[14], - m_aCpCurrent[15], m_aCpCurrent[16], m_aCpCurrent[17], m_aCpCurrent[18], m_aCpCurrent[19], - m_aCpCurrent[20], m_aCpCurrent[21], m_aCpCurrent[22], m_aCpCurrent[23], m_aCpCurrent[24], - m_NotEligibleForFinish, - m_HasTelegunGun, m_HasTelegunLaser, m_HasTelegunGrenade, - m_aGameUuid, - HookedPlayer, m_NewHook, - m_InputDirection, m_InputJump, m_InputFire, m_InputHook, - m_ReloadTimer - ); + "%s\t%d\t%d\t%d\t%d\t%d\t" + // weapons + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t" + // tee stats + "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_SuperJump + "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_DDRaceState + "%d\t%d\t%d\t%d\t" // m_Pos.x + "%d\t%d\t" // m_TeleCheckpoint + "%d\t%d\t%f\t%f\t" // m_CorePos.x + "%d\t%d\t%d\t%d\t" // m_ActiveWeapon + "%d\t%d\t%f\t%f\t" // m_HookPos.x + "%d\t%d\t%d\t%d\t" // m_HookTeleBase.x + // time checkpoints + "%d\t%d\t%d\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%d\t" + "%d\t%d\t%d\t" + "%s\t" + "%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d", + m_aName, m_Alive, m_Paused, m_NeededFaketuning, m_TeeFinished, m_IsSolo, + // weapons + m_aWeapons[0].m_AmmoRegenStart, m_aWeapons[0].m_Ammo, m_aWeapons[0].m_Ammocost, m_aWeapons[0].m_Got, + m_aWeapons[1].m_AmmoRegenStart, m_aWeapons[1].m_Ammo, m_aWeapons[1].m_Ammocost, m_aWeapons[1].m_Got, + m_aWeapons[2].m_AmmoRegenStart, m_aWeapons[2].m_Ammo, m_aWeapons[2].m_Ammocost, m_aWeapons[2].m_Got, + m_aWeapons[3].m_AmmoRegenStart, m_aWeapons[3].m_Ammo, m_aWeapons[3].m_Ammocost, m_aWeapons[3].m_Got, + m_aWeapons[4].m_AmmoRegenStart, m_aWeapons[4].m_Ammo, m_aWeapons[4].m_Ammocost, m_aWeapons[4].m_Got, + m_aWeapons[5].m_AmmoRegenStart, m_aWeapons[5].m_Ammo, m_aWeapons[5].m_Ammocost, m_aWeapons[5].m_Got, + m_LastWeapon, m_QueuedWeapon, + // tee states + m_SuperJump, m_Jetpack, m_NinjaJetpack, m_FreezeTime, m_FreezeTick, m_DeepFreeze, m_EndlessHook, + m_DDRaceState, m_Hit, m_Collision, m_TuneZone, m_TuneZoneOld, m_Hook, Time, + (int)m_Pos.x, (int)m_Pos.y, (int)m_PrevPos.x, (int)m_PrevPos.y, + m_TeleCheckpoint, m_LastPenalty, + (int)m_CorePos.x, (int)m_CorePos.y, m_Vel.x, m_Vel.y, + m_ActiveWeapon, m_Jumped, m_JumpedTotal, m_Jumps, + (int)m_HookPos.x, (int)m_HookPos.y, m_HookDir.x, m_HookDir.y, + (int)m_HookTeleBase.x, (int)m_HookTeleBase.y, m_HookTick, m_HookState, + // time checkpoints + m_CpTime, m_CpActive, m_CpLastBroadcast, + m_aCpCurrent[0], m_aCpCurrent[1], m_aCpCurrent[2], m_aCpCurrent[3], m_aCpCurrent[4], + m_aCpCurrent[5], m_aCpCurrent[6], m_aCpCurrent[7], m_aCpCurrent[8], m_aCpCurrent[9], + m_aCpCurrent[10], m_aCpCurrent[11], m_aCpCurrent[12], m_aCpCurrent[13], m_aCpCurrent[14], + m_aCpCurrent[15], m_aCpCurrent[16], m_aCpCurrent[17], m_aCpCurrent[18], m_aCpCurrent[19], + m_aCpCurrent[20], m_aCpCurrent[21], m_aCpCurrent[22], m_aCpCurrent[23], m_aCpCurrent[24], + m_NotEligibleForFinish, + m_HasTelegunGun, m_HasTelegunLaser, m_HasTelegunGrenade, + m_aGameUuid, + HookedPlayer, m_NewHook, + m_InputDirection, m_InputJump, m_InputFire, m_InputHook, + m_ReloadTimer); return m_aString; } -int CSaveTee::FromString(const char* String) +int CSaveTee::FromString(const char *String) { int Num; Num = sscanf(String, - "%[^\t]\t%d\t%d\t%d\t%d\t%d\t" - // weapons - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t%d\t%d\t" - "%d\t%d\t" - // tee states - "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_SuperJump - "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_DDRaceState - "%f\t%f\t%f\t%f\t" // m_Pos.x - "%d\t%d\t" // m_TeleCheckpoint - "%f\t%f\t%f\t%f\t" // m_CorePos.x - "%d\t%d\t%d\t%d\t" // m_ActiveWeapon - "%f\t%f\t%f\t%f\t" // m_HookPos.x - "%f\t%f\t%d\t%d\t" // m_HookTeleBase.x - // time checkpoints - "%d\t%d\t%d\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%f\t%f\t%f\t%f\t%f\t" - "%d\t" - "%d\t%d\t%d\t" - "%*s\t" // discard the game uuid - "%d\t%d" - "%d\t%d\t%d\t%d\t" - "%d", - m_aName, &m_Alive, &m_Paused, &m_NeededFaketuning, &m_TeeFinished, &m_IsSolo, - // weapons - &m_aWeapons[0].m_AmmoRegenStart, &m_aWeapons[0].m_Ammo, &m_aWeapons[0].m_Ammocost, &m_aWeapons[0].m_Got, - &m_aWeapons[1].m_AmmoRegenStart, &m_aWeapons[1].m_Ammo, &m_aWeapons[1].m_Ammocost, &m_aWeapons[1].m_Got, - &m_aWeapons[2].m_AmmoRegenStart, &m_aWeapons[2].m_Ammo, &m_aWeapons[2].m_Ammocost, &m_aWeapons[2].m_Got, - &m_aWeapons[3].m_AmmoRegenStart, &m_aWeapons[3].m_Ammo, &m_aWeapons[3].m_Ammocost, &m_aWeapons[3].m_Got, - &m_aWeapons[4].m_AmmoRegenStart, &m_aWeapons[4].m_Ammo, &m_aWeapons[4].m_Ammocost, &m_aWeapons[4].m_Got, - &m_aWeapons[5].m_AmmoRegenStart, &m_aWeapons[5].m_Ammo, &m_aWeapons[5].m_Ammocost, &m_aWeapons[5].m_Got, - &m_LastWeapon, &m_QueuedWeapon, - // tee states - &m_SuperJump, &m_Jetpack, &m_NinjaJetpack, &m_FreezeTime, &m_FreezeTick, &m_DeepFreeze, &m_EndlessHook, - &m_DDRaceState, &m_Hit, &m_Collision, &m_TuneZone, &m_TuneZoneOld, &m_Hook, &m_Time, - &m_Pos.x, &m_Pos.y, &m_PrevPos.x, &m_PrevPos.y, - &m_TeleCheckpoint, &m_LastPenalty, - &m_CorePos.x, &m_CorePos.y, &m_Vel.x, &m_Vel.y, - &m_ActiveWeapon, &m_Jumped, &m_JumpedTotal, &m_Jumps, - &m_HookPos.x, &m_HookPos.y, &m_HookDir.x, &m_HookDir.y, - &m_HookTeleBase.x, &m_HookTeleBase.y, &m_HookTick, &m_HookState, - // time checkpoints - &m_CpTime, &m_CpActive, &m_CpLastBroadcast, - &m_aCpCurrent[0], &m_aCpCurrent[1], &m_aCpCurrent[2], &m_aCpCurrent[3], &m_aCpCurrent[4], - &m_aCpCurrent[5], &m_aCpCurrent[6], &m_aCpCurrent[7], &m_aCpCurrent[8], &m_aCpCurrent[9], - &m_aCpCurrent[10], &m_aCpCurrent[11], &m_aCpCurrent[12], &m_aCpCurrent[13], &m_aCpCurrent[14], - &m_aCpCurrent[15], &m_aCpCurrent[16], &m_aCpCurrent[17], &m_aCpCurrent[18], &m_aCpCurrent[19], - &m_aCpCurrent[20], &m_aCpCurrent[21], &m_aCpCurrent[22], &m_aCpCurrent[23], &m_aCpCurrent[24], - &m_NotEligibleForFinish, - &m_HasTelegunGun, &m_HasTelegunLaser, &m_HasTelegunGrenade, - &m_HookedPlayer, &m_NewHook, - &m_InputDirection, &m_InputJump, &m_InputFire, &m_InputHook, - &m_ReloadTimer - ); + "%[^\t]\t%d\t%d\t%d\t%d\t%d\t" + // weapons + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t" + "%d\t%d\t" + // tee states + "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_SuperJump + "%d\t%d\t%d\t%d\t%d\t%d\t%d\t" // m_DDRaceState + "%f\t%f\t%f\t%f\t" // m_Pos.x + "%d\t%d\t" // m_TeleCheckpoint + "%f\t%f\t%f\t%f\t" // m_CorePos.x + "%d\t%d\t%d\t%d\t" // m_ActiveWeapon + "%f\t%f\t%f\t%f\t" // m_HookPos.x + "%f\t%f\t%d\t%d\t" // m_HookTeleBase.x + // time checkpoints + "%d\t%d\t%d\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%f\t%f\t%f\t%f\t%f\t" + "%d\t" + "%d\t%d\t%d\t" + "%*s\t" // discard the game uuid + "%d\t%d" + "%d\t%d\t%d\t%d\t" + "%d", + m_aName, &m_Alive, &m_Paused, &m_NeededFaketuning, &m_TeeFinished, &m_IsSolo, + // weapons + &m_aWeapons[0].m_AmmoRegenStart, &m_aWeapons[0].m_Ammo, &m_aWeapons[0].m_Ammocost, &m_aWeapons[0].m_Got, + &m_aWeapons[1].m_AmmoRegenStart, &m_aWeapons[1].m_Ammo, &m_aWeapons[1].m_Ammocost, &m_aWeapons[1].m_Got, + &m_aWeapons[2].m_AmmoRegenStart, &m_aWeapons[2].m_Ammo, &m_aWeapons[2].m_Ammocost, &m_aWeapons[2].m_Got, + &m_aWeapons[3].m_AmmoRegenStart, &m_aWeapons[3].m_Ammo, &m_aWeapons[3].m_Ammocost, &m_aWeapons[3].m_Got, + &m_aWeapons[4].m_AmmoRegenStart, &m_aWeapons[4].m_Ammo, &m_aWeapons[4].m_Ammocost, &m_aWeapons[4].m_Got, + &m_aWeapons[5].m_AmmoRegenStart, &m_aWeapons[5].m_Ammo, &m_aWeapons[5].m_Ammocost, &m_aWeapons[5].m_Got, + &m_LastWeapon, &m_QueuedWeapon, + // tee states + &m_SuperJump, &m_Jetpack, &m_NinjaJetpack, &m_FreezeTime, &m_FreezeTick, &m_DeepFreeze, &m_EndlessHook, + &m_DDRaceState, &m_Hit, &m_Collision, &m_TuneZone, &m_TuneZoneOld, &m_Hook, &m_Time, + &m_Pos.x, &m_Pos.y, &m_PrevPos.x, &m_PrevPos.y, + &m_TeleCheckpoint, &m_LastPenalty, + &m_CorePos.x, &m_CorePos.y, &m_Vel.x, &m_Vel.y, + &m_ActiveWeapon, &m_Jumped, &m_JumpedTotal, &m_Jumps, + &m_HookPos.x, &m_HookPos.y, &m_HookDir.x, &m_HookDir.y, + &m_HookTeleBase.x, &m_HookTeleBase.y, &m_HookTick, &m_HookState, + // time checkpoints + &m_CpTime, &m_CpActive, &m_CpLastBroadcast, + &m_aCpCurrent[0], &m_aCpCurrent[1], &m_aCpCurrent[2], &m_aCpCurrent[3], &m_aCpCurrent[4], + &m_aCpCurrent[5], &m_aCpCurrent[6], &m_aCpCurrent[7], &m_aCpCurrent[8], &m_aCpCurrent[9], + &m_aCpCurrent[10], &m_aCpCurrent[11], &m_aCpCurrent[12], &m_aCpCurrent[13], &m_aCpCurrent[14], + &m_aCpCurrent[15], &m_aCpCurrent[16], &m_aCpCurrent[17], &m_aCpCurrent[18], &m_aCpCurrent[19], + &m_aCpCurrent[20], &m_aCpCurrent[21], &m_aCpCurrent[22], &m_aCpCurrent[23], &m_aCpCurrent[24], + &m_NotEligibleForFinish, + &m_HasTelegunGun, &m_HasTelegunLaser, &m_HasTelegunGrenade, + &m_HookedPlayer, &m_NewHook, + &m_InputDirection, &m_InputJump, &m_InputFire, &m_InputHook, + &m_ReloadTimer); switch(Num) // Don't forget to update this when you save / load more / less. { case 96: @@ -393,7 +391,7 @@ void CSaveTee::LoadHookedPlayer(const CSaveTeam *pTeam) m_HookedPlayer = pTeam->m_pSavedTees[m_HookedPlayer].GetClientID(); } -CSaveTeam::CSaveTeam(IGameController* Controller) +CSaveTeam::CSaveTeam(IGameController *Controller) { m_pController = Controller; m_pSwitchers = 0; @@ -412,7 +410,7 @@ int CSaveTeam::save(int Team) { if(g_Config.m_SvTeam == 3 || (Team > 0 && Team < MAX_CLIENTS)) { - CGameTeams* Teams = &(((CGameControllerDDRace*)m_pController)->m_Teams); + CGameTeams *Teams = &(((CGameControllerDDRace *)m_pController)->m_Teams); m_MembersCount = Teams->Count(Team); if(m_MembersCount <= 0) @@ -448,9 +446,9 @@ int CSaveTeam::save(int Team) if(m_pController->GameServer()->Collision()->m_NumSwitchers) { - m_pSwitchers = new SSimpleSwitchers[m_pController->GameServer()->Collision()->m_NumSwitchers+1]; + m_pSwitchers = new SSimpleSwitchers[m_pController->GameServer()->Collision()->m_NumSwitchers + 1]; - for(int i=1; i < m_pController->GameServer()->Collision()->m_NumSwitchers+1; i++) + for(int i = 1; i < m_pController->GameServer()->Collision()->m_NumSwitchers + 1; i++) { m_pSwitchers[i].m_Status = m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Status[Team]; if(m_pController->GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team]) @@ -470,37 +468,37 @@ bool CSaveTeam::HandleSaveError(int Result, int ClientID, CGameContext *pGameCon { switch(Result) { - case 0: - return false; - case 1: - pGameContext->SendChatTarget(ClientID, "You have to be in a team (from 1-63)"); - break; - case 2: - pGameContext->SendChatTarget(ClientID, "Could not find your Team"); - break; - case 3: - pGameContext->SendChatTarget(ClientID, "Unable to find all Characters"); - break; - case 4: - pGameContext->SendChatTarget(ClientID, "Your team has not started yet"); - break; - default: // this state should never be reached - pGameContext->SendChatTarget(ClientID, "Unknown error while saving"); - break; + case 0: + return false; + case 1: + pGameContext->SendChatTarget(ClientID, "You have to be in a team (from 1-63)"); + break; + case 2: + pGameContext->SendChatTarget(ClientID, "Could not find your Team"); + break; + case 3: + pGameContext->SendChatTarget(ClientID, "Unable to find all Characters"); + break; + case 4: + pGameContext->SendChatTarget(ClientID, "Your team has not started yet"); + break; + default: // this state should never be reached + pGameContext->SendChatTarget(ClientID, "Unknown error while saving"); + break; } return true; } void CSaveTeam::load(int Team, bool KeepCurrentWeakStrong) { - CGameTeams* pTeams = &(((CGameControllerDDRace*)m_pController)->m_Teams); + CGameTeams *pTeams = &(((CGameControllerDDRace *)m_pController)->m_Teams); pTeams->ChangeTeamState(Team, m_TeamState); pTeams->SetTeamLock(Team, m_TeamLocked); if(m_Practice) pTeams->EnablePractice(Team); - for (int i = m_MembersCount; i-- > 0;) + for(int i = m_MembersCount; i-- > 0;) { int ClientID = m_pSavedTees[i].GetClientID(); if(m_pController->GameServer()->m_apPlayers[ClientID] && pTeams->m_Core.Team(ClientID) == Team) @@ -512,7 +510,7 @@ void CSaveTeam::load(int Team, bool KeepCurrentWeakStrong) if(m_pController->GameServer()->Collision()->m_NumSwitchers) { - for(int i=1; i < m_pController->GameServer()->Collision()->m_NumSwitchers+1; i++) + for(int i = 1; i < m_pController->GameServer()->Collision()->m_NumSwitchers + 1; i++) { m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Status[Team] = m_pSwitchers[i].m_Status; if(m_pSwitchers[i].m_EndTime) @@ -522,7 +520,7 @@ void CSaveTeam::load(int Team, bool KeepCurrentWeakStrong) } } -CCharacter* CSaveTeam::MatchCharacter(int ClientID, int SaveID, bool KeepCurrentCharacter) +CCharacter *CSaveTeam::MatchCharacter(int ClientID, int SaveID, bool KeepCurrentCharacter) { if(KeepCurrentCharacter && m_pController->GameServer()->m_apPlayers[ClientID]->GetCharacter()) { @@ -533,7 +531,7 @@ CCharacter* CSaveTeam::MatchCharacter(int ClientID, int SaveID, bool KeepCurrent return m_pController->GameServer()->m_apPlayers[ClientID]->ForceSpawn(m_pSavedTees[SaveID].GetPos()); } -char* CSaveTeam::GetString() +char *CSaveTeam::GetString() { str_format(m_aString, sizeof(m_aString), "%d\t%d\t%d\t%d\t%d", m_TeamState, m_MembersCount, m_NumSwitchers, m_TeamLocked, m_Practice); @@ -546,7 +544,7 @@ char* CSaveTeam::GetString() if(m_pSwitchers && m_NumSwitchers) { - for(int i=1; i < m_NumSwitchers+1; i++) + for(int i = 1; i < m_NumSwitchers + 1; i++) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "\n%d\t%d\t%d", m_pSwitchers[i].m_Status, m_pSwitchers[i].m_EndTime, m_pSwitchers[i].m_Type); @@ -557,20 +555,20 @@ char* CSaveTeam::GetString() return m_aString; } -int CSaveTeam::FromString(const char* String) +int CSaveTeam::FromString(const char *String) { char TeamStats[MAX_CLIENTS]; char Switcher[64]; char SaveTee[1024]; - char* CopyPos; + char *CopyPos; unsigned int Pos = 0; unsigned int LastPos = 0; unsigned int StrSize; str_copy(m_aString, String, sizeof(m_aString)); - while (m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 + while(m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 Pos++; CopyPos = m_aString + LastPos; @@ -593,15 +591,15 @@ int CSaveTeam::FromString(const char* String) int Num = sscanf(TeamStats, "%d\t%d\t%d\t%d\t%d", &m_TeamState, &m_MembersCount, &m_NumSwitchers, &m_TeamLocked, &m_Practice); switch(Num) // Don't forget to update this when you save / load more / less. { - case 4: - m_Practice = false; - // fallthrough - case 5: - break; - default: - dbg_msg("load", "failed to load teamstats"); - dbg_msg("load", "loaded %d vars", Num); - return Num + 1; // never 0 here + case 4: + m_Practice = false; + // fallthrough + case 5: + break; + default: + dbg_msg("load", "failed to load teamstats"); + dbg_msg("load", "loaded %d vars", Num); + return Num + 1; // never 0 here } } else @@ -612,16 +610,16 @@ int CSaveTeam::FromString(const char* String) if(m_pSavedTees) { - delete [] m_pSavedTees; + delete[] m_pSavedTees; m_pSavedTees = 0; } if(m_MembersCount) m_pSavedTees = new CSaveTee[m_MembersCount]; - for (int n = 0; n < m_MembersCount; n++) + for(int n = 0; n < m_MembersCount; n++) { - while (m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 + while(m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 Pos++; CopyPos = m_aString + LastPos; @@ -645,7 +643,7 @@ int CSaveTeam::FromString(const char* String) if(Num) { dbg_msg("load", "failed to load tee"); - dbg_msg("load", "loaded %d vars", Num-1); + dbg_msg("load", "loaded %d vars", Num - 1); return 1; } } @@ -658,16 +656,16 @@ int CSaveTeam::FromString(const char* String) if(m_pSwitchers) { - delete [] m_pSwitchers; + delete[] m_pSwitchers; m_pSwitchers = 0; } if(m_NumSwitchers) - m_pSwitchers = new SSimpleSwitchers[m_NumSwitchers+1]; + m_pSwitchers = new SSimpleSwitchers[m_NumSwitchers + 1]; - for (int n = 1; n < m_NumSwitchers+1; n++) + for(int n = 1; n < m_NumSwitchers + 1; n++) { - while (m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 + while(m_aString[Pos] != '\n' && Pos < sizeof(m_aString) && m_aString[Pos]) // find next \n or \0 Pos++; CopyPos = m_aString + LastPos; @@ -691,7 +689,7 @@ int CSaveTeam::FromString(const char* String) if(Num != 3) { dbg_msg("load", "failed to load switcher"); - dbg_msg("load", "loaded %d vars", Num-1); + dbg_msg("load", "loaded %d vars", Num - 1); } } else @@ -748,7 +746,7 @@ bool CSaveTeam::MatchPlayers(const char (*paNames)[MAX_NAME_LENGTH], const int * } } // match hook to correct ClientID - for (int n = 0; n < m_MembersCount; n++) + for(int n = 0; n < m_MembersCount; n++) m_pSavedTees[n].LoadHookedPlayer(this); return true; } diff --git a/src/game/server/save.h b/src/game/server/save.h index 16ec774bb..bc50ecf3d 100644 --- a/src/game/server/save.h +++ b/src/game/server/save.h @@ -15,21 +15,21 @@ class CSaveTee public: CSaveTee(); ~CSaveTee(); - void save(CCharacter* pchr); - void load(CCharacter* pchr, int Team); - char* GetString(const CSaveTeam *pTeam); - int FromString(const char* String); + void save(CCharacter *pchr); + void load(CCharacter *pchr, int Team); + char *GetString(const CSaveTeam *pTeam); + int FromString(const char *String); void LoadHookedPlayer(const CSaveTeam *pTeam); vec2 GetPos() const { return m_Pos; } - const char* GetName() const { return m_aName; } + const char *GetName() const { return m_aName; } int GetClientID() const { return m_ClientID; } void SetClientID(int ClientID) { m_ClientID = ClientID; }; private: int m_ClientID; - char m_aString [2048]; - char m_aName [16]; + char m_aString[2048]; + char m_aName[16]; int m_Alive; int m_Paused; @@ -110,24 +110,25 @@ private: class CSaveTeam { public: - CSaveTeam(IGameController* Controller); + CSaveTeam(IGameController *Controller); ~CSaveTeam(); - char* GetString(); + char *GetString(); int GetMembersCount() const { return m_MembersCount; } // MatchPlayers has to be called afterwards - int FromString(const char* String); + int FromString(const char *String); // returns true if a team can load, otherwise writes a nice error Message in pMessage bool MatchPlayers(const char (*paNames)[MAX_NAME_LENGTH], const int *pClientID, int NumPlayer, char *pMessage, int MessageLen); int save(int Team); void load(int Team, bool KeepCurrentWeakStrong); - CSaveTee* m_pSavedTees; + CSaveTee *m_pSavedTees; // returns true if an error occured static bool HandleSaveError(int Result, int ClientID, CGameContext *pGameContext); -private: - CCharacter* MatchCharacter(int ClientID, int SaveID, bool KeepCurrentWeakStrong); - IGameController* m_pController; +private: + CCharacter *MatchCharacter(int ClientID, int SaveID, bool KeepCurrentWeakStrong); + + IGameController *m_pController; char m_aString[65536]; @@ -137,7 +138,7 @@ private: int m_EndTime; int m_Type; }; - SSimpleSwitchers* m_pSwitchers; + SSimpleSwitchers *m_pSwitchers; int m_TeamState; int m_MembersCount; diff --git a/src/game/server/score.cpp b/src/game/server/score.cpp index 74fef7934..a74f7af82 100644 --- a/src/game/server/score.cpp +++ b/src/game/server/score.cpp @@ -12,10 +12,10 @@ #include #include -#include -#include -#include #include +#include +#include +#include CScorePlayerResult::CScorePlayerResult() : m_Done(false) @@ -98,11 +98,11 @@ std::shared_ptr CScore::NewSqlPlayerResult(int ClientID) } void CScore::ExecPlayerThread( - bool (*pFuncPtr) (IDbConnection *, const ISqlData *), - const char *pThreadName, - int ClientID, - const char *pName, - int Offset) + bool (*pFuncPtr)(IDbConnection *, const ISqlData *), + const char *pThreadName, + int ClientID, + const char *pName, + int Offset) { auto pResult = NewSqlPlayerResult(ClientID); if(pResult == nullptr) @@ -140,13 +140,13 @@ void CScore::GeneratePassphrase(char *pBuf, int BufSize) } CScore::CScore(CGameContext *pGameServer, CDbConnectionPool *pPool) : - m_pPool(pPool), - m_pGameServer(pGameServer), - m_pServer(pGameServer->Server()) + m_pPool(pPool), + m_pGameServer(pGameServer), + m_pServer(pGameServer->Server()) { auto InitResult = std::make_shared(); auto Tmp = std::unique_ptr(new CSqlInitData(InitResult)); - ((CGameControllerDDRace*)(pGameServer->m_pController))->m_pInitResult = InitResult; + ((CGameControllerDDRace *)(pGameServer->m_pController))->m_pInitResult = InitResult; str_copy(Tmp->m_Map, g_Config.m_SvMap, sizeof(Tmp->m_Map)); IOHANDLE File = GameServer()->Storage()->OpenFile("wordlist.txt", IOFLAG_READ, IStorage::TYPE_ALL); @@ -186,8 +186,8 @@ bool CScore::Init(IDbConnection *pSqlServer, const ISqlData *pGameData) char aBuf[512]; // get the best time str_format(aBuf, sizeof(aBuf), - "SELECT Time FROM %s_race WHERE Map=? ORDER BY `Time` ASC LIMIT 1;", - pSqlServer->GetPrefix()); + "SELECT Time FROM %s_race WHERE Map=? ORDER BY `Time` ASC LIMIT 1;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); @@ -212,14 +212,14 @@ bool CScore::LoadPlayerDataThread(IDbConnection *pSqlServer, const ISqlData *pGa char aBuf[512]; // get best race time str_format(aBuf, sizeof(aBuf), - "SELECT Time, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, " - " cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, " - " cp21, cp22, cp23, cp24, cp25 " - "FROM %s_race " - "WHERE Map = ? AND Name = ? " - "ORDER BY Time ASC " - "LIMIT 1;", - pSqlServer->GetPrefix()); + "SELECT Time, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, " + " cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, " + " cp21, cp22, cp23, cp24, cp25 " + "FROM %s_race " + "WHERE Map = ? AND Name = ? " + "ORDER BY Time ASC " + "LIMIT 1;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_RequestingPlayer); @@ -236,17 +236,17 @@ bool CScore::LoadPlayerDataThread(IDbConnection *pSqlServer, const ISqlData *pGa { for(int i = 0; i < NUM_CHECKPOINTS; i++) { - pData->m_pResult->m_Data.m_Info.m_CpTime[i] = pSqlServer->GetFloat(i+2); + pData->m_pResult->m_Data.m_Info.m_CpTime[i] = pSqlServer->GetFloat(i + 2); } } } // birthday check str_format(aBuf, sizeof(aBuf), - "SELECT CURRENT_TIMESTAMP AS Current, MIN(Timestamp) AS Stamp " - "FROM %s_race " - "WHERE Name = ?", - pSqlServer->GetPrefix()); + "SELECT CURRENT_TIMESTAMP AS Current, MIN(Timestamp) AS Stamp " + "FROM %s_race " + "WHERE Name = ?", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_RequestingPlayer); @@ -258,16 +258,14 @@ bool CScore::LoadPlayerDataThread(IDbConnection *pSqlServer, const ISqlData *pGa pSqlServer->GetString(2, aStamp, sizeof(aStamp)); int CurrentYear, CurrentMonth, CurrentDay; int StampYear, StampMonth, StampDay; - if(sscanf(aCurrent, "%d-%d-%d", &CurrentYear, &CurrentMonth, &CurrentDay) == 3 - && sscanf(aStamp, "%d-%d-%d", &StampYear, &StampMonth, &StampDay) == 3 - && CurrentMonth == StampMonth && CurrentDay == StampDay) + if(sscanf(aCurrent, "%d-%d-%d", &CurrentYear, &CurrentMonth, &CurrentDay) == 3 && sscanf(aStamp, "%d-%d-%d", &StampYear, &StampMonth, &StampDay) == 3 && CurrentMonth == StampMonth && CurrentDay == StampDay) pData->m_pResult->m_Data.m_Info.m_Birthday = CurrentYear - StampYear; } pData->m_pResult->m_Done = true; return true; } -void CScore::MapVote(int ClientID, const char* MapName) +void CScore::MapVote(int ClientID, const char *MapName) { if(RateLimitPlayer(ClientID)) return; @@ -289,15 +287,15 @@ bool CScore::MapVoteThread(IDbConnection *pSqlServer, const ISqlData *pGameData) char aBuf[768]; str_format(aBuf, sizeof(aBuf), - "SELECT Map, Server " - "FROM %s_maps " - "WHERE Map LIKE %s " - "ORDER BY " - " CASE WHEN Map = ? THEN 0 ELSE 1 END, " - " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " - " LENGTH(Map), Map " - "LIMIT 1;", - pSqlServer->GetPrefix(), pSqlServer->CollateNocase()); + "SELECT Map, Server " + "FROM %s_maps " + "WHERE Map LIKE %s " + "ORDER BY " + " CASE WHEN Map = ? THEN 0 ELSE 1 END, " + " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " + " LENGTH(Map), Map " + "LIMIT 1;", + pSqlServer->GetPrefix(), pSqlServer->CollateNocase()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, aFuzzyMap); pSqlServer->BindString(2, pData->m_Name); @@ -318,16 +316,16 @@ bool CScore::MapVoteThread(IDbConnection *pSqlServer, const ISqlData *pGameData) { pData->m_pResult->SetVariant(CScorePlayerResult::DIRECT); str_format(paMessages[0], sizeof(paMessages[0]), - "No map like \"%s\" found. " - "Try adding a '%%' at the start if you don't know the first character. " - "Example: /map %%castle for \"Out of Castle\"", - pData->m_Name); + "No map like \"%s\" found. " + "Try adding a '%%' at the start if you don't know the first character. " + "Example: /map %%castle for \"Out of Castle\"", + pData->m_Name); } pData->m_pResult->m_Done = true; return true; } -void CScore::MapInfo(int ClientID, const char* MapName) +void CScore::MapInfo(int ClientID, const char *MapName) { if(RateLimitPlayer(ClientID)) return; @@ -353,28 +351,27 @@ bool CScore::MapInfoThread(IDbConnection *pSqlServer, const ISqlData *pGameData) char aBuf[1024]; str_format(aBuf, sizeof(aBuf), - "SELECT l.Map, l.Server, Mapper, Points, Stars, " - " (SELECT COUNT(Name) FROM %s_race WHERE Map = l.Map) AS Finishes, " - " (SELECT COUNT(DISTINCT Name) FROM %s_race WHERE Map = l.Map) AS Finishers, " - " (SELECT ROUND(AVG(Time)) FROM %s_race WHERE Map = l.Map) AS Average, " - " %s AS Stamp, " - " %s-%s AS Ago, " - " (SELECT MIN(Time) FROM %s_race WHERE Map = l.Map AND Name = ?) AS OwnTime " - "FROM (" - " SELECT * FROM %s_maps " - " WHERE Map LIKE %s " - " ORDER BY " - " CASE WHEN Map = ? THEN 0 ELSE 1 END, " - " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " - " LENGTH(Map), " - " Map " - " LIMIT 1" - ") as l;", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), - aTimestamp, aCurrentTimestamp, aTimestamp, - pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), - pSqlServer->CollateNocase() - ); + "SELECT l.Map, l.Server, Mapper, Points, Stars, " + " (SELECT COUNT(Name) FROM %s_race WHERE Map = l.Map) AS Finishes, " + " (SELECT COUNT(DISTINCT Name) FROM %s_race WHERE Map = l.Map) AS Finishers, " + " (SELECT ROUND(AVG(Time)) FROM %s_race WHERE Map = l.Map) AS Average, " + " %s AS Stamp, " + " %s-%s AS Ago, " + " (SELECT MIN(Time) FROM %s_race WHERE Map = l.Map AND Name = ?) AS OwnTime " + "FROM (" + " SELECT * FROM %s_maps " + " WHERE Map LIKE %s " + " ORDER BY " + " CASE WHEN Map = ? THEN 0 ELSE 1 END, " + " CASE WHEN Map LIKE ? THEN 0 ELSE 1 END, " + " LENGTH(Map), " + " Map " + " LIMIT 1" + ") as l;", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), + aTimestamp, aCurrentTimestamp, aTimestamp, + pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), + pSqlServer->CollateNocase()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_RequestingPlayer); pSqlServer->BindString(2, aFuzzyMap); @@ -415,37 +412,35 @@ bool CScore::MapInfoThread(IDbConnection *pSqlServer, const ISqlData *pGameData) char aStars[20]; switch(Stars) { - case 0: strcpy(aStars, "✰✰✰✰✰"); break; - case 1: strcpy(aStars, "★✰✰✰✰"); break; - case 2: strcpy(aStars, "★★✰✰✰"); break; - case 3: strcpy(aStars, "★★★✰✰"); break; - case 4: strcpy(aStars, "★★★★✰"); break; - case 5: strcpy(aStars, "★★★★★"); break; - default: aStars[0] = '\0'; + case 0: strcpy(aStars, "✰✰✰✰✰"); break; + case 1: strcpy(aStars, "★✰✰✰✰"); break; + case 2: strcpy(aStars, "★★✰✰✰"); break; + case 3: strcpy(aStars, "★★★✰✰"); break; + case 4: strcpy(aStars, "★★★★✰"); break; + case 5: strcpy(aStars, "★★★★★"); break; + default: aStars[0] = '\0'; } char aOwnFinishesString[40] = "\0"; if(OwnTime > 0) { str_format(aOwnFinishesString, sizeof(aOwnFinishesString), - ", your time: %02d:%05.2f", (int)(OwnTime/60), OwnTime-((int)OwnTime/60*60) - ); + ", your time: %02d:%05.2f", (int)(OwnTime / 60), OwnTime - ((int)OwnTime / 60 * 60)); } str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "\"%s\" by %s on %s, %s, %d %s%s, %d %s by %d %s%s%s", - aMap, aMapper, aServer, aStars, - Points, Points == 1 ? "point" : "points", - aReleasedString, - Finishes, Finishes == 1 ? "finish" : "finishes", - Finishers, Finishers == 1 ? "tee" : "tees", - aAverageString, aOwnFinishesString - ); + "\"%s\" by %s on %s, %s, %d %s%s, %d %s by %d %s%s%s", + aMap, aMapper, aServer, aStars, + Points, Points == 1 ? "point" : "points", + aReleasedString, + Finishes, Finishes == 1 ? "finish" : "finishes", + Finishers, Finishers == 1 ? "tee" : "tees", + aAverageString, aOwnFinishesString); } else { str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "No map like \"%s\" found.", pData->m_Name); + "No map like \"%s\" found.", pData->m_Name); } pData->m_pResult->m_Done = true; return true; @@ -453,7 +448,7 @@ bool CScore::MapInfoThread(IDbConnection *pSqlServer, const ISqlData *pGameData) void CScore::SaveScore(int ClientID, float Time, const char *pTimestamp, float CpTime[NUM_CHECKPOINTS], bool NotEligible) { - CConsole* pCon = (CConsole*)GameServer()->Console(); + CConsole *pCon = (CConsole *)GameServer()->Console(); if(pCon->m_Cheated || NotEligible) return; @@ -482,8 +477,8 @@ bool CScore::SaveScoreThread(IDbConnection *pSqlServer, const ISqlData *pGameDat char aBuf[1024]; str_format(aBuf, sizeof(aBuf), - "SELECT COUNT(*) AS NumFinished FROM %s_race WHERE Map=? AND Name=? ORDER BY time ASC LIMIT 1;", - pSqlServer->GetPrefix()); + "SELECT COUNT(*) AS NumFinished FROM %s_race WHERE Map=? AND Name=? ORDER BY time ASC LIMIT 1;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_Name); @@ -501,8 +496,8 @@ bool CScore::SaveScoreThread(IDbConnection *pSqlServer, const ISqlData *pGameDat int Points = pSqlServer->GetInt(1); pSqlServer->AddPoints(pData->m_Name, Points); str_format(paMessages[0], sizeof(paMessages[0]), - "You earned %d point%s for finishing this map!", - Points, Points == 1 ? "" : "s"); + "You earned %d point%s for finishing this map!", + Points, Points == 1 ? "" : "s"); } } @@ -542,9 +537,9 @@ bool CScore::SaveScoreThread(IDbConnection *pSqlServer, const ISqlData *pGameDat return true; } -void CScore::SaveTeamScore(int* aClientIDs, unsigned int Size, float Time, const char *pTimestamp) +void CScore::SaveTeamScore(int *aClientIDs, unsigned int Size, float Time, const char *pTimestamp) { - CConsole* pCon = (CConsole*)GameServer()->Console(); + CConsole *pCon = (CConsole *)GameServer()->Console(); if(pCon->m_Cheated) return; for(unsigned int i = 0; i < Size; i++) @@ -552,7 +547,7 @@ void CScore::SaveTeamScore(int* aClientIDs, unsigned int Size, float Time, const if(GameServer()->m_apPlayers[aClientIDs[i]]->m_NotEligibleForFinish) return; } - auto Tmp = std::unique_ptr(new CSqlTeamScoreData()); + auto Tmp = std::unique_ptr(new CSqlTeamScoreData()); for(unsigned int i = 0; i < Size; i++) str_copy(Tmp->m_aNames[i], Server()->ClientName(aClientIDs[i]), sizeof(Tmp->m_aNames[i])); Tmp->m_Size = Size; @@ -577,14 +572,14 @@ bool CScore::SaveTeamScoreThread(IDbConnection *pSqlServer, const ISqlData *pGam std::sort(aNames.begin(), aNames.end()); str_format(aBuf, sizeof(aBuf), - "SELECT l.ID, Name, Time " - "FROM (" // preselect teams with first name in team - " SELECT ID " - " FROM %s_teamrace " - " WHERE Map = ? AND Name = ? AND DDNet7 = false" - ") as l INNER JOIN %s_teamrace AS r ON l.ID = r.ID " - "ORDER BY l.ID, Name COLLATE %s;", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->BinaryCollate()); + "SELECT l.ID, Name, Time " + "FROM (" // preselect teams with first name in team + " SELECT ID " + " FROM %s_teamrace " + " WHERE Map = ? AND Name = ? AND DDNet7 = false" + ") as l INNER JOIN %s_teamrace AS r ON l.ID = r.ID " + "ORDER BY l.ID, Name COLLATE %s;", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->BinaryCollate()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_aNames[0]); @@ -612,8 +607,8 @@ bool CScore::SaveTeamScoreThread(IDbConnection *pSqlServer, const ISqlData *pGam if(pData->m_Time < Time) { str_format(aBuf, sizeof(aBuf), - "UPDATE %s_teamrace SET Time=%.2f, Timestamp=?, DDNet7=false, GameID=? WHERE ID = ?;", - pSqlServer->GetPrefix(), pData->m_Time); + "UPDATE %s_teamrace SET Time=%.2f, Timestamp=?, DDNet7=false, GameID=? WHERE ID = ?;", + pSqlServer->GetPrefix(), pData->m_Time); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_aTimestamp); pSqlServer->BindString(2, pData->m_GameUuid); @@ -646,7 +641,7 @@ bool CScore::SaveTeamScoreThread(IDbConnection *pSqlServer, const ISqlData *pGam return true; } -void CScore::ShowRank(int ClientID, const char* pName) +void CScore::ShowRank(int ClientID, const char *pName) { if(RateLimitPlayer(ClientID)) return; @@ -661,16 +656,16 @@ bool CScore::ShowRankThread(IDbConnection *pSqlServer, const ISqlData *pGameData char aBuf[600]; str_format(aBuf, sizeof(aBuf), - "SELECT Rank, Name, Time " - "FROM (" - " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " - " FROM %s_race " - " WHERE Map = ? " - " GROUP BY Name " - " WINDOW w AS (ORDER BY Time)" - ") as a " - "WHERE Name = ?;", - pSqlServer->GetPrefix()); + "SELECT Rank, Name, Time " + "FROM (" + " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " + " FROM %s_race " + " WHERE Map = ? " + " GROUP BY Name " + " WINDOW w AS (ORDER BY Time)" + ") as a " + "WHERE Name = ?;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_Name); @@ -682,7 +677,7 @@ bool CScore::ShowRankThread(IDbConnection *pSqlServer, const ISqlData *pGameData if(g_Config.m_SvHideScore) { str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "Your time: %02d:%05.2f", (int)(Time/60), Time-((int)Time/60*60)); + "Your time: %02d:%05.2f", (int)(Time / 60), Time - ((int)Time / 60 * 60)); } else { @@ -690,21 +685,21 @@ bool CScore::ShowRankThread(IDbConnection *pSqlServer, const ISqlData *pGameData pSqlServer->GetString(2, aName, sizeof(aName)); pData->m_pResult->m_MessageKind = CScorePlayerResult::ALL; str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "%d. %s Time: %02d:%05.2f, requested by %s", - Rank, aName, (int)(Time/60), Time-((int)Time/60*60), pData->m_RequestingPlayer); + "%d. %s Time: %02d:%05.2f, requested by %s", + Rank, aName, (int)(Time / 60), Time - ((int)Time / 60 * 60), pData->m_RequestingPlayer); } } else { str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "%s is not ranked", pData->m_Name); + "%s is not ranked", pData->m_Name); } pData->m_pResult->m_Done = true; return true; } -void CScore::ShowTeamRank(int ClientID, const char* pName) +void CScore::ShowTeamRank(int ClientID, const char *pName) { if(RateLimitPlayer(ClientID)) return; @@ -719,22 +714,22 @@ bool CScore::ShowTeamRankThread(IDbConnection *pSqlServer, const ISqlData *pGame char aBuf[2400]; str_format(aBuf, sizeof(aBuf), - "SELECT l.ID, Name, Time, Rank " - "FROM (" // teamrank score board - " SELECT RANK() OVER w AS Rank, ID " - " FROM %s_teamrace " - " WHERE Map = ? " - " GROUP BY ID " - " WINDOW w AS (ORDER BY Time)" - ") AS TeamRank INNER JOIN (" // select rank with Name in team - " SELECT ID " - " FROM %s_teamrace " - " WHERE Map = ? AND Name = ? " - " ORDER BY Time " - " LIMIT 1" - ") AS l ON TeamRank.ID = l.ID " - "INNER JOIN %s_teamrace AS r ON l.ID = r.ID ", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); + "SELECT l.ID, Name, Time, Rank " + "FROM (" // teamrank score board + " SELECT RANK() OVER w AS Rank, ID " + " FROM %s_teamrace " + " WHERE Map = ? " + " GROUP BY ID " + " WINDOW w AS (ORDER BY Time)" + ") AS TeamRank INNER JOIN (" // select rank with Name in team + " SELECT ID " + " FROM %s_teamrace " + " WHERE Map = ? AND Name = ? " + " ORDER BY Time " + " LIMIT 1" + ") AS l ON TeamRank.ID = l.ID " + "INNER JOIN %s_teamrace AS r ON l.ID = r.ID ", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_Map); @@ -752,29 +747,29 @@ bool CScore::ShowTeamRankThread(IDbConnection *pSqlServer, const ISqlData *pGame { str_append(aFormattedNames, Teamrank.m_aaNames[Name], sizeof(aFormattedNames)); - if (Name < Teamrank.m_NumNames - 2) + if(Name < Teamrank.m_NumNames - 2) str_append(aFormattedNames, ", ", sizeof(aFormattedNames)); - else if (Name < Teamrank.m_NumNames - 1) + else if(Name < Teamrank.m_NumNames - 1) str_append(aFormattedNames, " & ", sizeof(aFormattedNames)); } if(g_Config.m_SvHideScore) { str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "Your team time: %02d:%05.02f", (int)(Time/60), Time-((int)Time/60*60)); + "Your team time: %02d:%05.02f", (int)(Time / 60), Time - ((int)Time / 60 * 60)); } else { pData->m_pResult->m_MessageKind = CScorePlayerResult::ALL; str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "%d. %s Team time: %02d:%05.02f, requested by %s", - Rank, aFormattedNames, (int)(Time/60), Time-((int)Time/60*60), pData->m_RequestingPlayer); + "%d. %s Team time: %02d:%05.02f, requested by %s", + Rank, aFormattedNames, (int)(Time / 60), Time - ((int)Time / 60 * 60), pData->m_RequestingPlayer); } } else { str_format(pData->m_pResult->m_Data.m_aaMessages[0], sizeof(pData->m_pResult->m_Data.m_aaMessages[0]), - "%s has no team ranks", pData->m_Name); + "%s has no team ranks", pData->m_Name); } pData->m_pResult->m_Done = true; return true; @@ -791,25 +786,25 @@ bool CScore::ShowTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGameData { const CSqlPlayerRequest *pData = dynamic_cast(pGameData); - int LimitStart = maximum(abs(pData->m_Offset)-1, 0); + int LimitStart = maximum(abs(pData->m_Offset) - 1, 0); const char *pOrder = pData->m_Offset >= 0 ? "ASC" : "DESC"; // check sort method char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT Name, Time, Rank " - "FROM (" - " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " - " FROM %s_race " - " WHERE Map = ? " - " GROUP BY Name " - " WINDOW w AS (ORDER BY Time)" - ") as a " - "ORDER BY Rank %s " - "LIMIT %d, 5;", - pSqlServer->GetPrefix(), - pOrder, - LimitStart); + "SELECT Name, Time, Rank " + "FROM (" + " SELECT RANK() OVER w AS Rank, Name, MIN(Time) AS Time " + " FROM %s_race " + " WHERE Map = ? " + " GROUP BY Name " + " WINDOW w AS (ORDER BY Time)" + ") as a " + "ORDER BY Rank %s " + "LIMIT %d, 5;", + pSqlServer->GetPrefix(), + pOrder, + LimitStart); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); @@ -824,9 +819,8 @@ bool CScore::ShowTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGameData float Time = pSqlServer->GetFloat(2); int Rank = pSqlServer->GetInt(3); str_format(pData->m_pResult->m_Data.m_aaMessages[Line], sizeof(pData->m_pResult->m_Data.m_aaMessages[Line]), - "%d. %s Time: %02d:%05.2f", - Rank, aName, (int)(Time/60), Time-((int)Time/60*60) - ); + "%d. %s Time: %02d:%05.2f", + Rank, aName, (int)(Time / 60), Time - ((int)Time / 60 * 60)); Line++; } strcpy(pData->m_pResult->m_Data.m_aaMessages[Line], "-------------------------------"); @@ -847,29 +841,29 @@ bool CScore::ShowTeamTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGame const CSqlPlayerRequest *pData = dynamic_cast(pGameData); auto paMessages = pData->m_pResult->m_Data.m_aaMessages; - int LimitStart = maximum(abs(pData->m_Offset)-1, 0); + int LimitStart = maximum(abs(pData->m_Offset) - 1, 0); const char *pOrder = pData->m_Offset >= 0 ? "ASC" : "DESC"; // check sort method char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT Name, Time, Rank, TeamSize " - "FROM (" // limit to 5 - " SELECT TeamSize, Rank, ID " - " FROM (" // teamrank score board - " SELECT RANK() OVER w AS Rank, ID, COUNT(*) AS Teamsize " - " FROM %s_teamrace " - " WHERE Map = ? " - " GROUP BY Id " - " WINDOW w AS (ORDER BY Time)" - " ) as l1 " - " ORDER BY Rank %s " - " LIMIT %d, 5" - ") as l2 " - "INNER JOIN %s_teamrace as r ON l2.ID = r.ID " - "ORDER BY Rank %s, r.ID, Name ASC;", - pSqlServer->GetPrefix(), pOrder, LimitStart, pSqlServer->GetPrefix(), pOrder); + "SELECT Name, Time, Rank, TeamSize " + "FROM (" // limit to 5 + " SELECT TeamSize, Rank, ID " + " FROM (" // teamrank score board + " SELECT RANK() OVER w AS Rank, ID, COUNT(*) AS Teamsize " + " FROM %s_teamrace " + " WHERE Map = ? " + " GROUP BY Id " + " WINDOW w AS (ORDER BY Time)" + " ) as l1 " + " ORDER BY Rank %s " + " LIMIT %d, 5" + ") as l2 " + "INNER JOIN %s_teamrace as r ON l2.ID = r.ID " + "ORDER BY Rank %s, r.ID, Name ASC;", + pSqlServer->GetPrefix(), pOrder, LimitStart, pSqlServer->GetPrefix(), pOrder); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); @@ -886,15 +880,15 @@ bool CScore::ShowTeamTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGame int Rank = pSqlServer->GetInt(3); int TeamSize = pSqlServer->GetInt(4); - char aNames[2300] = { 0 }; + char aNames[2300] = {0}; for(int i = 0; i < TeamSize; i++) { char aName[MAX_NAME_LENGTH]; pSqlServer->GetString(1, aName, sizeof(aName)); str_append(aNames, aName, sizeof(aNames)); - if (i < TeamSize - 2) + if(i < TeamSize - 2) str_append(aNames, ", ", sizeof(aNames)); - else if (i == TeamSize - 2) + else if(i == TeamSize - 2) str_append(aNames, " & ", sizeof(aNames)); if(!pSqlServer->Step()) { @@ -903,7 +897,7 @@ bool CScore::ShowTeamTop5Thread(IDbConnection *pSqlServer, const ISqlData *pGame } } str_format(paMessages[Line], sizeof(paMessages[Line]), "%d. %s Team Time: %02d:%05.2f", - Rank, aNames, (int)(Time/60), Time-((int)Time/60*60)); + Rank, aNames, (int)(Time / 60), Time - ((int)Time / 60 * 60)); if(Last) { Line++; @@ -924,7 +918,7 @@ void CScore::ShowTimes(int ClientID, int Offset) ExecPlayerThread(ShowTimesThread, "show times", ClientID, "", Offset); } -void CScore::ShowTimes(int ClientID, const char* pName, int Offset) +void CScore::ShowTimes(int ClientID, const char *pName, int Offset) { if(RateLimitPlayer(ClientID)) return; @@ -936,7 +930,7 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat const CSqlPlayerRequest *pData = dynamic_cast(pGameData); auto paMessages = pData->m_pResult->m_Data.m_aaMessages; - int LimitStart = maximum(abs(pData->m_Offset)-1, 0); + int LimitStart = maximum(abs(pData->m_Offset) - 1, 0); const char *pOrder = pData->m_Offset >= 0 ? "DESC" : "ASC"; char aCurrentTimestamp[512]; @@ -947,13 +941,13 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat if(pData->m_Name[0] != '\0') // last 5 times of a player { str_format(aBuf, sizeof(aBuf), - "SELECT Time, (%s-%s) as Ago, %s as Stamp " - "FROM %s_race " - "WHERE Map = ? AND Name = ? " - "ORDER BY Timestamp %s " - "LIMIT ?, 5;", - aCurrentTimestamp, aTimestamp, aTimestamp, - pSqlServer->GetPrefix(), pOrder); + "SELECT Time, (%s-%s) as Ago, %s as Stamp " + "FROM %s_race " + "WHERE Map = ? AND Name = ? " + "ORDER BY Timestamp %s " + "LIMIT ?, 5;", + aCurrentTimestamp, aTimestamp, aTimestamp, + pSqlServer->GetPrefix(), pOrder); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, pData->m_Name); @@ -962,13 +956,13 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat else // last 5 times of server { str_format(aBuf, sizeof(aBuf), - "SELECT Time, (%s-%s) as Ago, %s as Stamp, Name " - "FROM %s_race " - "WHERE Map = ? " - "ORDER BY Timestamp %s " - "LIMIT ?, 5;", - aCurrentTimestamp, aTimestamp, aTimestamp, - pSqlServer->GetPrefix(), pOrder); + "SELECT Time, (%s-%s) as Ago, %s as Stamp, Name " + "FROM %s_race " + "WHERE Map = ? " + "ORDER BY Timestamp %s " + "LIMIT ?, 5;", + aCurrentTimestamp, aTimestamp, aTimestamp, + pSqlServer->GetPrefix(), pOrder); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindInt(2, LimitStart); @@ -998,12 +992,12 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat { if(Stamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet str_format(paMessages[Line], sizeof(paMessages[Line]), - "%02d:%05.02f, don't know how long ago", - (int)(Time/60), Time-((int)Time/60*60)); + "%02d:%05.02f, don't know how long ago", + (int)(Time / 60), Time - ((int)Time / 60 * 60)); else str_format(paMessages[Line], sizeof(paMessages[Line]), - "%s ago, %02d:%05.02f", - aAgoString, (int)(Time/60), Time-((int)Time/60*60)); + "%s ago, %02d:%05.02f", + aAgoString, (int)(Time / 60), Time - ((int)Time / 60 * 60)); } else // last 5 times of the server { @@ -1012,14 +1006,14 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat if(Stamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet { str_format(paMessages[Line], sizeof(paMessages[Line]), - "%s, %02d:%05.02f, don't know when", - aName, (int)(Time/60), Time-((int)Time/60*60)); + "%s, %02d:%05.02f, don't know when", + aName, (int)(Time / 60), Time - ((int)Time / 60 * 60)); } else { str_format(paMessages[Line], sizeof(paMessages[Line]), - "%s, %s ago, %02d:%05.02f", - aName, aAgoString, (int)(Time/60), Time-((int)Time/60*60)); + "%s, %s ago, %02d:%05.02f", + aName, aAgoString, (int)(Time / 60), Time - ((int)Time / 60 * 60)); } } Line++; @@ -1030,7 +1024,7 @@ bool CScore::ShowTimesThread(IDbConnection *pSqlServer, const ISqlData *pGameDat return true; } -void CScore::ShowPoints(int ClientID, const char* pName) +void CScore::ShowPoints(int ClientID, const char *pName) { if(RateLimitPlayer(ClientID)) return; @@ -1044,12 +1038,12 @@ bool CScore::ShowPointsThread(IDbConnection *pSqlServer, const ISqlData *pGameDa char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT (" - " SELECT COUNT(Name) + 1 FROM %s_points WHERE Points > (" - " SELECT points FROM %s_points WHERE Name = ?" - ")) as Rank, Points, Name " - "FROM %s_points WHERE Name = ?;", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); + "SELECT (" + " SELECT COUNT(Name) + 1 FROM %s_points WHERE Points > (" + " SELECT points FROM %s_points WHERE Name = ?" + ")) as Rank, Points, Name " + "FROM %s_points WHERE Name = ?;", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Name); pSqlServer->BindString(2, pData->m_Name); @@ -1062,13 +1056,13 @@ bool CScore::ShowPointsThread(IDbConnection *pSqlServer, const ISqlData *pGameDa pSqlServer->GetString(3, aName, sizeof(aName)); pData->m_pResult->m_MessageKind = CScorePlayerResult::ALL; str_format(paMessages[0], sizeof(paMessages[0]), - "%d. %s Points: %d, requested by %s", - Rank, aName, Count, pData->m_RequestingPlayer); + "%d. %s Points: %d, requested by %s", + Rank, aName, Count, pData->m_RequestingPlayer); } else { str_format(paMessages[0], sizeof(paMessages[0]), - "%s has not collected any points so far", pData->m_Name); + "%s has not collected any points so far", pData->m_Name); } pData->m_pResult->m_Done = true; @@ -1087,20 +1081,20 @@ bool CScore::ShowTopPointsThread(IDbConnection *pSqlServer, const ISqlData *pGam const CSqlPlayerRequest *pData = dynamic_cast(pGameData); auto paMessages = pData->m_pResult->m_Data.m_aaMessages; - int LimitStart = maximum(abs(pData->m_Offset)-1, 0); + int LimitStart = maximum(abs(pData->m_Offset) - 1, 0); const char *pOrder = pData->m_Offset >= 0 ? "ASC" : "DESC"; char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT Rank, Points, Name " - "FROM (" - " SELECT RANK() OVER w AS Rank, Points, Name " - " FROM %s_points " - " WINDOW w as (ORDER BY Points DESC)" - ") as a " - "ORDER BY Rank %s " - "LIMIT ?, 5;", - pSqlServer->GetPrefix(), pOrder); + "SELECT Rank, Points, Name " + "FROM (" + " SELECT RANK() OVER w AS Rank, Points, Name " + " FROM %s_points " + " WINDOW w as (ORDER BY Points DESC)" + ") as a " + "ORDER BY Rank %s " + "LIMIT ?, 5;", + pSqlServer->GetPrefix(), pOrder); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindInt(1, LimitStart); @@ -1115,7 +1109,7 @@ bool CScore::ShowTopPointsThread(IDbConnection *pSqlServer, const ISqlData *pGam char aName[MAX_NAME_LENGTH]; pSqlServer->GetString(3, aName, sizeof(aName)); str_format(paMessages[Line], sizeof(paMessages[Line]), - "%d. %s Points: %d", Rank, aName, Points); + "%d. %s Points: %d", Rank, aName, Points); Line++; } strcpy(paMessages[Line], "-------------------------------"); @@ -1146,20 +1140,20 @@ bool CScore::RandomMapThread(IDbConnection *pSqlServer, const ISqlData *pGameDat if(0 <= pData->m_Stars && pData->m_Stars <= 5) { str_format(aBuf, sizeof(aBuf), - "SELECT Map FROM %s_maps " - "WHERE Server = ? AND Map != ? AND Stars = ? " - "ORDER BY RAND() LIMIT 1;", - pSqlServer->GetPrefix()); + "SELECT Map FROM %s_maps " + "WHERE Server = ? AND Map != ? AND Stars = ? " + "ORDER BY RAND() LIMIT 1;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindInt(3, pData->m_Stars); } else { str_format(aBuf, sizeof(aBuf), - "SELECT Map FROM %s_maps " - "WHERE Server = ? AND Map != ? " - "ORDER BY RAND() LIMIT 1;", - pSqlServer->GetPrefix()); + "SELECT Map FROM %s_maps " + "WHERE Server = ? AND Map != ? " + "ORDER BY RAND() LIMIT 1;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); } pSqlServer->BindString(1, pData->m_ServerType); @@ -1200,15 +1194,15 @@ bool CScore::RandomUnfinishedMapThread(IDbConnection *pSqlServer, const ISqlData if(pData->m_Stars >= 0) { str_format(aBuf, sizeof(aBuf), - "SELECT Map " - "FROM %s_maps " - "WHERE Server = ? AND Map != ? AND Stars = ? AND Map NOT IN (" - " SELECT Map " - " FROM %s_race " - " WHERE Name = ?" - ") ORDER BY RAND() " - "LIMIT 1;", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); + "SELECT Map " + "FROM %s_maps " + "WHERE Server = ? AND Map != ? AND Stars = ? AND Map NOT IN (" + " SELECT Map " + " FROM %s_race " + " WHERE Name = ?" + ") ORDER BY RAND() " + "LIMIT 1;", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_ServerType); pSqlServer->BindString(2, pData->m_CurrentMap); @@ -1218,15 +1212,15 @@ bool CScore::RandomUnfinishedMapThread(IDbConnection *pSqlServer, const ISqlData else { str_format(aBuf, sizeof(aBuf), - "SELECT Map " - "FROM %s_maps AS maps " - "WHERE Server = ? AND Map != ? AND Map NOT IN (" - " SELECT Map " - " FROM %s_race as race " - " WHERE Name = ?" - ") ORDER BY RAND() " - "LIMIT 1;", - pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); + "SELECT Map " + "FROM %s_maps AS maps " + "WHERE Server = ? AND Map != ? AND Map NOT IN (" + " SELECT Map " + " FROM %s_race as race " + " WHERE Name = ?" + ") ORDER BY RAND() " + "LIMIT 1;", + pSqlServer->GetPrefix(), pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_ServerType); pSqlServer->BindString(2, pData->m_CurrentMap); @@ -1246,11 +1240,11 @@ bool CScore::RandomUnfinishedMapThread(IDbConnection *pSqlServer, const ISqlData return true; } -void CScore::SaveTeam(int ClientID, const char* Code, const char* Server) +void CScore::SaveTeam(int ClientID, const char *Code, const char *Server) { if(RateLimitPlayer(ClientID)) return; - auto pController = ((CGameControllerDDRace*)(GameServer()->m_pController)); + auto pController = ((CGameControllerDDRace *)(GameServer()->m_pController)); int Team = pController->m_Teams.m_Core.Team(ClientID); if(pController->m_Teams.GetSaving(Team)) return; @@ -1335,31 +1329,31 @@ bool CScore::SaveTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData if(str_comp(pData->m_Server, g_Config.m_SvSqlServerName) == 0) { str_format(pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage), - "Team successfully saved by %s. Use '/load %s' to continue", - pData->m_ClientName, Code); + "Team successfully saved by %s. Use '/load %s' to continue", + pData->m_ClientName, Code); } else { str_format(pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage), - "Team successfully saved by %s. Use '/load %s' on %s to continue", - pData->m_ClientName, Code, pData->m_Server); + "Team successfully saved by %s. Use '/load %s' on %s to continue", + pData->m_ClientName, Code, pData->m_Server); } } else { strcpy(pData->m_pResult->m_aBroadcast, - "Database connection failed, teamsave written to a file instead. Admins will add it manually in a few days."); + "Database connection failed, teamsave written to a file instead. Admins will add it manually in a few days."); if(str_comp(pData->m_Server, g_Config.m_SvSqlServerName) == 0) { str_format(pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage), - "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' to continue", - pData->m_ClientName, Code); + "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' to continue", + pData->m_ClientName, Code); } else { str_format(pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage), - "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' on %s to continue", - pData->m_ClientName, Code, pData->m_Server); + "Team successfully saved by %s. The database connection failed, using generated save code instead to avoid collisions. Use '/load %s' on %s to continue", + pData->m_ClientName, Code, pData->m_Server); } } @@ -1376,11 +1370,11 @@ bool CScore::SaveTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData return true; } -void CScore::LoadTeam(const char* Code, int ClientID) +void CScore::LoadTeam(const char *Code, int ClientID) { if(RateLimitPlayer(ClientID)) return; - auto pController = ((CGameControllerDDRace*)(GameServer()->m_pController)); + auto pController = ((CGameControllerDDRace *)(GameServer()->m_pController)); int Team = pController->m_Teams.m_Core.Team(ClientID); if(pController->m_Teams.GetSaving(Team)) return; @@ -1429,8 +1423,8 @@ bool CScore::LoadTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData char aSaveLike[128] = ""; str_append(aSaveLike, "%\n", sizeof(aSaveLike)); sqlstr::EscapeLike(aSaveLike + str_length(aSaveLike), - pData->m_RequestingPlayer, - sizeof(aSaveLike) - str_length(aSaveLike)); + pData->m_RequestingPlayer, + sizeof(aSaveLike) - str_length(aSaveLike)); str_append(aSaveLike, "\t%", sizeof(aSaveLike)); char aCurrentTimestamp[512]; @@ -1440,11 +1434,11 @@ bool CScore::LoadTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT Savegame, %s-%s AS Ago, SaveID " - "FROM %s_saves " - "where Code = ? AND Map = ? AND DDNet7 = false AND Savegame LIKE ?;", - aCurrentTimestamp, aTimestamp, - pSqlServer->GetPrefix()); + "SELECT Savegame, %s-%s AS Ago, SaveID " + "FROM %s_saves " + "where Code = ? AND Map = ? AND DDNet7 = false AND Savegame LIKE ?;", + aCurrentTimestamp, aTimestamp, + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Code); pSqlServer->BindString(2, pData->m_Map); @@ -1460,8 +1454,8 @@ bool CScore::LoadTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData if(Since < g_Config.m_SvSaveGamesDelay) { str_format(pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage), - "You have to wait %d seconds until you can load this savegame", - g_Config.m_SvSaveGamesDelay - Since); + "You have to wait %d seconds until you can load this savegame", + g_Config.m_SvSaveGamesDelay - Since); goto end; } @@ -1489,16 +1483,16 @@ bool CScore::LoadTeamThread(IDbConnection *pSqlServer, const ISqlData *pGameData } bool CanLoad = pData->m_pResult->m_SavedTeam.MatchPlayers( - pData->m_aClientNames, pData->m_aClientID, pData->m_NumPlayer, - pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage)); + pData->m_aClientNames, pData->m_aClientID, pData->m_NumPlayer, + pData->m_pResult->m_aMessage, sizeof(pData->m_pResult->m_aMessage)); if(!CanLoad) goto end; str_format(aBuf, sizeof(aBuf), - "DELETE FROM %s_saves " - "WHERE Code = ? AND Map = ?;", - pSqlServer->GetPrefix()); + "DELETE FROM %s_saves " + "WHERE Code = ? AND Map = ?;", + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Code); pSqlServer->BindString(2, pData->m_Map); @@ -1528,11 +1522,10 @@ bool CScore::GetSavesThread(IDbConnection *pSqlServer, const ISqlData *pGameData char aSaveLike[128] = ""; str_append(aSaveLike, "%\n", sizeof(aSaveLike)); sqlstr::EscapeLike(aSaveLike + str_length(aSaveLike), - pData->m_RequestingPlayer, - sizeof(aSaveLike) - str_length(aSaveLike)); + pData->m_RequestingPlayer, + sizeof(aSaveLike) - str_length(aSaveLike)); str_append(aSaveLike, "\t%", sizeof(aSaveLike)); - char aCurrentTimestamp[512]; pSqlServer->ToUnixTimestamp("CURRENT_TIMESTAMP", aCurrentTimestamp, sizeof(aCurrentTimestamp)); char aMaxTimestamp[512]; @@ -1540,11 +1533,11 @@ bool CScore::GetSavesThread(IDbConnection *pSqlServer, const ISqlData *pGameData char aBuf[512]; str_format(aBuf, sizeof(aBuf), - "SELECT COUNT(*) AS NumSaves, %s-%s AS Ago " - "FROM %s_saves " - "WHERE Map = ? AND Savegame LIKE ?;", - aCurrentTimestamp, aMaxTimestamp, - pSqlServer->GetPrefix()); + "SELECT COUNT(*) AS NumSaves, %s-%s AS Ago " + "FROM %s_saves " + "WHERE Map = ? AND Savegame LIKE ?;", + aCurrentTimestamp, aMaxTimestamp, + pSqlServer->GetPrefix()); pSqlServer->PrepareStatement(aBuf); pSqlServer->BindString(1, pData->m_Map); pSqlServer->BindString(2, aSaveLike); @@ -1562,10 +1555,10 @@ bool CScore::GetSavesThread(IDbConnection *pSqlServer, const ISqlData *pGameData } str_format(paMessages[0], sizeof(paMessages[0]), - "%s has %d save%s on %s%s", - pData->m_RequestingPlayer, - NumSaves, NumSaves == 1 ? "" : "s", - pData->m_Map, aLastSavedString); + "%s has %d save%s on %s%s", + pData->m_RequestingPlayer, + NumSaves, NumSaves == 1 ? "" : "s", + pData->m_Map, aLastSavedString); } pData->m_pResult->m_Done = true; diff --git a/src/game/server/score.h b/src/game/server/score.h index c2031fa36..840924df7 100644 --- a/src/game/server/score.h +++ b/src/game/server/score.h @@ -1,15 +1,15 @@ #ifndef GAME_SERVER_SCORE_H #define GAME_SERVER_SCORE_H -#include #include +#include #include #include -#include #include -#include +#include #include +#include #include "save.h" @@ -29,7 +29,8 @@ struct CScorePlayerResult std::atomic_bool m_Done; CScorePlayerResult(); - enum { + enum + { MAX_MESSAGES = 7, }; @@ -41,10 +42,12 @@ struct CScorePlayerResult MAP_VOTE, PLAYER_INFO, } m_MessageKind; - union { + union + { char m_aaMessages[MAX_MESSAGES][512]; char m_Broadcast[1024]; - struct { + struct + { float m_Time; float m_CpTime[NUM_CHECKPOINTS]; int m_Score; @@ -54,8 +57,8 @@ struct CScorePlayerResult struct { char m_Reason[VOTE_REASON_LENGTH]; - char m_Server[32+1]; - char m_Map[MAX_MAP_LENGTH+1]; + char m_Server[32 + 1]; + char m_Map[MAX_MAP_LENGTH + 1]; } m_MapVote; } m_Data; // PLAYER_INFO @@ -79,7 +82,7 @@ struct CScoreRandomMapResult struct CScoreSaveResult { - CScoreSaveResult(int PlayerID, IGameController* Controller) : + CScoreSaveResult(int PlayerID, IGameController *Controller) : m_Status(SAVE_FAILED), m_SavedTeam(CSaveTeam(Controller)), m_RequestingPlayer(PlayerID) @@ -107,7 +110,8 @@ struct CScoreInitResult CScoreInitResult() : m_Done(false), m_CurrentRecord(0) - { } + { + } std::atomic_bool m_Done; float m_CurrentRecord; }; @@ -146,7 +150,8 @@ struct CSqlInitData : ISqlData { CSqlInitData(std::shared_ptr pResult) : m_pResult(pResult) - {} + { + } std::shared_ptr m_pResult; // current map @@ -157,7 +162,8 @@ struct CSqlPlayerRequest : ISqlData { CSqlPlayerRequest(std::shared_ptr pResult) : m_pResult(pResult) - {} + { + } std::shared_ptr m_pResult; // object being requested, either map (128 bytes) or player (16 bytes) char m_Name[MAX_MAP_LENGTH]; @@ -172,7 +178,8 @@ struct CSqlRandomMapRequest : ISqlData { CSqlRandomMapRequest(std::shared_ptr pResult) : m_pResult(pResult) - {} + { + } std::shared_ptr m_pResult; char m_ServerType[32]; @@ -185,8 +192,9 @@ struct CSqlScoreData : ISqlData { CSqlScoreData(std::shared_ptr pResult) : m_pResult(pResult) - {} - virtual ~CSqlScoreData() {}; + { + } + virtual ~CSqlScoreData(){}; std::shared_ptr m_pResult; @@ -217,8 +225,9 @@ struct CSqlTeamSave : ISqlData { CSqlTeamSave(std::shared_ptr pResult) : m_pResult(pResult) - {} - virtual ~CSqlTeamSave() {}; + { + } + virtual ~CSqlTeamSave(){}; std::shared_ptr m_pResult; @@ -233,8 +242,9 @@ struct CSqlTeamLoad : ISqlData { CSqlTeamLoad(std::shared_ptr pResult) : m_pResult(pResult) - {} - virtual ~CSqlTeamLoad() {}; + { + } + virtual ~CSqlTeamLoad(){}; std::shared_ptr m_pResult; @@ -248,7 +258,8 @@ struct CSqlTeamLoad : ISqlData int m_NumPlayer; }; -struct CTeamrank { +struct CTeamrank +{ CUuid m_TeamID; char m_aaNames[MAX_CLIENTS][MAX_NAME_LENGTH]; unsigned int m_NumNames; @@ -309,11 +320,11 @@ class CScore std::shared_ptr NewSqlPlayerResult(int ClientID); // Creates for player database requests void ExecPlayerThread( - bool (*pFuncPtr) (IDbConnection *, const ISqlData *), - const char *pThreadName, - int ClientID, - const char *pName, - int Offset); + bool (*pFuncPtr)(IDbConnection *, const ISqlData *), + const char *pThreadName, + int ClientID, + const char *pName, + int Offset); // returns true if the player should be rate limited bool RateLimitPlayer(int ClientID); @@ -331,13 +342,13 @@ public: void SaveTeamScore(int *pClientIDs, unsigned int Size, float Time, const char *pTimestamp); - void ShowTop5(int ClientID, int Offset=1); + void ShowTop5(int ClientID, int Offset = 1); void ShowRank(int ClientID, const char *pName); - void ShowTeamTop5(int ClientID, int Offset=1); + void ShowTeamTop5(int ClientID, int Offset = 1); void ShowTeamRank(int ClientID, const char *pName); - void ShowTopPoints(int ClientID, int Offset=1); + void ShowTopPoints(int ClientID, int Offset = 1); void ShowPoints(int ClientID, const char *pName); void ShowTimes(int ClientID, const char *pName, int Offset = 1); diff --git a/src/game/server/teams.cpp b/src/game/server/teams.cpp index a056c9869..ccebcae1e 100644 --- a/src/game/server/teams.cpp +++ b/src/game/server/teams.cpp @@ -1,11 +1,11 @@ /* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ #include "teams.h" -#include "teehistorian.h" #include "score.h" +#include "teehistorian.h" #include CGameTeams::CGameTeams(CGameContext *pGameContext) : - m_pGameContext(pGameContext) + m_pGameContext(pGameContext) { Reset(); } @@ -13,7 +13,7 @@ CGameTeams::CGameTeams(CGameContext *pGameContext) : void CGameTeams::Reset() { m_Core.Reset(); - for (int i = 0; i < MAX_CLIENTS; ++i) + for(int i = 0; i < MAX_CLIENTS; ++i) { m_TeamState[i] = TEAMSTATE_EMPTY; m_TeeFinished[i] = false; @@ -27,8 +27,9 @@ void CGameTeams::Reset() void CGameTeams::ResetSwitchers(int Team) { - if (GameServer()->Collision()->m_NumSwitchers > 0) { - for (int i = 0; i < GameServer()->Collision()->m_NumSwitchers+1; ++i) + if(GameServer()->Collision()->m_NumSwitchers > 0) + { + for(int i = 0; i < GameServer()->Collision()->m_NumSwitchers + 1; ++i) { GameServer()->Collision()->m_pSwitchers[i].m_Status[Team] = GameServer()->Collision()->m_pSwitchers[i].m_Initial; GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team] = 0; @@ -40,13 +41,13 @@ void CGameTeams::ResetSwitchers(int Team) void CGameTeams::OnCharacterStart(int ClientID) { int Tick = Server()->Tick(); - CCharacter* pStartingChar = Character(ClientID); + CCharacter *pStartingChar = Character(ClientID); if(!pStartingChar) return; if((g_Config.m_SvTeam == 3 || m_Core.Team(ClientID) != TEAM_FLOCK) && pStartingChar->m_DDRaceState == DDRACE_FINISHED) return; if(g_Config.m_SvTeam != 3 && - (m_Core.Team(ClientID) == TEAM_FLOCK || m_Core.Team(ClientID) == TEAM_SUPER)) + (m_Core.Team(ClientID) == TEAM_FLOCK || m_Core.Team(ClientID) == TEAM_SUPER)) { pStartingChar->m_DDRaceState = DDRACE_STARTED; pStartingChar->m_StartTime = Tick; @@ -57,7 +58,7 @@ void CGameTeams::OnCharacterStart(int ClientID) { if(m_Core.Team(ClientID) != m_Core.Team(i)) continue; - CPlayer* pPlayer = GetPlayer(i); + CPlayer *pPlayer = GetPlayer(i); if(!pPlayer || !pPlayer->IsPlaying()) continue; if(GetDDRaceState(pPlayer) != DDRACE_FINISHED) @@ -66,27 +67,25 @@ void CGameTeams::OnCharacterStart(int ClientID) Waiting = true; pStartingChar->m_DDRaceState = DDRACE_NONE; - if(m_LastChat[ClientID] + Server()->TickSpeed() - + g_Config.m_SvChatDelay < Tick) + if(m_LastChat[ClientID] + Server()->TickSpeed() + g_Config.m_SvChatDelay < Tick) { char aBuf[128]; str_format( - aBuf, - sizeof(aBuf), - "%s has finished and didn't go through start yet, wait for him or join another team.", - Server()->ClientName(i)); + aBuf, + sizeof(aBuf), + "%s has finished and didn't go through start yet, wait for him or join another team.", + Server()->ClientName(i)); GameServer()->SendChatTarget(ClientID, aBuf); m_LastChat[ClientID] = Tick; } - if(m_LastChat[i] + Server()->TickSpeed() - + g_Config.m_SvChatDelay < Tick) + if(m_LastChat[i] + Server()->TickSpeed() + g_Config.m_SvChatDelay < Tick) { char aBuf[128]; str_format( - aBuf, - sizeof(aBuf), - "%s wants to start a new round, kill or walk to start.", - Server()->ClientName(ClientID)); + aBuf, + sizeof(aBuf), + "%s wants to start a new round, kill or walk to start.", + Server()->ClientName(ClientID)); GameServer()->SendChatTarget(i, aBuf); m_LastChat[i] = Tick; } @@ -100,13 +99,12 @@ void CGameTeams::OnCharacterStart(int ClientID) char aBuf[512]; str_format( - aBuf, - sizeof(aBuf), - "Team %d started with %d player%s: ", - m_Core.Team(ClientID), - NumPlayers, - NumPlayers == 1 ? "" : "s"); - + aBuf, + sizeof(aBuf), + "Team %d started with %d player%s: ", + m_Core.Team(ClientID), + NumPlayers, + NumPlayers == 1 ? "" : "s"); bool First = true; @@ -114,7 +112,7 @@ void CGameTeams::OnCharacterStart(int ClientID) { if(m_Core.Team(ClientID) == m_Core.Team(i)) { - CPlayer* pPlayer = GetPlayer(i); + CPlayer *pPlayer = GetPlayer(i); // TODO: THE PROBLEM IS THAT THERE IS NO CHARACTER SO START TIME CAN'T BE SET! if(pPlayer && (pPlayer->IsPlaying() || TeamLocked(m_Core.Team(ClientID)))) { @@ -135,7 +133,7 @@ void CGameTeams::OnCharacterStart(int ClientID) { for(int i = 0; i < MAX_CLIENTS; ++i) { - CPlayer* pPlayer = GetPlayer(i); + CPlayer *pPlayer = GetPlayer(i); if(m_Core.Team(ClientID) == m_Core.Team(i) && pPlayer && (pPlayer->IsPlaying() || TeamLocked(m_Core.Team(ClientID)))) { GameServer()->SendChatTarget(i, aBuf); @@ -147,15 +145,13 @@ void CGameTeams::OnCharacterStart(int ClientID) void CGameTeams::OnCharacterFinish(int ClientID) { - if((m_Core.Team(ClientID) == TEAM_FLOCK && g_Config.m_SvTeam != 3) - || m_Core.Team(ClientID) == TEAM_SUPER) + if((m_Core.Team(ClientID) == TEAM_FLOCK && g_Config.m_SvTeam != 3) || m_Core.Team(ClientID) == TEAM_SUPER) { - CPlayer* pPlayer = GetPlayer(ClientID); - if (pPlayer && pPlayer->IsPlaying()) + CPlayer *pPlayer = GetPlayer(ClientID); + if(pPlayer && pPlayer->IsPlaying()) { - float Time = (float)(Server()->Tick() - GetStartTime(pPlayer)) - / ((float)Server()->TickSpeed()); - if (Time < 0.000001f) + float Time = (float)(Server()->Tick() - GetStartTime(pPlayer)) / ((float)Server()->TickSpeed()); + if(Time < 0.000001f) return; char aTimestamp[TIMESTAMP_STR_LENGTH]; str_timestamp_format(aTimestamp, sizeof(aTimestamp), FORMAT_SPACE); // 2019-04-02 19:41:58 @@ -173,17 +169,17 @@ void CGameTeams::OnCharacterFinish(int ClientID) void CGameTeams::CheckTeamFinished(int Team) { - if (TeamFinished(Team)) + if(TeamFinished(Team)) { CPlayer *TeamPlayers[MAX_CLIENTS]; unsigned int PlayersCount = 0; - for (int i = 0; i < MAX_CLIENTS; ++i) + for(int i = 0; i < MAX_CLIENTS; ++i) { - if (Team == m_Core.Team(i)) + if(Team == m_Core.Team(i)) { - CPlayer* pPlayer = GetPlayer(i); - if (pPlayer && pPlayer->IsPlaying()) + CPlayer *pPlayer = GetPlayer(i); + if(pPlayer && pPlayer->IsPlaying()) { m_TeeFinished[i] = false; @@ -192,11 +188,10 @@ void CGameTeams::CheckTeamFinished(int Team) } } - if (PlayersCount > 0) + if(PlayersCount > 0) { - float Time = (float)(Server()->Tick() - GetStartTime(TeamPlayers[0])) - / ((float)Server()->TickSpeed()); - if (Time < 0.000001f) + float Time = (float)(Server()->Tick() - GetStartTime(TeamPlayers[0])) / ((float)Server()->TickSpeed()); + if(Time < 0.000001f) { return; } @@ -229,7 +224,7 @@ void CGameTeams::CheckTeamFinished(int Team) char aTimestamp[TIMESTAMP_STR_LENGTH]; str_timestamp_format(aTimestamp, sizeof(aTimestamp), FORMAT_SPACE); // 2019-04-02 19:41:58 - for (unsigned int i = 0; i < PlayersCount; ++i) + for(unsigned int i = 0; i < PlayersCount; ++i) OnFinish(TeamPlayers[i], Time, aTimestamp); ChangeTeamState(Team, TEAMSTATE_FINISHED); //TODO: Make it better //ChangeTeamState(Team, TEAMSTATE_OPEN); @@ -241,31 +236,29 @@ void CGameTeams::CheckTeamFinished(int Team) bool CGameTeams::SetCharacterTeam(int ClientID, int Team) { //Check on wrong parameters. +1 for TEAM_SUPER - if (ClientID < 0 || ClientID >= MAX_CLIENTS || Team < 0 - || Team >= MAX_CLIENTS + 1) + if(ClientID < 0 || ClientID >= MAX_CLIENTS || Team < 0 || Team >= MAX_CLIENTS + 1) return false; //You can join to TEAM_SUPER at any time, but any other group you cannot if it started - if (Team != TEAM_SUPER && m_TeamState[Team] > TEAMSTATE_OPEN) + if(Team != TEAM_SUPER && m_TeamState[Team] > TEAMSTATE_OPEN) return false; //No need to switch team if you there - if (m_Core.Team(ClientID) == Team) + if(m_Core.Team(ClientID) == Team) return false; - if (!Character(ClientID)) + if(!Character(ClientID)) return false; //You cannot be in TEAM_SUPER if you not super - if (Team == TEAM_SUPER && !Character(ClientID)->m_Super) + if(Team == TEAM_SUPER && !Character(ClientID)->m_Super) return false; //if you begin race - if (Character(ClientID)->m_DDRaceState != DDRACE_NONE && Team != TEAM_SUPER) + if(Character(ClientID)->m_DDRaceState != DDRACE_NONE && Team != TEAM_SUPER) return false; //No cheating through noob filter with practice and then leaving team - if (m_Practice[m_Core.Team(ClientID)]) + if(m_Practice[m_Core.Team(ClientID)]) return false; //you can not join a team which is currently in the process of saving, //because the save-process can fail and then the team is reset into the game - if((Team != TEAM_SUPER && GetSaving(Team)) - || (m_Core.Team(ClientID) != TEAM_SUPER && GetSaving(m_Core.Team(ClientID)))) + if((Team != TEAM_SUPER && GetSaving(Team)) || (m_Core.Team(ClientID) != TEAM_SUPER && GetSaving(m_Core.Team(ClientID)))) return false; SetForceCharacterTeam(ClientID, Team); @@ -275,7 +268,7 @@ bool CGameTeams::SetCharacterTeam(int ClientID, int Team) void CGameTeams::SetForceCharacterTeam(int ClientID, int Team) { - if (Team != m_Core.Team(ClientID)) + if(Team != m_Core.Team(ClientID)) ForceLeaveTeam(ClientID); else m_TeeFinished[ClientID] = false; @@ -284,7 +277,7 @@ void CGameTeams::SetForceCharacterTeam(int ClientID, int Team) m_Core.Team(ClientID, Team); - if (OldTeam != Team) + if(OldTeam != Team) { for(int LoopClientID = 0; LoopClientID < MAX_CLIENTS; ++LoopClientID) if(GetPlayer(LoopClientID)) @@ -294,9 +287,9 @@ void CGameTeams::SetForceCharacterTeam(int ClientID, int Team) GetPlayer(ClientID)->m_VotedForPractice = false; } - if (Team != TEAM_SUPER && (m_TeamState[Team] == TEAMSTATE_EMPTY || m_TeamLocked[Team])) + if(Team != TEAM_SUPER && (m_TeamState[Team] == TEAMSTATE_EMPTY || m_TeamLocked[Team])) { - if (!m_TeamLocked[Team]) + if(!m_TeamLocked[Team]) ChangeTeamState(Team, TEAMSTATE_OPEN); ResetSwitchers(Team); @@ -307,18 +300,16 @@ void CGameTeams::ForceLeaveTeam(int ClientID) { m_TeeFinished[ClientID] = false; - if((m_Core.Team(ClientID) != TEAM_FLOCK || g_Config.m_SvTeam == 3) - && m_Core.Team(ClientID) != TEAM_SUPER - && m_TeamState[m_Core.Team(ClientID)] != TEAMSTATE_EMPTY) + if((m_Core.Team(ClientID) != TEAM_FLOCK || g_Config.m_SvTeam == 3) && m_Core.Team(ClientID) != TEAM_SUPER && m_TeamState[m_Core.Team(ClientID)] != TEAMSTATE_EMPTY) { bool NoOneInOldTeam = true; - for (int i = 0; i < MAX_CLIENTS; ++i) - if (i != ClientID && m_Core.Team(ClientID) == m_Core.Team(i)) + for(int i = 0; i < MAX_CLIENTS; ++i) + if(i != ClientID && m_Core.Team(ClientID) == m_Core.Team(i)) { NoOneInOldTeam = false; //all good exists someone in old team break; } - if (NoOneInOldTeam) + if(NoOneInOldTeam) { m_TeamState[m_Core.Team(ClientID)] = TEAMSTATE_EMPTY; @@ -333,13 +324,13 @@ void CGameTeams::ForceLeaveTeam(int ClientID) int CGameTeams::Count(int Team) const { - if (Team == TEAM_SUPER) + if(Team == TEAM_SUPER) return -1; int Count = 0; - for (int i = 0; i < MAX_CLIENTS; ++i) - if (m_Core.Team(i) == Team) + for(int i = 0; i < MAX_CLIENTS; ++i) + if(m_Core.Team(i) == Team) Count++; return Count; @@ -354,11 +345,11 @@ void CGameTeams::ChangeTeamState(int Team, int State) void CGameTeams::onChangeTeamState(int Team, int State, int OldState) { - if (OldState != State && State == TEAMSTATE_STARTED) + if(OldState != State && State == TEAMSTATE_STARTED) { // OnTeamStateStarting } - if (OldState != State && State == TEAMSTATE_FINISHED) + if(OldState != State && State == TEAMSTATE_FINISHED) { // OnTeamStateFinishing } @@ -366,8 +357,8 @@ void CGameTeams::onChangeTeamState(int Team, int State, int OldState) bool CGameTeams::TeamFinished(int Team) { - for (int i = 0; i < MAX_CLIENTS; ++i) - if (m_Core.Team(i) == Team && !m_TeeFinished[i]) + for(int i = 0; i < MAX_CLIENTS; ++i) + if(m_Core.Team(i) == Team && !m_TeeFinished[i]) return false; return true; } @@ -376,18 +367,18 @@ int64 CGameTeams::TeamMask(int Team, int ExceptID, int Asker) { int64 Mask = 0; - for (int i = 0; i < MAX_CLIENTS; ++i) + for(int i = 0; i < MAX_CLIENTS; ++i) { - if (i == ExceptID) + if(i == ExceptID) continue; // Explicitly excluded - if (!GetPlayer(i)) + if(!GetPlayer(i)) continue; // Player doesn't exist - if (!(GetPlayer(i)->GetTeam() == -1 || GetPlayer(i)->IsPaused())) + if(!(GetPlayer(i)->GetTeam() == -1 || GetPlayer(i)->IsPaused())) { // Not spectator - if (i != Asker) + if(i != Asker) { // Actions of other players - if (!Character(i)) + if(!Character(i)) continue; // Player is currently dead if(GetPlayer(i)->m_ShowOthers == 2) { @@ -396,20 +387,20 @@ int64 CGameTeams::TeamMask(int Team, int ExceptID, int Asker) } else if(GetPlayer(i)->m_ShowOthers == 0) { - if (m_Core.GetSolo(Asker)) + if(m_Core.GetSolo(Asker)) continue; // When in solo part don't show others - if (m_Core.GetSolo(i)) + if(m_Core.GetSolo(i)) continue; // When in solo part don't show others - if (m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) + if(m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) continue; // In different teams } } // See everything of yourself } - else if (GetPlayer(i)->m_SpectatorID != SPEC_FREEVIEW) + else if(GetPlayer(i)->m_SpectatorID != SPEC_FREEVIEW) { // Spectating specific player - if (GetPlayer(i)->m_SpectatorID != Asker) + if(GetPlayer(i)->m_SpectatorID != Asker) { // Actions of other players - if (!Character(GetPlayer(i)->m_SpectatorID)) + if(!Character(GetPlayer(i)->m_SpectatorID)) continue; // Player is currently dead if(GetPlayer(i)->m_ShowOthers == 2) { @@ -418,20 +409,20 @@ int64 CGameTeams::TeamMask(int Team, int ExceptID, int Asker) } else if(GetPlayer(i)->m_ShowOthers == 0) { - if (m_Core.GetSolo(Asker)) + if(m_Core.GetSolo(Asker)) continue; // When in solo part don't show others - if (m_Core.GetSolo(GetPlayer(i)->m_SpectatorID)) + if(m_Core.GetSolo(GetPlayer(i)->m_SpectatorID)) continue; // When in solo part don't show others - if (m_Core.Team(GetPlayer(i)->m_SpectatorID) != Team && m_Core.Team(GetPlayer(i)->m_SpectatorID) != TEAM_SUPER) + if(m_Core.Team(GetPlayer(i)->m_SpectatorID) != Team && m_Core.Team(GetPlayer(i)->m_SpectatorID) != TEAM_SUPER) continue; // In different teams } } // See everything of player you're spectating } else { // Freeview - if (GetPlayer(i)->m_SpecTeam) + if(GetPlayer(i)->m_SpecTeam) { // Show only players in own team when spectating - if (m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) + if(m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) continue; // in different teams } } @@ -443,10 +434,10 @@ int64 CGameTeams::TeamMask(int Team, int ExceptID, int Asker) void CGameTeams::SendTeamsState(int ClientID) { - if (g_Config.m_SvTeam == 3) + if(g_Config.m_SvTeam == 3) return; - if (!m_pGameContext->m_apPlayers[ClientID] || m_pGameContext->m_apPlayers[ClientID]->GetClientVersion() <= VERSION_DDRACE) + if(!m_pGameContext->m_apPlayers[ClientID] || m_pGameContext->m_apPlayers[ClientID]->GetClientVersion() <= VERSION_DDRACE) return; CMsgPacker Msg(NETMSGTYPE_SV_TEAMSSTATE); @@ -457,70 +448,70 @@ void CGameTeams::SendTeamsState(int ClientID) Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } -int CGameTeams::GetDDRaceState(CPlayer* Player) +int CGameTeams::GetDDRaceState(CPlayer *Player) { - if (!Player) + if(!Player) return DDRACE_NONE; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) return pChar->m_DDRaceState; return DDRACE_NONE; } -void CGameTeams::SetDDRaceState(CPlayer* Player, int DDRaceState) +void CGameTeams::SetDDRaceState(CPlayer *Player, int DDRaceState) { - if (!Player) + if(!Player) return; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) pChar->m_DDRaceState = DDRaceState; } -int CGameTeams::GetStartTime(CPlayer* Player) +int CGameTeams::GetStartTime(CPlayer *Player) { - if (!Player) + if(!Player) return 0; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) return pChar->m_StartTime; return 0; } -void CGameTeams::SetStartTime(CPlayer* Player, int StartTime) +void CGameTeams::SetStartTime(CPlayer *Player, int StartTime) { - if (!Player) + if(!Player) return; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) pChar->m_StartTime = StartTime; } -void CGameTeams::SetCpActive(CPlayer* Player, int CpActive) +void CGameTeams::SetCpActive(CPlayer *Player, int CpActive) { - if (!Player) + if(!Player) return; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) pChar->m_CpActive = CpActive; } -float *CGameTeams::GetCpCurrent(CPlayer* Player) +float *CGameTeams::GetCpCurrent(CPlayer *Player) { - if (!Player) + if(!Player) return NULL; - CCharacter* pChar = Player->GetCharacter(); - if (pChar) + CCharacter *pChar = Player->GetCharacter(); + if(pChar) return pChar->m_CpCurrent; return NULL; } -void CGameTeams::OnTeamFinish(CPlayer** Players, unsigned int Size, float Time, const char *pTimestamp) +void CGameTeams::OnTeamFinish(CPlayer **Players, unsigned int Size, float Time, const char *pTimestamp) { int PlayerCIDs[MAX_CLIENTS]; @@ -533,18 +524,18 @@ void CGameTeams::OnTeamFinish(CPlayer** Players, unsigned int Size, float Time, SetForceCharacterTeam(Players[i]->GetCID(), TEAM_FLOCK); char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s joined team 0", - GameServer()->Server()->ClientName(Players[i]->GetCID())); + GameServer()->Server()->ClientName(Players[i]->GetCID())); GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); } } - if (Size >= 2) + if(Size >= 2) GameServer()->Score()->SaveTeamScore(PlayerCIDs, Size, Time, pTimestamp); } -void CGameTeams::OnFinish(CPlayer* Player, float Time, const char *pTimestamp) +void CGameTeams::OnFinish(CPlayer *Player, float Time, const char *pTimestamp) { - if (!Player || !Player->IsPlaying()) + if(!Player || !Player->IsPlaying()) return; //TODO:DDRace:btd: this ugly const int ClientID = Player->GetCID(); @@ -553,50 +544,50 @@ void CGameTeams::OnFinish(CPlayer* Player, float Time, const char *pTimestamp) char aBuf[128]; SetCpActive(Player, -2); str_format(aBuf, sizeof(aBuf), - "%s finished in: %d minute(s) %5.2f second(s)", - Server()->ClientName(ClientID), (int)Time / 60, - Time - ((int)Time / 60 * 60)); - if (g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) + "%s finished in: %d minute(s) %5.2f second(s)", + Server()->ClientName(ClientID), (int)Time / 60, + Time - ((int)Time / 60 * 60)); + if(g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) GameServer()->SendChatTarget(ClientID, aBuf, CGameContext::CHAT_SIX); else GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, -1., CGameContext::CHAT_SIX); float Diff = fabs(Time - pData->m_BestTime); - if (Time - pData->m_BestTime < 0) + if(Time - pData->m_BestTime < 0) { // new record \o/ Server()->SaveDemo(ClientID, Time); - if (Diff >= 60) + if(Diff >= 60) str_format(aBuf, sizeof(aBuf), "New record: %d minute(s) %5.2f second(s) better.", - (int)Diff / 60, Diff - ((int)Diff / 60 * 60)); + (int)Diff / 60, Diff - ((int)Diff / 60 * 60)); else str_format(aBuf, sizeof(aBuf), "New record: %5.2f second(s) better.", - Diff); - if (g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) + Diff); + if(g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) GameServer()->SendChatTarget(ClientID, aBuf, CGameContext::CHAT_SIX); else GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, CGameContext::CHAT_SIX); } - else if (pData->m_BestTime != 0) // tee has already finished? + else if(pData->m_BestTime != 0) // tee has already finished? { Server()->StopRecord(ClientID); - if (Diff <= 0.005f) + if(Diff <= 0.005f) { GameServer()->SendChatTarget(ClientID, - "You finished with your best time."); + "You finished with your best time."); } else { - if (Diff >= 60) + if(Diff >= 60) str_format(aBuf, sizeof(aBuf), "%d minute(s) %5.2f second(s) worse, better luck next time.", - (int)Diff / 60, Diff - ((int)Diff / 60 * 60)); + (int)Diff / 60, Diff - ((int)Diff / 60 * 60)); else str_format(aBuf, sizeof(aBuf), - "%5.2f second(s) worse, better luck next time.", - Diff); + "%5.2f second(s) worse, better luck next time.", + Diff); GameServer()->SendChatTarget(ClientID, aBuf, CGameContext::CHAT_SIX); //this is private, sent only to the tee } } @@ -607,25 +598,24 @@ void CGameTeams::OnFinish(CPlayer* Player, float Time, const char *pTimestamp) bool CallSaveScore = g_Config.m_SvSaveWorseScores; - if (!pData->m_BestTime || Time < pData->m_BestTime) + if(!pData->m_BestTime || Time < pData->m_BestTime) { // update the score pData->Set(Time, GetCpCurrent(Player)); CallSaveScore = true; } - if (CallSaveScore) - if (g_Config.m_SvNamelessScore || !str_startswith(Server()->ClientName(ClientID), "nameless tee")) + if(CallSaveScore) + if(g_Config.m_SvNamelessScore || !str_startswith(Server()->ClientName(ClientID), "nameless tee")) GameServer()->Score()->SaveScore(ClientID, Time, pTimestamp, - GetCpCurrent(Player), Player->m_NotEligibleForFinish); + GetCpCurrent(Player), Player->m_NotEligibleForFinish); bool NeedToSendNewRecord = false; // update server best time - if (GameServer()->m_pController->m_CurrentRecord == 0 - || Time < GameServer()->m_pController->m_CurrentRecord) + if(GameServer()->m_pController->m_CurrentRecord == 0 || Time < GameServer()->m_pController->m_CurrentRecord) { // check for nameless - if (g_Config.m_SvNamelessScore || !str_startswith(Server()->ClientName(ClientID), "nameless tee")) + if(g_Config.m_SvNamelessScore || !str_startswith(Server()->ClientName(ClientID), "nameless tee")) { GameServer()->m_pController->m_CurrentRecord = Time; //dbg_msg("character", "Finish"); @@ -635,32 +625,31 @@ void CGameTeams::OnFinish(CPlayer* Player, float Time, const char *pTimestamp) SetDDRaceState(Player, DDRACE_FINISHED); // set player score - if (!pData->m_CurrentTime || pData->m_CurrentTime > Time) + if(!pData->m_CurrentTime || pData->m_CurrentTime > Time) { pData->m_CurrentTime = Time; NeedToSendNewRecord = true; } - if (NeedToSendNewRecord && Player->GetClientVersion() >= VERSION_DDRACE) + if(NeedToSendNewRecord && Player->GetClientVersion() >= VERSION_DDRACE) { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { - if (GameServer()->m_apPlayers[i] - && GameServer()->m_apPlayers[i]->GetClientVersion() >= VERSION_DDRACE) + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetClientVersion() >= VERSION_DDRACE) { GameServer()->SendRecord(i); } } } - if (Player->GetClientVersion() >= VERSION_DDRACE) + if(Player->GetClientVersion() >= VERSION_DDRACE) { CNetMsg_Sv_DDRaceTime Msg; Msg.m_Time = (int)(Time * 100.0f); Msg.m_Check = 0; Msg.m_Finish = 1; - if (pData->m_BestTime) + if(pData->m_BestTime) { float Diff = (Time - pData->m_BestTime) * 100; Msg.m_Check = (int)Diff; @@ -676,11 +665,11 @@ void CGameTeams::OnFinish(CPlayer* Player, float Time, const char *pTimestamp) Msg.m_Diff = Diff * 1000 * (Time < pData->m_BestTime ? -1 : 1); Msg.m_RecordPersonal = Time < pData->m_BestTime; Msg.m_RecordServer = Time < GameServer()->m_pController->m_CurrentRecord; - Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL | MSGFLAG_NORECORD, -1); } int TTime = 0 - (int)Time; - if (Player->m_Score < TTime || !Player->m_HasFinishScore) + if(Player->m_Score < TTime || !Player->m_HasFinishScore) { Player->m_Score = TTime; Player->m_HasFinishScore = true; @@ -704,9 +693,9 @@ void CGameTeams::ProcessSaveTeam() if(GameServer()->TeeHistorianActive()) { GameServer()->TeeHistorian()->RecordTeamSaveSuccess( - Team, - m_pSaveTeamResult[Team]->m_SaveID, - m_pSaveTeamResult[Team]->m_SavedTeam.GetString()); + Team, + m_pSaveTeamResult[Team]->m_SaveID, + m_pSaveTeamResult[Team]->m_SavedTeam.GetString()); } ResetSavedTeam(m_pSaveTeamResult[Team]->m_RequestingPlayer, Team); char aSaveID[UUID_MAXSTRSIZE]; @@ -728,9 +717,9 @@ void CGameTeams::ProcessSaveTeam() if(GameServer()->TeeHistorianActive()) { GameServer()->TeeHistorian()->RecordTeamLoadSuccess( - Team, - m_pSaveTeamResult[Team]->m_SaveID, - m_pSaveTeamResult[Team]->m_SavedTeam.GetString()); + Team, + m_pSaveTeamResult[Team]->m_SaveID, + m_pSaveTeamResult[Team]->m_SavedTeam.GetString()); } if(Count(Team) > 0) { @@ -761,7 +750,7 @@ void CGameTeams::OnCharacterSpawn(int ClientID) if(GetSaving(Team)) return; - if (m_Core.Team(ClientID) >= TEAM_SUPER || !m_TeamLocked[Team]) + if(m_Core.Team(ClientID) >= TEAM_SUPER || !m_TeamLocked[Team]) { if(g_Config.m_SvTeam != 3) SetForceCharacterTeam(ClientID, TEAM_FLOCK); @@ -808,7 +797,7 @@ void CGameTeams::OnCharacterDeath(int ClientID, int Weapon) if(i != ClientID) { GameServer()->m_apPlayers[i]->KillCharacter(WEAPON_SELF); - if (Weapon == WEAPON_SELF) + if(Weapon == WEAPON_SELF) GameServer()->m_apPlayers[i]->Respawn(true); // spawn the rest of team with weak hook on the killer } if(Count(Team) > 1) @@ -866,7 +855,7 @@ void CGameTeams::ResetSavedTeam(int ClientID, int Team) } else { - for (int i = 0; i < MAX_CLIENTS; i++) + for(int i = 0; i < MAX_CLIENTS; i++) { if(m_Core.Team(i) == Team && GameServer()->m_apPlayers[i]) { diff --git a/src/game/server/teams.h b/src/game/server/teams.h index 1f5a7683c..a99588878 100644 --- a/src/game/server/teams.h +++ b/src/game/server/teams.h @@ -3,8 +3,8 @@ #define GAME_SERVER_TEAMS_H #include -#include #include +#include class CGameTeams { @@ -15,17 +15,20 @@ class CGameTeams bool m_Practice[MAX_CLIENTS]; std::shared_ptr m_pSaveTeamResult[MAX_CLIENTS]; - class CGameContext * m_pGameContext; + class CGameContext *m_pGameContext; void CheckTeamFinished(int ClientID); bool TeamFinished(int Team); - void OnTeamFinish(CPlayer** Players, unsigned int Size, float Time, const char *pTimestamp); - void OnFinish(CPlayer* Player, float Time, const char *pTimestamp); + void OnTeamFinish(CPlayer **Players, unsigned int Size, float Time, const char *pTimestamp); + void OnFinish(CPlayer *Player, float Time, const char *pTimestamp); public: enum { - TEAMSTATE_EMPTY, TEAMSTATE_OPEN, TEAMSTATE_STARTED, TEAMSTATE_FINISHED + TEAMSTATE_EMPTY, + TEAMSTATE_OPEN, + TEAMSTATE_STARTED, + TEAMSTATE_FINISHED }; CTeamsCore m_Core; @@ -33,11 +36,11 @@ public: CGameTeams(CGameContext *pGameContext); //helper methods - CCharacter* Character(int ClientID) + CCharacter *Character(int ClientID) { return GameServer()->GetPlayerChar(ClientID); } - CPlayer* GetPlayer(int ClientID) + CPlayer *GetPlayer(int ClientID) { return GameServer()->m_apPlayers[ClientID]; } @@ -80,12 +83,12 @@ public: int m_LastChat[MAX_CLIENTS]; - int GetDDRaceState(CPlayer* Player); - int GetStartTime(CPlayer* Player); - float *GetCpCurrent(CPlayer* Player); - void SetDDRaceState(CPlayer* Player, int DDRaceState); - void SetStartTime(CPlayer* Player, int StartTime); - void SetCpActive(CPlayer* Player, int CpActive); + int GetDDRaceState(CPlayer *Player); + int GetStartTime(CPlayer *Player); + float *GetCpCurrent(CPlayer *Player); + void SetDDRaceState(CPlayer *Player, int DDRaceState); + void SetStartTime(CPlayer *Player, int StartTime); + void SetCpActive(CPlayer *Player, int CpActive); void KillSavedTeam(int ClientID, int Team); void ResetSavedTeam(int ClientID, int Team); void ProcessSaveTeam(); @@ -102,7 +105,7 @@ public: bool TeamLocked(int Team) { - if (Team <= TEAM_FLOCK || Team >= TEAM_SUPER) + if(Team <= TEAM_FLOCK || Team >= TEAM_SUPER) return false; return m_TeamLocked[Team]; diff --git a/src/game/server/teehistorian.h b/src/game/server/teehistorian.h index 62599b530..0e3be5141 100644 --- a/src/game/server/teehistorian.h +++ b/src/game/server/teehistorian.h @@ -41,7 +41,7 @@ public: enum { - PROTOCOL_6=1, + PROTOCOL_6 = 1, PROTOCOL_7, }; diff --git a/src/game/server/teeinfo.cpp b/src/game/server/teeinfo.cpp index 7cfaffcbc..03b70f019 100644 --- a/src/game/server/teeinfo.cpp +++ b/src/game/server/teeinfo.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include "teeinfo.h" @@ -12,22 +12,22 @@ struct StdSkin }; static StdSkin g_StdSkins[] = { -{"default",{"standard","","","standard","standard","standard"},{true,false,false,true,true,false},{1798004,0,0,1799582,1869630,0}}, -{"bluekitty",{"kitty","whisker","","standard","standard","standard"},{true,true,false,true,true,false},{8681144,-8229413,0,7885547,7885547,0}}, -{"bluestripe",{"standard","stripes","","standard","standard","standard"},{true,false,false,true,true,false},{10187898,0,0,750848,1944919,0}}, -{"brownbear",{"bear","bear","hair","standard","standard","standard"},{true,true,false,true,true,false},{1082745,-15634776,0,1082745,1147174,0}}, -{"cammo",{"standard","cammo2","","standard","standard","standard"},{true,true,false,true,true,false},{5334342,-11771603,0,750848,1944919,0}}, -{"cammostripes",{"standard","cammostripes","","standard","standard","standard"},{true,true,false,true,true,false},{5334342,-14840320,0,750848,1944919,0}}, -{"coala",{"koala","twinbelly","","standard","standard","standard"},{true,true,false,true,true,false},{184,-15397662,0,184,9765959,0}}, -{"limekitty",{"kitty","whisker","","standard","standard","standard"},{true,true,false,true,true,false},{4612803,-12229920,0,3827951,3827951,0}}, -{"pinky",{"standard","whisker","","standard","standard","standard"},{true,true,false,true,true,false},{15911355,-801066,0,15043034,15043034,0}}, -{"redbopp",{"standard","donny","unibop","standard","standard","standard"},{true,true,true,true,true,false},{16177260,-16590390,16177260,16177260,7624169,0}}, -{"redstripe",{"standard","stripe","","standard","standard","standard"},{true,false,false,true,true,false},{16307835,0,0,184,9765959,0}}, -{"saddo",{"standard","saddo","","standard","standard","standard"},{true,true,false,true,true,false},{7171455,-9685436,0,3640746,5792119,0}}, -{"toptri",{"standard","toptri","","standard","standard","standard"},{true,false,false,true,true,false},{6119331,0,0,3640746,5792119,0}}, -{"twinbop",{"standard","duodonny","twinbopp","standard","standard","standard"},{true,true,true,true,true,false},{15310519,-1600806,15310519,15310519,37600,0}}, -{"twintri",{"standard","twintri","","standard","standard","standard"},{true,true,false,true,true,false},{3447932,-14098717,0,185,9634888,0}}, -{"warpaint",{"standard","warpaint","","standard","standard","standard"},{true,false,false,true,true,false},{1944919,0,0,750337,1944919,0}}}; + {"default", {"standard", "", "", "standard", "standard", "standard"}, {true, false, false, true, true, false}, {1798004, 0, 0, 1799582, 1869630, 0}}, + {"bluekitty", {"kitty", "whisker", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {8681144, -8229413, 0, 7885547, 7885547, 0}}, + {"bluestripe", {"standard", "stripes", "", "standard", "standard", "standard"}, {true, false, false, true, true, false}, {10187898, 0, 0, 750848, 1944919, 0}}, + {"brownbear", {"bear", "bear", "hair", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {1082745, -15634776, 0, 1082745, 1147174, 0}}, + {"cammo", {"standard", "cammo2", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {5334342, -11771603, 0, 750848, 1944919, 0}}, + {"cammostripes", {"standard", "cammostripes", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {5334342, -14840320, 0, 750848, 1944919, 0}}, + {"coala", {"koala", "twinbelly", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {184, -15397662, 0, 184, 9765959, 0}}, + {"limekitty", {"kitty", "whisker", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {4612803, -12229920, 0, 3827951, 3827951, 0}}, + {"pinky", {"standard", "whisker", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {15911355, -801066, 0, 15043034, 15043034, 0}}, + {"redbopp", {"standard", "donny", "unibop", "standard", "standard", "standard"}, {true, true, true, true, true, false}, {16177260, -16590390, 16177260, 16177260, 7624169, 0}}, + {"redstripe", {"standard", "stripe", "", "standard", "standard", "standard"}, {true, false, false, true, true, false}, {16307835, 0, 0, 184, 9765959, 0}}, + {"saddo", {"standard", "saddo", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {7171455, -9685436, 0, 3640746, 5792119, 0}}, + {"toptri", {"standard", "toptri", "", "standard", "standard", "standard"}, {true, false, false, true, true, false}, {6119331, 0, 0, 3640746, 5792119, 0}}, + {"twinbop", {"standard", "duodonny", "twinbopp", "standard", "standard", "standard"}, {true, true, true, true, true, false}, {15310519, -1600806, 15310519, 15310519, 37600, 0}}, + {"twintri", {"standard", "twintri", "", "standard", "standard", "standard"}, {true, true, false, true, true, false}, {3447932, -14098717, 0, 185, 9634888, 0}}, + {"warpaint", {"standard", "warpaint", "", "standard", "standard", "standard"}, {true, false, false, true, true, false}, {1944919, 0, 0, 750337, 1944919, 0}}}; CTeeInfo::CTeeInfo(const char *pSkinName, int UseCustomColor, int ColorBody, int ColorFeet) { @@ -103,9 +103,7 @@ void CTeeInfo::FromSixup() bool match = true; for(int p = 0; p < 6; p++) { - if(str_comp(m_apSkinPartNames[p], g_StdSkins[s].m_apSkinPartNames[p]) - || m_aUseCustomColors[p] != g_StdSkins[s].m_aUseCustomColors[p] - || (m_aUseCustomColors[p] && m_aSkinPartColors[p] != g_StdSkins[s].m_aSkinPartColors[p])) + if(str_comp(m_apSkinPartNames[p], g_StdSkins[s].m_apSkinPartNames[p]) || m_aUseCustomColors[p] != g_StdSkins[s].m_aUseCustomColors[p] || (m_aUseCustomColors[p] && m_aSkinPartColors[p] != g_StdSkins[s].m_aSkinPartColors[p])) { match = false; break; diff --git a/src/game/server/teeinfo.h b/src/game/server/teeinfo.h index 66b02b395..4bfa9a70d 100644 --- a/src/game/server/teeinfo.h +++ b/src/game/server/teeinfo.h @@ -4,26 +4,26 @@ class CTeeInfo { public: - constexpr static const float DARKEST_LGT_7 = 61/255.0f; + constexpr static const float DARKEST_LGT_7 = 61 / 255.0f; - char m_SkinName[64] = {'\0'}; - int m_UseCustomColor = 0; - int m_ColorBody = 0; - int m_ColorFeet = 0; + char m_SkinName[64] = {'\0'}; + int m_UseCustomColor = 0; + int m_ColorBody = 0; + int m_ColorFeet = 0; - // 0.7 - char m_apSkinPartNames[6][24] = {"", "", "", "", "", ""}; - bool m_aUseCustomColors[6] = {false, false, false, false, false, false}; - int m_aSkinPartColors[6] = {0, 0, 0, 0, 0, 0}; + // 0.7 + char m_apSkinPartNames[6][24] = {"", "", "", "", "", ""}; + bool m_aUseCustomColors[6] = {false, false, false, false, false, false}; + int m_aSkinPartColors[6] = {0, 0, 0, 0, 0, 0}; - CTeeInfo() = default; + CTeeInfo() = default; - CTeeInfo(const char *pSkinName, int UseCustomColor, int ColorBody, int ColorFeet); + CTeeInfo(const char *pSkinName, int UseCustomColor, int ColorBody, int ColorFeet); - // This constructor will assume all arrays are of length 6 - CTeeInfo(const char *pSkinPartNames[6], int *pUseCustomColors, int *pSkinPartColors); + // This constructor will assume all arrays are of length 6 + CTeeInfo(const char *pSkinPartNames[6], int *pUseCustomColors, int *pSkinPartColors); - void FromSixup(); - void ToSixup(); + void FromSixup(); + void ToSixup(); }; #endif //GAME_SERVER_TEEINFO_H diff --git a/src/game/teamscore.cpp b/src/game/teamscore.cpp index 37ec7c887..eb433a1ac 100644 --- a/src/game/teamscore.cpp +++ b/src/game/teamscore.cpp @@ -24,18 +24,16 @@ void CTeamsCore::Team(int ClientID, int Team) bool CTeamsCore::CanKeepHook(int ClientID1, int ClientID2) const { - if (m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) - || ClientID1 == ClientID2) + if(m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || ClientID1 == ClientID2) return true; return m_Team[ClientID1] == m_Team[ClientID2]; } bool CTeamsCore::CanCollide(int ClientID1, int ClientID2) const { - if (m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) - || ClientID1 == ClientID2) + if(m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || ClientID1 == ClientID2) return true; - if (m_IsSolo[ClientID1] || m_IsSolo[ClientID2]) + if(m_IsSolo[ClientID1] || m_IsSolo[ClientID2]) return false; return m_Team[ClientID1] == m_Team[ClientID2]; } @@ -44,7 +42,7 @@ void CTeamsCore::Reset() { m_IsDDRace16 = false; - for (int i = 0; i < MAX_CLIENTS; ++i) + for(int i = 0; i < MAX_CLIENTS; ++i) { if(g_Config.m_SvTeam == 3) m_Team[i] = i; diff --git a/src/game/teamscore.h b/src/game/teamscore.h index 13704ca52..dc44d3048 100644 --- a/src/game/teamscore.h +++ b/src/game/teamscore.h @@ -6,13 +6,16 @@ enum { - TEAM_FLOCK = 0, TEAM_SUPER = MAX_CLIENTS, VANILLA_TEAM_SUPER = VANILLA_MAX_CLIENTS + TEAM_FLOCK = 0, + TEAM_SUPER = MAX_CLIENTS, + VANILLA_TEAM_SUPER = VANILLA_MAX_CLIENTS }; class CTeamsCore { int m_Team[MAX_CLIENTS]; bool m_IsSolo[MAX_CLIENTS]; + public: bool m_IsDDRace16; diff --git a/src/game/tuning.h b/src/game/tuning.h index fd63084f8..b1912b1a7 100644 --- a/src/game/tuning.h +++ b/src/game/tuning.h @@ -53,7 +53,7 @@ MACRO_TUNING_PARAM(HammerStrength, hammer_strength, 1.0f, "Hammer strength") MACRO_TUNING_PARAM(HookDuration, hook_duration, 1.25f, "Hook duration") MACRO_TUNING_PARAM(HammerFireDelay, hammer_fire_delay, 125, "Delay of hammering") -MACRO_TUNING_PARAM(GunFireDelay, gun_fire_delay, 125, "Delay of firing gun" ) +MACRO_TUNING_PARAM(GunFireDelay, gun_fire_delay, 125, "Delay of firing gun") MACRO_TUNING_PARAM(ShotgunFireDelay, shotgun_fire_delay, 500, "Delay of firing shotgun") MACRO_TUNING_PARAM(GrenadeFireDelay, grenade_fire_delay, 500, "Delay of firing grenade") MACRO_TUNING_PARAM(LaserFireDelay, laser_fire_delay, 800, "Delay of firing laser laser") diff --git a/src/game/variables.h b/src/game/variables.h index 01f335c33..d81cc8812 100644 --- a/src/game/variables.h +++ b/src/game/variables.h @@ -5,77 +5,77 @@ #undef GAME_VARIABLES_H // this file will be included several times // client -MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict client movements") -MACRO_CONFIG_INT(ClPredictDummy, cl_predict_dummy, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict dummy movements") -MACRO_CONFIG_INT(ClAntiPingLimit, cl_antiping_limit, 0, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Antiping limit (0 to disable)") -MACRO_CONFIG_INT(ClAntiPing, cl_antiping, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Enable antiping, i. e. more aggressive prediction.") -MACRO_CONFIG_INT(ClAntiPingPlayers, cl_antiping_players, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict other player's movement more aggressively (only enabled if cl_antiping is set to 1)") -MACRO_CONFIG_INT(ClAntiPingGrenade, cl_antiping_grenade, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict grenades (only enabled if cl_antiping is set to 1)") -MACRO_CONFIG_INT(ClAntiPingWeapons, cl_antiping_weapons, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict weapon projectiles (only enabled if cl_antiping is set to 1)") -MACRO_CONFIG_INT(ClAntiPingSmooth, cl_antiping_smooth, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Make the prediction of other player's movement smoother") -MACRO_CONFIG_INT(ClAntiPingGunfire, cl_antiping_gunfire, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict gunfire and show predicted weapon physics (with cl_antiping_grenade 1 and cl_antiping_weapons 1)") +MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict client movements") +MACRO_CONFIG_INT(ClPredictDummy, cl_predict_dummy, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict dummy movements") +MACRO_CONFIG_INT(ClAntiPingLimit, cl_antiping_limit, 0, 0, 200, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Antiping limit (0 to disable)") +MACRO_CONFIG_INT(ClAntiPing, cl_antiping, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Enable antiping, i. e. more aggressive prediction.") +MACRO_CONFIG_INT(ClAntiPingPlayers, cl_antiping_players, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict other player's movement more aggressively (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClAntiPingGrenade, cl_antiping_grenade, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict grenades (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClAntiPingWeapons, cl_antiping_weapons, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict weapon projectiles (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClAntiPingSmooth, cl_antiping_smooth, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Make the prediction of other player's movement smoother") +MACRO_CONFIG_INT(ClAntiPingGunfire, cl_antiping_gunfire, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Predict gunfire and show predicted weapon physics (with cl_antiping_grenade 1 and cl_antiping_weapons 1)") -MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show name plates") -MACRO_CONFIG_INT(ClAfkEmote, cl_afk_emote, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show zzz emote next to afk players") -MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show name plates disregarding of distance") -MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use team colors for name plates") -MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the name plates from 0 to 100%") -MACRO_CONFIG_INT(ClNameplatesClan, cl_nameplates_clan, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show clan in name plates") -MACRO_CONFIG_INT(ClNameplatesClanSize, cl_nameplates_clan_size, 30, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the clan plates from 0 to 100%") -MACRO_CONFIG_INT(ClNameplatesIDs, cl_nameplates_ids, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show IDs in name plates") -MACRO_CONFIG_INT(ClNameplatesHA, cl_nameplates_ha, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show Health and Armor in name plates") -MACRO_CONFIG_INT(ClNameplatesHASize, cl_nameplates_ha_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the health and armor nameplates from 0 to 100%") -MACRO_CONFIG_INT(ClNameplatesOwn, cl_nameplates_own, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show own name plate (useful for demo recording)") -MACRO_CONFIG_INT(ClNameplatesFriendMark, cl_nameplates_friendmark, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show friend mark (♥) in name plates") -MACRO_CONFIG_INT(ClTextEntities, cl_text_entities, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Render textual entity data") -MACRO_CONFIG_INT(ClTextEntitiesSize, cl_text_entities_size, 100, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of textual entity data from 0 to 100%") +MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show name plates") +MACRO_CONFIG_INT(ClAfkEmote, cl_afk_emote, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show zzz emote next to afk players") +MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Always show name plates disregarding of distance") +MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Use team colors for name plates") +MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Size of the name plates from 0 to 100%") +MACRO_CONFIG_INT(ClNameplatesClan, cl_nameplates_clan, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show clan in name plates") +MACRO_CONFIG_INT(ClNameplatesClanSize, cl_nameplates_clan_size, 30, 0, 100, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Size of the clan plates from 0 to 100%") +MACRO_CONFIG_INT(ClNameplatesIDs, cl_nameplates_ids, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show IDs in name plates") +MACRO_CONFIG_INT(ClNameplatesHA, cl_nameplates_ha, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show Health and Armor in name plates") +MACRO_CONFIG_INT(ClNameplatesHASize, cl_nameplates_ha_size, 50, 0, 100, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Size of the health and armor nameplates from 0 to 100%") +MACRO_CONFIG_INT(ClNameplatesOwn, cl_nameplates_own, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show own name plate (useful for demo recording)") +MACRO_CONFIG_INT(ClNameplatesFriendMark, cl_nameplates_friendmark, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show friend mark (♥) in name plates") +MACRO_CONFIG_INT(ClTextEntities, cl_text_entities, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Render textual entity data") +MACRO_CONFIG_INT(ClTextEntitiesSize, cl_text_entities_size, 100, 0, 100, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Size of textual entity data from 0 to 100%") -MACRO_CONFIG_COL(ClAuthedPlayerColor, cl_authed_player_color, 5898211, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Color of name of authenticated player in scoreboard") -MACRO_CONFIG_COL(ClSameClanColor, cl_same_clan_color, 5898211, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Clan color of players with the same clan as you in scoreboard.") +MACRO_CONFIG_COL(ClAuthedPlayerColor, cl_authed_player_color, 5898211, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Color of name of authenticated player in scoreboard") +MACRO_CONFIG_COL(ClSameClanColor, cl_same_clan_color, 5898211, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Clan color of players with the same clan as you in scoreboard.") -MACRO_CONFIG_INT(ClEnablePingColor, cl_enable_ping_color, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether ping is colored in scoreboard.") -MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup") -MACRO_CONFIG_INT(ClAutoswitchWeaponsOutOfAmmo, cl_autoswitch_weapons_out_of_ammo, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon when out of ammo") +MACRO_CONFIG_INT(ClEnablePingColor, cl_enable_ping_color, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Whether ping is colored in scoreboard.") +MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Auto switch weapon on pickup") +MACRO_CONFIG_INT(ClAutoswitchWeaponsOutOfAmmo, cl_autoswitch_weapons_out_of_ammo, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Auto switch weapon when out of ammo") -MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD") -MACRO_CONFIG_INT(ClShowhudHealthAmmo, cl_showhud_healthammo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD (Health + Ammo)") -MACRO_CONFIG_INT(ClShowhudScore, cl_showhud_score, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD (Score)") -MACRO_CONFIG_INT(ClShowRecord, cl_showrecord, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show old style DDRace client records") -MACRO_CONFIG_INT(ClShowNotifications, cl_shownotifications, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Make the client notify when someone highlights you") -MACRO_CONFIG_INT(ClShowEmotes, cl_showemotes, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show tee emotes") -MACRO_CONFIG_INT(ClShowChat, cl_showchat, 1, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat (2 to always show large chat area)") -MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show only chat messages from friends") -MACRO_CONFIG_INT(ClShowChatSystem, cl_show_chat_system, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat messages from the server") -MACRO_CONFIG_INT(ClShowKillMessages, cl_showkillmessages, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show kill messages") -MACRO_CONFIG_INT(ClShowVotesAfterVoting, cl_show_votes_after_voting, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show votes window after voting") -MACRO_CONFIG_INT(ClShowLocalTimeAlways, cl_show_local_time_always, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show local time") -MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter") -MACRO_CONFIG_INT(ClShowpred, cl_showpred, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame prediction time in milliseconds") -MACRO_CONFIG_INT(ClEyeWheel, cl_eye_wheel, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show eye wheel along together with emotes") -MACRO_CONFIG_INT(ClEyeDuration, cl_eye_duration, 999999, 1, 999999, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long the eyes emotes last") +MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame HUD") +MACRO_CONFIG_INT(ClShowhudHealthAmmo, cl_showhud_healthammo, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame HUD (Health + Ammo)") +MACRO_CONFIG_INT(ClShowhudScore, cl_showhud_score, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame HUD (Score)") +MACRO_CONFIG_INT(ClShowRecord, cl_showrecord, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show old style DDRace client records") +MACRO_CONFIG_INT(ClShowNotifications, cl_shownotifications, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Make the client notify when someone highlights you") +MACRO_CONFIG_INT(ClShowEmotes, cl_showemotes, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show tee emotes") +MACRO_CONFIG_INT(ClShowChat, cl_showchat, 1, 0, 2, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show chat (2 to always show large chat area)") +MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show only chat messages from friends") +MACRO_CONFIG_INT(ClShowChatSystem, cl_show_chat_system, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show chat messages from the server") +MACRO_CONFIG_INT(ClShowKillMessages, cl_showkillmessages, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show kill messages") +MACRO_CONFIG_INT(ClShowVotesAfterVoting, cl_show_votes_after_voting, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show votes window after voting") +MACRO_CONFIG_INT(ClShowLocalTimeAlways, cl_show_local_time_always, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Always show local time") +MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame FPS counter") +MACRO_CONFIG_INT(ClShowpred, cl_showpred, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame prediction time in milliseconds") +MACRO_CONFIG_INT(ClEyeWheel, cl_eye_wheel, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show eye wheel along together with emotes") +MACRO_CONFIG_INT(ClEyeDuration, cl_eye_duration, 999999, 1, 999999, CFGFLAG_CLIENT | CFGFLAG_SAVE, "How long the eyes emotes last") -MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Load sound files threaded") +MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Load sound files threaded") -MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Warn about team balance") +MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Warn about team balance") -MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 0, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 400, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClMouseMinDistance, cl_mouse_min_distance, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 0, 0, 0, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 0, 0, 200, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 400, 0, 0, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMouseMinDistance, cl_mouse_min_distance, 0, 0, 0, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClDyncam, cl_dyncam, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Enable dyncam") -MACRO_CONFIG_INT(ClDyncamMaxDistance, cl_dyncam_max_distance, 1000, 0, 2000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Maximum dynamic camera distance") -MACRO_CONFIG_INT(ClDyncamMinDistance, cl_dyncam_min_distance, 0, 0, 2000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Minimum dynamic camera distance") -MACRO_CONFIG_INT(ClDyncamMousesens, cl_dyncam_mousesens, 0, 0, 100000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Mouse sens used when dyncam is toggled on") -MACRO_CONFIG_INT(ClDyncamDeadzone, cl_dyncam_deadzone, 300, 1, 1300, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dynamic camera dead zone") -MACRO_CONFIG_INT(ClDyncamFollowFactor, cl_dyncam_follow_factor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dynamic camera follow factor") +MACRO_CONFIG_INT(ClDyncam, cl_dyncam, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Enable dyncam") +MACRO_CONFIG_INT(ClDyncamMaxDistance, cl_dyncam_max_distance, 1000, 0, 2000, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Maximum dynamic camera distance") +MACRO_CONFIG_INT(ClDyncamMinDistance, cl_dyncam_min_distance, 0, 0, 2000, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Minimum dynamic camera distance") +MACRO_CONFIG_INT(ClDyncamMousesens, cl_dyncam_mousesens, 0, 0, 100000, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Mouse sens used when dyncam is toggled on") +MACRO_CONFIG_INT(ClDyncamDeadzone, cl_dyncam_deadzone, 300, 1, 1300, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Dynamic camera dead zone") +MACRO_CONFIG_INT(ClDyncamFollowFactor, cl_dyncam_follow_factor, 60, 0, 200, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Dynamic camera follow factor") -MACRO_CONFIG_INT(EdZoomTarget, ed_zoom_target, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Zoom to the current mouse target") -MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(EdZoomTarget, ed_zoom_target, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Zoom to the current mouse target") +MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") -MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long to show the server message of the day") +MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT | CFGFLAG_SAVE, "How long to show the server message of the day") // http map download MACRO_CONFIG_STR(ClMapDownloadUrl, cl_map_download_url, 100, "https://maps2.ddnet.tw", CFGFLAG_CLIENT | CFGFLAG_SAVE, "URL used to download maps (can start with http:// or https://)") @@ -90,8 +90,8 @@ MACRO_CONFIG_INT(ClDownloadSkins, cl_download_skins, 1, 0, 1, CFGFLAG_CLIENT | C MACRO_CONFIG_INT(ClAutoStatboardScreenshot, cl_auto_statboard_screenshot, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Automatically take game over statboard screenshot") MACRO_CONFIG_INT(ClAutoStatboardScreenshotMax, cl_auto_statboard_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE | CFGFLAG_CLIENT, "Maximum number of automatically created statboard screenshots (0 = no limit)") -MACRO_CONFIG_INT(ClDefaultZoom, cl_default_zoom, 10, 0, 20, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Default zoom level (10 default, min 0, max 20)") -MACRO_CONFIG_INT(ClSmoothZoomTime, cl_smooth_zoom_time, 250, 0, 5000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Time of smooth zoom animation in ms (0 for off)") +MACRO_CONFIG_INT(ClDefaultZoom, cl_default_zoom, 10, 0, 20, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Default zoom level (10 default, min 0, max 20)") +MACRO_CONFIG_INT(ClSmoothZoomTime, cl_smooth_zoom_time, 250, 0, 5000, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Time of smooth zoom animation in ms (0 for off)") MACRO_CONFIG_INT(ClPlayerUseCustomColor, player_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Toggles usage of custom colors") MACRO_CONFIG_COL(ClPlayerColorBody, player_color_body, 65408, CFGFLAG_CLIENT | CFGFLAG_SAVE | CFGFLAG_COLLIGHT, "Player body color") @@ -100,36 +100,36 @@ MACRO_CONFIG_STR(ClPlayerSkin, player_skin, 24, "default", CFGFLAG_CLIENT | CFGF MACRO_CONFIG_STR(ClSkinPrefix, cl_skin_prefix, 12, "", CFGFLAG_CLIENT | CFGFLAG_SAVE, "Replace the skins by skins with this prefix (e.g. kitty, santa)") MACRO_CONFIG_INT(ClFatSkins, cl_fat_skins, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Enable fat skins") -MACRO_CONFIG_INT(UiPage, ui_page, 9, 0, 12, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page") -MACRO_CONFIG_INT(UiSettingsPage, ui_settings_page, 0, 0, 8, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface settings page") -MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toolbox page") -MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address") -MACRO_CONFIG_INT(UiScale, ui_scale, 100, 50, 150, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface scale") -MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 200, 1, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor") +MACRO_CONFIG_INT(UiPage, ui_page, 9, 0, 12, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Interface page") +MACRO_CONFIG_INT(UiSettingsPage, ui_settings_page, 0, 0, 8, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Interface settings page") +MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Toolbox page") +MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT | CFGFLAG_SAVE, "Interface server address") +MACRO_CONFIG_INT(UiScale, ui_scale, 100, 50, 150, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Interface scale") +MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 200, 1, 100000, CFGFLAG_SAVE | CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor") -MACRO_CONFIG_COL(UiColor, ui_color, 0xE4A046AF, CFGFLAG_CLIENT|CFGFLAG_SAVE|CFGFLAG_COLALPHA, "Interface color") // 160 70 175 228 hasalpha +MACRO_CONFIG_COL(UiColor, ui_color, 0xE4A046AF, CFGFLAG_CLIENT | CFGFLAG_SAVE | CFGFLAG_COLALPHA, "Interface color") // 160 70 175 228 hasalpha -MACRO_CONFIG_INT(UiColorizePing, ui_colorize_ping, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Highlight ping") -MACRO_CONFIG_INT(UiColorizeGametype, ui_colorize_gametype, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Highlight gametype") +MACRO_CONFIG_INT(UiColorizePing, ui_colorize_ping, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Highlight ping") +MACRO_CONFIG_INT(UiColorizeGametype, ui_colorize_gametype, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Highlight gametype") MACRO_CONFIG_STR(UiDemoSelected, ui_demo_selected, 256, "", CFGFLAG_CLIENT | CFGFLAG_SAVE, "Selected demo file") MACRO_CONFIG_INT(UiCloseWindowAfterChangingSetting, ui_close_window_after_changing_setting, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Close window after changing setting") MACRO_CONFIG_INT(UiUnreadNews, ui_unread_news, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Whether there is unread news") -MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable clipping") +MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Disable clipping") // dummy -MACRO_CONFIG_STR(ClDummyName, dummy_name, 16, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Name of the dummy") -MACRO_CONFIG_STR(ClDummyClan, dummy_clan, 12, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clan of the dummy") -MACRO_CONFIG_INT(ClDummyCountry, dummy_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Country of the Dummy") -MACRO_CONFIG_INT(ClDummyUseCustomColor, dummy_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors") -MACRO_CONFIG_COL(ClDummyColorBody, dummy_color_body, 65408, CFGFLAG_CLIENT|CFGFLAG_SAVE|CFGFLAG_COLLIGHT, "Dummy body color") -MACRO_CONFIG_COL(ClDummyColorFeet, dummy_color_feet, 65408, CFGFLAG_CLIENT|CFGFLAG_SAVE|CFGFLAG_COLLIGHT, "Dummy feet color") -MACRO_CONFIG_STR(ClDummySkin, dummy_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dummy skin") +MACRO_CONFIG_STR(ClDummyName, dummy_name, 16, "", CFGFLAG_SAVE | CFGFLAG_CLIENT, "Name of the dummy") +MACRO_CONFIG_STR(ClDummyClan, dummy_clan, 12, "", CFGFLAG_SAVE | CFGFLAG_CLIENT, "Clan of the dummy") +MACRO_CONFIG_INT(ClDummyCountry, dummy_country, -1, -1, 1000, CFGFLAG_SAVE | CFGFLAG_CLIENT, "Country of the Dummy") +MACRO_CONFIG_INT(ClDummyUseCustomColor, dummy_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Toggles usage of custom colors") +MACRO_CONFIG_COL(ClDummyColorBody, dummy_color_body, 65408, CFGFLAG_CLIENT | CFGFLAG_SAVE | CFGFLAG_COLLIGHT, "Dummy body color") +MACRO_CONFIG_COL(ClDummyColorFeet, dummy_color_feet, 65408, CFGFLAG_CLIENT | CFGFLAG_SAVE | CFGFLAG_COLLIGHT, "Dummy feet color") +MACRO_CONFIG_STR(ClDummySkin, dummy_skin, 24, "default", CFGFLAG_CLIENT | CFGFLAG_SAVE, "Dummy skin") MACRO_CONFIG_INT(ClDummy, cl_dummy, 0, 0, 1, CFGFLAG_CLIENT, "0 - player / 1 - dummy") MACRO_CONFIG_INT(ClDummyHammer, cl_dummy_hammer, 0, 0, 1, CFGFLAG_CLIENT, "Whether dummy is hammering for a hammerfly") -MACRO_CONFIG_INT(ClDummyResetOnSwitch, cl_dummy_resetonswitch, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether dummy or player should stop pressing keys when you switch. 0 = off, 1 = dummy, 2 = player") -MACRO_CONFIG_INT(ClDummyRestoreWeapon, cl_dummy_restore_weapon, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether dummy should switch to last weapon after hammerfly") +MACRO_CONFIG_INT(ClDummyResetOnSwitch, cl_dummy_resetonswitch, 0, 0, 2, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Whether dummy or player should stop pressing keys when you switch. 0 = off, 1 = dummy, 2 = player") +MACRO_CONFIG_INT(ClDummyRestoreWeapon, cl_dummy_restore_weapon, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Whether dummy should switch to last weapon after hammerfly") MACRO_CONFIG_INT(ClDummyCopyMoves, cl_dummy_copy_moves, 0, 0, 1, CFGFLAG_CLIENT, "Whether dummy should copy your moves") // more controlable dummy command @@ -159,13 +159,13 @@ MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, "Allow votin MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Minimum number of players required to start a kick vote") MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time in seconds to ban a player if kicked by vote. 0 makes it just use kick") MACRO_CONFIG_INT(SvJoinVoteDelay, sv_join_vote_delay, 300, 0, 1000, CFGFLAG_SERVER, "Add a delay before recently joined players can call any vote or participate in a kick/spec vote (in seconds)") -MACRO_CONFIG_INT(SvOldTeleportWeapons, sv_old_teleport_weapons, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Teleporting of all weapons (deprecated, use special entities instead)") -MACRO_CONFIG_INT(SvOldTeleportHook, sv_old_teleport_hook, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Hook through teleporter (deprecated, use special entities instead)") -MACRO_CONFIG_INT(SvTeleportHoldHook, sv_teleport_hold_hook, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Hold hook when teleported") -MACRO_CONFIG_INT(SvTeleportLoseWeapons, sv_teleport_lose_weapons, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Lose weapons when teleported (useful for some race maps)") -MACRO_CONFIG_INT(SvDeepfly, sv_deepfly, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Allow fire non auto weapons when deep") -MACRO_CONFIG_INT(SvDestroyBulletsOnDeath, sv_destroy_bullets_on_death, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Destroy bullets when their owner dies") -MACRO_CONFIG_INT(SvDestroyLasersOnDeath, sv_destroy_lasers_on_death, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Destroy lasers when their owner dies") +MACRO_CONFIG_INT(SvOldTeleportWeapons, sv_old_teleport_weapons, 0, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Teleporting of all weapons (deprecated, use special entities instead)") +MACRO_CONFIG_INT(SvOldTeleportHook, sv_old_teleport_hook, 0, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Hook through teleporter (deprecated, use special entities instead)") +MACRO_CONFIG_INT(SvTeleportHoldHook, sv_teleport_hold_hook, 0, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Hold hook when teleported") +MACRO_CONFIG_INT(SvTeleportLoseWeapons, sv_teleport_lose_weapons, 0, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Lose weapons when teleported (useful for some race maps)") +MACRO_CONFIG_INT(SvDeepfly, sv_deepfly, 1, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Allow fire non auto weapons when deep") +MACRO_CONFIG_INT(SvDestroyBulletsOnDeath, sv_destroy_bullets_on_death, 1, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Destroy bullets when their owner dies") +MACRO_CONFIG_INT(SvDestroyLasersOnDeath, sv_destroy_lasers_on_death, 0, 0, 1, CFGFLAG_SERVER | CFGFLAG_GAME, "Destroy lasers when their owner dies") MACRO_CONFIG_INT(SvMapUpdateRate, sv_mapupdaterate, 5, 1, 100, CFGFLAG_SERVER, "64 player id <-> vanilla id players map update rate") @@ -177,18 +177,18 @@ MACRO_CONFIG_INT(SvRescue, sv_rescue, 0, 0, 1, CFGFLAG_SERVER, "Allow /rescue co MACRO_CONFIG_INT(SvRescueDelay, sv_rescue_delay, 1, 0, 1000, CFGFLAG_SERVER, "Number of seconds between two rescues") MACRO_CONFIG_INT(SvPractice, sv_practice, 1, 0, 1, CFGFLAG_SERVER, "Enable practice mode for teams. Means you can use /rescue, but in turn your rank doesn't count.") -MACRO_CONFIG_INT(ClVideoPauseWithDemo, cl_video_pausewithdemo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Pause video rendering when demo playing pause") -MACRO_CONFIG_INT(ClVideoShowhud, cl_video_showhud, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD when rendering video") -MACRO_CONFIG_INT(ClVideoShowChat, cl_video_showchat, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat when rendering video") -MACRO_CONFIG_INT(ClVideoSndEnable, cl_video_sound_enable, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use sound when rendering video") -MACRO_CONFIG_INT(ClVideoShowHookCollOther, cl_video_show_hook_coll_other, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show other players' hook collision lines when rendering video") -MACRO_CONFIG_INT(ClVideoShowDirection, cl_video_showdirection, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show other players' key presses when rendering video") -MACRO_CONFIG_INT(ClVideoX264Crf, cl_video_crf, 18, 0, 51, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Set crf when encode video with libx264") -MACRO_CONFIG_INT(ClVideoX264Preset, cl_video_preset, 5, 0, 9, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Set preset when encode video with libx264, default is 5 (medium), 0 is ultrafast, 9 is placebo(the slowest, not recommend)") +MACRO_CONFIG_INT(ClVideoPauseWithDemo, cl_video_pausewithdemo, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Pause video rendering when demo playing pause") +MACRO_CONFIG_INT(ClVideoShowhud, cl_video_showhud, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show ingame HUD when rendering video") +MACRO_CONFIG_INT(ClVideoShowChat, cl_video_showchat, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show chat when rendering video") +MACRO_CONFIG_INT(ClVideoSndEnable, cl_video_sound_enable, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Use sound when rendering video") +MACRO_CONFIG_INT(ClVideoShowHookCollOther, cl_video_show_hook_coll_other, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show other players' hook collision lines when rendering video") +MACRO_CONFIG_INT(ClVideoShowDirection, cl_video_showdirection, 0, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Show other players' key presses when rendering video") +MACRO_CONFIG_INT(ClVideoX264Crf, cl_video_crf, 18, 0, 51, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Set crf when encode video with libx264") +MACRO_CONFIG_INT(ClVideoX264Preset, cl_video_preset, 5, 0, 9, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Set preset when encode video with libx264, default is 5 (medium), 0 is ultrafast, 9 is placebo(the slowest, not recommend)") // debug #ifdef CONF_DEBUG // this one can crash the server if not used correctly - MACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, 15, CFGFLAG_SERVER, "") +MACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, 15, CFGFLAG_SERVER, "") #endif MACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, "") diff --git a/src/game/voting.h b/src/game/voting.h index 61d86143d..60262794b 100644 --- a/src/game/voting.h +++ b/src/game/voting.h @@ -5,11 +5,11 @@ enum { - VOTE_DESC_LENGTH=64, - VOTE_CMD_LENGTH=512, - VOTE_REASON_LENGTH=16, + VOTE_DESC_LENGTH = 64, + VOTE_CMD_LENGTH = 512, + VOTE_REASON_LENGTH = 16, - MAX_VOTE_OPTIONS=8192, + MAX_VOTE_OPTIONS = 8192, }; struct CVoteOptionClient diff --git a/src/mastersrv/mastersrv.cpp b/src/mastersrv/mastersrv.cpp index a7f955337..58186944f 100644 --- a/src/mastersrv/mastersrv.cpp +++ b/src/mastersrv/mastersrv.cpp @@ -13,11 +13,12 @@ #include "mastersrv.h" -enum { +enum +{ MTU = 1400, - MAX_SERVERS_PER_PACKET=75, - MAX_PACKETS=16, - MAX_SERVERS=MAX_SERVERS_PER_PACKET*MAX_PACKETS, + MAX_SERVERS_PER_PACKET = 75, + MAX_PACKETS = 16, + MAX_SERVERS = MAX_SERVERS_PER_PACKET * MAX_PACKETS, EXPIRE_TIME = 90 }; @@ -46,7 +47,8 @@ static int m_NumServers = 0; struct CPacketData { int m_Size; - struct { + struct + { unsigned char m_aHeader[sizeof(SERVERBROWSE_LIST)]; CMastersrvAddr m_aServers[MAX_SERVERS_PER_PACKET]; } m_Data; @@ -59,7 +61,8 @@ static int m_NumPackets = 0; struct CPacketDataLegacy { int m_Size; - struct { + struct + { unsigned char m_aHeader[sizeof(SERVERBROWSE_LIST_LEGACY)]; CMastersrvAddrLegacy m_aServers[MAX_SERVERS_PER_PACKET]; } m_Data; @@ -68,7 +71,6 @@ struct CPacketDataLegacy CPacketDataLegacy m_aPacketsLegacy[MAX_PACKETS]; static int m_NumPacketsLegacy = 0; - struct CCountPacketData { unsigned char m_Header[sizeof(SERVERBROWSE_COUNT)]; @@ -79,7 +81,6 @@ struct CCountPacketData static CCountPacketData m_CountData; static CCountPacketData m_CountDataLegacy; - CNetBan m_NetBan; static CNetClient m_NetChecker; // NAT/FW checker @@ -106,31 +107,31 @@ void BuildPackets() } // copy header - mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)); + mem_copy(m_aPackets[m_NumPackets - 1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)); // copy server addresses if(pCurrent->m_Address.type == NETTYPE_IPV6) { - mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, pCurrent->m_Address.ip, - sizeof(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp)); + mem_copy(m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp, pCurrent->m_Address.ip, + sizeof(m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp)); } else { - static char IPV4Mapping[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (char)0xFF, (char)0xFF }; + static char IPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (char)0xFF, (char)0xFF}; - mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, IPV4Mapping, sizeof(IPV4Mapping)); - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[12] = pCurrent->m_Address.ip[0]; - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[13] = pCurrent->m_Address.ip[1]; - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[14] = pCurrent->m_Address.ip[2]; - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[15] = pCurrent->m_Address.ip[3]; + mem_copy(m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp, IPV4Mapping, sizeof(IPV4Mapping)); + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp[12] = pCurrent->m_Address.ip[0]; + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp[13] = pCurrent->m_Address.ip[1]; + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp[14] = pCurrent->m_Address.ip[2]; + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aIp[15] = pCurrent->m_Address.ip[3]; } - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[0] = (pCurrent->m_Address.port>>8)&0xff; - m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[1] = pCurrent->m_Address.port&0xff; + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aPort[0] = (pCurrent->m_Address.port >> 8) & 0xff; + m_aPackets[m_NumPackets - 1].m_Data.m_aServers[PacketIndex].m_aPort[1] = pCurrent->m_Address.port & 0xff; PacketIndex++; - m_aPackets[m_NumPackets-1].m_Size = sizeof(SERVERBROWSE_LIST) + sizeof(CMastersrvAddr)*PacketIndex; + m_aPackets[m_NumPackets - 1].m_Size = sizeof(SERVERBROWSE_LIST) + sizeof(CMastersrvAddr) * PacketIndex; pCurrent++; } @@ -143,24 +144,24 @@ void BuildPackets() } // copy header - mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aHeader, SERVERBROWSE_LIST_LEGACY, sizeof(SERVERBROWSE_LIST_LEGACY)); + mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Data.m_aHeader, SERVERBROWSE_LIST_LEGACY, sizeof(SERVERBROWSE_LIST_LEGACY)); // copy server addresses - mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp, pCurrent->m_Address.ip, - sizeof(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp)); + mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Data.m_aServers[PacketIndexLegacy].m_aIp, pCurrent->m_Address.ip, + sizeof(m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Data.m_aServers[PacketIndexLegacy].m_aIp)); // 0.5 has the port in little endian on the network - m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[0] = pCurrent->m_Address.port&0xff; - m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[1] = (pCurrent->m_Address.port>>8)&0xff; + m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[0] = pCurrent->m_Address.port & 0xff; + m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[1] = (pCurrent->m_Address.port >> 8) & 0xff; PacketIndexLegacy++; - m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Size = sizeof(SERVERBROWSE_LIST_LEGACY) + sizeof(CMastersrvAddrLegacy)*PacketIndexLegacy; + m_aPacketsLegacy[m_NumPacketsLegacy - 1].m_Size = sizeof(SERVERBROWSE_LIST_LEGACY) + sizeof(CMastersrvAddrLegacy) * PacketIndexLegacy; pCurrent++; } else { - *pCurrent = m_aServers[m_NumServers-1]; + *pCurrent = m_aServers[m_NumServers - 1]; m_NumServers--; dbg_msg("mastersrv", "ERROR: server of invalid type, dropping it"); } @@ -235,7 +236,7 @@ void AddServer(NETADDR *pInfo, ServerType Type) char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "updated: %s", aAddrStr); - m_aServers[i].m_Expire = time_get()+time_freq()*EXPIRE_TIME; + m_aServers[i].m_Expire = time_get() + time_freq() * EXPIRE_TIME; return; } } @@ -251,7 +252,7 @@ void AddServer(NETADDR *pInfo, ServerType Type) net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "added: %s", aAddrStr); m_aServers[m_NumServers].m_Address = *pInfo; - m_aServers[m_NumServers].m_Expire = time_get()+time_freq()*EXPIRE_TIME; + m_aServers[m_NumServers].m_Expire = time_get() + time_freq() * EXPIRE_TIME; m_aServers[m_NumServers].m_Type = Type; m_NumServers++; } @@ -262,7 +263,7 @@ void UpdateServers() int64 Freq = time_freq(); for(int i = 0; i < m_NumCheckServers; i++) { - if(Now > m_aCheckServers[i].m_TryTime+Freq) + if(Now > m_aCheckServers[i].m_TryTime + Freq) { if(m_aCheckServers[i].m_TryCount == 10) { @@ -274,7 +275,7 @@ void UpdateServers() // FAIL!! SendError(&m_aCheckServers[i].m_Address); - m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers-1]; + m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers - 1]; m_NumCheckServers--; i--; } @@ -282,7 +283,7 @@ void UpdateServers() { m_aCheckServers[i].m_TryCount++; m_aCheckServers[i].m_TryTime = Now; - if(m_aCheckServers[i].m_TryCount&1) + if(m_aCheckServers[i].m_TryCount & 1) SendCheck(&m_aCheckServers[i].m_Address); else SendCheck(&m_aCheckServers[i].m_AltAddress); @@ -303,7 +304,7 @@ void PurgeServers() char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "expired: %s", aAddrStr); - m_aServers[i] = m_aServers[m_NumServers-1]; + m_aServers[i] = m_aServers[m_NumServers - 1]; m_NumServers--; } else @@ -344,7 +345,7 @@ int main(int argc, const char **argv) // ignore_convention pConfig->Init(); m_NetBan.Init(m_pConsole, pStorage); if(argc > 1) // ignore_convention - m_pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + m_pConsole->ParseArguments(argc - 1, &argv[1]); // ignore_convention if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) { @@ -364,7 +365,7 @@ int main(int argc, const char **argv) // ignore_convention dbg_msg("mastersrv", "couldn't start network (op)"); return -1; } - BindAddr.port = MASTERSERVER_PORT+1; + BindAddr.port = MASTERSERVER_PORT + 1; if(!m_NetChecker.Open(BindAddr, 0)) { dbg_msg("mastersrv", "couldn't start network (checker)"); @@ -389,28 +390,28 @@ int main(int argc, const char **argv) // ignore_convention if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0)) continue; - if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT)+2 && + if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT) + 2 && mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)) == 0) { NETADDR Alt; unsigned char *d = (unsigned char *)Packet.m_pData; Alt = Packet.m_Address; Alt.port = - (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | - d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; + (d[sizeof(SERVERBROWSE_HEARTBEAT)] << 8) | + d[sizeof(SERVERBROWSE_HEARTBEAT) + 1]; // add it AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_NORMAL); } - else if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)+2 && + else if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT_LEGACY) + 2 && mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT_LEGACY, sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)) == 0) { NETADDR Alt; unsigned char *d = (unsigned char *)Packet.m_pData; Alt = Packet.m_Address; Alt.port = - (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | - d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; + (d[sizeof(SERVERBROWSE_HEARTBEAT)] << 8) | + d[sizeof(SERVERBROWSE_HEARTBEAT) + 1]; // add it AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_LEGACY); @@ -427,8 +428,8 @@ int main(int argc, const char **argv) // ignore_convention p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(m_CountData); p.m_pData = &m_CountData; - m_CountData.m_High = (m_NumServers>>8)&0xff; - m_CountData.m_Low = m_NumServers&0xff; + m_CountData.m_High = (m_NumServers >> 8) & 0xff; + m_CountData.m_Low = m_NumServers & 0xff; m_NetOp.Send(&p); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT_LEGACY) && @@ -442,8 +443,8 @@ int main(int argc, const char **argv) // ignore_convention p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(m_CountData); p.m_pData = &m_CountDataLegacy; - m_CountDataLegacy.m_High = (m_NumServers>>8)&0xff; - m_CountDataLegacy.m_Low = m_NumServers&0xff; + m_CountDataLegacy.m_High = (m_NumServers >> 8) & 0xff; + m_CountDataLegacy.m_Low = m_NumServers & 0xff; m_NetOp.Send(&p); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST) && @@ -517,14 +518,14 @@ int main(int argc, const char **argv) // ignore_convention } } - if(time_get()-LastBanReload > time_freq()*300) + if(time_get() - LastBanReload > time_freq() * 300) { LastBanReload = time_get(); ReloadBans(); } - if(time_get()-LastBuild > time_freq()*5) + if(time_get() - LastBuild > time_freq() * 5) { LastBuild = time_get(); diff --git a/src/mastersrv/mastersrv.h b/src/mastersrv/mastersrv.h index eb99f1173..a01083464 100644 --- a/src/mastersrv/mastersrv.h +++ b/src/mastersrv/mastersrv.h @@ -39,7 +39,6 @@ static const unsigned char SERVERBROWSE_FWRESPONSE[] = {255, 255, 255, 255, 'f', static const unsigned char SERVERBROWSE_FWOK[] = {255, 255, 255, 255, 'f', 'w', 'o', 'k'}; static const unsigned char SERVERBROWSE_FWERROR[] = {255, 255, 255, 255, 'f', 'w', 'e', 'r'}; - // packet headers for the 0.5 branch struct CMastersrvAddrLegacy @@ -58,7 +57,7 @@ static const unsigned char SERVERBROWSE_COUNT_LEGACY[] = {255, 255, 255, 255, 's enum { - SERVERINFO_VANILLA=0, + SERVERINFO_VANILLA = 0, SERVERINFO_64_LEGACY, SERVERINFO_EXTENDED, SERVERINFO_EXTENDED_MORE, diff --git a/src/steam/steam_api_flat.h b/src/steam/steam_api_flat.h index f63ed8fc2..ea9564f37 100644 --- a/src/steam/steam_api_flat.h +++ b/src/steam/steam_api_flat.h @@ -9,8 +9,7 @@ #define STEAMAPI DYNAMIC_IMPORT #endif -extern "C" -{ +extern "C" { typedef uint64_t CSteamID; typedef int32_t HSteamPipe; @@ -26,14 +25,20 @@ struct CallbackMsg_t struct GameRichPresenceJoinRequested_t { - enum { k_iCallback = 337 }; + enum + { + k_iCallback = 337 + }; CSteamID m_steamIDFriend; char m_rgchConnect[256]; }; struct NewUrlLaunchParameters_t { - enum { k_iCallback = 1014 }; + enum + { + k_iCallback = 1014 + }; unsigned char m_EmptyStructDontUse; }; @@ -57,7 +62,6 @@ STEAMAPI ISteamFriends *SteamAPI_SteamFriends_v017(); STEAMAPI void SteamAPI_ISteamFriends_ClearRichPresence(ISteamFriends *pSelf); STEAMAPI const char *SteamAPI_ISteamFriends_GetPersonaName(ISteamFriends *pSelf); STEAMAPI bool SteamAPI_ISteamFriends_SetRichPresence(ISteamFriends *pSelf, const char *pKey, const char *pValue); - } #endif // STEAM_STEAM_API_FLAT_H diff --git a/src/steam/steam_api_stub.cpp b/src/steam/steam_api_stub.cpp index a5e966c67..0e1e5867b 100644 --- a/src/steam/steam_api_stub.cpp +++ b/src/steam/steam_api_stub.cpp @@ -4,8 +4,7 @@ #include -extern "C" -{ +extern "C" { bool SteamAPI_Init() { return false; } HSteamPipe SteamAPI_GetHSteamPipe() { abort(); } @@ -21,5 +20,4 @@ ISteamFriends *SteamAPI_SteamFriends_v017() { abort(); } const char *SteamAPI_ISteamFriends_GetPersonaName(ISteamFriends *pSelf) { abort(); } bool SteamAPI_ISteamFriends_SetRichPresence(ISteamFriends *pSelf, const char *pKey, const char *pValue) { abort(); } void SteamAPI_ISteamFriends_ClearRichPresence(ISteamFriends *pSelf) { abort(); } - } diff --git a/src/test/color.cpp b/src/test/color.cpp index f9d163603..eddd74eca 100644 --- a/src/test/color.cpp +++ b/src/test/color.cpp @@ -1,24 +1,26 @@ #include "test.h" #include -#include #include +#include TEST(Color, HRHConv) { - for(int i = 0; i < 0xFFFFFF; i+= 0xFF){ - ColorHSLA hsl = i; - ColorRGBA rgb = color_cast(hsl); - ColorHSLA hsl2 = color_cast(rgb); + for(int i = 0; i < 0xFFFFFF; i += 0xFF) + { + ColorHSLA hsl = i; + ColorRGBA rgb = color_cast(hsl); + ColorHSLA hsl2 = color_cast(rgb); - if(hsl.s == 0.0f || hsl.s == 1.0f) - EXPECT_FLOAT_EQ(hsl.l, hsl2.l); - else if(hsl.l == 0.0f || hsl.l == 1.0f) - EXPECT_FLOAT_EQ(hsl.l, hsl2.l); - else { - EXPECT_NEAR(fmod(hsl.h, 1.0f), fmod(hsl2.h, 1.0f), 0.001f); - EXPECT_NEAR(hsl.s, hsl2.s, 0.0001f); - EXPECT_FLOAT_EQ(hsl.l, hsl2.l); - } - } + if(hsl.s == 0.0f || hsl.s == 1.0f) + EXPECT_FLOAT_EQ(hsl.l, hsl2.l); + else if(hsl.l == 0.0f || hsl.l == 1.0f) + EXPECT_FLOAT_EQ(hsl.l, hsl2.l); + else + { + EXPECT_NEAR(fmod(hsl.h, 1.0f), fmod(hsl2.h, 1.0f), 0.001f); + EXPECT_NEAR(hsl.s, hsl2.s, 0.0001f); + EXPECT_FLOAT_EQ(hsl.l, hsl2.l); + } + } } diff --git a/src/test/csv.cpp b/src/test/csv.cpp index bd2e6cf1f..905983fdf 100644 --- a/src/test/csv.cpp +++ b/src/test/csv.cpp @@ -24,12 +24,12 @@ static void Expect(int NumColumns, const char *const *ppColumns, const char *pEx ASSERT_EQ(aBuf[Read], '\n'); aBuf[Read] = 0; - #if defined(CONF_FAMILY_WINDOWS) +#if defined(CONF_FAMILY_WINDOWS) ASSERT_TRUE(Read >= 1); Read -= 1; ASSERT_EQ(aBuf[Read], '\r'); aBuf[Read] = 0; - #endif +#endif for(int i = 0; i < Read; i++) { @@ -40,17 +40,26 @@ static void Expect(int NumColumns, const char *const *ppColumns, const char *pEx TEST(Csv, Simple) { - const char *apCols1[] = {"a", "b"}; Expect(2, apCols1, "a,b"); - const char *apCols2[] = {"こんにちは"}; Expect(1, apCols2, "こんにちは"); - const char *apCols3[] = {"я", "", "й"}; Expect(3, apCols3, "я,,й"); - const char *apCols4[] = {""}; Expect(1, apCols4, ""); - const char *apCols5[] = {0}; Expect(0, apCols5, ""); + const char *apCols1[] = {"a", "b"}; + Expect(2, apCols1, "a,b"); + const char *apCols2[] = {"こんにちは"}; + Expect(1, apCols2, "こんにちは"); + const char *apCols3[] = {"я", "", "й"}; + Expect(3, apCols3, "я,,й"); + const char *apCols4[] = {""}; + Expect(1, apCols4, ""); + const char *apCols5[] = {0}; + Expect(0, apCols5, ""); } TEST(Csv, LetTheQuotingBegin) { - const char *apCols1[] = {"\""}; Expect(1, apCols1, "\"\"\"\""); - const char *apCols2[] = {","}; Expect(1, apCols2, "\",\""); - const char *apCols3[] = {",,", ",\"\"\""}; Expect(2, apCols3, "\",,\",\",\"\"\"\"\"\"\""); - const char *apCols4[] = {"\",", " "}; Expect(2, apCols4, "\"\"\",\", "); + const char *apCols1[] = {"\""}; + Expect(1, apCols1, "\"\"\"\""); + const char *apCols2[] = {","}; + Expect(1, apCols2, "\",\""); + const char *apCols3[] = {",,", ",\"\"\""}; + Expect(2, apCols3, "\",,\",\",\"\"\"\"\"\"\""); + const char *apCols4[] = {"\",", " "}; + Expect(2, apCols4, "\"\"\",\", "); } diff --git a/src/test/hash.cpp b/src/test/hash.cpp index b218fc411..66fa992af 100644 --- a/src/test/hash.cpp +++ b/src/test/hash.cpp @@ -44,10 +44,38 @@ TEST(Hash, Sha256Eq) TEST(Hash, Sha256FromStr) { SHA256_DIGEST Expected = {{ - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, - 0x01, 0x23, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, }}; SHA256_DIGEST Sha256; EXPECT_FALSE(sha256_from_str(&Sha256, "0123456789012345678901234567890123456789012345678901234567890123")); @@ -99,8 +127,22 @@ TEST(Hash, Md5Eq) TEST(Hash, Md5FromStr) { MD5_DIGEST Expected = {{ - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, + 0x23, + 0x45, + 0x67, + 0x89, + 0x01, }}; MD5_DIGEST Md5; EXPECT_FALSE(md5_from_str(&Md5, "01234567890123456789012345678901")); diff --git a/src/test/jobs.cpp b/src/test/jobs.cpp index dd74fdd9b..e8d567ba7 100644 --- a/src/test/jobs.cpp +++ b/src/test/jobs.cpp @@ -2,8 +2,8 @@ #include #include -#include #include +#include #include @@ -29,8 +29,10 @@ class CJob : public IJob { std::function m_JobFunction; void Run() { m_JobFunction(); } + public: - CJob(std::function&& JobFunction) : m_JobFunction(JobFunction) {} + CJob(std::function &&JobFunction) : + m_JobFunction(JobFunction) {} }; TEST_F(Jobs, Constructor) @@ -81,8 +83,7 @@ TEST_F(Jobs, Many) sphore_init(&sphore); for(int i = 0; i < TEST_NUM_THREADS; i++) { - std::shared_ptr pJob = std::make_shared([&] - { + std::shared_ptr pJob = std::make_shared([&] { int Prev = ThreadsRunning.fetch_add(1); if(Prev == TEST_NUM_THREADS - 1) { @@ -92,14 +93,14 @@ TEST_F(Jobs, Many) EXPECT_EQ(pJob->Status(), IJob::STATE_PENDING); apJobs.push_back(pJob); } - for(auto &pJob: apJobs) + for(auto &pJob : apJobs) { Add(pJob); } sphore_wait(&sphore); sphore_destroy(&sphore); m_Pool.~CJobPool(); - for(auto &pJob: apJobs) + for(auto &pJob : apJobs) { EXPECT_EQ(pJob->Status(), IJob::STATE_DONE); } diff --git a/src/test/packer.cpp b/src/test/packer.cpp index 9fa3ed24f..52936ff7f 100644 --- a/src/test/packer.cpp +++ b/src/test/packer.cpp @@ -56,7 +56,9 @@ TEST(Packer, AddStringBroken) ExpectAddString5("\x80", 0, "�"); ExpectAddString5("\x80\x80", 0, 0); ExpectAddString5("a\x80", 0, "a�"); - ExpectAddString5("\x80""a", 0, "�a"); + ExpectAddString5("\x80" + "a", + 0, "�a"); ExpectAddString5("\x80", 1, ""); ExpectAddString5("\x80\x80", 3, "�"); ExpectAddString5("\x80\x80", 5, "�"); diff --git a/src/test/prng.cpp b/src/test/prng.cpp index 940f58fc8..5dcb5c1ea 100644 --- a/src/test/prng.cpp +++ b/src/test/prng.cpp @@ -42,7 +42,12 @@ // something more complicated is done. static const unsigned int PCG32_GLOBAL_DEMO[] = { - 0xa15c02b7, 0x7b47f409, 0xba1d3330, 0x83d2f293, 0xbfa4784b, 0xcbed606e, + 0xa15c02b7, + 0x7b47f409, + 0xba1d3330, + 0x83d2f293, + 0xbfa4784b, + 0xcbed606e, }; TEST(Prng, EqualsPcg32GlobalDemo) diff --git a/src/test/str.cpp b/src/test/str.cpp index 58de067dd..a0b8678a8 100644 --- a/src/test/str.cpp +++ b/src/test/str.cpp @@ -40,10 +40,18 @@ TEST(Str, Utf8SkipWhitespaces) TEST(Str, Utf8TrimRight) { - char A1[] = "abc"; str_utf8_trim_right(A1); EXPECT_STREQ(A1, "abc"); - char A2[] = " abc"; str_utf8_trim_right(A2); EXPECT_STREQ(A2, " abc"); - char A3[] = "abc "; str_utf8_trim_right(A3); EXPECT_STREQ(A3, "abc"); - char A4[] = "abc \xe2\x80\x8b"; str_utf8_trim_right(A4); EXPECT_STREQ(A4, "abc"); + char A1[] = "abc"; + str_utf8_trim_right(A1); + EXPECT_STREQ(A1, "abc"); + char A2[] = " abc"; + str_utf8_trim_right(A2); + EXPECT_STREQ(A2, " abc"); + char A3[] = "abc "; + str_utf8_trim_right(A3); + EXPECT_STREQ(A3, "abc"); + char A4[] = "abc \xe2\x80\x8b"; + str_utf8_trim_right(A4); + EXPECT_STREQ(A4, "abc"); } TEST(Str, Utf8CompConfusables) @@ -67,7 +75,7 @@ TEST(Str, Utf8ToLower) EXPECT_TRUE(str_utf8_comp_nocase("ÖlÜ", "ölüa") < 0); // NULL < a EXPECT_TRUE(str_utf8_comp_nocase("ölüa", "ÖlÜ") > 0); // a < NULL -#if (CHAR_MIN < 0) +#if(CHAR_MIN < 0) const char a[2] = {CHAR_MIN, 0}; const char b[2] = {0, 0}; EXPECT_TRUE(str_utf8_comp_nocase(a, b) > 0); @@ -81,8 +89,8 @@ TEST(Str, Utf8ToLower) const char str[] = "ÄÖÜ"; EXPECT_TRUE(str_utf8_find_nocase(str, "ä") == str); - EXPECT_TRUE(str_utf8_find_nocase(str, "ö") == str+2); - EXPECT_TRUE(str_utf8_find_nocase(str, "ü") == str+4); + EXPECT_TRUE(str_utf8_find_nocase(str, "ö") == str + 2); + EXPECT_TRUE(str_utf8_find_nocase(str, "ü") == str + 4); EXPECT_TRUE(str_utf8_find_nocase(str, "z") == NULL); } @@ -128,14 +136,22 @@ TEST(Str, Endswith) TEST(Str, HexDecode) { char aOut[5] = {'a', 'b', 'c', 'd', 0}; - EXPECT_EQ(str_hex_decode(aOut, 0, ""), 0); EXPECT_STREQ(aOut, "abcd"); - EXPECT_EQ(str_hex_decode(aOut, 0, " "), 2); EXPECT_STREQ(aOut, "abcd"); - EXPECT_EQ(str_hex_decode(aOut, 1, "1"), 2); EXPECT_STREQ(aOut + 1, "bcd"); - EXPECT_EQ(str_hex_decode(aOut, 1, "41"), 0); EXPECT_STREQ(aOut, "Abcd"); - EXPECT_EQ(str_hex_decode(aOut, 1, "4x"), 1); EXPECT_STREQ(aOut + 1, "bcd"); - EXPECT_EQ(str_hex_decode(aOut, 1, "x1"), 1); EXPECT_STREQ(aOut + 1, "bcd"); - EXPECT_EQ(str_hex_decode(aOut, 1, "411"), 2); EXPECT_STREQ(aOut + 1, "bcd"); - EXPECT_EQ(str_hex_decode(aOut, 4, "41424344"), 0); EXPECT_STREQ(aOut, "ABCD"); + EXPECT_EQ(str_hex_decode(aOut, 0, ""), 0); + EXPECT_STREQ(aOut, "abcd"); + EXPECT_EQ(str_hex_decode(aOut, 0, " "), 2); + EXPECT_STREQ(aOut, "abcd"); + EXPECT_EQ(str_hex_decode(aOut, 1, "1"), 2); + EXPECT_STREQ(aOut + 1, "bcd"); + EXPECT_EQ(str_hex_decode(aOut, 1, "41"), 0); + EXPECT_STREQ(aOut, "Abcd"); + EXPECT_EQ(str_hex_decode(aOut, 1, "4x"), 1); + EXPECT_STREQ(aOut + 1, "bcd"); + EXPECT_EQ(str_hex_decode(aOut, 1, "x1"), 1); + EXPECT_STREQ(aOut + 1, "bcd"); + EXPECT_EQ(str_hex_decode(aOut, 1, "411"), 2); + EXPECT_STREQ(aOut + 1, "bcd"); + EXPECT_EQ(str_hex_decode(aOut, 4, "41424344"), 0); + EXPECT_STREQ(aOut, "ABCD"); } TEST(Str, Tokenize) diff --git a/src/test/teehistorian.cpp b/src/test/teehistorian.cpp index 412fdb437..d626a30ee 100644 --- a/src/test/teehistorian.cpp +++ b/src/test/teehistorian.cpp @@ -31,22 +31,21 @@ protected: TeeHistorian() { mem_zero(&m_Config, sizeof(m_Config)); - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) \ - m_Config.m_##Name = (Def); - #define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) MACRO_CONFIG_INT(Name,ScriptName,Def,0,0,Save,Desc) - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) \ - str_copy(m_Config.m_##Name, (Def), sizeof(m_Config.m_##Name)); - #include - #undef MACRO_CONFIG_STR - #undef MACRO_CONFIG_COL - #undef MACRO_CONFIG_INT +#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Save, Desc) \ + m_Config.m_##Name = (Def); +#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) MACRO_CONFIG_INT(Name, ScriptName, Def, 0, 0, Save, Desc) +#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Save, Desc) \ + str_copy(m_Config.m_##Name, (Def), sizeof(m_Config.m_##Name)); +#include +#undef MACRO_CONFIG_STR +#undef MACRO_CONFIG_COL +#undef MACRO_CONFIG_INT RegisterUuids(&m_UuidManager); RegisterTeehistorianUuids(&m_UuidManager); RegisterGameUuids(&m_UuidManager); - SHA256_DIGEST Sha256 = {{ - 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, + SHA256_DIGEST Sha256 = {{0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23}}; @@ -126,9 +125,7 @@ protected: ::testing::UnitTest::GetInstance()->current_test_info(); const char *pTestName = pTestInfo->name(); - if(m_Buffer.Error() - || m_Buffer.Size() != OutputSize - || mem_comp(m_Buffer.Data(), pOutput, OutputSize) != 0) + if(m_Buffer.Error() || m_Buffer.Size() != OutputSize || mem_comp(m_Buffer.Data(), pOutput, OutputSize) != 0) { char aFilename[64]; IOHANDLE File; @@ -217,7 +214,8 @@ TEST_F(TeeHistorian, TickImplicitOneTick) 0x42, 0x00, 0x01, 0x02, // PLAYERNEW cid=0 x=1 y=2 0x40, // FINISH }; - Tick(1); Player(0, 1, 2); + Tick(1); + Player(0, 1, 2); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -229,8 +227,10 @@ TEST_F(TeeHistorian, TickImplicitTwoTicks) 0x00, 0x01, 0x40, // PLAYER cid=0 dx=1 dy=-1 0x40, // FINISH }; - Tick(1); Player(0, 1, 2); - Tick(2); Player(0, 2, 1); + Tick(1); + Player(0, 1, 2); + Tick(2); + Player(0, 2, 1); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -242,8 +242,12 @@ TEST_F(TeeHistorian, TickImplicitDescendingClientID) 0x42, 0x00, 0x04, 0x05, // PLAYER_NEW cid=0 x=4 y=5 0x40, // FINISH }; - Tick(1); DeadPlayer(0); Player(1, 2, 3); - Tick(2); Player(0, 4, 5); Player(1, 2, 3); + Tick(1); + DeadPlayer(0); + Player(1, 2, 3); + Tick(2); + Player(0, 4, 5); + Player(1, 2, 3); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -256,8 +260,12 @@ TEST_F(TeeHistorian, TickExplicitAscendingClientID) 0x42, 0x01, 0x02, 0x03, // PLAYER_NEW cid=1 x=2 y=3 0x40, // FINISH }; - Tick(1); Player(0, 4, 5); DeadPlayer(1); - Tick(2); Player(0, 4, 5); Player(1, 2, 3); + Tick(1); + Player(0, 4, 5); + DeadPlayer(1); + Tick(2); + Player(0, 4, 5); + Player(1, 2, 3); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -286,7 +294,8 @@ TEST_F(TeeHistorian, TickExplicitStart) 0x42, 0x00, 0x40, 0x40, // PLAYER_NEW cid=0 x=-1 y=-1 0x40, // FINISH }; - Tick(500); Player(0, -1, -1); + Tick(500); + Player(0, -1, -1); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -298,7 +307,9 @@ TEST_F(TeeHistorian, TickExplicitPlayerMessage) 0x46, 0x3f, 0x01, 0x00, // MESSAGE cid=63 msg="\0" 0x40, // FINISH }; - Tick(1); Inputs(); m_TH.RecordPlayerMessage(63, "", 1); + Tick(1); + Inputs(); + m_TH.RecordPlayerMessage(63, "", 1); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -314,7 +325,9 @@ TEST_F(TeeHistorian, ExtraMessage) 0x00, 0x40, // FINISH }; - Tick(1); Inputs(); m_TH.RecordTestExtra(); + Tick(1); + Inputs(); + m_TH.RecordTestExtra(); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } @@ -332,10 +345,10 @@ TEST_F(TeeHistorian, DDNetVersion) 0x00, 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, 0xb8, 0x15, 0xee, 0xdc, 0x6d, 0x98, 0x01, 0x5b, - 0x92, 0xcb, 0x01, 'D', 'D', 'N', 'e', 't', - ' ', '1', '3', '.', '1', ' ', '(', '3', - '6', '2', '3', 'f', '5', 'e', '4', 'c', - 'd', '1', '8', '4', '5', '5', '6', ')', + 0x92, 0xcb, 0x01, 'D', 'D', 'N', 'e', 't', + ' ', '1', '3', '.', '1', ' ', '(', '3', + '6', '2', '3', 'f', '5', 'e', '4', 'c', + 'd', '1', '8', '4', '5', '5', '6', ')', 0x00, // EX uuid=1397b63e-ee4e-3919-b86a-b058887fcaf5 data_len=4 0x4a, @@ -364,15 +377,15 @@ TEST_F(TeeHistorian, Auth) 0xb8, 0xba, 0xb2, 0x95, 0x3f, 0xb5, 0x5a, 0x17, 0x10, // (AUTH_INIT) cid=0 level=3 auth_name="default_admin" - 0x00, 0x03, 'd', 'e', 'f', 'a', 'u', 'l', - 't', '_', 'a', 'd', 'm', 'i', 'n', 0x00, + 0x00, 0x03, 'd', 'e', 'f', 'a', 'u', 'l', + 't', '_', 'a', 'd', 'm', 'i', 'n', 0x00, // EX uuid=37ecd3b8-9218-3bb9-a71b-a935b86f6a81 data_len=9 0x4a, 0x37, 0xec, 0xd3, 0xb8, 0x92, 0x18, 0x3b, 0xb9, 0xa7, 0x1b, 0xa9, 0x35, 0xb8, 0x6f, 0x6a, 0x81, 0x09, // (AUTH_LOGIN) cid=1 level=2 auth_name="foobar" - 0x01, 0x02, 'f', 'o', 'o', 'b', 'a', 'r', + 0x01, 0x02, 'f', 'o', 'o', 'b', 'a', 'r', 0x00, // EX uuid=37ecd3b8-9218-3bb9-a71b-a935b86f6a81 data_len=7 0x4a, @@ -380,7 +393,7 @@ TEST_F(TeeHistorian, Auth) 0xa7, 0x1b, 0xa9, 0x35, 0xb8, 0x6f, 0x6a, 0x81, 0x07, // (AUTH_LOGIN) cid=1 level=2 auth_name="foobar" - 0x02, 0x01, 'h', 'e', 'l', 'p', 0x00, + 0x02, 0x01, 'h', 'e', 'l', 'p', 0x00, // EX uuid=d4f5abe8-edd2-3fb9-abd8-1c8bb84f4a63 data_len=7 0x4a, 0xd4, 0xf5, 0xab, 0xe8, 0xed, 0xd2, 0x3f, 0xb9, @@ -400,7 +413,6 @@ TEST_F(TeeHistorian, Auth) TEST_F(TeeHistorian, JoinLeave) { - const unsigned char EXPECTED[] = { // EX uuid=1899a382-71e3-36da-937d-c9de6bb95b1d data_len=1 0x4a, @@ -421,9 +433,9 @@ TEST_F(TeeHistorian, JoinLeave) // JOIN cid=7 0x47, 0x07, // LEAVE cid=6 reason="too many pancakes" - 0x48, 0x06, 't', 'o', 'o', ' ', 'm', 'a', - 'n', 'y', ' ', 'p', 'a', 'n', 'c', 'a', - 'k', 'e', 's', 0x00, + 0x48, 0x06, 't', 'o', 'o', ' ', 'm', 'a', + 'n', 'y', ' ', 'p', 'a', 'n', 'c', 'a', + 'k', 'e', 's', 0x00, 0x40, // FINISH }; m_TH.RecordPlayerJoin(6, CTeeHistorian::PROTOCOL_6); @@ -449,8 +461,7 @@ TEST_F(TeeHistorian, SaveSuccess) // team_save '2', '\t', 'H', '.', '\n', 'l', 'l', '0', 0x00, // FINISH - 0x40 - }; + 0x40}; CUuid SaveID = { 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, @@ -471,8 +482,7 @@ TEST_F(TeeHistorian, SaveFailed) 0x01, // team=12 0x0c, - 0x40 - }; + 0x40}; m_TH.RecordTeamSaveFailure(12); Finish(); @@ -495,8 +505,7 @@ TEST_F(TeeHistorian, LoadSuccess) // team_save '2', '\t', 'H', '.', '\n', 'l', 'l', '0', 0x00, // FINISH - 0x40 - }; + 0x40}; CUuid SaveID = { 0xfb, 0x13, 0xa5, 0x76, 0xd3, 0x5f, 0x48, 0x93, @@ -517,11 +526,9 @@ TEST_F(TeeHistorian, LoadFailed) 0x01, // team=12 0x0c, - 0x40 - }; + 0x40}; m_TH.RecordTeamLoadFailure(12); Finish(); Expect(EXPECTED, sizeof(EXPECTED)); } - diff --git a/src/tools/crapnet.cpp b/src/tools/crapnet.cpp index 0ad63a4f8..04bb86ae6 100644 --- a/src/tools/crapnet.cpp +++ b/src/tools/crapnet.cpp @@ -31,23 +31,23 @@ struct CPingConfig }; static CPingConfig m_aConfigPings[] = { - // base flux spike loss delay delayfreq - {0, 0, 0, 0, 0, 0}, - {40, 20, 100, 0, 0, 0}, - {140, 40, 200, 0, 0, 0}, + // base flux spike loss delay delayfreq + {0, 0, 0, 0, 0, 0}, + {40, 20, 100, 0, 0, 0}, + {140, 40, 200, 0, 0, 0}, }; -static int m_ConfigNumpingconfs = sizeof(m_aConfigPings)/sizeof(CPingConfig); +static int m_ConfigNumpingconfs = sizeof(m_aConfigPings) / sizeof(CPingConfig); static int m_ConfigInterval = 10; // seconds between different pingconfigs static int m_ConfigLog = 0; static int m_ConfigReorder = 0; void Run(unsigned short Port, NETADDR Dest) { - NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port}; + NETADDR Src = {NETTYPE_IPV4, {0, 0, 0, 0}, Port}; NETSOCKET Socket = net_udp_create(Src); - char aBuffer[1024*2]; + char aBuffer[1024 * 2]; int ID = 0; int Delaycounter = 0; MMSGS m; @@ -56,7 +56,7 @@ void Run(unsigned short Port, NETADDR Dest) while(1) { static int Lastcfg = 0; - int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs; + int n = ((time_get() / time_freq()) / m_ConfigInterval) % m_ConfigNumpingconfs; CPingConfig Ping = m_aConfigPings[n]; if(n != Lastcfg) @@ -70,11 +70,11 @@ void Run(unsigned short Port, NETADDR Dest) int DataTrash = 0; NETADDR From; unsigned char *pData; - int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2, &m, &pData); + int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024 * 2, &m, &pData); if(Bytes <= 0) break; - if((rand()%100) < Ping.m_Loss) // drop the packet + if((rand() % 100) < Ping.m_Loss) // drop the packet { if(m_ConfigLog) dbg_msg("crapnet", "dropped packet"); @@ -112,10 +112,10 @@ void Run(unsigned short Port, NETADDR Dest) if(ID > 20 && Bytes > 6 && DataTrash) { - p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte - if((rand()%10) == 0) + p->m_aData[6 + (rand() % (Bytes - 6))] = rand() & 255; // modify a byte + if((rand() % 10) == 0) { - p->m_DataSize -= rand()%32; + p->m_DataSize -= rand() % 32; if(p->m_DataSize < 6) p->m_DataSize = 6; } @@ -124,7 +124,7 @@ void Run(unsigned short Port, NETADDR Dest) if(Delaycounter <= 0) { if(Ping.m_Delay) - p->m_Timestamp += (time_freq()*1000)/Ping.m_Delay; + p->m_Timestamp += (time_freq() * 1000) / Ping.m_Delay; Delaycounter = Ping.m_DelayFreq; } Delaycounter--; @@ -149,11 +149,11 @@ void Run(unsigned short Port, NETADDR Dest) break; pNext = p->m_pNext; - if((time_get()-p->m_Timestamp) > m_CurrentLatency) + if((time_get() - p->m_Timestamp) > m_CurrentLatency) { char aFlags[] = " "; - if(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext) + if(m_ConfigReorder && (rand() % 2) == 0 && p->m_pNext) { aFlags[0] = 'R'; p = m_pFirst->m_pNext; @@ -181,15 +181,15 @@ void Run(unsigned short Port, NETADDR Dest) net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize); // update lag - double Flux = rand()/(double)RAND_MAX; + double Flux = rand() / (double)RAND_MAX; int MsSpike = Ping.m_Spike; int MsFlux = Ping.m_Flux; int MsPing = Ping.m_Base; - m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms + m_CurrentLatency = ((time_freq() * MsPing) / 1000) + (int64)(((time_freq() * MsFlux) / 1000) * Flux); // 50ms - if(MsSpike && (p->m_ID%100) == 0) + if(MsSpike && (p->m_ID % 100) == 0) { - m_CurrentLatency += (time_freq()*MsSpike)/1000; + m_CurrentLatency += (time_freq() * MsSpike) / 1000; aFlags[1] = 'S'; } @@ -200,7 +200,6 @@ void Run(unsigned short Port, NETADDR Dest) dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags); } - free(p); } } @@ -211,7 +210,7 @@ void Run(unsigned short Port, NETADDR Dest) int main(int argc, char **argv) // ignore_convention { - NETADDR Addr = {NETTYPE_IPV4, {127,0,0,1},8303}; + NETADDR Addr = {NETTYPE_IPV4, {127, 0, 0, 1}, 8303}; dbg_logger_stdout(); Run(8302, Addr); return 0; diff --git a/src/tools/fake_server.cpp b/src/tools/fake_server.cpp index faae05e45..0f3494fa8 100644 --- a/src/tools/fake_server.cpp +++ b/src/tools/fake_server.cpp @@ -1,10 +1,10 @@ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include //rand #include #include #include #include +#include //rand CNetServer *pNet; @@ -16,7 +16,7 @@ const char *pVersion = "trunk"; const char *pMap = "somemap"; const char *pServerName = "unnamed server"; -NETADDR aMasterServers[16] = {{0,{0},0}}; +NETADDR aMasterServers[16] = {{0, {0}, 0}}; int NumMasters = 0; const char *PlayerNames[16] = {0}; @@ -41,7 +41,7 @@ static void SendHeartBeats() /* supply the set port that the master can use if it has problems */ s_aData[sizeof(SERVERBROWSE_HEARTBEAT)] = 0; - s_aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = 0; + s_aData[sizeof(SERVERBROWSE_HEARTBEAT) + 1] = 0; for(int i = 0; i < NumMasters; i++) { @@ -52,7 +52,7 @@ static void SendHeartBeats() static void WriteStr(const char *pStr) { - int l = str_length(pStr)+1; + int l = str_length(pStr) + 1; mem_copy(&aInfoMsg[aInfoMsgSize], pStr, l); aInfoMsgSize += l; } @@ -111,7 +111,7 @@ static void SendFWCheckResponse(NETADDR *pAddr) static int Run() { int64 NextHeartBeat = 0; - NETADDR BindAddr = {NETTYPE_IPV4, {0},0}; + NETADDR BindAddr = {NETTYPE_IPV4, {0}, 0}; if(!pNet->Open(BindAddr, 0, 0, 0, 0)) return 0; @@ -141,7 +141,7 @@ static int Run() /* send heartbeats if needed */ if(NextHeartBeat < time_get()) { - NextHeartBeat = time_get()+time_freq()*(15+(rand()%15)); + NextHeartBeat = time_get() + time_freq() * (15 + (rand() % 15)); SendHeartBeats(); } @@ -164,45 +164,55 @@ int main(int argc, char **argv) aMasterServers[NumMasters].port = str_toint(*argv); NumMasters++; } - else */if(str_comp(*argv, "-p") == 0) + else */ + if(str_comp(*argv, "-p") == 0) { - argc--; argv++; + argc--; + argv++; PlayerNames[NumPlayers++] = *argv; - argc--; argv++; + argc--; + argv++; PlayerScores[NumPlayers] = str_toint(*argv); } else if(str_comp(*argv, "-a") == 0) { - argc--; argv++; + argc--; + argv++; pMap = *argv; } else if(str_comp(*argv, "-x") == 0) { - argc--; argv++; + argc--; + argv++; MaxPlayers = str_toint(*argv); } else if(str_comp(*argv, "-t") == 0) { - argc--; argv++; + argc--; + argv++; GameType = str_toint(*argv); } else if(str_comp(*argv, "-g") == 0) { - argc--; argv++; + argc--; + argv++; Progression = str_toint(*argv); } else if(str_comp(*argv, "-f") == 0) { - argc--; argv++; + argc--; + argv++; Flags = str_toint(*argv); } else if(str_comp(*argv, "-n") == 0) { - argc--; argv++; + argc--; + argv++; pServerName = *argv; } - argc--; argv++; + argc--; + argv++; } BuildInfoMsg(); diff --git a/src/tools/map_convert_07.cpp b/src/tools/map_convert_07.cpp index 3621122e6..783ec5c40 100644 --- a/src/tools/map_convert_07.cpp +++ b/src/tools/map_convert_07.cpp @@ -1,11 +1,11 @@ /* (c) DDNet developers. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include +#include #include #include -#include #include #include @@ -39,7 +39,7 @@ int LoadPNG(CImageInfo *pImg, const char *pFilename) return 0; } - if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA) || Png.width > (2<<12) || Png.height > (2<<12)) + if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA) || Png.width > (2 << 12) || Png.height > (2 << 12)) { dbg_msg("map_convert_07", "invalid image format. filename='%s'", pFilename); png_close_file(&Png); @@ -64,10 +64,10 @@ inline void IntsToStr(const int *pInts, int Num, char *pStr) { while(Num) { - pStr[0] = (((*pInts)>>24)&0xff)-128; - pStr[1] = (((*pInts)>>16)&0xff)-128; - pStr[2] = (((*pInts)>>8)&0xff)-128; - pStr[3] = ((*pInts)&0xff)-128; + pStr[0] = (((*pInts) >> 24) & 0xff) - 128; + pStr[1] = (((*pInts) >> 16) & 0xff) - 128; + pStr[2] = (((*pInts) >> 8) & 0xff) - 128; + pStr[3] = ((*pInts) & 0xff) - 128; pStr += 4; pInts++; Num--; @@ -102,7 +102,7 @@ bool CheckImageDimensions(void *pItem, int Type, const char *pFilename) return true; char aTileLayerName[12]; - IntsToStr(pTMap->m_aName, sizeof(pTMap->m_aName)/sizeof(int), aTileLayerName); + IntsToStr(pTMap->m_aName, sizeof(pTMap->m_aName) / sizeof(int), aTileLayerName); char *pName = (char *)g_DataReader.GetData(pImgItem->m_ImageName); dbg_msg("map_convert_07", "%s: Tile layer \"%s\" uses image \"%s\" with width %d, height %d, which is not divisible by 16. This is not supported in Teeworlds 0.7. Please scale the image and replace it manually.", pFilename, aTileLayerName, pName, pImgItem->m_Width, pImgItem->m_Height); return false; @@ -208,7 +208,7 @@ int main(int argc, const char **argv) return -1; } - png_init(0,0); + png_init(0, 0); g_NextDataItemID = g_DataReader.NumData(); diff --git a/src/tools/map_diff.cpp b/src/tools/map_diff.cpp index 624b29226..b8407dae8 100644 --- a/src/tools/map_diff.cpp +++ b/src/tools/map_diff.cpp @@ -1,8 +1,8 @@ -#include -#include #include #include #include +#include +#include #include @@ -46,9 +46,9 @@ bool Process(IStorage *pStorage, char **pMapNames) CMapItemLayerTilemap *pTilemap[2]; for(int i = 0; i < 2; ++i) { - pItem[i] = (CMapItemLayer *)Maps[i].GetItem(Start[i]+j, 0, 0); + pItem[i] = (CMapItemLayer *)Maps[i].GetItem(Start[i] + j, 0, 0); pTilemap[i] = (CMapItemLayerTilemap *)pItem[i]; - (void)(CTile *)Maps[i].GetData(pTilemap[i]->m_Data); + (void)(CTile *) Maps[i].GetData(pTilemap[i]->m_Data); } } @@ -57,7 +57,7 @@ bool Process(IStorage *pStorage, char **pMapNames) { CMapItemLayer *pItem[2]; for(int i = 0; i < 2; ++i) - pItem[i] = (CMapItemLayer *)Maps[i].GetItem(Start[i]+j, 0, 0); + pItem[i] = (CMapItemLayer *)Maps[i].GetItem(Start[i] + j, 0, 0); if(pItem[0]->m_Type != LAYERTYPE_TILES) continue; @@ -68,7 +68,7 @@ bool Process(IStorage *pStorage, char **pMapNames) for(int i = 0; i < 2; ++i) { pTilemap[i] = (CMapItemLayerTilemap *)pItem[i]; - IntsToStr(pTilemap[i]->m_aName, sizeof(pTilemap[i]->m_aName)/sizeof(int), aName[i]); + IntsToStr(pTilemap[i]->m_aName, sizeof(pTilemap[i]->m_aName) / sizeof(int), aName[i]); } if(str_comp(aName[0], aName[1]) != 0 || pTilemap[0]->m_Width != pTilemap[1]->m_Width || pTilemap[0]->m_Height != pTilemap[1]->m_Height) @@ -98,7 +98,7 @@ bool Process(IStorage *pStorage, char **pMapNames) return true; } -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { dbg_logger_stdout(); dbg_logger_file("map_diff.txt"); diff --git a/src/tools/map_extract.cpp b/src/tools/map_extract.cpp index 7f51eb614..f77645494 100644 --- a/src/tools/map_extract.cpp +++ b/src/tools/map_extract.cpp @@ -1,8 +1,8 @@ // Adapted from TWMapImagesRecovery by Tardo: https://github.com/Tardo/TWMapImagesRecovery -#include #include #include #include +#include #include @@ -16,7 +16,6 @@ bool Process(IStorage *pStorage, const char *pMapName, const char *pPathSave) return false; } - // check version CMapItemVersion *pVersion = (CMapItemVersion *)Map.FindItem(MAPITEMTYPE_VERSION, 0); if(pVersion && pVersion->m_Version != 1) @@ -41,7 +40,7 @@ bool Process(IStorage *pStorage, const char *pMapName, const char *pPathSave) for(int i = 0; i < Num; i++) { - CMapItemImage *pItem = (CMapItemImage *)Map.GetItem(Start+i, 0, 0); + CMapItemImage *pItem = (CMapItemImage *)Map.GetItem(Start + i, 0, 0); char *pName = (char *)Map.GetData(pItem->m_ImageName); if(pItem->m_External) @@ -54,7 +53,7 @@ bool Process(IStorage *pStorage, const char *pMapName, const char *pPathSave) // copy image data png_t Png; png_open_file_write(&Png, aBuf); - png_set_data(&Png, pItem->m_Width, pItem->m_Height, 8, PNG_TRUECOLOR_ALPHA, (unsigned char*)Map.GetData(pItem->m_ImageData)); + png_set_data(&Png, pItem->m_Width, pItem->m_Height, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)Map.GetData(pItem->m_ImageData)); png_close_file(&Png); } @@ -63,7 +62,7 @@ bool Process(IStorage *pStorage, const char *pMapName, const char *pPathSave) for(int i = 0; i < Num; i++) { - CMapItemSound *pItem = (CMapItemSound *)Map.GetItem(Start+i, 0, 0); + CMapItemSound *pItem = (CMapItemSound *)Map.GetItem(Start + i, 0, 0); char *pName = (char *)Map.GetData(pItem->m_SoundName); if(pItem->m_External) @@ -74,7 +73,7 @@ bool Process(IStorage *pStorage, const char *pMapName, const char *pPathSave) dbg_msg("map_extract", "writing sound: %s (%d B)", aBuf, pItem->m_SoundDataSize); IOHANDLE Opus = io_open(aBuf, IOFLAG_WRITE); - io_write(Opus, (unsigned char*)Map.GetData(pItem->m_SoundData), pItem->m_SoundDataSize); + io_write(Opus, (unsigned char *)Map.GetData(pItem->m_SoundData), pItem->m_SoundDataSize); io_close(Opus); } @@ -90,12 +89,12 @@ int main(int argc, char *argv[]) IStorage *pStorage = CreateLocalStorage(); - if (argc == 2) + if(argc == 2) { str_copy(aMap, argv[1], sizeof(aMap)); str_copy(aDir, ".", sizeof(aMap)); } - else if (argc == 3) + else if(argc == 3) { str_copy(aMap, argv[1], sizeof(aMap)); str_copy(aDir, argv[2], sizeof(aDir)); @@ -106,7 +105,7 @@ int main(int argc, char *argv[]) return -1; } - if (!fs_is_dir(aDir)) + if(!fs_is_dir(aDir)) { dbg_msg("usage", "directory '%s' does not exist", aDir); return -1; diff --git a/src/tools/map_replace_image.cpp b/src/tools/map_replace_image.cpp index 456bfa907..3fb8832e5 100644 --- a/src/tools/map_replace_image.cpp +++ b/src/tools/map_replace_image.cpp @@ -1,11 +1,11 @@ /* (c) DDNet developers. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ -#include #include +#include +#include #include #include -#include #include #include @@ -21,7 +21,7 @@ CDataFileWriter g_DataWriter; // global new image data (set by ReplaceImageItem) int g_NewNameID = -1; char g_aNewName[128]; -int g_NewDataID = -1; +int g_NewDataID = -1; int g_NewDataSize = 0; void *g_pNewData = 0; @@ -39,7 +39,7 @@ int LoadPNG(CImageInfo *pImg, const char *pFilename) return 0; } - if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA) || Png.width > (2<<12) || Png.height > (2<<12)) + if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA) || Png.width > (2 << 12) || Png.height > (2 << 12)) { dbg_msg("map_replace_image", "invalid image format. filename='%s'", pFilename); png_close_file(&Png); @@ -79,7 +79,7 @@ void *ReplaceImageItem(void *pItem, int Type, const char *pImgName, const char * *pNewImgItem = *pImgItem; - pNewImgItem->m_Width = ImgInfo.m_Width; + pNewImgItem->m_Width = ImgInfo.m_Width; pNewImgItem->m_Height = ImgInfo.m_Height; int PixelSize = ImgInfo.m_Format == CImageInfo::FORMAT_RGB ? 3 : 4; @@ -107,7 +107,7 @@ int main(int argc, const char **argv) return -1; } - if (!pStorage) + if(!pStorage) { dbg_msg("map_replace_image", "error loading storage"); return -1; @@ -136,7 +136,7 @@ int main(int argc, const char **argv) return -1; } - png_init(0,0); + png_init(0, 0); // add all items for(int Index = 0; Index < g_DataReader.NumItems(); Index++) @@ -164,7 +164,7 @@ int main(int argc, const char **argv) pData = g_pNewData; Size = g_NewDataSize; } - else if (Index == g_NewNameID) + else if(Index == g_NewNameID) { pData = (void *)g_aNewName; Size = str_length(g_aNewName) + 1; diff --git a/src/tools/packetgen.cpp b/src/tools/packetgen.cpp index 9b52aadce..b2128e5be 100644 --- a/src/tools/packetgen.cpp +++ b/src/tools/packetgen.cpp @@ -2,7 +2,10 @@ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include -enum { NUM_SOCKETS = 64 }; +enum +{ + NUM_SOCKETS = 64 +}; void Run(NETADDR Dest) { @@ -11,7 +14,7 @@ void Run(NETADDR Dest) for(int i = 0; i < NUM_SOCKETS; i++) { NETADDR BindAddr = {NETTYPE_IPV4, {0}, 0}; - aSockets[i] = net_udp_create(BindAddr); + aSockets[i] = net_udp_create(BindAddr); } while(1) @@ -30,7 +33,7 @@ void Run(NETADDR Dest) int main(int argc, char **argv) { - NETADDR Dest = {NETTYPE_IPV4, {127,0,0,1}, 8303}; + NETADDR Dest = {NETTYPE_IPV4, {127, 0, 0, 1}, 8303}; Run(Dest); return 0; } diff --git a/src/twping/twping.cpp b/src/twping/twping.cpp index 2964d66f5..dbc9a6adf 100644 --- a/src/twping/twping.cpp +++ b/src/twping/twping.cpp @@ -1,9 +1,9 @@ -#include -#include #include -#include +#include #include #include +#include +#include static CNetClient g_NetOp; // main @@ -21,7 +21,7 @@ int main(int argc, char **argv) // ignore_convention } NETADDR Addr; - if (net_host_lookup(argv[1], &Addr, NETTYPE_ALL)) + if(net_host_lookup(argv[1], &Addr, NETTYPE_ALL)) { fprintf(stderr, "host lookup failed\n"); return 1; @@ -30,7 +30,7 @@ int main(int argc, char **argv) // ignore_convention if(Addr.port == 0) Addr.port = 8303; - unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO) + 1]; CNetChunk Packet; mem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)); @@ -59,7 +59,7 @@ int main(int argc, char **argv) // ignore_convention // we got ze info CUnpacker Up; - Up.Reset((unsigned char*)Packet.m_pData+sizeof(SERVERBROWSE_INFO), Packet.m_DataSize-sizeof(SERVERBROWSE_INFO)); + Up.Reset((unsigned char *)Packet.m_pData + sizeof(SERVERBROWSE_INFO), Packet.m_DataSize - sizeof(SERVERBROWSE_INFO)); int Token = str_toint(Up.GetString()); if(Token != CurToken) continue; From ee8872fb752b36c94132e932dc66c2019ef09891 Mon Sep 17 00:00:00 2001 From: def Date: Fri, 25 Sep 2020 18:52:45 +0200 Subject: [PATCH 6/7] Add formatting-revs.txt to filter out automatic clang-formats for better git blame information, for example: $ git blame --ignore-revs-file formatting-revs.txt src/antibot/antibot_null.cpp You can also set it in your .git/config: [blame] ignoreRevsFile = formatting-revs.txt --- formatting-revs.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 formatting-revs.txt diff --git a/formatting-revs.txt b/formatting-revs.txt new file mode 100644 index 000000000..2cef7ba35 --- /dev/null +++ b/formatting-revs.txt @@ -0,0 +1,11 @@ +f7b37eaf6a5dcd20c3bf53c842474129197b585f +3a986fbe529a0b34b4ca968cd8d9e12a07ba3e68 +a67a8e36aa81f12b2cac8f5e240228e669fdd11e +f42a5a0431b16cfe3ed7f3f8158606e8fd36d0b1 +833e3640b469d5fb98bb431ef834759815d94b55 +8ef6a0da169d6eba151d6909a96fb52dc0a47384 +4e157c64e3d7e36f23b3dfad0555f3095f31f712 +a273969bc198d7259f57286c8a19214d48d22de5 +cfd32c357b5aca410c7befb8ae4953fec1fa54ed +d4da82f977abb34cd0ed9a77e707b4c42f26673d +aecc6fb1a59407f84ef5d2b51af9432408cc9563 From b178c7c74a0306c6fad59b0c796e18418318ea33 Mon Sep 17 00:00:00 2001 From: def Date: Sat, 26 Sep 2020 10:23:33 +0200 Subject: [PATCH 7/7] Make sure headers compile standalone Not planning to do this automatically, but at least cleaning it up once provides some benefit. Every header should include what it uses. $ for i in src/**/*.h; do j=${i#"src/"}; echo $j; echo "#include <$j>\nint main() { return 0; }" | /usr/bin/c++ -DCONF_OPENSSL -DCONF_SQL -DCONF_VIDEORECORDER -DCONF_WAVPACK_CLOSE_FILE -DCONF_WAVPACK_OPEN_FILE_INPUT_EX -DGAME_RELEASE_VERSION=\"15.0.5\" -DGLEW_STATIC -D_FORTIFY_SOURCE=2 -I/usr/include/freetype2 -I/usr/include/opus -I/usr/include/SDL2 -I/usr/include/wavpack -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/libmount -I/usr/include/blkid -Isrc -I/usr/include/mysql -I/home/deen/sys/include/ -O2 -g -DNDEBUG -fdiagnostics-color=always -fstack-protector-all -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Wformat=2 -Wno-nullability-completeness -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wrestrict -std=gnu++11 -o /dev/null -x c++ -; done Ignored: tuning.h, variables.h, config_common.h, mapitems_ex_types.h, mapbugs_list.h, protocol7.h, teehistorian_ex_chunks.h, protocol_ex_msgs.h, config.h, config_variables.h, external, keynames.h --- src/engine/client/backend_sdl.h | 3 +++ src/engine/client/client.h | 17 +++++++++++++++++ src/engine/client/friends.h | 2 ++ src/engine/client/graphics_threaded.h | 1 + src/engine/client/input.h | 5 +++++ src/engine/client/serverbrowser.h | 3 +++ src/engine/client/sound.h | 2 ++ src/engine/shared/econ.h | 2 ++ src/engine/shared/filecollection.h | 4 ++++ src/engine/shared/netban.h | 2 ++ src/engine/shared/websockets.h | 2 ++ src/engine/uuid.h | 2 ++ 12 files changed, 45 insertions(+) diff --git a/src/engine/client/backend_sdl.h b/src/engine/client/backend_sdl.h index cb0b42653..53ae93d32 100644 --- a/src/engine/client/backend_sdl.h +++ b/src/engine/client/backend_sdl.h @@ -2,9 +2,12 @@ #define ENGINE_CLIENT_BACKEND_SDL_H #include "SDL.h" +#include "SDL_opengl.h" #include "graphics_threaded.h" +#include + #include #if defined(CONF_PLATFORM_MACOSX) diff --git a/src/engine/client/client.h b/src/engine/client/client.h index 4b1d289ca..fb05019b4 100644 --- a/src/engine/client/client.h +++ b/src/engine/client/client.h @@ -3,12 +3,29 @@ #ifndef ENGINE_CLIENT_CLIENT_H #define ENGINE_CLIENT_CLIENT_H +#include #include #include +#include +#include #include #include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #define CONNECTLINK "ddnet:" diff --git a/src/engine/client/friends.h b/src/engine/client/friends.h index 4ddc043d0..8e98c9b49 100644 --- a/src/engine/client/friends.h +++ b/src/engine/client/friends.h @@ -3,6 +3,8 @@ #ifndef ENGINE_CLIENT_FRIENDS_H #define ENGINE_CLIENT_FRIENDS_H +#include +#include #include class CFriends : public IFriends diff --git a/src/engine/client/graphics_threaded.h b/src/engine/client/graphics_threaded.h index b421ce90a..c596cf5c3 100644 --- a/src/engine/client/graphics_threaded.h +++ b/src/engine/client/graphics_threaded.h @@ -2,6 +2,7 @@ #define ENGINE_CLIENT_GRAPHICS_THREADED_H #include +#include #include diff --git a/src/engine/client/input.h b/src/engine/client/input.h index 83da74fb8..8d1b40111 100644 --- a/src/engine/client/input.h +++ b/src/engine/client/input.h @@ -3,6 +3,11 @@ #ifndef ENGINE_CLIENT_INPUT_H #define ENGINE_CLIENT_INPUT_H +#include +#include + +#include + class CInput : public IEngineInput { IEngineGraphics *m_pGraphics; diff --git a/src/engine/client/serverbrowser.h b/src/engine/client/serverbrowser.h index 47740fa5d..db7cea02e 100644 --- a/src/engine/client/serverbrowser.h +++ b/src/engine/client/serverbrowser.h @@ -3,8 +3,11 @@ #ifndef ENGINE_CLIENT_SERVERBROWSER_H #define ENGINE_CLIENT_SERVERBROWSER_H +#include #include +#include #include +#include #include class CServerBrowser : public IServerBrowser diff --git a/src/engine/client/sound.h b/src/engine/client/sound.h index dfc59d5c9..884042947 100644 --- a/src/engine/client/sound.h +++ b/src/engine/client/sound.h @@ -3,7 +3,9 @@ #ifndef ENGINE_CLIENT_SOUND_H #define ENGINE_CLIENT_SOUND_H +#include #include +#include #include "SDL.h" diff --git a/src/engine/shared/econ.h b/src/engine/shared/econ.h index 9be62263b..a7f82a984 100644 --- a/src/engine/shared/econ.h +++ b/src/engine/shared/econ.h @@ -3,6 +3,8 @@ #include "network.h" +#include + class CEcon { enum diff --git a/src/engine/shared/filecollection.h b/src/engine/shared/filecollection.h index 752d9190d..19d32c503 100644 --- a/src/engine/shared/filecollection.h +++ b/src/engine/shared/filecollection.h @@ -3,6 +3,10 @@ #ifndef ENGINE_SHARED_FILECOLLECTION_H #define ENGINE_SHARED_FILECOLLECTION_H +#include + +#include + class CFileCollection { enum diff --git a/src/engine/shared/netban.h b/src/engine/shared/netban.h index 7507620f7..4c87b0069 100644 --- a/src/engine/shared/netban.h +++ b/src/engine/shared/netban.h @@ -1,6 +1,8 @@ #ifndef ENGINE_SHARED_NETBAN_H #define ENGINE_SHARED_NETBAN_H +#include + #include inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2) diff --git a/src/engine/shared/websockets.h b/src/engine/shared/websockets.h index b52eae240..32763f39f 100644 --- a/src/engine/shared/websockets.h +++ b/src/engine/shared/websockets.h @@ -6,6 +6,8 @@ #include #endif +#include + int websocket_create(const char *addr, int port); int websocket_destroy(int socket); int websocket_recv(int socket, unsigned char *data, size_t maxsize, struct sockaddr_in *sockaddrbuf, size_t fromLen); diff --git a/src/engine/uuid.h b/src/engine/uuid.h index 591a9a8db..6063f63e2 100644 --- a/src/engine/uuid.h +++ b/src/engine/uuid.h @@ -1,4 +1,6 @@ #ifndef ENGINE_UUID_H #define ENGINE_UUID_H +#include + void RegisterGameUuids(CUuidManager *pManager); #endif // ENGINE_UUID_H