From efb29e6be5d58e44a6c99c72833b1cfe33747906 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 12:42:22 +0100 Subject: [PATCH 01/42] d_cliserv: do some cleanups - expose SAVEGAMESIZE - pass node number to SV_AddWaitingPlayers (saves iterating through all 128 net nodes everytime a player joins) lifted from RR - move all packet handling to the packet handlers - Reorder packethandling switches a little, so common/important packets get checked first - fix wrong clamp for realfirsttic that was too early - add nowtime division by NEWTICRATERATIO (no change unless ticrate changes) --- src/d_clisrv.c | 427 ++++++++++++++++++++++++------------------------- src/d_clisrv.h | 4 +- src/g_game.c | 5 +- 3 files changed, 215 insertions(+), 221 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index fa1536e72..33b69045e 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -1933,8 +1933,6 @@ static boolean SV_SendServerConfig(INT32 node) return waspacketsent; } -#define SAVEGAMESIZE (768*1024) - #ifdef SATURNPAK static boolean SV_ResendingSavegameToAnyone(void) { @@ -4565,71 +4563,69 @@ static void Got_RemovePlayer(const UINT8 **p, INT32 playernum) #endif } -static boolean SV_AddWaitingPlayers(void) +static boolean SV_AddWaitingPlayers(SINT8 node) { - INT32 node, n, newplayer = false; + INT32 n; UINT8 buf[2]; UINT8 newplayernum = 0; + boolean newplayer = false; // What is the reason for this? Why can't newplayernum always be 0? // Sal: Because the dedicated player is stupidly forced into players[0]..... if (dedicated) newplayernum = 1; - for (node = 0; node < MAXNETNODES; node++) + // splitscreen can allow 2+ players in one node + for (; nodewaiting[node] > 0; nodewaiting[node]--) { - // splitscreen can allow 2+ players in one node - for (; nodewaiting[node] > 0; nodewaiting[node]--) + newplayer = true; + + // search for a free playernum + // we can't use playeringame since it is not updated here + for (; newplayernum < MAXPLAYERS; newplayernum++) { - newplayer = true; - - // search for a free playernum - // we can't use playeringame since it is not updated here - for (; newplayernum < MAXPLAYERS; newplayernum++) - { - for (n = 0; n < MAXNETNODES; n++) - if (nodetoplayer[n] == newplayernum || nodetoplayer2[n] == newplayernum - || nodetoplayer3[n] == newplayernum || nodetoplayer4[n] == newplayernum) - break; - if (n == MAXNETNODES) + for (n = 0; n < MAXNETNODES; n++) + if (nodetoplayer[n] == newplayernum || nodetoplayer2[n] == newplayernum + || nodetoplayer3[n] == newplayernum || nodetoplayer4[n] == newplayernum) break; - } - - // should never happen since we check the playernum - // before accepting the join - I_Assert(newplayernum < MAXPLAYERS); - - playernode[newplayernum] = (UINT8)node; - - buf[0] = (UINT8)node; - buf[1] = newplayernum; - if (playerpernode[node] < 1) - { - nodetoplayer[node] = newplayernum; - } - else if (playerpernode[node] < 2) - { - nodetoplayer2[node] = newplayernum; - buf[1] += MAXPLAYERS; - } - else if (playerpernode[node] < 3) - { - nodetoplayer3[node] = newplayernum; - buf[1] += MAXPLAYERS*2; - } - else - { - nodetoplayer4[node] = newplayernum; - buf[1] += MAXPLAYERS*3; - } - playerpernode[node]++; - - SendNetXCmd(XD_ADDPLAYER, &buf, 2); - - DEBFILE(va("Server added player %d node %d\n", newplayernum, node)); - // use the next free slot (we can't put playeringame[newplayernum] = true here) - newplayernum++; + if (n == MAXNETNODES) + break; } + + // should never happen since we check the playernum + // before accepting the join + I_Assert(newplayernum < MAXPLAYERS); + + playernode[newplayernum] = (UINT8)node; + + buf[0] = (UINT8)node; + buf[1] = newplayernum; + if (playerpernode[node] < 1) + { + nodetoplayer[node] = newplayernum; + } + else if (playerpernode[node] < 2) + { + nodetoplayer2[node] = newplayernum; + buf[1] += MAXPLAYERS; + } + else if (playerpernode[node] < 3) + { + nodetoplayer3[node] = newplayernum; + buf[1] += MAXPLAYERS*2; + } + else + { + nodetoplayer4[node] = newplayernum; + buf[1] += MAXPLAYERS*3; + } + playerpernode[node]++; + + SendNetXCmd(XD_ADDPLAYER, &buf, 2); + + DEBFILE(va("Server added player %d node %d\n", newplayernum, node)); + // use the next free slot (we can't put playeringame[newplayernum] = true here) + newplayernum++; } return newplayer; @@ -4666,6 +4662,8 @@ boolean Playing(void) boolean SV_SpawnServer(void) { + boolean result = false; + if (demo.playback) G_StopDemo(); // reset engine parameter @@ -4686,7 +4684,15 @@ boolean SV_SpawnServer(void) else doomcom->numslots = 1; } - return SV_AddWaitingPlayers(); + // strictly speaking, i'm not convinced the following is necessary + // but I'm not confident enough to remove it entirely in case it breaks something + { + SINT8 node = 0; + for (; node < MAXNETNODES; node++) + result |= SV_AddWaitingPlayers(node); + } + + return result; } void SV_StopServer(void) @@ -4772,8 +4778,12 @@ static size_t TotalTextCmdPerTic(tic_t tic) * \param node The packet sender * */ -static void HandleConnect(SINT8 node) +static void PT_ClientJoin(SINT8 node) { + // Ignore duplicate packets + if (client || nodeingame[node]|| levelloading) + return; + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); // Sal: Dedicated mode is INCREDIBLY hacked together. @@ -4783,8 +4793,17 @@ static void HandleConnect(SINT8 node) UINT8 connectedplayers = 0; for (UINT8 i = dedicated ? 1 : 0; i < MAXPLAYERS; i++) - if (playernode[i] != UINT8_MAX) // We use this to count players because it is affected by SV_AddWaitingPlayers when more than one client joins on the same tic, unlike playeringame and D_NumPlayers. UINT8_MAX denotes no node for that player + { + // We use this to count players because it is affected by SV_AddWaitingPlayers when + // more than one client joins on the same tic, unlike playeringame and D_NumPlayers. + // UINT8_MAX denotes no node for that player. + + if (playernode[i] != UINT8_MAX) + { connectedplayers++; + } + } + #ifdef SATURNJOIN const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && netbuffer->u.clientcfg.issaturn == ISSATURN); // Check the packet lenght to skip potential garbo data! @@ -4840,7 +4859,7 @@ static void HandleConnect(SINT8 node) else if (netbuffer->u.clientcfg.version != VERSION || netbuffer->u.clientcfg.subversion != SUBVERSION) { - SV_SendRefuse(node, va(M_GetText("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)"), VERSION, SUBVERSION)); + SV_SendRefuse(node, va("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)", VERSION, SUBVERSION)); } #ifdef SATURNJOIN else if (((!cv_allownewplayer.value && !issaturn) || (!cv_allownewsaturnplayer.value && issaturn)) && node) @@ -4848,71 +4867,61 @@ static void HandleConnect(SINT8 node) else if (!cv_allownewplayer.value && node) #endif { - SV_SendRefuse(node, M_GetText(cv_joinrefusemessage.string)); + SV_SendRefuse(node, cv_joinrefusemessage.string); } else if (connectedplayers >= maxplayers) { - SV_SendRefuse(node, va(M_GetText("Maximum players reached: %d"), maxplayers)); + SV_SendRefuse(node, va("Maximum players reached: %d", maxplayers)); } else if (netgame && netbuffer->u.clientcfg.localplayers > 4) // Hacked client? { - SV_SendRefuse(node, M_GetText("Too many players from\nthis node.")); + SV_SendRefuse(node, "Too many players from\nthis node."); } else if (netgame && connectedplayers + netbuffer->u.clientcfg.localplayers > maxplayers) { - SV_SendRefuse(node, va(M_GetText("Number of local players\nwould exceed maximum: %d"), maxplayers)); + SV_SendRefuse(node, va("Number of local players\nwould exceed maximum: %d", maxplayers)); } else if (netgame && !netbuffer->u.clientcfg.localplayers) // Stealth join? { - SV_SendRefuse(node, M_GetText("No players from\nthis node.")); + SV_SendRefuse(node, "No players from\nthis node."); } else { - boolean newnode = false; - // client authorised to join nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); - if (!nodeingame[node]) + gamestate_t backupstate = gamestate; + + SV_AddNode(node); + + /// \note Wait what??? + /// What if the gamestate takes more than one second to get downloaded? + /// Or if a lagspike happens? + // you get a free second before desynch checks. use it wisely. + SV_InitResynchVars(node); + + if (!SV_SendServerConfig(node)) { - gamestate_t backupstate = gamestate; - - newnode = true; - - SV_AddNode(node); - - /// \note Wait what??? - /// What if the gamestate takes more than one second to get downloaded? - /// Or if a lagspike happens? - // you get a free second before desynch checks. use it wisely. - SV_InitResynchVars(node); - - if (!SV_SendServerConfig(node)) - { - G_SetGamestate(backupstate); - /// \note Shouldn't SV_SendRefuse be called before ResetNode? - SV_SendRefuse(node, M_GetText("Server couldn't send info, please try again")); - ResetNode(node); // Yeah, lets try it! - /// \todo fix this !!! - return; // restart the while - } - - SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea - //if (gamestate != GS_LEVEL) // GS_INTERMISSION, etc? - // SV_SendPlayerConfigs(node); // send bare minimum player info G_SetGamestate(backupstate); - DEBFILE("new node joined\n"); + /// \note Shouldn't SV_SendRefuse be called before ResetNode? + SV_SendRefuse(node, "Server couldn't send info, please try again"); + ResetNode(node); // Yeah, lets try it! + /// \todo fix this !!! + return; // restart the while } + SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea + //if (gamestate != GS_LEVEL) // GS_INTERMISSION, etc? + // SV_SendPlayerConfigs(node); // send bare minimum player info + G_SetGamestate(backupstate); + DEBFILE("new node joined\n"); + if (nodewaiting[node]) { - if (node && newnode) - { - SV_SendSaveGame(node, false); // send a complete game state - DEBFILE("send savegame\n"); - } + SV_SendSaveGame(node, false); // send a complete game state + DEBFILE("send savegame\n"); - SV_AddWaitingPlayers(); + SV_AddWaitingPlayers(node); } } } @@ -4922,8 +4931,11 @@ static void HandleConnect(SINT8 node) * \param node The packet sender (should be the server) * */ -static void HandleShutdown(SINT8 node) +static void PT_ServerShutdown(SINT8 node) { + if (node != servernode || server || cl_mode == CL_SEARCHING) + return; + (void)node; D_QuitNetGame(); CL_Reset(); @@ -4951,7 +4963,7 @@ static void HandleTimeout(SINT8 node) * \note What happens if the packet comes from a client or something like that? * */ -static void HandleServerInfo(SINT8 node) +static void PT_ServerInfo(SINT8 node) { char servername[MAXSERVERNAME]; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -4974,7 +4986,7 @@ static void HandleServerInfo(SINT8 node) memcpy(connectedservername, netbuffer->u.serverinfo.servername, MAXSERVERNAME); } -static void HandlePlayerInfo(void) +static void PT_PlayerInfo(void) { INT32 i; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -5372,6 +5384,9 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_ASKINFOVIAMS: Net_CloseConnection(node); break; + case PT_SERVERINFO: + PT_ServerInfo(node); + break; case PT_TELLFILESNEEDED: PT_TellFilesNeeded(node); break; @@ -5402,7 +5417,7 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_CLIENTCMD: break; // This is not an "unknown packet" case PT_PLAYERINFO: - HandlePlayerInfo(); + PT_PlayerInfo(); break; case PT_MAPICON: PT_MapIcon(); @@ -5410,6 +5425,13 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_NEEDMAPICON: PT_NeedMapIcon(node); break; + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; + case PT_SERVERSHUTDOWN: + PT_ServerShutdown(node); + break; + case PT_SERVERTICS: // Do not remove my own server (we have just get a out of order packet) if (node == servernode) @@ -5659,6 +5681,10 @@ static void PT_BasicKeepAlive(INT32 netconsole, SINT8 node) static void PT_TextCmd(INT32 netconsole, SINT8 node) { + size_t j; + tic_t tic; + UINT8 *textcmd; + if (client) return; @@ -5680,79 +5706,84 @@ static void PT_TextCmd(INT32 netconsole, SINT8 node) } if (netconsole < 0 || netconsole >= MAXPLAYERS) - Net_UnAcknowledgePacket(node); - else { - size_t j; - tic_t tic = maketic; - UINT8 *textcmd; - - // ignore if the textcmd has a reported size of zero - // this shouldn't be sent at all - if (!netbuffer->u.textcmd[0]) - { - DEBFILE(va("GetPacket: Textcmd with size 0 detected! (node %u, player %d)\n", - node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // ignore if the textcmd size var is actually larger than it should be - // BASEPACKETSIZE + 1 (for size) + textcmd[0] should == datalength - if (netbuffer->u.textcmd[0] > (size_t)doomcom->datalength-1) - { - DEBFILE(va("GetPacket: Bad Textcmd packet size! (expected %d, actual %s, node %u, player %d)\n", - netbuffer->u.textcmd[0], sizeu1((size_t)doomcom->datalength-1), - node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // check if tic that we are making isn't too large else we cannot send it :( - // doomcom->numslots+1 "+1" since doomcom->numslots can change within this time and sent time - j = (software_MAXPACKETLENGTH - (netbuffer->u.textcmd[0]+2+BASESERVERTICSSIZE + (doomcom->numslots+1)*sizeof(ticcmd_t))); - - // search a tic that have enougth space in the ticcmd - while ((textcmd = D_GetExistingTextcmd(tic, netconsole)), - (TotalTextCmdPerTic(tic) > j || netbuffer->u.textcmd[0] + (textcmd ? textcmd[0] : 0) > MAXTEXTCMD) - && tic < firstticstosend + BACKUPTICS) - { - tic++; - } - - if (tic >= firstticstosend + BACKUPTICS) - { - DEBFILE(va("GetPacket: Textcmd too long (max %s, used %s, mak %d, " - "tosend %u, node %u, player %d)\n", sizeu1(j), sizeu2(TotalTextCmdPerTic(maketic)), - maketic, firstticstosend, node, netconsole)); - Net_UnAcknowledgePacket(node); - return; - } - - // Make sure we have a buffer - if (!textcmd) - textcmd = D_GetTextcmd(tic, netconsole); - - DEBFILE(va("textcmd put in tic %u at position %d (player %d) ftts %u mk %u\n", - tic, textcmd[0]+1, netconsole, firstticstosend, maketic)); - - memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); - textcmd[0] += (UINT8)netbuffer->u.textcmd[0]; + Net_UnAcknowledgePacket(node); + return; } + + // ignore if the textcmd has a reported size of zero + // this shouldn't be sent at all + if (!netbuffer->u.textcmd[0]) + { + DEBFILE(va("GetPacket: Textcmd with size 0 detected! (node %u, player %d)\n", + node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // ignore if the textcmd size var is actually larger than it should be + // BASEPACKETSIZE + 1 (for size) + textcmd[0] should == datalength + if (netbuffer->u.textcmd[0] > (size_t)doomcom->datalength-1) + { + DEBFILE(va("GetPacket: Bad Textcmd packet size! (expected %d, actual %s, node %u, player %d)\n", + netbuffer->u.textcmd[0], sizeu1((size_t)doomcom->datalength-1), + node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // check if tic that we are making isn't too large else we cannot send it :( + // doomcom->numslots+1 "+1" since doomcom->numslots can change within this time and sent time + j = (software_MAXPACKETLENGTH - (netbuffer->u.textcmd[0]+2+BASESERVERTICSSIZE + (doomcom->numslots+1)*sizeof(ticcmd_t))); + + tic = maketic; + + // search a tic that have enougth space in the ticcmd + while ((textcmd = D_GetExistingTextcmd(tic, netconsole)), + (TotalTextCmdPerTic(tic) > j || netbuffer->u.textcmd[0] + (textcmd ? textcmd[0] : 0) > MAXTEXTCMD) + && tic < firstticstosend + BACKUPTICS) + { + tic++; + } + + if (tic >= firstticstosend + BACKUPTICS) + { + DEBFILE(va("GetPacket: Textcmd too long (max %s, used %s, mak %d, " + "tosend %u, node %u, player %d)\n", sizeu1(j), sizeu2(TotalTextCmdPerTic(maketic)), + maketic, firstticstosend, node, netconsole)); + Net_UnAcknowledgePacket(node); + return; + } + + // Make sure we have a buffer + if (!textcmd) + textcmd = D_GetTextcmd(tic, netconsole); + + DEBFILE(va("textcmd put in tic %u at position %d (player %d) ftts %u mk %u\n", + tic, textcmd[0]+1, netconsole, firstticstosend, maketic)); + + memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); + textcmd[0] += (UINT8)netbuffer->u.textcmd[0]; } static void PT_ClientQuit(INT32 netconsole, SINT8 node) { + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + if (client) + { + if (node == servernode && cl_mode != CL_SEARCHING && netbuffer->packettype == PT_NODETIMEOUT) + HandleTimeout(node); return; + } // nodeingame will be put false in the execution of kick command // this allow to send some packets to the quitting client to have their ack back nodewaiting[node] = 0; if (netconsole != -1 && playeringame[netconsole]) { - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - SendKick(netconsole, (netbuffer->packettype == PT_NODETIMEOUT) ? KICK_MSG_TIMEOUT : KICK_MSG_PLAYER_QUIT); + const int quitreason = ((netbuffer->packettype == PT_NODETIMEOUT) ? KICK_MSG_TIMEOUT : KICK_MSG_PLAYER_QUIT); + SendKick(netconsole, quitreason); } Net_CloseConnection(node); nodeingame[node] = false; @@ -5938,9 +5969,6 @@ static void HandlePacketFromPlayer(SINT8 node) switch (netbuffer->packettype) { // -------------------------------------------- SERVER RECEIVE ---------- - case PT_RESYNCHGET: - SV_AcknowledgeResynchAck(node, netbuffer->u.resynchgot); - break; case PT_CLIENTCMD: case PT_CLIENT2CMD: case PT_CLIENT3CMD: @@ -5966,16 +5994,13 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENTQUIT: PT_ClientQuit(netconsole, node); break; -// -------------------------------------------- CLIENT RECEIVE ---------- - case PT_RESYNCHEND: - PT_Resynched(node); + case PT_RESYNCHGET: + SV_AcknowledgeResynchAck(node, netbuffer->u.resynchgot); break; +// -------------------------------------------- CLIENT RECEIVE ---------- case PT_SERVERTICS: PT_ServerTics(node); break; - case PT_RESYNCHING: - PT_Resynching(node); - break; case PT_PING: PT_Ping(node); break; @@ -5999,6 +6024,12 @@ static void HandlePacketFromPlayer(SINT8 node) is_client_saturn[node] = true; break; #endif + case PT_RESYNCHING: + PT_Resynching(node); + break; + case PT_RESYNCHEND: + PT_Resynched(node); + break; default: DEBFILE(va("UNKNOWN PACKET TYPE RECEIVED %d from host %d\n", netbuffer->packettype, node)); } @@ -6019,36 +6050,6 @@ static void GetPackets(void) { node = (SINT8)doomcom->remotenode; - if (server && netbuffer->packettype == PT_CLIENTJOIN) - { - if (!levelloading) // Otherwise just ignore - { - HandleConnect(node); - } - - continue; - } - - if (client && node == servernode && cl_mode != CL_SEARCHING) - { - if (netbuffer->packettype == PT_SERVERSHUTDOWN) - { - HandleShutdown(node); - continue; - } - if (netbuffer->packettype == PT_NODETIMEOUT) - { - HandleTimeout(node); - continue; - } - } - - if (netbuffer->packettype == PT_SERVERINFO) - { - HandleServerInfo(node); - continue; - } - /*if (netbuffer->packettype == PT_PLAYERINFO) continue; // We do nothing with PLAYERINFO, that's for the MS browser. Not quite true anymore :p*/ @@ -6367,21 +6368,7 @@ static void CL_SendClientCmd(void) { if (localtextcmd[i][0]) { - switch (i) - { - case 3: - netbuffer->packettype = PT_TEXTCMD4; - break; - case 2: - netbuffer->packettype = PT_TEXTCMD3; - break; - case 1: - netbuffer->packettype = PT_TEXTCMD2; - break; - default: - netbuffer->packettype = PT_TEXTCMD; - break; - } + netbuffer->packettype = PT_TEXTCMD + i; memcpy(netbuffer->u.textcmd, localtextcmd[i], localtextcmd[i][0]+1); @@ -6425,7 +6412,7 @@ static void SV_SendTics(void) continue; // assert supposedtics[n]>=nettics[n] - realfirsttic = max(supposedtics[n], firstticstosend); + realfirsttic = supposedtics[n]; lasttictosend = min(maketic, nettics[n] + CLIENTBACKUPTICS); if (realfirsttic >= lasttictosend) @@ -7164,6 +7151,8 @@ void NetUpdate(void) Net_AckTicker(); HandleNodeTimeouts(); + nowtime /= NEWTICRATERATIO; + if (nowtime > resptime) { resptime = nowtime; @@ -7189,9 +7178,15 @@ void NetUpdate(void) INT32 D_NumPlayers(void) { INT32 num = 0, ix; + for (ix = 0; ix < MAXPLAYERS; ix++) + { if (playeringame[ix]) + { num++; + } + } + return num; } diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 430729bc2..08bccf845 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -660,9 +660,11 @@ extern UINT8 hu_redownloadinggamestate; #endif extern boolean hu_stopped; // kart, true when the game is stopped for players due to a disconnecting or connecting player +#define SAVEGAMESIZE (768*1024) + typedef struct rewind_s { - UINT8 savebuffer[(768*1024)]; + UINT8 savebuffer[SAVEGAMESIZE]; tic_t leveltime; size_t demopos; diff --git a/src/g_game.c b/src/g_game.c index 55c2c6c1a..14acd7f62 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -69,9 +69,6 @@ UINT8 botcolor = 0; JoyType_t Joystick[MAXSPLITSCREENPLAYERS] = {}; -// 1024 bytes is plenty for a savegame -#define SAVEGAMESIZE (1024) - // SRB2kart char gamedatafilename[64] = "kartdata.dat"; char timeattackfolder[64] = "kart"; @@ -3837,7 +3834,7 @@ void G_SaveGame(UINT32 savegameslot) char name[VERSIONSIZE]; size_t length; - save.p = save.buffer = (UINT8 *)Z_Malloc(SAVEGAMESIZE, PU_STATIC, NULL); + save.p = save.buffer = (UINT8 *)Z_Malloc(1024, PU_STATIC, NULL); // 1024 bytes is plenty for a savegame if (!save.p) { CONS_Alert(CONS_ERROR, M_GetText("No more free memory for saving game data\n")); From 96aaaf52615cd010f68a49b12a33b3b04ffa6c41 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 12:45:47 +0100 Subject: [PATCH 02/42] merge SendNameAndColor & SendWeaponPref TODO: make a bunch of player specific cvars arrays for splitscreen handling - also cleanup some strlen usage --- src/d_clisrv.c | 2 +- src/d_netcmd.c | 626 ++++++++++++------------------------------------- src/d_netcmd.h | 7 +- src/r_main.cpp | 8 +- 4 files changed, 151 insertions(+), 492 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 33b69045e..ccb8d092b 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4495,7 +4495,7 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) P_ForceLocalAngle(&players[newplayernum], (angle_t)(players[newplayernum].cmd.angleturn << TICCMD_REDUCE)); - D_SendPlayerConfig(); + D_SendPlayerConfig(splitscreenplayer); addedtogame = true; } diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 00760e4a4..246702a4d 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -1197,11 +1197,11 @@ static boolean AllowedPlayerNameChar(char ch) static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) { - INT32 ix; + size_t ix, len = strlen(name); - if (strlen(name) == 0 || strlen(name) > MAXPLAYERNAME) + if (len == 0 || len > MAXPLAYERNAME) return false; // Empty or too long. - if (name[0] == ' ' || name[strlen(name)-1] == ' ') + if (name[0] == ' ' || name[len-1] == ' ') return false; // Starts or ends with a space. if (isdigit(name[0])) return false; // Starts with a digit. @@ -1215,20 +1215,19 @@ static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) // Also, anything over 0x80 is disallowed too, since compilers love to // differ on whether they're printable characters or not. - for (ix = 0; name[ix] != '\0'; ix++) + for (ix = 0; ix < len; ix++) if (!AllowedPlayerNameChar(name[ix])) return false; // Check if a player is currently using the name, case-insensitively. for (ix = 0; ix < MAXPLAYERS; ix++) { - if (ix != playernum && playeringame[ix] + if (ix != (size_t)playernum && playeringame[ix] && fasticmp(name, player_names[ix])) { // We shouldn't kick people out just because // they joined the game with the same name // as someone else -- modify the name instead. - size_t len = strlen(name); // Recursion! // Slowly strip characters off the end of the @@ -1447,7 +1446,9 @@ UINT8 CanChangeSkin(INT32 playernum) return true; } - if (players[playernum].spectator || players[playernum].playerstate == PST_DEAD || players[playernum].playerstate == PST_REBORN) + if (players[playernum].spectator || + players[playernum].playerstate == PST_DEAD || + players[playernum].playerstate == PST_REBORN) return true; return false; @@ -1481,445 +1482,144 @@ static void ForceAllSkins(INT32 forcedskin) } } -static INT32 snacpending = 0, snac2pending = 0, snac3pending = 0, snac4pending = 0, chmappending = 0; +static INT32 chmappending; +static INT32 snacpending[MAXSPLITSCREENPLAYERS]; + +// wonky compat, idk if anything uses this.... +#define playerisbot (splitplayer == 1 && botingame) // name, color, or skin has changed // -static void SendNameAndColor(void) +static void SendNameAndColor(UINT8 splitplayer) { char buf[MAXPLAYERNAME+2]; char *p; p = buf; + // splitscreen + if (splitscreen < splitplayer && !playerisbot) + return; + + const INT32 pnum = P_GetLocalPlayerNumForNum(splitplayer); + + player_t *player = &players[pnum]; + + // TODO: make those cvars arrays + consvar_t *playercolor, *playername, *playerskin; + consvar_t *colorvars[] = {&cv_playercolor, &cv_playercolor2, &cv_playercolor3, &cv_playercolor4}; + consvar_t *namevars[] = {&cv_playername, &cv_playername2, &cv_playername3, &cv_playername4}; + consvar_t *skinvars[] = {&cv_skin, &cv_skin2, &cv_skin3, &cv_skin4}; + + playercolor = colorvars[splitplayer]; + playername = namevars[splitplayer]; + playerskin = skinvars[splitplayer]; + // normal player colors if (G_GametypeHasTeams()) { - if (players[consoleplayer].ctfteam == 1 && cv_playercolor.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor, skincolor_redteam); - else if (players[consoleplayer].ctfteam == 2 && cv_playercolor.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor, skincolor_blueteam); + if (player->ctfteam == 1 && playercolor->value != skincolor_redteam) + CV_StealthSetValue(playercolor, skincolor_redteam); + else if (player->ctfteam == 2 && playercolor->value != skincolor_blueteam) + CV_StealthSetValue(playercolor, skincolor_blueteam); } // never allow the color "none" - if (!cv_playercolor.value) + if (!playercolor->value) { - if (players[consoleplayer].skincolor) - CV_StealthSetValue(&cv_playercolor, players[consoleplayer].skincolor); - else if (skins[players[consoleplayer].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor, skins[players[consoleplayer].skin].prefcolor); + if (player->skincolor) + CV_StealthSetValue(playercolor, player->skincolor); + else if (skins[player->skin].prefcolor) + CV_StealthSetValue(playercolor, skins[player->skin].prefcolor); else - CV_StealthSet(&cv_playercolor, cv_playercolor.defaultvalue); + CV_StealthSet(playercolor, playercolor->defaultvalue); } - if (fastcmp(cv_playername.string, player_names[consoleplayer]) - && cv_playercolor.value == players[consoleplayer].skincolor - && fastcmp(cv_skin.string, skins[players[consoleplayer].skin].name)) - return; - // We'll handle it later if we're not playing. if (!Playing()) return; + if (fastcmp(playername->string, player_names[pnum]) + && playercolor->value == player->skincolor + && fastcmp(playerskin->string, skins[player->skin].name)) + return; + + if (playerisbot) + { + players[pnum].skincolor = botcolor; + if (players[pnum].mo) + players[pnum].mo->color = players[pnum].skincolor; + SetPlayerSkinByNum(pnum, botskin-1); + return; + } + // If you're not in a netgame, merely update the skin, color, and name. if (!netgame) { INT32 foundskin; - CleanupPlayerName(consoleplayer, cv_playername.zstring); - strcpy(player_names[consoleplayer], cv_playername.zstring); + CleanupPlayerName(pnum, playername->zstring); + strcpy(player_names[pnum], playername->zstring); - players[consoleplayer].skincolor = cv_playercolor.value; + player->skincolor = playercolor->value; - if (players[consoleplayer].mo) - players[consoleplayer].mo->color = players[consoleplayer].skincolor; + if (player->mo) + player->mo->color = player->skincolor; - if ((foundskin = R_SkinAvailable(cv_skin.string)) != -1) + if ((foundskin = R_SkinAvailable(playerskin->string)) != -1) { - cv_skin.value = foundskin; - SetPlayerSkin(consoleplayer, cv_skin.string); - CV_StealthSet(&cv_skin, skins[cv_skin.value].name); + playerskin->value = foundskin; + SetPlayerSkin(pnum, playerskin->string); + CV_StealthSet(playerskin, skins[playerskin->value].name); } else { - cv_skin.value = players[consoleplayer].skin; - CV_StealthSet(&cv_skin, skins[players[consoleplayer].skin].name); + playerskin->value = player->skin; + CV_StealthSet(playerskin, skins[player->skin].name); // will always be same as current - SetPlayerSkin(consoleplayer, cv_skin.string); + SetPlayerSkin(pnum, playerskin->string); } return; } - snacpending++; + snacpending[splitplayer]++; // Don't change name if muted - if (player_name_changes[consoleplayer] >= MAXNAMECHANGES) + if (player_name_changes[pnum] >= MAXNAMECHANGES) { - CV_StealthSet(&cv_playername, player_names[consoleplayer]); + CV_StealthSet(playername, player_names[pnum]); HU_AddChatText("\x85*You must wait to change your name again", false); } - else if (cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) - CV_StealthSet(&cv_playername, player_names[consoleplayer]); + else if (cv_mute.value && !(server || IsPlayerAdmin(pnum))) + CV_StealthSet(playername, player_names[pnum]); else // Cleanup name if changing it - CleanupPlayerName(consoleplayer, cv_playername.zstring); + CleanupPlayerName(pnum, playername->zstring); // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(consoleplayer)) - CV_StealthSet(&cv_skin, skins[players[consoleplayer].skin].name); + if (!CanChangeSkin(pnum)) + CV_StealthSet(playerskin, skins[player->skin].name); // check if player has the skin loaded (cv_skin may have // the name of a skin that was available in the previous game) - cv_skin.value = R_SkinAvailable(cv_skin.string); - if (cv_skin.value < 0) + playerskin->value = R_SkinAvailable(playerskin->string); + if (playerskin->value < 0) { - INT32 skinnum = players[consoleplayer].skin; - CV_StealthSet(&cv_skin, skins[skinnum].name); - cv_skin.value = skinnum; + INT32 skinnum = player->skin; + CV_StealthSet(playerskin, skins[skinnum].name); + playerskin->value = skinnum; } // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor.value); - WRITEUINT8(p, (UINT8)cv_skin.value); - SendNetXCmdForPlayer(0, XD_NAMEANDCOLOR, buf, p - buf); -} - -// splitscreen -static void SendNameAndColor2(void) -{ - INT32 secondplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 1 && !botingame) - return; // can happen if skin2/color2/name2 changed - - if (displayplayers[1] != consoleplayer) - secondplaya = displayplayers[1]; - else if (!netgame) // HACK - secondplaya = 1; - - if (secondplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[secondplaya].ctfteam == 1 && cv_playercolor2.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor2, skincolor_redteam); - else if (players[secondplaya].ctfteam == 2 && cv_playercolor2.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor2, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor2.value) - { - if (players[secondplaya].skincolor) - CV_StealthSetValue(&cv_playercolor2, players[secondplaya].skincolor); - else if (skins[players[secondplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor2, skins[players[secondplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor2, cv_playercolor2.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (botingame) - { - players[secondplaya].skincolor = botcolor; - if (players[secondplaya].mo) - players[secondplaya].mo->color = players[secondplaya].skincolor; - SetPlayerSkinByNum(secondplaya, botskin-1); - return; - } - else if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(secondplaya, cv_playername2.zstring); - strcpy(player_names[secondplaya], cv_playername2.zstring); - - // don't use displayplayers[1]: the second player must be 1 - players[secondplaya].skincolor = cv_playercolor2.value; - if (players[secondplaya].mo) - players[secondplaya].mo->color = players[secondplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin2.string)) != -1) - { - cv_skin2.value = foundskin; - SetPlayerSkin(secondplaya, cv_skin2.string); - } - else - { - cv_skin2.value = players[secondplaya].skin; - CV_StealthSet(&cv_skin2, skins[players[secondplaya].skin].name); - // will always be same as current - SetPlayerSkin(secondplaya, cv_skin2.string); - } - return; - } - - snac2pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[1]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[1]))) - CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[1], cv_playername2.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[1])) - CV_StealthSet(&cv_skin2, skins[players[displayplayers[1]].skin].name); - - // check if player has the skin loaded (cv_skin2 may have - // the name of a skin that was available in the previous game) - cv_skin2.value = R_SkinAvailable(cv_skin2.string); - if (cv_skin2.value < 0) - { - INT32 skinnum = players[displayplayers[1]].skin; - CV_StealthSet(&cv_skin2, skins[skinnum].name); - cv_skin2.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername2.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor2.value); - WRITEUINT8(p, (UINT8)cv_skin2.value); - SendNetXCmdForPlayer(1, XD_NAMEANDCOLOR, buf, p - buf); -} - -static void SendNameAndColor3(void) -{ - INT32 thirdplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 2) - return; // can happen if skin3/color3/name3 changed - - if (displayplayers[2] != consoleplayer) - thirdplaya = displayplayers[2]; - else if (!netgame) // HACK - thirdplaya = 2; - - if (thirdplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[thirdplaya].ctfteam == 1 && cv_playercolor3.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor3, skincolor_redteam); - else if (players[thirdplaya].ctfteam == 2 && cv_playercolor3.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor3, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor3.value) - { - if (players[thirdplaya].skincolor) - CV_StealthSetValue(&cv_playercolor3, players[thirdplaya].skincolor); - else if (skins[players[thirdplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor3, skins[players[thirdplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor3, cv_playercolor3.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(thirdplaya, cv_playername3.zstring); - strcpy(player_names[thirdplaya], cv_playername3.zstring); - - // don't use displayplayers[2]: the third player must be 2 - players[thirdplaya].skincolor = cv_playercolor3.value; - if (players[thirdplaya].mo) - players[thirdplaya].mo->color = players[thirdplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin3.string)) != -1) - { - cv_skin3.value = foundskin; - SetPlayerSkin(thirdplaya, cv_skin3.string); - } - else - { - cv_skin3.value = players[thirdplaya].skin; - CV_StealthSet(&cv_skin3, skins[players[thirdplaya].skin].name); - // will always be same as current - SetPlayerSkin(thirdplaya, cv_skin3.string); - } - return; - } - - snac3pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[2]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[2]))) - CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[2], cv_playername3.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[2])) - CV_StealthSet(&cv_skin3, skins[players[displayplayers[2]].skin].name); - - // check if player has the skin loaded (cv_skin3 may have - // the name of a skin that was available in the previous game) - cv_skin3.value = R_SkinAvailable(cv_skin3.string); - if (cv_skin3.value < 0) - { - INT32 skinnum = players[displayplayers[2]].skin; - CV_StealthSet(&cv_skin3, skins[skinnum].name); - cv_skin3.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername3.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor3.value); - WRITEUINT8(p, (UINT8)cv_skin3.value); - SendNetXCmdForPlayer(2, XD_NAMEANDCOLOR, buf, p - buf); -} - -static void SendNameAndColor4(void) -{ - INT32 fourthplaya = -1; - char buf[MAXPLAYERNAME+2]; - char *p; - - if (splitscreen < 3) - return; // can happen if skin4/color4/name4 changed - - if (displayplayers[3] != consoleplayer) - fourthplaya = displayplayers[3]; - else if (!netgame) // HACK - fourthplaya = 3; - - if (fourthplaya == -1) - return; - - p = buf; - - // normal player colors - if (G_GametypeHasTeams()) - { - if (players[fourthplaya].ctfteam == 1 && cv_playercolor4.value != skincolor_redteam) - CV_StealthSetValue(&cv_playercolor4, skincolor_redteam); - else if (players[fourthplaya].ctfteam == 2 && cv_playercolor4.value != skincolor_blueteam) - CV_StealthSetValue(&cv_playercolor4, skincolor_blueteam); - } - - // never allow the color "none" - if (!cv_playercolor4.value) - { - if (players[fourthplaya].skincolor) - CV_StealthSetValue(&cv_playercolor4, players[fourthplaya].skincolor); - else if (skins[players[fourthplaya].skin].prefcolor) - CV_StealthSetValue(&cv_playercolor4, skins[players[fourthplaya].skin].prefcolor); - else - CV_StealthSet(&cv_playercolor4, cv_playercolor4.defaultvalue); - } - - // We'll handle it later if we're not playing. - if (!Playing()) - return; - - // If you're not in a netgame, merely update the skin, color, and name. - if (botingame) - { - players[fourthplaya].skincolor = botcolor; - if (players[fourthplaya].mo) - players[fourthplaya].mo->color = players[fourthplaya].skincolor; - SetPlayerSkinByNum(fourthplaya, botskin-1); - return; - } - else if (!netgame) - { - INT32 foundskin; - - CleanupPlayerName(fourthplaya, cv_playername4.zstring); - strcpy(player_names[fourthplaya], cv_playername4.zstring); - - // don't use displayplayers[3]: the second player must be 4 - players[fourthplaya].skincolor = cv_playercolor4.value; - if (players[fourthplaya].mo) - players[fourthplaya].mo->color = players[fourthplaya].skincolor; - - if ((foundskin = R_SkinAvailable(cv_skin4.string)) != -1) - { - cv_skin4.value = foundskin; - SetPlayerSkin(fourthplaya, cv_skin4.string); - } - else - { - cv_skin4.value = players[fourthplaya].skin; - CV_StealthSet(&cv_skin4, skins[players[fourthplaya].skin].name); - // will always be same as current - SetPlayerSkin(fourthplaya, cv_skin4.string); - } - return; - } - - snac4pending++; - - // Don't change name if muted - if (player_name_changes[displayplayers[3]] >= MAXNAMECHANGES) - { - CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); - HU_AddChatText("\x85*You must wait to change your name again", false); - } - else if (cv_mute.value && !(server || IsPlayerAdmin(displayplayers[3]))) - CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); - else // Cleanup name if changing it - CleanupPlayerName(displayplayers[3], cv_playername4.zstring); - - // Don't change skin if the server doesn't want you to. - if (!CanChangeSkin(displayplayers[3])) - CV_StealthSet(&cv_skin4, skins[players[displayplayers[3]].skin].name); - - // check if player has the skin loaded (cv_skin4 may have - // the name of a skin that was available in the previous game) - cv_skin4.value = R_SkinAvailable(cv_skin4.string); - if (cv_skin4.value < 0) - { - INT32 skinnum = players[displayplayers[3]].skin; - CV_StealthSet(&cv_skin4, skins[skinnum].name); - cv_skin4.value = skinnum; - } - - // Finally write out the complete packet and send it off. - WRITESTRINGN(p, cv_playername4.zstring, MAXPLAYERNAME); - WRITEUINT8(p, (UINT8)cv_playercolor4.value); - WRITEUINT8(p, (UINT8)cv_skin4.value); - SendNetXCmdForPlayer(3, XD_NAMEANDCOLOR, buf, p - buf); + WRITESTRINGN(p, playername->zstring, MAXPLAYERNAME); + WRITEUINT8(p, (UINT8)playercolor->value); + WRITEUINT8(p, (UINT8)playerskin->value); + SendNetXCmdForPlayer(splitplayer, XD_NAMEANDCOLOR, buf, p - buf); } static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) { - player_t *p = &players[playernum]; + player_t *player = &players[playernum]; char name[MAXPLAYERNAME+1]; UINT8 color, skin; @@ -1928,19 +1628,14 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) I_Error("There is no player %d!", playernum); #endif - if (playernum == consoleplayer) - snacpending--; // TODO: make snacpending an array instead of 4 separate vars? - else if (playernum == displayplayers[1]) - snac2pending--; - else if (playernum == displayplayers[2]) - snac3pending--; - else if (playernum == displayplayers[3]) - snac4pending--; - + if (P_IsLocalPlayer(player)) + { + snacpending[playernum]--; #ifdef PARANOIA - if (snacpending < 0 || snac2pending < 0 || snac3pending < 0 || snac4pending < 0) - I_Error("snacpending negative!"); + if (snacpending[playernum] < 0) + I_Error("snacpending negative!"); #endif + } READSTRINGN(*cp, name, MAXPLAYERNAME); color = READUINT8(*cp); @@ -1954,33 +1649,32 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) } // set color - p->skincolor = color % MAXSKINCOLORS; - if (p->mo) - p->mo->color = (UINT8)p->skincolor; + player->skincolor = color % MAXSKINCOLORS; + if (player->mo) + player->mo->color = (UINT8)player->skincolor; demo_extradata[playernum] |= DXD_COLOR; // normal player colors - if (server && (p != &players[consoleplayer] && p != &players[displayplayers[1]] - && p != &players[displayplayers[2]] && p != &players[displayplayers[3]])) + if (server && !P_IsLocalPlayer(player)) { boolean kick = false; // team colors if (G_GametypeHasTeams()) { - if (p->ctfteam == 1 && p->skincolor != skincolor_redteam) + if (player->ctfteam == 1 && player->skincolor != skincolor_redteam) kick = true; - else if (p->ctfteam == 2 && p->skincolor != skincolor_blueteam) + else if (player->ctfteam == 2 && player->skincolor != skincolor_blueteam) kick = true; } // don't allow color "none" - if (!p->skincolor) + if (!player->skincolor) kick = true; if (kick) { - CONS_Alert(CONS_WARNING, M_GetText("Illegal color change received from %s (team: %d), color: %d)\n"), player_names[playernum], p->ctfteam, p->skincolor); + CONS_Alert(CONS_WARNING, M_GetText("Illegal color change received from %s (team: %d), color: %d)\n"), player_names[playernum], player->ctfteam, player->skincolor); SendKick(playernum, KICK_MSG_CON_FAIL); return; } @@ -1992,6 +1686,7 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) const INT32 forcedskin = cv_forceskin.value; SetPlayerSkinByNum(playernum, forcedskin); + // TODO: make cv_skin an array if (playernum == consoleplayer) CV_StealthSet(&cv_skin, skins[forcedskin].name); else if (playernum == displayplayers[1]) @@ -2005,44 +1700,16 @@ static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) SetPlayerSkinByNum(playernum, skin); } -void SendWeaponPref(void) +void SendWeaponPref(UINT8 splitplayer) { UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam[0].value) + + if (cv_flipcam[splitplayer].value) buf[0] |= 1; - SendNetXCmdForPlayer(0, XD_WEAPONPREF, buf, 1); -} -void SendWeaponPref2(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[1].value) - buf[0] |= 1; - SendNetXCmdForPlayer(1, XD_WEAPONPREF, buf, 1); -} - -void SendWeaponPref3(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[2].value) - buf[0] |= 1; - SendNetXCmdForPlayer(2, XD_WEAPONPREF, buf, 1); -} - -void SendWeaponPref4(void) -{ - UINT8 buf[1]; - - buf[0] = 0; - if (cv_flipcam[3].value) - buf[0] |= 1; - SendNetXCmdForPlayer(3, XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(splitplayer, XD_WEAPONPREF, buf, 1); } static void Got_WeaponPref(const UINT8 **cp, INT32 playernum) @@ -2058,23 +1725,10 @@ static void Got_WeaponPref(const UINT8 **cp, INT32 playernum) player->pflags |= PF_ANALOGMODE; } -void D_SendPlayerConfig(void) +void D_SendPlayerConfig(UINT8 splitplayer) { - SendNameAndColor(); - if (splitscreen || botingame) - SendNameAndColor2(); - if (splitscreen > 1) - SendNameAndColor3(); - if (splitscreen > 2) - SendNameAndColor4(); - - SendWeaponPref(); - if (splitscreen) - SendWeaponPref2(); - if (splitscreen > 1) - SendWeaponPref3(); - if (splitscreen > 2) - SendWeaponPref4(); + SendNameAndColor(splitplayer); + SendWeaponPref(splitplayer); } // Only works for displayplayer, sorry! @@ -2097,10 +1751,12 @@ INT32 D_LookupPlayer(const char *s) return playernum; } + const size_t len = strlen(s); + for (playernum = 0; playernum < MAXPLAYERS; ++playernum) { /* Match name case-insensitively: fully, or partially the start. */ - if (playeringame[playernum] && (strnicmp(player_names[playernum], s, strlen(s)) == 0)) + if (playeringame[playernum] && (strnicmp(player_names[playernum], s, len) == 0)) { return playernum; } @@ -2140,13 +1796,15 @@ static void GetViewablePlayerPlaceRange(INT32 *first, INT32 *last) (*last) = 0; for (i = 0; i < MAXPLAYERS; ++i) - if (G_CouldView(i)) { - place = players[i].kartstuff[k_position]; - if (place < (*first)) - (*first) = place; - if (place > (*last)) - (*last) = place; + if (G_CouldView(i)) + { + place = players[i].kartstuff[k_position]; + if (place < (*first)) + (*first) = place; + if (place > (*last)) + (*last) = place; + } } } @@ -2480,7 +2138,7 @@ void D_MapChange(INT32 mapnum, INT32 newgametype, boolean pencoremode, boolean r displayplayers[1] = 1; playeringame[1] = true; players[1].bot = 1; - SendNameAndColor2(); + SendNameAndColor(1); } } @@ -5735,50 +5393,54 @@ static void ForceSkin_OnChange(void) } } -//Allows the player's name to be changed if cv_mute is off. +// Allows the player's name to be changed if cv_mute is off. static void Name_OnChange(void) { if (cv_mute.value && !(server || IsPlayerAdmin(consoleplayer))) { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername, player_names[consoleplayer]); + return; } - else - SendNameAndColor(); + + SendNameAndColor(0); } static void Name2_OnChange(void) { - if (cv_mute.value) //Secondary player can't be admin. + if (cv_mute.value) // Secondary player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername2, player_names[displayplayers[1]]); + return; } - else - SendNameAndColor2(); + + SendNameAndColor(1); } static void Name3_OnChange(void) { - if (cv_mute.value) //Third player can't be admin. + if (cv_mute.value) // Third player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername3, player_names[displayplayers[2]]); + return; } - else - SendNameAndColor3(); + + SendNameAndColor(2); } static void Name4_OnChange(void) { - if (cv_mute.value) //Secondary player can't be admin. + if (cv_mute.value) // Secondary player can't be admin. { CONS_Alert(CONS_NOTICE, M_GetText("You may not change your name when chat is muted.\n")); CV_StealthSet(&cv_playername4, player_names[displayplayers[3]]); + return; } - else - SendNameAndColor4(); + + SendNameAndColor(3); } /** Sends a skin change for the console player, unless that player is moving. @@ -5800,7 +5462,7 @@ static void Skin_OnChange(void) } if (CanChangeSkin(consoleplayer) && !P_PlayerMoving(consoleplayer)) - SendNameAndColor(); + SendNameAndColor(0); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5821,7 +5483,7 @@ static void Skin2_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[1]) && !P_PlayerMoving(displayplayers[1])) - SendNameAndColor2(); + SendNameAndColor(1); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5837,7 +5499,7 @@ static void Skin3_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[2]) && !P_PlayerMoving(displayplayers[2])) - SendNameAndColor3(); + SendNameAndColor(2); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5853,7 +5515,7 @@ static void Skin4_OnChange(void) return; // do whatever you want if (CanChangeSkin(displayplayers[3]) && !P_PlayerMoving(displayplayers[3])) - SendNameAndColor4(); + SendNameAndColor(3); else { CONS_Alert(CONS_NOTICE, M_GetText("You can't change your skin at the moment.\n")); @@ -5966,7 +5628,7 @@ static void Color_OnChange(void) if (!P_PlayerMoving(consoleplayer)) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor(); + SendNameAndColor(0); } else { @@ -5988,7 +5650,7 @@ static void Color2_OnChange(void) if (!P_PlayerMoving(displayplayers[1])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor2(); + SendNameAndColor(1); } else { @@ -6005,7 +5667,7 @@ static void Color3_OnChange(void) if (!P_PlayerMoving(displayplayers[2])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor3(); + SendNameAndColor(2); } else { @@ -6022,7 +5684,7 @@ static void Color4_OnChange(void) if (!P_PlayerMoving(displayplayers[3])) { // Color change menu scrolling fix is no longer necessary - SendNameAndColor4(); + SendNameAndColor(3); } else { diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 6b7382403..f22fe33a8 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -21,10 +21,7 @@ extern "C" { #include "command.h" -void SendWeaponPref(void); -void SendWeaponPref2(void); -void SendWeaponPref3(void); -void SendWeaponPref4(void); +void SendWeaponPref(UINT8 splitplayer); // console vars extern consvar_t cv_playername; @@ -295,7 +292,7 @@ typedef union { // add game commands, needs cleanup void D_RegisterServerCommands(void); void D_RegisterClientCommands(void); -void D_SendPlayerConfig(void); +void D_SendPlayerConfig(UINT8 splitplayer); void Command_ExitGame_f(void); void Command_Retry_f(void); void D_GameTypeChanged(INT32 lastgametype); // not a real _OnChange function anymore diff --git a/src/r_main.cpp b/src/r_main.cpp index 1ad8e8be9..fe9edc9eb 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -277,22 +277,22 @@ static void Fov_OnChange(void) static void FlipCam_OnChange(void) { - SendWeaponPref(); + SendWeaponPref(0); } static void FlipCam2_OnChange(void) { - SendWeaponPref2(); + SendWeaponPref(1); } static void FlipCam3_OnChange(void) { - SendWeaponPref3(); + SendWeaponPref(2); } static void FlipCam4_OnChange(void) { - SendWeaponPref4(); + SendWeaponPref(3); } static void Precipstuff_OnChange(void) From c680dd3222667b4f948d0c01a05925e65b63f63a Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 20:24:39 +0100 Subject: [PATCH 03/42] fix some packet types not being correctly handled --- src/d_clisrv.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index ccb8d092b..f622b4802 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -5994,6 +5994,9 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENTQUIT: PT_ClientQuit(netconsole, node); break; + case PT_SERVERINFO: + PT_ServerInfo(node); + break; case PT_RESYNCHGET: SV_AcknowledgeResynchAck(node, netbuffer->u.resynchgot); break; @@ -6024,6 +6027,12 @@ static void HandlePacketFromPlayer(SINT8 node) is_client_saturn[node] = true; break; #endif + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; + case PT_SERVERSHUTDOWN: + PT_ServerShutdown(node); + break; case PT_RESYNCHING: PT_Resynching(node); break; From e83e2659a7567cf219c4d9ff0b86b3e31a470402 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 21:50:44 +0100 Subject: [PATCH 04/42] reorder packets again --- src/d_clisrv.c | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index f622b4802..5d1566f47 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4804,7 +4804,6 @@ static void PT_ClientJoin(SINT8 node) } } - #ifdef SATURNJOIN const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && netbuffer->u.clientcfg.issaturn == ISSATURN); // Check the packet lenght to skip potential garbo data! #endif @@ -5425,19 +5424,17 @@ static void HandlePacketFromAwayNode(SINT8 node) case PT_NEEDMAPICON: PT_NeedMapIcon(node); break; - case PT_CLIENTJOIN: - PT_ClientJoin(node); - break; case PT_SERVERSHUTDOWN: PT_ServerShutdown(node); break; - + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; case PT_SERVERTICS: // Do not remove my own server (we have just get a out of order packet) if (node == servernode) break; /* FALLTHRU */ - default: DEBFILE(va("unknown packet received (%d) from unknown host\n", netbuffer->packettype)); Net_CloseConnection(node); @@ -5994,6 +5991,14 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENTQUIT: PT_ClientQuit(netconsole, node); break; +#ifdef SATURNPAK + case PT_CANRECEIVEGAMESTATE: + PT_CanReceiveGamestate(node); + break; + case PT_RECEIVEDGAMESTATE: + PT_ReceivedGamestate(node); + break; +#endif case PT_SERVERINFO: PT_ServerInfo(node); break; @@ -6007,18 +6012,11 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_PING: PT_Ping(node); break; - case PT_SERVERCFG: - break; + case PT_FILEFRAGMENT: PT_FileFragmentFromPlayer(node); break; #ifdef SATURNPAK - case PT_CANRECEIVEGAMESTATE: - PT_CanReceiveGamestate(node); - break; - case PT_RECEIVEDGAMESTATE: - PT_ReceivedGamestate(node); - break; case PT_WILLRESENDGAMESTATE: PT_WillResendGamestate(); break; @@ -6027,12 +6025,14 @@ static void HandlePacketFromPlayer(SINT8 node) is_client_saturn[node] = true; break; #endif - case PT_CLIENTJOIN: - PT_ClientJoin(node); - break; case PT_SERVERSHUTDOWN: PT_ServerShutdown(node); break; + case PT_SERVERCFG: + break; + case PT_CLIENTJOIN: + PT_ClientJoin(node); + break; case PT_RESYNCHING: PT_Resynching(node); break; From 265f4a50ef6eb414572d16096cf50c1f837b6a7f Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 22:04:18 +0100 Subject: [PATCH 05/42] readd check for node before SV_SendSaveGame Apparently in some cases the server will connect to itself, in this case the server tries to send itself the savegame, leading to a crash in some cases. oops --- src/d_clisrv.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 5d1566f47..a7745242d 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4781,7 +4781,7 @@ static size_t TotalTextCmdPerTic(tic_t tic) static void PT_ClientJoin(SINT8 node) { // Ignore duplicate packets - if (client || nodeingame[node]|| levelloading) + if (client || nodeingame[node] || levelloading) return; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -4917,8 +4917,11 @@ static void PT_ClientJoin(SINT8 node) if (nodewaiting[node]) { - SV_SendSaveGame(node, false); // send a complete game state - DEBFILE("send savegame\n"); + if (node) + { + SV_SendSaveGame(node, false); // send a complete game state + DEBFILE("send savegame\n"); + } SV_AddWaitingPlayers(node); } From f49e57a38c29e845e62032528a1e01a08ea1988f Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 23:16:35 +0100 Subject: [PATCH 06/42] d_cliserv: Cleanup PT_ClientJoin move refuse message handling into its own function --- src/d_clisrv.c | 168 +++++++++++++++++++++++++++---------------------- 1 file changed, 92 insertions(+), 76 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index a7745242d..653dae05e 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4746,17 +4746,6 @@ void SV_StartSinglePlayerServer(void) multiplayer = true; } -static void SV_SendRefuse(INT32 node, const char *reason) -{ - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - - strcpy(netbuffer->u.serverrefuse.reason, reason); - - netbuffer->packettype = PT_SERVERREFUSE; - HSendPacket(node, false, 0, strlen(netbuffer->u.serverrefuse.reason) + 1); - Net_CloseConnection(node); -} - // used at txtcmds received to check packetsize bound static size_t TotalTextCmdPerTic(tic_t tic) { @@ -4773,19 +4762,25 @@ static size_t TotalTextCmdPerTic(tic_t tic) return total; } -/** Called when a PT_CLIENTJOIN packet is received - * - * \param node The packet sender - * - */ -static void PT_ClientJoin(SINT8 node) +static void SV_SendRefuse(INT32 node, const char *reason) { - // Ignore duplicate packets - if (client || nodeingame[node] || levelloading) - return; - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + strcpy(netbuffer->u.serverrefuse.reason, reason); + + netbuffer->packettype = PT_SERVERREFUSE; + HSendPacket(node, false, 0, strlen(netbuffer->u.serverrefuse.reason) + 1); + Net_CloseConnection(node); +} + +static const char *GetRefuseMessage(SINT8 node) +{ + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + clientconfig_pak *cc = &netbuffer->u.clientcfg; + + if (!node) /* server connecting to itself */ + return NULL; + // Sal: Dedicated mode is INCREDIBLY hacked together. // If a server filled out, then it'd overwrite the host and turn everyone into weird husks..... // It's too much effort to legimately fix right now. Just prevent it from reaching that state. @@ -4805,7 +4800,7 @@ static void PT_ClientJoin(SINT8 node) } #ifdef SATURNJOIN - const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && netbuffer->u.clientcfg.issaturn == ISSATURN); // Check the packet lenght to skip potential garbo data! + const boolean issaturn = (((doomcom->datalength) == sizeof(clientconfig_pak)) && (cc->issaturn == ISSATURN)); // Check the packet length to skip garbo data! #endif if (bannednode && bannednode[node].banid != SIZE_MAX) @@ -4818,47 +4813,44 @@ static void PT_ClientJoin(SINT8 node) if (bannednode[node].timeleft != NO_BAN_TIME) { - // these are fudged a little to allow it to sink in for impatient rejoiners + // these are fudged a little to allow it to sink in for impatient rejoiners int minutes = (bannednode[node].timeleft + 30) / 60; int hours = (minutes + 1) / 60; int days = (hours + 1) / 24; if (days) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d day%s)", reason, days, days > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d day%s)", reason, days, days > 1 ? "s" : ""); } else if (hours) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d hour%s)", reason, hours, hours > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d hour%s)", reason, hours, hours > 1 ? "s" : ""); } else if (minutes) { - SV_SendRefuse(node, va("K|%s\n(Time remaining: %d minute%s)", reason, minutes, minutes > 1 ? "s" : "")); + return va("K|%s\n(Time remaining: %d minute%s)", reason, minutes, minutes > 1 ? "s" : ""); } else { - SV_SendRefuse(node, va("K|%s\n(Time remaining: <1 minute)", reason)); + return va("K|%s\n(Time remaining: <1 minute)", reason); } } else { - SV_SendRefuse(node, va("B|%s", reason)); + return va("B|%s", reason); } } - else if (netbuffer->u.clientcfg._255 != 255 || - netbuffer->u.clientcfg.packetversion != PACKETVERSION) + else if (cc->_255 != 255 || cc->packetversion != PACKETVERSION) { - SV_SendRefuse(node, "Incompatible packet formats."); + return "Incompatible packet formats."; } - else if (strncmp(netbuffer->u.clientcfg.application, SRB2APPLICATION, - sizeof netbuffer->u.clientcfg.application)) + else if (strncmp(cc->application, SRB2APPLICATION, sizeof(cc->application))) { - SV_SendRefuse(node, "Different SRB2Kart modifications\nare not compatible."); + return "Different SRB2Kart modifications\nare not compatible."; } - else if (netbuffer->u.clientcfg.version != VERSION - || netbuffer->u.clientcfg.subversion != SUBVERSION) + else if (cc->version != VERSION || cc->subversion != SUBVERSION) { - SV_SendRefuse(node, va("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)", VERSION, SUBVERSION)); + return va("Different SRB2Kart versions cannot\nplay a netgame!\n(server version %d.%d)", VERSION, SUBVERSION); } #ifdef SATURNJOIN else if (((!cv_allownewplayer.value && !issaturn) || (!cv_allownewsaturnplayer.value && issaturn)) && node) @@ -4866,65 +4858,89 @@ static void PT_ClientJoin(SINT8 node) else if (!cv_allownewplayer.value && node) #endif { - SV_SendRefuse(node, cv_joinrefusemessage.string); + return cv_joinrefusemessage.string; } else if (connectedplayers >= maxplayers) { - SV_SendRefuse(node, va("Maximum players reached: %d", maxplayers)); + return va("Maximum players reached: %d", maxplayers); } - else if (netgame && netbuffer->u.clientcfg.localplayers > 4) // Hacked client? + else if (cc->localplayers != 1) { - SV_SendRefuse(node, "Too many players from\nthis node."); + return "Wrong player count."; } - else if (netgame && connectedplayers + netbuffer->u.clientcfg.localplayers > maxplayers) + else if (netgame && !cc->localplayers) // Stealth join? { - SV_SendRefuse(node, va("Number of local players\nwould exceed maximum: %d", maxplayers)); + return "No players from\nthis node."; } - else if (netgame && !netbuffer->u.clientcfg.localplayers) // Stealth join? + else if (netgame && cc->localplayers > 4) // Hacked client? { - SV_SendRefuse(node, "No players from\nthis node."); + return "Too many players from\nthis node."; } - else + else if (netgame && connectedplayers + cc->localplayers > maxplayers) { - // client authorised to join - nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); + return va("Number of local players\nwould exceed maximum: %d", maxplayers); + } - gamestate_t backupstate = gamestate; + return NULL; +} - SV_AddNode(node); +/** Called when a PT_CLIENTJOIN packet is received + * + * \param node The packet sender + * + */ +static void PT_ClientJoin(SINT8 node) +{ + // Ignore duplicate packets + if (client || nodeingame[node] || levelloading) + return; - /// \note Wait what??? - /// What if the gamestate takes more than one second to get downloaded? - /// Or if a lagspike happens? - // you get a free second before desynch checks. use it wisely. - SV_InitResynchVars(node); + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - if (!SV_SendServerConfig(node)) - { - G_SetGamestate(backupstate); - /// \note Shouldn't SV_SendRefuse be called before ResetNode? - SV_SendRefuse(node, "Server couldn't send info, please try again"); - ResetNode(node); // Yeah, lets try it! - /// \todo fix this !!! - return; // restart the while - } + const char *refuse = GetRefuseMessage(node); - SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea - //if (gamestate != GS_LEVEL) // GS_INTERMISSION, etc? - // SV_SendPlayerConfigs(node); // send bare minimum player info + if (refuse) + { + SV_SendRefuse(node, refuse); + return; + } + + // client authorised to join + nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); + + gamestate_t backupstate = gamestate; + + SV_AddNode(node); + + /// \note Wait what??? + /// What if the gamestate takes more than one second to get downloaded? + /// Or if a lagspike happens? + // you get a free second before desynch checks. use it wisely. + SV_InitResynchVars(node); + + if (!SV_SendServerConfig(node)) + { G_SetGamestate(backupstate); - DEBFILE("new node joined\n"); + /// \note Shouldn't SV_SendRefuse be called before ResetNode? + SV_SendRefuse(node, "Server couldn't send info, please try again"); + ResetNode(node); // Yeah, lets try it! + /// \todo fix this !!! + return; // restart the while + } - if (nodewaiting[node]) + SV_SendServerInfo(node, 0); // Dunno if 0 time is good idea + G_SetGamestate(backupstate); + DEBFILE("new node joined\n"); + + if (nodewaiting[node]) + { + if (node) { - if (node) - { - SV_SendSaveGame(node, false); // send a complete game state - DEBFILE("send savegame\n"); - } - - SV_AddWaitingPlayers(node); + SV_SendSaveGame(node, false); // send a complete game state + DEBFILE("send savegame\n"); } + + SV_AddWaitingPlayers(node); } } From 7eb2ad1e35669293a4a35afd493bcfd967f97032 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 2 Dec 2025 23:20:17 +0100 Subject: [PATCH 07/42] slightly cleanup SV_AddWaitingPlayers --- src/d_clisrv.c | 52 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 653dae05e..1117112cb 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4445,18 +4445,21 @@ static inline void SV_AddNode(INT32 node) // Xcmd XD_ADDPLAYER static void Got_AddPlayer(const UINT8 **p, INT32 playernum) { + UINT8 i; INT16 node, newplayernum; UINT8 splitscreenplayer = 0; - UINT8 i; + player_t *newplayer; if (playernum != serverplayer && !IsPlayerAdmin(playernum)) { // protect against hacked/buggy client CONS_Alert(CONS_WARNING, M_GetText("Illegal add player command received from %s\n"), player_names[playernum]); + if (server) { SendKick(playernum, KICK_MSG_CON_FAIL); } + return; } @@ -4465,14 +4468,19 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) splitscreenplayer = newplayernum/MAXPLAYERS; newplayernum %= MAXPLAYERS; + CONS_Debug(DBG_NETPLAY, "addplayer: %d %d\n", node, newplayernum); + // Clear player before joining, lest some things get set incorrectly CL_ClearPlayer(newplayernum); playeringame[newplayernum] = true; G_AddPlayer(newplayernum); + if (newplayernum+1 > doomcom->numslots) doomcom->numslots = (INT16)(newplayernum+1); + newplayer = &players[newplayernum]; + // the server is creating my player if (node == mynode) { @@ -4483,7 +4491,7 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) displayplayers[splitscreenplayer] = newplayernum; DEBFILE(va("spawning one of my sister number %d\n", splitscreenplayer)); if (splitscreenplayer == 1 && botingame) - players[newplayernum].bot = 1; + newplayer->bot = 1; // do we really want this löl } else { @@ -4493,13 +4501,13 @@ static void Got_AddPlayer(const UINT8 **p, INT32 playernum) DEBFILE("spawning me\n"); } - P_ForceLocalAngle(&players[newplayernum], (angle_t)(players[newplayernum].cmd.angleturn << TICCMD_REDUCE)); + P_ForceLocalAngle(newplayer, (angle_t)(newplayer->cmd.angleturn << TICCMD_REDUCE)); D_SendPlayerConfig(splitscreenplayer); addedtogame = true; } - players[newplayernum].splitscreenindex = splitscreenplayer; + newplayer->splitscreenindex = splitscreenplayer; if (netgame) { @@ -4570,24 +4578,27 @@ static boolean SV_AddWaitingPlayers(SINT8 node) UINT8 newplayernum = 0; boolean newplayer = false; - // What is the reason for this? Why can't newplayernum always be 0? - // Sal: Because the dedicated player is stupidly forced into players[0]..... - if (dedicated) - newplayernum = 1; - // splitscreen can allow 2+ players in one node for (; nodewaiting[node] > 0; nodewaiting[node]--) { newplayer = true; // search for a free playernum - // we can't use playeringame since it is not updated here - for (; newplayernum < MAXPLAYERS; newplayernum++) + // we can't solely use playeringame since it is not updated here + for (newplayernum = dedicated ? 1 : 0; newplayernum < MAXPLAYERS; newplayernum++) { + if (playeringame[newplayernum]) + continue; + for (n = 0; n < MAXNETNODES; n++) - if (nodetoplayer[n] == newplayernum || nodetoplayer2[n] == newplayernum - || nodetoplayer3[n] == newplayernum || nodetoplayer4[n] == newplayernum) + { + if (nodetoplayer[n] == newplayernum || + nodetoplayer2[n] == newplayernum || + nodetoplayer3[n] == newplayernum || + nodetoplayer4[n] == newplayernum) break; + } + if (n == MAXNETNODES) break; } @@ -4596,10 +4607,9 @@ static boolean SV_AddWaitingPlayers(SINT8 node) // before accepting the join I_Assert(newplayernum < MAXPLAYERS); - playernode[newplayernum] = (UINT8)node; - buf[0] = (UINT8)node; buf[1] = newplayernum; + if (playerpernode[node] < 1) { nodetoplayer[node] = newplayernum; @@ -4614,11 +4624,21 @@ static boolean SV_AddWaitingPlayers(SINT8 node) nodetoplayer3[node] = newplayernum; buf[1] += MAXPLAYERS*2; } - else + else if (playerpernode[node] < 4) { nodetoplayer4[node] = newplayernum; buf[1] += MAXPLAYERS*3; } + else + { + // I don't know if it's safe to assert here, + // but I do know this should not be allowed + // to be reached. + return newplayer; + } + + playernode[newplayernum] = (UINT8)node; + playerpernode[node]++; SendNetXCmd(XD_ADDPLAYER, &buf, 2); From 3996abef3638dfb09c86021254a876bd7133b32e Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 4 Dec 2025 18:55:05 +0100 Subject: [PATCH 08/42] convert w_wad to ceepeepee prep for smth i might try --- src/Sourcefile | 2 +- src/console.h | 8 ++ src/dehacked.h | 9 ++ src/lzf.h | 8 ++ src/md5.h | 8 ++ src/{w_wad.c => w_wad.cpp} | 190 +++++++++++++++++++------------------ src/w_wad.h | 2 +- 7 files changed, 134 insertions(+), 93 deletions(-) rename src/{w_wad.c => w_wad.cpp} (90%) diff --git a/src/Sourcefile b/src/Sourcefile index 761806e6b..cd5a44c86 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -45,7 +45,7 @@ st_stuff.c string.c tables.c v_video.c -w_wad.c +w_wad.cpp y_inter.c z_zone.cpp r_bsp.cpp diff --git a/src/console.h b/src/console.h index a16ef47b6..3292bc6e3 100644 --- a/src/console.h +++ b/src/console.h @@ -13,6 +13,10 @@ #ifndef __CONSOLE__ #define __CONSOLE__ +#ifdef __cplusplus +extern "C" { +#endif + #include "d_event.h" #include "command.h" #include "i_threads.h" @@ -63,4 +67,8 @@ boolean CON_Ready(void); void CON_LogMessage(const char *msg); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/dehacked.h b/src/dehacked.h index eb22c5f6a..0db20ee56 100644 --- a/src/dehacked.h +++ b/src/dehacked.h @@ -13,6 +13,10 @@ #ifndef __DEHACKED_H__ #define __DEHACKED_H__ +#ifdef __cplusplus +extern "C" { +#endif + #include "m_fixed.h" // for get_number #include "info.h" @@ -71,4 +75,9 @@ typedef struct } MYFILE; #define myfeof(a) (a->data + a->size <= a->curpos) char *myfgets(char *buf, size_t bufsize, MYFILE *f); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/lzf.h b/src/lzf.h index 85daf255e..995e4ebd6 100644 --- a/src/lzf.h +++ b/src/lzf.h @@ -13,6 +13,10 @@ #define LZF_H #include +#ifdef __cplusplus +extern "C" { +#endif + /*********************************************************************** ** ** lzf -- an extremely fast/free compression/decompression-method @@ -71,5 +75,9 @@ size_t lzf_decompress (const void *const in_data, size_t in_len, void *out_data, size_t out_len); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/md5.h b/src/md5.h index f09d865ab..85384c479 100644 --- a/src/md5.h +++ b/src/md5.h @@ -16,6 +16,10 @@ #ifndef _MD5_H #define _MD5_H 1 +#ifdef __cplusplus +extern "C" { +#endif + #include #if defined (HAVE_LIMITS_H) || (defined (_LIBC) && _LIBC) || defined (_WIN32) @@ -52,4 +56,8 @@ int md5_stream(FILE *stream, void *resblock) THROWFUNC; digest. */ extern void *md5_buffer(const char *buffer, size_t len, void *resblock) THROWFUNC; +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* md5.h */ diff --git a/src/w_wad.c b/src/w_wad.cpp similarity index 90% rename from src/w_wad.c rename to src/w_wad.cpp index 640ee0367..114e5c77c 100644 --- a/src/w_wad.c +++ b/src/w_wad.cpp @@ -257,7 +257,7 @@ static inline void W_LoadDehackedLumpsPK3(UINT16 wadnum) lumpinfo_t *lump_p = &wadfiles[wadnum]->lumpinfo[posStart]; size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = malloc(length + 1); + char *name = static_cast(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumpsPK3: Out of memory!\n"); @@ -293,7 +293,7 @@ static inline void W_LoadDehackedLumps(UINT16 wadnum) if (memcmp(lump_p->name, "SOC_", 4) == 0) // Check for generic SOC lump { // shameless copy+paste of code from LUA_LoadLump size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = malloc(length + 1); + char *name = static_cast(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumps: Out of memory!\n"); @@ -389,24 +389,24 @@ static restype_t ResourceFileDetect(const char* filename) */ static lumpinfo_t* ResGetLumpsStandalone(FILE* handle, UINT16* numlumps, const char* lumpname) { - lumpinfo_t* lumpinfo = Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL); + lumpinfo_t* lumpinfo = static_cast(Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL)); lumpinfo->position = 0; fseek(handle, 0, SEEK_END); - lumpinfo->size = ftell(handle); + lumpinfo->size = static_cast(ftell(handle)); fseek(handle, 0, SEEK_SET); strlcpy(lumpinfo->name, lumpname, sizeof(lumpinfo->name)); lumpinfo->namelength = strlen(lumpinfo->name); lumpinfo->hash.name = W_HashLumpName(lumpname); // Allocate the lump's long name. - lumpinfo->longname = Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL); + lumpinfo->longname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->longname, lumpname); lumpinfo->longname[lumpinfo->namelength] = '\0'; lumpinfo->longnamelength = lumpinfo->namelength; lumpinfo->hash.longname = lumpinfo->hash.name; // Allocate the lump's full name. - lumpinfo->fullname = Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL); + lumpinfo->fullname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->fullname, lumpname); lumpinfo->fullname[lumpinfo->namelength] = '\0'; lumpinfo->fullnamelength = lumpinfo->namelength; @@ -454,7 +454,7 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena // read wad file directory i = header.numlumps * sizeof (*fileinfo); - fileinfov = fileinfo = malloc(i); + fileinfov = fileinfo = static_cast(malloc(i)); if (fseek(handle, header.infotableofs, SEEK_SET) == -1 || fread(fileinfo, 1, i, handle) < i) @@ -466,7 +466,7 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena numlumps = header.numlumps; // fill in lumpinfo for this wad - lump_p = lumpinfo = Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL); + lump_p = lumpinfo = static_cast(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); for (i = 0; i < numlumps; i++, lump_p++, fileinfo++) { @@ -510,14 +510,14 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena lump_p->hash.name = W_HashLumpName(lump_p->name); // Allocate the lump's long name. - lump_p->longname = Z_Malloc(9 * sizeof(char), PU_STATIC, NULL); + lump_p->longname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->longname, fileinfo->name, 8); lump_p->longname[8] = '\0'; lump_p->longnamelength = lump_p->namelength; lump_p->hash.longname = lump_p->hash.name; // Allocate the lump's full name. - lump_p->fullname = Z_Malloc(9 * sizeof(char), PU_STATIC, NULL); + lump_p->fullname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->fullname, fileinfo->name, 8); lump_p->fullname[8] = '\0'; lump_p->fullnamelength = lump_p->namelength; @@ -538,24 +538,24 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp int c; fseek(handle, 0, SEEK_END); - size_t len = ftell(handle); + size_t len = static_cast(ftell(handle)); fseek(handle, startpos, SEEK_SET); - size_t remaining = len - startpos; - size_t chunkpos = startpos; + size_t remaining = static_cast(len - startpos); + size_t chunkpos = static_cast(startpos); s = endPat; //128k buffers - size_t buffer_size = min(128 * 1024 * sizeof(char), remaining); - CLEANUP(pfree) char* buffer = (char*)(malloc(buffer_size)); + size_t buffer_size = std::min(128 * 1024 * sizeof(char), remaining); + CLEANUP(pfree) char* buffer = static_cast(malloc(buffer_size)); size_t bytes_read = 0; while ((bytes_read = fread(buffer, 1, buffer_size, handle)) > 0) { for (size_t i = 0; i < bytes_read; i++) { - c = (int)buffer[i]; + c = static_cast(buffer[i]); if (*s != c && s > endPat) // No match? s = endPat; // We "reset" the counter by sending the s pointer back to the start of the array. @@ -567,7 +567,7 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp if (*s == 0x00) // The array pointer has reached the key char which marks the end. It means we have matched the signature. { //the original function would leave the FILE* seeked to the end of the match - size_t foundpos = chunkpos + i + 1; + size_t foundpos = static_cast(chunkpos + i + 1); fseek(handle, foundpos, SEEK_SET); return true; } @@ -644,8 +644,8 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) // Contains entry number (number of lumps), and central directory start offset. fseek(handle, 0, SEEK_END); - const long startpos = (ftell(handle) - (22 + 65536)); - if (!ResFindSignature(handle, pat_end, max(0l, startpos))) + const long startpos = ftell(handle) - (22 + 65536); + if (!ResFindSignature(handle, pat_end, std::max(0l, startpos))) { CONS_Alert(CONS_ERROR, "Missing central directory\n"); return NULL; @@ -660,11 +660,11 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) numlumps = SHORT(zend.entries); - lump_p = lumpinfo = Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL); + lump_p = lumpinfo = static_cast(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); fseek(handle, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(Z_Pfree) char *cdir = Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir); + CLEANUP(Z_Pfree) char *cdir = static_cast(Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir)); if (fread(cdir, 1, LONG(zend.cdirsize), handle) < (UINT32)(LONG(zend.cdirsize))) { @@ -677,7 +677,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) for (i = 0; i < numlumps; i++, lump_p++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = reinterpret_cast(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -693,8 +693,8 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->disksize = LONG(zentry->compsize); lump_p->size = LONG(zentry->size); - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + strlcpy(fullname, reinterpret_cast(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. if ((trimname = strrchr(fullname, '/')) != 0) @@ -706,16 +706,16 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lump_p->name, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lump_p->name, trimname, min(8, dotpos - trimname)); + strncpy(lump_p->name, trimname, std::min(8, dotpos - trimname)); lump_p->namelength = strlen(lump_p->name); lump_p->hash.name = W_HashLumpName(lump_p->name); - lump_p->longname = Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL); + lump_p->longname = static_cast(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); strlcpy(lump_p->longname, trimname, dotpos - trimname + 1); lump_p->longnamelength = strlen(lump_p->longname); lump_p->hash.longname = W_HashLumpName(lump_p->longname); - lump_p->fullname = (char*)(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); + lump_p->fullname = static_cast(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); strncpy(lump_p->fullname, fullname, SHORT(zentry->namelen)); lump_p->fullnamelength = zentry->namelen; lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); @@ -893,14 +893,14 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) // // link wad file to search files // - wadfile = Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL); + wadfile = static_cast(Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL)); wadfile->filename = Z_StrDup(filename); wadfile->handle = handle; - wadfile->numlumps = (UINT16)numlumps; + wadfile->numlumps = static_cast(numlumps); wadfile->lumpinfo = lumpinfo; wadfile->important = important; fseek(handle, 0, SEEK_END); - wadfile->filesize = (unsigned)ftell(handle); + wadfile->filesize = static_cast(ftell(handle)); wadfile->type = type; wadfile->startfolders = M_AATreeAlloc(AATREE_STRING); wadfile->endfolders = M_AATreeAlloc(AATREE_STRING); @@ -928,7 +928,7 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) #ifdef HWRENDER // Read shaders from file if (rendermode == render_opengl && (vid.glstate == VID_GL_LIBRARY_LOADED)) - HWR_LoadCustomShadersFromFile(numwadfiles - 1, (type == RET_PK3)); + HWR_LoadCustomShadersFromFile(numwadfiles - 1, static_cast(type == RET_PK3)); #endif // TODO: HACK ALERT - Load Lua & SOC stuff right here. I feel like this should be out of this place, but... Let's stick with this for now. @@ -1028,7 +1028,7 @@ INT32 W_AddAutoloadedLocalFiles(char **filenames) /** Make sure a lump number is valid. * Compiles away to nothing if PARANOIA is not defined. */ -static boolean TestValidLump(UINT16 wad, UINT16 lump) +static inline boolean TestValidLump(UINT16 wad, UINT16 lump) { I_Assert(wad < MAX_WADFILES); if (!wadfiles[wad]) // make sure the wad file exists @@ -1051,7 +1051,7 @@ const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump) const char *W_CheckNameForNum(lumpnum_t lumpnum) { - return W_CheckNameForNumPwad(WADFILENUM(lumpnum),LUMPNUM(lumpnum)); + return W_CheckNameForNumPwad(WADFILENUM(lumpnum), LUMPNUM(lumpnum)); } // @@ -1142,9 +1142,11 @@ UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlump) { UINT16 marker; + marker = W_CheckNumForNamePwad(name, wad, startlump); if (marker != INT16_MAX) marker++; // Do not count the first marker + return marker; } @@ -1152,13 +1154,13 @@ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlu UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlump) { size_t name_length; - INT32 i; + UINT16 i; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; name_length = strlen(name); void *val = M_AATreeGetString(wadfiles[wad]->startfolders, name); if (val != NULL) - return (uintptr_t)val; + return static_cast(reinterpret_cast(val)); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { @@ -1168,12 +1170,12 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum if (strlen(lump_p->fullname) == name_length) i++; - M_AATreeSetString(wadfiles[wad]->startfolders, name, (void *)(uintptr_t)i); + M_AATreeSetString(wadfiles[wad]->startfolders, name, reinterpret_cast(static_cast(i))); return i; } } - M_AATreeSetString(wadfiles[wad]->startfolders, name, (void *)INT16_MAX); + M_AATreeSetString(wadfiles[wad]->startfolders, name, reinterpret_cast(INT16_MAX)); return INT16_MAX; } @@ -1182,13 +1184,13 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum // Returns the position of the lumpinfo entry. UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) { - INT32 i; + UINT16 i; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; size_t name_length = strlen(name); void *val = M_AATreeGetString(wadfiles[wad]->endfolders, name); if (val != NULL) - return (uintptr_t)val; + return static_cast(reinterpret_cast(val)); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { @@ -1196,7 +1198,7 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) break; } - M_AATreeSetString(wadfiles[wad]->endfolders, name, (void *)(uintptr_t)i); + M_AATreeSetString(wadfiles[wad]->endfolders, name, reinterpret_cast(static_cast(i))); return i; } @@ -1204,7 +1206,7 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) // Returns lump position in PK3's lumpinfo, or INT16_MAX if not found. UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) { - INT32 i; + UINT16 i; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; size_t name_length = strlen(name); @@ -1297,7 +1299,7 @@ lumpnum_t W_CheckNumForName(const char *name) // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForNamePwad(name, (UINT16)i, 0); + check = W_CheckNumForNamePwad(name, static_cast(i), 0); if (check != INT16_MAX) break; //found it @@ -1339,7 +1341,7 @@ lumpnum_t W_CheckNumForLongName(const char *name) // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForLongNamePwad(name, (UINT16)i, 0); + check = W_CheckNumForLongNamePwad(name, static_cast(i), 0); if (check != INT16_MAX) break; //found it @@ -1409,25 +1411,27 @@ lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, con { if (wadfiles[i]->type == RET_WAD) { - bsid = W_CheckNumForNamePwad(blockstart, (UINT16)i, 0); + bsid = W_CheckNumForNamePwad(blockstart, static_cast(i), 0); if (bsid == INT16_MAX) continue; // Start block doesn't exist? - beid = W_CheckNumForNamePwad(blockend, (UINT16)i, 0); + beid = W_CheckNumForNamePwad(blockend, static_cast(i), 0); if (beid == INT16_MAX) continue; // End block doesn't exist? - check = W_CheckNumForNamePwad(name, (UINT16)i, bsid); + check = W_CheckNumForNamePwad(name, static_cast(i), bsid); if (check < beid) - return (i<<16)+check; // found it, in our constraints + return (i << 16)+check; // found it, in our constraints } } + return LUMPERROR; } // Used by Lua. Case sensitive lump checking, quickly... UINT8 W_LumpExists(const char *name) { - INT32 i,j; + INT32 i, j; + for (i = numwadfiles - 1; i >= 0; i--) { lumpinfo_t *lump_p = wadfiles[i]->lumpinfo; @@ -1435,6 +1439,7 @@ UINT8 W_LumpExists(const char *name) if (fastcmp(lump_p->name, name)) return true; } + return false; } @@ -1594,13 +1599,13 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si fseek(handle, (long)(l->position + offset), SEEK_SET); // But let's not copy it yet. We support different compression formats on lumps, so we need to take that into account. - switch(wadfiles[wad]->lumpinfo[lump].compression) + switch (wadfiles[wad]->lumpinfo[lump].compression) { case CM_NOCOMPRESSION: // If it's uncompressed, we directly write the data into our destination, and return the bytes read. #ifdef NO_PNG_LUMPS { size_t bytesread = fread(dest, 1, size, handle); - ErrorIfPNG((UINT8 *)dest, bytesread, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG(static_cast(dest), bytesread, wadfiles[wad]->filename, l->fullname); return bytesread; } #else @@ -1613,8 +1618,8 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si char *decData; // Lump's decompressed real data. size_t retval; // Helper var, lzf_decompress returns 0 when an error occurs. - rawData = Z_Malloc(l->disksize, PU_STATIC, NULL); - decData = Z_Malloc(l->size, PU_STATIC, NULL); + rawData = static_cast(Z_Malloc(l->disksize, PU_STATIC, NULL)); + decData = static_cast(Z_Malloc(l->size, PU_STATIC, NULL)); if (fread(rawData, 1, l->disksize, handle) < l->disksize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); @@ -1641,7 +1646,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); Z_Free(decData); #ifdef NO_PNG_LUMPS - ErrorIfPNG((UINT8 *)dest, size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG(static_cast(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; #else @@ -1661,8 +1666,8 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si unsigned long rawSize = l->disksize; unsigned long decSize = size; - rawData = Z_Malloc(rawSize, PU_STATIC, NULL); - decData = dest; + rawData = static_cast(Z_Malloc(rawSize, PU_STATIC, NULL)); + decData = static_cast(dest); if (fread(rawData, 1, rawSize, handle) < rawSize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); @@ -1698,7 +1703,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); #ifdef NO_PNG_LUMPS - ErrorIfPNG((UINT8 *)dest, size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG(static_cast(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; } @@ -1886,7 +1891,7 @@ void *W_CacheSoftwarePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) W_ReadLumpHeaderPwad(wad, lump, lumpdata, 0, 0); dest = Z_Calloc(sizeof(patch_t), tag, &lumpcache[lump]); - Patch_Create((softwarepatch_t*)lumpdata, len, dest); + Patch_Create(static_cast(lumpdata), len, dest); Z_Free(lumpdata); } @@ -1908,7 +1913,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) if (!TestValidLump(wad, lump)) return NULL; - patch = (patch_t *)W_CacheSoftwarePatchNumPwad(wad, lump, tag); + patch = static_cast(W_CacheSoftwarePatchNumPwad(wad, lump, tag)); if (patch == NULL) return NULL; @@ -1919,7 +1924,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) Patch_CreateGL(patch); #endif - return (void *)patch; + return static_cast(patch); } void *W_CachePatchNum(lumpnum_t lumpnum, INT32 tag) @@ -1937,17 +1942,20 @@ void *W_GetCachedPatchNumPwad(UINT16 wad, UINT16 lump) #ifdef ROTSPRITE // Caches a rotsprite for patch rotation. -void *W_GetCachedRotPatchPwad(UINT16 wadnum, UINT16 lumpnum) +void *W_GetCachedRotPatchPwad(UINT16 wad, UINT16 lump) { - lumpcache_t *rotcache = wadfiles[wadnum]->rotcache; + if (!TestValidLump(wad, lump)) + return NULL; - if (!rotcache[lumpnum]) + lumpcache_t *rotcache = wadfiles[wad]->rotcache; + + if (!rotcache[lump]) { rotsprite_t *rspr = RotatedPatch_Create(ROTANGLES); - Z_SetUser(rspr, (void **)(&rotcache[lumpnum])); + Z_SetUser(rspr, static_cast(&rotcache[lump])); } - return (void *)(rotcache[lumpnum]); + return static_cast(rotcache[lump]); } #endif // ROTSPRITE @@ -1960,7 +1968,7 @@ void W_UnlockCachedPatch(void *patch) // have different lifetimes from software's. #ifdef HWRENDER if (rendermode == render_opengl) - HWR_UnlockCachedPatch((GLPatch_t *)((patch_t *)patch)->hardware); + HWR_UnlockCachedPatch(static_cast((static_cast(patch))->hardware)); else #endif Z_ChangeTag(patch, PU_PATCH); @@ -1995,13 +2003,13 @@ void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag) if (rotationangle < 1 || rotationangle >= ROTANGLES) return W_CachePatchNum(num, tag); - rspr = (rotsprite_t *)W_GetCachedRotPatchPwad(WADFILENUM(num),LUMPNUM(num)); + rspr = static_cast(W_GetCachedRotPatchPwad(WADFILENUM(num), LUMPNUM(num))); if (rspr->patches[idx] == NULL) { INT32 xpivot = 0, ypivot = 0; - ptr = (patch_t *)W_CachePatchNum(num, PU_PATCH); + ptr = static_cast(W_CachePatchNum(num, PU_PATCH)); // >y pivot centered // >x pivot not centered @@ -2192,8 +2200,8 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) fseek(fp, 0, SEEK_END); file_size = ftell(fp); - const long startpos = (file_size - (22 + 65536)); - if (!ResFindSignature(fp, pat_end, max(0l, startpos))) + const long startpos = file_size - (22 + 65536); + if (!ResFindSignature(fp, pat_end, std::max(0l, startpos))) return true; fseek(fp, -4, SEEK_CUR); @@ -2206,7 +2214,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = (char*)(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = static_cast(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2217,7 +2225,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = reinterpret_cast(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -2229,8 +2237,8 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) if (verified == true) { - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + strlcpy(fullname, reinterpret_cast(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. if ((trimname = strrchr(fullname, '/')) != 0) @@ -2244,7 +2252,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lumpname, trimname, min(8, dotpos - trimname)); + strncpy(lumpname, trimname, std::min(8, dotpos - trimname)); if (!W_VerifyName(lumpname, checklist, status)) verified = false; @@ -2439,8 +2447,8 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) fseek(fp, 0, SEEK_END); file_size = ftell(fp); - const long startpos = (file_size - (22 + 65536)); - if (!ResFindSignature(fp, pat_end, max(0l, startpos))) + const long startpos = file_size - (22 + 65536); + if (!ResFindSignature(fp, pat_end, std::max(0l, startpos))) return true; fseek(fp, -4, SEEK_CUR); @@ -2453,7 +2461,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = (char*)(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = static_cast(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2464,7 +2472,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = (zentry_t*)(cdir + offset); + zentry_t *zentry = reinterpret_cast(cdir + offset); CLEANUP(pfree) char* fullname = NULL; char* trimname; char* dotpos; @@ -2474,8 +2482,8 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) return false; } - fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); - strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + strlcpy(fullname, reinterpret_cast(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. if ((trimname = strrchr(fullname, '/')) != 0) @@ -2489,7 +2497,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lumpname, trimname, min(8, dotpos - trimname)); + strncpy(lumpname, trimname, std::min(8, dotpos - trimname)); if (W_NameStartsWith(lumpname, checklist)) { @@ -2611,15 +2619,15 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) size_t *vsizecache; // Remember that we're assuming that the WAD will have a specific set of lumps in a specific order. - UINT8 *wadData = (UINT8*)(W_CacheLumpNum(lumpnum, PU_LEVEL)); - filelump_t *fileinfo = (filelump_t *)(wadData + LONG(((wadinfo_t *)wadData)->infotableofs)); + UINT8 *wadData = static_cast(W_CacheLumpNum(lumpnum, PU_LEVEL)); + filelump_t *fileinfo = reinterpret_cast(wadData + LONG((reinterpret_cast(wadData))->infotableofs)); - i = LONG(((wadinfo_t *)wadData)->numlumps); - vsizecache = (size_t*)(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); + i = LONG((reinterpret_cast(wadData))->numlumps); + vsizecache = static_cast(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); for (realentry = 0; realentry < i; realentry++) { - vsizecache[realentry] = (size_t)(LONG(((filelump_t *)(fileinfo + realentry))->size)); + vsizecache[realentry] = static_cast(LONG((reinterpret_cast(fileinfo + realentry))->size)); if (!vsizecache[realentry]) continue; @@ -2627,7 +2635,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) numlumps++; } - vlumps = (virtlump_t*)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = static_cast(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); // Build the lumps, skipping over empty entries. for (i = 0, realentry = 0; i < numlumps; realentry++) @@ -2647,7 +2655,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) // Play it safe with the name in this case. memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = (UINT8*)( + vlumps[i].data = static_cast( Z_Malloc(vlumps[i].size, PU_LEVEL, NULL) // This is memory inefficient, sorry about that. ); memcpy(vlumps[i].data, wadData + LONG((fileinfo + realentry)->filepos), vlumps[i].size); @@ -2670,7 +2678,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) } numlumps++; - vlumps = (virtlump_t*)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = static_cast(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); for (i = 0; i < numlumps; i++, lumpnum++) { // Check if it is map marker. It is not always first lump sadly, so we need to expect it anywhere @@ -2686,11 +2694,11 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) vlumps[i].size = W_LumpLength(lumpnum); memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = (UINT8*)(W_CacheLumpNum(lumpnum, PU_LEVEL)); + vlumps[i].data = static_cast(W_CacheLumpNum(lumpnum, PU_LEVEL)); } } - vres = (virtres_t*)(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); + vres = static_cast(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); vres->vlumps = vlumps; vres->numlumps = numlumps; diff --git a/src/w_wad.h b/src/w_wad.h index 6240c31f3..9122df1b7 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -233,7 +233,7 @@ void *W_CacheSoftwarePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag); void *W_CacheSoftwarePatchNum(lumpnum_t lumpnum, INT32 tag); #ifdef ROTSPRITE -void *W_GetCachedRotPatchPwad(UINT16 wadnum, UINT16 lumpnum); // Get patch-based rotsprites from the cache. +void *W_GetCachedRotPatchPwad(UINT16 wad, UINT16 lump); // Get patch-based rotsprites from the cache. void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag); #endif From 699113fb25cdc4462de7e181b3e659c7d34e5d91 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 4 Dec 2025 20:31:54 +0100 Subject: [PATCH 09/42] w_wad: replace lumpnumcache with unordered_map hash lookup needs testing if actually better but the old lumpnumcache was basically useless due to being incredibly small even just booting up the game we have around 1000 entries already this hopefully should still be faster than potentially going through ALL lumps in ALL wads we have loaded to find the lumpnums not sure if longnames should get any special handling like before, but i dont think it really matters if theyre long honestly thanks ceepeepeereference for the basis of this --- src/w_wad.cpp | 97 ++++++++++++++++++--------------------------------- 1 file changed, 34 insertions(+), 63 deletions(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 114e5c77c..3adf929a8 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -87,18 +87,32 @@ typedef struct } lumpchecklist_t; // Must be a power of two -#define LUMPNUMCACHESIZE 64 +#define LUMPNUMCACHESIZE 2048 // should be reasonable ig #define LUMPNUMCACHENAME 32 -typedef struct lumpnum_cache_s -{ - char lumpname[LUMPNUMCACHENAME]; - lumpnum_t lumpnum; - UINT32 hash; -} lumpnum_cache_t; +#include +#include +#include -static lumpnum_cache_t lumpnumcache[LUMPNUMCACHESIZE]; -static UINT16 lumpnumcacheindex = 0; +struct LumpnumNameHash +{ + std::size_t operator()(const std::string& str) const + { + // hopefully this is fast enough but should be + return static_cast(quickncasehash(str.c_str(), str.length())); + } +}; + +struct LumpnumStringEquals +{ + bool operator()(const std::string& str1, const std::string& str2) const + { + // fasticmp should be plenty fast and ignores case + return fasticmp(str1.c_str(), str2.c_str()); + } +}; + +static std::unordered_map lumpnumcache(LUMPNUMCACHESIZE); static const char pat_central[] = {0x50, 0x4b, 0x01, 0x02, 0x00}; static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; @@ -360,7 +374,7 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) // Invalidates the cache of lump numbers. Call this whenever a wad is added. static void W_InvalidateLumpnumCache(void) { - memset(lumpnumcache, 0, sizeof(lumpnumcache)); + lumpnumcache.clear(); } UINT32 W_HashLumpName(const char *name) @@ -1222,61 +1236,18 @@ UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) return INT16_MAX; } -static lumpnum_t CheckLumpInCache(const char *name, boolean longname) +static lumpnum_t CheckLumpInCache(const char *name) { - if (longname) - { - UINT32 hash = quickncasehash(name, 32); - - // Loop backwards so that we check most recent entries first - for (INT32 i = lumpnumcacheindex + LUMPNUMCACHESIZE; i > lumpnumcacheindex; i--) - { - if (lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].hash == hash - && fasticmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name)) - { - lumpnumcacheindex = i & (LUMPNUMCACHESIZE - 1); - return lumpnumcache[lumpnumcacheindex].lumpnum; - } - } - } - else - { - UINT32 hash = quickncasehash(name, 8); - - // Loop backwards so that we check most recent entries first - for (INT32 i = lumpnumcacheindex + LUMPNUMCACHESIZE; i > lumpnumcacheindex; i--) - { - if (lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].hash == hash - && lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname[8] == '\0' - && strnicmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name, 8) == 0) - { - lumpnumcacheindex = i & (LUMPNUMCACHESIZE - 1); - return lumpnumcache[lumpnumcacheindex].lumpnum; - } - } - } + auto it = lumpnumcache.find(name); + if (it != lumpnumcache.end()) + return it->second; return LUMPERROR; } -static void AddLumpToCache(lumpnum_t lumpnum, const char *name, boolean longname) +static void AddLumpToCache(lumpnum_t lumpnum, const char *name) { - if (longname && strlen(name) >= LUMPNUMCACHENAME) - return; - - lumpnumcacheindex = (lumpnumcacheindex + 1) & (LUMPNUMCACHESIZE - 1); - memset(lumpnumcache[lumpnumcacheindex].lumpname, '\0', LUMPNUMCACHENAME); - if (longname) - { - strlcpy(lumpnumcache[lumpnumcacheindex].lumpname, name, LUMPNUMCACHENAME); - lumpnumcache[lumpnumcacheindex].hash = quickncasehash(name, LUMPNUMCACHENAME); - } - else - { - strncpy(lumpnumcache[lumpnumcacheindex].lumpname, name, 8); - lumpnumcache[lumpnumcacheindex].hash = quickncasehash(name, 8); - } - lumpnumcache[lumpnumcacheindex].lumpnum = lumpnum; + lumpnumcache.insert({name, lumpnum}); } // @@ -1292,7 +1263,7 @@ lumpnum_t W_CheckNumForName(const char *name) return LUMPERROR; // Check the lumpnumcache first. - lumpnum_t cachenum = CheckLumpInCache(name, false); + lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) return cachenum; @@ -1313,7 +1284,7 @@ lumpnum_t W_CheckNumForName(const char *name) { // Update the cache. lumpnum_t lumpnum = (i << 16) | check; - AddLumpToCache(lumpnum, name, false); + AddLumpToCache(lumpnum, name); return lumpnum; } @@ -1334,7 +1305,7 @@ lumpnum_t W_CheckNumForLongName(const char *name) return LUMPERROR; // Check the lumpnumcache first. - lumpnum_t cachenum = CheckLumpInCache(name, true); + lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) return cachenum; @@ -1355,7 +1326,7 @@ lumpnum_t W_CheckNumForLongName(const char *name) { // Update the cache. lumpnum_t lumpnum = (i << 16) | check; - AddLumpToCache(lumpnum, name, true); + AddLumpToCache(lumpnum, name); return lumpnum; } From 8091d825d5e942a86d9f25e71faaa52ff04e1bbd Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 5 Dec 2025 13:45:24 +0100 Subject: [PATCH 10/42] w_wad: use our lump fullnamelenght in W_CheckNumForFolderStartPK3 --- src/w_wad.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 3adf929a8..6d0353b98 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -1167,21 +1167,22 @@ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlu // Look for the first lump from a folder. UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlump) { - size_t name_length; UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - name_length = strlen(name); + void *val = M_AATreeGetString(wadfiles[wad]->startfolders, name); if (val != NULL) return static_cast(reinterpret_cast(val)); + namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (strnicmp(name, lump_p->fullname, name_length) == 0) + if (strnicmp(name, lump_p->fullname, namelen) == 0) { /* SLADE is special and puts a single directory entry. Skip that. */ - if (strlen(lump_p->fullname) == name_length) + if (lump_p->fullnamelength == namelen) i++; M_AATreeSetString(wadfiles[wad]->startfolders, name, reinterpret_cast(static_cast(i))); @@ -1199,16 +1200,18 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) { UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - size_t name_length = strlen(name); void *val = M_AATreeGetString(wadfiles[wad]->endfolders, name); if (val != NULL) return static_cast(reinterpret_cast(val)); + namelen = strlen(name); + for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (strnicmp(name, lump_p->fullname, name_length)) + if (strnicmp(name, lump_p->fullname, namelen)) break; } @@ -1221,12 +1224,14 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) { UINT16 i; + size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - size_t name_length = strlen(name); + + namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) { - if (!strnicmp(name, lump_p->fullname, name_length)) + if (!strnicmp(name, lump_p->fullname, namelen)) { return i; } From 41c887f2bf5038917a479c9f9de61d8ec800e19c Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 5 Dec 2025 13:47:21 +0100 Subject: [PATCH 11/42] w_wad: comment out fullname lump hash for now its unused and not particulary useful eitherway, save us a few hash generates and a struct field lul --- src/w_wad.cpp | 6 +++--- src/w_wad.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 6d0353b98..09d74f993 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -424,7 +424,7 @@ static lumpinfo_t* ResGetLumpsStandalone(FILE* handle, UINT16* numlumps, const c strcpy(lumpinfo->fullname, lumpname); lumpinfo->fullname[lumpinfo->namelength] = '\0'; lumpinfo->fullnamelength = lumpinfo->namelength; - lumpinfo->hash.fullname = lumpinfo->hash.name; + //lumpinfo->hash.fullname = lumpinfo->hash.name; *numlumps = 1; return lumpinfo; @@ -535,7 +535,7 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena strncpy(lump_p->fullname, fileinfo->name, 8); lump_p->fullname[8] = '\0'; lump_p->fullnamelength = lump_p->namelength; - lump_p->hash.fullname = lump_p->hash.name; + //lump_p->hash.fullname = lump_p->hash.name; } *nlmp = numlumps; @@ -732,7 +732,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->fullname = static_cast(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); strncpy(lump_p->fullname, fullname, SHORT(zentry->namelen)); lump_p->fullnamelength = zentry->namelen; - lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); + //lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); switch(SHORT(zentry->compression)) { diff --git a/src/w_wad.h b/src/w_wad.h index 9122df1b7..b045b9673 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -81,7 +81,7 @@ typedef struct struct { UINT32 name; // hash of name UINT32 longname; // hash of longname - UINT32 fullname; // hash of fullname + //UINT32 fullname; // hash of fullname } hash; } lumpinfo_t; From fd1e41573170ce60dce049aedd981f1e009ddc94 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 5 Dec 2025 14:00:04 +0100 Subject: [PATCH 12/42] w_wad: use unordered map to cache wad start and end folders --- src/w_wad.cpp | 31 ++++++++++++++++++------------- src/w_wad.h | 4 ++-- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 09d74f993..8488fe4d6 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -114,6 +114,11 @@ struct LumpnumStringEquals static std::unordered_map lumpnumcache(LUMPNUMCACHESIZE); +// gotta wrap this in a struct due to external C linkage +struct FolderCache { + std::unordered_map map; +}; + static const char pat_central[] = {0x50, 0x4b, 0x01, 0x02, 0x00}; static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; @@ -143,8 +148,8 @@ void W_Shutdown(void) Z_Free(wad->lumpinfo[wad->numlumps].fullname); } - M_AATreeFree(wad->startfolders); - M_AATreeFree(wad->endfolders); + delete wad->startfolders; + delete wad->endfolders; Z_Free(wad->lumpinfo); Z_Free(wad); @@ -916,8 +921,8 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) fseek(handle, 0, SEEK_END); wadfile->filesize = static_cast(ftell(handle)); wadfile->type = type; - wadfile->startfolders = M_AATreeAlloc(AATREE_STRING); - wadfile->endfolders = M_AATreeAlloc(AATREE_STRING); + wadfile->startfolders = new FolderCache(); + wadfile->endfolders = new FolderCache(); // already generated, just copy it over memcpy(&wadfile->md5sum, &md5sum, 16); @@ -1171,10 +1176,10 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; + auto it = wadfiles[wad]->startfolders->map.find(name); + if (it != wadfiles[wad]->startfolders->map.end()) + return it->second; - void *val = M_AATreeGetString(wadfiles[wad]->startfolders, name); - if (val != NULL) - return static_cast(reinterpret_cast(val)); namelen = strlen(name); for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++) @@ -1185,12 +1190,12 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum if (lump_p->fullnamelength == namelen) i++; - M_AATreeSetString(wadfiles[wad]->startfolders, name, reinterpret_cast(static_cast(i))); + wadfiles[wad]->startfolders->map[name] = i; return i; } } - M_AATreeSetString(wadfiles[wad]->startfolders, name, reinterpret_cast(INT16_MAX)); + wadfiles[wad]->startfolders->map[name] = INT16_MAX; return INT16_MAX; } @@ -1203,9 +1208,9 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - void *val = M_AATreeGetString(wadfiles[wad]->endfolders, name); - if (val != NULL) - return static_cast(reinterpret_cast(val)); + auto it = wadfiles[wad]->endfolders->map.find(name); + if (it != wadfiles[wad]->endfolders->map.end()) + return it->second; namelen = strlen(name); @@ -1215,7 +1220,7 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) break; } - M_AATreeSetString(wadfiles[wad]->endfolders, name, reinterpret_cast(static_cast(i))); + wadfiles[wad]->endfolders->map[name] = i; return i; } diff --git a/src/w_wad.h b/src/w_wad.h index b045b9673..9ed733f78 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -137,8 +137,8 @@ typedef struct wadfile_s #ifdef ROTSPRITE lumpcache_t *rotcache; // Cache rotsprites for rotating patches. #endif - aatree_t *startfolders; - aatree_t *endfolders; + struct FolderCache *startfolders; + struct FolderCache *endfolders; UINT16 numlumps; // this wad's number of resources FILE *handle; UINT32 filesize; // for network From b76ce836a0b0e54c3395707584927cfb78ff3fb1 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 5 Dec 2025 14:51:58 +0100 Subject: [PATCH 13/42] w_wad: optimize W_LumpExists in two parts: - Use our lumpcache lookup first (our unordered map), BUT since it is case insensitive we extract our lump out of it to do another case sensitive name compare - In the manual lump seach falltthrough case, we can also check against the string lenghts and hash (its case insensitive but will still reject differing names, same with stringlenght) this improves the performance of the leaderboard map browser quite a bit and everything else using v.patchExists --- src/w_wad.cpp | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 8488fe4d6..27de24789 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -1412,13 +1412,38 @@ lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, con UINT8 W_LumpExists(const char *name) { INT32 i, j; + UINT32 hash; + size_t namelen; + + lumpnum_t cachenum = CheckLumpInCache(name); + if (cachenum != LUMPERROR) + { + // ok ok, we did find a lump in our lumpcache BUTT + // the lumpcache map is case insensitive + // extract the lumpinfo out of the lumpnum + // so we can do one more extra case ~sensitive~ name compare + // otherwise we gotta fall through to our manual lump search below + // lumpnum == (wadnum << 16) | lumpinfo id + UINT16 wadnum = (cachenum >> 16) & 0xFFFF; + UINT16 lumpid = cachenum & 0xFFFF; + lumpinfo_t *lump_p = &wadfiles[wadnum]->lumpinfo[lumpid]; + if (fastcmp(lump_p->name, name)) + return true; + } + + namelen = strlen(name); + hash = W_HashLumpName(name); for (i = numwadfiles - 1; i >= 0; i--) { lumpinfo_t *lump_p = wadfiles[i]->lumpinfo; for (j = 0; j < wadfiles[i]->numlumps; ++j, ++lump_p) - if (fastcmp(lump_p->name, name)) + { + if (lump_p->namelength == namelen + && lump_p->hash.name == hash + && fastcmp(lump_p->name, name)) return true; + } } return false; From 8f3b7158e3b574591aa739320c7fe7b7acf92a3a Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 7 Dec 2025 18:57:56 +0100 Subject: [PATCH 14/42] w_wad: kill longname support we dont use it for anything, we also cannot use it for anything. Due to massive amounts of unterminated string being passed to everything So we dont need to waste memory and resources --- src/w_wad.cpp | 26 +++++++++++++------------- src/w_wad.h | 12 ++++++------ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index 27de24789..8afb38cab 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -144,7 +144,7 @@ void W_Shutdown(void) Z_Free(wad->filename); while (wad->numlumps--) { - Z_Free(wad->lumpinfo[wad->numlumps].longname); + //Z_Free(wad->lumpinfo[wad->numlumps].longname); Z_Free(wad->lumpinfo[wad->numlumps].fullname); } @@ -418,11 +418,11 @@ static lumpinfo_t* ResGetLumpsStandalone(FILE* handle, UINT16* numlumps, const c lumpinfo->hash.name = W_HashLumpName(lumpname); // Allocate the lump's long name. - lumpinfo->longname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); + /*lumpinfo->longname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->longname, lumpname); lumpinfo->longname[lumpinfo->namelength] = '\0'; lumpinfo->longnamelength = lumpinfo->namelength; - lumpinfo->hash.longname = lumpinfo->hash.name; + lumpinfo->hash.longname = lumpinfo->hash.name;*/ // Allocate the lump's full name. lumpinfo->fullname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); @@ -529,11 +529,11 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena lump_p->hash.name = W_HashLumpName(lump_p->name); // Allocate the lump's long name. - lump_p->longname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); + /*lump_p->longname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->longname, fileinfo->name, 8); lump_p->longname[8] = '\0'; lump_p->longnamelength = lump_p->namelength; - lump_p->hash.longname = lump_p->hash.name; + lump_p->hash.longname = lump_p->hash.name;*/ // Allocate the lump's full name. lump_p->fullname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); @@ -729,10 +729,10 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->namelength = strlen(lump_p->name); lump_p->hash.name = W_HashLumpName(lump_p->name); - lump_p->longname = static_cast(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); + /*lump_p->longname = static_cast(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); strlcpy(lump_p->longname, trimname, dotpos - trimname + 1); lump_p->longnamelength = strlen(lump_p->longname); - lump_p->hash.longname = W_HashLumpName(lump_p->longname); + lump_p->hash.longname = W_HashLumpName(lump_p->longname);*/ lump_p->fullname = static_cast(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); strncpy(lump_p->fullname, fullname, SHORT(zentry->namelen)); @@ -1124,7 +1124,7 @@ UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) +/*UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) { UINT16 i; UINT32 hash; @@ -1156,7 +1156,7 @@ UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) // not found. return INT16_MAX; -} +}*/ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlump) { @@ -1306,7 +1306,7 @@ lumpnum_t W_CheckNumForName(const char *name) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -lumpnum_t W_CheckNumForLongName(const char *name) +/*lumpnum_t W_CheckNumForLongName(const char *name) { INT32 i; lumpnum_t check = INT16_MAX; @@ -1340,7 +1340,7 @@ lumpnum_t W_CheckNumForLongName(const char *name) return lumpnum; } -} +}*/ // // W_GetNumForName @@ -1365,7 +1365,7 @@ lumpnum_t W_GetNumForName(const char *name) // Should be the only version, but that's not possible until we fix // all the instances of non null-terminated strings in the codebase... // -lumpnum_t W_GetNumForLongName(const char *name) +/*lumpnum_t W_GetNumForLongName(const char *name) { lumpnum_t i; @@ -1375,7 +1375,7 @@ lumpnum_t W_GetNumForLongName(const char *name) I_Error("W_GetNumForLongName: %s not found!\n", name); return i; -} +}*/ // // W_CheckNumForNameInBlock diff --git a/src/w_wad.h b/src/w_wad.h index 9ed733f78..75c7e9c04 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -68,11 +68,11 @@ typedef struct unsigned long position; // filelump_t filepos unsigned long disksize; // filelump_t size char name[9]; // filelump_t name[] e.g. "LongEntr" - char *longname; // e.g. "LongEntryName" + //char *longname; // e.g. "LongEntryName" char *fullname; // e.g. "Folder/Subfolder/LongEntryName.extension" size_t namelength; // length of name - size_t longnamelength; // length of longname + //size_t longnamelength; // length of longname size_t fullnamelength; // length of fullname size_t size; // real (uncompressed) size @@ -80,7 +80,7 @@ typedef struct struct { UINT32 name; // hash of name - UINT32 longname; // hash of longname + //UINT32 longname; // hash of longname //UINT32 fullname; // hash of fullname } hash; } lumpinfo_t; @@ -180,7 +180,7 @@ const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump); const char *W_CheckNameForNum(lumpnum_t lumpnum); UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump); // checks only in one pwad -UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump); +//UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump); /* Find the first lump after F_START for instance. */ UINT16 W_CheckNumForMarkerStartPwad(const char *name, UINT16 wad, UINT16 startlump); @@ -190,9 +190,9 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump); lumpnum_t W_CheckNumForName(const char *name); -lumpnum_t W_CheckNumForLongName(const char *name); +//lumpnum_t W_CheckNumForLongName(const char *name); lumpnum_t W_GetNumForName(const char *name); // like W_CheckNumForName but I_Error on LUMPERROR -lumpnum_t W_GetNumForLongName(const char *name); +//lumpnum_t W_GetNumForLongName(const char *name); lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, const char *blockend); UINT8 W_LumpExists(const char *name); // Lua uses this. UINT8 W_CheckMultipleLumps(const char* lump, ...); // variadic version of above lmao From 37eba186f5621895112320878026e26bddb93cb9 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 9 Dec 2025 18:06:48 +0100 Subject: [PATCH 15/42] netcode: replace some stuff with memsets + add a little bounds safety in some places --- src/d_clisrv.c | 16 ++++++++++++++++ src/d_net.c | 6 +----- src/d_netfil.c | 32 ++++++++++++++++---------------- src/i_tcp.c | 16 +++++++++------- 4 files changed, 42 insertions(+), 28 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 1117112cb..b380b2ed0 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -1939,8 +1939,11 @@ static boolean SV_ResendingSavegameToAnyone(void) INT32 i; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i] && resendingsavegame[i]) return true; + } + return false; } #endif @@ -2923,8 +2926,10 @@ static void CL_ConnectToServer(void) { pnumnodes = 0; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) pnumnodes++; + } } } while (!(cl_mode == CL_CONNECTED && (client || (server && nodewaited <= pnumnodes)))); @@ -4400,8 +4405,10 @@ void D_QuitNetGame(void) netbuffer->packettype = PT_SERVERSHUTDOWN; for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) HSendPacket(i, true, 0, 0); + } #ifdef MASTERSERVER if (serverrunning && netgame && cv_advertise.value) // see mserv.c Online() UnregisterServer(); @@ -6851,8 +6858,10 @@ static inline void PingUpdate(void) //send out our ping packets for (i = 0; i < MAXNETNODES; i++) + { if (nodeingame[i]) HSendPacket(i, true, 0, sizeof(INT32) * (MAXPLAYERS+1)); + } pingmeasurecount = 0; //Reset count } @@ -6955,10 +6964,15 @@ static void RenewHolePunch(void) static void HandleNodeTimeouts(void) { INT32 i; + if (server) + { for (i = 1; i < MAXNETNODES; i++) + { if (nodeingame[i] && freezetimeout[i] < I_GetTime()) Net_ConnectionTimeout(i); + } + } } // Keep the network alive while not advancing tics! @@ -7168,11 +7182,13 @@ void NetUpdate(void) } for (i = 0; i < MAXNETNODES; ++i) + { if (resynch_inprogress[i]) { SV_SendResynch(i); counts = -666; } + } // Do not make tics while resynching if (counts != -666) diff --git a/src/d_net.c b/src/d_net.c index ba70cb7c1..33654ee67 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -611,12 +611,8 @@ void Net_WaitAllAckReceived(UINT32 timeout) static void InitNode(node_t *node) { - node->acktosend_head = node->acktosend_tail = 0; - memset(node->acktosend, 0, sizeof(node->acktosend)); - node->firstacktosend = 0; + memset(node, 0, sizeof(node_t)); node->nextacknum = 1; - node->remotefirstack = 0; - node->flags = 0; } static void InitAck(void) diff --git a/src/d_netfil.c b/src/d_netfil.c index d35bb09b3..ecbca1eed 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -958,7 +958,7 @@ void Got_Filetxpak(void) || fastcmp(filename, "music.kart") || fastcmp(filename, "patch.kart") )) - I_Error("Tried to download \"%s\"", filename); + I_Error("Tried to download base-game file: \"%s\"", filename); if (filenum >= fileneedednum) { @@ -1017,21 +1017,21 @@ void Got_Filetxpak(void) switch(file->status) { - case FS_NOTFOUND: - s = "FS_NOTFOUND"; - break; - case FS_FOUND: - s = "FS_FOUND"; - break; - case FS_OPEN: - s = "FS_OPEN"; - break; - case FS_MD5SUMBAD: - s = "FS_MD5SUMBAD"; - break; - default: - s = "unknown"; - break; + case FS_NOTFOUND: + s = "FS_NOTFOUND"; + break; + case FS_FOUND: + s = "FS_FOUND"; + break; + case FS_OPEN: + s = "FS_OPEN"; + break; + case FS_MD5SUMBAD: + s = "FS_MD5SUMBAD"; + break; + default: + s = "unknown"; + break; } I_Error("Received a file not requested (file id: %d, file status: %s)\n", filenum, s); diff --git a/src/i_tcp.c b/src/i_tcp.c index 98a03f841..e4d9e0a7a 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -496,8 +496,10 @@ static void cleanupnodes(void) // Why can't I start at zero? for (j = 1; j < MAXNETNODES; j++) + { if (!(nodeingame[j] || SV_SendingFile(j))) nodeconnected[j] = false; + } } static SINT8 getfreenode(void) @@ -507,11 +509,13 @@ static SINT8 getfreenode(void) cleanupnodes(); for (j = 0; j < MAXNETNODES; j++) + { if (!nodeconnected[j]) { nodeconnected[j] = true; return j; } + } /** \warning No free node? Just in case a node might not have been freed properly, * look if there are connected nodes that aren't in game, and forget them. @@ -810,7 +814,7 @@ static void SOCK_Send(void) static void SOCK_FreeNodenum(INT32 numnode) { // can't disconnect from self :) - if (!numnode || numnode > MAXNETNODES) + if (numnode <= 0 || numnode > MAXNETNODES) return; DEBFILE(va("Free node %d (%s)\n", numnode, SOCK_GetNodeAddress(numnode))); @@ -1431,14 +1435,12 @@ static void SOCK_RegisterHolePunch(void) static boolean SOCK_OpenSocket(void) { - size_t i; - - memset(clientaddress, 0, sizeof (clientaddress)); + memset(clientaddress, 0, sizeof(clientaddress)); + memset(nodeconnected, false, sizeof(nodeconnected)); nodeconnected[0] = true; // always connected to self - for (i = 1; i < MAXNETNODES; i++) - nodeconnected[i] = false; nodeconnected[BROADCASTADDR] = true; + I_NetSend = SOCK_Send; I_NetGet = SOCK_Get; I_NetCloseSocket = SOCK_CloseSocket; @@ -1478,7 +1480,7 @@ static boolean SOCK_Ban(INT32 node) { INT32 ban; - if (node > MAXNETNODES) + if (node < 0 || node > MAXNETNODES) return false; ban = numbans; From 4a3c9ccfbb81f8c11d92213be6c0ffdfd08abbdd Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 26 Dec 2025 21:36:29 +0100 Subject: [PATCH 16/42] Remove tic provision (vanilla compat edition) based on https://codeberg.org/srb2classic/srb2classic/commit/7cf14fbe740998c3246dd190904f49a236b2ccec seems to get rid of some jitter in localhost --- src/d_clisrv.c | 54 +++++++++++++------------------------------------- src/d_net.c | 3 ++- 2 files changed, 16 insertions(+), 41 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 1a2717a12..ef78fe91a 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -159,7 +159,6 @@ boolean nodeingame[MAXNETNODES] = {}; // set false as nodes leave game tic_t servermaxping = 20; // server's max delay, in frames. Defaults to 20 static tic_t nettics[MAXNETNODES]; // what tic the client have received -static tic_t supposedtics[MAXNETNODES]; // nettics prevision for smaller packet static UINT8 nodewaiting[MAXNETNODES]; static tic_t firstticstosend; // min of the nettics static tic_t tictoclear = 0; // optimize d_clearticcmd @@ -186,7 +185,6 @@ boolean hu_stopped = false; // Client specific static ticcmd_t localcmds[MAXSPLITSCREENPLAYERS][MAXGENTLEMENDELAY]; -static boolean cl_packetmissed; // here it is for the secondary local player (splitscreen) static UINT8 mynode; // my address pointofview server @@ -4296,7 +4294,6 @@ static void ResetNode(INT32 node) playerpernode[node] = 0; nettics[node] = gametic; - supposedtics[node] = gametic; sendingsavegame[node] = false; @@ -4351,7 +4348,7 @@ void SV_ResetServer(void) ClearAdminPlayers(); mynode = 0; - cl_packetmissed = false; + #ifdef SATURNPAK cl_redownloadinggamestate = false; #endif @@ -4453,7 +4450,7 @@ void D_QuitNetGame(void) static inline void SV_AddNode(INT32 node) { nettics[node] = gametic; - supposedtics[node] = gametic; + // little hack because the server connects to itself and puts // nodeingame when connected not here if (node) @@ -5535,14 +5532,6 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) realstart = ExpandTics(netbuffer->u.clientpak.client_tic, nettics[node]); realend = ExpandTics(netbuffer->u.clientpak.resendfrom, nettics[node]); - if (netbuffer->packettype == PT_CLIENTMIS || netbuffer->packettype == PT_CLIENT2MIS - || netbuffer->packettype == PT_CLIENT3MIS || netbuffer->packettype == PT_CLIENT4MIS - || netbuffer->packettype == PT_NODEKEEPALIVEMIS - || supposedtics[node] < realend) - { - supposedtics[node] = realend; - } - // Discard out of order packet if (nettics[node] > realend) { @@ -5894,7 +5883,6 @@ static void PT_ServerTics(SINT8 node) if (realend > gametic + CLIENTBACKUPTICS) realend = gametic + CLIENTBACKUPTICS; - cl_packetmissed = realstart > neededtic; UINT8 *pak = (UINT8 *)&packet->cmds; UINT8 *txtpak = (UINT8 *)&packet->cmds[packet->numslots * packet->numtics]; @@ -6027,11 +6015,12 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENT2CMD: case PT_CLIENT3CMD: case PT_CLIENT4CMD: + case PT_NODEKEEPALIVE: + // "mis" tics kept for vanilla compat case PT_CLIENTMIS: case PT_CLIENT2MIS: case PT_CLIENT3MIS: case PT_CLIENT4MIS: - case PT_NODEKEEPALIVE: case PT_NODEKEEPALIVEMIS: PT_ClientCmd(netconsole, node); break; @@ -6323,25 +6312,18 @@ static void SV_SendServerKeepAlive(void) static void CL_SendClientCmd(void) { size_t packetsize = 0; - boolean mis = false; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); netbuffer->packettype = PT_CLIENTCMD; - if (cl_packetmissed) - { - netbuffer->packettype = PT_CLIENTMIS; - mis = true; - } - netbuffer->u.clientpak.resendfrom = (UINT8)(neededtic & UINT8_MAX); netbuffer->u.clientpak.client_tic = (UINT8)(gametic & UINT8_MAX); if (gamestate == GS_WAITINGPLAYERS) { // Send PT_NODEKEEPALIVE packet - netbuffer->packettype = (mis ? PT_NODEKEEPALIVEMIS : PT_NODEKEEPALIVE); + netbuffer->packettype = PT_NODEKEEPALIVE; packetsize = sizeof (clientcmd_pak) - sizeof (ticcmd_t) - sizeof (INT16); HSendPacket(servernode, false, 0, packetsize); } @@ -6404,19 +6386,19 @@ static void CL_SendClientCmd(void) if (splitscreen || botingame) // Send a special packet with 2 cmd for splitscreen { - netbuffer->packettype = (mis ? PT_CLIENT2MIS : PT_CLIENT2CMD); + netbuffer->packettype = PT_CLIENT2CMD; packetsize = sizeof (client2cmd_pak); G_MoveTiccmd(&netbuffer->u.client2pak.cmd2, &localcmds[1][lagDelay], 1); if (splitscreen > 1) { - netbuffer->packettype = (mis ? PT_CLIENT3MIS : PT_CLIENT3CMD); + netbuffer->packettype = PT_CLIENT3CMD; packetsize = sizeof (client3cmd_pak); G_MoveTiccmd(&netbuffer->u.client3pak.cmd3, &localcmds[2][lagDelay], 1); if (splitscreen > 2) { - netbuffer->packettype = (mis ? PT_CLIENT4MIS : PT_CLIENT4CMD); + netbuffer->packettype = PT_CLIENT4CMD; packetsize = sizeof (client4cmd_pak); G_MoveTiccmd(&netbuffer->u.client4pak.cmd4, &localcmds[3][lagDelay], 1); } @@ -6471,14 +6453,13 @@ static void SV_SendTics(void) // send to all client but not to me // for each node create a packet with x tics and send it - // x is computed using supposedtics[n], max packet size and maketic + // x is computed using nettics[n], max packet size and maketic for (n = 1; n < MAXNETNODES; n++) { if (!nodeingame[n]) continue; - // assert supposedtics[n]>=nettics[n] - realfirsttic = supposedtics[n]; + realfirsttic = nettics[n]; lasttictosend = min(maketic, nettics[n] + CLIENTBACKUPTICS); if (realfirsttic >= lasttictosend) @@ -6487,8 +6468,8 @@ static void SV_SendTics(void) // to resent packet that are supposed lost (this is necessary since lost // packet detection work when we have received packet with firsttic > neededtic // (getpacket servertics case) - DEBFILE(va("Nothing to send node %u mak=%u sup=%u net=%u \n", - n, lasttictosend, supposedtics[n], nettics[n])); + DEBFILE(va("Nothing to send node %u mak=%u net=%u \n", + n, lasttictosend, nettics[n])); realfirsttic = nettics[n]; if (realfirsttic >= lasttictosend || (I_GetTime() + n)&3) // all tic are ok @@ -6568,17 +6549,10 @@ static void SV_SendTics(void) packsize = bufpos - (UINT8 *)&(netbuffer->u); HSendPacket(n, false, 0, packsize); - - // when tic are too large, only one tic is sent so don't go backward! - if (lasttictosend-doomcom->extratics > realfirsttic) - supposedtics[n] = lasttictosend-doomcom->extratics; - else - supposedtics[n] = lasttictosend; - - supposedtics[n] = max(supposedtics[n], nettics[n]); } + // node 0 is me! - supposedtics[0] = maketic; + nettics[0] = maketic; } // diff --git a/src/d_net.c b/src/d_net.c index fd8fb0e31..3e0d4410c 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -863,11 +863,12 @@ static void DebugPrintpacket(const char *header) case PT_CLIENT2CMD: case PT_CLIENT3CMD: case PT_CLIENT4CMD: + case PT_NODEKEEPALIVE: + // "mis" tics kept for vanilla compat case PT_CLIENTMIS: case PT_CLIENT2MIS: case PT_CLIENT3MIS: case PT_CLIENT4MIS: - case PT_NODEKEEPALIVE: case PT_NODEKEEPALIVEMIS: fprintf(debugfile, " tic %4u resendfrom %u\n", (UINT32)netbuffer->u.clientpak.client_tic, From 08864e27b2de8382ca7530feedc37e7f5783d3e5 Mon Sep 17 00:00:00 2001 From: PAS Date: Tue, 23 Dec 2025 17:17:32 -0500 Subject: [PATCH 17/42] Fix double byte-swap in SV_MakeTic --- src/d_clisrv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index ef78fe91a..729a8f698 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -6626,7 +6626,7 @@ void SV_SpawnPlayer(INT32 playernum, INT32 x, INT32 y, angle_t angle) // create missed tic static void SV_Maketic(void) { - G_MoveTiccmd(netcmds[maketic % BACKUPTICS], playercmds, MAXPLAYERS); + G_CopyTiccmd(netcmds[maketic % BACKUPTICS], playercmds, MAXPLAYERS); maketic++; } From 39a46e8f79ed4032b78b058817bf010e4923c6f3 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 30 Dec 2025 01:09:14 +0100 Subject: [PATCH 18/42] Revert "Remove tic provision (vanilla compat edition)" This reverts commit 4a3c9ccfbb81f8c11d92213be6c0ffdfd08abbdd. --- src/d_clisrv.c | 54 +++++++++++++++++++++++++++++++++++++------------- src/d_net.c | 3 +-- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 729a8f698..5125a6c7b 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -159,6 +159,7 @@ boolean nodeingame[MAXNETNODES] = {}; // set false as nodes leave game tic_t servermaxping = 20; // server's max delay, in frames. Defaults to 20 static tic_t nettics[MAXNETNODES]; // what tic the client have received +static tic_t supposedtics[MAXNETNODES]; // nettics prevision for smaller packet static UINT8 nodewaiting[MAXNETNODES]; static tic_t firstticstosend; // min of the nettics static tic_t tictoclear = 0; // optimize d_clearticcmd @@ -185,6 +186,7 @@ boolean hu_stopped = false; // Client specific static ticcmd_t localcmds[MAXSPLITSCREENPLAYERS][MAXGENTLEMENDELAY]; +static boolean cl_packetmissed; // here it is for the secondary local player (splitscreen) static UINT8 mynode; // my address pointofview server @@ -4294,6 +4296,7 @@ static void ResetNode(INT32 node) playerpernode[node] = 0; nettics[node] = gametic; + supposedtics[node] = gametic; sendingsavegame[node] = false; @@ -4348,7 +4351,7 @@ void SV_ResetServer(void) ClearAdminPlayers(); mynode = 0; - + cl_packetmissed = false; #ifdef SATURNPAK cl_redownloadinggamestate = false; #endif @@ -4450,7 +4453,7 @@ void D_QuitNetGame(void) static inline void SV_AddNode(INT32 node) { nettics[node] = gametic; - + supposedtics[node] = gametic; // little hack because the server connects to itself and puts // nodeingame when connected not here if (node) @@ -5532,6 +5535,14 @@ static void PT_ClientCmd(INT32 netconsole, SINT8 node) realstart = ExpandTics(netbuffer->u.clientpak.client_tic, nettics[node]); realend = ExpandTics(netbuffer->u.clientpak.resendfrom, nettics[node]); + if (netbuffer->packettype == PT_CLIENTMIS || netbuffer->packettype == PT_CLIENT2MIS + || netbuffer->packettype == PT_CLIENT3MIS || netbuffer->packettype == PT_CLIENT4MIS + || netbuffer->packettype == PT_NODEKEEPALIVEMIS + || supposedtics[node] < realend) + { + supposedtics[node] = realend; + } + // Discard out of order packet if (nettics[node] > realend) { @@ -5883,6 +5894,7 @@ static void PT_ServerTics(SINT8 node) if (realend > gametic + CLIENTBACKUPTICS) realend = gametic + CLIENTBACKUPTICS; + cl_packetmissed = realstart > neededtic; UINT8 *pak = (UINT8 *)&packet->cmds; UINT8 *txtpak = (UINT8 *)&packet->cmds[packet->numslots * packet->numtics]; @@ -6015,12 +6027,11 @@ static void HandlePacketFromPlayer(SINT8 node) case PT_CLIENT2CMD: case PT_CLIENT3CMD: case PT_CLIENT4CMD: - case PT_NODEKEEPALIVE: - // "mis" tics kept for vanilla compat case PT_CLIENTMIS: case PT_CLIENT2MIS: case PT_CLIENT3MIS: case PT_CLIENT4MIS: + case PT_NODEKEEPALIVE: case PT_NODEKEEPALIVEMIS: PT_ClientCmd(netconsole, node); break; @@ -6312,18 +6323,25 @@ static void SV_SendServerKeepAlive(void) static void CL_SendClientCmd(void) { size_t packetsize = 0; + boolean mis = false; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); netbuffer->packettype = PT_CLIENTCMD; + if (cl_packetmissed) + { + netbuffer->packettype = PT_CLIENTMIS; + mis = true; + } + netbuffer->u.clientpak.resendfrom = (UINT8)(neededtic & UINT8_MAX); netbuffer->u.clientpak.client_tic = (UINT8)(gametic & UINT8_MAX); if (gamestate == GS_WAITINGPLAYERS) { // Send PT_NODEKEEPALIVE packet - netbuffer->packettype = PT_NODEKEEPALIVE; + netbuffer->packettype = (mis ? PT_NODEKEEPALIVEMIS : PT_NODEKEEPALIVE); packetsize = sizeof (clientcmd_pak) - sizeof (ticcmd_t) - sizeof (INT16); HSendPacket(servernode, false, 0, packetsize); } @@ -6386,19 +6404,19 @@ static void CL_SendClientCmd(void) if (splitscreen || botingame) // Send a special packet with 2 cmd for splitscreen { - netbuffer->packettype = PT_CLIENT2CMD; + netbuffer->packettype = (mis ? PT_CLIENT2MIS : PT_CLIENT2CMD); packetsize = sizeof (client2cmd_pak); G_MoveTiccmd(&netbuffer->u.client2pak.cmd2, &localcmds[1][lagDelay], 1); if (splitscreen > 1) { - netbuffer->packettype = PT_CLIENT3CMD; + netbuffer->packettype = (mis ? PT_CLIENT3MIS : PT_CLIENT3CMD); packetsize = sizeof (client3cmd_pak); G_MoveTiccmd(&netbuffer->u.client3pak.cmd3, &localcmds[2][lagDelay], 1); if (splitscreen > 2) { - netbuffer->packettype = PT_CLIENT4CMD; + netbuffer->packettype = (mis ? PT_CLIENT4MIS : PT_CLIENT4CMD); packetsize = sizeof (client4cmd_pak); G_MoveTiccmd(&netbuffer->u.client4pak.cmd4, &localcmds[3][lagDelay], 1); } @@ -6453,13 +6471,14 @@ static void SV_SendTics(void) // send to all client but not to me // for each node create a packet with x tics and send it - // x is computed using nettics[n], max packet size and maketic + // x is computed using supposedtics[n], max packet size and maketic for (n = 1; n < MAXNETNODES; n++) { if (!nodeingame[n]) continue; - realfirsttic = nettics[n]; + // assert supposedtics[n]>=nettics[n] + realfirsttic = supposedtics[n]; lasttictosend = min(maketic, nettics[n] + CLIENTBACKUPTICS); if (realfirsttic >= lasttictosend) @@ -6468,8 +6487,8 @@ static void SV_SendTics(void) // to resent packet that are supposed lost (this is necessary since lost // packet detection work when we have received packet with firsttic > neededtic // (getpacket servertics case) - DEBFILE(va("Nothing to send node %u mak=%u net=%u \n", - n, lasttictosend, nettics[n])); + DEBFILE(va("Nothing to send node %u mak=%u sup=%u net=%u \n", + n, lasttictosend, supposedtics[n], nettics[n])); realfirsttic = nettics[n]; if (realfirsttic >= lasttictosend || (I_GetTime() + n)&3) // all tic are ok @@ -6549,10 +6568,17 @@ static void SV_SendTics(void) packsize = bufpos - (UINT8 *)&(netbuffer->u); HSendPacket(n, false, 0, packsize); - } + // when tic are too large, only one tic is sent so don't go backward! + if (lasttictosend-doomcom->extratics > realfirsttic) + supposedtics[n] = lasttictosend-doomcom->extratics; + else + supposedtics[n] = lasttictosend; + + supposedtics[n] = max(supposedtics[n], nettics[n]); + } // node 0 is me! - nettics[0] = maketic; + supposedtics[0] = maketic; } // diff --git a/src/d_net.c b/src/d_net.c index 3e0d4410c..fd8fb0e31 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -863,12 +863,11 @@ static void DebugPrintpacket(const char *header) case PT_CLIENT2CMD: case PT_CLIENT3CMD: case PT_CLIENT4CMD: - case PT_NODEKEEPALIVE: - // "mis" tics kept for vanilla compat case PT_CLIENTMIS: case PT_CLIENT2MIS: case PT_CLIENT3MIS: case PT_CLIENT4MIS: + case PT_NODEKEEPALIVE: case PT_NODEKEEPALIVEMIS: fprintf(debugfile, " tic %4u resendfrom %u\n", (UINT32)netbuffer->u.clientpak.client_tic, From 5184115216790614e9953e0268a5563034051446 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 8 Jan 2026 00:33:43 +0100 Subject: [PATCH 19/42] enable "Wzero-as-null-pointer-constant", fix cases of it prevent ambiguity and bad practices, i like expressive and "correct" code shoutout blankart for making me aware this exists --- src/Makefile.d/versions.mk | 2 +- src/blua/lstrlib.c | 2 +- src/blua/luaconf.h | 6 +++--- src/d_clisrv.c | 14 +++++++------- src/d_main.c | 3 ++- src/d_netcmd.c | 14 +++++++------- src/f_finale.c | 2 +- src/g_demo.c | 2 +- src/g_game.c | 14 +++++++------- src/hardware/hw_batching.c | 2 +- src/hardware/hw_md2load.c | 28 ++++++++++++++-------------- src/hardware/hw_md3load.c | 24 ++++++++++++------------ src/hardware/hw_model.c | 18 +++++++++--------- src/hardware/r_opengl/r_opengl.c | 12 ++++++------ src/http-mserv.c | 8 ++++---- src/lua_mobjlib.c | 2 +- src/m_cheat.c | 8 ++++---- src/m_cond.c | 2 +- src/m_menu.c | 8 ++++---- src/m_perfstats.c | 18 +++++++++--------- src/p_enemy.c | 8 ++++---- src/p_mobj.c | 24 ++++++++++++------------ src/p_setup.c | 4 ++-- src/p_spec.c | 6 +++--- src/r_main.cpp | 2 +- src/r_skins.c | 2 +- src/r_things.cpp | 4 ++-- src/s_sound.c | 6 +++--- src/s_sound.h | 4 ++-- src/strcasestr.c | 8 ++++---- src/w_wad.c | 18 +++++++++--------- src/y_inter.c | 8 ++++---- 32 files changed, 142 insertions(+), 141 deletions(-) diff --git a/src/Makefile.d/versions.mk b/src/Makefile.d/versions.mk index 2a80cfa39..e57119fb9 100644 --- a/src/Makefile.d/versions.mk +++ b/src/Makefile.d/versions.mk @@ -20,7 +20,7 @@ $(foreach v,$(join $(wordlist 2,$(_n),- $(gcc_versions)),\ CXXFLAGS+= -Wno-aggregate-return # -W -Wno-unused -WFLAGS:=-Wall -Wno-trigraphs -Wnull-dereference +WFLAGS:=-Wall -Wno-trigraphs -Wnull-dereference -Wzero-as-null-pointer-constant ifndef GCC295 #WFLAGS+=-Wno-packed endif diff --git a/src/blua/lstrlib.c b/src/blua/lstrlib.c index e2fd23604..6fe279bcb 100644 --- a/src/blua/lstrlib.c +++ b/src/blua/lstrlib.c @@ -527,7 +527,7 @@ static int str_find_aux (lua_State *L, int find) { if (find) { lua_pushinteger(L, s1-s+1); /* start */ lua_pushinteger(L, res-s); /* end */ - return push_captures(&ms, NULL, 0) + 2; + return push_captures(&ms, NULL, NULL) + 2; } else return push_captures(&ms, s1, res); diff --git a/src/blua/luaconf.h b/src/blua/luaconf.h index 76a798751..22fa8bf53 100644 --- a/src/blua/luaconf.h +++ b/src/blua/luaconf.h @@ -772,10 +772,10 @@ union luai_Cast { double l_d; long l_l; }; #include #if defined(__GNUC__) -#define l_likely(x) (__builtin_expect(((x) != 0), 1)) -#define l_unlikely(x) (__builtin_expect(((x) != 0), 0)) +#define l_likely(x) (__builtin_expect(!!(x), 1)) +#define l_unlikely(x) (__builtin_expect(!!(x), 0)) #else -#define l_likely(x) (x) +#define l_likely(x) (x) #define l_unlikely(x) (x) #endif diff --git a/src/d_clisrv.c b/src/d_clisrv.c index d4983daa2..68ab08c5a 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -332,7 +332,7 @@ void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(const UINT8 **p, INT32 playernu #ifdef PARANOIA if (id >= MAXNETXCMD) I_Error("Command id %d too big", id); - if (listnetxcmd[id] != 0) + if (listnetxcmd[id] != NULL) I_Error("Command id %d already used", id); #endif listnetxcmd[id] = cmd_f; @@ -1236,7 +1236,7 @@ static void CL_DrawConnectionStatus(void) va(" %4uK/%4uK", currentsize>>10, totalsize>>10)); V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, - va("%3.1fK/s ", ((double)getbps)/1024)); + va("%3.1fK/s ", ((double)getbps)/1024.0)); } else cltext = M_GetText("Waiting to download game state..."); @@ -1963,7 +1963,7 @@ static boolean SV_ResendingSavegameToAnyone(void) static void SV_SendSaveGame(INT32 node, boolean resending) { size_t length, compressedlen; - savebuffer_t save = {0}; + savebuffer_t save = {}; UINT8 *compressedsave; UINT8 *buffertosend; @@ -2033,7 +2033,7 @@ static consvar_t cv_dumpconsistency = {"dumpconsistency", "Off", CV_NETVAR, CV_O static void SV_SavedGame(void) { size_t length; - savebuffer_t save = {0}; + savebuffer_t save = {}; char tmpsave[264]; if (!cv_dumpconsistency.value) @@ -2073,7 +2073,7 @@ static void SV_SavedGame(void) static void CL_LoadReceivedSavegame(boolean reloading) { - savebuffer_t save = {0}; + savebuffer_t save = {}; size_t length, decompressedlen; char tmpsave[264]; @@ -7237,7 +7237,7 @@ void CL_ClearRewinds(void) rewind_t *CL_SaveRewindPoint(size_t demopos) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; if (rewindhead && rewindhead->leveltime + REWIND_POINT_INTERVAL > leveltime) @@ -7260,7 +7260,7 @@ rewind_t *CL_SaveRewindPoint(size_t demopos) rewind_t *CL_RewindToTime(tic_t time) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; while (rewindhead && rewindhead->leveltime > time) diff --git a/src/d_main.c b/src/d_main.c index ab5fe7a10..3e474cec3 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1865,7 +1865,8 @@ void D_SRB2Main(void) if (M_CheckParm("-warp") && M_IsNextParm()) { const char *word = M_GetNextParm(); - pstartmap = G_FindMapByNameOrCode(word, 0); + pstartmap = G_FindMapByNameOrCode(word, NULL); + if (! pstartmap) I_Error("Cannot find a map remotely named '%s'\n", word); else diff --git a/src/d_netcmd.c b/src/d_netcmd.c index c669da59b..781120be2 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -249,7 +249,7 @@ consvar_t cv_competitionboxes = {"competitionboxes", "Random", CV_NETVAR|CV_CHEA #ifdef SEENAMES static CV_PossibleValue_t seenames_cons_t[] = {{0, "Off"}, {1, "Colorless"}, {2, "Team"}, {3, "Ally/Foe"}, {0, NULL}}; -consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_allowseenames = {"allowseenames", "No", CV_NETVAR, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; #endif @@ -458,16 +458,16 @@ consvar_t cv_showping = {"showping", "Always", CV_SAVE, showping_cons_t, NULL, 0 static CV_PossibleValue_t pingmeasurement_cons_t[] = {{0, "Frames"}, {1, "Milliseconds"}, {0, NULL}}; consvar_t cv_pingmeasurement = {"pingmeasurement", "Frames", CV_SAVE, pingmeasurement_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t cv_pingstyle_cons_t[] = {{0, "New"}, {1, "Old"}, {0, NULL}}; -consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // Intermission time Tails 04-19-2002 static CV_PossibleValue_t inttime_cons_t[] = {{0, "MIN"}, {3600, "MAX"}, {0, NULL}}; @@ -2789,7 +2789,7 @@ static void Command_Map_f(void) // G_TOLFlag handles both multiplayer gametype and ignores it for !multiplayer else { - if (!mapheaderinfo[newmapnum-1]) + if (mapheaderinfo[newmapnum-1] == NULL) { CONS_Alert(CONS_WARNING, M_GetText("Invalid mapheaderinfo for Course %s (%s)\n"), realmapname, G_BuildMapName(newmapnum)); return; diff --git a/src/f_finale.c b/src/f_finale.c index 801af8ab5..32ed8c3ec 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -1318,7 +1318,7 @@ boolean F_ContinueResponder(event_t *event) keypressed = true; imcontinuing = true; continuetime = TICRATE; - S_StartSound(0, sfx_itemup); + S_StartSound(NULL, sfx_itemup); return true; } diff --git a/src/g_demo.c b/src/g_demo.c index 312e57530..ede5adf18 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -76,7 +76,7 @@ static tic_t demostarttime; // for comparative timing purposes //@TODO put these all in a struct for namespacing purposes? static char demoname[128]; -savebuffer_t demobuf = {0}; +savebuffer_t demobuf = {}; static UINT8 *demotime_p, *demoinfo_p; static UINT8 *demoend; static UINT8 demoflags; diff --git a/src/g_game.c b/src/g_game.c index 892579163..27a2922a8 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -3501,7 +3501,7 @@ void G_LoadGameData(void) INT32 i, j; UINT8 modded = false; UINT8 rtemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; //For records tic_t rectime; @@ -3634,7 +3634,7 @@ void G_SaveGameData(boolean force) size_t length; INT32 i, j; UINT8 btemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; (void)force; char backupfile[MAX_WADPATH+4]; @@ -3805,7 +3805,7 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) size_t length; char vcheck[VERSIONSIZE]; char savename[255]; - savebuffer_t save = {0}; + savebuffer_t save = {}; // memset savedata to all 0, fixes calling perfectly valid saves corrupt because of bots memset(&savedata, 0, sizeof(savedata)); @@ -3891,7 +3891,7 @@ void G_SaveGame(UINT32 savegameslot) boolean saved; char savename[256] = ""; const char *backup; - savebuffer_t save = {0}; + savebuffer_t save = {}; sprintf(savename, savegamename, savegameslot); backup = va("%s",savename); @@ -4161,7 +4161,7 @@ static void measurekeywords(mapsearchfreq_t *fr, PU_STATIC, NULL); for (qp = strtok(va("%s", q), " "); qp && fr->total < 255; - qp = strtok(0, " ")) + qp = strtok(NULL, " ")) { if (( sp = strcasestr(s, qp) )) { @@ -4242,7 +4242,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { newmapnum = mapnum; newmapname = realmapname; - realmapname = 0; + realmapname = NULL; Z_Free(apromapname); if (!wanttable) break; @@ -4263,7 +4263,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { apromapnum = mapnum; apromapname = realmapname; - realmapname = 0; + realmapname = NULL; } } else/* ...match individual keywords */ diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c index 4d6b1ea6e..8bf7f7375 100644 --- a/src/hardware/hw_batching.c +++ b/src/hardware/hw_batching.c @@ -391,7 +391,7 @@ void HWR_RenderBatches(void) nextSurfaceInfo = nextEntry->surf; if (nextPolyFlags & PF_NoTexture) - nextTexture = 0; + nextTexture = NULL; if (useshader && currentShader != nextShader) { diff --git a/src/hardware/hw_md2load.c b/src/hardware/hw_md2load.c index 3805deffb..d28ebf058 100644 --- a/src/hardware/hw_md2load.c +++ b/src/hardware/hw_md2load.c @@ -274,7 +274,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); //size_t fileLen; @@ -288,13 +288,13 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) { texPos++; namelen = strlen(texPos) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, texPos); } else { namelen = strlen(fileName) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, fileName); } @@ -316,7 +316,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) header = (md2header_t*)buffer; retModel->numMeshes = 1; // MD2 only has one mesh - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, NULL); retModel->meshes[0].numFrames = header->numFrames; // const float WUNITS = 1.0f; // float dataScale = WUNITS; @@ -332,7 +332,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); // int t; for (t = 0; t < retModel->numMaterials; t++) @@ -409,9 +409,9 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) float *uvptr; dataScale = 0.015624f; // 1 / 64.0f - retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, 0); + retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, NULL); retModel->meshes[0].numVertices = header->numXYZ; - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); ptr = (char*)frames; for (i = 0; i < header->numFrames; i++, ptr += header->framesize) @@ -423,12 +423,12 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, 0); - retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, 0); + retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, NULL); + retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[0].tinyframes[i].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*header->numVerts, ztag); - retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, 0); + retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, NULL); vertptr = retModel->meshes[0].tinyframes[i].vertices; normptr = retModel->meshes[0].tinyframes[i].normals; @@ -484,8 +484,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) char *ptr; retModel->meshes[0].numVertices = header->numTris * 3; - retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, 0); - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, NULL); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); trisPtr = tris; uvptr = retModel->meshes[0].uvs; @@ -507,8 +507,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); - retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); + retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); + retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[0].frames[i].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*header->numTris*3, ztag); //float *vertptr, *normptr; diff --git a/src/hardware/hw_md3load.c b/src/hardware/hw_md3load.c index 53f6034c0..b536c7e73 100644 --- a/src/hardware/hw_md3load.c +++ b/src/hardware/hw_md3load.c @@ -168,7 +168,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); // find length of file fseek(f, 0, SEEK_END); @@ -201,7 +201,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); for (t = 0; t < retModel->numMaterials; t++) { @@ -225,7 +225,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) retModel->materials[t].spheremap = false; } - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, NULL); matCount = 0; for (i = 0, surfEnd = 0; i < mdh->numSurfaces; i++) @@ -298,9 +298,9 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) unsigned short *indexptr; md3Triangle *mdT; - retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, 0); + retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, NULL); retModel->meshes[i].numVertices = mdS->numVerts; - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, 0); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { short *vertptr; @@ -308,12 +308,12 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) // char *tanptr; int k; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, 0); - retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, 0); + retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, NULL); + retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[i].tinyframes[j].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag); - retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, 0); + retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, NULL); vertptr = retModel->meshes[i].tinyframes[j].vertices; normptr = retModel->meshes[i].tinyframes[j].normals; @@ -374,16 +374,16 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) int k; retModel->meshes[i].numVertices = mdS->numTriangles * 3;//mdS->numVerts; - retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, 0); - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, 0); + retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, NULL); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { float *vertptr; float *normptr; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); - retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); + retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); + retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); // if (retModel->materials[i].lightmap) // retModel->meshes[i].frames[j].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag); vertptr = retModel->meshes[i].frames[j].vertices; diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 8698365e4..274c23394 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -189,7 +189,7 @@ model_t *LoadModel(const char *filename, int ztag) return NULL; } - model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, 0); + model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, NULL); strcpy(model->mdlFilename, filename); Optimize(model); @@ -237,7 +237,7 @@ void GenerateVertexNormals(model_t *model) { mdlframe_t *frame = &mesh->frames[j]; int memTag = PU_STATIC; - float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, 0); + float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, NULL); int k; float *vertPtr = frame->vertices; float *oldNormals; @@ -309,7 +309,7 @@ static boolean AddMaterialToList(materiallist_t **head, material_t *material) } // Didn't find it, so add to the list - newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, 0); + newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, NULL); newMatNode->material = material; ListAdd(newMatNode, (listitem_t**)head); return true; @@ -351,7 +351,7 @@ void Optimize(model_t *model) } memTag = PU_STATIC; - newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, 0); + newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, NULL); i = 0; for (node = matListHead; node; node = node->next) @@ -377,14 +377,14 @@ void Optimize(model_t *model) newMesh->numFrames = 1; newMesh->numTriangles = numTriangles; newMesh->numVertices = numTriangles * 3; - newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, 0); - newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, 0); + newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, NULL); + newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, NULL); curFrame = &newMesh->frames[0]; curFrame->material = curMat; - curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, 0); + curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, NULL); // Now traverse the meshes of the model, adding in // vertices/normals/uvs that match the current material diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index edd2f51a7..fab0a8a6d 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -98,10 +98,10 @@ static size_t textureBufferSize = 0; static LTListItem *LightTablesTail = NULL; static LTListItem *LightTablesHead = NULL; -static RGBA_t screenPalette[256] = {0}; // the palette for the postprocessing step in palette rendering +static RGBA_t screenPalette[256] = {}; // the palette for the postprocessing step in palette rendering static GLuint screenPaletteTex = 0; // 1D texture containing the screen palette static GLuint paletteLookupTex = 0; // 3D texture containing RGB -> palette index lookup table -RGBA_t myPaletteData[256] = {0}; // the palette for converting textures to RGBA +RGBA_t myPaletteData[256] = {}; // the palette for converting textures to RGBA static GLint gltexformat = GL_RGB5_A1; GLint screen_width = 0; // used by Draw2DLine() @@ -127,9 +127,9 @@ GLuint gl_num_extensions; int majorGL = 0, minorGL = 0; //Hurdler: 04/10/2000: added for the kick ass coronas as Boris wanted;-) -GLfloat modelMatrix[16] = {0}; -GLfloat projMatrix[16] = {0}; -static GLint viewport[4]; +GLfloat modelMatrix[16] = {}; +GLfloat projMatrix[16] = {}; +static GLint viewport[4]; #ifdef USE_FBO_OGL enum @@ -171,7 +171,7 @@ boolean supportstencil = false; // flush all of the stored textures, leaving them unavailable at times such as between levels // These need to start at 0 and be set to their number, and be reset to 0 when deleted so that Intel GPUs // can know when the textures aren't there, as textures are always considered resident in their virtual memory -static GLuint screenTextures[NUMSCREENTEXTURES] = {0}; +static GLuint screenTextures[NUMSCREENTEXTURES] = {}; #define byte2float(byte) (GLfloat)(byte / 255.0f) diff --git a/src/http-mserv.c b/src/http-mserv.c index 8e35f905d..fd63c5f69 100644 --- a/src/http-mserv.c +++ b/src/http-mserv.c @@ -189,7 +189,7 @@ HMS_connect (const char *format, ...) seek = strlen(hms_api) + 1;/* + '/' */ va_start (ap, format); - url = malloc(seek + vsnprintf(0, 0, format, ap) + sizeof HMS_QUERY_VERSION - 1 + token_length + 1); + url = malloc(seek + vsnprintf(NULL, 0, format, ap) + sizeof HMS_QUERY_VERSION - 1 + token_length + 1); va_end (ap); sprintf(url, "%s/", hms_api); @@ -471,8 +471,8 @@ HMS_fetch_servers (msg_server_t *list, int query_id) *end = '\0'; address = strtok(p, " "); - port = strtok(0, " "); - contact = strtok(0, ""); + port = strtok(NULL, " "); + contact = strtok(NULL, ""); if (address && port) { @@ -539,7 +539,7 @@ HMS_compare_mod_version (char *buffer, size_t buffer_size) if (HMS_do(hms)) { version = strtok(hms->buffer, " "); - version_name = strtok(0, "\n"); + version_name = strtok(NULL, "\n"); if (version && version_name) { diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index 45c3a9f19..9bd5f5203 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -475,7 +475,7 @@ int mobj_localskin_setter(lua_State *L) } else { - mo->localskin = 0; + mo->localskin = NULL; mo->skinlocal = false; } } diff --git a/src/m_cheat.c b/src/m_cheat.c index 2890c7196..58bc1401d 100644 --- a/src/m_cheat.c +++ b/src/m_cheat.c @@ -80,7 +80,7 @@ static UINT8 cheatf_warp(void) if (success) { G_SaveGameData(true); //G_SetGameModified(false); - S_StartSound(0, sfx_kc42); + S_StartSound(NULL, sfx_kc42); } // Refresh secrets menu existing. @@ -117,13 +117,13 @@ static UINT8 cheatf_devmode(void) #endif static cheatseq_t cheat_warp = { - 0, cheatf_warp, + NULL, cheatf_warp, //{ SCRAMBLE('r'), SCRAMBLE('e'), SCRAMBLE('d'), SCRAMBLE('x'), SCRAMBLE('v'), SCRAMBLE('i'), 0xff } { SCRAMBLE('b'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), 0xff } }; static cheatseq_t cheat_warp_joy = { - 0, cheatf_warp, + NULL, cheatf_warp, /*{ SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), @@ -136,7 +136,7 @@ static cheatseq_t cheat_warp_joy = { #ifdef DEVELOP static cheatseq_t cheat_devmode = { - 0, cheatf_devmode, + NULL, cheatf_devmode, { SCRAMBLE('d'), SCRAMBLE('e'), SCRAMBLE('v'), SCRAMBLE('m'), SCRAMBLE('o'), SCRAMBLE('d'), SCRAMBLE('e'), 0xff } }; #endif diff --git a/src/m_cond.c b/src/m_cond.c index acf78e6ef..126d5a49a 100644 --- a/src/m_cond.c +++ b/src/m_cond.c @@ -235,7 +235,7 @@ void M_AddRawCondition(UINT8 set, UINT8 id, conditiontype_t c, INT32 r, INT16 x1 wnum = conditionSets[set - 1].numconditions; num = ++conditionSets[set - 1].numconditions; - conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, 0); + conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, NULL); cond = conditionSets[set - 1].condition; diff --git a/src/m_menu.c b/src/m_menu.c index c2978fe82..55112356b 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -5385,7 +5385,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na { CONS_Printf("custom settings menu initiation\n"); for (CVARSETUP = 0; CVARSETUP < MAXMENUCCVARS; ++CVARSETUP) - OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", 0, INT16_MAX}; + OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", NULL, INT16_MAX}; } if (category && ((ccvarposition == 0 && category[0] != '\0') || !fasticmp(category, OP_CustomCvarMenu[ccvarlaststheader].text))) @@ -7494,7 +7494,7 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) if ((lumpnum = W_CheckNumForName(va("%sE", mapname))) != LUMPERROR) mappingforencore = (patch_t *)W_CachePatchNum(lumpnum, PU_PATCH);*/ - V_DrawFixedPatch((x+w)<>1), (staty+67)<>1, 0, statlr, flashcol); V_DrawFixedPatch((statx+40+GRIDSTATOFFSET)<>1, 0, statud, flashcol); // bg - V_DrawFixedPatch(((statx+48+GRIDSTATOFFSET)<>1), (staty+73)<>1, 0, statbg, 0); + V_DrawFixedPatch(((statx+48+GRIDSTATOFFSET)<>1), (staty+73)<>1, 0, statbg, NULL); for (i = 0; i < numskins; i++) // draw the stat dots { @@ -8218,7 +8218,7 @@ static void M_DrawSetupMultiPlayerMenu(void) V_DrawFixedPatch((statx+64)<flags2 & MF2_FRET) { P_SetMobjState(actor, S_BLACKEGG_DESTROYPLAT1); - S_StartSound(0, sfx_s3k53); + S_StartSound(NULL, sfx_s3k53); actor->flags2 &= ~MF2_FRET; return; } @@ -6011,7 +6011,7 @@ void A_Boss7Chase(void *thing) { // Punch him! P_SetMobjState(actor, actor->info->meleestate); - S_StartSound(0, sfx_begrnd); // warning sound + S_StartSound(NULL, sfx_begrnd); // warning sound return; } } @@ -6057,7 +6057,7 @@ void A_Boss7Chase(void *thing) case 2: // Homing Missile A_FaceTarget(actor); P_SetMobjState(actor, actor->info->missilestate); - S_StartSound(0, sfx_beflap); + S_StartSound(NULL, sfx_beflap); break; } @@ -10739,7 +10739,7 @@ void A_BrakChase(void *thing) { actor->reactiontime--; if (actor->reactiontime == 0 && actor->type == MT_CYBRAKDEMON) - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } // modify target threshold diff --git a/src/p_mobj.c b/src/p_mobj.c index ad7982d87..581edf2f0 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -3606,10 +3606,10 @@ static void P_CalculatePrecipFloor(precipmobj_t *mobj) // Just the identification of a precip thinker. The thinker // should never actually be called! // -void P_NullPrecipThinker(precipmobj_t *mobj) +FUNCNORETURN void P_NullPrecipThinker(precipmobj_t *mobj) { (void)mobj; - I_Assert("P_NullPrecipThinker should not be called" == 0); + I_Error("P_NullPrecipThinker should not be called"); } boolean P_PrecipThinker(precipmobj_t *mobj) @@ -4012,7 +4012,7 @@ static void P_Boss3Thinker(mobj_t *mobj) if ((UINT32)mobj->extravalue1 + TICRATE*2 < leveltime) { mobj->extravalue1 = (INT32)leveltime; - S_StartSound(0, sfx_buzz1); + S_StartSound(NULL, sfx_buzz1); } // If in the center, check to make sure @@ -4631,7 +4631,7 @@ static void P_Boss7Thinker(mobj_t *mobj) if (mobj->health > 0) mobj->health--; - S_StartSound(0, (mobj->health) ? sfx_behurt : sfx_bedie2); + S_StartSound(NULL, (mobj->health) ? sfx_behurt : sfx_bedie2); mobj->reactiontime /= 3; @@ -4670,7 +4670,7 @@ static void P_Boss7Thinker(mobj_t *mobj) INT32 i; mobj->state->nextstate = mobj->info->painstate; // Reset - S_StartSound(0, sfx_bedeen); + S_StartSound(NULL, sfx_bedeen); for (i = 0; i < MAXPLAYERS; i++) { @@ -4694,7 +4694,7 @@ static void P_Boss7Thinker(mobj_t *mobj) mobj->state->nextstate = mobj->info->spawnstate; // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } } } @@ -4714,7 +4714,7 @@ static void P_Boss7Thinker(mobj_t *mobj) var2 = 2*TICRATE + (80<<16); A_LobShot(mobj); - S_StartSound(0, sfx_begoop); + S_StartSound(NULL, sfx_begoop); } } else if (mobj->state == &states[S_BLACKEGG_SHOOT2]) @@ -4738,7 +4738,7 @@ static void P_Boss7Thinker(mobj_t *mobj) S_StopSound(missile); if (leveltime & 1) - S_StartSound(0, sfx_beshot); + S_StartSound(NULL, sfx_beshot); } else if (mobj->state == &states[S_BLACKEGG_JUMP1] && mobj->tics == 1) { @@ -4871,7 +4871,7 @@ static void P_Boss7Thinker(mobj_t *mobj) fixed_t x,y,z; mobj_t *mo2; - S_StartSound(0, sfx_befall); + S_StartSound(NULL, sfx_befall); z = mobj->floorz; for (j = 0; j < 2; j++) @@ -4910,13 +4910,13 @@ static void P_Boss7Thinker(mobj_t *mobj) P_DamageMobj(players[i].mo, mobj, mobj, 1); // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } P_SetMobjState(mobj, mobj->info->spawnstate); } else if (mobj->state == &states[mobj->info->deathstate] && mobj->tics == mobj->state->tics) - S_StartSound(0, sfx_bedie1 + (P_RandomFixed() & 1)); + S_StartSound(NULL, sfx_bedie1 + (P_RandomFixed() & 1)); } // Metal Sonic battle boss @@ -10711,7 +10711,7 @@ void P_SpawnPlayer(INT32 playernum) // the dead body mobj retains the skin through the 'spritedef' override). mobj->skin = &skins[p->skin]; - mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : 0); + mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : NULL); mobj->skinlocal = p->skinlocal; mobj->health = p->health; diff --git a/src/p_setup.c b/src/p_setup.c index bf40afe9d..612530882 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -1022,7 +1022,7 @@ void P_WriteThings(lumpnum_t lumpnum) size_t i, length; mapthing_t *mt; UINT8 *data; - savebuffer_t save = {0}; + savebuffer_t save = {}; INT16 temp; data = W_CacheLumpNum(lumpnum, PU_LEVEL); @@ -1166,7 +1166,7 @@ static void P_LoadLineDefs2(void) for (; i--; ld++) { ld->frontsector = sides[ld->sidenum[0]].sector; //e6y: Can't be -1 here - ld->backsector = ld->sidenum[1] != 0xffff ? sides[ld->sidenum[1]].sector : 0; + ld->backsector = ld->sidenum[1] != 0xffff ? sides[ld->sidenum[1]].sector : NULL; // Repeat count for midtexture if ((ld->flags & ML_EFFECT5) && (ld->sidenum[1] != 0xffff)) diff --git a/src/p_spec.c b/src/p_spec.c index 66901d234..5045a8287 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -4579,8 +4579,8 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) if (!sec->ffloors) { sec->ffloors = ffloor; - ffloor->next = 0; - ffloor->prev = 0; + ffloor->next = NULL; + ffloor->prev = NULL; return; } @@ -4588,7 +4588,7 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) rover->next = ffloor; ffloor->prev = rover; - ffloor->next = 0; + ffloor->next = NULL; } /** Adds a 3Dfloor. diff --git a/src/r_main.cpp b/src/r_main.cpp index fecfba580..e3bfb83fa 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -1087,7 +1087,7 @@ subsector_t *R_IsPointInSubsector(fixed_t x, fixed_t y) ret = &subsectors[nodenum & ~NF_SUBSECTOR]; for (i = 0; i < ret->numlines; i++) if (P_PointOnLineSide(x, y, segs[ret->firstline + i].linedef) != segs[ret->firstline + i].side) - return 0; + return NULL; return ret; } diff --git a/src/r_skins.c b/src/r_skins.c index 538b8c38a..41971788c 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -302,7 +302,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) if (player->mo) { - player->mo->localskin = 0; + player->mo->localskin = NULL; player->mo->skinlocal = false; } } diff --git a/src/r_things.cpp b/src/r_things.cpp index cab9512e3..77b02b78c 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -532,8 +532,8 @@ void R_ClearSprites(void) visspritecount = numvisiblesprites = clippedvissprites = 0; } -static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; -static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; +static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; +static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; static void R_AllocVisSpriteChunkMemory(UINT32 chunk) { diff --git a/src/s_sound.c b/src/s_sound.c index e8075469c..7f931671d 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -884,7 +884,7 @@ static void S_StopChannel(INT32 cnum) if (cnum != i && c->sfxinfo == channels[i].sfxinfo) break; - c->sfxinfo = 0; + c->sfxinfo = NULL; } c->origin = NULL; @@ -1271,7 +1271,7 @@ static musicdef_t *S_AddMusicCredit(void) return &musicdefs[chunk][i]; } -struct cursongcredit cursongcredit = {0}; // Currently displayed song credit info +struct cursongcredit cursongcredit = {}; // Currently displayed song credit info static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicdef_t **defp) { @@ -1704,7 +1704,7 @@ static void S_UnloadMusic(void) music.flags = 0; music.looping = false; - music_refade_cv = 0; + music_refade_cv = NULL; } static boolean S_PlayMusic(boolean looping, UINT32 fadeinms) diff --git a/src/s_sound.h b/src/s_sound.h index 9e0296d2b..c7f487e92 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -253,9 +253,9 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 void S_ChangeMusicSpecial (const char *mmusic); -void S_SetRestoreMusicFadeInCvar (consvar_t *cvar); +void S_SetRestoreMusicFadeInCvar(consvar_t *cvar); #define S_ClearRestoreMusicFadeInCvar() \ - S_SetRestoreMusicFadeInCvar(0) + S_SetRestoreMusicFadeInCvar(NULL) int S_GetRestoreMusicFadeIn (void); // Stops the music. diff --git a/src/strcasestr.c b/src/strcasestr.c index d24a36e54..f50141dcf 100644 --- a/src/strcasestr.c +++ b/src/strcasestr.c @@ -73,8 +73,8 @@ nongnu_strcasestr (const char *s, const char *q) up = strchr(s, uc); lp = strchr(s, lc); - if (!( (intptr_t)up|(intptr_t)lp )) - return 0; + if (up == NULL || lp == NULL) + return NULL; if (!lp || ( up && up < lp )) { @@ -100,12 +100,12 @@ nongnu_strcasestr (const char *s, const char *q) if (trycmp(ppa, cpa, q, qn) == 0) return (*ppa); - if (!( (intptr_t)up|(intptr_t)lp )) + if (up == NULL || lp == NULL) break; if (!(*ppa) || ( (*ppb) && (*ppb) < (*ppa) )) swapp(&ppa, &ppb, &cpa, &cpb); } - return 0; + return NULL; } diff --git a/src/w_wad.c b/src/w_wad.c index 7e1ec30df..432f1421f 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -697,12 +697,12 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lump_p->name, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -1667,9 +1667,9 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si if (fread(rawData, 1, rawSize, handle) < rawSize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; + strm.zalloc = NULL; + strm.zfree = NULL; + strm.opaque = NULL; strm.total_in = strm.avail_in = rawSize; strm.total_out = strm.avail_out = decSize; @@ -2238,14 +2238,14 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -2483,14 +2483,14 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? diff --git a/src/y_inter.c b/src/y_inter.c index d35fa7825..27e794ffc 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -104,7 +104,7 @@ typedef struct } y_voteclient; // votescreen stuff -votescreen_t VoteScreen = {0}; +votescreen_t VoteScreen = {}; static y_votelvlinfo levelinfo[5]; static y_voteclient voteclient; @@ -1093,7 +1093,7 @@ void Y_VoteDrawer(void) V_DrawSmallScaledPatch(BASEVIDWIDTH-100, y, V_SNAPTORIGHT, pic); else { - V_DrawFixedPatch((BASEVIDWIDTH-20)< Date: Thu, 8 Jan 2026 00:27:06 +0100 Subject: [PATCH 20/42] K_SpawnSparkleTrail: check for blend effect apply outside the loop tiny optimization --- src/k_kart.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/k_kart.c b/src/k_kart.c index bb4da62a5..342414738 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -3595,6 +3595,8 @@ void K_SpawnSparkleTrail(mobj_t *mo) I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); + const boolean shouldblend = (mo->player && K_PlayerEffectsShouldBlend(mo->player)); + for (i = 0; i < 3; i++) { fixed_t newx = mo->x + mo->momx + (P_RandomRange(-rad, rad)<color = mo->color; - if (mo->player && K_PlayerEffectsShouldBlend(mo->player)) + if (shouldblend) sparkle->blendmode = AST_ADD; } From e923777eb67df6d889c8196e496f722b7c44ed20 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 8 Jan 2026 00:26:02 +0100 Subject: [PATCH 21/42] Acessability: add basic "reducevfx" toggle to disable/reduce certain effects toggles certain effects, which may be troublesome to some players -disabled hyudoro flashing, instead makes player translucent - Makes rainbow colour effects, such as invul, change colours very slowly - Disables underwater and heatwave screen effects - Disables palette flashing - Disables vhs effect not the most pretty implementation, but im lazy and this works feel free to suggest more things --- src/g_game.h | 1 + src/hardware/hw_main.cpp | 24 ++++- src/hardware/hw_md2.c | 11 ++- src/k_kart.c | 11 ++- src/p_mobj.c | 3 +- src/r_things.cpp | 11 ++- src/v_video.c | 197 ++++++++++++++++++++------------------- 7 files changed, 150 insertions(+), 108 deletions(-) diff --git a/src/g_game.h b/src/g_game.h index 509749c5f..6ecc69dfa 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -130,6 +130,7 @@ extern consvar_t cv_spinoutroll; extern consvar_t cv_squishdance, cv_squishdancespeed; extern consvar_t cv_playerblendeffects; +extern consvar_t cv_reducevfx; extern consvar_t cv_cechotoggle; diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 70a5a3a8d..1622a4528 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -3786,8 +3786,15 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) blend = HWR_GetBlendModeFlag(blendmode)|PF_Occlude; } - if (cv_playerfade.value && sprmo->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + if (sprmo->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + } if (HWR_UseShader()) { @@ -4076,8 +4083,15 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) blend = HWR_GetBlendModeFlag(blendmode)|PF_Occlude; } - if (cv_playerfade.value && sprmo->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + if (sprmo->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + } if (HWR_UseShader()) { @@ -6100,7 +6114,7 @@ static void HWR_DoPostProcessor(void) const camera_t *thiscam = &camera[0]; // Not supported in splitscreen - someone want to add support? - const boolean screenwave = (!splitscreen && (thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT)); + const boolean screenwave = (!splitscreen && !cv_reducevfx.value && (thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT)); // Capture the screen for intermission and screen waving if ((lastdraw || screenwave) && gamestate != GS_INTERMISSION) diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 763fb873c..e45a56cda 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -1198,8 +1198,15 @@ void HWR_DrawMD2(gl_vissprite_t *spr) Surf.PolyFlags = HWR_GetBlendModeFlag(blendmode); } - if (cv_playerfade.value && spr->mobj->player) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(spr->mobj), Surf.PolyColor.s.alpha); + if (spr->mobj->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && spr->mobj->player->kartstuff[k_hyudorotimer] > 0) + Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + + if (cv_playerfade.value) + Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(spr->mobj), Surf.PolyColor.s.alpha); + } // dont forget to enabled the depth test because we can't do this like // before: polygons models are not sorted diff --git a/src/k_kart.c b/src/k_kart.c index 342414738..59271a1e4 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -47,6 +47,8 @@ consvar_t cv_airsparks = {"airdriftsparks", "Off", CV_SAVE, CV_OnOff, NULL, 0, N consvar_t cv_playerblendeffects = {"playerblendeffects", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_reducevfx = {"reducevfx", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + // funn-E streeetch static CV_PossibleValue_t stretchfactor_t[] = {{0, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; consvar_t cv_gravstretch = {"gravstretch", "MIN", CV_SAVE|CV_FLOAT, stretchfactor_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -482,7 +484,8 @@ UINT8 colortranslations[MAXTRANSLATIONS][16] = { // UINT8 K_RainbowColor(void) { - return (UINT8)(1 + (leveltime % (MAXSKINCOLORS-1))); + const INT32 time = cv_reducevfx.value ? (leveltime >> 3) : leveltime; + return (UINT8)(1 + (time % (MAXSKINCOLORS-1))); } // Define for getting accurate color brightness readings according to how the human eye sees them. @@ -764,6 +767,8 @@ void K_RegisterClientKartStuff(void) CV_RegisterVar(&cv_playerblendeffects); + CV_RegisterVar(&cv_reducevfx); + CV_RegisterVar(&cv_saltyhop); CV_RegisterVar(&cv_saltyhopsfx); CV_RegisterVar(&cv_saltysquish); @@ -6768,7 +6773,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) { if (splitscreen) { - if (leveltime & 1) + if (!cv_reducevfx.value && leveltime & 1) player->mo->flags2 |= MF2_DONTDRAW; else player->mo->flags2 &= ~MF2_DONTDRAW; @@ -6794,7 +6799,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) if (P_IsDisplayPlayer(player) || (!P_IsDisplayPlayer(player) && (player->kartstuff[k_hyudorotimer] < (1*TICRATE/2) || player->kartstuff[k_hyudorotimer] > hyudorotime-(1*TICRATE/2)))) { - if (leveltime & 1) + if (!cv_reducevfx.value && leveltime & 1) player->mo->flags2 |= MF2_DONTDRAW; else player->mo->flags2 &= ~MF2_DONTDRAW; diff --git a/src/p_mobj.c b/src/p_mobj.c index 581edf2f0..d1b8b850a 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -12354,8 +12354,9 @@ mobj_t *P_SPMAngle(mobj_t *source, mobjtype_t type, angle_t angle, UINT8 allowai // void P_FlashPal(player_t *pl, UINT16 type, UINT16 duration) { - if (!pl) + if (!pl || cv_reducevfx.value) // no palette flashing with reducevfx return; + pl->flashcount = duration; pl->flashpal = type; } diff --git a/src/r_things.cpp b/src/r_things.cpp index 77b02b78c..d1c856238 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -1588,8 +1588,15 @@ static void R_ProjectSprite(mobj_t *thing) else trans = 0; - if (cv_playerfade.value && thing->player) - trans = static_cast(R_GetThingTransTable(R_DoPlayerFade(thing), static_cast(trans))); + if (thing->player) + { + // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap + if (cv_reducevfx.value && thing->player->kartstuff[k_hyudorotimer] > 0) + trans = static_cast(R_GetThingTransTable(FRACUNIT/2, static_cast(trans))); + + if (cv_playerfade.value) + trans = static_cast(R_GetThingTransTable(R_DoPlayerFade(thing), static_cast(trans))); + } //SoM: 3/17/2000: Disregard sprites that are out of view.. if (vflip) diff --git a/src/v_video.c b/src/v_video.c index ac85715ef..bb118d269 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -15,6 +15,7 @@ #include "doomdef.h" #include "d_main.h" +#include "g_game.h" #include "r_local.h" #include "p_local.h" #include "v_video.h" @@ -1755,6 +1756,9 @@ void V_DrawVhsEffect(boolean rewind) #endif SINT8 offs; + if (cv_reducevfx.value) + return; + barsize = vid.dup << 5; updistort = vid.dup << (rewind ? 5 : 3); downdistort = updistort >> 1; @@ -3639,127 +3643,130 @@ void V_DoPostProcessor(INT32 view, INT32 param) UINT8 *tmpscr = vid.screens[4]; UINT8 *srcscr = vid.screens[0]; - if (thiscam->postimg & POSTIMG_WATER) + if (!cv_reducevfx.value) { - INT32 y; - // Set disStart to a range from 0 to FINEANGLE, incrementing by 128 per tic - angle_t disStart = (((leveltime-1)*128) + (R_GetTimeFrac(RTF_LEVEL) / (FRACUNIT/128))) & FINEMASK; - INT32 newpix; - INT32 sine; - //UINT8 *transme = transtables + ((tr_trans50-1)<postimg & POSTIMG_WATER) { - sine = (FINESINE(disStart)*5)>>FRACBITS; - newpix = abs(sine); + INT32 y; + // Set disStart to a range from 0 to FINEANGLE, incrementing by 128 per tic + angle_t disStart = (((leveltime-1)*128) + (R_GetTimeFrac(RTF_LEVEL) / (FRACUNIT/128))) & FINEMASK; + INT32 newpix; + INT32 sine; + //UINT8 *transme = transtables + ((tr_trans50-1)<>FRACBITS; + newpix = abs(sine); - // Cleanup edge - while (newpix) + if (sine < 0) { - tmpscr[(y*vid.width)+xoffset+newpix] = srcscr[(y*vid.width)+xoffset]; - newpix--; - } - } - else - { - memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); + memcpy(&tmpscr[(y*vid.width)+xoffset+newpix], &srcscr[(y*vid.width)+xoffset], viewwidth-newpix); - // Cleanup edge - while (newpix) + // Cleanup edge + while (newpix) + { + tmpscr[(y*vid.width)+xoffset+newpix] = srcscr[(y*vid.width)+xoffset]; + newpix--; + } + } + else { - tmpscr[(y*vid.width)+xoffset+viewwidth-newpix] = srcscr[(y*vid.width)+xoffset+(viewwidth-1)]; - newpix--; + memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); + + // Cleanup edge + while (newpix) + { + tmpscr[(y*vid.width)+xoffset+viewwidth-newpix] = srcscr[(y*vid.width)+xoffset+(viewwidth-1)]; + newpix--; + } } + + /* + Unoptimized version + for (x = 0; x < vid.width; x++) + { + newpix = (x + sine); + + if (newpix < 0) + newpix = 0; + else if (newpix >= vid.width) + newpix = vid.width-1; + + tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); + }*/ + + disStart += 22;//the offset into the displacement map, increment each game loop + disStart &= FINEMASK; //clip it to FINEMASK } - /* - Unoptimized version - for (x = 0; x < vid.width; x++) - { - newpix = (x + sine); - - if (newpix < 0) - newpix = 0; - else if (newpix >= vid.width) - newpix = vid.width-1; - - tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); - }*/ - - disStart += 22;//the offset into the displacement map, increment each game loop - disStart &= FINEMASK; //clip it to FINEMASK + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - - UINT8 *tmp = tmpscr; - tmpscr = srcscr; - srcscr = tmp; - } - else if (thiscam->postimg & POSTIMG_HEAT) // Heat wave - { - INT32 y; - - // Make sure table is built - if (heatshifter == NULL || lastheight != viewheight) + else if (thiscam->postimg & POSTIMG_HEAT) // Heat wave { - if (heatshifter) - Z_Free(heatshifter); + INT32 y; - heatshifter = Z_Calloc(viewheight * sizeof(boolean), PU_STATIC, NULL); - - for (y = 0; y < viewheight; y++) + // Make sure table is built + if (heatshifter == NULL || lastheight != viewheight) { - if (M_RandomChance(FRACUNIT/8)) // 12.5% - heatshifter[y] = true; + if (heatshifter) + Z_Free(heatshifter); + + heatshifter = Z_Calloc(viewheight * sizeof(boolean), PU_STATIC, NULL); + + for (y = 0; y < viewheight; y++) + { + if (M_RandomChance(FRACUNIT/8)) // 12.5% + heatshifter[y] = true; + } + + heatindex[0] = heatindex[1] = heatindex[2] = heatindex[3] = 0; + lastheight = viewheight; } - heatindex[0] = heatindex[1] = heatindex[2] = heatindex[3] = 0; - lastheight = viewheight; - } - - for (y = yoffset; y < yoffset+viewheight; y++) - { - if (heatshifter[heatindex[view]++]) + for (y = yoffset; y < yoffset+viewheight; y++) { - // Shift this row of pixels to the right by 2 - tmpscr[(y*vid.width)+xoffset] = srcscr[(y*vid.width)+xoffset]; - memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); + if (heatshifter[heatindex[view]++]) + { + // Shift this row of pixels to the right by 2 + tmpscr[(y*vid.width)+xoffset] = srcscr[(y*vid.width)+xoffset]; + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); + } + else + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); + + heatindex[view] %= viewheight; } - else - memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); - heatindex[view] %= viewheight; + if (renderisnewtic) // This isn't interpolated... but how do you interpolate a one-pixel shift? + { + heatindex[view]++; + heatindex[view] %= vid.height; + } + + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - if (renderisnewtic) // This isn't interpolated... but how do you interpolate a one-pixel shift? - { - heatindex[view]++; - heatindex[view] %= vid.height; - } - - UINT8 *tmp = tmpscr; - tmpscr = srcscr; - srcscr = tmp; - } - #ifdef MOTIONBLUR - if (thiscam->postimg & POSTIMG_MOTION) // Motion Blur! - { - INT32 x, y; - - // TODO: Add a postimg_param so that we can pick the translucency level... - UINT8 *transme = transtables + ((param-1)<postimg & POSTIMG_MOTION) // Motion Blur! { - for (x = xoffset; x < xoffset+viewwidth; x++) - tmpscr[y*vid.width + x] = colormaps[*(transme + (srcscr [(y*vid.width)+x ] <<8) + (tmpscr[(y*vid.width)+x]))]; + INT32 x, y; + + // TODO: Add a postimg_param so that we can pick the translucency level... + UINT8 *transme = transtables + ((param-1)<postimg & POSTIMG_FLIP) && !(thiscam->postimg & POSTIMG_MIRROR)) // Flip the screen upside-down { From 3bf3bdf641add15d06adc37eeae47fca47c1e29b Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 8 Jan 2026 00:33:06 +0100 Subject: [PATCH 22/42] enable "Wzero-as-null-pointer-constant", fix cases of it prevent ambiguity and bad practices, i like expressive and "correct" code shoutout blankart for making me aware this exists --- src/Makefile.d/versions.mk | 2 +- src/blua/lstrlib.c | 2 +- src/blua/luaconf.h | 6 +++--- src/d_clisrv.c | 18 +++++++++--------- src/d_main.c | 3 ++- src/d_netcmd.c | 14 +++++++------- src/f_finale.c | 2 +- src/g_demo.c | 2 +- src/g_game.c | 14 +++++++------- src/hardware/hw_batching.c | 2 +- src/hardware/hw_md2load.c | 28 ++++++++++++++-------------- src/hardware/hw_md3load.c | 24 ++++++++++++------------ src/hardware/hw_model.c | 18 +++++++++--------- src/hardware/r_opengl/r_opengl.c | 12 ++++++------ src/http-mserv.c | 8 ++++---- src/lua_mobjlib.c | 2 +- src/m_cheat.c | 8 ++++---- src/m_cond.c | 2 +- src/m_menu.c | 8 ++++---- src/m_perfstats.c | 18 +++++++++--------- src/p_enemy.c | 8 ++++---- src/p_mobj.c | 24 ++++++++++++------------ src/p_setup.c | 4 ++-- src/p_spec.c | 6 +++--- src/r_main.cpp | 2 +- src/r_skins.c | 2 +- src/r_things.cpp | 4 ++-- src/s_sound.c | 6 +++--- src/s_sound.h | 4 ++-- src/strcasestr.c | 8 ++++---- src/w_wad.c | 18 +++++++++--------- src/y_inter.c | 8 ++++---- 32 files changed, 144 insertions(+), 143 deletions(-) diff --git a/src/Makefile.d/versions.mk b/src/Makefile.d/versions.mk index 2a80cfa39..e57119fb9 100644 --- a/src/Makefile.d/versions.mk +++ b/src/Makefile.d/versions.mk @@ -20,7 +20,7 @@ $(foreach v,$(join $(wordlist 2,$(_n),- $(gcc_versions)),\ CXXFLAGS+= -Wno-aggregate-return # -W -Wno-unused -WFLAGS:=-Wall -Wno-trigraphs -Wnull-dereference +WFLAGS:=-Wall -Wno-trigraphs -Wnull-dereference -Wzero-as-null-pointer-constant ifndef GCC295 #WFLAGS+=-Wno-packed endif diff --git a/src/blua/lstrlib.c b/src/blua/lstrlib.c index e2fd23604..6fe279bcb 100644 --- a/src/blua/lstrlib.c +++ b/src/blua/lstrlib.c @@ -527,7 +527,7 @@ static int str_find_aux (lua_State *L, int find) { if (find) { lua_pushinteger(L, s1-s+1); /* start */ lua_pushinteger(L, res-s); /* end */ - return push_captures(&ms, NULL, 0) + 2; + return push_captures(&ms, NULL, NULL) + 2; } else return push_captures(&ms, s1, res); diff --git a/src/blua/luaconf.h b/src/blua/luaconf.h index 76a798751..22fa8bf53 100644 --- a/src/blua/luaconf.h +++ b/src/blua/luaconf.h @@ -772,10 +772,10 @@ union luai_Cast { double l_d; long l_l; }; #include #if defined(__GNUC__) -#define l_likely(x) (__builtin_expect(((x) != 0), 1)) -#define l_unlikely(x) (__builtin_expect(((x) != 0), 0)) +#define l_likely(x) (__builtin_expect(!!(x), 1)) +#define l_unlikely(x) (__builtin_expect(!!(x), 0)) #else -#define l_likely(x) (x) +#define l_likely(x) (x) #define l_unlikely(x) (x) #endif diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 5125a6c7b..50d9a322f 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -332,7 +332,7 @@ void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(const UINT8 **p, INT32 playernu #ifdef PARANOIA if (id >= MAXNETXCMD) I_Error("Command id %d too big", id); - if (listnetxcmd[id] != 0) + if (listnetxcmd[id] != NULL) I_Error("Command id %d already used", id); #endif listnetxcmd[id] = cmd_f; @@ -1234,7 +1234,7 @@ static inline void CL_DrawConnectionStatus(void) va(" %4uK/%4uK",currentsize>>10,totalsize>>10)); V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, - va("%3.1fK/s ", ((double)getbps)/1024)); + va("%3.1fK/s ", ((double)getbps)/1024.0)); } else cltext = M_GetText("Waiting to download game state..."); @@ -1956,7 +1956,7 @@ static boolean SV_ResendingSavegameToAnyone(void) static void SV_SendSaveGame(INT32 node, boolean resending) { size_t length, compressedlen; - savebuffer_t save = {0}; + savebuffer_t save = {}; UINT8 *compressedsave; UINT8 *buffertosend; @@ -2026,7 +2026,7 @@ static consvar_t cv_dumpconsistency = {"dumpconsistency", "Off", CV_NETVAR, CV_O static void SV_SavedGame(void) { size_t length; - savebuffer_t save = {0}; + savebuffer_t save = {}; char tmpsave[264]; if (!cv_dumpconsistency.value) @@ -2066,7 +2066,7 @@ static void SV_SavedGame(void) static void CL_LoadReceivedSavegame(boolean reloading) { - savebuffer_t save = {0}; + savebuffer_t save = {}; size_t length, decompressedlen; char tmpsave[264]; @@ -4933,8 +4933,6 @@ static void PT_ClientJoin(SINT8 node) if (client || nodeingame[node] || levelloading) return; - doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); - const char *refuse = GetRefuseMessage(node); if (refuse) @@ -4943,6 +4941,8 @@ static void PT_ClientJoin(SINT8 node) return; } + doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); + // client authorised to join nodewaiting[node] = (UINT8)(netbuffer->u.clientcfg.localplayers - playerpernode[node]); @@ -7288,7 +7288,7 @@ void CL_ClearRewinds(void) rewind_t *CL_SaveRewindPoint(size_t demopos) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; if (rewindhead && rewindhead->leveltime + REWIND_POINT_INTERVAL > leveltime) @@ -7311,7 +7311,7 @@ rewind_t *CL_SaveRewindPoint(size_t demopos) rewind_t *CL_RewindToTime(tic_t time) { - savebuffer_t save = {0}; + savebuffer_t save = {}; rewind_t *rewind; while (rewindhead && rewindhead->leveltime > time) diff --git a/src/d_main.c b/src/d_main.c index c46ef0c44..486ca5b07 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1869,7 +1869,8 @@ void D_SRB2Main(void) if (M_CheckParm("-warp") && M_IsNextParm()) { const char *word = M_GetNextParm(); - pstartmap = G_FindMapByNameOrCode(word, 0); + pstartmap = G_FindMapByNameOrCode(word, NULL); + if (! pstartmap) I_Error("Cannot find a map remotely named '%s'\n", word); else diff --git a/src/d_netcmd.c b/src/d_netcmd.c index b579e6848..e9f814857 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -249,7 +249,7 @@ consvar_t cv_competitionboxes = {"competitionboxes", "Random", CV_NETVAR|CV_CHEA #ifdef SEENAMES static CV_PossibleValue_t seenames_cons_t[] = {{0, "Off"}, {1, "Colorless"}, {2, "Team"}, {3, "Ally/Foe"}, {0, NULL}}; -consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_seenames = {"seenames", "Off", CV_SAVE, seenames_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_allowseenames = {"allowseenames", "No", CV_NETVAR, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; #endif @@ -458,16 +458,16 @@ consvar_t cv_showping = {"showping", "Always", CV_SAVE, showping_cons_t, NULL, 0 static CV_PossibleValue_t pingmeasurement_cons_t[] = {{0, "Frames"}, {1, "Milliseconds"}, {0, NULL}}; consvar_t cv_pingmeasurement = {"pingmeasurement", "Frames", CV_SAVE, pingmeasurement_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingicon = {"pingicon", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t cv_pingstyle_cons_t[] = {{0, "New"}, {1, "Old"}, {0, NULL}}; -consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_pingstyle = {"pingstyle", "New", CV_SAVE, cv_pingstyle_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_luaimmersion = {"luaimmersion", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showviewpointtext = {"showviewpointtext", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, 0, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_showdownloadprompt = {"showdownloadprompt", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // Intermission time Tails 04-19-2002 static CV_PossibleValue_t inttime_cons_t[] = {{0, "MIN"}, {3600, "MAX"}, {0, NULL}}; @@ -2447,7 +2447,7 @@ static void Command_Map_f(void) // G_TOLFlag handles both multiplayer gametype and ignores it for !multiplayer else { - if (!mapheaderinfo[newmapnum-1]) + if (mapheaderinfo[newmapnum-1] == NULL) { CONS_Alert(CONS_WARNING, M_GetText("Invalid mapheaderinfo for Course %s (%s)\n"), realmapname, G_BuildMapName(newmapnum)); return; diff --git a/src/f_finale.c b/src/f_finale.c index 801af8ab5..32ed8c3ec 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -1318,7 +1318,7 @@ boolean F_ContinueResponder(event_t *event) keypressed = true; imcontinuing = true; continuetime = TICRATE; - S_StartSound(0, sfx_itemup); + S_StartSound(NULL, sfx_itemup); return true; } diff --git a/src/g_demo.c b/src/g_demo.c index 312e57530..ede5adf18 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -76,7 +76,7 @@ static tic_t demostarttime; // for comparative timing purposes //@TODO put these all in a struct for namespacing purposes? static char demoname[128]; -savebuffer_t demobuf = {0}; +savebuffer_t demobuf = {}; static UINT8 *demotime_p, *demoinfo_p; static UINT8 *demoend; static UINT8 demoflags; diff --git a/src/g_game.c b/src/g_game.c index c304c2e6f..64328da06 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -3498,7 +3498,7 @@ void G_LoadGameData(void) INT32 i, j; UINT8 modded = false; UINT8 rtemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; //For records tic_t rectime; @@ -3631,7 +3631,7 @@ void G_SaveGameData(boolean force) size_t length; INT32 i, j; UINT8 btemp; - savebuffer_t save = {0}; + savebuffer_t save = {}; (void)force; char backupfile[MAX_WADPATH+4]; @@ -3802,7 +3802,7 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) size_t length; char vcheck[VERSIONSIZE]; char savename[255]; - savebuffer_t save = {0}; + savebuffer_t save = {}; // memset savedata to all 0, fixes calling perfectly valid saves corrupt because of bots memset(&savedata, 0, sizeof(savedata)); @@ -3888,7 +3888,7 @@ void G_SaveGame(UINT32 savegameslot) boolean saved; char savename[256] = ""; const char *backup; - savebuffer_t save = {0}; + savebuffer_t save = {}; sprintf(savename, savegamename, savegameslot); backup = va("%s",savename); @@ -4158,7 +4158,7 @@ static void measurekeywords(mapsearchfreq_t *fr, PU_STATIC, NULL); for (qp = strtok(va("%s", q), " "); qp && fr->total < 255; - qp = strtok(0, " ")) + qp = strtok(NULL, " ")) { if (( sp = strcasestr(s, qp) )) { @@ -4239,7 +4239,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { newmapnum = mapnum; newmapname = realmapname; - realmapname = 0; + realmapname = NULL; Z_Free(apromapname); if (!wanttable) break; @@ -4260,7 +4260,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, { apromapnum = mapnum; apromapname = realmapname; - realmapname = 0; + realmapname = NULL; } } else/* ...match individual keywords */ diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c index 4d6b1ea6e..8bf7f7375 100644 --- a/src/hardware/hw_batching.c +++ b/src/hardware/hw_batching.c @@ -391,7 +391,7 @@ void HWR_RenderBatches(void) nextSurfaceInfo = nextEntry->surf; if (nextPolyFlags & PF_NoTexture) - nextTexture = 0; + nextTexture = NULL; if (useshader && currentShader != nextShader) { diff --git a/src/hardware/hw_md2load.c b/src/hardware/hw_md2load.c index 3805deffb..d28ebf058 100644 --- a/src/hardware/hw_md2load.c +++ b/src/hardware/hw_md2load.c @@ -274,7 +274,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); //size_t fileLen; @@ -288,13 +288,13 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) { texPos++; namelen = strlen(texPos) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, texPos); } else { namelen = strlen(fileName) + 1; - texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, 0); + texturefilename = (char*)Z_Malloc(namelen, PU_CACHE, NULL); strcpy(texturefilename, fileName); } @@ -316,7 +316,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) header = (md2header_t*)buffer; retModel->numMeshes = 1; // MD2 only has one mesh - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * retModel->numMeshes, ztag, NULL); retModel->meshes[0].numFrames = header->numFrames; // const float WUNITS = 1.0f; // float dataScale = WUNITS; @@ -332,7 +332,7 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); // int t; for (t = 0; t < retModel->numMaterials; t++) @@ -409,9 +409,9 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) float *uvptr; dataScale = 0.015624f; // 1 / 64.0f - retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, 0); + retModel->meshes[0].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*header->numFrames, ztag, NULL); retModel->meshes[0].numVertices = header->numXYZ; - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); ptr = (char*)frames; for (i = 0; i < header->numFrames; i++, ptr += header->framesize) @@ -423,12 +423,12 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, 0); - retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, 0); + retModel->meshes[0].tinyframes[i].vertices = (short*)Z_Malloc(sizeof(short) * 3 * header->numXYZ, ztag, NULL); + retModel->meshes[0].tinyframes[i].normals = (char*)Z_Malloc(sizeof(char) * 3 * header->numXYZ, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[0].tinyframes[i].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*header->numVerts, ztag); - retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, 0); + retModel->meshes[0].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * header->numTris, ztag, NULL); vertptr = retModel->meshes[0].tinyframes[i].vertices; normptr = retModel->meshes[0].tinyframes[i].normals; @@ -484,8 +484,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) char *ptr; retModel->meshes[0].numVertices = header->numTris * 3; - retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, 0); - retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, 0); + retModel->meshes[0].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*header->numFrames, ztag, NULL); + retModel->meshes[0].uvs = (float*)Z_Malloc(sizeof(float) * 2 * retModel->meshes[0].numVertices, ztag, NULL); trisPtr = tris; uvptr = retModel->meshes[0].uvs; @@ -507,8 +507,8 @@ model_t *MD2_LoadModel(const char *fileName, int ztag, boolean useFloat) md2vertex_t *vertex; md2frame_t *framePtr = (md2frame_t*)ptr; - retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); - retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, 0); + retModel->meshes[0].frames[i].normals = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); + retModel->meshes[0].frames[i].vertices = (float*)Z_Malloc(sizeof(float) * 3 * header->numTris * 3, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[0].frames[i].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*header->numTris*3, ztag); //float *vertptr, *normptr; diff --git a/src/hardware/hw_md3load.c b/src/hardware/hw_md3load.c index 53f6034c0..b536c7e73 100644 --- a/src/hardware/hw_md3load.c +++ b/src/hardware/hw_md3load.c @@ -168,7 +168,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (!f) return NULL; - retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, 0); + retModel = (model_t*)Z_Calloc(sizeof(model_t), ztag, NULL); // find length of file fseek(f, 0, SEEK_END); @@ -201,7 +201,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) if (retModel->numMaterials <= 0) // Always at least one skin, duh retModel->numMaterials = 1; - retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, 0); + retModel->materials = (material_t*)Z_Calloc(sizeof(material_t)*retModel->numMaterials, ztag, NULL); for (t = 0; t < retModel->numMaterials; t++) { @@ -225,7 +225,7 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) retModel->materials[t].spheremap = false; } - retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, 0); + retModel->meshes = (mesh_t*)Z_Calloc(sizeof(mesh_t)*retModel->numMeshes, ztag, NULL); matCount = 0; for (i = 0, surfEnd = 0; i < mdh->numSurfaces; i++) @@ -298,9 +298,9 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) unsigned short *indexptr; md3Triangle *mdT; - retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, 0); + retModel->meshes[i].tinyframes = (tinyframe_t*)Z_Calloc(sizeof(tinyframe_t)*mdS->numFrames, ztag, NULL); retModel->meshes[i].numVertices = mdS->numVerts; - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, 0); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numVerts, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { short *vertptr; @@ -308,12 +308,12 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) // char *tanptr; int k; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, 0); - retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, 0); + retModel->meshes[i].tinyframes[j].vertices = (short*)Z_Malloc(sizeof(short)*3*mdS->numVerts, ztag, NULL); + retModel->meshes[i].tinyframes[j].normals = (char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag, NULL); // if (retModel->materials[0].lightmap) // retModel->meshes[i].tinyframes[j].tangents = (char*)malloc(sizeof(char));//(char*)Z_Malloc(sizeof(char)*3*mdS->numVerts, ztag); - retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, 0); + retModel->meshes[i].indices = (unsigned short*)Z_Malloc(sizeof(unsigned short) * 3 * mdS->numTriangles, ztag, NULL); vertptr = retModel->meshes[i].tinyframes[j].vertices; normptr = retModel->meshes[i].tinyframes[j].normals; @@ -374,16 +374,16 @@ model_t *MD3_LoadModel(const char *fileName, int ztag, boolean useFloat) int k; retModel->meshes[i].numVertices = mdS->numTriangles * 3;//mdS->numVerts; - retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, 0); - retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, 0); + retModel->meshes[i].frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t)*mdS->numFrames, ztag, NULL); + retModel->meshes[i].uvs = (float*)Z_Malloc(sizeof(float)*2*mdS->numTriangles*3, ztag, NULL); for (j = 0; j < mdS->numFrames; j++) { float *vertptr; float *normptr; md3Vertex *mdV = (md3Vertex*)((char*)mdS + mdS->offsetXYZNormal + (mdS->numVerts*j*sizeof(md3Vertex))); - retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); - retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, 0); + retModel->meshes[i].frames[j].vertices = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); + retModel->meshes[i].frames[j].normals = (float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag, NULL); // if (retModel->materials[i].lightmap) // retModel->meshes[i].frames[j].tangents = (float*)malloc(sizeof(float));//(float*)Z_Malloc(sizeof(float)*3*mdS->numTriangles*3, ztag); vertptr = retModel->meshes[i].frames[j].vertices; diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 8698365e4..274c23394 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -189,7 +189,7 @@ model_t *LoadModel(const char *filename, int ztag) return NULL; } - model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, 0); + model->mdlFilename = (char*)Z_Malloc(strlen(filename)+1, ztag, NULL); strcpy(model->mdlFilename, filename); Optimize(model); @@ -237,7 +237,7 @@ void GenerateVertexNormals(model_t *model) { mdlframe_t *frame = &mesh->frames[j]; int memTag = PU_STATIC; - float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, 0); + float *newNormals = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag, NULL); int k; float *vertPtr = frame->vertices; float *oldNormals; @@ -309,7 +309,7 @@ static boolean AddMaterialToList(materiallist_t **head, material_t *material) } // Didn't find it, so add to the list - newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, 0); + newMatNode = (materiallist_t*)Z_Malloc(sizeof(materiallist_t), PU_CACHE, NULL); newMatNode->material = material; ListAdd(newMatNode, (listitem_t**)head); return true; @@ -351,7 +351,7 @@ void Optimize(model_t *model) } memTag = PU_STATIC; - newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, 0); + newMeshes = (mesh_t*)Z_Calloc(sizeof(mesh_t) * numMeshes, memTag, NULL); i = 0; for (node = matListHead; node; node = node->next) @@ -377,14 +377,14 @@ void Optimize(model_t *model) newMesh->numFrames = 1; newMesh->numTriangles = numTriangles; newMesh->numVertices = numTriangles * 3; - newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, 0); - newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, 0); + newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, NULL); + newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, NULL); curFrame = &newMesh->frames[0]; curFrame->material = curMat; - curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); - curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, 0); + curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, NULL); + curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, NULL); // Now traverse the meshes of the model, adding in // vertices/normals/uvs that match the current material diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 94656e843..86d1f5faa 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -98,10 +98,10 @@ static size_t textureBufferSize = 0; static LTListItem *LightTablesTail = NULL; static LTListItem *LightTablesHead = NULL; -static RGBA_t screenPalette[256] = {0}; // the palette for the postprocessing step in palette rendering +static RGBA_t screenPalette[256] = {}; // the palette for the postprocessing step in palette rendering static GLuint screenPaletteTex = 0; // 1D texture containing the screen palette static GLuint paletteLookupTex = 0; // 3D texture containing RGB -> palette index lookup table -RGBA_t myPaletteData[256] = {0}; // the palette for converting textures to RGBA +RGBA_t myPaletteData[256] = {}; // the palette for converting textures to RGBA static GLint gltexformat = GL_RGB5_A1; GLint screen_width = 0; // used by Draw2DLine() @@ -127,9 +127,9 @@ GLuint gl_num_extensions; int majorGL = 0, minorGL = 0; //Hurdler: 04/10/2000: added for the kick ass coronas as Boris wanted;-) -GLfloat modelMatrix[16] = {0}; -GLfloat projMatrix[16] = {0}; -static GLint viewport[4]; +GLfloat modelMatrix[16] = {}; +GLfloat projMatrix[16] = {}; +static GLint viewport[4]; #ifdef USE_FBO_OGL enum @@ -171,7 +171,7 @@ boolean supportstencil = false; // flush all of the stored textures, leaving them unavailable at times such as between levels // These need to start at 0 and be set to their number, and be reset to 0 when deleted so that Intel GPUs // can know when the textures aren't there, as textures are always considered resident in their virtual memory -static GLuint screenTextures[NUMSCREENTEXTURES] = {0}; +static GLuint screenTextures[NUMSCREENTEXTURES] = {}; #define byte2float(byte) (GLfloat)(byte / 255.0f) diff --git a/src/http-mserv.c b/src/http-mserv.c index 8e35f905d..fd63c5f69 100644 --- a/src/http-mserv.c +++ b/src/http-mserv.c @@ -189,7 +189,7 @@ HMS_connect (const char *format, ...) seek = strlen(hms_api) + 1;/* + '/' */ va_start (ap, format); - url = malloc(seek + vsnprintf(0, 0, format, ap) + sizeof HMS_QUERY_VERSION - 1 + token_length + 1); + url = malloc(seek + vsnprintf(NULL, 0, format, ap) + sizeof HMS_QUERY_VERSION - 1 + token_length + 1); va_end (ap); sprintf(url, "%s/", hms_api); @@ -471,8 +471,8 @@ HMS_fetch_servers (msg_server_t *list, int query_id) *end = '\0'; address = strtok(p, " "); - port = strtok(0, " "); - contact = strtok(0, ""); + port = strtok(NULL, " "); + contact = strtok(NULL, ""); if (address && port) { @@ -539,7 +539,7 @@ HMS_compare_mod_version (char *buffer, size_t buffer_size) if (HMS_do(hms)) { version = strtok(hms->buffer, " "); - version_name = strtok(0, "\n"); + version_name = strtok(NULL, "\n"); if (version && version_name) { diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index 45c3a9f19..9bd5f5203 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -475,7 +475,7 @@ int mobj_localskin_setter(lua_State *L) } else { - mo->localskin = 0; + mo->localskin = NULL; mo->skinlocal = false; } } diff --git a/src/m_cheat.c b/src/m_cheat.c index 2890c7196..58bc1401d 100644 --- a/src/m_cheat.c +++ b/src/m_cheat.c @@ -80,7 +80,7 @@ static UINT8 cheatf_warp(void) if (success) { G_SaveGameData(true); //G_SetGameModified(false); - S_StartSound(0, sfx_kc42); + S_StartSound(NULL, sfx_kc42); } // Refresh secrets menu existing. @@ -117,13 +117,13 @@ static UINT8 cheatf_devmode(void) #endif static cheatseq_t cheat_warp = { - 0, cheatf_warp, + NULL, cheatf_warp, //{ SCRAMBLE('r'), SCRAMBLE('e'), SCRAMBLE('d'), SCRAMBLE('x'), SCRAMBLE('v'), SCRAMBLE('i'), 0xff } { SCRAMBLE('b'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), SCRAMBLE('n'), SCRAMBLE('a'), 0xff } }; static cheatseq_t cheat_warp_joy = { - 0, cheatf_warp, + NULL, cheatf_warp, /*{ SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_UPARROW), @@ -136,7 +136,7 @@ static cheatseq_t cheat_warp_joy = { #ifdef DEVELOP static cheatseq_t cheat_devmode = { - 0, cheatf_devmode, + NULL, cheatf_devmode, { SCRAMBLE('d'), SCRAMBLE('e'), SCRAMBLE('v'), SCRAMBLE('m'), SCRAMBLE('o'), SCRAMBLE('d'), SCRAMBLE('e'), 0xff } }; #endif diff --git a/src/m_cond.c b/src/m_cond.c index acf78e6ef..126d5a49a 100644 --- a/src/m_cond.c +++ b/src/m_cond.c @@ -235,7 +235,7 @@ void M_AddRawCondition(UINT8 set, UINT8 id, conditiontype_t c, INT32 r, INT16 x1 wnum = conditionSets[set - 1].numconditions; num = ++conditionSets[set - 1].numconditions; - conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, 0); + conditionSets[set - 1].condition = Z_Realloc(conditionSets[set - 1].condition, sizeof(condition_t)*num, PU_STATIC, NULL); cond = conditionSets[set - 1].condition; diff --git a/src/m_menu.c b/src/m_menu.c index c2978fe82..55112356b 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -5385,7 +5385,7 @@ void M_SlotCvarIntoModMenu(consvar_t* cvar, const char* category, const char* na { CONS_Printf("custom settings menu initiation\n"); for (CVARSETUP = 0; CVARSETUP < MAXMENUCCVARS; ++CVARSETUP) - OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", 0, INT16_MAX}; + OP_CustomCvarMenu[CVARSETUP] = (menuitem_t){IT_DISABLED, NULL, "", NULL, INT16_MAX}; } if (category && ((ccvarposition == 0 && category[0] != '\0') || !fasticmp(category, OP_CustomCvarMenu[ccvarlaststheader].text))) @@ -7494,7 +7494,7 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) if ((lumpnum = W_CheckNumForName(va("%sE", mapname))) != LUMPERROR) mappingforencore = (patch_t *)W_CachePatchNum(lumpnum, PU_PATCH);*/ - V_DrawFixedPatch((x+w)<>1), (staty+67)<>1, 0, statlr, flashcol); V_DrawFixedPatch((statx+40+GRIDSTATOFFSET)<>1, 0, statud, flashcol); // bg - V_DrawFixedPatch(((statx+48+GRIDSTATOFFSET)<>1), (staty+73)<>1, 0, statbg, 0); + V_DrawFixedPatch(((statx+48+GRIDSTATOFFSET)<>1), (staty+73)<>1, 0, statbg, NULL); for (i = 0; i < numskins; i++) // draw the stat dots { @@ -8218,7 +8218,7 @@ static void M_DrawSetupMultiPlayerMenu(void) V_DrawFixedPatch((statx+64)<flags2 & MF2_FRET) { P_SetMobjState(actor, S_BLACKEGG_DESTROYPLAT1); - S_StartSound(0, sfx_s3k53); + S_StartSound(NULL, sfx_s3k53); actor->flags2 &= ~MF2_FRET; return; } @@ -6011,7 +6011,7 @@ void A_Boss7Chase(void *thing) { // Punch him! P_SetMobjState(actor, actor->info->meleestate); - S_StartSound(0, sfx_begrnd); // warning sound + S_StartSound(NULL, sfx_begrnd); // warning sound return; } } @@ -6057,7 +6057,7 @@ void A_Boss7Chase(void *thing) case 2: // Homing Missile A_FaceTarget(actor); P_SetMobjState(actor, actor->info->missilestate); - S_StartSound(0, sfx_beflap); + S_StartSound(NULL, sfx_beflap); break; } @@ -10739,7 +10739,7 @@ void A_BrakChase(void *thing) { actor->reactiontime--; if (actor->reactiontime == 0 && actor->type == MT_CYBRAKDEMON) - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } // modify target threshold diff --git a/src/p_mobj.c b/src/p_mobj.c index ad7982d87..581edf2f0 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -3606,10 +3606,10 @@ static void P_CalculatePrecipFloor(precipmobj_t *mobj) // Just the identification of a precip thinker. The thinker // should never actually be called! // -void P_NullPrecipThinker(precipmobj_t *mobj) +FUNCNORETURN void P_NullPrecipThinker(precipmobj_t *mobj) { (void)mobj; - I_Assert("P_NullPrecipThinker should not be called" == 0); + I_Error("P_NullPrecipThinker should not be called"); } boolean P_PrecipThinker(precipmobj_t *mobj) @@ -4012,7 +4012,7 @@ static void P_Boss3Thinker(mobj_t *mobj) if ((UINT32)mobj->extravalue1 + TICRATE*2 < leveltime) { mobj->extravalue1 = (INT32)leveltime; - S_StartSound(0, sfx_buzz1); + S_StartSound(NULL, sfx_buzz1); } // If in the center, check to make sure @@ -4631,7 +4631,7 @@ static void P_Boss7Thinker(mobj_t *mobj) if (mobj->health > 0) mobj->health--; - S_StartSound(0, (mobj->health) ? sfx_behurt : sfx_bedie2); + S_StartSound(NULL, (mobj->health) ? sfx_behurt : sfx_bedie2); mobj->reactiontime /= 3; @@ -4670,7 +4670,7 @@ static void P_Boss7Thinker(mobj_t *mobj) INT32 i; mobj->state->nextstate = mobj->info->painstate; // Reset - S_StartSound(0, sfx_bedeen); + S_StartSound(NULL, sfx_bedeen); for (i = 0; i < MAXPLAYERS; i++) { @@ -4694,7 +4694,7 @@ static void P_Boss7Thinker(mobj_t *mobj) mobj->state->nextstate = mobj->info->spawnstate; // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } } } @@ -4714,7 +4714,7 @@ static void P_Boss7Thinker(mobj_t *mobj) var2 = 2*TICRATE + (80<<16); A_LobShot(mobj); - S_StartSound(0, sfx_begoop); + S_StartSound(NULL, sfx_begoop); } } else if (mobj->state == &states[S_BLACKEGG_SHOOT2]) @@ -4738,7 +4738,7 @@ static void P_Boss7Thinker(mobj_t *mobj) S_StopSound(missile); if (leveltime & 1) - S_StartSound(0, sfx_beshot); + S_StartSound(NULL, sfx_beshot); } else if (mobj->state == &states[S_BLACKEGG_JUMP1] && mobj->tics == 1) { @@ -4871,7 +4871,7 @@ static void P_Boss7Thinker(mobj_t *mobj) fixed_t x,y,z; mobj_t *mo2; - S_StartSound(0, sfx_befall); + S_StartSound(NULL, sfx_befall); z = mobj->floorz; for (j = 0; j < 2; j++) @@ -4910,13 +4910,13 @@ static void P_Boss7Thinker(mobj_t *mobj) P_DamageMobj(players[i].mo, mobj, mobj, 1); // Laugh - S_StartSound(0, sfx_bewar1 + P_RandomKey(4)); + S_StartSound(NULL, sfx_bewar1 + P_RandomKey(4)); } P_SetMobjState(mobj, mobj->info->spawnstate); } else if (mobj->state == &states[mobj->info->deathstate] && mobj->tics == mobj->state->tics) - S_StartSound(0, sfx_bedie1 + (P_RandomFixed() & 1)); + S_StartSound(NULL, sfx_bedie1 + (P_RandomFixed() & 1)); } // Metal Sonic battle boss @@ -10711,7 +10711,7 @@ void P_SpawnPlayer(INT32 playernum) // the dead body mobj retains the skin through the 'spritedef' override). mobj->skin = &skins[p->skin]; - mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : 0); + mobj->localskin = (p->localskin ? K_GetPlayerSkin(p) : NULL); mobj->skinlocal = p->skinlocal; mobj->health = p->health; diff --git a/src/p_setup.c b/src/p_setup.c index bf40afe9d..612530882 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -1022,7 +1022,7 @@ void P_WriteThings(lumpnum_t lumpnum) size_t i, length; mapthing_t *mt; UINT8 *data; - savebuffer_t save = {0}; + savebuffer_t save = {}; INT16 temp; data = W_CacheLumpNum(lumpnum, PU_LEVEL); @@ -1166,7 +1166,7 @@ static void P_LoadLineDefs2(void) for (; i--; ld++) { ld->frontsector = sides[ld->sidenum[0]].sector; //e6y: Can't be -1 here - ld->backsector = ld->sidenum[1] != 0xffff ? sides[ld->sidenum[1]].sector : 0; + ld->backsector = ld->sidenum[1] != 0xffff ? sides[ld->sidenum[1]].sector : NULL; // Repeat count for midtexture if ((ld->flags & ML_EFFECT5) && (ld->sidenum[1] != 0xffff)) diff --git a/src/p_spec.c b/src/p_spec.c index 66901d234..5045a8287 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -4579,8 +4579,8 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) if (!sec->ffloors) { sec->ffloors = ffloor; - ffloor->next = 0; - ffloor->prev = 0; + ffloor->next = NULL; + ffloor->prev = NULL; return; } @@ -4588,7 +4588,7 @@ static inline void P_AddFFloorToList(sector_t *sec, ffloor_t *ffloor) rover->next = ffloor; ffloor->prev = rover; - ffloor->next = 0; + ffloor->next = NULL; } /** Adds a 3Dfloor. diff --git a/src/r_main.cpp b/src/r_main.cpp index 493105929..e470e5b5d 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -1087,7 +1087,7 @@ subsector_t *R_IsPointInSubsector(fixed_t x, fixed_t y) ret = &subsectors[nodenum & ~NF_SUBSECTOR]; for (i = 0; i < ret->numlines; i++) if (P_PointOnLineSide(x, y, segs[ret->firstline + i].linedef) != segs[ret->firstline + i].side) - return 0; + return NULL; return ret; } diff --git a/src/r_skins.c b/src/r_skins.c index 538b8c38a..41971788c 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -302,7 +302,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) if (player->mo) { - player->mo->localskin = 0; + player->mo->localskin = NULL; player->mo->skinlocal = false; } } diff --git a/src/r_things.cpp b/src/r_things.cpp index b62d9e5d7..f9e159843 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -532,8 +532,8 @@ void R_ClearSprites(void) visspritecount = numvisiblesprites = clippedvissprites = 0; } -static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; -static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; +static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; +static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {}; static void R_AllocVisSpriteChunkMemory(UINT32 chunk) { diff --git a/src/s_sound.c b/src/s_sound.c index e8075469c..7f931671d 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -884,7 +884,7 @@ static void S_StopChannel(INT32 cnum) if (cnum != i && c->sfxinfo == channels[i].sfxinfo) break; - c->sfxinfo = 0; + c->sfxinfo = NULL; } c->origin = NULL; @@ -1271,7 +1271,7 @@ static musicdef_t *S_AddMusicCredit(void) return &musicdefs[chunk][i]; } -struct cursongcredit cursongcredit = {0}; // Currently displayed song credit info +struct cursongcredit cursongcredit = {}; // Currently displayed song credit info static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicdef_t **defp) { @@ -1704,7 +1704,7 @@ static void S_UnloadMusic(void) music.flags = 0; music.looping = false; - music_refade_cv = 0; + music_refade_cv = NULL; } static boolean S_PlayMusic(boolean looping, UINT32 fadeinms) diff --git a/src/s_sound.h b/src/s_sound.h index 9e0296d2b..c7f487e92 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -253,9 +253,9 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 void S_ChangeMusicSpecial (const char *mmusic); -void S_SetRestoreMusicFadeInCvar (consvar_t *cvar); +void S_SetRestoreMusicFadeInCvar(consvar_t *cvar); #define S_ClearRestoreMusicFadeInCvar() \ - S_SetRestoreMusicFadeInCvar(0) + S_SetRestoreMusicFadeInCvar(NULL) int S_GetRestoreMusicFadeIn (void); // Stops the music. diff --git a/src/strcasestr.c b/src/strcasestr.c index d24a36e54..f50141dcf 100644 --- a/src/strcasestr.c +++ b/src/strcasestr.c @@ -73,8 +73,8 @@ nongnu_strcasestr (const char *s, const char *q) up = strchr(s, uc); lp = strchr(s, lc); - if (!( (intptr_t)up|(intptr_t)lp )) - return 0; + if (up == NULL || lp == NULL) + return NULL; if (!lp || ( up && up < lp )) { @@ -100,12 +100,12 @@ nongnu_strcasestr (const char *s, const char *q) if (trycmp(ppa, cpa, q, qn) == 0) return (*ppa); - if (!( (intptr_t)up|(intptr_t)lp )) + if (up == NULL || lp == NULL) break; if (!(*ppa) || ( (*ppb) && (*ppb) < (*ppa) )) swapp(&ppa, &ppb, &cpa, &cpb); } - return 0; + return NULL; } diff --git a/src/w_wad.c b/src/w_wad.c index 7e1ec30df..432f1421f 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -697,12 +697,12 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lump_p->name, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -1667,9 +1667,9 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si if (fread(rawData, 1, rawSize, handle) < rawSize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; + strm.zalloc = NULL; + strm.zfree = NULL; + strm.opaque = NULL; strm.total_in = strm.avail_in = rawSize; strm.total_out = strm.avail_out = decSize; @@ -2238,14 +2238,14 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? @@ -2483,14 +2483,14 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); // Strip away file address and extension for the 8char name. - if ((trimname = strrchr(fullname, '/')) != 0) + if ((trimname = strrchr(fullname, '/')) != NULL) trimname++; else trimname = fullname; // Care taken for root files. if (*trimname) // Ignore directories, well kinda { - if ((dotpos = strrchr(trimname, '.')) == 0) + if ((dotpos = strrchr(trimname, '.')) == NULL) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? diff --git a/src/y_inter.c b/src/y_inter.c index d35fa7825..27e794ffc 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -104,7 +104,7 @@ typedef struct } y_voteclient; // votescreen stuff -votescreen_t VoteScreen = {0}; +votescreen_t VoteScreen = {}; static y_votelvlinfo levelinfo[5]; static y_voteclient voteclient; @@ -1093,7 +1093,7 @@ void Y_VoteDrawer(void) V_DrawSmallScaledPatch(BASEVIDWIDTH-100, y, V_SNAPTORIGHT, pic); else { - V_DrawFixedPatch((BASEVIDWIDTH-20)< Date: Tue, 6 Jan 2026 12:54:25 +0100 Subject: [PATCH 23/42] Simplify textcmd handling --- src/d_clisrv.c | 43 ++++++++----------------------------------- 1 file changed, 8 insertions(+), 35 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 4da62742f..1ec57eaaf 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -212,14 +212,9 @@ tic_t firstconnectattempttime = 0; // engine -// Must be a power of two -#define TEXTCMD_HASH_SIZE 4 - typedef struct textcmdtic_s { - tic_t tic; UINT8 *playercmds[MAXPLAYERS]; - struct textcmdtic_s *next; } textcmdtic_t; typedef struct textcmdbuf_s textcmdbuf_t; @@ -234,7 +229,7 @@ static textcmdbuf_t *textcmdbuf[MAXSPLITSCREENPLAYERS] = {NULL}; static ticcmd_t playercmds[MAXPLAYERS]; ticcmd_t netcmds[BACKUPTICS][MAXPLAYERS] = {}; -static textcmdtic_t *textcmds[TEXTCMD_HASH_SIZE] = {NULL}; +static textcmdtic_t *textcmds[BACKUPTICS] = {NULL}; consvar_t cv_showjoinaddress = {"showjoinaddress", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -396,20 +391,10 @@ void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_ // Frees all textcmd memory for the specified tic static void D_FreeTextcmd(tic_t tic) { - textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - textcmdtic_t *textcmdtic = *tctprev; - - while (textcmdtic && textcmdtic->tic != tic) - { - tctprev = &textcmdtic->next; - textcmdtic = textcmdtic->next; - } + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; if (textcmdtic) { - // Remove this tic from the list. - *tctprev = textcmdtic->next; - // Free all players. for (INT32 i = 0; i < MAXPLAYERS; i++) { @@ -418,14 +403,14 @@ static void D_FreeTextcmd(tic_t tic) // Free this tic's own memory. Z_Free(textcmdtic); + textcmds[tic%BACKUPTICS] = NULL; } } // Gets the buffer for the specified ticcmd, or NULL if there isn't one static UINT8* D_GetExistingTextcmd(tic_t tic, INT32 playernum) { - textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - while (textcmdtic && textcmdtic->tic != tic) textcmdtic = textcmdtic->next; + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; // Do we have an entry for the tic? If so, look for player. if (textcmdtic) @@ -441,22 +426,11 @@ static UINT8* D_GetExistingTextcmd(tic_t tic, INT32 playernum) // Gets the buffer for the specified ticcmd, creating one if necessary static UINT8* D_GetTextcmd(tic_t tic, INT32 playernum) { - textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)]; - - // Look for the tic. - while (textcmdtic && textcmdtic->tic != tic) - { - tctprev = &textcmdtic->next; - textcmdtic = textcmdtic->next; - } + textcmdtic_t *textcmdtic = textcmds[tic%BACKUPTICS]; // If we don't have an entry for the tic, make it. if (!textcmdtic) - { - textcmdtic = *tctprev = (textcmdtic_t*)Z_Calloc(sizeof (textcmdtic_t), PU_STATIC, NULL); - textcmdtic->tic = tic; - } + textcmds[tic%BACKUPTICS] = textcmdtic = (textcmdtic_t*)Z_Calloc(sizeof(textcmdtic_t), PU_STATIC, NULL); // If we don't have an entry for the player, make it. if (!textcmdtic->playercmds[playernum]) @@ -540,9 +514,8 @@ void D_ResetTiccmds(void) } // Reset the net command list - for (i = 0; i < TEXTCMD_HASH_SIZE; i++) - while (textcmds[i]) - D_Clearticcmd(textcmds[i]->tic); + for (i = 0; i < BACKUPTICS; i++) + D_Clearticcmd(i); } void SendKick(UINT8 playernum, UINT8 msg) From 7dbb08315c820e4ee0ba90a3cbd1d43821110bc6 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 21 Jan 2026 20:48:04 +0100 Subject: [PATCH 24/42] fix cmake --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f09b95633..02dab08da 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -54,7 +54,7 @@ set(SRB2_CORE_SOURCES string.c tables.c v_video.c - w_wad.c + w_wad.cpp y_inter.c z_zone.cpp ) From 3e476d7658ed82ee22a6002f4d895e87bc62675c Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 27 Jan 2026 18:06:22 +0100 Subject: [PATCH 25/42] implement allowing to load addons and gamestate only instead of joining server really messy, needs some cleanup, not sure if this is good at all --- src/d_clisrv.c | 62 ++++++++++++++++++++++++++++++++++------------- src/d_clisrv.h | 2 ++ src/m_menu.c | 65 ++++++++++++++++++++++++++++++++++++++++---------- 3 files changed, 99 insertions(+), 30 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 68ab08c5a..31c309c17 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -100,6 +100,10 @@ static int map_icon_request_count; // current count of icon requests sent static UINT8 *map_icon_data; static patch_t *map_icon; +// if true, signals the game to only load addons AND gamestate +// instead of fully joining a server +boolean addonsonly = false; + plrinfo playerinfo[MAXPLAYERS] = {}; SINT8 joinnode = 0; // used for CL_VIEWSERVER @@ -1438,6 +1442,7 @@ static void CL_DrawConnectionStatus(void) // Buttons V_DrawFill(8, BASEVIDHEIGHT - 14, BASEVIDWIDTH - 16, 12, 239); V_DrawThinString(16, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sESC%s] = Abort", "\x82", "\x80")); + V_DrawCenteredThinString(BASEVIDWIDTH/2, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sSPACE%s] = Load Addons", "\x82", "\x80")); V_DrawRightAlignedThinString(BASEVIDWIDTH - 12, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sENTER%s] = Join", "\x82", "\x80")); } else if (filedownload.current != -1) @@ -2579,7 +2584,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) return true; } - cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = (cv_serverinfoscreen.value && !addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; } else { @@ -2600,6 +2605,17 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) return true; } +static void FreeMapIcon(void) +{ + if (map_icon != NULL) + Patch_Free(map_icon); + map_icon = NULL; + if (map_icon_data != NULL) + Z_Free(map_icon_data); + map_icon_data = NULL; + map_icon_request_count = 0; +} + /** Called by CL_ConnectToServer * * \param tmpsave The name of the gamestate file??? @@ -2624,7 +2640,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic case CL_ASKFULLFILELIST: if (cl_lastcheckedfilecount == UINT16_MAX) // All files retrieved - cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = (cv_serverinfoscreen.value && !addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; else if (fileneedednum != cl_lastcheckedfilecount || I_GetTime() >= *asksent) { if (CL_AskFileList(fileneedednum)) @@ -2757,7 +2773,19 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { // Gamestate is now handled within CL_LoadReceivedSavegame() CL_LoadReceivedSavegame(false); - cl_mode = CL_CONNECTED; + + if (addonsonly) + { + // close connection after savegame load + // we want the actual server state + // in case theres some stuff like records to be synched + cl_mode = CL_ABORTED; + } + else + { + cl_mode = CL_CONNECTED; + } + break; } // don't break case continue to CL_CONNECTED else @@ -2771,7 +2799,6 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic case CL_ABORTED: cl_mode = CL_SEARCHING; return false; - } GetPackets(); @@ -2793,24 +2820,20 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { if (key == KEY_ENTER || key == KEY_JOY1) { + addonsonly = false; cl_mode = CL_CHECKFILES; - if (map_icon != NULL) - Patch_Free(map_icon); - map_icon = NULL; - if (map_icon_data != NULL) - Z_Free(map_icon_data); - map_icon_data = NULL; + FreeMapIcon(); } else if (key == KEY_ESCAPE || key == KEY_JOY1+1) { cl_mode = CL_ABORTED; - if (map_icon != NULL) - Patch_Free(map_icon); - map_icon = NULL; - if (map_icon_data != NULL) - Z_Free(map_icon_data); - map_icon_data = NULL; - map_icon_request_count = 0; + FreeMapIcon(); + } + else if (key == KEY_SPACE || key == KEY_JOY1+2) + { + addonsonly = true; + cl_mode = CL_CHECKFILES; + FreeMapIcon(); } } @@ -2819,6 +2842,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { CONS_Printf(M_GetText("Network game synchronization aborted.\n")); CL_AbortConnection(); + addonsonly = false; return false; } @@ -3315,6 +3339,10 @@ static void Command_connect(void) CONS_Alert(CONS_ERROR, M_GetText("There is no network driver\n")); } + // idk how that shit works + //if (*COM_Argv(3) && fasticmp(COM_Argv(3), "-addonsonly")) + //addonsonly = true; + CV_Set(&cv_lastserver, I_GetNodeAddress(servernode)); if (splitscreen != cv_splitplayers.value-1) diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 430729bc2..13a8470dc 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -552,6 +552,8 @@ typedef enum KR_LEAVE, //Quit the game } kickreason_t; +extern boolean addonsonly; + /* the max number of name changes in some time period */ #define MAXNAMECHANGES (5) #define NAMECHANGERATE (60*TICRATE) diff --git a/src/m_menu.c b/src/m_menu.c index a98a230d5..a0c501af8 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -186,8 +186,8 @@ static INT16 itemOn = 1; // menu item skull is on, Hack by Tails 09-18-2002 static INT16 skullAnimCounter = 10; // skull animation counter static boolean interpTimerHackAllow = 0; -static UINT8 setupcontrolplayer; -static INT32 (*setupcontrols)[2]; // pointer to the gamecontrols of the player being edited +static UINT8 setupcontrolplayer; +static INT32 (*setupcontrols)[2]; // pointer to the gamecontrols of the player being edited // shhh... what am I doing... nooooo! static INT32 vidm_testingmode = 0; @@ -201,8 +201,8 @@ static char setupm_ip[64]; static textinput_t setupm_input_ip; -static fixed_t multi_tics; -static state_t *multi_state; +static fixed_t multi_tics; +static state_t *multi_state; // this is set before entering the MultiPlayer setup menu, // for either player 1 or 2 @@ -1024,9 +1024,9 @@ boolean M_Responder(event_t *ev) //case KEY_JOY1 + 2: ch = KEY_ENTER; break; - /*case KEY_JOY1 + 3: // Brake can function as 'n' for message boxes now. - ch = 'n'; - break;*/ + /*case KEY_JOY1 + 3: // Brake can function as 'n' for message boxes now. + ch = 'n'; + break;*/ case KEY_MOUSE1 + 1: //case KEY_JOY1 + 1: ch = KEY_BACKSPACE; @@ -1250,6 +1250,20 @@ boolean M_Responder(event_t *ev) routine = currentMenu->menuitems[itemOn].itemaction; + // really hacky but the whole menu system sucks so + // allows to just load addons and gamestate instead of joining + if (currentMenu == &MP_ConnectDef && + (routine && routine == M_Connect) && + (ch == gamecontrol[0][gc_lookback][0] || + ch == gamecontrol[0][gc_lookback][1])) + { + addonsonly = true; + noFurtherInput = true; + currentMenu->lastOn = itemOn; + routine(itemOn); + return true; + } + // Handle menuitems which need a specific key handling if (routine && (currentMenu->menuitems[itemOn].status & IT_TYPE) == IT_KEYHANDLER) { @@ -1305,12 +1319,21 @@ boolean M_Responder(event_t *ev) { playback_last_menu_interaction_leveltime = leveltime; // Flip left/right with up/down for the playback menu, since it's a horizontal icon row. + switch (ch) { - case KEY_LEFTARROW: ch = KEY_UPARROW; break; - case KEY_UPARROW: ch = KEY_RIGHTARROW; break; - case KEY_RIGHTARROW: ch = KEY_DOWNARROW; break; - case KEY_DOWNARROW: ch = KEY_LEFTARROW; break; + case KEY_LEFTARROW: + ch = KEY_UPARROW; + break; + case KEY_UPARROW: + ch = KEY_RIGHTARROW; + break; + case KEY_RIGHTARROW: + ch = KEY_DOWNARROW; + break; + case KEY_DOWNARROW: + ch = KEY_LEFTARROW; + break; // arbitrary keyboard shortcuts because fuck you @@ -1361,7 +1384,8 @@ boolean M_Responder(event_t *ev) G_AdjustView(4, 1, true); break; - default: break; + default: + break; } } @@ -1486,6 +1510,7 @@ boolean M_Responder(event_t *ev) } return false; + break; default: CON_Responder(ev); @@ -7059,6 +7084,21 @@ static void M_DrawConnectMenu(void) M_DrawServerLines(currentMenu->x, serverlistpage); } + // copy pasted this abomination from encore toggle + if (itemOn > mp_connect_search) + { + char addontoggle[32] = {0}; + const char *item1 = gamecontrol[0][gc_lookback][0] != 0 ? G_KeynumToString(gamecontrol[0][gc_lookback][0]) : NULL; + const char *item2 = gamecontrol[0][gc_lookback][1] != 0 ? G_KeynumToString(gamecontrol[0][gc_lookback][1]) : NULL; + + if (item1 != NULL && item2 != NULL) + snprintf(addontoggle, 32, "%s/%s - Load Addons Only", item1, item2); + else + snprintf(addontoggle, 32, "%s - Load Addons Only", item1 != NULL ? item1 : item2 != NULL ? item2 : "Lookback"); + + V_DrawThinString(1, BASEVIDHEIGHT-8-1, V_SNAPTOLEFT|V_SNAPTOBOTTOM|V_TRANSLUCENT|V_ALLOWLOWERCASE, addontoggle); + } + INT32 input_y = currentMenu->menuitems[mp_connect_search].alphaKey; V_DrawFill(currentMenu->x, currentMenu->y+input_y, MAXSTRINGLENGTH*8+6, 8+6, 239); @@ -10046,7 +10086,6 @@ static void M_DrawVideoMode(void) va("Wait %d second%s", testtime, (testtime > 1) ? "s" : "")); M_CentreText(OP_VideoModeDef.y + 158, "or press ESC to return"); - } else { From f12b55f63bad96e2b288ce4dfa0170da0d17b899 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 27 Jan 2026 18:08:12 +0100 Subject: [PATCH 26/42] rename addonsonly variable to cl_addonsonly very generic name so add the prefix for whatever cl means --- src/d_clisrv.c | 17 +++++++++-------- src/d_clisrv.h | 2 +- src/m_menu.c | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 31c309c17..3bc5428b4 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -102,7 +102,7 @@ static patch_t *map_icon; // if true, signals the game to only load addons AND gamestate // instead of fully joining a server -boolean addonsonly = false; +boolean cl_addonsonly = false; plrinfo playerinfo[MAXPLAYERS] = {}; SINT8 joinnode = 0; // used for CL_VIEWSERVER @@ -2584,7 +2584,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) return true; } - cl_mode = (cv_serverinfoscreen.value && !addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = (cv_serverinfoscreen.value && !cl_addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; } else { @@ -2640,7 +2640,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic case CL_ASKFULLFILELIST: if (cl_lastcheckedfilecount == UINT16_MAX) // All files retrieved - cl_mode = (cv_serverinfoscreen.value && !addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = (cv_serverinfoscreen.value && !cl_addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; else if (fileneedednum != cl_lastcheckedfilecount || I_GetTime() >= *asksent) { if (CL_AskFileList(fileneedednum)) @@ -2774,7 +2774,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic // Gamestate is now handled within CL_LoadReceivedSavegame() CL_LoadReceivedSavegame(false); - if (addonsonly) + if (cl_addonsonly) { // close connection after savegame load // we want the actual server state @@ -2820,18 +2820,19 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { if (key == KEY_ENTER || key == KEY_JOY1) { - addonsonly = false; + cl_addonsonly = false; cl_mode = CL_CHECKFILES; FreeMapIcon(); } else if (key == KEY_ESCAPE || key == KEY_JOY1+1) { cl_mode = CL_ABORTED; + cl_addonsonly = false; FreeMapIcon(); } else if (key == KEY_SPACE || key == KEY_JOY1+2) { - addonsonly = true; + cl_addonsonly = true; cl_mode = CL_CHECKFILES; FreeMapIcon(); } @@ -2842,7 +2843,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { CONS_Printf(M_GetText("Network game synchronization aborted.\n")); CL_AbortConnection(); - addonsonly = false; + cl_addonsonly = false; return false; } @@ -3341,7 +3342,7 @@ static void Command_connect(void) // idk how that shit works //if (*COM_Argv(3) && fasticmp(COM_Argv(3), "-addonsonly")) - //addonsonly = true; + //cl_addonsonly = true; CV_Set(&cv_lastserver, I_GetNodeAddress(servernode)); diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 13a8470dc..a4466fbc3 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -552,7 +552,7 @@ typedef enum KR_LEAVE, //Quit the game } kickreason_t; -extern boolean addonsonly; +extern boolean cl_addonsonly; /* the max number of name changes in some time period */ #define MAXNAMECHANGES (5) diff --git a/src/m_menu.c b/src/m_menu.c index a0c501af8..378aec970 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -1257,7 +1257,7 @@ boolean M_Responder(event_t *ev) (ch == gamecontrol[0][gc_lookback][0] || ch == gamecontrol[0][gc_lookback][1])) { - addonsonly = true; + cl_addonsonly = true; noFurtherInput = true; currentMenu->lastOn = itemOn; routine(itemOn); From 00bc8bc149e2523f68b3b06a1a9028a839e7cf2b Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 27 Jan 2026 18:23:44 +0100 Subject: [PATCH 27/42] limit addon only stuff to server info screen quite honestly everything else is awful and i dont want to bother with it --- src/d_clisrv.c | 10 +++------- src/d_clisrv.h | 2 -- src/m_menu.c | 29 ----------------------------- 3 files changed, 3 insertions(+), 38 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 3bc5428b4..09a9f85c7 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -102,7 +102,7 @@ static patch_t *map_icon; // if true, signals the game to only load addons AND gamestate // instead of fully joining a server -boolean cl_addonsonly = false; +static boolean cl_addonsonly = false; plrinfo playerinfo[MAXPLAYERS] = {}; SINT8 joinnode = 0; // used for CL_VIEWSERVER @@ -2584,7 +2584,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent) return true; } - cl_mode = (cv_serverinfoscreen.value && !cl_addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = cv_serverinfoscreen.value ? CL_VIEWSERVER : CL_CHECKFILES; } else { @@ -2640,7 +2640,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic case CL_ASKFULLFILELIST: if (cl_lastcheckedfilecount == UINT16_MAX) // All files retrieved - cl_mode = (cv_serverinfoscreen.value && !cl_addonsonly) ? CL_VIEWSERVER : CL_CHECKFILES; + cl_mode = cv_serverinfoscreen.value ? CL_VIEWSERVER : CL_CHECKFILES; else if (fileneedednum != cl_lastcheckedfilecount || I_GetTime() >= *asksent) { if (CL_AskFileList(fileneedednum)) @@ -3340,10 +3340,6 @@ static void Command_connect(void) CONS_Alert(CONS_ERROR, M_GetText("There is no network driver\n")); } - // idk how that shit works - //if (*COM_Argv(3) && fasticmp(COM_Argv(3), "-addonsonly")) - //cl_addonsonly = true; - CV_Set(&cv_lastserver, I_GetNodeAddress(servernode)); if (splitscreen != cv_splitplayers.value-1) diff --git a/src/d_clisrv.h b/src/d_clisrv.h index a4466fbc3..430729bc2 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -552,8 +552,6 @@ typedef enum KR_LEAVE, //Quit the game } kickreason_t; -extern boolean cl_addonsonly; - /* the max number of name changes in some time period */ #define MAXNAMECHANGES (5) #define NAMECHANGERATE (60*TICRATE) diff --git a/src/m_menu.c b/src/m_menu.c index 378aec970..134c89739 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -1250,20 +1250,6 @@ boolean M_Responder(event_t *ev) routine = currentMenu->menuitems[itemOn].itemaction; - // really hacky but the whole menu system sucks so - // allows to just load addons and gamestate instead of joining - if (currentMenu == &MP_ConnectDef && - (routine && routine == M_Connect) && - (ch == gamecontrol[0][gc_lookback][0] || - ch == gamecontrol[0][gc_lookback][1])) - { - cl_addonsonly = true; - noFurtherInput = true; - currentMenu->lastOn = itemOn; - routine(itemOn); - return true; - } - // Handle menuitems which need a specific key handling if (routine && (currentMenu->menuitems[itemOn].status & IT_TYPE) == IT_KEYHANDLER) { @@ -7084,21 +7070,6 @@ static void M_DrawConnectMenu(void) M_DrawServerLines(currentMenu->x, serverlistpage); } - // copy pasted this abomination from encore toggle - if (itemOn > mp_connect_search) - { - char addontoggle[32] = {0}; - const char *item1 = gamecontrol[0][gc_lookback][0] != 0 ? G_KeynumToString(gamecontrol[0][gc_lookback][0]) : NULL; - const char *item2 = gamecontrol[0][gc_lookback][1] != 0 ? G_KeynumToString(gamecontrol[0][gc_lookback][1]) : NULL; - - if (item1 != NULL && item2 != NULL) - snprintf(addontoggle, 32, "%s/%s - Load Addons Only", item1, item2); - else - snprintf(addontoggle, 32, "%s - Load Addons Only", item1 != NULL ? item1 : item2 != NULL ? item2 : "Lookback"); - - V_DrawThinString(1, BASEVIDHEIGHT-8-1, V_SNAPTOLEFT|V_SNAPTOBOTTOM|V_TRANSLUCENT|V_ALLOWLOWERCASE, addontoggle); - } - INT32 input_y = currentMenu->menuitems[mp_connect_search].alphaKey; V_DrawFill(currentMenu->x, currentMenu->y+input_y, MAXSTRINGLENGTH*8+6, 8+6, 239); From c84724da37c5700c8d83c46304e0bc22ce316f1c Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 8 Feb 2026 20:29:01 +0100 Subject: [PATCH 28/42] make lumpnumcache case sensitive + optimize + replace quickncase hash with FNV1a lumpnumcache can be case sensitive W_CheckNumForName should also look for uppercase stuff and W_LumpExists is case sensitive anyways this avoids having to always account for case (toupper/tolower) during hash and string comparisons and even allows us to even directly compare our strings instead of using fastcmp (std::strings allow this!) from some benchmarking externally this makes this faster quite a bit --- src/doomdef.h | 16 ---------------- src/m_misc.c | 16 ++++++++++++++++ src/m_misc.h | 1 + src/r_data.c | 6 +++--- src/s_sound.c | 4 ++-- src/w_wad.cpp | 31 ++++++++++--------------------- src/w_wad.h | 2 -- 7 files changed, 32 insertions(+), 44 deletions(-) diff --git a/src/doomdef.h b/src/doomdef.h index 23768d0f4..445b6951f 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -516,22 +516,6 @@ extern boolean capslock; // i_system.c, replace getchar() once the keyboard has been appropriated INT32 I_GetKey(void); -/* http://www.cse.yorku.ca/~oz/hash.html */ -static inline -UINT32 quickncasehash (const char *p, size_t n) -{ - size_t i = 0; - UINT32 x = 5381; - - while (i < n && p[i]) - { - x = (x * 33) ^ tolower(p[i]); - i++; - } - - return x; -} - #ifndef __cplusplus #ifndef min // Double-Check with WATTCP-32's cdefs.h #define min(x, y) (((x) < (y)) ? (x) : (y)) diff --git a/src/m_misc.c b/src/m_misc.c index 8c7b34163..bd038a488 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -1956,6 +1956,22 @@ UINT32 FNV1a_Hash(const char *message, size_t size) return hash; } +// Behaves like the old quickncasehash +// Stops either if it encounters null terminator +// or reaches size +UINT32 FNV1a_QuickCaseHash(const char *message, size_t size) +{ + UINT32 hash = FNV1A_OFFSET_BASIS; + + for (size_t i = 0; i < size && message[i]; i++) + { + hash ^= tolower(message[i]); + hash *= FNV1A_PRIME; + } + + return hash; +} + UINT32 FNV1a_HashString(const char *message) { UINT32 hash = FNV1A_OFFSET_BASIS; diff --git a/src/m_misc.h b/src/m_misc.h index ab7c8986f..813e8abf1 100644 --- a/src/m_misc.h +++ b/src/m_misc.h @@ -123,6 +123,7 @@ FUNCMATH UINT8 M_CountBits(UINT32 num, UINT8 size); // Hashes some message using FNV-1a UINT32 FNV1a_Hash(const char *message, size_t size); +UINT32 FNV1a_QuickCaseHash(const char *message, size_t size); UINT32 FNV1a_HashString(const char *message); UINT32 FNV1a_HashLowercaseString(const char *message); diff --git a/src/r_data.c b/src/r_data.c index 386f0e700..a99218765 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -622,7 +622,7 @@ Rloadtextures (INT32 i, INT32 w) // Set texture properties. memcpy(texture->name, W_CheckNameForNumPwad(wadnum, lumpnum), sizeof(texture->name)); - texture->hash = quickncasehash(texture->name, 8); + texture->hash = FNV1a_QuickCaseHash(texture->name, 8); texture->width = SHORT(patchlump.width); texture->height = SHORT(patchlump.height); @@ -1066,7 +1066,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) // Allocate memory for a zero-patch texture. Obviously, we'll be adding patches momentarily. resultTexture = (texture_t *)Z_Calloc(sizeof(texture_t), PU_STATIC, NULL); memcpy(resultTexture->name, newTextureName, 8); - resultTexture->hash = quickncasehash(newTextureName, 8); + resultTexture->hash = FNV1a_QuickCaseHash(newTextureName, 8); resultTexture->width = newTextureWidth; resultTexture->height = newTextureHeight; resultTexture->type = TEXTURETYPE_COMPOSITE; @@ -1756,7 +1756,7 @@ INT32 R_CheckTextureNumForName(const char *name) if (name[0] == '-') return 0; - hash = quickncasehash(name, 8); + hash = FNV1a_QuickCaseHash(name, 8); for (i = 0; i < tidcachelen; i++) if (tidcache[i].hash == hash && !strncasecmp(tidcache[i].name, name, 8)) diff --git a/src/s_sound.c b/src/s_sound.c index 7f931671d..206b5c37c 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -1302,7 +1302,7 @@ static boolean ReadMusicDefFields(UINT16 wadnum, int line, char *stoken, musicde STRBUFCPY(def->name, value); strlwr(def->name); - def->hash = quickncasehash (def->name, 6); + def->hash = FNV1a_QuickCaseHash(def->name, 6); } (*defp) = def; @@ -1484,7 +1484,7 @@ void S_InitMusicDefs(void) // musicdef_t *S_FindMusicCredit(const char *musname) { - UINT32 hash = quickncasehash(musname, 6); + UINT32 hash = FNV1a_QuickCaseHash(musname, 6); musicdef_t *def; for (INT32 i = 0; i < nummusicdefs; ++i) diff --git a/src/w_wad.cpp b/src/w_wad.cpp index bbf543f1d..44fece4a7 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.cpp @@ -99,7 +99,7 @@ struct LumpnumNameHash std::size_t operator()(const std::string& str) const { // hopefully this is fast enough but should be - return static_cast(quickncasehash(str.c_str(), str.length())); + return static_cast(FNV1a_Hash(str.c_str(), str.length())); } }; @@ -107,8 +107,8 @@ struct LumpnumStringEquals { bool operator()(const std::string& str1, const std::string& str2) const { - // fasticmp should be plenty fast and ignores case - return fasticmp(str1.c_str(), str2.c_str()); + //return fastcmp(str1.c_str(), str2.c_str()); + return str1 == str2; } }; @@ -377,12 +377,12 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) } // Invalidates the cache of lump numbers. Call this whenever a wad is added. -static void W_InvalidateLumpnumCache(void) +FUNCINLINE static ATTRINLINE void W_InvalidateLumpnumCache(void) { lumpnumcache.clear(); } -UINT32 W_HashLumpName(const char *name) +FUNCINLINE static ATTRINLINE UINT32 W_HashLumpName(const char *name) { return FNV1a_HashLowercaseString(name); } @@ -1246,7 +1246,7 @@ UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) return INT16_MAX; } -static lumpnum_t CheckLumpInCache(const char *name) +FUNCINLINE static ATTRINLINE lumpnum_t CheckLumpInCache(const char *name) { auto it = lumpnumcache.find(name); if (it != lumpnumcache.end()) @@ -1255,9 +1255,9 @@ static lumpnum_t CheckLumpInCache(const char *name) return LUMPERROR; } -static void AddLumpToCache(lumpnum_t lumpnum, const char *name) +FUNCINLINE static ATTRINLINE void AddLumpToCache(lumpnum_t lumpnum, const char *name) { - lumpnumcache.insert({name, lumpnum}); + lumpnumcache.emplace(name, lumpnum); } // @@ -1415,21 +1415,10 @@ UINT8 W_LumpExists(const char *name) UINT32 hash; size_t namelen; + // Check the lumpnumcache first. lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) - { - // ok ok, we did find a lump in our lumpcache BUTT - // the lumpcache map is case insensitive - // extract the lumpinfo out of the lumpnum - // so we can do one more extra case ~sensitive~ name compare - // otherwise we gotta fall through to our manual lump search below - // lumpnum == (wadnum << 16) | lumpinfo id - UINT16 wadnum = (cachenum >> 16) & 0xFFFF; - UINT16 lumpid = cachenum & 0xFFFF; - lumpinfo_t *lump_p = &wadfiles[wadnum]->lumpinfo[lumpid]; - if (fastcmp(lump_p->name, name)) - return true; - } + return cachenum; namelen = strlen(name); hash = W_HashLumpName(name); diff --git a/src/w_wad.h b/src/w_wad.h index 75c7e9c04..d21afb982 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -174,8 +174,6 @@ INT32 W_AddAutoloadedLocalFiles(char **filenames); #define W_FileHasFolders(wadfile) ((wadfile)->type == RET_PK3) -UINT32 W_HashLumpName(const char *name); - const char *W_CheckNameForNumPwad(UINT16 wad, UINT16 lump); const char *W_CheckNameForNum(lumpnum_t lumpnum); From cd02242a014cbb21366ab65352d01d3dedf3a012 Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 23 Feb 2026 17:01:14 +0100 Subject: [PATCH 29/42] fix splitscreen clients being unable to join saturn servers lmao oops idk dumb copy paste sry --- src/d_clisrv.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 1ec57eaaf..27206b337 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4121,7 +4121,7 @@ static void Command_ResendGamestate(void) } playernum = nametonum(COM_Argv(1)); - if (playernum == -1 || playernum == 0) + if (playernum <= 0) return; doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); @@ -4591,7 +4591,7 @@ static boolean SV_AddWaitingPlayers(SINT8 node) for (n = 0; n < MAXNETNODES; n++) { - if (nodetoplayer[n] == newplayernum || + if (nodetoplayer[n] == newplayernum || nodetoplayer2[n] == newplayernum || nodetoplayer3[n] == newplayernum || nodetoplayer4[n] == newplayernum) @@ -4883,10 +4883,6 @@ static const char *GetRefuseMessage(SINT8 node) { return va("Maximum players reached: %d", maxplayers); } - else if (cc->localplayers != 1) - { - return "Wrong player count."; - } else if (netgame && !cc->localplayers) // Stealth join? { return "No players from\nthis node."; From 014a22e9336e4b5d34bdda2afbd61ca12de07c7a Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 24 Feb 2026 16:06:27 +0100 Subject: [PATCH 30/42] w_wad: replace unordered_map with verstable hashmap for lumpnumcache + convert back to C from C++ been rethinking this and been doing some digging online the unordered_map was just a quick and simple fix for performance issues in blan, but came with caveats: - unordered_map is simple to use but not particulary great in terms of performance during lookups especially - we needed to convert w_wad to c++ just for the lumpnumcache - due to needing to preserve the key since they gotta outlive the scope of the function that inserts things into the map, we effectively did a string copy on each map insert and lookup after some research came across verstable, which is basically almost the exact same as unordered map but in C while being extremely fast (even more with its builtin string hash and comparisor) only caveat with verstable is we need to rely on a new lib, though its just a single header file, and we gotta manage ensuring the input keys outlive functionscope ourselves, which we do with strdup in this case good thing, verstable allows to call a "destructor" specified by us whenever it removes or replaces keys in the map this also means we only need to copy strings on insert and not on lookup anymore all in all this is much faster while giving us the simple usage of c++ unordered_map while staying in C due to the strdup quirk i had to slightly modify verstable to allow to take const as inputs for the getter functions even if the keys themselves are not const marked with "KEY_GET_CONST" Verstable can be found here: https://github.com/JacksonAllan/Verstable and is licensed under MIT which is perfect! --- src/Sourcefile | 2 +- src/dedicated/i_system.c | 1 + src/sdl/i_system.cpp | 3 + src/verstable.h | 2119 ++++++++++++++++++++++++++++++++++++ src/{w_wad.cpp => w_wad.c} | 236 ++-- src/w_wad.h | 2 +- 6 files changed, 2248 insertions(+), 115 deletions(-) create mode 100644 src/verstable.h rename src/{w_wad.cpp => w_wad.c} (90%) diff --git a/src/Sourcefile b/src/Sourcefile index 2c4024f5f..08c18ebf0 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -45,7 +45,7 @@ sounds.c st_stuff.c tables.c v_video.c -w_wad.cpp +w_wad.c y_inter.c z_zone.cpp r_bsp.cpp diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index f6450134c..ddc17d6a5 100644 --- a/src/dedicated/i_system.c +++ b/src/dedicated/i_system.c @@ -1384,6 +1384,7 @@ static void I_Fork(void) INT32 I_StartupSystem(void) { + W_Startup(); I_StartupConsole(); #ifdef NEWSIGNALHANDLER // This is useful when debugging. It lets GDB attach to diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 5310cc855..407e5c3a0 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -1886,6 +1886,9 @@ INT32 I_StartupSystem(void) SDL_version SDLlinked; SDL_VERSION(&SDLcompiled) SDL_GetVersion(&SDLlinked); + + W_Startup(); + I_StartupConsole(); #ifdef NEWSIGNALHANDLER // This is useful when debugging. It lets GDB attach to diff --git a/src/verstable.h b/src/verstable.h new file mode 100644 index 000000000..8c5a49dc3 --- /dev/null +++ b/src/verstable.h @@ -0,0 +1,2119 @@ +/*------------------------------------------------- VERSTABLE v2.2.1 --------------------------------------------------- + +Verstable is a C99-compatible, open-addressing hash table using quadratic probing and the following additions: + +* All keys that hash (i.e. "belong") to the same bucket (their "home bucket") are linked together by an 11-bit integer + specifying the quadratic displacement, relative to that bucket, of the next key in the chain. + +* If a chain of keys exists for a given bucket, then it always begins at that bucket. To maintain this policy, a 1-bit + flag is used to mark whether the key occupying a bucket belongs there. When inserting a new key, if the bucket it + belongs to is occupied by a key that does not belong there, then the occupying key is evicted and the new key takes + the bucket. + +* A 4-bit fragment of each key's hash code is also stored. + +* The aforementioned metadata associated with each bucket (the 4-bit hash fragment, the 1-bit flag, and the 11-bit link + to the next key in the chain) are stored together in a uint16_t array rather than in the bucket alongside the key and + (optionally) the value. + +One way to conceptualize this scheme is as a chained hash table in which overflowing keys are stored not in separate +memory allocations but in otherwise unused buckets. In this regard, it shares similarities with Malte Skarupke's Bytell +hash table (https://www.youtube.com/watch?v=M2fKMP47slQ) and traditional "coalesced hashing". + +Advantages of this scheme include: + +* Fast lookups impervious to load factor: If the table contains any key belonging to the lookup key's home bucket, then + that bucket contains the first in a traversable chain of all keys belonging to it. Hence, only the home bucket and + other buckets containing keys belonging to it are ever probed. Moreover, the stored hash fragments allow skipping most + non-matching keys in the chain without accessing the actual buckets array or calling the (potentially expensive) key + comparison function. + +* Fast insertions: Insertions are faster than they are in other schemes that move keys around (e.g. Robin Hood) because + they only move, at most, one existing key. + +* Fast, tombstone-free deletions: Deletions, which usually require tombstones in quadratic-probing hash tables, are + tombstone-free and only move, at most, one existing key. + +* Fast iteration: The separate metadata array allows keys in sparsely populated tables to be found without incurring the + frequent cache misses that would result from traversing the buckets array. + +Usage example: + + +---------------------------------------------------------+----------------------------------------------------------+ + | Using the generic macro API (C11 and later): | Using the prefixed functions API (C99 and later): | + +---------------------------------------------------------+----------------------------------------------------------+ + | #include | #include | + | | | + | // Instantiating a set template. | // Instantiating a set template. | + | #define NAME int_set | #define NAME int_set | + | #define KEY_TY int | #define KEY_TY int | + | #include "verstable.h" | #define HASH_FN vt_hash_integer | + | | #define CMPR_FN vt_cmpr_integer | + | // Instantiating a map template. | #include "verstable.h" | + | #define NAME int_int_map | | + | #define KEY_TY int | // Instantiating a map template. | + | #define VAL_TY int | #define NAME int_int_map | + | #include "verstable.h" | #define KEY_TY int | + | | #define VAL_TY int | + | int main( void ) | #define HASH_FN vt_hash_integer | + | { | #define CMPR_FN vt_cmpr_integer | + | // Set. | #include "verstable.h" | + | | | + | int_set our_set; | int main( void ) | + | vt_init( &our_set ); | { | + | | // Set. | + | // Inserting keys. | | + | for( int i = 0; i < 10; ++i ) | int_set our_set; | + | { | int_set_init( &our_set ); | + | int_set_itr itr = vt_insert( &our_set, i ); | | + | if( vt_is_end( itr ) ) | // Inserting keys. | + | { | for( int i = 0; i < 10; ++i ) | + | // Out of memory, so abort. | { | + | vt_cleanup( &our_set ); | int_set_itr itr = | + | return 1; | int_set_insert( &our_set, i ); | + | } | if( int_set_is_end( itr ) ) | + | } | { | + | | // Out of memory, so abort. | + | // Erasing keys. | int_set_cleanup( &our_set ); | + | for( int i = 0; i < 10; i += 3 ) | return 1; | + | vt_erase( &our_set, i ); | } | + | | } | + | // Retrieving keys. | | + | for( int i = 0; i < 10; ++i ) | // Erasing keys. | + | { | for( int i = 0; i < 10; i += 3 ) | + | int_set_itr itr = vt_get( &our_set, i ); | int_set_erase( &our_set, i ); | + | if( !vt_is_end( itr ) ) | | + | printf( "%d ", itr.data->key ); | // Retrieving keys. | + | } | for( int i = 0; i < 10; ++i ) | + | // Printed: 1 2 4 5 7 8 | { | + | | int_set_itr itr = int_set_get( &our_set, i ); | + | // Iteration. | if( !int_set_is_end( itr ) ) | + | for( | printf( "%d ", itr.data->key ); | + | int_set_itr itr = vt_first( &our_set ); | } | + | !vt_is_end( itr ); | // Printed: 1 2 4 5 7 8 | + | itr = vt_next( itr ) | | + | ) | // Iteration. | + | printf( "%d ", itr.data->key ); | for( | + | // Printed: 2 4 7 1 5 8 | int_set_itr itr = | + | | int_set_first( &our_set ); | + | vt_cleanup( &our_set ); | !int_set_is_end( itr ); | + | | itr = int_set_next( itr ) | + | // Map. | ) | + | | printf( "%d ", itr.data->key ); | + | int_int_map our_map; | // Printed: 2 4 7 1 5 8 | + | vt_init( &our_map ); | | + | | int_set_cleanup( &our_set ); | + | // Inserting keys and values. | | + | for( int i = 0; i < 10; ++i ) | // Map. | + | { | | + | int_int_map_itr itr = | int_int_map our_map; | + | vt_insert( &our_map, i, i + 1 ); | int_int_map_init( &our_map ); | + | if( vt_is_end( itr ) ) | | + | { | // Inserting keys and values. | + | // Out of memory, so abort. | for( int i = 0; i < 10; ++i ) | + | vt_cleanup( &our_map ); | { | + | return 1; | int_int_map_itr itr = | + | } | int_int_map_insert( &our_map, i, i + 1 ); | + | } | if( int_int_map_is_end( itr ) ) | + | | { | + | // Erasing keys and values. | // Out of memory, so abort. | + | for( int i = 0; i < 10; i += 3 ) | int_int_map_cleanup( &our_map ); | + | vt_erase( &our_map, i ); | return 1; | + | | } | + | // Retrieving keys and values. | } | + | for( int i = 0; i < 10; ++i ) | | + | { | // Erasing keys and values. | + | int_int_map_itr itr = vt_get( &our_map, i ); | for( int i = 0; i < 10; i += 3 ) | + | if( !vt_is_end( itr ) ) | int_int_map_erase( &our_map, i ); | + | printf( | | + | "%d:%d ", | // Retrieving keys and values. | + | itr.data->key, | for( int i = 0; i < 10; ++i ) | + | itr.data->val | { | + | ); | int_int_map_itr itr = | + | } | int_int_map_get( &our_map, i ); | + | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | if( !int_int_map_is_end( itr ) ) | + | | printf( | + | // Iteration. | "%d:%d ", | + | for( | itr.data->key, | + | int_int_map_itr itr = vt_first( &our_map ); | itr.data->val | + | !vt_is_end( itr ); | ); | + | itr = vt_next( itr ) | } | + | ) | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | + | printf( | | + | "%d:%d ", | // Iteration. | + | itr.data->key, | for( | + | itr.data->val | int_int_map_itr itr = | + | ); | int_int_map_first( &our_map ); | + | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | !int_int_map_is_end( itr ); | + | | itr = int_int_map_next( itr ) | + | vt_cleanup( &our_map ); | ) | + | } | printf( | + | | "%d:%d ", | + | | itr.data->key, | + | | itr.data->val | + | | ); | + | | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | + | | | + | | int_int_map_cleanup( &our_map ); | + | | } | + | | | + +---------------------------------------------------------+----------------------------------------------------------+ + +API: + + Instantiating a hash table template: + + Create a new hash table type in the following manner: + + #define NAME + #define KEY_TY + #include "verstable.h" + + The NAME macro specifies the name of hash table type that the library will declare, the prefix for the functions + associated with it, and the prefix for the associated iterator type. + + The KEY_TY macro specifies the key type. + + In C99, it is also always necessary to define HASH_FN and CMPR_FN (see below) before including the header. + + The following macros may also be defined before including the header: + + #define KEY_GET_CONST + + Forces the key getter to take a const pointer even if the input key is not marked const + + #define VAL_TY + + The type of the value associated with each key. + If this macro is defined, the hash table acts as a map associating keys with values. + Otherwise, it acts as a set containing only keys. + + #define HASH_FN + + The name of the existing function used to hash each key. + The function should have the signature uint64_t ( KEY_TY key ) and return a 64-bit hash code. + For best performance, the hash function should provide a high level of entropy across all bits. + There are two default hash functions: vt_hash_integer for all integer types up to 64 bits in size, and + vt_hash_string for NULL-terminated strings (i.e. char *). + When KEY_TY is one of such types and the compiler is in C11 mode or later, HASH_FN may be left undefined, in + which case the appropriate default function is inferred from KEY_TY. + Otherwise, HASH_FN must be defined. + + #define CMPR_FN + + The name of the existing function used to compare two keys. + The function should have the signature bool ( KEY_TY key_1, KEY_TY key_2 ) and return true if the two keys are + equal. + There are two default comparison functions: vt_cmpr_integer for all integer types up to 64 bits in size, and + vt_cmpr_string for NULL-terminated strings (i.e. char *). + As with the default hash functions, in C11 or later the appropriate default comparison function is inferred if + KEY_TY is one of such types and CMPR_FN is left undefined. + Otherwise, CMPR_FN must be defined. + + #define MAX_LOAD + + The floating-point load factor at which the hash table automatically doubles the size of its internal buckets + array. + The default is 0.9, i.e. 90%. + + #define KEY_DTOR_FN + + The name of the existing destructor function, with the signature void ( KEY_TY key ), called on a key when it is + erased from the table or replaced by a newly inserted key. + The API functions that may call the key destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define VAL_DTOR_FN + + The name of the existing destructor function, with the signature void ( VAL_TY val ), called on a value when it + is erased from the table or replaced by a newly inserted value. + The API functions that may call the value destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define CTX_TY + + The type of the hash table type's ctx (context) member. + This member only exists if CTX_TY was defined. + It is intended to be used in conjunction with MALLOC_FN and FREE_FN (see below). + + #define MALLOC_FN + + The name of the existing function used to allocate memory. + If CTX_TY was defined, the signature should be void *( size_t size, CTX_TY *ctx ), where size is the number of + bytes to allocate and ctx points to the table's ctx member. + Otherwise, the signature should be void *( size_t size ). + The default wraps stdlib.h's malloc. + + #define FREE_FN + + The name of the existing function used to free memory. + If CTX_TY was defined, the signature should be void ( void *ptr, size_t size, CTX_TY *ctx ), where ptr points to + the memory to free, size is the number of bytes that were allocated, and ctx points to the table's ctx member. + Otherwise, the signature should be void ( void *ptr, size_t size ). + The default wraps stdlib.h's free. + + #define HEADER_MODE + #define IMPLEMENTATION_MODE + + By default, all hash table functions are defined as static inline functions, the intent being that a given hash + table template should be instantiated once per translation unit; for best performance, this is the recommended + way to use the library. + However, it is also possible to separate the struct definitions and function declarations from the function + definitions such that one implementation can be shared across all translation units (as in a traditional header + and source file pair). + In that case, instantiate a template wherever it is needed by defining HEADER_MODE, along with only NAME, + KEY_TY, and (optionally) VAL_TY, CTX_TY, and header guards, and including the library, e.g.: + + #ifndef INT_INT_MAP_H + #define INT_INT_MAP_H + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HEADER_MODE + #include "verstable.h" + #endif + + In one source file, define IMPLEMENTATION_MODE, along with NAME, KEY_TY, and any of the aforementioned optional + macros, and include the library, e.g.: + + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HASH_FN vt_hash_integer // C99. + #define CMPR_FN vt_cmpr_integer // C99. + #define MAX_LOAD 0.8 + #define IMPLEMENTATION_MODE + #include "verstable.h" + + Including the library automatically undefines all the aforementioned macros after they have been used to instantiate + the template. + + Functions: + + The functions associated with a hash table type are all prefixed with the name the user supplied via the NAME macro. + In C11 and later, the generic "vt_"-prefixed macros may be used to automatically select the correct version of the + specified function based on the arguments. + + void NAME_init( NAME *table ) + void NAME_init( NAME *table, CTX_TY ctx ) + // C11 generic macro: vt_init. + + Initializes the table for use. + If CTX_TY was defined, ctx sets the table's ctx member. + + bool NAME_init_clone( NAME *table, NAME *source ) + bool NAME_init_clone( NAME *table, NAME *source, CTX_TY ctx ) + // C11 generic macro: vt_init_clone. + + Initializes the table as a shallow copy of the specified source table. + If CTX_TY was defined, ctx sets the table's ctx member. + Returns false in the case of memory allocation failure. + + size_t NAME_size( NAME *table ) // C11 generic macro: vt_size. + + Returns the number of keys currently in the table. + + size_t NAME_bucket_count( NAME *table ) // C11 generic macro: vt_bucket_count. + + Returns the table's current bucket count. + + NAME_itr NAME_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_insert. + + Inserts the specified key (and value, if VAL_TY was defined) into the hash table. + If the same key already exists, then the new key (and value) replaces the existing key (and value). + Returns an iterator to the new key, or an end iterator in the case of memory allocation failure. + + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_get_or_insert. + + Inserts the specified key (and value, if VAL_TY was defined) if it does not already exist in the table. + Returns an iterator to the new key if it was inserted, or an iterator to the existing key, or an end iterator if + the key did not exist but the new key could not be inserted because of memory allocation failure. + Determine whether the key was inserted by comparing the table's size before and after the call. + + NAME_itr NAME_get( NAME *table, KEY_TY key ) // C11 generic macro: vt_get. + + Returns a iterator to the specified key, or an end iterator if no such key exists. + + bool NAME_erase( NAME *table, KEY_TY key ) // C11 generic macro: vt_erase. + + Erases the specified key (and associated value, if VAL_TY was defined), if it exists. + Returns true if a key was erased. + + NAME_itr NAME_erase_itr( NAME *table, NAME_itr itr ) // C11 generic macro: vt_erase_itr. + + Erases the key (and associated value, if VAL_TY was defined) pointed to by the specified iterator. + Returns an iterator to the next key in the table, or an end iterator if the erased key was the last one. + + bool NAME_reserve( NAME *table, size_t size ) // C11 generic macro: vt_reserve. + + Ensures that the bucket count is large enough to support the specified key count (i.e. size) without rehashing. + Returns false if unsuccessful due to memory allocation failure. + + bool NAME_shrink( NAME *table ) // C11 generic macro: vt_shrink. + + Shrinks the bucket count to best accommodate the current size. + Returns false if unsuccessful due to memory allocation failure. + + NAME_itr NAME_first( NAME *table ) // C11 generic macro: vt_first. + + Returns an iterator to the first key in the table, or an end iterator if the table is empty. + + bool NAME_is_end( NAME_itr itr ) // C11 generic macro: vt_is_end. + + Returns true if the iterator is an end iterator. + + NAME_itr NAME_next( NAME_itr itr ) // C11 generic macro: vt_next. + + Returns an iterator to the key after the one pointed to by the specified iterator, or an end iterator if the + specified iterator points to the last key in the table. + + void NAME_clear( NAME *table ) // C11 generic macro: vt_clear. + + Erases all keys (and values, if VAL_TY was defined) in the table. + + void NAME_cleanup( NAME *table ) // C11 generic macro: vt_cleanup. + + Erases all keys (and values, if VAL_TY was defined) in the table, frees all memory associated with it, and + initializes it for reuse. + + Iterators: + + Access the key (and value, if VAL_TY was defined) that an iterator points to using the NAME_itr struct's data + member: + + itr.data->key + itr.data->val + + Functions that may insert new keys (NAME_insert and NAME_get_or_insert), erase keys (NAME_erase and NAME_erase_itr), + or reallocate the internal bucket array (NAME_reserve and NAME_shrink) invalidate all existing iterators. + To delete keys during iteration and resume iterating, use the return value of NAME_erase_itr. + +SRB2Kart - Saturn: + added KEY_GET_CONST to force the getters to take a const pointer even if the type of key to be inserted is not const + +Version history: + + 06/05/2025 2.2.1: Fixed incorrect signature of NAME_is_end in documentation. + 18/04/2025 2.2.0: Added const qualifier to the table parameter of NAME_size, NAME_bucket_count, NAME_get, and + NAME_first and to the source parameter of NAME_init_clone. + Added default support for const char * strings. + Added support for -Wextra. + Replaced FNV-1a with Wyhash as the default string hash function. + 18/06/2024 2.1.1: Fixed a bug affecting iteration on big-endian platforms under MSVC. + 27/05/2024 2.1.0: Replaced the Murmur3 mixer with the fast-hash mixer as the default integer hash function. + Fixed a bug that could theoretically cause a crash on rehash (triggerable in testing using + NAME_shrink with a maximum load factor significantly higher than 1.0). + 06/02/2024 2.0.0: Improved custom allocator support by introducing the CTX_TY option and allowing user-supplied free + functions to receive the allocation size. + Improved documentation. + Introduced various optimizations, including storing the buckets-array size mask instead of the + bucket count, eliminating empty-table checks, combining the buckets memory and metadata memory into + one allocation, and adding branch prediction macros. + Fixed a bug that caused a key to be used after destruction during erasure. + 12/12/2023 1.0.0: Initial release. + +License (MIT): + + Copyright (c) 2023-2025 Jackson L. Allan + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Common header section */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifdef __GNUC__ + #if (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) // >= GCC 3.1 + #define FORCEINLINE __attribute__((always_inline)) + #else + #define FORCEINLINE + #endif +#else + #define FORCEINLINE +#endif + +#ifndef VERSTABLE_H +#define VERSTABLE_H + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Waggregate-return" + +#include +#include +#include +#include +#include +#include + +// Two-way concatenation macro. +#define VT_CAT_( a, b ) a##b +#define VT_CAT( a, b ) VT_CAT_( a, b ) + +// Branch optimization macros. +#ifdef __GNUC__ +#define VT_LIKELY( expression ) __builtin_expect( (bool)( expression ), true ) +#define VT_UNLIKELY( expression ) __builtin_expect( (bool)( expression ), false ) +#else +#define VT_LIKELY( expression ) ( expression ) +#define VT_UNLIKELY( expression ) ( expression ) +#endif + +// Masks for manipulating and extracting data from a bucket's uint16_t metadatum. +#define VT_EMPTY 0x0000 +#define VT_HASH_FRAG_MASK 0xF000 // 0b1111000000000000. +#define VT_IN_HOME_BUCKET_MASK 0x0800 // 0b0000100000000000. +#define VT_DISPLACEMENT_MASK 0x07FF // 0b0000011111111111, also denotes the displacement limit. Set to VT_LOAD to 1.0 + // to test proper handling of encroachment on the displacement limit during + // inserts. + +// Extracts a hash fragment from a uint64_t hash code. +// We take the highest four bits so that keys that map (via modulo) to the same bucket have distinct hash fragments. +static inline FORCEINLINE uint16_t vt_hashfrag( uint64_t hash ) +{ + return ( hash >> 48 ) & VT_HASH_FRAG_MASK; +} + +// Standard quadratic probing formula that guarantees that all buckets are visited when the bucket count is a power of +// two (at least in theory, because the displacement limit could terminate the search early when the bucket count is +// high). +static inline FORCEINLINE size_t vt_quadratic( uint16_t displacement ) +{ + return ( (size_t)displacement * displacement + displacement ) / 2; +} + +#define VT_MIN_NONZERO_BUCKET_COUNT 8 // Must be a power of two. + +// Function to find the left-most non-zero uint16_t in a uint64_t. +// This function is used when we scan four buckets at a time while iterating and relies on compiler intrinsics wherever +// possible. + +#if defined( __GNUC__ ) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFF + +static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) // Little-endian (the compiler will optimize away the check at -O1 and above). + return __builtin_ctzll( val ) / 16; + + return __builtin_clzll( val ) / 16; +} + +#elif defined( _MSC_VER ) && ( defined( _M_X64 ) || defined( _M_ARM64 ) ) + +#include +#pragma intrinsic(_BitScanForward64) +#pragma intrinsic(_BitScanReverse64) + +static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + unsigned long result; + + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) + _BitScanForward64( &result, val ); + else + { + _BitScanReverse64( &result, val ); + result = 63 - result; + } + + return result / 16; +} + +#else + +static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +{ + int result = 0; + + uint32_t half; + memcpy( &half, &val, sizeof( uint32_t ) ); + if( !half ) + result += 2; + + uint16_t quarter; + memcpy( &quarter, (char *)&val + result * sizeof( uint16_t ), sizeof( uint16_t ) ); + if( !quarter ) + result += 1; + + return result; +} + +#endif + +// When the bucket count is zero, setting the metadata pointer to point to a VT_EMPTY placeholder, rather than NULL, +// allows us to avoid checking for a zero bucket count during insertion and lookup. +static const uint16_t vt_empty_placeholder_metadatum = VT_EMPTY; + +// Default hash and comparison functions. + +// Fast-hash, as described by https://jonkagstrom.com/bit-mixer-construction and +// https://code.google.com/archive/p/fast-hash. +// In testing, this hash function provided slightly better performance than the Murmur3 mixer. +static inline FORCEINLINE uint64_t vt_hash_integer( uint64_t key ) +{ + key ^= key >> 23; + key *= 0x2127599bf4325c37ull; + key ^= key >> 47; + return key; +} + +// For hashing strings, we use the public-domain Wyhash +// (https://github.com/wangyi-fudan/wyhash) with the following modifications: +// * We use a fixed seed and secret (the defaults suggested in the Wyhash repository). +// * We do not handle endianness, so the result will differ depending on the platform. +// * We omit the code optimized for 32-bit platforms. + +static inline FORCEINLINE void vt_wymum( uint64_t *a, uint64_t *b ) +{ +#if defined( __SIZEOF_INT128__ ) + __uint128_t r = *a; + r *= *b; + *a = (uint64_t)r; + *b = (uint64_t)( r >> 64 ); +#elif defined( _MSC_VER ) && defined( _M_X64 ) + *a = _umul128( *a, *b, b ); +#else + uint64_t ha = *a >> 32; + uint64_t hb = *b >> 32; + uint64_t la = (uint32_t)*a; + uint64_t lb = (uint32_t)*b; + uint64_t rh = ha * hb; + uint64_t rm0 = ha * lb; + uint64_t rm1 = hb * la; + uint64_t rl = la * lb; + uint64_t t = rl + ( rm0 << 32 ); + uint64_t c = t < rl; + uint64_t lo = t + ( rm1 << 32 ); + c += lo < t; + uint64_t hi = rh + ( rm0 >> 32 ) + ( rm1 >> 32 ) + c; + *a = lo; + *b = hi; +#endif +} + +static inline FORCEINLINE uint64_t vt_wymix( uint64_t a, uint64_t b ) +{ + vt_wymum( &a, &b ); + return a ^ b; +} + +static inline FORCEINLINE uint64_t vt_wyr8( const unsigned char *p ) +{ + uint64_t v; + memcpy( &v, p, 8 ); + return v; +} + +static inline FORCEINLINE uint64_t vt_wyr4( const unsigned char *p ) +{ + uint32_t v; + memcpy( &v, p, 4 ); + return v; +} + +static inline FORCEINLINE uint64_t vt_wyr3( const unsigned char *p, size_t k ) +{ + return ( ( (uint64_t)p[ 0 ] ) << 16 ) | ( ( (uint64_t)p[ k >> 1 ] ) << 8 ) | p[ k - 1 ]; +} + +static inline FORCEINLINE size_t vt_wyhash( const void *key, size_t len ) +{ + const unsigned char *p = (const unsigned char *)key; + uint64_t seed = 0xca813bf4c7abf0a9ull; + uint64_t a; + uint64_t b; + if( VT_LIKELY( len <= 16 ) ) + { + if( VT_LIKELY( len >= 4 ) ) + { + a = ( vt_wyr4( p ) << 32 ) | vt_wyr4( p + ( ( len >> 3 ) << 2 ) ); + b = ( vt_wyr4( p + len - 4 ) << 32 ) | vt_wyr4( p + len - 4 - ( ( len >> 3 ) << 2 ) ); + } + else if( VT_LIKELY( len > 0 ) ) + { + a = vt_wyr3( p, len ); + b = 0; + } + else + { + a = 0; + b = 0; + } + } + else + { + size_t i = len; + if( VT_UNLIKELY( i >= 48 ) ) + { + uint64_t see1 = seed; + uint64_t see2 = seed; + do{ + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + see1 = vt_wymix( vt_wyr8( p + 16 ) ^ 0x4b33a62ed433d4a3ull, vt_wyr8( p + 24 ) ^ see1 ); + see2 = vt_wymix( vt_wyr8( p + 32 ) ^ 0x4d5a2da51de1aa47ull, vt_wyr8( p + 40 ) ^ see2 ); + p += 48; + i -= 48; + } + while( VT_LIKELY( i >= 48 ) ); + seed ^= see1 ^ see2; + } + + while( VT_UNLIKELY( i > 16 ) ) + { + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + i -= 16; + p += 16; + } + + a = vt_wyr8( p + i - 16 ); + b = vt_wyr8( p + i - 8 ); + } + + a ^= 0x8bb84b93962eacc9ull; + b ^= seed; + vt_wymum( &a, &b ); + return (size_t)vt_wymix( a ^ 0x2d358dccaa6c78a5ull ^ len, b ^ 0x8bb84b93962eacc9ull ); +} + +static inline FORCEINLINE uint64_t vt_hash_string( const char *key ) +{ + return vt_wyhash( key, strlen( key ) ); +} + +static inline FORCEINLINE bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 ) +{ + return key_1 == key_2; +} + +static inline FORCEINLINE bool vt_cmpr_string( const char *key_1, const char *key_2 ) +{ + return strcmp( key_1, key_2 ) == 0; +} + +// Default allocation and free functions. + +static inline FORCEINLINE void *vt_malloc( size_t size ) +{ + return malloc( size ); +} + +static inline FORCEINLINE void vt_free( void *ptr, size_t size ) +{ + (void)size; + free( ptr ); +} + +static inline FORCEINLINE void *vt_malloc_with_ctx( size_t size, void *ctx ) +{ + (void)ctx; + return malloc( size ); +} + +static inline FORCEINLINE void vt_free_with_ctx( void *ptr, size_t size, void *ctx ) +{ + (void)size; + (void)ctx; + free( ptr ); +} + +// The rest of the common header section pertains to the C11 generic macro API. +// This interface is based on the extendible-_Generic mechanism documented in detail at +// https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md. +// In summary, instantiating a template also defines wrappers for the template's types and functions with names in the +// pattern of vt_table_NNNN and vt_init_NNNN, where NNNN is an automatically generated integer unique to the template +// instance in the current translation unit. +// These wrappers plug into _Generic-based API macros, which use preprocessor magic to automatically generate _Generic +// slots for every existing template instance. +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined( VT_NO_C11_GENERIC_API ) + +// Octal counter that supports up to 511 hash table templates. +#define VT_TEMPLATE_COUNT_D1 0 // Digit 1, i.e. least significant digit. +#define VT_TEMPLATE_COUNT_D2 0 +#define VT_TEMPLATE_COUNT_D3 0 + +// Four-way concatenation macro. +#define VT_CAT_4_( a, b, c, d ) a##b##c##d +#define VT_CAT_4( a, b, c, d ) VT_CAT_4_( a, b, c, d ) + +// Provides the current value of the counter as a three-digit octal number preceded by 0. +#define VT_TEMPLATE_COUNT VT_CAT_4( 0, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2, VT_TEMPLATE_COUNT_D1 ) + +// _Generic-slot generation macros. + +#define VT_GENERIC_SLOT( ty, fn, n ) , VT_CAT( ty, n ): VT_CAT( fn, n ) +#define VT_R1_0( ty, fn, d3, d2 ) +#define VT_R1_1( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 0 ) ) +#define VT_R1_2( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 1 ) ) VT_R1_1( ty, fn, d3, d2 ) +#define VT_R1_3( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 2 ) ) VT_R1_2( ty, fn, d3, d2 ) +#define VT_R1_4( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 3 ) ) VT_R1_3( ty, fn, d3, d2 ) +#define VT_R1_5( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 4 ) ) VT_R1_4( ty, fn, d3, d2 ) +#define VT_R1_6( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 5 ) ) VT_R1_5( ty, fn, d3, d2 ) +#define VT_R1_7( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 6 ) ) VT_R1_6( ty, fn, d3, d2 ) +#define VT_R1_8( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 7 ) ) VT_R1_7( ty, fn, d3, d2 ) +#define VT_R2_0( ty, fn, d3 ) +#define VT_R2_1( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 0 ) +#define VT_R2_2( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 1 ) VT_R2_1( ty, fn, d3 ) +#define VT_R2_3( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 2 ) VT_R2_2( ty, fn, d3 ) +#define VT_R2_4( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 3 ) VT_R2_3( ty, fn, d3 ) +#define VT_R2_5( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 4 ) VT_R2_4( ty, fn, d3 ) +#define VT_R2_6( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 5 ) VT_R2_5( ty, fn, d3 ) +#define VT_R2_7( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 6 ) VT_R2_6( ty, fn, d3 ) +#define VT_R2_8( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 7 ) VT_R2_7( ty, fn, d3 ) +#define VT_R3_0( ty, fn ) +#define VT_R3_1( ty, fn ) VT_R2_8( ty, fn, 0 ) +#define VT_R3_2( ty, fn ) VT_R2_8( ty, fn, 1 ) VT_R3_1( ty, fn ) +#define VT_R3_3( ty, fn ) VT_R2_8( ty, fn, 2 ) VT_R3_2( ty, fn ) +#define VT_R3_4( ty, fn ) VT_R2_8( ty, fn, 3 ) VT_R3_3( ty, fn ) +#define VT_R3_5( ty, fn ) VT_R2_8( ty, fn, 4 ) VT_R3_4( ty, fn ) +#define VT_R3_6( ty, fn ) VT_R2_8( ty, fn, 5 ) VT_R3_5( ty, fn ) +#define VT_R3_7( ty, fn ) VT_R2_8( ty, fn, 6 ) VT_R3_6( ty, fn ) + +#define VT_GENERIC_SLOTS( ty, fn ) \ +VT_CAT( VT_R1_, VT_TEMPLATE_COUNT_D1 )( ty, fn, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2 ) \ +VT_CAT( VT_R2_, VT_TEMPLATE_COUNT_D2 )( ty, fn, VT_TEMPLATE_COUNT_D3 ) \ +VT_CAT( VT_R3_, VT_TEMPLATE_COUNT_D3 )( ty, fn ) \ + +// Actual generic API macros. + +// vt_init must be handled as a special case because it could take one or two arguments, depending on whether CTX_TY +// was defined. +#define VT_ARG_3( _1, _2, _3, ... ) _3 +#define vt_init( ... ) VT_ARG_3( __VA_ARGS__, vt_init_with_ctx, vt_init_without_ctx, )( __VA_ARGS__ ) +#define vt_init_without_ctx( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_init_ ) )( table ) +#define vt_init_with_ctx( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_init_clone( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_clone_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_size( table )_Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_size_ ) )( table ) + +#define vt_bucket_count( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_bucket_count_ ) )( table ) + +#define vt_is_end( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_is_end_ ) )( itr ) + +#define vt_insert( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_insert_ ) )( table, __VA_ARGS__ ) + +#define vt_get_or_insert( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_get_or_insert_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_get( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_get_ ) )( table, __VA_ARGS__ ) + +#define vt_erase( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_erase_ ) )( table, __VA_ARGS__ ) + +#define vt_next( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_next_ ) )( itr ) + +#define vt_erase_itr( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_erase_itr_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_reserve( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_reserve_ ) )( table, __VA_ARGS__ ) + +#define vt_shrink( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_shrink_ ) )( table ) + +#define vt_first( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_first_ ) )( table ) + +#define vt_clear( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_clear_ ) )( table ) + +#define vt_cleanup( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_cleanup_ ) )( table ) + +#endif + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Prefixed structs */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef IMPLEMENTATION_MODE + +typedef struct +{ + KEY_TY key; + #ifdef VAL_TY + VAL_TY val; + #endif +} VT_CAT( NAME, _bucket ); + +typedef struct +{ + VT_CAT( NAME, _bucket ) *data; + uint16_t *metadatum; + uint16_t *metadata_end; // Iterators carry an internal end pointer so that NAME_is_end does not need the table to be + // passed in as an argument. + // This also allows for the zero-bucket-count check to occur once in NAME_first, rather than + // repeatedly in NAME_is_end. + size_t home_bucket; // SIZE_MAX if home bucket is unknown. +} VT_CAT( NAME, _itr ); + +typedef struct +{ + size_t key_count; + size_t buckets_mask; // Rather than storing the bucket count directly, we store the bit mask used to reduce a hash + // code or displacement-derived bucket index to the buckets array, i.e. the bucket count minus + // one. + // Consequently, a zero bucket count (i.e. when .metadata points to the placeholder) constitutes + // a special case, represented by all bits unset (i.e. zero). + VT_CAT( NAME, _bucket ) *buckets; + uint16_t *metadata; // As described above, each metadatum consists of a 4-bit hash-code fragment (X), a 1-bit flag + // indicating whether the key in this bucket begins a chain associated with the bucket (Y), and + // an 11-bit value indicating the quadratic displacement of the next key in the chain (Z): + // XXXXYZZZZZZZZZZZ. + #ifdef CTX_TY + CTX_TY ctx; + #endif +} NAME; + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function prototypes */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE ) +#define VT_API_FN_QUALIFIERS +#else +#define VT_API_FN_QUALIFIERS static inline FORCEINLINE +#endif + +#ifndef IMPLEMENTATION_MODE + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *, + const NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME * ); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME * ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( + const NAME *table, +#ifdef KEY_GET_CONST + const KEY_TY key +#else + KEY_TY key +#endif +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *, KEY_TY ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *, size_t ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME * ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME * ); + +// Not an API function, but must be prototyped anyway because it is called by the inline NAME_erase_itr below. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw ) ( NAME *, VT_CAT( NAME, _itr ) ); + +// Erases the key pointed to by itr and returns an iterator to the next key in the table. +// This function must be inlined to ensure that the compiler optimizes away the NAME_fast_forward call if the returned +// iterator is discarded. +#ifdef __GNUC__ +static inline FORCEINLINE +#elif defined( _MSC_VER ) +static __forceinline +#else +static inline +#endif +VT_CAT( NAME, _itr ) VT_CAT( NAME, _erase_itr )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + if( VT_CAT( NAME, _erase_itr_raw )( table, itr ) ) + return VT_CAT( NAME, _next )( itr ); + + return itr; +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function implementations */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef HEADER_MODE + +// Default settings. + +#ifndef MAX_LOAD +#define MAX_LOAD 0.9 +#endif + +#ifndef MALLOC_FN +#ifdef CTX_TY +#define MALLOC_FN vt_malloc_with_ctx +#else +#define MALLOC_FN vt_malloc +#endif +#endif + +#ifndef FREE_FN +#ifdef CTX_TY +#define FREE_FN vt_free_with_ctx +#else +#define FREE_FN vt_free +#endif +#endif + +#ifndef HASH_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER // In MSVC, the compound literal in the _Generic triggers a warning about unused local variables at /W4. +#define HASH_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_hash_string, const char*: vt_hash_string, default: vt_hash_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define HASH_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_hash_string, \ + const char*: vt_hash_string, \ + default: vt_hash_integer \ +) +#endif +#else +#error Hash function inference is only available in C11 and later. In C99, you need to define HASH_FN manually to \ +vt_hash_integer, vt_hash_string, or your own custom function with the signature uint64_t ( KEY_TY ). +#endif +#endif + +#ifndef CMPR_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER +#define CMPR_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_cmpr_string, const char*: vt_cmpr_string, default: vt_cmpr_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define CMPR_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_cmpr_string, \ + const char*: vt_cmpr_string, \ + default: vt_cmpr_integer \ +) +#endif +#else +#error Comparison function inference is only available in C11 and later. In C99, you need to define CMPR_FN manually \ +to vt_cmpr_integer, vt_cmpr_string, or your own custom function with the signature bool ( KEY_TY, KEY_TY ). +#endif +#endif + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = 0; + table->buckets_mask = 0x0000000000000000ull; + table->buckets = NULL; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + #ifdef CTX_TY + table->ctx = ctx; + #endif +} + +#pragma GCC diagnostic pop + +// For efficiency, especially in the case of a small table, the buckets array and metadata share the same dynamic memory +// allocation: +// +-----------------------------+-----+----------------+--------+ +// | Buckets | Pad | Metadata | Excess | +// +-----------------------------+-----+----------------+--------+ +// Any allocated metadata array requires four excess elements to ensure that iteration functions, which read four +// metadata at a time, never read beyond the end of it. +// This function returns the offset of the beginning of the metadata, i.e. the size of the buckets array plus the +// (usually zero) padding. +// It assumes that the bucket count is not zero. +static inline FORCEINLINE size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) +{ + // Use sizeof, rather than alignof, for C99 compatibility. + return ( ( ( table->buckets_mask + 1 ) * sizeof( VT_CAT( NAME, _bucket ) ) + sizeof( uint16_t ) - 1 ) / + sizeof( uint16_t ) ) * sizeof( uint16_t ); +} + +// Returns the total allocation size, including the buckets array, padding, metadata, and excess metadata. +// As above, this function assumes that the bucket count is not zero. +static inline FORCEINLINE size_t VT_CAT( NAME, _total_alloc_size )( NAME *table ) +{ + return VT_CAT( NAME, _metadata_offset )( table ) + ( table->buckets_mask + 1 + 4 ) * sizeof( uint16_t ); +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *table, + const NAME *source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = source->key_count; + table->buckets_mask = source->buckets_mask; + #ifdef CTX_TY + table->ctx = ctx; + #endif + + if( !source->buckets_mask ) + { + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + table->buckets = NULL; + return true; + } + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + table->buckets = (VT_CAT( NAME, _bucket ) *)allocation; + table->metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( table ) ); + memcpy( allocation, source->buckets, VT_CAT( NAME, _total_alloc_size )( table ) ); + + return true; +} + +#pragma GCC diagnostic pop + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME *table ) +{ + return table->key_count; +} + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME *table ) +{ + // If the bucket count is zero, buckets_mask will be zero, not the bucket count minus one. + // We account for this special case by adding (bool)buckets_mask rather than one. + return table->buckets_mask + (bool)table->buckets_mask; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) itr ) +{ + return itr.metadatum == itr.metadata_end; +} + +// Finds the earliest empty bucket in which a key belonging to home_bucket can be placed, assuming that home_bucket +// is already occupied. +// The reason to begin the search at home_bucket, rather than the end of the existing chain, is that keys deleted from +// other chains might have freed up buckets that could fall in this chain before the final key. +// Returns true if an empty bucket within the range of the displacement limit was found, in which case the final two +// pointer arguments contain the index of the empty bucket and its quadratic displacement from home_bucket. +static inline FORCEINLINE bool VT_CAT( NAME, _find_first_empty )( + NAME *table, + size_t home_bucket, + size_t *empty, + uint16_t *displacement +) +{ + *displacement = 1; + size_t linear_dispacement = 1; + + while( true ) + { + *empty = ( home_bucket + linear_dispacement ) & table->buckets_mask; + if( table->metadata[ *empty ] == VT_EMPTY ) + return true; + + if( VT_UNLIKELY( ++*displacement == VT_DISPLACEMENT_MASK ) ) + return false; + + linear_dispacement += *displacement; + } +} + +// Finds the key in the chain beginning in home_bucket after which to link a new key with displacement_to_empty +// quadratic displacement and returns the index of the bucket containing that key. +// Although the new key could simply be linked to the end of the chain, keeping the chain ordered by displacement +// theoretically improves cache locality during lookups. +static inline FORCEINLINE size_t VT_CAT( NAME, _find_insert_location_in_chain )( + NAME *table, + size_t home_bucket, + uint16_t displacement_to_empty +) +{ + size_t candidate = home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ candidate ] & VT_DISPLACEMENT_MASK; + + if( displacement > displacement_to_empty ) + return candidate; + + candidate = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Frees up a bucket occupied by a key not belonging there so that a new key belonging there can be placed there as the +// beginning of a new chain. +// This requires: +// * Finding the previous key in the chain to which the occupying key belongs by rehashing it and then traversing the +// chain. +// * Disconnecting the key from the chain. +// * Finding the appropriate empty bucket to which to move the key. +// * Moving the key (and value) data to the empty bucket. +// * Re-linking the key to the chain. +// Returns true if the eviction succeeded, or false if no empty bucket to which to evict the occupying key could be +// found within the displacement limit. +static inline FORCEINLINE bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket ) +{ + // Find the previous key in chain. + size_t home_bucket = HASH_FN( table->buckets[ bucket ].key ) & table->buckets_mask; + size_t prev = home_bucket; + while( true ) + { + size_t next = ( home_bucket + vt_quadratic( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( next == bucket ) + break; + + prev = next; + } + + // Disconnect the key from chain. + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | ( table->metadata[ bucket ] & + VT_DISPLACEMENT_MASK ); + + // Find the empty bucket to which to move the key. + size_t empty; + uint16_t displacement; + if( VT_UNLIKELY( !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) ) ) + return false; + + // Find the key in the chain after which to link the moved key. + prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + // Move the key (and value) data. + table->buckets[ empty ] = table->buckets[ bucket ]; + + // Re-link the key to the chain from its new bucket. + table->metadata[ empty ] = ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) | ( table->metadata[ prev ] & + VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + return true; +} + +// Returns an end iterator, i.e. any iterator for which .metadatum == .metadata_end. +// This function just cleans up the library code in functions that return an end iterator as a failure indicator. +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) +{ + VT_CAT( NAME, _itr ) itr = { NULL, NULL, NULL, 0 }; + return itr; +} + +// Inserts a key, optionally replacing the existing key if it already exists. +// There are two main cases that must be handled: +// * If the key's home bucket is empty or occupied by a key that does not belong there, then the key is inserted there, +// evicting the occupying key if there is one. +// * Otherwise, the chain of keys beginning at the home bucket is (if unique is false) traversed in search of a matching +// key. +// If none is found, then the new key is inserted at the earliest available bucket, per quadratic probing from the +// home bucket, and then linked to the chain in a manner that maintains its quadratic order. +// The unique argument tells the function whether to skip searching for the key before inserting it (on rehashing, this +// step is unnecessary). +// The replace argument tells the function whether to replace an existing key. +// If replace is true, the function returns an iterator to the inserted key, or an end iterator if the key was not +// inserted because of the maximum load factor or displacement limit constraints. +// If replace is false, then the return value is as described above, except that if the key already exists, the function +// returns an iterator to the existing key. +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( + NAME *table, + KEY_TY key, + #ifdef VAL_TY + VAL_TY *val, + #endif + bool unique, + bool replace +) +{ + uint64_t hash = HASH_FN( key ); + uint16_t hashfrag = vt_hashfrag( hash ); + size_t home_bucket = hash & table->buckets_mask; + + // Case 1: The home bucket is empty or contains a key that doesn't belong there. + // This case also implicitly handles the case of a zero bucket count, since home_bucket will be zero and metadata[ 0 ] + // will be the empty placeholder. + // In that scenario, the zero buckets_mask triggers the below load-factor check. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + { + if( + // Load-factor check. + VT_UNLIKELY( table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD ) || + // Vacate the home bucket if it contains a key. + ( table->metadata[ home_bucket ] != VT_EMPTY && VT_UNLIKELY( !VT_CAT( NAME, _evict )( table, home_bucket ) ) ) + ) + return VT_CAT( NAME, _end_itr )(); + + table->buckets[ home_bucket ].key = key; + #ifdef VAL_TY + table->buckets[ home_bucket ].val = *val; + #endif + table->metadata[ home_bucket ] = hashfrag | VT_IN_HOME_BUCKET_MASK | VT_DISPLACEMENT_MASK; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + home_bucket, + table->metadata + home_bucket, + table->metadata + table->buckets_mask + 1, // Iteration stopper (i.e. the first of the four excess metadata). + home_bucket + }; + return itr; + } + + // Case 2: The home bucket contains the beginning of a chain. + + // Optionally, check the existing chain. + if( !unique ) + { + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + if( replace ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ bucket ].key ); + #endif + table->buckets[ bucket ].key = key; + + #ifdef VAL_TY + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ bucket ].val ); + #endif + table->buckets[ bucket ].val = *val; + #endif + } + + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + break; + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } + } + + size_t empty; + uint16_t displacement; + if( + VT_UNLIKELY( + // Load-factor check. + table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD || + // Find the earliest empty bucket, per quadratic probing. + !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) + ) + ) + return VT_CAT( NAME, _end_itr )(); + + // Insert the new key (and value) in the empty bucket and link it to the chain. + + size_t prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + table->buckets[ empty ].key = key; + #ifdef VAL_TY + table->buckets[ empty ].val = *val; + #endif + table->metadata[ empty ] = hashfrag | ( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + empty, + table->metadata + empty, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; +} + +// Resizes the bucket array. +// This function assumes that bucket_count is a power of two and large enough to accommodate all keys without violating +// the maximum load factor. +// Returns false in the case of allocation failure. +// As this function is called very rarely in _insert and _get_or_insert, ideally it should not be inlined into those +// functions. +// In testing, the no-inline approach showed a performance benefit when inserting existing keys (i.e. replacing). +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline FORCEINLINE. +__attribute__((noinline)) static inline +#elif defined( _MSC_VER ) +__declspec(noinline) static inline +#else +static inline +#endif +bool VT_CAT( NAME, _rehash )( NAME *table, size_t bucket_count ) +{ + // The attempt to resize the bucket array and rehash the keys must occur inside a loop that incrementally doubles the + // target bucket count because a failure could theoretically occur at any load factor due to the displacement limit. + while( true ) + { + NAME new_table = { + 0, + bucket_count - 1, + NULL, + NULL + #ifdef CTX_TY + , table->ctx + #endif + }; + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + new_table.buckets = (VT_CAT( NAME, _bucket ) *)allocation; + new_table.metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( &new_table ) ); + + memset( new_table.metadata, 0x00, ( bucket_count + 4 ) * sizeof( uint16_t ) ); + + // Iteration stopper at the end of the actual metadata array (i.e. the first of the four excess metadata). + new_table.metadata[ bucket_count ] = 0x01; + + for( size_t bucket = 0; bucket < VT_CAT( NAME, _bucket_count )( table ); ++bucket ) + if( table->metadata[ bucket ] != VT_EMPTY ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + &new_table, + table->buckets[ bucket ].key, + #ifdef VAL_TY + &table->buckets[ bucket ].val, + #endif + true, + false + ); + + if( VT_UNLIKELY( VT_CAT( NAME, _is_end )( itr ) ) ) + break; + } + + // If a key could not be reinserted due to the displacement limit, double the bucket count and retry. + if( VT_UNLIKELY( new_table.key_count < table->key_count ) ) + { + FREE_FN( + new_table.buckets, + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + bucket_count *= 2; + continue; + } + + if( table->buckets_mask ) + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + *table = new_table; + return true; + } +} +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +// Inserts a key, replacing the existing key if it already exists. +// This function wraps insert_raw in a loop that handles growing and rehashing the table if a new key cannot be inserted +// because of the maximum load factor or displacement limit constraints. +// Returns an iterator to the inserted key, or an end iterator in the case of allocation failure. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + true + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Same as NAME_insert, except that if the key already exists, no insertion occurs and the function returns an iterator +// to the existing key. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + false + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Returns an iterator pointing to the specified key, or an end iterator if the key does not exist. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( const NAME *table, +#ifdef KEY_GET_CONST + const KEY_TY key +#else + KEY_TY key +#endif + ) +{ + uint64_t hash = HASH_FN( key ); + size_t home_bucket = hash & table->buckets_mask; + + // If the home bucket is empty or contains a key that does not belong there, then our key does not exist. + // This check also implicitly handles the case of a zero bucket count, since home_bucket will be zero and + // metadata[ 0 ] will be the empty placeholder. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + return VT_CAT( NAME, _end_itr )(); + + // Traverse the chain of keys belonging to the home bucket. + uint16_t hashfrag = vt_hashfrag( hash ); + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + return VT_CAT( NAME, _end_itr )(); + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Erases the key pointed to by the specified iterator. +// The erasure always occurs at the end of the chain to which the key belongs. +// If the key to be erased is not the last in the chain, it is swapped with the last so that erasure occurs at the end. +// This helps keep a chain's keys close to their home bucket for the sake of cache locality. +// Returns true if, in the case of iteration from first to end, NAME_next should now be called on the iterator to find +// the next key. +// This return value is necessary because at the iterator location, the erasure could result in an empty bucket, a +// bucket containing a moved key already visited during the iteration, or a bucket containing a moved key not yet +// visited. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + --table->key_count; + size_t itr_bucket = itr.metadatum - table->metadata; + + // For now, we only call the value's destructor because the key may need to be hashed below to determine the home + // bucket. + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ itr_bucket ].val ); + #endif + + // Case 1: The key is the only one in its chain, so just remove it. + if( + table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK && + ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK + ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + // Case 2 and 3 require that we know the key's home bucket, which the iterator may not have recorded. + if( itr.home_bucket == SIZE_MAX ) + { + if( table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK ) + itr.home_bucket = itr_bucket; + else + itr.home_bucket = HASH_FN( table->buckets[ itr_bucket ].key ) & table->buckets_mask; + } + + // The key can now be safely destructed for cases 2 and 3. + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + + // Case 2: The key is the last in a multi-key chain. + // Traverse the chain from the beginning and find the penultimate key. + // Then disconnect the key and erase. + if( ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + size_t bucket = itr.home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + size_t next = ( itr.home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + if( next == itr_bucket ) + { + table->metadata[ bucket ] |= VT_DISPLACEMENT_MASK; + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + bucket = next; + } + } + + // Case 3: The chain has multiple keys, and the key is not the last one. + // Traverse the chain from the key to be erased and find the last and penultimate keys. + // Disconnect the last key from the chain, and swap it with the key to erase. + size_t bucket = itr_bucket; + while( true ) + { + size_t prev = bucket; + bucket = ( itr.home_bucket + vt_quadratic( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( ( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + table->buckets[ itr_bucket ] = table->buckets[ bucket ]; + + table->metadata[ itr_bucket ] = ( table->metadata[ itr_bucket ] & ~VT_HASH_FRAG_MASK ) | ( + table->metadata[ bucket ] & VT_HASH_FRAG_MASK ); + + table->metadata[ prev ] |= VT_DISPLACEMENT_MASK; + table->metadata[ bucket ] = VT_EMPTY; + + // Whether the iterator should be advanced depends on whether the key moved to the iterator bucket came from + // before or after that bucket. + // In the former case, the iteration would already have hit the moved key, so the iterator should still be + // advanced. + if( bucket > itr_bucket ) + return false; + + return true; + } + } +} + +// Erases the specified key, if it exists. +// Returns true if a key was erased. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *table, KEY_TY key ) +{ + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _get)( table, key ); + if( VT_CAT( NAME, _is_end )( itr ) ) + return false; + + VT_CAT( NAME, _erase_itr_raw )( table, itr ); + return true; +} + +// Finds the first occupied bucket at or after the bucket pointed to by itr. +// This function scans four buckets at a time, ideally using intrinsics. +static inline FORCEINLINE void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr ) +{ + while( true ) + { + uint64_t metadata; + memcpy( &metadata, itr->metadatum, sizeof( uint64_t ) ); + if( metadata ) + { + int offset = vt_first_nonzero_uint16( metadata ); + itr->data += offset; + itr->metadatum += offset; + itr->home_bucket = SIZE_MAX; + return; + } + + itr->data += 4; + itr->metadatum += 4; + } +} + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) itr ) +{ + ++itr.data; + ++itr.metadatum; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +// Returns the minimum bucket count required to accommodate a certain number of keys, which is governed by the maximum +// load factor. +static inline FORCEINLINE size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size ) +{ + if( size == 0 ) + return 0; + + // Round up to a power of two. + size_t bucket_count = VT_MIN_NONZERO_BUCKET_COUNT; + while( size > bucket_count * MAX_LOAD ) + bucket_count *= 2; + + return bucket_count; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *table, size_t size ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( size ); + + if( bucket_count <= VT_CAT( NAME, _bucket_count )( table ) ) + return true; + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME *table ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( table->key_count ); + + if( bucket_count == VT_CAT( NAME, _bucket_count )( table ) ) // Shrink unnecessary. + return true; + + if( bucket_count == 0 ) + { + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + table->buckets_mask = 0x0000000000000000ull; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + return true; + } + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +#pragma GCC diagnostic pop + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME *table ) +{ + if( !table->key_count ) + return VT_CAT( NAME, _end_itr )(); + + VT_CAT( NAME, _itr ) itr = { table->buckets, table->metadata, table->metadata + table->buckets_mask + 1, SIZE_MAX }; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME *table ) +{ + if( !table->key_count ) + return; + + for( size_t i = 0; i < VT_CAT( NAME, _bucket_count )( table ); ++i ) + { + if( table->metadata[ i ] != VT_EMPTY ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ i ].key ); + #endif + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ i ].val ); + #endif + } + + table->metadata[ i ] = VT_EMPTY; + } + + table->key_count = 0; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME *table ) +{ + if( !table->buckets_mask ) + return; + + #if defined( KEY_DTOR_FN ) || defined( VAL_DTOR_FN ) + VT_CAT( NAME, _clear )( table ); + #endif + + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , table->ctx + #endif + ); +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Wrapper types and functions for the C11 generic API */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 201112L && \ + !defined( IMPLEMENTATION_MODE ) && \ + !defined( VT_NO_C11_GENERIC_API ) \ + +typedef NAME VT_CAT( vt_table_, VT_TEMPLATE_COUNT ); +typedef VT_CAT( NAME, _itr ) VT_CAT( vt_table_itr_, VT_TEMPLATE_COUNT ); + +static inline FORCEINLINE void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline FORCEINLINE bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( + NAME *table, + const NAME* source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + return VT_CAT( NAME, _init_clone )( + table, + source + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline FORCEINLINE size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _size )( table ); +} + +static inline FORCEINLINE size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _bucket_count )( table ); +} + +static inline FORCEINLINE bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _is_end )( itr ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _get_or_insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _get )( table, key ); +} + +static inline FORCEINLINE bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _erase )( table, key ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _next )( itr ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _erase_itr )( table, itr ); +} + +static inline FORCEINLINE bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count ) +{ + return VT_CAT( NAME, _reserve )( table, bucket_count ); +} + +static inline FORCEINLINE bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + return VT_CAT( NAME, _shrink )( table ); +} + +static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _first )( table ); +} + +static inline FORCEINLINE void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _clear )( table ); +} + +static inline FORCEINLINE void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _cleanup )( table ); +} + +// Increment the template counter. +#if VT_TEMPLATE_COUNT_D1 == 0 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 1 +#elif VT_TEMPLATE_COUNT_D1 == 1 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 2 +#elif VT_TEMPLATE_COUNT_D1 == 2 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 3 +#elif VT_TEMPLATE_COUNT_D1 == 3 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 4 +#elif VT_TEMPLATE_COUNT_D1 == 4 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 5 +#elif VT_TEMPLATE_COUNT_D1 == 5 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 6 +#elif VT_TEMPLATE_COUNT_D1 == 6 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 7 +#elif VT_TEMPLATE_COUNT_D1 == 7 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 0 +#if VT_TEMPLATE_COUNT_D2 == 0 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 1 +#elif VT_TEMPLATE_COUNT_D2 == 1 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 2 +#elif VT_TEMPLATE_COUNT_D2 == 2 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 3 +#elif VT_TEMPLATE_COUNT_D2 == 3 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 4 +#elif VT_TEMPLATE_COUNT_D2 == 4 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 5 +#elif VT_TEMPLATE_COUNT_D2 == 5 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 6 +#elif VT_TEMPLATE_COUNT_D2 == 6 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 7 +#elif VT_TEMPLATE_COUNT_D2 == 7 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 0 +#if VT_TEMPLATE_COUNT_D3 == 0 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 1 +#elif VT_TEMPLATE_COUNT_D3 == 1 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 2 +#elif VT_TEMPLATE_COUNT_D3 == 2 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 3 +#elif VT_TEMPLATE_COUNT_D3 == 3 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 4 +#elif VT_TEMPLATE_COUNT_D3 == 4 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 5 +#elif VT_TEMPLATE_COUNT_D3 == 5 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 6 +#elif VT_TEMPLATE_COUNT_D3 == 6 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 7 +#elif VT_TEMPLATE_COUNT_D3 == 7 +#error Sorry, the number of template instances is limited to 511. Define VT_NO_C11_GENERIC_API globally and use the \ +C99 prefixed function API to circumvent this restriction. +#endif +#endif +#endif + +#pragma GCC diagnostic pop + +#endif + +#undef NAME +#undef KEY_TY +#undef KEY_GET_CONST +#undef VAL_TY +#undef HASH_FN +#undef CMPR_FN +#undef MAX_LOAD +#undef KEY_DTOR_FN +#undef VAL_DTOR_FN +#undef CTX_TY +#undef MALLOC_FN +#undef FREE_FN +#undef HEADER_MODE +#undef IMPLEMENTATION_MODE +#undef VT_API_FN_QUALIFIERS + +#undef FORCEINLINE diff --git a/src/w_wad.cpp b/src/w_wad.c similarity index 90% rename from src/w_wad.cpp rename to src/w_wad.c index 9e2475095..cfc25bbaa 100644 --- a/src/w_wad.cpp +++ b/src/w_wad.c @@ -90,34 +90,29 @@ typedef struct #define LUMPNUMCACHESIZE 2048 // should be reasonable ig #define LUMPNUMCACHENAME 32 -#include -#include -#include +#define NAME lumpnum_map +#define KEY_TY char * +#define KEY_GET_CONST +#define VAL_TY lumpnum_t +#define HASH_FN vt_hash_string +#define CMPR_FN vt_cmpr_string +#define KEY_DTOR_FN free +#include "verstable.h" -struct LumpnumNameHash -{ - std::size_t operator()(const std::string& str) const - { - // hopefully this is fast enough but should be - return static_cast(FNV1a_Hash(str.c_str(), str.length())); - } -}; +#define NAME folder_map +#define KEY_TY char * +#define KEY_GET_CONST +#define VAL_TY UINT16 +#define HASH_FN vt_hash_string +#define CMPR_FN vt_cmpr_string +#define KEY_DTOR_FN free +#include "verstable.h" -struct LumpnumStringEquals -{ - bool operator()(const std::string& str1, const std::string& str2) const - { - //return fastcmp(str1.c_str(), str2.c_str()); - return str1 == str2; - } -}; +static lumpnum_map lumpnumcache; -static std::unordered_map lumpnumcache(LUMPNUMCACHESIZE); - -// gotta wrap this in a struct due to external C linkage -struct FolderCache { - std::unordered_map map; -}; +typedef struct FolderCache { + folder_map map; +} FolderCache; static const char pat_central[] = {0x50, 0x4b, 0x01, 0x02, 0x00}; static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; @@ -135,6 +130,8 @@ wadfile_t *wadfiles[MAX_WADFILES] = {}; // 0 to numwadfiles-1 are valid // being ejected void W_Shutdown(void) { + lumpnum_map_cleanup(&lumpnumcache); + while (numwadfiles--) { wadfile_t *wad = wadfiles[numwadfiles]; @@ -150,14 +147,24 @@ void W_Shutdown(void) Z_Free(wad->lumpinfo[wad->numlumps].fullname); } - delete wad->startfolders; - delete wad->endfolders; + folder_map_cleanup(&wad->startfolders->map); + free(wad->startfolders); + folder_map_cleanup(&wad->endfolders->map); + free(wad->endfolders); Z_Free(wad->lumpinfo); Z_Free(wad); } } +// the lumpnum cache needs to be initialized before use +// call this as early as possible! +void W_Startup(void) +{ + lumpnum_map_init(&lumpnumcache); + lumpnum_map_reserve(&lumpnumcache, LUMPNUMCACHESIZE); +} + //=========================================================================== // LUMP BASED ROUTINES //=========================================================================== @@ -278,7 +285,7 @@ static inline void W_LoadDehackedLumpsPK3(UINT16 wadnum) lumpinfo_t *lump_p = &wadfiles[wadnum]->lumpinfo[posStart]; size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = static_cast(malloc(length + 1)); + char *name = (char *)(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumpsPK3: Out of memory!\n"); @@ -314,7 +321,7 @@ static inline void W_LoadDehackedLumps(UINT16 wadnum) if (memcmp(lump_p->name, "SOC_", 4) == 0) // Check for generic SOC lump { // shameless copy+paste of code from LUA_LoadLump size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name - char *name = static_cast(malloc(length + 1)); + char *name = (char *)(malloc(length + 1)); if (!name) I_Error("W_LoadDehackedLumps: Out of memory!\n"); @@ -381,7 +388,7 @@ static inline INT32 W_MakeFileMD5(const char *filename, void *resblock) // Invalidates the cache of lump numbers. Call this whenever a wad is added. FUNCINLINE static ATTRINLINE void W_InvalidateLumpnumCache(void) { - lumpnumcache.clear(); + lumpnum_map_clear(&lumpnumcache); } FUNCINLINE static ATTRINLINE UINT32 W_HashLumpName(const char *name) @@ -410,24 +417,24 @@ static restype_t ResourceFileDetect(const char* filename) */ static lumpinfo_t* ResGetLumpsStandalone(FILE* handle, UINT16* numlumps, const char* lumpname) { - lumpinfo_t* lumpinfo = static_cast(Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL)); + lumpinfo_t* lumpinfo = (lumpinfo_t *)(Z_Calloc(sizeof (*lumpinfo), PU_STATIC, NULL)); lumpinfo->position = 0; fseek(handle, 0, SEEK_END); - lumpinfo->size = static_cast(ftell(handle)); + lumpinfo->size = (size_t)(ftell(handle)); fseek(handle, 0, SEEK_SET); strlcpy(lumpinfo->name, lumpname, sizeof(lumpinfo->name)); lumpinfo->namelength = strlen(lumpinfo->name); lumpinfo->hash.name = W_HashLumpName(lumpname); // Allocate the lump's long name. - /*lumpinfo->longname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); + /*lumpinfo->longname = (char *)(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->longname, lumpname); lumpinfo->longname[lumpinfo->namelength] = '\0'; lumpinfo->longnamelength = lumpinfo->namelength; lumpinfo->hash.longname = lumpinfo->hash.name;*/ // Allocate the lump's full name. - lumpinfo->fullname = static_cast(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); + lumpinfo->fullname = (char *)(Z_Malloc((lumpinfo->namelength + 1) * sizeof(char), PU_STATIC, NULL)); strcpy(lumpinfo->fullname, lumpname); lumpinfo->fullname[lumpinfo->namelength] = '\0'; lumpinfo->fullnamelength = lumpinfo->namelength; @@ -474,8 +481,8 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena header.infotableofs = LONG(header.infotableofs); // read wad file directory - i = header.numlumps * sizeof (*fileinfo); - fileinfov = fileinfo = static_cast(malloc(i)); + i = header.numlumps * sizeof(*fileinfo); + fileinfov = fileinfo = (filelump_t *)(malloc(i)); if (fseek(handle, header.infotableofs, SEEK_SET) == -1 || fread(fileinfo, 1, i, handle) < i) @@ -487,7 +494,7 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena numlumps = header.numlumps; // fill in lumpinfo for this wad - lump_p = lumpinfo = static_cast(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); + lump_p = lumpinfo = (lumpinfo_t *)(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); for (i = 0; i < numlumps; i++, lump_p++, fileinfo++) { @@ -531,14 +538,14 @@ static lumpinfo_t* ResGetLumpsWad(FILE* handle, UINT16* nlmp, const char* filena lump_p->hash.name = W_HashLumpName(lump_p->name); // Allocate the lump's long name. - /*lump_p->longname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); + /*lump_p->longname = (char *)(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->longname, fileinfo->name, 8); lump_p->longname[8] = '\0'; lump_p->longnamelength = lump_p->namelength; lump_p->hash.longname = lump_p->hash.name;*/ // Allocate the lump's full name. - lump_p->fullname = static_cast(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); + lump_p->fullname = (char *)(Z_Malloc(9 * sizeof(char), PU_STATIC, NULL)); strncpy(lump_p->fullname, fileinfo->name, 8); lump_p->fullname[8] = '\0'; lump_p->fullnamelength = lump_p->namelength; @@ -559,24 +566,24 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp int c; fseek(handle, 0, SEEK_END); - size_t len = static_cast(ftell(handle)); + size_t len = (size_t)(ftell(handle)); fseek(handle, startpos, SEEK_SET); - size_t remaining = static_cast(len - startpos); - size_t chunkpos = static_cast(startpos); + size_t remaining = (size_t)(len - startpos); + size_t chunkpos = (size_t)(startpos); s = endPat; //128k buffers - size_t buffer_size = std::min(128 * 1024 * sizeof(char), remaining); - CLEANUP(pfree) char* buffer = static_cast(malloc(buffer_size)); + size_t buffer_size = min(128 * 1024 * sizeof(char), remaining); + CLEANUP(pfree) char* buffer = (char *)(malloc(buffer_size)); size_t bytes_read = 0; while ((bytes_read = fread(buffer, 1, buffer_size, handle)) > 0) { for (size_t i = 0; i < bytes_read; i++) { - c = static_cast(buffer[i]); + c = (int)(buffer[i]); if (*s != c && s > endPat) // No match? s = endPat; // We "reset" the counter by sending the s pointer back to the start of the array. @@ -588,7 +595,7 @@ static boolean ResFindSignature(FILE* handle, const char endPat[], UINT32 startp if (*s == 0x00) // The array pointer has reached the key char which marks the end. It means we have matched the signature. { //the original function would leave the FILE* seeked to the end of the match - size_t foundpos = static_cast(chunkpos + i + 1); + size_t foundpos = (size_t)(chunkpos + i + 1); fseek(handle, foundpos, SEEK_SET); return true; } @@ -666,7 +673,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) fseek(handle, 0, SEEK_END); const long startpos = ftell(handle) - (22 + 65536); - if (!ResFindSignature(handle, pat_end, std::max(0l, startpos))) + if (!ResFindSignature(handle, pat_end, max(0l, startpos))) { CONS_Alert(CONS_ERROR, "Missing central directory\n"); return NULL; @@ -681,11 +688,11 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) numlumps = SHORT(zend.entries); - lump_p = lumpinfo = static_cast(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); + lump_p = lumpinfo = (lumpinfo_t *)(Z_Malloc(numlumps * sizeof (*lumpinfo), PU_STATIC, NULL)); fseek(handle, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(Z_Pfree) char *cdir = static_cast(Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir)); + CLEANUP(Z_Pfree) char *cdir = (char *)(Z_Malloc(LONG(zend.cdirsize), PU_STATIC, &cdir)); if (fread(cdir, 1, LONG(zend.cdirsize), handle) < (UINT32)(LONG(zend.cdirsize))) { @@ -698,7 +705,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) for (i = 0; i < numlumps; i++, lump_p++) { - zentry_t *zentry = reinterpret_cast(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -714,7 +721,7 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) lump_p->disksize = LONG(zentry->compsize); lump_p->size = LONG(zentry->size); - fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); fullname[zentry->namelen] = 0; @@ -728,16 +735,16 @@ static lumpinfo_t* ResGetLumpsZip(FILE* handle, UINT16* nlmp) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lump_p->name, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lump_p->name, trimname, std::min(8, dotpos - trimname)); + strncpy(lump_p->name, trimname, min(8, dotpos - trimname)); lump_p->namelength = strlen(lump_p->name); lump_p->hash.name = W_HashLumpName(lump_p->name); - /*lump_p->longname = static_cast(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); + /*lump_p->longname = (char *)(Z_Calloc(dotpos - trimname + 1, PU_STATIC, NULL)); strlcpy(lump_p->longname, trimname, dotpos - trimname + 1); lump_p->longnamelength = strlen(lump_p->longname); lump_p->hash.longname = W_HashLumpName(lump_p->longname);*/ - lump_p->fullname = static_cast(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); + lump_p->fullname = (char *)(Z_Calloc(SHORT(zentry->namelen) + 1, PU_STATIC, NULL)); strncpy(lump_p->fullname, fullname, SHORT(zentry->namelen)); lump_p->fullnamelength = zentry->namelen; //lump_p->hash.fullname = W_HashLumpName(lump_p->fullname); @@ -915,17 +922,19 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) // // link wad file to search files // - wadfile = static_cast(Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL)); + wadfile = (wadfile_t *)(Z_Calloc(sizeof (*wadfile), PU_STATIC, NULL)); wadfile->filename = Z_StrDup(filename); wadfile->handle = handle; - wadfile->numlumps = static_cast(numlumps); + wadfile->numlumps = (UINT16)(numlumps); wadfile->lumpinfo = lumpinfo; wadfile->important = important; fseek(handle, 0, SEEK_END); - wadfile->filesize = static_cast(ftell(handle)); + wadfile->filesize = (unsigned)(ftell(handle)); wadfile->type = type; - wadfile->startfolders = new FolderCache(); - wadfile->endfolders = new FolderCache(); + wadfile->startfolders = (FolderCache *)malloc(sizeof(FolderCache)); + folder_map_init(&wadfile->startfolders->map); + wadfile->endfolders = (FolderCache *)malloc(sizeof(FolderCache)); + folder_map_init(&wadfile->endfolders->map); // already generated, just copy it over memcpy(&wadfile->md5sum, &md5sum, 16); @@ -950,7 +959,7 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) #ifdef HWRENDER // Read shaders from file if (rendermode == render_opengl && (vid.glstate == VID_GL_LIBRARY_LOADED)) - HWR_LoadCustomShadersFromFile(numwadfiles - 1, static_cast(type == RET_PK3)); + HWR_LoadCustomShadersFromFile(numwadfiles - 1, (boolean)(type == RET_PK3)); #endif // TODO: HACK ALERT - Load Lua & SOC stuff right here. I feel like this should be out of this place, but... Let's stick with this for now. @@ -1179,9 +1188,9 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - auto it = wadfiles[wad]->startfolders->map.find(name); - if (it != wadfiles[wad]->startfolders->map.end()) - return it->second; + folder_map_itr it = folder_map_get(&wadfiles[wad]->startfolders->map, name); + if (!folder_map_is_end(it)) + return it.data->val; namelen = strlen(name); @@ -1193,12 +1202,12 @@ UINT16 W_CheckNumForFolderStartPK3(const char *name, UINT16 wad, UINT16 startlum if (lump_p->fullnamelength == namelen) i++; - wadfiles[wad]->startfolders->map[name] = i; + folder_map_insert(&wadfiles[wad]->startfolders->map, strdup(name), i); return i; } } - wadfiles[wad]->startfolders->map[name] = INT16_MAX; + folder_map_insert(&wadfiles[wad]->startfolders->map, strdup(name), INT16_MAX); return INT16_MAX; } @@ -1211,9 +1220,9 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) size_t namelen; lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump; - auto it = wadfiles[wad]->endfolders->map.find(name); - if (it != wadfiles[wad]->endfolders->map.end()) - return it->second; + folder_map_itr it = folder_map_get(&wadfiles[wad]->endfolders->map, name); + if (!folder_map_is_end(it)) + return it.data->val; namelen = strlen(name); @@ -1223,7 +1232,7 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump) break; } - wadfiles[wad]->endfolders->map[name] = i; + folder_map_insert(&wadfiles[wad]->endfolders->map, strdup(name), i); return i; } @@ -1251,16 +1260,17 @@ UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump) FUNCINLINE static ATTRINLINE lumpnum_t CheckLumpInCache(const char *name) { - auto it = lumpnumcache.find(name); - if (it != lumpnumcache.end()) - return it->second; + lumpnum_map_itr it = lumpnum_map_get(&lumpnumcache, name); + if (!lumpnum_map_is_end(it)) + return it.data->val; return LUMPERROR; } FUNCINLINE static ATTRINLINE void AddLumpToCache(lumpnum_t lumpnum, const char *name) { - lumpnumcache.emplace(name, lumpnum); + I_Assert(strlen(name) <= 8); // we dont have longnames, so assume this is a non terminated string + lumpnum_map_insert(&lumpnumcache, strdup(name), lumpnum); } // @@ -1283,7 +1293,7 @@ lumpnum_t W_CheckNumForName(const char *name) // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForNamePwad(name, static_cast(i), 0); + check = W_CheckNumForNamePwad(name, (UINT16)(i), 0); if (check != INT16_MAX) break; //found it @@ -1325,7 +1335,7 @@ lumpnum_t W_CheckNumForName(const char *name) // scan wad files backwards so patch lump files take precedence for (i = numwadfiles - 1; i >= 0; i--) { - check = W_CheckNumForLongNamePwad(name, static_cast(i), 0); + check = W_CheckNumForLongNamePwad(name, (UINT16)(i), 0); if (check != INT16_MAX) break; //found it @@ -1395,14 +1405,14 @@ lumpnum_t W_CheckNumForNameInBlock(const char *name, const char *blockstart, con { if (wadfiles[i]->type == RET_WAD) { - bsid = W_CheckNumForNamePwad(blockstart, static_cast(i), 0); + bsid = W_CheckNumForNamePwad(blockstart, (UINT16)(i), 0); if (bsid == INT16_MAX) continue; // Start block doesn't exist? - beid = W_CheckNumForNamePwad(blockend, static_cast(i), 0); + beid = W_CheckNumForNamePwad(blockend, (UINT16)(i), 0); if (beid == INT16_MAX) continue; // End block doesn't exist? - check = W_CheckNumForNamePwad(name, static_cast(i), bsid); + check = W_CheckNumForNamePwad(name, (UINT16)(i), bsid); if (check < beid) return (i << 16)+check; // found it, in our constraints } @@ -1603,7 +1613,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si #ifdef NO_PNG_LUMPS { size_t bytesread = fread(dest, 1, size, handle); - ErrorIfPNG(static_cast(dest), bytesread, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), bytesread, wadfiles[wad]->filename, l->fullname); return bytesread; } #else @@ -1616,8 +1626,8 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si char *decData; // Lump's decompressed real data. size_t retval; // Helper var, lzf_decompress returns 0 when an error occurs. - rawData = static_cast(Z_Malloc(l->disksize, PU_STATIC, NULL)); - decData = static_cast(Z_Malloc(l->size, PU_STATIC, NULL)); + rawData = (char *)(Z_Malloc(l->disksize, PU_STATIC, NULL)); + decData = (char *)(Z_Malloc(l->size, PU_STATIC, NULL)); if (fread(rawData, 1, l->disksize, handle) < l->disksize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); @@ -1644,7 +1654,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); Z_Free(decData); #ifdef NO_PNG_LUMPS - ErrorIfPNG(static_cast(dest), size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; #else @@ -1664,8 +1674,8 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si unsigned long rawSize = l->disksize; unsigned long decSize = size; - rawData = static_cast(Z_Malloc(rawSize, PU_STATIC, NULL)); - decData = static_cast(dest); + rawData = (UINT8 *)(Z_Malloc(rawSize, PU_STATIC, NULL)); + decData = (UINT8 *)(dest); if (fread(rawData, 1, rawSize, handle) < rawSize) I_Error("wad %d, lump %d: cannot read compressed data", wad, lump); @@ -1701,7 +1711,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si Z_Free(rawData); #ifdef NO_PNG_LUMPS - ErrorIfPNG(static_cast(dest), size, wadfiles[wad]->filename, l->fullname); + ErrorIfPNG((UINT8 *)(dest), size, wadfiles[wad]->filename, l->fullname); #endif return size; } @@ -1889,7 +1899,7 @@ void *W_CacheSoftwarePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) W_ReadLumpHeaderPwad(wad, lump, lumpdata, 0, 0); dest = Z_Calloc(sizeof(patch_t), tag, &lumpcache[lump]); - Patch_Create(static_cast(lumpdata), len, dest); + Patch_Create((softwarepatch_t *)(lumpdata), len, dest); Z_Free(lumpdata); } @@ -1911,7 +1921,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) if (!TestValidLump(wad, lump)) return NULL; - patch = static_cast(W_CacheSoftwarePatchNumPwad(wad, lump, tag)); + patch = (patch_t *)(W_CacheSoftwarePatchNumPwad(wad, lump, tag)); if (patch == NULL) return NULL; @@ -1922,7 +1932,7 @@ void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) Patch_CreateGL(patch); #endif - return static_cast(patch); + return (void*)(patch); } void *W_CachePatchNum(lumpnum_t lumpnum, INT32 tag) @@ -1950,10 +1960,10 @@ void *W_GetCachedRotPatchPwad(UINT16 wad, UINT16 lump) if (!rotcache[lump]) { rotsprite_t *rspr = RotatedPatch_Create(ROTANGLES); - Z_SetUser(rspr, static_cast(&rotcache[lump])); + Z_SetUser(rspr, (void**)(&rotcache[lump])); } - return static_cast(rotcache[lump]); + return (void*)(rotcache[lump]); } #endif // ROTSPRITE @@ -1966,7 +1976,7 @@ void W_UnlockCachedPatch(void *patch) // have different lifetimes from software's. #ifdef HWRENDER if (rendermode == render_opengl) - HWR_UnlockCachedPatch(static_cast((static_cast(patch))->hardware)); + HWR_UnlockCachedPatch((GLPatch_t *)(((patch_t *)(patch))->hardware)); else #endif Z_ChangeTag(patch, PU_PATCH); @@ -2001,7 +2011,7 @@ void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag) if (rotationangle < 1 || rotationangle >= ROTANGLES) return W_CachePatchNum(num, tag); - rspr = static_cast(W_GetCachedRotPatchPwad(WADFILENUM(num), LUMPNUM(num))); + rspr = (rotsprite_t *)(W_GetCachedRotPatchPwad(WADFILENUM(num), LUMPNUM(num))); if (rspr == NULL) return W_CachePatchNum(W_GetNumForName("MISSING"), tag); @@ -2010,7 +2020,7 @@ void *W_CachePatchNameRotated(const char *name, INT32 rotationangle, INT32 tag) { INT32 xpivot = 0, ypivot = 0; - ptr = static_cast(W_CachePatchNum(num, PU_PATCH)); + ptr = (patch_t *)(W_CachePatchNum(num, PU_PATCH)); if (ptr == NULL) return W_CachePatchNum(W_GetNumForName("MISSING"), tag); @@ -2204,7 +2214,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) file_size = ftell(fp); const long startpos = file_size - (22 + 65536); - if (!ResFindSignature(fp, pat_end, std::max(0l, startpos))) + if (!ResFindSignature(fp, pat_end, max(0l, startpos))) return true; fseek(fp, -4, SEEK_CUR); @@ -2217,7 +2227,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = static_cast(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = (char *)(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2228,7 +2238,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = reinterpret_cast(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); char* fullname; char* trimname; char* dotpos; @@ -2240,7 +2250,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) if (verified == true) { - fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); fullname[zentry->namelen] = 0; @@ -2256,7 +2266,7 @@ static int W_VerifyPK3(FILE *fp, lumpchecklist_t *checklist, boolean status) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lumpname, trimname, std::min(8, dotpos - trimname)); + strncpy(lumpname, trimname, min(8, dotpos - trimname)); if (!W_VerifyName(lumpname, checklist, status)) verified = false; @@ -2452,7 +2462,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) file_size = ftell(fp); const long startpos = file_size - (22 + 65536); - if (!ResFindSignature(fp, pat_end, std::max(0l, startpos))) + if (!ResFindSignature(fp, pat_end, max(0l, startpos))) return true; fseek(fp, -4, SEEK_CUR); @@ -2465,7 +2475,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) fseek(fp, LONG(zend.cdiroffset), SEEK_SET); - CLEANUP(pfree) char *cdir = static_cast(malloc(LONG(zend.cdirsize))); + CLEANUP(pfree) char *cdir = (char *)(malloc(LONG(zend.cdirsize))); if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) { @@ -2476,7 +2486,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) for (i = 0; i < numlumps; i++) { - zentry_t *zentry = reinterpret_cast(cdir + offset); + zentry_t *zentry = (zentry_t *)(cdir + offset); CLEANUP(pfree) char* fullname = NULL; char* trimname; char* dotpos; @@ -2486,7 +2496,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) return false; } - fullname = static_cast(malloc(SHORT(zentry->namelen) + 1)); + fullname = (char *)(malloc(SHORT(zentry->namelen) + 1)); strncpy(fullname, (char *)(zentry + 1), SHORT(zentry->namelen)); fullname[zentry->namelen] = 0; @@ -2502,7 +2512,7 @@ static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) dotpos = fullname + strlen(fullname); // Watch for files without extension. memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? - strncpy(lumpname, trimname, std::min(8, dotpos - trimname)); + strncpy(lumpname, trimname, min(8, dotpos - trimname)); if (W_NameStartsWith(lumpname, checklist)) { @@ -2624,18 +2634,18 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) size_t *vsizecache; // Remember that we're assuming that the WAD will have a specific set of lumps in a specific order. - UINT8 *wadData = static_cast(W_CacheLumpNum(lumpnum, PU_LEVEL)); + UINT8 *wadData = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_LEVEL)); if (wadData == NULL) I_Error("vres_GetMap: Invalid WadData!\n"); - filelump_t *fileinfo = reinterpret_cast(wadData + LONG((reinterpret_cast(wadData))->infotableofs)); + filelump_t *fileinfo = (filelump_t *)(wadData + LONG(((wadinfo_t *)(wadData))->infotableofs)); - i = LONG((reinterpret_cast(wadData))->numlumps); - vsizecache = static_cast(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); + i = LONG(((wadinfo_t *)(wadData))->numlumps); + vsizecache = (size_t *)(Z_Malloc(sizeof(size_t)*i, PU_LEVEL, NULL)); for (realentry = 0; realentry < i; realentry++) { - vsizecache[realentry] = static_cast(LONG((reinterpret_cast(fileinfo + realentry))->size)); + vsizecache[realentry] = (size_t)(LONG(((filelump_t *)(fileinfo + realentry))->size)); if (!vsizecache[realentry]) continue; @@ -2643,7 +2653,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) numlumps++; } - vlumps = static_cast(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = (virtlump_t *)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); if (vlumps == NULL) I_Error("vres_GetMap: Out of memory!\n"); @@ -2665,7 +2675,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) // Play it safe with the name in this case. memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = static_cast( + vlumps[i].data = (UINT8 *)( Z_Malloc(vlumps[i].size, PU_LEVEL, NULL) // This is memory inefficient, sorry about that. ); memcpy(vlumps[i].data, wadData + LONG((fileinfo + realentry)->filepos), vlumps[i].size); @@ -2692,7 +2702,7 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) } numlumps++; - vlumps = static_cast(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); + vlumps = (virtlump_t *)(Z_Malloc(sizeof(virtlump_t)*numlumps, PU_LEVEL, NULL)); if (vlumps == NULL) I_Error("vres_GetMap: Out of memory!\n"); @@ -2713,11 +2723,11 @@ virtres_t* vres_GetMap(lumpnum_t lumpnum) vlumps[i].size = W_LumpLength(lumpnum); memcpy(vlumps[i].name, name, 8); vlumps[i].name[8] = '\0'; - vlumps[i].data = static_cast(W_CacheLumpNum(lumpnum, PU_LEVEL)); + vlumps[i].data = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_LEVEL)); } } - vres = static_cast(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); + vres = (virtres_t *)(Z_Malloc(sizeof(virtres_t), PU_LEVEL, NULL)); vres->vlumps = vlumps; vres->numlumps = numlumps; diff --git a/src/w_wad.h b/src/w_wad.h index d21afb982..fc7f25fec 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -126,7 +126,6 @@ typedef enum restype RET_UNKNOWN, } restype_t; - typedef struct wadfile_s { char *filename; @@ -155,6 +154,7 @@ extern wadfile_t *wadfiles[MAX_WADFILES]; // ========================================================================= +void W_Startup(void); void W_Shutdown(void); // Opens a WAD file. Returns the FILE * handle for the file, or NULL if not found or could not be opened From ba808307e95434707a8fdb0b345229f8e87cbbbc Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 24 Feb 2026 16:10:54 +0100 Subject: [PATCH 31/42] FORCEINLINE is apparently used by windows already lmao --- src/verstable.h | 102 ++++++++++++++++++++++++------------------------ 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/src/verstable.h b/src/verstable.h index 8c5a49dc3..b3fe13f91 100644 --- a/src/verstable.h +++ b/src/verstable.h @@ -441,12 +441,12 @@ License (MIT): #ifdef __GNUC__ #if (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) // >= GCC 3.1 - #define FORCEINLINE __attribute__((always_inline)) + #define FORCE_INLINE __attribute__((always_inline)) #else - #define FORCEINLINE + #define FORCE_INLINE #endif #else - #define FORCEINLINE + #define FORCE_INLINE #endif #ifndef VERSTABLE_H @@ -485,7 +485,7 @@ License (MIT): // Extracts a hash fragment from a uint64_t hash code. // We take the highest four bits so that keys that map (via modulo) to the same bucket have distinct hash fragments. -static inline FORCEINLINE uint16_t vt_hashfrag( uint64_t hash ) +static inline FORCE_INLINE uint16_t vt_hashfrag( uint64_t hash ) { return ( hash >> 48 ) & VT_HASH_FRAG_MASK; } @@ -493,7 +493,7 @@ static inline FORCEINLINE uint16_t vt_hashfrag( uint64_t hash ) // Standard quadratic probing formula that guarantees that all buckets are visited when the bucket count is a power of // two (at least in theory, because the displacement limit could terminate the search early when the bucket count is // high). -static inline FORCEINLINE size_t vt_quadratic( uint16_t displacement ) +static inline FORCE_INLINE size_t vt_quadratic( uint16_t displacement ) { return ( (size_t)displacement * displacement + displacement ) / 2; } @@ -506,7 +506,7 @@ static inline FORCEINLINE size_t vt_quadratic( uint16_t displacement ) #if defined( __GNUC__ ) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFF -static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) { const uint16_t endian_checker = 0x0001; if( *(const char *)&endian_checker ) // Little-endian (the compiler will optimize away the check at -O1 and above). @@ -521,7 +521,7 @@ static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) #pragma intrinsic(_BitScanForward64) #pragma intrinsic(_BitScanReverse64) -static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) { unsigned long result; @@ -539,7 +539,7 @@ static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) #else -static inline FORCEINLINE int vt_first_nonzero_uint16( uint64_t val ) +static inline FORCE_INLINE int vt_first_nonzero_uint16( uint64_t val ) { int result = 0; @@ -567,7 +567,7 @@ static const uint16_t vt_empty_placeholder_metadatum = VT_EMPTY; // Fast-hash, as described by https://jonkagstrom.com/bit-mixer-construction and // https://code.google.com/archive/p/fast-hash. // In testing, this hash function provided slightly better performance than the Murmur3 mixer. -static inline FORCEINLINE uint64_t vt_hash_integer( uint64_t key ) +static inline FORCE_INLINE uint64_t vt_hash_integer( uint64_t key ) { key ^= key >> 23; key *= 0x2127599bf4325c37ull; @@ -581,7 +581,7 @@ static inline FORCEINLINE uint64_t vt_hash_integer( uint64_t key ) // * We do not handle endianness, so the result will differ depending on the platform. // * We omit the code optimized for 32-bit platforms. -static inline FORCEINLINE void vt_wymum( uint64_t *a, uint64_t *b ) +static inline FORCE_INLINE void vt_wymum( uint64_t *a, uint64_t *b ) { #if defined( __SIZEOF_INT128__ ) __uint128_t r = *a; @@ -609,32 +609,32 @@ static inline FORCEINLINE void vt_wymum( uint64_t *a, uint64_t *b ) #endif } -static inline FORCEINLINE uint64_t vt_wymix( uint64_t a, uint64_t b ) +static inline FORCE_INLINE uint64_t vt_wymix( uint64_t a, uint64_t b ) { vt_wymum( &a, &b ); return a ^ b; } -static inline FORCEINLINE uint64_t vt_wyr8( const unsigned char *p ) +static inline FORCE_INLINE uint64_t vt_wyr8( const unsigned char *p ) { uint64_t v; memcpy( &v, p, 8 ); return v; } -static inline FORCEINLINE uint64_t vt_wyr4( const unsigned char *p ) +static inline FORCE_INLINE uint64_t vt_wyr4( const unsigned char *p ) { uint32_t v; memcpy( &v, p, 4 ); return v; } -static inline FORCEINLINE uint64_t vt_wyr3( const unsigned char *p, size_t k ) +static inline FORCE_INLINE uint64_t vt_wyr3( const unsigned char *p, size_t k ) { return ( ( (uint64_t)p[ 0 ] ) << 16 ) | ( ( (uint64_t)p[ k >> 1 ] ) << 8 ) | p[ k - 1 ]; } -static inline FORCEINLINE size_t vt_wyhash( const void *key, size_t len ) +static inline FORCE_INLINE size_t vt_wyhash( const void *key, size_t len ) { const unsigned char *p = (const unsigned char *)key; uint64_t seed = 0xca813bf4c7abf0a9ull; @@ -693,41 +693,41 @@ static inline FORCEINLINE size_t vt_wyhash( const void *key, size_t len ) return (size_t)vt_wymix( a ^ 0x2d358dccaa6c78a5ull ^ len, b ^ 0x8bb84b93962eacc9ull ); } -static inline FORCEINLINE uint64_t vt_hash_string( const char *key ) +static inline FORCE_INLINE uint64_t vt_hash_string( const char *key ) { return vt_wyhash( key, strlen( key ) ); } -static inline FORCEINLINE bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 ) +static inline FORCE_INLINE bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 ) { return key_1 == key_2; } -static inline FORCEINLINE bool vt_cmpr_string( const char *key_1, const char *key_2 ) +static inline FORCE_INLINE bool vt_cmpr_string( const char *key_1, const char *key_2 ) { return strcmp( key_1, key_2 ) == 0; } // Default allocation and free functions. -static inline FORCEINLINE void *vt_malloc( size_t size ) +static inline FORCE_INLINE void *vt_malloc( size_t size ) { return malloc( size ); } -static inline FORCEINLINE void vt_free( void *ptr, size_t size ) +static inline FORCE_INLINE void vt_free( void *ptr, size_t size ) { (void)size; free( ptr ); } -static inline FORCEINLINE void *vt_malloc_with_ctx( size_t size, void *ctx ) +static inline FORCE_INLINE void *vt_malloc_with_ctx( size_t size, void *ctx ) { (void)ctx; return malloc( size ); } -static inline FORCEINLINE void vt_free_with_ctx( void *ptr, size_t size, void *ctx ) +static inline FORCE_INLINE void vt_free_with_ctx( void *ptr, size_t size, void *ctx ) { (void)size; (void)ctx; @@ -894,7 +894,7 @@ typedef struct #if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE ) #define VT_API_FN_QUALIFIERS #else -#define VT_API_FN_QUALIFIERS static inline FORCEINLINE +#define VT_API_FN_QUALIFIERS static inline FORCE_INLINE #endif #ifndef IMPLEMENTATION_MODE @@ -966,7 +966,7 @@ VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw ) ( NAME *, VT_CAT( NAME, // This function must be inlined to ensure that the compiler optimizes away the NAME_fast_forward call if the returned // iterator is discarded. #ifdef __GNUC__ -static inline FORCEINLINE +static inline FORCE_INLINE #elif defined( _MSC_VER ) static __forceinline #else @@ -1083,7 +1083,7 @@ VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( // This function returns the offset of the beginning of the metadata, i.e. the size of the buckets array plus the // (usually zero) padding. // It assumes that the bucket count is not zero. -static inline FORCEINLINE size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) +static inline FORCE_INLINE size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) { // Use sizeof, rather than alignof, for C99 compatibility. return ( ( ( table->buckets_mask + 1 ) * sizeof( VT_CAT( NAME, _bucket ) ) + sizeof( uint16_t ) - 1 ) / @@ -1092,7 +1092,7 @@ static inline FORCEINLINE size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) // Returns the total allocation size, including the buckets array, padding, metadata, and excess metadata. // As above, this function assumes that the bucket count is not zero. -static inline FORCEINLINE size_t VT_CAT( NAME, _total_alloc_size )( NAME *table ) +static inline FORCE_INLINE size_t VT_CAT( NAME, _total_alloc_size )( NAME *table ) { return VT_CAT( NAME, _metadata_offset )( table ) + ( table->buckets_mask + 1 + 4 ) * sizeof( uint16_t ); } @@ -1163,7 +1163,7 @@ VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) itr ) // other chains might have freed up buckets that could fall in this chain before the final key. // Returns true if an empty bucket within the range of the displacement limit was found, in which case the final two // pointer arguments contain the index of the empty bucket and its quadratic displacement from home_bucket. -static inline FORCEINLINE bool VT_CAT( NAME, _find_first_empty )( +static inline FORCE_INLINE bool VT_CAT( NAME, _find_first_empty )( NAME *table, size_t home_bucket, size_t *empty, @@ -1190,7 +1190,7 @@ static inline FORCEINLINE bool VT_CAT( NAME, _find_first_empty )( // quadratic displacement and returns the index of the bucket containing that key. // Although the new key could simply be linked to the end of the chain, keeping the chain ordered by displacement // theoretically improves cache locality during lookups. -static inline FORCEINLINE size_t VT_CAT( NAME, _find_insert_location_in_chain )( +static inline FORCE_INLINE size_t VT_CAT( NAME, _find_insert_location_in_chain )( NAME *table, size_t home_bucket, uint16_t displacement_to_empty @@ -1219,7 +1219,7 @@ static inline FORCEINLINE size_t VT_CAT( NAME, _find_insert_location_in_chain )( // * Re-linking the key to the chain. // Returns true if the eviction succeeded, or false if no empty bucket to which to evict the occupying key could be // found within the displacement limit. -static inline FORCEINLINE bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket ) +static inline FORCE_INLINE bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket ) { // Find the previous key in chain. size_t home_bucket = HASH_FN( table->buckets[ bucket ].key ) & table->buckets_mask; @@ -1261,7 +1261,7 @@ static inline FORCEINLINE bool VT_CAT( NAME, _evict )( NAME *table, size_t bucke // Returns an end iterator, i.e. any iterator for which .metadatum == .metadata_end. // This function just cleans up the library code in functions that return an end iterator as a failure indicator. -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) { VT_CAT( NAME, _itr ) itr = { NULL, NULL, NULL, 0 }; return itr; @@ -1282,7 +1282,7 @@ static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) // inserted because of the maximum load factor or displacement limit constraints. // If replace is false, then the return value is as described above, except that if the key already exists, the function // returns an iterator to the existing key. -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( NAME *table, KEY_TY key, #ifdef VAL_TY @@ -1415,7 +1415,7 @@ static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( // In testing, the no-inline approach showed a performance benefit when inserting existing keys (i.e. replacing). #ifdef __GNUC__ #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline FORCEINLINE. +#pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline FORCE_INLINE. __attribute__((noinline)) static inline #elif defined( _MSC_VER ) __declspec(noinline) static inline @@ -1738,7 +1738,7 @@ VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *table, KEY_TY key ) // Finds the first occupied bucket at or after the bucket pointed to by itr. // This function scans four buckets at a time, ideally using intrinsics. -static inline FORCEINLINE void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr ) +static inline FORCE_INLINE void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr ) { while( true ) { @@ -1768,7 +1768,7 @@ VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _ // Returns the minimum bucket count required to accommodate a certain number of keys, which is governed by the maximum // load factor. -static inline FORCEINLINE size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size ) +static inline FORCE_INLINE size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size ) { if( size == 0 ) return 0; @@ -1893,7 +1893,7 @@ VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME *table ) typedef NAME VT_CAT( vt_table_, VT_TEMPLATE_COUNT ); typedef VT_CAT( NAME, _itr ) VT_CAT( vt_table_itr_, VT_TEMPLATE_COUNT ); -static inline FORCEINLINE void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( +static inline FORCE_INLINE void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( NAME *table #ifdef CTX_TY , CTX_TY ctx @@ -1908,7 +1908,7 @@ static inline FORCEINLINE void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( ); } -static inline FORCEINLINE bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( +static inline FORCE_INLINE bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( NAME *table, const NAME* source #ifdef CTX_TY @@ -1925,22 +1925,22 @@ static inline FORCEINLINE bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( ); } -static inline FORCEINLINE size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table ) +static inline FORCE_INLINE size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table ) { return VT_CAT( NAME, _size )( table ); } -static inline FORCEINLINE size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table ) +static inline FORCE_INLINE size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table ) { return VT_CAT( NAME, _bucket_count )( table ); } -static inline FORCEINLINE bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +static inline FORCE_INLINE bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) { return VT_CAT( NAME, _is_end )( itr ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )( +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key #ifdef VAL_TY @@ -1957,7 +1957,7 @@ static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_C ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )( +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key #ifdef VAL_TY @@ -1974,47 +1974,47 @@ static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEM ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key ) +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key ) { return VT_CAT( NAME, _get )( table, key ); } -static inline FORCEINLINE bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key ) +static inline FORCE_INLINE bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key ) { return VT_CAT( NAME, _erase )( table, key ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) { return VT_CAT( NAME, _next )( itr ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr ) +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr ) { return VT_CAT( NAME, _erase_itr )( table, itr ); } -static inline FORCEINLINE bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count ) +static inline FORCE_INLINE bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count ) { return VT_CAT( NAME, _reserve )( table, bucket_count ); } -static inline FORCEINLINE bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table ) +static inline FORCE_INLINE bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table ) { return VT_CAT( NAME, _shrink )( table ); } -static inline FORCEINLINE VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table ) +static inline FORCE_INLINE VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table ) { return VT_CAT( NAME, _first )( table ); } -static inline FORCEINLINE void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table ) +static inline FORCE_INLINE void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table ) { VT_CAT( NAME, _clear )( table ); } -static inline FORCEINLINE void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table ) +static inline FORCE_INLINE void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table ) { VT_CAT( NAME, _cleanup )( table ); } @@ -2116,4 +2116,4 @@ C99 prefixed function API to circumvent this restriction. #undef IMPLEMENTATION_MODE #undef VT_API_FN_QUALIFIERS -#undef FORCEINLINE +#undef FORCE_INLINE From fedccd25b997b5b79cc9f67ac9381c8a9a579238 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 25 Feb 2026 18:04:45 +0100 Subject: [PATCH 32/42] hw_cache: use verstable for HWR_PrecacheLevelFlats flatchecks + convert to C replaces the unordered_set and doesent require c++ --- src/hardware/{hw_cache.cpp => hw_cache.c} | 100 ++++++++++++---------- src/hardware/hw_data.h | 2 +- 2 files changed, 58 insertions(+), 44 deletions(-) rename src/hardware/{hw_cache.cpp => hw_cache.c} (92%) diff --git a/src/hardware/hw_cache.cpp b/src/hardware/hw_cache.c similarity index 92% rename from src/hardware/hw_cache.cpp rename to src/hardware/hw_cache.c index 09f4f1a7b..f7cfceecb 100644 --- a/src/hardware/hw_cache.cpp +++ b/src/hardware/hw_cache.c @@ -15,8 +15,6 @@ #ifdef HWRENDER -#include - #include "hw_main.h" #include "hw_glob.h" #include "hw_gl.h" @@ -100,7 +98,7 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm position = 0; } - position = std::max(((position * scale_y) + (FRACUNIT/2)) >> FRACBITS, 0); + position = max(((position * scale_y) + (FRACUNIT/2)) >> FRACBITS, 0); if (position + count >= pblockheight) count = pblockheight - position; @@ -164,7 +162,7 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, fixed_t xfrac, xfracstep; fixed_t yfracstep, scale_y; const column_t *patchcol; - UINT8 *block = static_cast(mipmap->data); + UINT8 *block = (UINT8 *)(mipmap->data); INT32 bpp; INT32 blockmodulo; RGBA_t *palette; @@ -214,7 +212,7 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap, fixed_t xfrac, xfracstep; fixed_t yfracstep, scale_y; const column_t *patchcol; - UINT8 *block = static_cast(mipmap->data); + UINT8 *block = (UINT8 *)(mipmap->data); INT32 bpp; INT32 blockmodulo; INT32 width, height; @@ -290,7 +288,7 @@ static UINT8 *MakeBlock(GLMipmap_t *glMipmap) INT32 blocksize = (glMipmap->width * glMipmap->height); bpp = format2bpp(glMipmap->format); - block = static_cast(Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(glMipmap->data))); + block = (UINT8 *)(Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(glMipmap->data))); switch (bpp) { @@ -327,7 +325,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe texture = textures[texnum]; gltex->mipmap.flags = TF_CHROMAKEYED | TF_WRAPXY; - gltex->mipmap.format = static_cast(textureformat); + gltex->mipmap.format = (GLTextureFormat_t)(textureformat); // hack the Legacy skies.. if (UNLIKELY(memcmp(texture->name, "SKY", 3) == 0 && @@ -346,7 +344,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe colormap += COLORMAP_REMAPOFFSET; #endif - gltex->mipmap.colormap = static_cast(Z_Calloc(sizeof(*gltex->mipmap.colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + gltex->mipmap.colormap = (GLColormap_t *)(Z_Calloc(sizeof(*gltex->mipmap.colormap), PU_HWRPATCHCOLMIPMAP, NULL)); gltex->mipmap.colormap->source = colormap; memcpy(gltex->mipmap.colormap->data, colormap, 256 * sizeof(UINT8)); @@ -379,7 +377,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe // Composite the columns together. for (i = 0, patch = texture->patches; i < texture->patchcount; i++, patch++) { - pdata = static_cast(W_CacheLumpNumPwad(patch->wad, patch->lump, PU_LEVEL)); + pdata = (UINT8 *)(W_CacheLumpNumPwad(patch->wad, patch->lump, PU_LEVEL)); realpatch = (softwarepatch_t *)pdata; HWR_DrawTexturePatchInCache(&gltex->mipmap, blockwidth, blockheight, texture, patch, realpatch); @@ -415,7 +413,7 @@ void HWR_MakePatch(const patch_t *patch, GLPatch_t *glPatch, GLMipmap_t *glMipma glMipmap->flags = 0; // setup the texture info - glMipmap->format = static_cast(patchformat); + glMipmap->format = (GLTextureFormat_t)(patchformat); glPatch->max_s = (float)patch->width / (float)glMipmap->width; glPatch->max_t = (float)patch->height / (float)glMipmap->height; @@ -457,7 +455,7 @@ static void HWR_FreeTextureData(patch_t *patch) if (!patch || !patch->hardware) return; - glPatch = static_cast(patch->hardware); + glPatch = (GLPatch_t *)(patch->hardware); if (vid.glstate == VID_GL_LIBRARY_LOADED) GL_DeleteTexture(glPatch->mipmap); @@ -473,7 +471,7 @@ void HWR_FreeTexture(patch_t *patch) if (patch->hardware) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); HWR_FreeTextureColormaps(patch); @@ -499,7 +497,7 @@ static void HWR_FreeTextureColormaps(patch_t *patch) if (!patch) return; - pat = static_cast(patch->hardware); + pat = (GLPatch_t *)(patch->hardware); if (!pat) return; @@ -614,24 +612,20 @@ void HWR_FreeMapTextures(void) gl_numtextures = 0; } +#define NAME flatcheck +#define KEY_TY UINT32 +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#include "../verstable.h" + static void HWR_PrecacheLevelFlats(void) { // lookup for flats that may´ve been already loaded - // too lazy to make a hashtable or smth so unordered set will do :carbuncle: - std::unordered_set flatpresent; + flatcheck flatpresent; + flatcheck_init(&flatpresent); size_t i, j; INT32 k; - auto load_flat = [&](lumpnum_t lump, boolean noencoremap) - { - // flat already loaded? - if (flatpresent.count(lump) == 0) - { - HWR_GetFlat(lump, noencoremap); - flatpresent.insert(lump); - } - }; - // special case for encore #ifdef GLENCORE if (encoremap) @@ -649,14 +643,23 @@ static void HWR_PrecacheLevelFlats(void) const levelflat_t *levelflat = &levelflats[pic]; - load_flat(levelflat->lumpnum, R_NoEncore(sec, ceiling)); + if (flatcheck_is_end(flatcheck_get(&flatpresent, levelflat->lumpnum))) + { + HWR_GetFlat(levelflat->lumpnum, R_NoEncore(sec, ceiling)); + flatcheck_insert(&flatpresent, levelflat->lumpnum); + } if (levelflat->speed) // is it an animated flat ? { // start from 0, occasionally basenumlump != flat->lumpnum for (k = 0; k < levelflat->numpics; k++) { - load_flat(levelflat->baselumpnum + k, R_NoEncore(sec, ceiling)); + lumpnum_t lump = levelflat->baselumpnum + k; + if (flatcheck_is_end(flatcheck_get(&flatpresent, lump))) + { + HWR_GetFlat(lump, R_NoEncore(sec, ceiling)); + flatcheck_insert(&flatpresent, lump); + } } } } @@ -671,18 +674,29 @@ static void HWR_PrecacheLevelFlats(void) { const levelflat_t *levelflat = &levelflats[i]; - load_flat(levelflat->lumpnum, false); + if (flatcheck_is_end(flatcheck_get(&flatpresent, levelflat->lumpnum))) + { + HWR_GetFlat(levelflat->lumpnum, false); + flatcheck_insert(&flatpresent, levelflat->lumpnum); + } if (levelflat->speed) // is it an animated flat ? { // start from 0, occasionally basenumlump != flat->lumpnum for (k = 0; k < levelflat->numpics; k++) { - load_flat(levelflat->baselumpnum + k, false); + lumpnum_t lump = levelflat->baselumpnum + k; + if (flatcheck_is_end(flatcheck_get(&flatpresent, lump))) + { + HWR_GetFlat(lump, false); + flatcheck_insert(&flatpresent, lump); + } } } } } + + flatcheck_cleanup(&flatpresent); } static void HWR_PrecacheLevelTextures(void) @@ -692,7 +706,7 @@ static void HWR_PrecacheLevelTextures(void) size_t i, j, f; INT32 h; - texturepresent = static_cast(calloc(gl_numtextures, sizeof(*texturepresent))); + texturepresent = (char *)(calloc(gl_numtextures, sizeof(*texturepresent))); if (texturepresent == NULL) I_Error("%s: Out of memory looking up textures", "HWR_PrecacheLevel"); @@ -867,7 +881,7 @@ void HWR_LoadMapTextures(size_t pnumtextures) HWR_FreeMapTextures(); gl_numtextures = pnumtextures; - gl_textures = static_cast(calloc(gl_numtextures, sizeof(*gl_textures))); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore), see: GLMapTextureSet_t + gl_textures = (GLMapTextureSet_t *)(calloc(gl_numtextures, sizeof(*gl_textures))); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore), see: GLMapTextureSet_t if (gl_textures == NULL) I_Error("HWR_LoadMapTextures: ran out of memory for OpenGL textures. Sad!"); @@ -964,7 +978,7 @@ static void HWR_CacheFlat(GLMipmap_t *glMipmap, lumpnum_t flatlumpnum) W_ReadLump(flatlumpnum, Z_Malloc(size, PU_HWRCACHE, &glMipmap->data)); #ifdef GLENCORE - flat = static_cast(glMipmap->data); + flat = (UINT8 *)(glMipmap->data); for (steppy = 0; steppy < size; steppy++) { if (flat[steppy] == HWR_PATCHES_CHROMAKEY_COLORINDEX) @@ -1008,7 +1022,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) if (!noencoremap && encoremap) colormap += COLORMAP_REMAPOFFSET; #endif - glMipmap->colormap = static_cast(Z_Calloc(sizeof(*glMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + glMipmap->colormap = (GLColormap_t *)(Z_Calloc(sizeof(*glMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); glMipmap->colormap->source = colormap; memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); } @@ -1032,7 +1046,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) // --------------------+ static void HWR_LoadPatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); if (!glMipmap->downloaded) { @@ -1053,7 +1067,7 @@ static void HWR_LoadPatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) // ----------------------+ static void HWR_UpdatePatchMipmap(patch_t *patch, GLMipmap_t *glMipmap) { - GLPatch_t *glPatch = static_cast(patch->hardware); + GLPatch_t *glPatch = (GLPatch_t *)(patch->hardware); HWR_MakePatch(patch, glPatch, glMipmap, true); // If hardware does not have the texture, then call GL_SetTexture to upload it @@ -1089,7 +1103,7 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) if (!patch->hardware) Patch_CreateGL(patch); - glPatch = static_cast(patch->hardware); + glPatch = (GLPatch_t *)(patch->hardware); // Blatant hack for encore colormapping aside... if (colormap == colormaps || colormap == NULL || colormap == (const UINT8*)(COLORMAP_REMAPOFFSET)) @@ -1125,12 +1139,12 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) // (it have a liste of mipmap) // this malloc is cleared in HWR_FreeColormapCache // (...) unfortunately z_malloc fragment alot the memory :(so malloc is better - newMipmap = static_cast(calloc(1, sizeof (*newMipmap))); + newMipmap = (GLMipmap_t *)(calloc(1, sizeof (*newMipmap))); if (newMipmap == NULL) I_Error("%s: Out of memory", "HWR_GetMappedPatch"); glMipmap->nextcolormap = newMipmap; - newMipmap->colormap = static_cast(Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); + newMipmap->colormap = (GLColormap_t *)(Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL)); newMipmap->colormap->source = colormap; memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); @@ -1153,7 +1167,7 @@ patch_t *HWR_GetCachedGLPatchPwad(UINT16 wadnum, UINT16 lumpnum) { void *ptr = Z_Calloc(sizeof(patch_t), PU_PATCH, &lumpcache[lumpnum]); Patch_Create(NULL, 0, ptr); - Patch_AllocateHardwarePatch(static_cast(ptr)); + Patch_AllocateHardwarePatch((patch_t *)(ptr)); } return (patch_t *)(lumpcache[lumpnum]); @@ -1170,7 +1184,7 @@ static void HWR_DrawFadeMaskInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 { INT32 i,j; fixed_t posx, posy, stepx, stepy; - UINT8 *block = static_cast(mipmap->data); // places the data directly into here + UINT8 *block = (UINT8 *)(mipmap->data); // places the data directly into here UINT8 *flat; UINT8 *dest, *src, texel; RGBA_t col; @@ -1326,7 +1340,7 @@ void HWR_SetPalette(RGBA_t *palette) static void HWR_SetPaletteLookup(RGBA_t *palette) { int r, g, b; - UINT8 *lut = static_cast(Z_Malloc( + UINT8 *lut = (UINT8 *)(Z_Malloc( HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*HWR_PALETTE_LUT_SIZE*sizeof(UINT8), PU_STATIC, NULL)); #define STEP_SIZE (256/HWR_PALETTE_LUT_SIZE) @@ -1371,7 +1385,7 @@ void HWR_SetMapPalette(void) if (palsize < 768) // 256 * 3 I_Error("HWR_SetMapPalette: A programmer assumed palette lumps are at least 768 bytes long, but apparently this was a wrong assumption!\n"); - RGB_data = static_cast(W_CacheLumpNum(lumpnum, PU_CACHE)); + RGB_data = (UINT8 *)(W_CacheLumpNum(lumpnum, PU_CACHE)); // we got the RGB palette now, but we need it in RGBA format. for (i = 0; i < 256; i++) { @@ -1406,7 +1420,7 @@ static UINT32 HWR_CreateLightTable(UINT8 *lighttable) { UINT32 i, id; RGBA_t *palette = HWR_GetTexturePalette(); - RGBA_t *hw_lighttable = static_cast(Z_Malloc(256 * 32 * sizeof(RGBA_t), PU_STATIC, NULL)); + RGBA_t *hw_lighttable = (RGBA_t *)(Z_Malloc(256 * 32 * sizeof(RGBA_t), PU_STATIC, NULL)); // To make the palette index -> RGBA mapping easier for the shader, // the hardware lighttable is composed of RGBA colors instead of palette indices. diff --git a/src/hardware/hw_data.h b/src/hardware/hw_data.h index bb174b205..93ccfd4ac 100644 --- a/src/hardware/hw_data.h +++ b/src/hardware/hw_data.h @@ -54,7 +54,7 @@ struct GLMipmap_s UINT16 width, height; UINT32 downloaded; // The GPU has this texture. - struct GLMipmap_s *nextcolormap; + struct GLMipmap_s *nextcolormap; struct GLColormap_s *colormap; }; typedef struct GLMipmap_s GLMipmap_t; From 3c70598aea71a51dd2abfe71f641e4e09ad11421 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 25 Feb 2026 22:38:36 +0100 Subject: [PATCH 33/42] lumpnumcache: W_LumpExists should return true or false whoops was oversight by me prob doesent really matter due to wraparound but its still incorrect --- src/w_wad.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/w_wad.c b/src/w_wad.c index cfc25bbaa..5402e90a0 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -1431,7 +1431,7 @@ UINT8 W_LumpExists(const char *name) // Check the lumpnumcache first. lumpnum_t cachenum = CheckLumpInCache(name); if (cachenum != LUMPERROR) - return cachenum; + return true; namelen = strlen(name); hash = W_HashLumpName(name); From af84105e40b7928496e476cbeef97c00689fe2e8 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 10 Mar 2026 16:55:20 +0100 Subject: [PATCH 34/42] better error for nodeless maps --- src/p_setup.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/p_setup.c b/src/p_setup.c index c9aba324a..8b0074d2b 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -414,7 +414,7 @@ void P_UpdateSegLightOffset(seg_t *li) angle_t liAngle = R_PointToAngle2(0, 0, (li->v1->x - li->v2->x), (li->v1->y - li->v2->y)) - ANGLE_90; light = FixedMul(FINECOSINE(liAngle >> ANGLETOFINESHIFT), FINECOSINE(maplighting.angle >> ANGLETOFINESHIFT)) - + FixedMul(FINESINE(liAngle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); + + FixedMul(FINESINE(liAngle >> ANGLETOFINESHIFT), FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); light = (light + FRACUNIT) / 2; } else @@ -1914,7 +1914,7 @@ static void P_LoadMapBSP(const virtres_t* virt) if (numsubsectors <= 0) I_Error("Level has no subsectors (did you forget to run it through a nodesbuilder?)"); if (numnodes <= 0) - I_Error("Level has no nodes"); + I_Error("Level has no nodes (does your map have at least 2 sectors?)"); if (numsegs <= 0) I_Error("Level has no segs"); @@ -2077,10 +2077,10 @@ static void P_LevelInitStuff(boolean reloadinggamestate) stagefailed = false; // earthquake camera - memset(&quake,0,sizeof(struct quake)); + memset(&quake, 0, sizeof(struct quake)); // song credit init - memset(&cursongcredit,0,sizeof(struct cursongcredit)); + memset(&cursongcredit, 0, sizeof(struct cursongcredit)); cursongcredit.trans = NUMTRANSMAPS; for (i = 0; i < MAXPLAYERS; i++) From 98da654e027139c44b01c4b86affd478efbcfec2 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 10 Mar 2026 16:54:42 +0100 Subject: [PATCH 35/42] Fix P_MakeMapMD5 printing incorrect time :chonkbuncle: --- src/p_setup.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/p_setup.c b/src/p_setup.c index 8b0074d2b..3f3759bf9 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -2174,14 +2174,14 @@ static INT32 P_MakeBufferMD5(const char *buffer, size_t len, void *resblock) memset(resblock, 0x00, 16); return 1; #else - tic_t t = I_GetTime(); + precise_t t = I_GetPreciseTime(); CONS_Debug(DBG_SETUP, "Making MD5\n"); if (md5_buffer(buffer, len, resblock) == NULL) return 1; - CONS_Debug(DBG_SETUP, "MD5 calc took %f seconds\n", (float)(I_GetTime() - t)/NEWTICRATE); + CONS_Debug(DBG_SETUP, "MD5 calc took %f seconds\n", (float)(I_GetPreciseTime() - t)/I_GetPrecisePrecision()); return 0; #endif @@ -2203,10 +2203,10 @@ static void P_MakeMapMD5(virtres_t *virt, void *dest) virtlump_t* virtmthings = vres_Find(virt, "THINGS"); virtlump_t* virtsides = vres_Find(virt, "SIDEDEFS"); - P_MakeBufferMD5((char*)virtlines->data, virtlines->size, linemd5); - P_MakeBufferMD5((char*)virtsectors->data, virtsectors->size, sectormd5); - P_MakeBufferMD5((char*)virtmthings->data, virtmthings->size, thingmd5); - P_MakeBufferMD5((char*)virtsides->data, virtsides->size, sidedefmd5); + P_MakeBufferMD5((char*)virtlines->data, virtlines->size, linemd5); + P_MakeBufferMD5((char*)virtsectors->data, virtsectors->size, sectormd5); + P_MakeBufferMD5((char*)virtmthings->data, virtmthings->size, thingmd5); + P_MakeBufferMD5((char*)virtsides->data, virtsides->size, sidedefmd5); for (i = 0; i < 16; i++) resmd5[i] = (linemd5[i] + sectormd5[i] + thingmd5[i] + sidedefmd5[i]) & 0xFF; From c7845118c00e6364945d397675afbfb1f21a2d43 Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 25 Jan 2026 13:22:56 +0100 Subject: [PATCH 36/42] explicitly cast those --- src/hardware/hw_main.cpp | 15 +++++++-------- src/r_things.cpp | 2 +- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index bf11f0c7c..0806d05c8 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -3681,7 +3681,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // Draw shadow BEFORE sprite if (UNLIKELY(cv_shadow.value // Shadows enabled @@ -3783,10 +3783,10 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) { // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) - Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + Surf.PolyColor.s.alpha = static_cast(FixedMul(FRACUNIT/2, static_cast(Surf.PolyColor.s.alpha))); if (cv_playerfade.value) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + Surf.PolyColor.s.alpha = static_cast(FixedMul(R_DoPlayerFade(sprmo), static_cast(Surf.PolyColor.s.alpha))); } if (HWR_UseShader()) @@ -3969,7 +3969,7 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // create the sprite billboard // @@ -4080,10 +4080,10 @@ static void HWR_DrawSprite(gl_vissprite_t *spr) { // make hyu´d players translucent with reducevfx, could be done better, but im lazy as crap if (cv_reducevfx.value && sprmo->player->kartstuff[k_hyudorotimer] > 0) - Surf.PolyColor.s.alpha = FixedMul(FRACUNIT/2, Surf.PolyColor.s.alpha); + Surf.PolyColor.s.alpha = static_cast(FixedMul(FRACUNIT/2, static_cast(Surf.PolyColor.s.alpha))); if (cv_playerfade.value) - Surf.PolyColor.s.alpha = FixedMul(R_DoPlayerFade(sprmo), Surf.PolyColor.s.alpha); + Surf.PolyColor.s.alpha = static_cast(FixedMul(R_DoPlayerFade(sprmo), static_cast(Surf.PolyColor.s.alpha))); } if (HWR_UseShader()) @@ -4119,7 +4119,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) //Hurdler: 25/04/2000: now support colormap in hardware mode HWR_GetMappedPatch(gpatch, spr->colormap); - hwrpatch = ((GLPatch_t *)gpatch->hardware); + hwrpatch = static_cast(gpatch->hardware); // create the sprite billboard // @@ -4510,7 +4510,6 @@ static void HWR_RenderDrawNodes(void) drawnodes.clear(); // clear so our size is 0 again! } - // -------------------------------------------------------------------------- // Draw all vissprites // -------------------------------------------------------------------------- diff --git a/src/r_things.cpp b/src/r_things.cpp index 9da1f4c3e..310896a68 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -1662,7 +1662,7 @@ static void R_ProjectSprite(mobj_t *thing) if (thing->frame & FF_ABSOLUTELIGHTLEVEL) { - const UINT8 n = R_ThingLightLevel(thing); + const UINT8 n = static_cast(R_ThingLightLevel(thing)); // n = uint8 aka 0 - 255, so the shift will always be 0 - LIGHTLEVELS - 1 lights_array = scalelight[n >> LIGHTSEGSHIFT]; } From d6ed923f831e517f6ad33419ae6e44eac6b6a18b Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 10 Feb 2026 16:43:34 +0100 Subject: [PATCH 37/42] P_XYMovement: check for kart specific stuff first to determine friction apply this stuff is much more common than the other stuff being checked, so more likely to return earlier and save a bunch of other checks --- src/p_mobj.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/p_mobj.c b/src/p_mobj.c index d44a48f1c..01b3977d0 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -1670,6 +1670,14 @@ void P_XYMovement(mobj_t *mo) if (mo->flags & MF_NOCLIPHEIGHT) return; // no frictions for objects that can pass through floors + //{ SRB2kart stuff + if (mo->type == MT_ORBINAUT || mo->type == MT_JAWZ_DUD || mo->type == MT_JAWZ || mo->type == MT_BALLHOG) //(mo->type == MT_JAWZ && !mo->tracer)) + return; + + if (mo->player && (mo->player->kartstuff[k_spinouttimer] && !mo->player->kartstuff[k_wipeoutslow]) && mo->player->speed <= K_GetKartSpeed(mo->player, false)/2) + return; + //} + if (mo->flags & MF_MISSILE || mo->flags2 & MF2_SKULLFLY || mo->type == MT_SHELL || mo->type == MT_VULTURE) return; // no friction for missiles ever @@ -1683,14 +1691,6 @@ void P_XYMovement(mobj_t *mo) && (mo->standingslope && abs(mo->standingslope->zdelta) > FRACUNIT>>8)) // Special exception for tumbleweeds on slopes return; - //{ SRB2kart stuff - if (mo->type == MT_ORBINAUT || mo->type == MT_JAWZ_DUD || mo->type == MT_JAWZ || mo->type == MT_BALLHOG) //(mo->type == MT_JAWZ && !mo->tracer)) - return; - - if (mo->player && (mo->player->kartstuff[k_spinouttimer] && !mo->player->kartstuff[k_wipeoutslow]) && mo->player->speed <= K_GetKartSpeed(mo->player, false)/2) - return; - //} - if (((!(mo->eflags & MFE_VERTICALFLIP) && mo->z > mo->floorz) || (mo->eflags & MFE_VERTICALFLIP && mo->z+mo->height < mo->ceilingz)) && !(player && player->pflags & PF_SLIDING)) return; // no friction when airborne From 04f63b23ffe1c6a47ef82a707f3f23f080ab1b69 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 4 Feb 2026 13:02:27 +0100 Subject: [PATCH 38/42] software: hack for bogus height walls as per comment, this is merely a shitty workaround for a chain reaction of bad fixed point maths since im honestly not feeling like rewriting most of the software renderer to either operate on 64bit or float maths, we just skip drawing anything that seems completely unreasonable --- src/r_segs.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/r_segs.cpp b/src/r_segs.cpp index 660b91494..a53d40ec4 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -1222,6 +1222,15 @@ static void R_RenderSegLoop(drawcolumndata_t* dc) if (yl < top) yl = top; + // insanely shitty hack to fix flickering on some maps + // for god knows why, on secret slide the renderer assumes some double sided linedefs have insanely tall walls + // since such tall walls are effectively nonsense in any case + // just skip them + if (yl > FRACUNIT*3) + { + continue; + } + if (markceiling) { bottom = yl > floorclip[rw_x] ? floorclip[rw_x] : yl; From 1aa37be676f67307f755bd4fc2dcae3c2cf55e55 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 10 Feb 2026 16:41:46 +0100 Subject: [PATCH 39/42] p_user: cache kartspeed value within P_3dMovement its result shouldnt change there, so no need to always recompute stuff, even if its not heavy work --- src/p_user.c | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/p_user.c b/src/p_user.c index 99566aa24..7c4756bfa 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -1992,20 +1992,23 @@ static void P_3dMovement(player_t *player) K_MomentumToFacing(player); } + const fixed_t kartspd = K_GetKartSpeed(player, true); + // Sideways movement if (cmd->sidemove != 0 && !((player->exiting || mapreset) || player->kartstuff[k_spinouttimer])) { if (cmd->sidemove > 0) - movepushside = (cmd->sidemove * FRACUNIT/128) + FixedDiv(player->speed, K_GetKartSpeed(player, true)); + movepushside = (cmd->sidemove * FRACUNIT/128) + FixedDiv(player->speed, kartspd); else - movepushside = (cmd->sidemove * FRACUNIT/128) - FixedDiv(player->speed, K_GetKartSpeed(player, true)); + movepushside = (cmd->sidemove * FRACUNIT/128) - FixedDiv(player->speed, kartspd); totalthrust.x += P_ReturnThrustX(player->mo, movepushsideangle, movepushside); totalthrust.y += P_ReturnThrustY(player->mo, movepushsideangle, movepushside); } if ((totalthrust.x || totalthrust.y) - && player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && abs(player->mo->standingslope->zdelta) > FRACUNIT/2) { + && player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && abs(player->mo->standingslope->zdelta) > FRACUNIT/2) + { // Factor thrust to slope, but only for the part pushing up it! // The rest is unaffected. angle_t thrustangle = R_PointToAngle2(0, 0, totalthrust.x, totalthrust.y)-player->mo->standingslope->xydirection; @@ -2041,11 +2044,11 @@ static void P_3dMovement(player_t *player) // -Shadow Hog newMagnitude = R_PointToDist2(player->mo->momx - player->cmomx, player->mo->momy - player->cmomy, 0, 0); - if (newMagnitude > K_GetKartSpeed(player, true)) //topspeed) + if (newMagnitude > kartspd) //topspeed) { fixed_t tempmomx, tempmomy; - if (oldMagnitude > K_GetKartSpeed(player, true) && onground) // SRB2Kart: onground check for air speed cap + if (oldMagnitude > kartspd && onground) // SRB2Kart: onground check for air speed cap { if (newMagnitude > oldMagnitude) { @@ -2058,8 +2061,8 @@ static void P_3dMovement(player_t *player) } else { - tempmomx = FixedMul(FixedDiv(player->mo->momx - player->cmomx, newMagnitude), K_GetKartSpeed(player, true)); //topspeed) - tempmomy = FixedMul(FixedDiv(player->mo->momy - player->cmomy, newMagnitude), K_GetKartSpeed(player, true)); //topspeed) + tempmomx = FixedMul(FixedDiv(player->mo->momx - player->cmomx, newMagnitude), kartspd); //topspeed) + tempmomy = FixedMul(FixedDiv(player->mo->momy - player->cmomy, newMagnitude), kartspd); //topspeed) player->mo->momx = tempmomx + player->cmomx; player->mo->momy = tempmomy + player->cmomy; } @@ -2474,9 +2477,10 @@ static void P_MovePlayer(player_t *player) const fixed_t runnyspeed = 20*FRACUNIT; speed = R_PointToDist2(player->rmomx, player->rmomy, 0, 0); + const fixed_t kartspd = K_GetKartSpeed(player, false); - if (speed > K_GetKartSpeed(player, false)-(5< kartspd-(5<= runnyspeed) player->fovadd = speed-runnyspeed; @@ -4584,7 +4588,7 @@ void P_PlayerThink(player_t *player) } #ifdef SEENAMES - if (netgame && player == &players[displayplayers[0]] && !(leveltime % (TICRATE/5)) && !splitscreen) + if (netgame && !splitscreen && player == &players[displayplayers[0]] && !(leveltime % (TICRATE/5))) { seenplayer = NULL; From 9087fd8377ee2e8947aef59fa43741055b4d76dd Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 26 Jan 2026 17:30:09 +0100 Subject: [PATCH 40/42] lua hooklib: use NUMMOBJTYPES to detect mobj hooks removes the "force_mobj" field, gives a suprising perf boost from my timedemo testing +6-7fps (164 - 169/170fps) this does however will prevent the generic hook from being called if the mobj being passed ever should be NULL This shouldnt ever happen, vanilla assumes this aswell and way worse things would happen there, but just wanted to note --- src/lua_hooklib.c | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index 59d1bc1f8..af15120ba 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -199,7 +199,7 @@ FUNCINLINE static ATTRINLINE void add_hook(hook_t *map) FUNCINLINE static ATTRINLINE void add_mobj_hook(lua_State *L, int hook_type) { - mobjtype_t mobj_type = luaL_optnumber(L, 3, MT_NULL); + mobjtype_t mobj_type = luaL_optnumber(L, 3, MT_NULL); luaL_argcheck(L, mobj_type < NUMMOBJTYPES, 3, "invalid mobjtype_t"); @@ -296,8 +296,7 @@ struct Hook_State { INT32 status;/* return status to calling function */ void * userdata; int hook_type; - mobjtype_t mobj_type;/* >0 if mobj hook */ - boolean force_mobj;// allows mobj_type equal 0 + mobjtype_t mobj_type;/* force_mobj = false; - return init_hook_type(hook, default_status, - hook_type, 0, NULL, + hook_type, NUMMOBJTYPES, NULL, hookIds[hook_type].numHooks); } @@ -381,8 +378,6 @@ FUNCINLINE static ATTRINLINE boolean prepare_mobj_hook const mobjtype_t mobj_type = primary_mobj ? primary_mobj->type : NUMMOBJTYPES; - hook->force_mobj = true; - return init_hook_type(hook, default_status, hook_type, mobj_type, NULL, mobj_hook_available(hook_type, mobj_type)); @@ -395,10 +390,8 @@ FUNCINLINE static ATTRINLINE boolean prepare_string_hook int hook_type, const char * string ){ - hook->force_mobj = false; - if (init_hook_type(hook, default_status, - hook_type, 0, string, + hook_type, NUMMOBJTYPES, string, stringHooks[hook_type].ref)) { lua_pushstring(gL, string); @@ -414,7 +407,7 @@ FUNCINLINE static ATTRINLINE boolean prepare_hud_hook int hook_type ){ return init_hook_type(hook, 0, - hook_type, 0, NULL, + hook_type, NUMMOBJTYPES, NULL, hudHookIds[hook_type].numHooks); } @@ -554,14 +547,11 @@ static int call_hooks { calls += call_string_hooks(hook); } - else if (hook->force_mobj) + else if (hook->mobj_type < NUMMOBJTYPES) { /* call generic mobj hooks first */ calls += call_mobj_type_hooks(hook, MT_NULL); - - if (hook->mobj_type < NUMMOBJTYPES) - calls += call_mobj_type_hooks(hook, hook->mobj_type); - + calls += call_mobj_type_hooks(hook, hook->mobj_type); ps_lua_mobjhooks.value.i += calls; } else From a0dffd0670b579b25b78ca2fdb486975bb7ef66e Mon Sep 17 00:00:00 2001 From: Indev Date: Mon, 16 Mar 2026 04:07:42 +0300 Subject: [PATCH 41/42] Fix listemotes calculating incorrect number of pages --- src/m_emotes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/m_emotes.cpp b/src/m_emotes.cpp index 515799af3..fe90c9a11 100644 --- a/src/m_emotes.cpp +++ b/src/m_emotes.cpp @@ -278,7 +278,7 @@ void M_DrawScaledEmote(fixed_t x, fixed_t y, fixed_t scale, emote_t *emote, INT3 static void Command_ListEmotes_f(void) { const int EMOTES_PER_PAGE = 24; - const int NUMPAGES = std::max(emotes.size()/EMOTES_PER_PAGE, 1); + const int NUMPAGES = emotes.size()/EMOTES_PER_PAGE + (emotes.size() % EMOTES_PER_PAGE != 0 ? 1 : 0); int page = 1; if (COM_Argc() > 1) From e13cb1ca9274c982ac2fd6588b0572371f4af8d7 Mon Sep 17 00:00:00 2001 From: Indev Date: Tue, 17 Mar 2026 19:00:38 +0300 Subject: [PATCH 42/42] Remove few remaining flashpal things in opengl menu --- src/m_menu.c | 1 - src/m_menudefs.c | 3 --- 2 files changed, 4 deletions(-) diff --git a/src/m_menu.c b/src/m_menu.c index ca408dc79..26b7213ab 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -2075,7 +2075,6 @@ void M_Init(void) OP_OpenGLOptionsMenu[op_gl_shader].status = IT_GRAYEDOUT; OP_OpenGLOptionsMenu[op_gl_lightdither].status = IT_GRAYEDOUT; OP_OpenGLOptionsMenu[op_gl_palrender].status = IT_GRAYEDOUT; - OP_OpenGLOptionsMenu[op_gl_flashpal].status = IT_GRAYEDOUT; OP_ExpOptionsMenu[op_exp_paldepth].status = IT_GRAYEDOUT; } diff --git a/src/m_menudefs.c b/src/m_menudefs.c index aa3f186c8..e734021eb 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -1043,7 +1043,6 @@ static const char* OP_OpenGLTooltips[] = "Fallback 3D model for characters that don't have any.", "Graphical Shaders.", "Recreates the look of software mode.", - "Flash palettes for palette rendering.", "Bit-depth of textures.", "Filter to use on textures.", "Anisotropic filtering.", @@ -1062,7 +1061,6 @@ enum op_gl_falbckmdls, op_gl_shader, op_gl_palrender, - op_gl_flashpal, op_gl_scrdepth, op_gl_filter, op_gl_anis, @@ -2772,6 +2770,5 @@ void M_UpdateOGLMenu(void) OP_OpenGLOptionsMenu[op_gl_lightdither].status = (!HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; OP_OpenGLOptionsMenu[op_gl_palrender].status = (cv_glscreentextures.value != 2 || !HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; - OP_OpenGLOptionsMenu[op_gl_flashpal].status = (!HWR_ShouldUsePaletteRendering()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; } #endif