diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 1cf61a2..764465b 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -27,20 +27,15 @@ - - - - - + - + + - - @@ -50,13 +45,14 @@ - - + + + + - - + @@ -67,37 +63,73 @@ + + + + + + + + + + + - - - + + + + + + + + - + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + - \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index cc17ed1..14cc516 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,4 +15,6 @@ target_link_libraries(quakespasm vorbisfile) target_link_libraries(quakespasm vorbis) target_link_libraries(quakespasm ogg) target_link_libraries(quakespasm mad) -target_link_libraries(quakespasm m) \ No newline at end of file +target_link_libraries(quakespasm m) + +add_compile_definitions(USE_CODEC_VORBIS) \ No newline at end of file diff --git a/Quake/bgmusic.cpp b/Quake/bgmusic.cpp index aa612e3..b1803c7 100644 --- a/Quake/bgmusic.cpp +++ b/Quake/bgmusic.cpp @@ -26,453 +26,420 @@ #include "snd_codec.hpp" #include "bgmusic.hpp" +#include + #define MUSIC_DIRNAME "music" -qboolean bgmloop; -convar bgm_extmusic{"bgm_extmusic", "1", {.archive = true}}; -static qboolean no_extmusic= false; -static float old_volume = -1.0f; - -typedef enum _bgm_player -{ - BGM_NONE = -1, - BGM_MIDIDRV = 1, - BGM_STREAMER -} bgm_player_t; - -typedef struct music_handler_s -{ - unsigned int type; /* 1U << n (see snd_codec.h) */ - bgm_player_t player; /* Enumerated bgm player type */ - int is_available; /* -1 means not present */ - const char *ext; /* Expected file extension */ - const char *dir; /* Where to look for music file */ - struct music_handler_s *next; -} music_handler_t; - -static music_handler_t wanted_handlers[] = -{ - { CODECTYPE_VORBIS,BGM_STREAMER,-1, "ogg", MUSIC_DIRNAME, NULL }, - { CODECTYPE_OPUS, BGM_STREAMER, -1, "opus", MUSIC_DIRNAME, NULL }, - { CODECTYPE_MP3, BGM_STREAMER, -1, "mp3", MUSIC_DIRNAME, NULL }, - { CODECTYPE_FLAC, BGM_STREAMER, -1, "flac", MUSIC_DIRNAME, NULL }, - { CODECTYPE_WAV, BGM_STREAMER, -1, "wav", MUSIC_DIRNAME, NULL }, - { CODECTYPE_MOD, BGM_STREAMER, -1, "it", MUSIC_DIRNAME, NULL }, - { CODECTYPE_MOD, BGM_STREAMER, -1, "s3m", MUSIC_DIRNAME, NULL }, - { CODECTYPE_MOD, BGM_STREAMER, -1, "xm", MUSIC_DIRNAME, NULL }, - { CODECTYPE_MOD, BGM_STREAMER, -1, "mod", MUSIC_DIRNAME, NULL }, - { CODECTYPE_UMX, BGM_STREAMER, -1, "umx", MUSIC_DIRNAME, NULL }, - { CODECTYPE_NONE, BGM_NONE, -1, NULL, NULL, NULL } -}; - -static music_handler_t *music_handlers = NULL; - -#define ANY_CODECTYPE 0xFFFFFFFF #define CDRIP_TYPES (CODECTYPE_VORBIS | CODECTYPE_MP3 | CODECTYPE_FLAC | CODECTYPE_WAV | CODECTYPE_OPUS) #define CDRIPTYPE(x) (((x) & CDRIP_TYPES) != 0) -static snd_stream_t *bgmstream = NULL; +namespace music { + bool bgmloop; + convar bgm_extmusic{"bgm_extmusic", "1", {.archive = true}}; -static void BGM_Play_f (void) -{ - if (command::argc() == 2) { - BGM_Play (command::argv(1)->c_str()); - } - else { - Con_Printf ("music \n"); - } + namespace { + snd_stream_t *bgmstream = nullptr; + bool no_extmusic = false; + float old_volume = -1.0f; + + constexpr unsigned int ANY_CODECTYPE = 0xFFFFFFFF; + + + enum class player_kind { + none = -1, + midi_drv = 1, + streamer + }; + + struct handler { + unsigned int type; /* 1U << n (see snd_codec.h) */ + player_kind player; /* Enumerated bgm player type */ + int is_available; /* -1 means not present */ + const char *ext; /* Expected file extension */ + const char *dir; /* Where to look for music file */ + }; + + std::vector active_handlers{}; + + std::array wanted_handlers = + { + handler{ + .type = CODECTYPE_VORBIS, .player = player_kind::streamer, .is_available = -1, .ext = "ogg", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_OPUS, .player = player_kind::streamer, .is_available = -1, .ext = "opus", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_MP3, .player = player_kind::streamer, .is_available = -1, .ext = "mp3", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_FLAC, .player = player_kind::streamer, .is_available = -1, .ext = "flac", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_WAV, .player = player_kind::streamer, .is_available = -1, .ext = "wav", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "it", .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "s3m", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "xm", .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_MOD, .player = player_kind::streamer, .is_available = -1, .ext = "mod", + .dir = MUSIC_DIRNAME + }, + handler{ + .type = CODECTYPE_UMX, .player = player_kind::streamer, .is_available = -1, .ext = "umx", + .dir = MUSIC_DIRNAME + }, + handler{.type = CODECTYPE_NONE, .player = player_kind::none, .is_available = -1, .ext = nullptr, .dir = nullptr} + }; + + void _play() { + if (command::argc() == 2) { + play(*command::argv(1)); + } else { + Con_Printf("music \n"); + } + } + + void _pause() { + pause(); + } + + void _resume() { + resume(); + } + + void _loop() { + if (command::argc() == 2) { + if (q_strcasecmp(command::argv(1)->c_str(), "0") == 0 || + q_strcasecmp(command::argv(1)->c_str(), "off") == 0) + bgmloop = false; + else if (q_strcasecmp(command::argv(1)->c_str(), "1") == 0 || + q_strcasecmp(command::argv(1)->c_str(), "on") == 0) + bgmloop = true; + else if (q_strcasecmp(command::argv(1)->c_str(), "toggle") == 0) + bgmloop = !bgmloop; + + if (bgmstream) bgmstream->loop = bgmloop; + } + + if (bgmloop) + Con_Printf("Music will be looped\n"); + else + Con_Printf("Music will not be looped\n"); + } + + void _stop() { + stop(); + } + + void _jump() { + if (command::argc() != 2) { + Con_Printf("music_jump \n"); + } else if (bgmstream) { + S_CodecJumpToOrder(bgmstream, static_cast(std::strtol(command::argv(1)->c_str(), nullptr, 10))); + } + } + + void play_noext(const std::string &filename, const unsigned int allowed_types) { + char tmp[MAX_QPATH]; + + for (auto &handler: active_handlers) { + if (!(handler.type & allowed_types)) { + continue; + } + if (!handler.is_available) { + continue; + } + q_snprintf(tmp, sizeof(tmp), "%s/%s.%s", + handler.dir, filename.c_str(), handler.ext); + switch (handler.player) { + case player_kind::midi_drv: + /* not supported in quake */ + break; + case player_kind::streamer: + bgmstream = S_CodecOpenStreamType(tmp, handler.type, bgmloop); + if (bgmstream) + return; /* success */ + break; + case player_kind::none: + default: + break; + } + } + + Con_Printf("Couldn't handle music file %s\n", filename.c_str()); + } + + void update_stream() { + bool did_rewind = false; + int res; /* Number of bytes read. */ + int bufferSamples; + int fileSamples; + int fileBytes; + byte raw[16384]; + + if (bgmstream->status != STREAM_PLAY) { + return; + } + + /* don't bother playing anything if musicvolume is 0 */ + if (bgmvolume.value <= 0) { + return; + } + + /* see how many samples should be copied into the raw buffer */ + if (s_rawend < paintedtime) { + s_rawend = paintedtime; + } + + while (s_rawend < paintedtime + MAX_RAW_SAMPLES) { + bufferSamples = MAX_RAW_SAMPLES - (s_rawend - paintedtime); + + /* decide how much data needs to be read from the file */ + fileSamples = bufferSamples * bgmstream->info.rate / shm->speed; + if (!fileSamples) + return; + + /* our max buffer size */ + fileBytes = fileSamples * (bgmstream->info.width * bgmstream->info.channels); + if (fileBytes > (int) sizeof(raw)) { + fileBytes = (int) sizeof(raw); + fileSamples = fileBytes / + (bgmstream->info.width * bgmstream->info.channels); + } + + /* Read */ + res = S_CodecReadStream(bgmstream, fileBytes, raw); + if (res < fileBytes) { + fileBytes = res; + fileSamples = res / (bgmstream->info.width * bgmstream->info.channels); + } + + if (res > 0) /* data: add to raw buffer */ + { + S_RawSamples(fileSamples, bgmstream->info.rate, + bgmstream->info.width, + bgmstream->info.channels, + raw, bgmvolume.value); + did_rewind = false; + } else if (res == 0) /* EOF */ + { + if (bgmloop) { + if (did_rewind) { + Con_Printf("Stream keeps returning EOF.\n"); + stop(); + return; + } + + res = S_CodecRewindStream(bgmstream); + if (res != 0) { + Con_Printf("Stream seek error (%i), stopping.\n", res); + stop(); + return; + } + did_rewind = true; + } else { + stop(); + return; + } + } else /* res < 0: some read error */ + { + Con_Printf("Stream read error (%i), stopping.\n", res); + stop(); + return; + } + } + } + } + + void init() { + bgm_extmusic.inscribe(); + command::add("music", _play); + command::add("music_pause", _pause); + command::add("music_resume", _resume); + command::add("music_loop", _loop); + command::add("music_stop", _stop); + command::add("music_jump", _jump); + + if (common::check_param("-noextmusic").has_value()) + no_extmusic = true; + + bgmloop = true; + + for (auto i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++) { + switch (wanted_handlers[i].player) { + case player_kind::midi_drv: + /* not supported in quake */ + break; + case player_kind::streamer: + wanted_handlers[i].is_available = + S_CodecIsAvailable(wanted_handlers[i].type); + break; + case player_kind::none: + default: + break; + } + if (wanted_handlers[i].is_available != -1) { + active_handlers.push_back(wanted_handlers[i]); + } + } + } + + void shutdown() { + stop(); + active_handlers.clear(); + } + + void play(const std::string &filename) { + char tmp[MAX_QPATH]; + + stop(); + + if (active_handlers.empty()) + return; + + if (filename.empty()) { + Con_DPrintf("null music file name\n"); + return; + } + + const char *ext = COM_FileGetExtension(filename.c_str()); + if (*ext == '\0') /* try all things */ + { + play_noext(filename, ANY_CODECTYPE); + return; + } + + const handler *chosen = nullptr; + for (const auto &handler: active_handlers) { + if (handler.is_available && + !q_strcasecmp(ext, handler.ext)) { + chosen = &handler; + break; + } + } + if (chosen == nullptr) { + Con_Printf("Unhandled extension for %s\n", filename.c_str()); + return; + } + q_snprintf(tmp, sizeof(tmp), "%s/%s", chosen->dir, filename.c_str()); + switch (chosen->player) { + case player_kind::midi_drv: + /* not supported in quake */ + break; + case player_kind::streamer: + bgmstream = S_CodecOpenStreamType(tmp, chosen->type, bgmloop); + if (bgmstream) + return; /* success */ + break; + case player_kind::none: + default: + break; + } + + Con_Printf("Couldn't handle music file %s\n", filename.c_str()); + } + + void stop() { + if (bgmstream) { + bgmstream->status = STREAM_NONE; + S_CodecCloseStream(bgmstream); + bgmstream = nullptr; + s_rawend = 0; + } + } + + void update() { + if (old_volume != bgmvolume.value) { + if (bgmvolume.value < 0) + bgmvolume.set("0"); + else if (bgmvolume.value > 1) + bgmvolume.set("1"); + old_volume = bgmvolume.value; + } + if (bgmstream) + update_stream(); + } + + void pause() { + if (bgmstream) { + if (bgmstream->status == STREAM_PLAY) + bgmstream->status = STREAM_PAUSE; + } + } + + void resume() { + if (bgmstream) { + if (bgmstream->status == STREAM_PAUSE) + bgmstream->status = STREAM_PLAY; + } + } + + void play_cd_track(const byte track, const bool looping) { + /* instead of searching by the order of music_handlers, do so by + * the order of searchpath priority: the file from the searchpath + * with the highest path_id is most likely from our own gamedir + * itself. This way, if a mod has track02 as a *.mp3 file, which + * is below *.ogg in the music_handler order, the mp3 will still + * have priority over track02.ogg from, say, id1. + */ + char tmp[MAX_QPATH]; + unsigned int path_id; + + stop(); + if (CDAudio_Play(track, looping) == 0) { + return; /* success */ + } + + if (active_handlers.empty()) + return; // We obviously can't play anything without handlers. + + if (no_extmusic || bgm_extmusic.value == 0.0) + return; + + unsigned int prev_id = 0; + unsigned int type = 0; + const char *ext = nullptr; + for (const auto handler: active_handlers) { + if (!handler.is_available) { + continue; + } + if (!CDRIPTYPE(handler.type)) { + continue; + } + q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s", + MUSIC_DIRNAME, static_cast(track), handler.ext); + if (!COM_FileExists(tmp, &path_id)) { + continue; + } + if (path_id > prev_id) { + prev_id = path_id; + type = handler.type; + ext = handler.ext; + } + } + + if (ext == nullptr) + Con_Printf("Couldn't find a cdrip for track %d\n", static_cast(track)); + else { + q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s", + MUSIC_DIRNAME, static_cast(track), ext); + bgmstream = S_CodecOpenStreamType(tmp, type, bgmloop); + if (!bgmstream) + Con_Printf("Couldn't handle music file %s\n", tmp); + } + } } - -static void BGM_Pause_f (void) -{ - BGM_Pause (); -} - -static void BGM_Resume_f (void) -{ - BGM_Resume (); -} - -static void BGM_Loop_f (void) -{ - if (command::argc() == 2) { - if (q_strcasecmp(command::argv(1)->c_str(), "0") == 0 || - q_strcasecmp(command::argv(1)->c_str(),"off") == 0) - bgmloop = false; - else if (q_strcasecmp(command::argv(1)->c_str(), "1") == 0 || - q_strcasecmp(command::argv(1)->c_str(),"on") == 0) - bgmloop = true; - else if (q_strcasecmp(command::argv(1)->c_str(),"toggle") == 0) - bgmloop = !bgmloop; - - if (bgmstream) bgmstream->loop = bgmloop; - } - - if (bgmloop) - Con_Printf("Music will be looped\n"); - else - Con_Printf("Music will not be looped\n"); -} - -static void BGM_Stop_f (void) -{ - BGM_Stop(); -} - -static void BGM_Jump_f (void) -{ - if (command::argc() != 2) { - Con_Printf ("music_jump \n"); - } - else if (bgmstream) { - S_CodecJumpToOrder(bgmstream, atoi(command::argv(1)->c_str())); - } -} - -qboolean BGM_Init (void) -{ - music_handler_t *handlers = NULL; - int i; - - bgm_extmusic.inscribe(); - command::add("music", BGM_Play_f); - command::add("music_pause", BGM_Pause_f); - command::add("music_resume", BGM_Resume_f); - command::add("music_loop", BGM_Loop_f); - command::add("music_stop", BGM_Stop_f); - command::add("music_jump", BGM_Jump_f); - - if (COM_CheckParm("-noextmusic") != 0) - no_extmusic = true; - - bgmloop = true; - - for (i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++) - { - switch (wanted_handlers[i].player) - { - case BGM_MIDIDRV: - /* not supported in quake */ - break; - case BGM_STREAMER: - wanted_handlers[i].is_available = - S_CodecIsAvailable(wanted_handlers[i].type); - break; - case BGM_NONE: - default: - break; - } - if (wanted_handlers[i].is_available != -1) - { - if (handlers) - { - handlers->next = &wanted_handlers[i]; - handlers = handlers->next; - } - else - { - music_handlers = &wanted_handlers[i]; - handlers = music_handlers; - } - } - } - - return true; -} - -void BGM_Shutdown (void) -{ - BGM_Stop(); -/* sever our connections to - * midi_drv and snd_codec */ - music_handlers = NULL; -} - -static void BGM_Play_noext (const char *filename, unsigned int allowed_types) -{ - char tmp[MAX_QPATH]; - music_handler_t *handler; - - handler = music_handlers; - while (handler) - { - if (! (handler->type & allowed_types)) - { - handler = handler->next; - continue; - } - if (!handler->is_available) - { - handler = handler->next; - continue; - } - q_snprintf(tmp, sizeof(tmp), "%s/%s.%s", - handler->dir, filename, handler->ext); - switch (handler->player) - { - case BGM_MIDIDRV: - /* not supported in quake */ - break; - case BGM_STREAMER: - bgmstream = S_CodecOpenStreamType(tmp, handler->type, bgmloop); - if (bgmstream) - return; /* success */ - break; - case BGM_NONE: - default: - break; - } - handler = handler->next; - } - - Con_Printf("Couldn't handle music file %s\n", filename); -} - -void BGM_Play (const char *filename) -{ - char tmp[MAX_QPATH]; - const char *ext; - music_handler_t *handler; - - BGM_Stop(); - - if (music_handlers == NULL) - return; - - if (!filename || !*filename) - { - Con_DPrintf("null music file name\n"); - return; - } - - ext = COM_FileGetExtension(filename); - if (! *ext) /* try all things */ - { - BGM_Play_noext(filename, ANY_CODECTYPE); - return; - } - - handler = music_handlers; - while (handler) - { - if (handler->is_available && - !q_strcasecmp(ext, handler->ext)) - break; - handler = handler->next; - } - if (!handler) - { - Con_Printf("Unhandled extension for %s\n", filename); - return; - } - q_snprintf(tmp, sizeof(tmp), "%s/%s", handler->dir, filename); - switch (handler->player) - { - case BGM_MIDIDRV: - /* not supported in quake */ - break; - case BGM_STREAMER: - bgmstream = S_CodecOpenStreamType(tmp, handler->type, bgmloop); - if (bgmstream) - return; /* success */ - break; - case BGM_NONE: - default: - break; - } - - Con_Printf("Couldn't handle music file %s\n", filename); -} - -void BGM_PlayCDtrack (byte track, qboolean looping) -{ -/* instead of searching by the order of music_handlers, do so by - * the order of searchpath priority: the file from the searchpath - * with the highest path_id is most likely from our own gamedir - * itself. This way, if a mod has track02 as a *.mp3 file, which - * is below *.ogg in the music_handler order, the mp3 will still - * have priority over track02.ogg from, say, id1. - */ - char tmp[MAX_QPATH]; - const char *ext; - unsigned int path_id, prev_id, type; - music_handler_t *handler; - - BGM_Stop(); - if (CDAudio_Play(track, looping) == 0) - return; /* success */ - - if (music_handlers == NULL) - return; - - if (no_extmusic || !bgm_extmusic.value) - return; - - prev_id = 0; - type = 0; - ext = NULL; - handler = music_handlers; - while (handler) - { - if (! handler->is_available) - goto _next; - if (! CDRIPTYPE(handler->type)) - goto _next; - q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s", - MUSIC_DIRNAME, (int)track, handler->ext); - if (! COM_FileExists(tmp, &path_id)) - goto _next; - if (path_id > prev_id) - { - prev_id = path_id; - type = handler->type; - ext = handler->ext; - } - _next: - handler = handler->next; - } - if (ext == NULL) - Con_Printf("Couldn't find a cdrip for track %d\n", (int)track); - else - { - q_snprintf(tmp, sizeof(tmp), "%s/track%02d.%s", - MUSIC_DIRNAME, (int)track, ext); - bgmstream = S_CodecOpenStreamType(tmp, type, bgmloop); - if (! bgmstream) - Con_Printf("Couldn't handle music file %s\n", tmp); - } -} - -void BGM_Stop (void) -{ - if (bgmstream) - { - bgmstream->status = STREAM_NONE; - S_CodecCloseStream(bgmstream); - bgmstream = NULL; - s_rawend = 0; - } -} - -void BGM_Pause (void) -{ - if (bgmstream) - { - if (bgmstream->status == STREAM_PLAY) - bgmstream->status = STREAM_PAUSE; - } -} - -void BGM_Resume (void) -{ - if (bgmstream) - { - if (bgmstream->status == STREAM_PAUSE) - bgmstream->status = STREAM_PLAY; - } -} - -static void BGM_UpdateStream (void) -{ - qboolean did_rewind = false; - int res; /* Number of bytes read. */ - int bufferSamples; - int fileSamples; - int fileBytes; - byte raw[16384]; - - if (bgmstream->status != STREAM_PLAY) - return; - - /* don't bother playing anything if musicvolume is 0 */ - if (bgmvolume.value <= 0) - return; - - /* see how many samples should be copied into the raw buffer */ - if (s_rawend < paintedtime) - s_rawend = paintedtime; - - while (s_rawend < paintedtime + MAX_RAW_SAMPLES) - { - bufferSamples = MAX_RAW_SAMPLES - (s_rawend - paintedtime); - - /* decide how much data needs to be read from the file */ - fileSamples = bufferSamples * bgmstream->info.rate / shm->speed; - if (!fileSamples) - return; - - /* our max buffer size */ - fileBytes = fileSamples * (bgmstream->info.width * bgmstream->info.channels); - if (fileBytes > (int) sizeof(raw)) - { - fileBytes = (int) sizeof(raw); - fileSamples = fileBytes / - (bgmstream->info.width * bgmstream->info.channels); - } - - /* Read */ - res = S_CodecReadStream(bgmstream, fileBytes, raw); - if (res < fileBytes) - { - fileBytes = res; - fileSamples = res / (bgmstream->info.width * bgmstream->info.channels); - } - - if (res > 0) /* data: add to raw buffer */ - { - S_RawSamples(fileSamples, bgmstream->info.rate, - bgmstream->info.width, - bgmstream->info.channels, - raw, bgmvolume.value); - did_rewind = false; - } - else if (res == 0) /* EOF */ - { - if (bgmloop) - { - if (did_rewind) - { - Con_Printf("Stream keeps returning EOF.\n"); - BGM_Stop(); - return; - } - - res = S_CodecRewindStream(bgmstream); - if (res != 0) - { - Con_Printf("Stream seek error (%i), stopping.\n", res); - BGM_Stop(); - return; - } - did_rewind = true; - } - else - { - BGM_Stop(); - return; - } - } - else /* res < 0: some read error */ - { - Con_Printf("Stream read error (%i), stopping.\n", res); - BGM_Stop(); - return; - } - } -} - -void BGM_Update (void) -{ - if (old_volume != bgmvolume.value) - { - if (bgmvolume.value < 0) - bgmvolume.set("0"); - else if (bgmvolume.value > 1) - bgmvolume.set("1"); - old_volume = bgmvolume.value; - } - if (bgmstream) - BGM_UpdateStream (); -} - diff --git a/Quake/bgmusic.hpp b/Quake/bgmusic.hpp index 0337d05..1c32869 100644 --- a/Quake/bgmusic.hpp +++ b/Quake/bgmusic.hpp @@ -4,6 +4,7 @@ * * Copyright (C) 1999-2005 Id Software, Inc. * Copyright (C) 2010-2012 O.Sezer + * Copyright (C) 2026 iikorni * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,22 +23,25 @@ * */ -#ifndef _BGMUSIC_H_ -#define _BGMUSIC_H_ +#pragma once -extern qboolean bgmloop; -extern convar bgm_extmusic; +namespace music { + extern bool bgmloop; + extern convar bgm_extmusic; -qboolean BGM_Init (void); -void BGM_Shutdown (void); + void init(); -void BGM_Play (const char *filename); -void BGM_Stop (void); -void BGM_Update (void); -void BGM_Pause (void); -void BGM_Resume (void); + void shutdown(); -void BGM_PlayCDtrack (byte track, qboolean looping); + void play(const std::string &filename); -#endif /* _BGMUSIC_H_ */ + void stop(); + void update(); + + void pause(); + + void resume(); + + void play_cd_track(byte track, bool looping); +} diff --git a/Quake/cd_null.cpp b/Quake/cd_null.cpp index 87afc7b..51986ea 100644 --- a/Quake/cd_null.cpp +++ b/Quake/cd_null.cpp @@ -20,7 +20,7 @@ #include "quakedef.h" -int CDAudio_Play(byte track, qboolean looping) +int CDAudio_Play(byte track, bool looping) { return -1; } diff --git a/Quake/cd_sdl.cpp b/Quake/cd_sdl.cpp index efa9579..601ea32 100644 --- a/Quake/cd_sdl.cpp +++ b/Quake/cd_sdl.cpp @@ -43,18 +43,18 @@ #include "quakedef.hpp" -static qboolean cdValid = false; -static qboolean playing = false; -static qboolean wasPlaying = false; -static qboolean enabled = true; -static qboolean playLooping = false; +static bool cdValid = false; +static bool playing = false; +static bool wasPlaying = false; +static bool enabled = true; +static bool playLooping = false; static byte remap[100]; static byte playTrack; static double endOfTrack = -1.0, pausetime = -1.0; static SDL_CD *cd_handle; static int cd_dev = -1; static float old_cdvolume; -static qboolean hw_vol_works = true; +static bool hw_vol_works = true; static void CDAudio_Eject(void) @@ -84,7 +84,7 @@ static int CDAudio_GetAudioDiskInfo(void) return 0; } -int CDAudio_Play(byte track, qboolean looping) +int CDAudio_Play(byte track, bool looping) { int len_m, len_s, len_f; @@ -370,21 +370,21 @@ static void CD_f (void) Con_Printf ("cd: unknown command \"%s\"\n", command); } -static qboolean CD_GetVolume (void *unused) +static bool CD_GetVolume (void *unused) { /* FIXME: write proper code in here when SDL supports cdrom volume control some day. */ return false; } -static qboolean CD_SetVolume (void *unused) +static bool CD_SetVolume (void *unused) { /* FIXME: write proper code in here when SDL supports cdrom volume control some day. */ return false; } -static qboolean CDAudio_SetVolume (float value) +static bool CDAudio_SetVolume (float value) { if (!cd_handle || !enabled) return false; @@ -485,11 +485,11 @@ static void export_cddev_arg (void) /* Bad ugly hack to workaround SDL's cdrom device detection. * not needed for windows due to the way SDL_cdrom works. */ #if !defined(_WIN32) - int i = COM_CheckParm("-cddev"); - if (i != 0 && i < com_argc - 1 && com_argv[i+1][0] != '\0') + auto i = common::check_param("-cddev"); + if (i.has_value() && i.value() < com_argc - 1 && com_argv[i.value()+1][0] != '\0') { static char arg[64]; - q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i+1]); + q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i.value()+1]); putenv(arg); } #endif @@ -497,9 +497,7 @@ static void export_cddev_arg (void) int CDAudio_Init(void) { - int i, sdl_num_drives; - - if (safemode || COM_CheckParm("-nocdaudio")) + if (safemode || common::check_param("-nocdaudio").has_value()) return -1; export_cddev_arg(); @@ -510,22 +508,22 @@ int CDAudio_Init(void) return -1; } - sdl_num_drives = SDL_CDNumDrives (); + const int sdl_num_drives = SDL_CDNumDrives(); Con_Printf ("SDL detected %d CD-ROM drive%c\n", sdl_num_drives, sdl_num_drives == 1 ? ' ' : 's'); if (sdl_num_drives < 1) return -1; - if ((i = COM_CheckParm("-cddev")) != 0 && i < com_argc - 1) + if (const auto dev = common::check_param("-cddev"); dev.has_value() && dev.value() < com_argc - 1) { - const char *userdev = get_cddev_arg(com_argv[i+1]); + const char *userdev = get_cddev_arg(com_argv[dev.value()+1]); if (!userdev) { Con_Printf("Invalid argument to -cddev\n"); return -1; } - for (i = 0; i < sdl_num_drives; i++) + for (auto i = 0; i < sdl_num_drives; i++) { if (!q_strcasecmp(SDL_CDName(i), userdev)) { @@ -551,7 +549,7 @@ int CDAudio_Init(void) return -1; } - for (i = 0; i < 100; i++) + for (auto i = 0; i < 100; i++) remap[i] = i; enabled = true; old_cdvolume = bgmvolume.value; diff --git a/Quake/cdaudio.hpp b/Quake/cdaudio.hpp index 7c8477f..d52078a 100644 --- a/Quake/cdaudio.hpp +++ b/Quake/cdaudio.hpp @@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define __CDAUDIO_H int CDAudio_Init (void); -int CDAudio_Play (byte track, qboolean looping); +int CDAudio_Play (byte track, bool looping); /* returns 0 for success, -1 for failure. */ void CDAudio_Stop (void); void CDAudio_Pause (void); diff --git a/Quake/cfgfile.cpp b/Quake/cfgfile.cpp index 7679356..e03d975 100644 --- a/Quake/cfgfile.cpp +++ b/Quake/cfgfile.cpp @@ -131,7 +131,7 @@ void CFG_ReadCvarOverrides (const char **vars, int num_vars) for (i = 0; i < num_vars; i++) { q_strlcpy (&buff[1], vars[i], sizeof(buff) - 1); - j = COM_CheckParm(buff); + j = common::check_param(buff).has_value(); if (j != 0 && j < com_argc - 1) { if (com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+') @@ -154,7 +154,7 @@ int CFG_OpenConfig (const char *cfg_name) { FILE *f; long length; - qboolean pak; + bool pak; CFG_CloseConfig (); diff --git a/Quake/cl_input.cpp b/Quake/cl_input.cpp index d14ebf3..29fd157 100644 --- a/Quake/cl_input.cpp +++ b/Quake/cl_input.cpp @@ -24,6 +24,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All // rights reserved. +#include + #include "quakedef.hpp" extern convar cl_maxpitch; //johnfitz -- variable pitch clamping @@ -51,116 +53,115 @@ state bit 2 is edge triggered on the down to up transition */ -kbutton_t in_mlook, in_klook; -kbutton_t in_left, in_right, in_forward, in_back; -kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; -kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; -kbutton_t in_up, in_down; +kbutton_t in_mlook, in_klook; +kbutton_t in_left, in_right, in_forward, in_back; +kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; +kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; +kbutton_t in_up, in_down; -int in_impulse; +int in_impulse; -void KeyDown (kbutton_t *b) -{ - int k; +void KeyDown(kbutton_t *b) { + int k; - auto c = command::argv(1).value_or(""); - if (!c.empty()) - k = atoi(c.c_str()); - else - k = -1; // typed manually at the console for continuous down + auto c = command::argv(1).value_or(""); + if (!c.empty()) + k = atoi(c.c_str()); + else + k = -1; // typed manually at the console for continuous down - if (k == b->down[0] || k == b->down[1]) - return; // repeating key + if (k == b->down[0] || k == b->down[1]) + return; // repeating key - if (!b->down[0]) - b->down[0] = k; - else if (!b->down[1]) - b->down[1] = k; - else - { - Con_Printf ("Three keys down for a button!\n"); - return; - } + if (!b->down[0]) + b->down[0] = k; + else if (!b->down[1]) + b->down[1] = k; + else { + Con_Printf("Three keys down for a button!\n"); + return; + } - if (b->state & 1) - return; // still down - b->state |= 1 + 2; // down + impulse down + if (b->state & 1) + return; // still down + b->state |= 1 + 2; // down + impulse down } -void KeyUp (kbutton_t *b) -{ - int k; - const char *c; +void KeyUp(kbutton_t *b) { + int k; + const char *c; - c = command::argv(1)->c_str(); - if (c[0]) - k = atoi(c); - else - { // typed manually at the console, assume for unsticking, so clear all - b->down[0] = b->down[1] = 0; - b->state = 4; // impulse up - return; - } + c = command::argv(1)->c_str(); + if (c[0]) + k = atoi(c); + else { + // typed manually at the console, assume for unsticking, so clear all + b->down[0] = b->down[1] = 0; + b->state = 4; // impulse up + return; + } - if (b->down[0] == k) - b->down[0] = 0; - else if (b->down[1] == k) - b->down[1] = 0; - else - return; // key up without coresponding down (menu pass through) - if (b->down[0] || b->down[1]) - return; // some other key is still holding it down + if (b->down[0] == k) + b->down[0] = 0; + else if (b->down[1] == k) + b->down[1] = 0; + else + return; // key up without coresponding down (menu pass through) + if (b->down[0] || b->down[1]) + return; // some other key is still holding it down - if (!(b->state & 1)) - return; // still up (this should not happen) - b->state &= ~1; // now up - b->state |= 4; // impulse up + if (!(b->state & 1)) + return; // still up (this should not happen) + b->state &= ~1; // now up + b->state |= 4; // impulse up } -void IN_KLookDown (void) {KeyDown(&in_klook);} -void IN_KLookUp (void) {KeyUp(&in_klook);} -void IN_MLookDown (void) {KeyDown(&in_mlook);} -void IN_MLookUp (void) { - KeyUp(&in_mlook); - if ( !(in_mlook.state&1) && lookspring.value) - V_StartPitchDrift(); +void IN_KLookDown(void) { KeyDown(&in_klook); } +void IN_KLookUp(void) { KeyUp(&in_klook); } +void IN_MLookDown(void) { KeyDown(&in_mlook); } + +void IN_MLookUp(void) { + KeyUp(&in_mlook); + if (!(in_mlook.state & 1) && lookspring.value) + V_StartPitchDrift(); } -void IN_UpDown(void) {KeyDown(&in_up);} -void IN_UpUp(void) {KeyUp(&in_up);} -void IN_DownDown(void) {KeyDown(&in_down);} -void IN_DownUp(void) {KeyUp(&in_down);} -void IN_LeftDown(void) {KeyDown(&in_left);} -void IN_LeftUp(void) {KeyUp(&in_left);} -void IN_RightDown(void) {KeyDown(&in_right);} -void IN_RightUp(void) {KeyUp(&in_right);} -void IN_ForwardDown(void) {KeyDown(&in_forward);} -void IN_ForwardUp(void) {KeyUp(&in_forward);} -void IN_BackDown(void) {KeyDown(&in_back);} -void IN_BackUp(void) {KeyUp(&in_back);} -void IN_LookupDown(void) {KeyDown(&in_lookup);} -void IN_LookupUp(void) {KeyUp(&in_lookup);} -void IN_LookdownDown(void) {KeyDown(&in_lookdown);} -void IN_LookdownUp(void) {KeyUp(&in_lookdown);} -void IN_MoveleftDown(void) {KeyDown(&in_moveleft);} -void IN_MoveleftUp(void) {KeyUp(&in_moveleft);} -void IN_MoverightDown(void) {KeyDown(&in_moveright);} -void IN_MoverightUp(void) {KeyUp(&in_moveright);} -void IN_SpeedDown(void) {KeyDown(&in_speed);} -void IN_SpeedUp(void) {KeyUp(&in_speed);} -void IN_StrafeDown(void) {KeyDown(&in_strafe);} -void IN_StrafeUp(void) {KeyUp(&in_strafe);} +void IN_UpDown(void) { KeyDown(&in_up); } +void IN_UpUp(void) { KeyUp(&in_up); } +void IN_DownDown(void) { KeyDown(&in_down); } +void IN_DownUp(void) { KeyUp(&in_down); } +void IN_LeftDown(void) { KeyDown(&in_left); } +void IN_LeftUp(void) { KeyUp(&in_left); } +void IN_RightDown(void) { KeyDown(&in_right); } +void IN_RightUp(void) { KeyUp(&in_right); } +void IN_ForwardDown(void) { KeyDown(&in_forward); } +void IN_ForwardUp(void) { KeyUp(&in_forward); } +void IN_BackDown(void) { KeyDown(&in_back); } +void IN_BackUp(void) { KeyUp(&in_back); } +void IN_LookupDown(void) { KeyDown(&in_lookup); } +void IN_LookupUp(void) { KeyUp(&in_lookup); } +void IN_LookdownDown(void) { KeyDown(&in_lookdown); } +void IN_LookdownUp(void) { KeyUp(&in_lookdown); } +void IN_MoveleftDown(void) { KeyDown(&in_moveleft); } +void IN_MoveleftUp(void) { KeyUp(&in_moveleft); } +void IN_MoverightDown(void) { KeyDown(&in_moveright); } +void IN_MoverightUp(void) { KeyUp(&in_moveright); } -void IN_AttackDown(void) {KeyDown(&in_attack);} -void IN_AttackUp(void) {KeyUp(&in_attack);} +void IN_SpeedDown(void) { KeyDown(&in_speed); } +void IN_SpeedUp(void) { KeyUp(&in_speed); } +void IN_StrafeDown(void) { KeyDown(&in_strafe); } +void IN_StrafeUp(void) { KeyUp(&in_strafe); } -void IN_UseDown (void) {KeyDown(&in_use);} -void IN_UseUp (void) {KeyUp(&in_use);} -void IN_JumpDown (void) {KeyDown(&in_jump);} -void IN_JumpUp (void) {KeyUp(&in_jump);} +void IN_AttackDown(void) { KeyDown(&in_attack); } +void IN_AttackUp(void) { KeyUp(&in_attack); } -void IN_Impulse (void) {in_impulse=Q_atoi(command::argv(1)->c_str());} +void IN_UseDown(void) { KeyDown(&in_use); } +void IN_UseUp(void) { KeyUp(&in_use); } +void IN_JumpDown(void) { KeyDown(&in_jump); } +void IN_JumpUp(void) { KeyUp(&in_jump); } + +void IN_Impulse(void) { in_impulse = std::atoi(command::argv(1)->c_str()); } /* =============== @@ -172,66 +173,61 @@ Returns 0.25 if a key was pressed and released during the frame, 1.0 if held for the entire time =============== */ -float CL_KeyState (kbutton_t *key) -{ - float val; - qboolean impulsedown, impulseup, down; +float CL_KeyState(kbutton_t *key) { + float val; + bool impulsedown, impulseup, down; - impulsedown = key->state & 2; - impulseup = key->state & 4; - down = key->state & 1; - val = 0; + impulsedown = key->state & 2; + impulseup = key->state & 4; + down = key->state & 1; + val = 0; - if (impulsedown && !impulseup) - { - if (down) - val = 0.5; // pressed and held this frame - else - val = 0; // I_Error (); - } - if (impulseup && !impulsedown) - { - if (down) - val = 0; // I_Error (); - else - val = 0; // released this frame - } - if (!impulsedown && !impulseup) - { - if (down) - val = 1.0; // held the entire frame - else - val = 0; // up the entire frame - } - if (impulsedown && impulseup) - { - if (down) - val = 0.75; // released and re-pressed this frame - else - val = 0.25; // pressed and released this frame - } + if (impulsedown && !impulseup) { + if (down) + val = 0.5; // pressed and held this frame + else + val = 0; // I_Error (); + } + if (impulseup && !impulsedown) { + if (down) + val = 0; // I_Error (); + else + val = 0; // released this frame + } + if (!impulsedown && !impulseup) { + if (down) + val = 1.0; // held the entire frame + else + val = 0; // up the entire frame + } + if (impulsedown && impulseup) { + if (down) + val = 0.75; // released and re-pressed this frame + else + val = 0.25; // pressed and released this frame + } - key->state &= 1; // clear impulses + key->state &= 1; // clear impulses - return val; + return val; } //========================================================================== -convar cl_upspeed{"cl_upspeed","200"}; -convar cl_forwardspeed{"cl_forwardspeed","200", {.archive = true}}; -convar cl_backspeed{"cl_backspeed","200", {.archive = true}}; -convar cl_sidespeed{"cl_sidespeed","350"}; +convar cl_upspeed{"cl_upspeed", "200"}; +convar cl_forwardspeed{"cl_forwardspeed", "200", {.archive = true}}; +convar cl_backspeed{"cl_backspeed", "200", {.archive = true}}; +convar cl_sidespeed{"cl_sidespeed", "350"}; -convar cl_movespeedkey{"cl_movespeedkey","2.0"}; +convar cl_movespeedkey{"cl_movespeedkey", "2.0"}; -convar cl_yawspeed{"cl_yawspeed","140"}; -convar cl_pitchspeed{"cl_pitchspeed","150"}; +convar cl_yawspeed{"cl_yawspeed", "140"}; +convar cl_pitchspeed{"cl_pitchspeed", "150"}; -convar cl_anglespeedkey{"cl_anglespeedkey","1.5"}; +convar cl_anglespeedkey{"cl_anglespeedkey", "1.5"}; -convar cl_alwaysrun{"cl_alwaysrun","0",{.archive = true}}; // QuakeSpasm -- new always run +convar cl_alwaysrun{"cl_alwaysrun", "0", {.archive = true}}; // QuakeSpasm -- new always run /* ================ @@ -240,49 +236,46 @@ CL_AdjustAngles Moves the local angle positions ================ */ -void CL_AdjustAngles (void) -{ - float speed; - float up, down; +void CL_AdjustAngles(void) { + float speed; + float up, down; - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) - speed = host_frametime * cl_anglespeedkey.value; - else - speed = host_frametime; + if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) + speed = host_frametime * cl_anglespeedkey.value; + else + speed = host_frametime; - if (!(in_strafe.state & 1)) - { - cl.viewangles[YAW] -= speed*cl_yawspeed.value*CL_KeyState (&in_right); - cl.viewangles[YAW] += speed*cl_yawspeed.value*CL_KeyState (&in_left); - cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); - } - if (in_klook.state & 1) - { - V_StopPitchDrift (); - cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * CL_KeyState (&in_forward); - cl.viewangles[PITCH] += speed*cl_pitchspeed.value * CL_KeyState (&in_back); - } + if (!(in_strafe.state & 1)) { + cl.viewangles[YAW] -= speed * cl_yawspeed.value * CL_KeyState(&in_right); + cl.viewangles[YAW] += speed * cl_yawspeed.value * CL_KeyState(&in_left); + cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); + } + if (in_klook.state & 1) { + V_StopPitchDrift(); + cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * CL_KeyState(&in_forward); + cl.viewangles[PITCH] += speed * cl_pitchspeed.value * CL_KeyState(&in_back); + } - up = CL_KeyState (&in_lookup); - down = CL_KeyState(&in_lookdown); + up = CL_KeyState(&in_lookup); + down = CL_KeyState(&in_lookdown); - cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * up; - cl.viewangles[PITCH] += speed*cl_pitchspeed.value * down; + cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * up; + cl.viewangles[PITCH] += speed * cl_pitchspeed.value * down; - if (up || down) - V_StopPitchDrift (); + if (up || down) + V_StopPitchDrift(); - //johnfitz -- variable pitch clamping - if (cl.viewangles[PITCH] > cl_maxpitch.value) - cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) - cl.viewangles[PITCH] = cl_minpitch.value; - //johnfitz + //johnfitz -- variable pitch clamping + if (cl.viewangles[PITCH] > cl_maxpitch.value) + cl.viewangles[PITCH] = cl_maxpitch.value; + if (cl.viewangles[PITCH] < cl_minpitch.value) + cl.viewangles[PITCH] = cl_minpitch.value; + //johnfitz - if (cl.viewangles[ROLL] > 50) - cl.viewangles[ROLL] = 50; - if (cl.viewangles[ROLL] < -50) - cl.viewangles[ROLL] = -50; + if (cl.viewangles[ROLL] > 50) + cl.viewangles[ROLL] = 50; + if (cl.viewangles[ROLL] < -50) + cl.viewangles[ROLL] = -50; } /* @@ -292,42 +285,38 @@ CL_BaseMove Send the intended movement message to the server ================ */ -void CL_BaseMove (usercmd_t *cmd) -{ - if (cls.signon != SIGNONS) - return; +void CL_BaseMove(usercmd_t *cmd) { + if (cls.signon != SIGNONS) + return; - CL_AdjustAngles (); + CL_AdjustAngles(); - Q_memset (cmd, 0, sizeof(*cmd)); + std::memset(cmd, 0, sizeof(*cmd)); - if (in_strafe.state & 1) - { - cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_right); - cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_left); - } + if (in_strafe.state & 1) { + cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_right); + cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_left); + } - cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_moveright); - cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_moveleft); + cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_moveright); + cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_moveleft); - cmd->upmove += cl_upspeed.value * CL_KeyState (&in_up); - cmd->upmove -= cl_upspeed.value * CL_KeyState (&in_down); + cmd->upmove += cl_upspeed.value * CL_KeyState(&in_up); + cmd->upmove -= cl_upspeed.value * CL_KeyState(&in_down); - if (! (in_klook.state & 1) ) - { - cmd->forwardmove += cl_forwardspeed.value * CL_KeyState (&in_forward); - cmd->forwardmove -= cl_backspeed.value * CL_KeyState (&in_back); - } + if (!(in_klook.state & 1)) { + cmd->forwardmove += cl_forwardspeed.value * CL_KeyState(&in_forward); + cmd->forwardmove -= cl_backspeed.value * CL_KeyState(&in_back); + } -// -// adjust for speed key -// - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) - { - cmd->forwardmove *= cl_movespeedkey.value; - cmd->sidemove *= cl_movespeedkey.value; - cmd->upmove *= cl_movespeedkey.value; - } + // + // adjust for speed key + // + if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) { + cmd->forwardmove *= cl_movespeedkey.value; + cmd->sidemove *= cl_movespeedkey.value; + cmd->upmove *= cl_movespeedkey.value; + } } @@ -336,74 +325,72 @@ void CL_BaseMove (usercmd_t *cmd) CL_SendMove ============== */ -void CL_SendMove (const usercmd_t *cmd) -{ - int i; - int bits; - sizebuf_t buf; - byte data[128]; +void CL_SendMove(const usercmd_t *cmd) { + int i; + int bits; + sizebuf_t buf; + byte data[128]; - buf.maxsize = 128; - buf.cursize = 0; - buf.data = data; + buf.maxsize = 128; + buf.cursize = 0; + buf.data = data; - cl.cmd = *cmd; + cl.cmd = *cmd; -// -// send the movement message -// - MSG_WriteByte (&buf, clc_move); + // + // send the movement message + // + MSG_WriteByte(&buf, clc_move); - MSG_WriteFloat (&buf, cl.mtime[0]); // so server can get ping times + MSG_WriteFloat(&buf, cl.mtime[0]); // so server can get ping times - for (i=0 ; i<3 ; i++) - //johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE - if (cl.protocol == PROTOCOL_NETQUAKE) - MSG_WriteAngle (&buf, cl.viewangles[i], cl.protocolflags); - else - MSG_WriteAngle16 (&buf, cl.viewangles[i], cl.protocolflags); - //johnfitz + for (i = 0; i < 3; i++) + //johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE + if (cl.protocol == PROTOCOL_NETQUAKE) + MSG_WriteAngle(&buf, cl.viewangles[i], cl.protocolflags); + else + MSG_WriteAngle16(&buf, cl.viewangles[i], cl.protocolflags); + //johnfitz - MSG_WriteShort (&buf, cmd->forwardmove); - MSG_WriteShort (&buf, cmd->sidemove); - MSG_WriteShort (&buf, cmd->upmove); + MSG_WriteShort(&buf, cmd->forwardmove); + MSG_WriteShort(&buf, cmd->sidemove); + MSG_WriteShort(&buf, cmd->upmove); -// -// send button bits -// - bits = 0; + // + // send button bits + // + bits = 0; - if ( in_attack.state & 3 ) - bits |= 1; - in_attack.state &= ~2; + if (in_attack.state & 3) + bits |= 1; + in_attack.state &= ~2; - if (in_jump.state & 3) - bits |= 2; - in_jump.state &= ~2; + if (in_jump.state & 3) + bits |= 2; + in_jump.state &= ~2; - MSG_WriteByte (&buf, bits); + MSG_WriteByte(&buf, bits); - MSG_WriteByte (&buf, in_impulse); - in_impulse = 0; + MSG_WriteByte(&buf, in_impulse); + in_impulse = 0; -// -// deliver the message -// - if (cls.demoplayback) - return; + // + // deliver the message + // + if (cls.demoplayback) + return; -// -// allways dump the first two message, because it may contain leftover inputs -// from the last level -// - if (++cl.movemessages <= 2) - return; + // + // allways dump the first two message, because it may contain leftover inputs + // from the last level + // + if (++cl.movemessages <= 2) + return; - if (NET_SendUnreliableMessage (cls.netcon, &buf) == -1) - { - Con_Printf ("CL_SendMove: lost server connection\n"); - CL_Disconnect (); - } + if (NET_SendUnreliableMessage(cls.netcon, &buf) == -1) { + Con_Printf("CL_SendMove: lost server connection\n"); + CL_Disconnect(); + } } /* @@ -411,43 +398,40 @@ void CL_SendMove (const usercmd_t *cmd) CL_InitInput ============ */ -void CL_InitInput (void) -{ - command::add ("+moveup",IN_UpDown); - command::add ("-moveup",IN_UpUp); - command::add ("+movedown",IN_DownDown); - command::add ("-movedown",IN_DownUp); - command::add ("+left",IN_LeftDown); - command::add ("-left",IN_LeftUp); - command::add ("+right",IN_RightDown); - command::add ("-right",IN_RightUp); - command::add ("+forward",IN_ForwardDown); - command::add ("-forward",IN_ForwardUp); - command::add ("+back",IN_BackDown); - command::add ("-back",IN_BackUp); - command::add ("+lookup", IN_LookupDown); - command::add ("-lookup", IN_LookupUp); - command::add ("+lookdown", IN_LookdownDown); - command::add ("-lookdown", IN_LookdownUp); - command::add ("+strafe", IN_StrafeDown); - command::add ("-strafe", IN_StrafeUp); - command::add ("+moveleft", IN_MoveleftDown); - command::add ("-moveleft", IN_MoveleftUp); - command::add ("+moveright", IN_MoverightDown); - command::add ("-moveright", IN_MoverightUp); - command::add ("+speed", IN_SpeedDown); - command::add ("-speed", IN_SpeedUp); - command::add ("+attack", IN_AttackDown); - command::add ("-attack", IN_AttackUp); - command::add ("+use", IN_UseDown); - command::add ("-use", IN_UseUp); - command::add ("+jump", IN_JumpDown); - command::add ("-jump", IN_JumpUp); - command::add ("impulse", IN_Impulse); - command::add ("+klook", IN_KLookDown); - command::add ("-klook", IN_KLookUp); - command::add ("+mlook", IN_MLookDown); - command::add ("-mlook", IN_MLookUp); - +void CL_InitInput(void) { + command::add("+moveup", IN_UpDown); + command::add("-moveup", IN_UpUp); + command::add("+movedown", IN_DownDown); + command::add("-movedown", IN_DownUp); + command::add("+left", IN_LeftDown); + command::add("-left", IN_LeftUp); + command::add("+right", IN_RightDown); + command::add("-right", IN_RightUp); + command::add("+forward", IN_ForwardDown); + command::add("-forward", IN_ForwardUp); + command::add("+back", IN_BackDown); + command::add("-back", IN_BackUp); + command::add("+lookup", IN_LookupDown); + command::add("-lookup", IN_LookupUp); + command::add("+lookdown", IN_LookdownDown); + command::add("-lookdown", IN_LookdownUp); + command::add("+strafe", IN_StrafeDown); + command::add("-strafe", IN_StrafeUp); + command::add("+moveleft", IN_MoveleftDown); + command::add("-moveleft", IN_MoveleftUp); + command::add("+moveright", IN_MoverightDown); + command::add("-moveright", IN_MoverightUp); + command::add("+speed", IN_SpeedDown); + command::add("-speed", IN_SpeedUp); + command::add("+attack", IN_AttackDown); + command::add("-attack", IN_AttackUp); + command::add("+use", IN_UseDown); + command::add("-use", IN_UseUp); + command::add("+jump", IN_JumpDown); + command::add("-jump", IN_JumpUp); + command::add("impulse", IN_Impulse); + command::add("+klook", IN_KLookDown); + command::add("-klook", IN_KLookUp); + command::add("+mlook", IN_MLookDown); + command::add("-mlook", IN_MLookUp); } - diff --git a/Quake/cl_main.cpp b/Quake/cl_main.cpp index 91eca7e..a6a09f0 100644 --- a/Quake/cl_main.cpp +++ b/Quake/cl_main.cpp @@ -28,42 +28,42 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // references them even when on a unix system. // these two are not intended to be set directly -convar cl_name{"_cl_name", "player", {.archive = true}}; -convar cl_color{"_cl_color", "0", {.archive = true}}; +convar cl_name{"_cl_name", "player", {.archive = true}}; +convar cl_color{"_cl_color", "0", {.archive = true}}; -convar cl_shownet{"cl_shownet","0"}; // can be 0, 1, or 2 -convar cl_nolerp{"cl_nolerp","0"}; +convar cl_shownet{"cl_shownet", "0"}; // can be 0, 1, or 2 +convar cl_nolerp{"cl_nolerp", "0"}; -convar cfg_unbindall{"cfg_unbindall", "1", {.archive = true}}; +convar cfg_unbindall{"cfg_unbindall", "1", {.archive = true}}; -convar lookspring{"lookspring","0", {.archive = true}}; -convar lookstrafe{"lookstrafe","0", {.archive = true}}; -convar sensitivity{"sensitivity","3", {.archive = true}}; +convar lookspring{"lookspring", "0", {.archive = true}}; +convar lookstrafe{"lookstrafe", "0", {.archive = true}}; +convar sensitivity{"sensitivity", "3", {.archive = true}}; -convar m_pitch{"m_pitch","0.022", {.archive = true}}; -convar m_yaw{"m_yaw","0.022", {.archive = true}}; -convar m_forward{"m_forward","1", {.archive = true}}; -convar m_side{"m_side","0.8", {.archive = true}}; +convar m_pitch{"m_pitch", "0.022", {.archive = true}}; +convar m_yaw{"m_yaw", "0.022", {.archive = true}}; +convar m_forward{"m_forward", "1", {.archive = true}}; +convar m_side{"m_side", "0.8", {.archive = true}}; -convar cl_maxpitch{"cl_maxpitch", "90", {.archive = true}}; //johnfitz -- variable pitch clamping -convar cl_minpitch{"cl_minpitch", "-90", {.archive = true}}; //johnfitz -- variable pitch clamping +convar cl_maxpitch{"cl_maxpitch", "90", {.archive = true}}; //johnfitz -- variable pitch clamping +convar cl_minpitch{"cl_minpitch", "-90", {.archive = true}}; //johnfitz -- variable pitch clamping -convar cl_startdemos{"cl_startdemos", "1", {.archive = true}}; +convar cl_startdemos{"cl_startdemos", "1", {.archive = true}}; -client_static_t cls; -client_state_t cl; +client_static_t cls; +client_state_t cl; // FIXME: put these on hunk? -entity_t cl_static_entities[MAX_STATIC_ENTITIES]; -lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; -dlight_t cl_dlights[MAX_DLIGHTS]; +entity_t cl_static_entities[MAX_STATIC_ENTITIES]; +lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; +dlight_t cl_dlights[MAX_DLIGHTS]; -entity_t *cl_entities; //johnfitz -- was a static array, now on hunk -int cl_max_edicts; //johnfitz -- only changes when new map loads +entity_t *cl_entities; //johnfitz -- was a static array, now on hunk +int cl_max_edicts; //johnfitz -- only changes when new map loads -int cl_numvisedicts; -entity_t *cl_visedicts[MAX_VISEDICTS]; +int cl_numvisedicts; +entity_t *cl_visedicts[MAX_VISEDICTS]; -extern convar r_lerpmodels, r_lerpmove; //johnfitz +extern convar r_lerpmodels, r_lerpmove; //johnfitz /* ===================== @@ -71,26 +71,25 @@ CL_ClearState ===================== */ -void CL_ClearState (void) -{ - if (!sv.active) - Host_ClearMemory (); +void CL_ClearState(void) { + if (!sv.active) + Host_ClearMemory(); -// wipe the entire cl structure - memset (&cl, 0, sizeof(cl)); + // wipe the entire cl structure + memset(&cl, 0, sizeof(cl)); - SZ_Clear (&cls.message); + SZ_Clear(&cls.message); -// clear other arrays - memset (cl_dlights, 0, sizeof(cl_dlights)); - memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); - memset (cl_temp_entities, 0, sizeof(cl_temp_entities)); - memset (cl_beams, 0, sizeof(cl_beams)); + // clear other arrays + memset(cl_dlights, 0, sizeof(cl_dlights)); + memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); + memset(cl_temp_entities, 0, sizeof(cl_temp_entities)); + memset(cl_beams, 0, sizeof(cl_beams)); - //johnfitz -- cl_entities is now dynamically allocated - cl_max_edicts = CLAMP (MIN_EDICTS,(int)max_edicts.value,MAX_EDICTS); - cl_entities = (entity_t *) Hunk_AllocName (cl_max_edicts*sizeof(entity_t), "cl_entities"); - //johnfitz + //johnfitz -- cl_entities is now dynamically allocated + cl_max_edicts = std::clamp((int) max_edicts.value,MIN_EDICTS, MAX_EDICTS); + cl_entities = (entity_t *) Hunk_AllocName(cl_max_edicts * sizeof(entity_t), "cl_entities"); + //johnfitz } /* @@ -101,47 +100,44 @@ Sends a disconnect message to the server This is also called on Host_Error, so it shouldn't cause any errors ===================== */ -void CL_Disconnect (void) -{ - if (key_dest == key_message) - Key_EndChat (); // don't get stuck in chat mode +void CL_Disconnect(void) { + if (key_dest == key_message) + Key_EndChat(); // don't get stuck in chat mode -// stop sounds (especially looping!) - S_StopAllSounds (true); - BGM_Stop(); - CDAudio_Stop(); + // stop sounds (especially looping!) + S_StopAllSounds(true); + music::stop(); + CDAudio_Stop(); -// if running a local server, shut it down - if (cls.demoplayback) - CL_StopPlayback (); - else if (cls.state == ca_connected) - { - if (cls.demorecording) - CL_Stop_f (); + // if running a local server, shut it down + if (cls.demoplayback) + CL_StopPlayback(); + else if (cls.state == ca_connected) { + if (cls.demorecording) + CL_Stop_f(); - Con_DPrintf ("Sending clc_disconnect\n"); - SZ_Clear (&cls.message); - MSG_WriteByte (&cls.message, clc_disconnect); - NET_SendUnreliableMessage (cls.netcon, &cls.message); - SZ_Clear (&cls.message); - NET_Close (cls.netcon); + Con_DPrintf("Sending clc_disconnect\n"); + SZ_Clear(&cls.message); + MSG_WriteByte(&cls.message, clc_disconnect); + NET_SendUnreliableMessage(cls.netcon, &cls.message); + SZ_Clear(&cls.message); + NET_Close(cls.netcon); - cls.state = ca_disconnected; - if (sv.active) - Host_ShutdownServer(false); - } + cls.state = ca_disconnected; + if (sv.active) + Host_ShutdownServer(false); + } - cls.demoplayback = cls.timedemo = false; - cls.demopaused = false; - cl.intermission = 0; - CL_ClearSignons (); + cls.demoplayback = cls.timedemo = false; + cls.demopaused = false; + cl.intermission = 0; + CL_ClearSignons(); } -void CL_Disconnect_f (void) -{ - CL_Disconnect (); - if (sv.active) - Host_ShutdownServer (false); +void CL_Disconnect_f(void) { + CL_Disconnect(); + if (sv.active) + Host_ShutdownServer(false); } @@ -152,25 +148,24 @@ CL_EstablishConnection Host should be either "local" or a net address to be passed on ===================== */ -void CL_EstablishConnection (const char *host) -{ - if (cls.state == ca_dedicated) - return; +void CL_EstablishConnection(const char *host) { + if (cls.state == ca_dedicated) + return; - if (cls.demoplayback) - return; + if (cls.demoplayback) + return; - CL_Disconnect (); + CL_Disconnect(); - cls.netcon = NET_Connect (host); - if (!cls.netcon) - Host_Error ("CL_Connect: connect failed"); - Con_DPrintf ("CL_EstablishConnection: connected to %s\n", host); + cls.netcon = NET_Connect(host); + if (!cls.netcon) + Host_Error("CL_Connect: connect failed"); + Con_DPrintf("CL_EstablishConnection: connected to %s\n", host); - cls.demonum = -1; // not in the demo loop now - cls.state = ca_connected; - CL_ClearSignons (); // need all the signon messages before playing - MSG_WriteByte (&cls.message, clc_nop); // NAT Fix from ProQuake + cls.demonum = -1; // not in the demo loop now + cls.state = ca_connected; + CL_ClearSignons(); // need all the signon messages before playing + MSG_WriteByte(&cls.message, clc_nop); // NAT Fix from ProQuake } /* @@ -180,41 +175,40 @@ CL_SignonReply An svc_signonnum has been received, perform a client side setup ===================== */ -void CL_SignonReply (void) -{ - char str[8192]; +void CL_SignonReply(void) { + char str[8192]; - Con_DPrintf ("CL_SignonReply: %i\n", cls.signon); + Con_DPrintf("CL_SignonReply: %i\n", cls.signon); - switch (cls.signon) - { - case 1: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, "prespawn"); - break; + switch (cls.signon) { + case 1: + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, "prespawn"); + break; - case 2: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, va("name \"%s\"\n", cl_name.string)); + case 2: + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, va("name \"%s\"\n", cl_name.string)); - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, va("color %i %i\n", ((int)cl_color.value)>>4, ((int)cl_color.value)&15)); + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, + va("color %i %i\n", ((int) cl_color.value) >> 4, ((int) cl_color.value) & 15)); - MSG_WriteByte (&cls.message, clc_stringcmd); - sprintf (str, "spawn %s", cls.spawnparms); - MSG_WriteString (&cls.message, str); - break; + MSG_WriteByte(&cls.message, clc_stringcmd); + sprintf(str, "spawn %s", cls.spawnparms); + MSG_WriteString(&cls.message, str); + break; - case 3: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, "begin"); - Cache_Report (); // print remaining memory - break; + case 3: + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, "begin"); + Cache_Report(); // print remaining memory + break; - case 4: - SCR_EndLoadingPlaque (); // allow normal screen updates - break; - } + case 4: + SCR_EndLoadingPlaque(); // allow normal screen updates + break; + } } /* @@ -224,30 +218,27 @@ CL_NextDemo Called to play the next demo in the demo loop ===================== */ -void CL_NextDemo (void) -{ - char str[1024]; +void CL_NextDemo(void) { + char str[1024]; - if (cls.demonum == -1) - return; // don't play demos + if (cls.demonum == -1) + return; // don't play demos - if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) - { - cls.demonum = 0; - if (!cls.demos[cls.demonum][0]) - { - Con_Printf ("No demos listed with startdemos\n"); - cls.demonum = -1; - CL_Disconnect(); - return; - } - } + if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) { + cls.demonum = 0; + if (!cls.demos[cls.demonum][0]) { + Con_Printf("No demos listed with startdemos\n"); + cls.demonum = -1; + CL_Disconnect(); + return; + } + } - SCR_BeginLoadingPlaque (); + SCR_BeginLoadingPlaque(); - sprintf (str,"playdemo %s\n", cls.demos[cls.demonum]); - Cbuf_InsertText (str); - cls.demonum++; + sprintf(str, "playdemo %s\n", cls.demos[cls.demonum]); + command::buffer::insert_text(str); + cls.demonum++; } /* @@ -255,25 +246,23 @@ void CL_NextDemo (void) CL_PrintEntities_f ============== */ -void CL_PrintEntities_f (void) -{ - entity_t *ent; - int i; +void CL_PrintEntities_f(void) { + entity_t *ent; + int i; - if (cls.state != ca_connected) - return; + if (cls.state != ca_connected) + return; - for (i=0,ent=cl_entities ; imodel) - { - Con_Printf ("EMPTY\n"); - continue; - } - Con_Printf ("%s:%2i (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" - ,ent->model->name,ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], ent->angles[1], ent->angles[2]); - } + for (i = 0, ent = cl_entities; i < cl.num_entities; i++, ent++) { + Con_Printf("%3i:", i); + if (!ent->model) { + Con_Printf("EMPTY\n"); + continue; + } + Con_Printf("%s:%2i (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" + , ent->model->name, ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], + ent->angles[1], ent->angles[2]); + } } /* @@ -282,45 +271,39 @@ CL_AllocDlight =============== */ -dlight_t *CL_AllocDlight (int key) -{ - int i; - dlight_t *dl; +dlight_t *CL_AllocDlight(int key) { + int i; + dlight_t *dl; -// first look for an exact key match - if (key) - { - dl = cl_dlights; - for (i=0 ; ikey == key) - { - memset (dl, 0, sizeof(*dl)); - dl->key = key; - dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc - return dl; - } - } - } + // first look for an exact key match + if (key) { + dl = cl_dlights; + for (i = 0; i < MAX_DLIGHTS; i++, dl++) { + if (dl->key == key) { + memset(dl, 0, sizeof(*dl)); + dl->key = key; + dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc + return dl; + } + } + } -// then look for anything else - dl = cl_dlights; - for (i=0 ; idie < cl.time) - { - memset (dl, 0, sizeof(*dl)); - dl->key = key; - dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc - return dl; - } - } + // then look for anything else + dl = cl_dlights; + for (i = 0; i < MAX_DLIGHTS; i++, dl++) { + if (dl->die < cl.time) { + memset(dl, 0, sizeof(*dl)); + dl->key = key; + dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc + return dl; + } + } - dl = &cl_dlights[0]; - memset (dl, 0, sizeof(*dl)); - dl->key = key; - dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc - return dl; + dl = &cl_dlights[0]; + memset(dl, 0, sizeof(*dl)); + dl->key = key; + dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc + return dl; } @@ -330,24 +313,22 @@ CL_DecayLights =============== */ -void CL_DecayLights (void) -{ - int i; - dlight_t *dl; - float time; +void CL_DecayLights(void) { + int i; + dlight_t *dl; + float time; - time = cl.time - cl.oldtime; + time = cl.time - cl.oldtime; - dl = cl_dlights; - for (i=0 ; idie < cl.time || !dl->radius) - continue; + dl = cl_dlights; + for (i = 0; i < MAX_DLIGHTS; i++, dl++) { + if (dl->die < cl.time || !dl->radius) + continue; - dl->radius -= time*dl->decay; - if (dl->radius < 0) - dl->radius = 0; - } + dl->radius -= time * dl->decay; + if (dl->radius < 0) + dl->radius = 0; + } } @@ -359,45 +340,40 @@ Determines the fraction between the last two messages that the objects should be put at. =============== */ -float CL_LerpPoint (void) -{ - float f, frac; +float CL_LerpPoint(void) { + float f, frac; - f = cl.mtime[0] - cl.mtime[1]; + f = cl.mtime[0] - cl.mtime[1]; - if (!f || cls.timedemo || sv.active) - { - cl.time = cl.mtime[0]; - return 1; - } + if (!f || cls.timedemo || sv.active) { + cl.time = cl.mtime[0]; + return 1; + } - if (f > 0.1) // dropped packet, or start of demo - { - cl.mtime[1] = cl.mtime[0] - 0.1; - f = 0.1; - } + if (f > 0.1) // dropped packet, or start of demo + { + cl.mtime[1] = cl.mtime[0] - 0.1; + f = 0.1; + } - frac = (cl.time - cl.mtime[1]) / f; + frac = (cl.time - cl.mtime[1]) / f; - if (frac < 0) - { - if (frac < -0.01) - cl.time = cl.mtime[1]; - frac = 0; - } - else if (frac > 1) - { - if (frac > 1.01) - cl.time = cl.mtime[0]; - frac = 1; - } + if (frac < 0) { + if (frac < -0.01) + cl.time = cl.mtime[1]; + frac = 0; + } else if (frac > 1) { + if (frac > 1.01) + cl.time = cl.mtime[0]; + frac = 1; + } - //johnfitz -- better nolerp behavior - if (cl_nolerp.value) - return 1; - //johnfitz + //johnfitz -- better nolerp behavior + if (cl_nolerp.value) + return 1; + //johnfitz - return frac; + return frac; } /* @@ -405,204 +381,187 @@ float CL_LerpPoint (void) CL_RelinkEntities =============== */ -void CL_RelinkEntities (void) -{ - entity_t *ent; - int i, j; - float frac, f, d; - vec3_t delta; - float bobjrotate; - vec3_t oldorg; - dlight_t *dl; +void CL_RelinkEntities(void) { + entity_t *ent; + int i, j; + float frac, f, d; + vec3_t delta; + float bobjrotate; + vec3_t oldorg; + dlight_t *dl; -// determine partial update time - frac = CL_LerpPoint (); + // determine partial update time + frac = CL_LerpPoint(); - cl_numvisedicts = 0; + cl_numvisedicts = 0; -// -// interpolate player info -// - for (i=0 ; i<3 ; i++) - cl.velocity[i] = cl.mvelocity[1][i] + - frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); + // + // interpolate player info + // + for (i = 0; i < 3; i++) + cl.velocity[i] = cl.mvelocity[1][i] + + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); - if (cls.demoplayback) - { - // interpolate the angles - for (j=0 ; j<3 ; j++) - { - d = cl.mviewangles[0][j] - cl.mviewangles[1][j]; - if (d > 180) - d -= 360; - else if (d < -180) - d += 360; - cl.viewangles[j] = cl.mviewangles[1][j] + frac*d; - } - } + if (cls.demoplayback) { + // interpolate the angles + for (j = 0; j < 3; j++) { + d = cl.mviewangles[0][j] - cl.mviewangles[1][j]; + if (d > 180) + d -= 360; + else if (d < -180) + d += 360; + cl.viewangles[j] = cl.mviewangles[1][j] + frac * d; + } + } - bobjrotate = anglemod(100*cl.time); + bobjrotate = anglemod(100 * cl.time); -// start on the entity after the world - for (i=1,ent=cl_entities+1 ; imodel) - { // empty slot - - // ericw -- efrags are only used for static entities in GLQuake - // ent can't be static, so this is a no-op. - //if (ent->forcelink) - // R_RemoveEfrags (ent); // just became empty - continue; - } + // start on the entity after the world + for (i = 1, ent = cl_entities + 1; i < cl.num_entities; i++, ent++) { + if (!ent->model) { + // empty slot -// if the object wasn't included in the last packet, remove it - if (ent->msgtime != cl.mtime[0]) - { - ent->model = NULL; - ent->lerpflags |= LERP_RESETMOVE|LERP_RESETANIM; //johnfitz -- next time this entity slot is reused, the lerp will need to be reset - continue; - } + // ericw -- efrags are only used for static entities in GLQuake + // ent can't be static, so this is a no-op. + //if (ent->forcelink) + // R_RemoveEfrags (ent); // just became empty + continue; + } - VectorCopy (ent->origin, oldorg); + // if the object wasn't included in the last packet, remove it + if (ent->msgtime != cl.mtime[0]) { + ent->model = NULL; + ent->lerpflags |= LERP_RESETMOVE | LERP_RESETANIM; + //johnfitz -- next time this entity slot is reused, the lerp will need to be reset + continue; + } - if (ent->forcelink) - { // the entity was not updated in the last message - // so move to the final spot - VectorCopy (ent->msg_origins[0], ent->origin); - VectorCopy (ent->msg_angles[0], ent->angles); - } - else - { // if the delta is large, assume a teleport and don't lerp - f = frac; - for (j=0 ; j<3 ; j++) - { - delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j]; - if (delta[j] > 100 || delta[j] < -100) - { - f = 1; // assume a teleportation, not a motion - ent->lerpflags |= LERP_RESETMOVE; //johnfitz -- don't lerp teleports - } - } + VectorCopy(ent->origin, oldorg); - //johnfitz -- don't cl_lerp entities that will be r_lerped - if (r_lerpmove.value && (ent->lerpflags & LERP_MOVESTEP)) - f = 1; - //johnfitz + if (ent->forcelink) { + // the entity was not updated in the last message + // so move to the final spot + VectorCopy(ent->msg_origins[0], ent->origin); + VectorCopy(ent->msg_angles[0], ent->angles); + } else { + // if the delta is large, assume a teleport and don't lerp + f = frac; + for (j = 0; j < 3; j++) { + delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j]; + if (delta[j] > 100 || delta[j] < -100) { + f = 1; // assume a teleportation, not a motion + ent->lerpflags |= LERP_RESETMOVE; //johnfitz -- don't lerp teleports + } + } - // interpolate the origin and angles - for (j=0 ; j<3 ; j++) - { - ent->origin[j] = ent->msg_origins[1][j] + f*delta[j]; + //johnfitz -- don't cl_lerp entities that will be r_lerped + if (r_lerpmove.value && (ent->lerpflags & LERP_MOVESTEP)) + f = 1; + //johnfitz - d = ent->msg_angles[0][j] - ent->msg_angles[1][j]; - if (d > 180) - d -= 360; - else if (d < -180) - d += 360; - ent->angles[j] = ent->msg_angles[1][j] + f*d; - } - } + // interpolate the origin and angles + for (j = 0; j < 3; j++) { + ent->origin[j] = ent->msg_origins[1][j] + f * delta[j]; -// rotate binary objects locally - if (ent->model->flags & EF_ROTATE) - ent->angles[1] = bobjrotate; + d = ent->msg_angles[0][j] - ent->msg_angles[1][j]; + if (d > 180) + d -= 360; + else if (d < -180) + d += 360; + ent->angles[j] = ent->msg_angles[1][j] + f * d; + } + } - if (ent->effects & EF_BRIGHTFIELD) - R_EntityParticles (ent); + // rotate binary objects locally + if (ent->model->flags & EF_ROTATE) + ent->angles[1] = bobjrotate; - if (ent->effects & EF_MUZZLEFLASH) - { - vec3_t fv, rv, uv; + if (ent->effects & EF_BRIGHTFIELD) + R_EntityParticles(ent); - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->origin[2] += 16; - AngleVectors (ent->angles, fv, rv, uv); + if (ent->effects & EF_MUZZLEFLASH) { + vec3_t fv, rv, uv; - VectorMA (dl->origin, 18, fv, dl->origin); - dl->radius = 200 + (rand()&31); - dl->minlight = 32; - dl->die = cl.time + 0.1; + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->origin[2] += 16; + AngleVectors(ent->angles, fv, rv, uv); - //johnfitz -- assume muzzle flash accompanied by muzzle flare, which looks bad when lerped - if (r_lerpmodels.value != 2) - { - if (ent == &cl_entities[cl.viewentity]) - cl.viewent.lerpflags |= LERP_RESETANIM|LERP_RESETANIM2; //no lerping for two frames - else - ent->lerpflags |= LERP_RESETANIM|LERP_RESETANIM2; //no lerping for two frames - } - //johnfitz - } - if (ent->effects & EF_BRIGHTLIGHT) - { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->origin[2] += 16; - dl->radius = 400 + (rand()&31); - dl->die = cl.time + 0.001; - } - if (ent->effects & EF_DIMLIGHT) - { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->radius = 200 + (rand()&31); - dl->die = cl.time + 0.001; - } - if (ent->effects & EF_QEX_QUADLIGHT) - { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->radius = 200 + (rand()&31); - dl->die = cl.time + 0.001; - dl->color[0] = 0.25f; - dl->color[1] = 0.25f; - dl->color[2] = 1.0f; - } - if (ent->effects & EF_QEX_PENTALIGHT) - { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->radius = 200 + (rand()&31); - dl->die = cl.time + 0.001; - dl->color[0] = 1.0f; - dl->color[1] = 0.25f; - dl->color[2] = 0.25f; - } + VectorMA(dl->origin, 18, fv, dl->origin); + dl->radius = 200 + (rand() & 31); + dl->minlight = 32; + dl->die = cl.time + 0.1; - if (ent->model->flags & EF_GIB) - R_RocketTrail (oldorg, ent->origin, 2); - else if (ent->model->flags & EF_ZOMGIB) - R_RocketTrail (oldorg, ent->origin, 4); - else if (ent->model->flags & EF_TRACER) - R_RocketTrail (oldorg, ent->origin, 3); - else if (ent->model->flags & EF_TRACER2) - R_RocketTrail (oldorg, ent->origin, 5); - else if (ent->model->flags & EF_ROCKET) - { - R_RocketTrail (oldorg, ent->origin, 0); - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->radius = 200; - dl->die = cl.time + 0.01; - } - else if (ent->model->flags & EF_GRENADE) - R_RocketTrail (oldorg, ent->origin, 1); - else if (ent->model->flags & EF_TRACER3) - R_RocketTrail (oldorg, ent->origin, 6); + //johnfitz -- assume muzzle flash accompanied by muzzle flare, which looks bad when lerped + if (r_lerpmodels.value != 2) { + if (ent == &cl_entities[cl.viewentity]) + cl.viewent.lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames + else + ent->lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames + } + //johnfitz + } + if (ent->effects & EF_BRIGHTLIGHT) { + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->origin[2] += 16; + dl->radius = 400 + (rand() & 31); + dl->die = cl.time + 0.001; + } + if (ent->effects & EF_DIMLIGHT) { + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->radius = 200 + (rand() & 31); + dl->die = cl.time + 0.001; + } + if (ent->effects & EF_QEX_QUADLIGHT) { + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->radius = 200 + (rand() & 31); + dl->die = cl.time + 0.001; + dl->color[0] = 0.25f; + dl->color[1] = 0.25f; + dl->color[2] = 1.0f; + } + if (ent->effects & EF_QEX_PENTALIGHT) { + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->radius = 200 + (rand() & 31); + dl->die = cl.time + 0.001; + dl->color[0] = 1.0f; + dl->color[1] = 0.25f; + dl->color[2] = 0.25f; + } - ent->forcelink = false; + if (ent->model->flags & EF_GIB) + R_RocketTrail(oldorg, ent->origin, 2); + else if (ent->model->flags & EF_ZOMGIB) + R_RocketTrail(oldorg, ent->origin, 4); + else if (ent->model->flags & EF_TRACER) + R_RocketTrail(oldorg, ent->origin, 3); + else if (ent->model->flags & EF_TRACER2) + R_RocketTrail(oldorg, ent->origin, 5); + else if (ent->model->flags & EF_ROCKET) { + R_RocketTrail(oldorg, ent->origin, 0); + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->radius = 200; + dl->die = cl.time + 0.01; + } else if (ent->model->flags & EF_GRENADE) + R_RocketTrail(oldorg, ent->origin, 1); + else if (ent->model->flags & EF_TRACER3) + R_RocketTrail(oldorg, ent->origin, 6); - if (i == cl.viewentity && !chase_active.value) - continue; + ent->forcelink = false; - if (cl_numvisedicts < MAX_VISEDICTS) - { - cl_visedicts[cl_numvisedicts] = ent; - cl_numvisedicts++; - } - } + if (i == cl.viewentity && !chase_active.value) + continue; + + if (cl_numvisedicts < MAX_VISEDICTS) { + cl_visedicts[cl_numvisedicts] = ent; + cl_numvisedicts++; + } + } } @@ -613,76 +572,75 @@ CL_ReadFromServer Read all incoming data from the server =============== */ -int CL_ReadFromServer (void) -{ - int ret; - extern int num_temp_entities; //johnfitz - int num_beams = 0; //johnfitz - int num_dlights = 0; //johnfitz - beam_t *b; //johnfitz - dlight_t *l; //johnfitz - int i; //johnfitz +int CL_ReadFromServer(void) { + int ret; + extern int num_temp_entities; //johnfitz + int num_beams = 0; //johnfitz + int num_dlights = 0; //johnfitz + beam_t *b; //johnfitz + dlight_t *l; //johnfitz + int i; //johnfitz - cl.oldtime = cl.time; - cl.time += host_frametime; + cl.oldtime = cl.time; + cl.time += host_frametime; - do - { - ret = CL_GetMessage (); - if (ret == -1) - Host_Error ("CL_ReadFromServer: lost server connection"); - if (!ret) - break; + do { + ret = CL_GetMessage(); + if (ret == -1) + Host_Error("CL_ReadFromServer: lost server connection"); + if (!ret) + break; - cl.last_received_message = realtime; - CL_ParseServerMessage (); - } while (ret && cls.state == ca_connected); + cl.last_received_message = realtime; + CL_ParseServerMessage(); + } while (ret && cls.state == ca_connected); - if (cl_shownet.value) - Con_Printf ("\n"); + if (cl_shownet.value) + Con_Printf("\n"); - CL_RelinkEntities (); - CL_UpdateTEnts (); + CL_RelinkEntities(); + CL_UpdateTEnts(); -//johnfitz -- devstats + //johnfitz -- devstats - //visedicts - if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) - Con_DWarning ("%i visedicts exceeds standard limit of 256 (max = %d).\n", cl_numvisedicts, MAX_VISEDICTS); - dev_stats.visedicts = cl_numvisedicts; - dev_peakstats.visedicts = std::max(cl_numvisedicts, dev_peakstats.visedicts); + //visedicts + if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) + Con_DWarning("%i visedicts exceeds standard limit of 256 (max = %d).\n", cl_numvisedicts, MAX_VISEDICTS); + dev_stats.visedicts = cl_numvisedicts; + dev_peakstats.visedicts = std::max(cl_numvisedicts, dev_peakstats.visedicts); - //temp entities - if (num_temp_entities > 64 && dev_peakstats.tempents <= 64) - Con_DWarning ("%i tempentities exceeds standard limit of 64 (max = %d).\n", num_temp_entities, MAX_TEMP_ENTITIES); - dev_stats.tempents = num_temp_entities; - dev_peakstats.tempents = std::max(num_temp_entities, dev_peakstats.tempents); + //temp entities + if (num_temp_entities > 64 && dev_peakstats.tempents <= 64) + Con_DWarning("%i tempentities exceeds standard limit of 64 (max = %d).\n", num_temp_entities, + MAX_TEMP_ENTITIES); + dev_stats.tempents = num_temp_entities; + dev_peakstats.tempents = std::max(num_temp_entities, dev_peakstats.tempents); - //beams - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) - if (b->model && b->endtime >= cl.time) - num_beams++; - if (num_beams > 24 && dev_peakstats.beams <= 24) - Con_DWarning ("%i beams exceeded standard limit of 24 (max = %d).\n", num_beams, MAX_BEAMS); - dev_stats.beams = num_beams; - dev_peakstats.beams = std::max(num_beams, dev_peakstats.beams); + //beams + for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++) + if (b->model && b->endtime >= cl.time) + num_beams++; + if (num_beams > 24 && dev_peakstats.beams <= 24) + Con_DWarning("%i beams exceeded standard limit of 24 (max = %d).\n", num_beams, MAX_BEAMS); + dev_stats.beams = num_beams; + dev_peakstats.beams = std::max(num_beams, dev_peakstats.beams); - //dlights - for (i=0, l=cl_dlights ; idie >= cl.time && l->radius) - num_dlights++; - if (num_dlights > 32 && dev_peakstats.dlights <= 32) - Con_DWarning ("%i dlights exceeded standard limit of 32 (max = %d).\n", num_dlights, MAX_DLIGHTS); - dev_stats.dlights = num_dlights; - dev_peakstats.dlights = std::max(num_dlights, dev_peakstats.dlights); + //dlights + for (i = 0, l = cl_dlights; i < MAX_DLIGHTS; i++, l++) + if (l->die >= cl.time && l->radius) + num_dlights++; + if (num_dlights > 32 && dev_peakstats.dlights <= 32) + Con_DWarning("%i dlights exceeded standard limit of 32 (max = %d).\n", num_dlights, MAX_DLIGHTS); + dev_stats.dlights = num_dlights; + dev_peakstats.dlights = std::max(num_dlights, dev_peakstats.dlights); -//johnfitz + //johnfitz -// -// bring the links up to date -// - return 0; + // + // bring the links up to date + // + return 0; } /* @@ -690,45 +648,41 @@ int CL_ReadFromServer (void) CL_SendCmd ================= */ -void CL_SendCmd (void) -{ - usercmd_t cmd; +void CL_SendCmd(void) { + usercmd_t cmd; - if (cls.state != ca_connected) - return; + if (cls.state != ca_connected) + return; - if (cls.signon == SIGNONS) - { - // get basic movement from keyboard - CL_BaseMove (&cmd); + if (cls.signon == SIGNONS) { + // get basic movement from keyboard + CL_BaseMove(&cmd); - // allow mice or other external controllers to add to the move - IN_Move (&cmd); + // allow mice or other external controllers to add to the move + IN_Move(&cmd); - // send the unreliable message - CL_SendMove (&cmd); - } + // send the unreliable message + CL_SendMove(&cmd); + } - if (cls.demoplayback) - { - SZ_Clear (&cls.message); - return; - } + if (cls.demoplayback) { + SZ_Clear(&cls.message); + return; + } -// send the reliable message - if (!cls.message.cursize) - return; // no message at all + // send the reliable message + if (!cls.message.cursize) + return; // no message at all - if (!NET_CanSendMessage (cls.netcon)) - { - Con_DPrintf ("CL_SendCmd: can't send\n"); - return; - } + if (!NET_CanSendMessage(cls.netcon)) { + Con_DPrintf("CL_SendCmd: can't send\n"); + return; + } - if (NET_SendMessage (cls.netcon, &cls.message) == -1) - Host_Error ("CL_SendCmd: lost server connection"); + if (NET_SendMessage(cls.netcon, &cls.message) == -1) + Host_Error("CL_SendCmd: lost server connection"); - SZ_Clear (&cls.message); + SZ_Clear(&cls.message); } /* @@ -738,20 +692,19 @@ CL_Tracepos_f -- johnfitz display impact point of trace along VPN ============= */ -void CL_Tracepos_f (void) -{ - vec3_t v, w; +void CL_Tracepos_f(void) { + vec3_t v, w; - if (cls.state != ca_connected) - return; + if (cls.state != ca_connected) + return; - VectorMA(r_refdef.vieworg, 8192.0, vpn, v); - TraceLine(r_refdef.vieworg, v, w); + VectorMA(r_refdef.vieworg, 8192.0, vpn, v); + TraceLine(r_refdef.vieworg, v, w); - if (VectorLength(w) == 0) - Con_Printf ("Tracepos: trace didn't hit anything\n"); - else - Con_Printf ("Tracepos: (%i %i %i)\n", (int)w[0], (int)w[1], (int)w[2]); + if (VectorLength(w) == 0) + Con_Printf("Tracepos: trace didn't hit anything\n"); + else + Con_Printf("Tracepos: (%i %i %i)\n", (int) w[0], (int) w[1], (int) w[2]); } /* @@ -761,28 +714,27 @@ CL_Viewpos_f -- johnfitz display client's position and angles ============= */ -void CL_Viewpos_f (void) -{ - if (cls.state != ca_connected) - return; +void CL_Viewpos_f(void) { + if (cls.state != ca_connected) + return; #if 0 - //camera position - Con_Printf ("Viewpos: (%i %i %i) %i %i %i\n", - (int)r_refdef.vieworg[0], - (int)r_refdef.vieworg[1], - (int)r_refdef.vieworg[2], - (int)r_refdef.viewangles[PITCH], - (int)r_refdef.viewangles[YAW], - (int)r_refdef.viewangles[ROLL]); + //camera position + Con_Printf("Viewpos: (%i %i %i) %i %i %i\n", + (int) r_refdef.vieworg[0], + (int) r_refdef.vieworg[1], + (int) r_refdef.vieworg[2], + (int) r_refdef.viewangles[PITCH], + (int) r_refdef.viewangles[YAW], + (int) r_refdef.viewangles[ROLL]); #else - //player position - Con_Printf ("Viewpos: (%i %i %i) %i %i %i\n", - (int)cl_entities[cl.viewentity].origin[0], - (int)cl_entities[cl.viewentity].origin[1], - (int)cl_entities[cl.viewentity].origin[2], - (int)cl.viewangles[PITCH], - (int)cl.viewangles[YAW], - (int)cl.viewangles[ROLL]); + //player position + Con_Printf("Viewpos: (%i %i %i) %i %i %i\n", + (int) cl_entities[cl.viewentity].origin[0], + (int) cl_entities[cl.viewentity].origin[1], + (int) cl_entities[cl.viewentity].origin[2], + (int) cl.viewangles[PITCH], + (int) cl.viewangles[YAW], + (int) cl.viewangles[ROLL]); #endif } @@ -791,51 +743,49 @@ void CL_Viewpos_f (void) CL_Init ================= */ -void CL_Init (void) -{ - SZ_Alloc (&cls.message, 1024); +void CL_Init(void) { + SZ_Alloc(&cls.message, 1024); - CL_InitInput (); - CL_InitTEnts (); + CL_InitInput(); + CL_InitTEnts(); - cl_name.inscribe(); - cl_color.inscribe(); - cl_upspeed.inscribe(); - cl_forwardspeed.inscribe(); - cl_backspeed.inscribe(); - cl_sidespeed.inscribe(); - cl_movespeedkey.inscribe(); - cl_yawspeed.inscribe(); - cl_pitchspeed.inscribe(); - cl_anglespeedkey.inscribe(); - cl_shownet.inscribe(); - cl_nolerp.inscribe(); - lookspring.inscribe(); - lookstrafe.inscribe(); - sensitivity.inscribe(); - - cl_alwaysrun.inscribe(); + cl_name.inscribe(); + cl_color.inscribe(); + cl_upspeed.inscribe(); + cl_forwardspeed.inscribe(); + cl_backspeed.inscribe(); + cl_sidespeed.inscribe(); + cl_movespeedkey.inscribe(); + cl_yawspeed.inscribe(); + cl_pitchspeed.inscribe(); + cl_anglespeedkey.inscribe(); + cl_shownet.inscribe(); + cl_nolerp.inscribe(); + lookspring.inscribe(); + lookstrafe.inscribe(); + sensitivity.inscribe(); - m_pitch.inscribe(); - m_yaw.inscribe(); - m_forward.inscribe(); - m_side.inscribe(); + cl_alwaysrun.inscribe(); - cfg_unbindall.inscribe(); + m_pitch.inscribe(); + m_yaw.inscribe(); + m_forward.inscribe(); + m_side.inscribe(); - cl_maxpitch.inscribe(); //johnfitz -- variable pitch clamping - cl_minpitch.inscribe(); //johnfitz -- variable pitch clamping + cfg_unbindall.inscribe(); - cl_startdemos.inscribe(); + cl_maxpitch.inscribe(); //johnfitz -- variable pitch clamping + cl_minpitch.inscribe(); //johnfitz -- variable pitch clamping - command::add ("entities", CL_PrintEntities_f); - command::add ("disconnect", CL_Disconnect_f); - command::add ("record", CL_Record_f); - command::add ("stop", CL_Stop_f); - command::add ("playdemo", CL_PlayDemo_f); - command::add ("timedemo", CL_TimeDemo_f); + cl_startdemos.inscribe(); - command::add ("tracepos", CL_Tracepos_f); //johnfitz - command::add ("viewpos", CL_Viewpos_f); //johnfitz + command::add("entities", CL_PrintEntities_f); + command::add("disconnect", CL_Disconnect_f); + command::add("record", CL_Record_f); + command::add("stop", CL_Stop_f); + command::add("playdemo", CL_PlayDemo_f); + command::add("timedemo", CL_TimeDemo_f); + + command::add("tracepos", CL_Tracepos_f); //johnfitz + command::add("viewpos", CL_Viewpos_f); //johnfitz } - diff --git a/Quake/cl_parse.cpp b/Quake/cl_parse.cpp index 518ab92..87cf398 100644 --- a/Quake/cl_parse.cpp +++ b/Quake/cl_parse.cpp @@ -98,9 +98,9 @@ const char *svc_strings[] = "svc_backtolobby", // 55 "svc_localsound" // 56 }; -#define NUM_SVC_STRINGS Q_COUNTOF(svc_strings) +#define NUM_SVC_STRINGS std::size(svc_strings) -qboolean warn_about_nehahra_protocol; //johnfitz +bool warn_about_nehahra_protocol; //johnfitz extern vec3_t v_punchangles[2]; //johnfitz @@ -432,7 +432,7 @@ void CL_ParseUpdate(int bits) { int i; qmodel_t *model; int modnum; - qboolean forcelink; + bool forcelink; entity_t *ent; int num; int skin; @@ -1034,7 +1034,7 @@ void CL_ParseServerMessage(void) { break; case svc_stufftext: - Cbuf_AddText(MSG_ReadString()); + command::buffer::add_text(MSG_ReadString()); break; case svc_damage: @@ -1060,7 +1060,7 @@ void CL_ParseServerMessage(void) { if (i >= MAX_LIGHTSTYLES) Sys_Error("svc_lightstyle > MAX_LIGHTSTYLES"); q_strlcpy(cl_lightstyle[i].map, MSG_ReadString(), MAX_STYLESTRING); - cl_lightstyle[i].length = Q_strlen(cl_lightstyle[i].map); + cl_lightstyle[i].length = std::strlen(cl_lightstyle[i].map); //johnfitz -- save extra info if (cl_lightstyle[i].length) { total = 0; @@ -1131,10 +1131,10 @@ void CL_ParseServerMessage(void) { cl.paused = MSG_ReadByte(); if (cl.paused) { CDAudio_Pause(); - BGM_Pause(); + music::pause(); } else { CDAudio_Resume(); - BGM_Resume(); + music::resume(); } break; @@ -1177,9 +1177,9 @@ void CL_ParseServerMessage(void) { cl.cdtrack = MSG_ReadByte(); cl.looptrack = MSG_ReadByte(); if ((cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1)) - BGM_PlayCDtrack((byte) cls.forcetrack, true); + music::play_cd_track((byte) cls.forcetrack, true); else - BGM_PlayCDtrack((byte) cl.cdtrack, true); + music::play_cd_track((byte) cl.cdtrack, true); break; case svc_intermission: diff --git a/Quake/client.hpp b/Quake/client.hpp index 1c8f412..fb33f14 100644 --- a/Quake/client.hpp +++ b/Quake/client.hpp @@ -112,14 +112,14 @@ typedef struct // demo recording info must be here, because record is started before // entering a map (and clearing client_state_t) - qboolean demorecording; - qboolean demoplayback; + bool demorecording; + bool demoplayback; // did the user pause demo playback? (separate from cl.paused because we don't // want a svc_setpause inside the demo to actually pause demo playback). - qboolean demopaused; + bool demopaused; - qboolean timedemo; + bool timedemo; int forcetrack; // -1 = use normal cd track FILE *demofile; int td_lastframe; // to meter out one message a frame @@ -173,16 +173,16 @@ typedef struct // pitch drifting vars float idealpitch; float pitchvel; - qboolean nodrift; + bool nodrift; float driftmove; double laststop; float viewheight; float crouch; // local amount for smoothing stepups - qboolean paused; // send over by server - qboolean onground; - qboolean inwater; + bool paused; // send over by server + bool onground; + bool inwater; int intermission; // don't change view angle, full screen, etc int completed_time; // latched at intermission start diff --git a/Quake/cmd.cpp b/Quake/cmd.cpp index 3132932..ec80407 100644 --- a/Quake/cmd.cpp +++ b/Quake/cmd.cpp @@ -29,8 +29,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.hpp" -void Cmd_ForwardToServer(void); - constexpr int CMDLINE_LENGTH = 256; constexpr int MAX_ARGS = 80; @@ -57,7 +55,7 @@ namespace command { * bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2" * ``` */ - void set_wait() { + void _set_wait() { waiting = true; } @@ -111,13 +109,11 @@ namespace command { } void _alias() { - char cmd[1024]; - switch (argc()) { case 1: { //list all aliases auto count = 0; - for (auto &[name, alias]: command::ALIASES) { + for (auto &[name, alias]: ALIASES) { Con_SafePrintf(" %s: %s", name.c_str(), alias.value.c_str()); count++; } @@ -130,7 +126,7 @@ namespace command { case 2: { //output current alias string const auto lookup = argv(1).value(); - for (auto &[name, alias]: command::ALIASES) + for (auto &[name, alias]: ALIASES) if (name.starts_with(lookup)) Con_Printf(" %s: %s", name.c_str(), alias.value.c_str()); break; @@ -138,14 +134,14 @@ namespace command { default: { //set alias string const auto new_name = argv(1).value(); - if (new_name.length() >= command::MAX_ALIAS_LENGTH) { + if (new_name.length() >= MAX_ALIAS_LENGTH) { Con_Printf("Alias name is too long\n"); return; } - std::optional new_alias = std::nullopt; + std::optional new_alias = std::nullopt; // if the alias already exists, reuse it - for (auto &[name, alias]: command::ALIASES) { + for (auto &[name, alias]: ALIASES) { if (name == new_name) { new_alias = alias; alias.value.clear(); @@ -154,26 +150,21 @@ namespace command { } if (!new_alias.has_value()) { - new_alias = command::alias{}; + new_alias = alias{}; } new_alias->name = new_name; // copy the rest of the command line - cmd[0] = 0; // start out with a null string - auto c = argc(); - // TODO: ew - for (auto i = 2; i < c; i++) { - q_strlcat(cmd, argv(i).value().c_str(), sizeof(cmd)); - if (i != c - 1) - q_strlcat(cmd, " ", sizeof(cmd)); + auto cmd = std::string{}; + const auto count = argc(); + for (auto i = 2; i < count; i++) { + cmd += argv(i).value(); + if (i != count - 1) { + cmd += ' '; + } } - if (q_strlcat(cmd, "\n", sizeof(cmd)) >= sizeof(cmd)) { - Con_Printf("alias value too long!\n"); - cmd[0] = '\n'; // nullify the string - cmd[1] = 0; - } - - new_alias->value = Z_Strdup(cmd); + cmd += '\n'; + new_alias->value = cmd; break; } } @@ -195,9 +186,9 @@ namespace command { */ void _stuffcmds() { char cmds[CMDLINE_LENGTH]; - int i, j, plus; + int i, j; - plus = false; // On Unix, argv[0] is command name + auto plus = false; // On Unix, argv[0] is command name for (i = 0, j = 0; cmdline.string[i]; i++) { if (cmdline.string[i] == '+') { @@ -214,33 +205,32 @@ namespace command { } cmds[j] = 0; - Cbuf_InsertText(cmds); + buffer::insert_text(cmds); } #include "default_cfg.hpp" void _exec() { - const char *f; - int mark; - if (argc() != 2) { Con_Printf("exec : execute a script file\n"); return; } - mark = Hunk_LowMark(); - auto filename = argv(1); - f = (const char *) COM_LoadHunkFile(filename->c_str(), NULL); - if (!f && !strcmp(argv(1)->c_str(), "default.cfg")) { + const auto mark = Hunk_LowMark(); + const auto filename = argv(1); + + auto f = reinterpret_cast(COM_LoadHunkFile(filename->c_str(), nullptr)); + + if (f == nullptr && argv(1) == "default.cfg") { f = default_cfg; /* see above.. */ } - if (!f) { + if (f == nullptr) { Con_Printf("couldn't exec %s\n", argv(1)->c_str()); return; } Con_Printf("execing %s\n", argv(1)->c_str()); - Cbuf_InsertText(f); + buffer::insert_text(f); if (f != default_cfg) { Hunk_FreeToLowMark(mark); } @@ -252,7 +242,7 @@ namespace command { Con_Printf("\n"); } - char *tint_substring(const char *in, const char *substr, char *out, size_t outsize) { + char *tint_substring(const char *in, const char *substr, char *out, const size_t outsize) { int l; char *m; q_strlcpy(out, in, outsize); @@ -311,8 +301,8 @@ namespace command { add("exec", _exec); add("echo", _echo); add("alias", _alias); - add("cmd", Cmd_ForwardToServer); - add("wait", set_wait); + add("cmd", forward_to_server); + add("wait", _set_wait); add("apropos", _apropos); add("find", _apropos); @@ -424,7 +414,7 @@ namespace command { if (argc() == 0) return; // no tokens - auto needle = argv(0).value(); + const auto needle = argv(0).value(); // check functions for (const auto &[name, ref]: REFS) { if (!q_strcasecmp(needle.c_str(), name.c_str())) { @@ -436,7 +426,7 @@ namespace command { // check alias for (const auto &[name, alias]: ALIASES) { if (!q_strcasecmp(argv(0).value().c_str(), name.c_str())) { - Cbuf_InsertText(alias.value.c_str()); + buffer::insert_text(alias.value); return; } } @@ -473,9 +463,6 @@ namespace command { alias_view get_aliases() { return std::ranges::views::values(ALIASES); } - - void print(std::string text) { - } } @@ -490,201 +477,72 @@ namespace command { ============================================================================= */ -sizebuf_t cmd_text; -/* -============ -Cbuf_Init -============ -*/ -void Cbuf_Init(void) { - SZ_Alloc(&cmd_text, 1 << 18); - // space for commands and script files. spike -- was 8192, but modern configs can be _HUGE_, at least if they contain lots of comments/docs for things. -} - - -/* -============ -Cbuf_AddText - -Adds command text at the end of the buffer -============ -*/ -void Cbuf_AddText(const char *text) { - int l; - - l = Q_strlen(text); - - if (cmd_text.cursize + l >= cmd_text.maxsize) { - Con_Printf("Cbuf_AddText: overflow\n"); - return; +namespace command::buffer { + namespace { + constexpr std::size_t MAX_BUFFER_SIZE = 1 << 18; + std::string _buffer; } - SZ_Write(&cmd_text, text, Q_strlen(text)); -} - - -/* -============ -Cbuf_InsertText - -Adds command text immediately after the current command -Adds a \n to the text -FIXME: actually change the command buffer to do less copying -============ -*/ -void Cbuf_InsertText(const char *text) { - char *temp; - int templen; - - // copy off any commands still remaining in the exec buffer - templen = cmd_text.cursize; - if (templen) { - temp = (char *) Z_Malloc(templen); - Q_memcpy(temp, cmd_text.data, templen); - SZ_Clear(&cmd_text); - } else - temp = NULL; // shut up compiler - - // add the entire text of the file - Cbuf_AddText(text); - SZ_Write(&cmd_text, "\n", 1); - // add the copied off data - if (templen) { - SZ_Write(&cmd_text, temp, templen); - Z_Free(temp); + void init() { + _buffer = std::string{}; + _buffer.reserve(MAX_BUFFER_SIZE); } -} -/* -============ -Cbuf_Execute -============ -*/ -void Cbuf_Execute(void) { - int i; - char *text; - char line[1024]; - int quotes; + void add_text(const std::string &text) { + if (_buffer.length() + text.length() >= MAX_BUFFER_SIZE) { + Con_Printf("command::buffer::add_text(): overflow\n"); + return; + } - while (cmd_text.cursize) { - // find a \n or ; line break - text = (char *) cmd_text.data; + _buffer.append(text); + } - quotes = 0; - for (i = 0; i < cmd_text.cursize; i++) { - if (text[i] == '"') - quotes++; - if (!(quotes & 1) && text[i] == ';') - break; // don't break if inside a quoted string - if (text[i] == '\n') + void insert_text(const std::string &text) { + if (_buffer.length() + text.length() >= MAX_BUFFER_SIZE) { + Con_Printf("command::buffer::insert_text(): overflow\n"); + return; + } + + _buffer = text + _buffer; + } + + void execute() { + while (!_buffer.empty()) { + std::string line{}; + auto quotes = 0; + for (const auto c: _buffer) { + if (c == '"') { + quotes++; + } + if (!(quotes & 1) && c == ';') { + break; // don't break if inside a quoted string + } + if (c == '\n') { + break; + } + line += c; + } + + // delete the text from the command buffer and move remaining commands down + // this is necessary because commands (exec, alias) can insert data at the + // beginning of the text buffer + + if (line.length() + 1 == _buffer.length()) { + _buffer.clear(); + } else { + _buffer = _buffer.substr(line.length() + 1); + } + + // execute the command line + execute_string(line, source::command); + + if (is_waiting()) { + // skip out while text still remains in buffer, leaving it + // for next frame + stop_waiting(); break; - } - - if (i > (int) sizeof(line) - 1) { - memcpy(line, text, sizeof(line) - 1); - line[sizeof(line) - 1] = 0; - } else { - memcpy(line, text, i); - line[i] = 0; - } - - // delete the text from the command buffer and move remaining commands down - // this is necessary because commands (exec, alias) can insert data at the - // beginning of the text buffer - - if (i == cmd_text.cursize) - cmd_text.cursize = 0; - else { - i++; - cmd_text.cursize -= i; - memmove(text, text + i, cmd_text.cursize); - } - - // execute the command line - command::execute_string(line, command::source::command); - - if (command::is_waiting()) { - // skip out while text still remains in buffer, leaving it - // for next frame - command::stop_waiting(); - break; + } } } } - -/* -============================================================================== - - SCRIPT COMMANDS - -============================================================================== -*/ - - -/* id1/pak0.pak from 2021 re-release doesn't have a default.cfg - * embedding Quakespasm's customized default.cfg for that... */ - - -/* -============================================================================= - - COMMAND EXECUTION - -============================================================================= -*/ - - -/* -============ -Cmd_AddCommand -============ -*/ - - -/* -============ -Cmd_Exists -============ -*/ - - -/* -============ -Cmd_CompleteCommand -============ -*/ - - -/* -============ -Cmd_ExecuteString - -A complete command line has been parsed, so try to execute it -FIXME: lookupnoadd the token to speed search? -============ -*/ - - -/* -=================== -Cmd_ForwardToServer - -Sends the entire command line over to the server -=================== -*/ -void Cmd_ForwardToServer(void) { -} - - -/* -================ -Cmd_CheckParm - -Returns the position (1 to argc-1) in the command's argument list -where the given parameter apears, or 0 if not present -================ -*/ - -int Cmd_CheckParm(const char *parm) { -} diff --git a/Quake/cmd.hpp b/Quake/cmd.hpp index 33ec07f..51daa02 100644 --- a/Quake/cmd.hpp +++ b/Quake/cmd.hpp @@ -2,6 +2,7 @@ Copyright (C) 1996-2001 Id Software, Inc. Copyright (C) 2002-2009 John Fitzgibbons and others Copyright (C) 2010-2014 QuakeSpasm developers +Copyright (C) 2026 iikorni This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License @@ -26,122 +27,71 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //=========================================================================== -/* - -Any number of commands can be added in a frame, from several different sources. -Most commands come from either keybindings or console line input, but remote -servers can also send across commands and entire text files can be execed. - -The + command line options are also added to the command buffer. - -The game starts with a Cbuf_AddText ("exec quake.rc\n"); Cbuf_Execute (); - -*/ - -void Cbuf_Init (void); -// allocates an initial text buffer that will grow as needed - -void Cbuf_AddText (const char *text); -// as new commands are generated from the console or keybindings, -// the text is added to the end of the command buffer. - -void Cbuf_InsertText (const char *text); -// when a command wants to issue other commands immediately, the text is -// inserted at the beginning of the buffer, before any remaining unexecuted -// commands. - -void Cbuf_Execute (void); -// Pulls off \n terminated lines of text from the command buffer and sends -// them through Cmd_ExecuteString. Stops when the buffer is empty. -// Normally called once per frame, but may be explicitly invoked. -// Do not call inside a command function! - -//=========================================================================== - -/* - -Command execution takes a null terminated string, breaks it into tokens, -then searches for a command or variable that matches the first token. - -Commands can come from three sources, but the handler functions may choose -to dissallow the action or forward it to a remote server if the source is -not apropriate. - -*/ - -typedef void (*xcommand_t) (void); - +typedef void (*xcommand_t)(); namespace command { - enum class source { - client, - command - }; + namespace buffer { + void init(); - extern source last_source; + void add_text(const std::string &text); - struct alias { - std::string name; - std::string value; - }; + void insert_text(const std::string &text); - struct definition { - std::string name{}; - xcommand_t func{nullptr}; + void execute(); + } - definition(const std::string &name, const xcommand_t func) { - this->name = name; - this->func = func; - } - }; + enum class source { + client, + command + }; - using definition_view = std::ranges::elements_view>>, 1>; - using alias_view = std::ranges::elements_view>>, 1>; + extern source last_source; + + struct alias { + std::string name; + std::string value; + }; + + struct definition { + std::string name{}; + xcommand_t func{nullptr}; + + definition(const std::string &name, const xcommand_t func) { + this->name = name; + this->func = func; + } + }; + + using definition_view = std::ranges::elements_view > >, 1>; + using alias_view = std::ranges::elements_view > >, 1> + ; - void init(); + void init(); - void add(const std::string &name, xcommand_t cmd); - std::optional complete(const std::string &partial); - bool exists(std::string_view lookup); + void add(const std::string &name, xcommand_t cmd); - int argc(); - std::optional argv(int arg); - std::string args(); + std::optional complete(const std::string &partial); - int check_parm(const std::string &parm); + bool exists(std::string_view lookup); - void tokenize_string(const std::string &text); + int argc(); - void execute_string(const std::string &text, source src); + std::optional argv(int arg); - void forward_to_server(); + std::string args(); - definition_view get_commands(); + int check_parm(const std::string &parm); - alias_view get_aliases(); + void tokenize_string(const std::string &text); + + void execute_string(const std::string &text, source src); + + void forward_to_server(); + + definition_view get_commands(); + + alias_view get_aliases(); } - -// called by the init functions of other parts of the program to -// register commands and functions to call for them. -// The cmd_name is referenced later, so it should not be in temp memory - -// used by the cvar code to check for cvar / command name overlap - -// attempts to match a partial command for automatic command line completion -// returns NULL if nothing fits - -// Returns the position (1 to argc-1) in the command's argument list -// where the given parameter apears, or 0 if not present - -// Parses a single line of text into arguments and tries to execute it. -// The text can come from the command buffer, a remote client, or stdin. - -// adds the current command line as a clc_stringcmd to the client message. -// things like godmode, noclip, etc, are commands directed to the server, -// so when they are typed in at the console, they will need to be forwarded. - -// used by command functions to send output to either the graphics console or -// passed as a print message to the client - diff --git a/Quake/common.cpp b/Quake/common.cpp index 4da62f9..d87a5a2 100644 --- a/Quake/common.cpp +++ b/Quake/common.cpp @@ -22,6 +22,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // common.c -- misc functions used in client and server +#include + #include "quakedef.hpp" #include "q_ctype.hpp" #include @@ -37,9 +39,9 @@ int safemode; convar registered = {"registered", "1", {.rom = true}}; /* set to correct value in COM_CheckRegistered() */ convar cmdline = {"cmdline", "", {.rom = true}/*|CVAR_SERVERINFO*/}; /* sending cmdline upon CCREQ_RULE_INFO is evil */ -static qboolean com_modified; // set true if using non-id files +static bool com_modified; // set true if using non-id files -qboolean fitzmode; +bool fitzmode; static void COM_Path_f(void); @@ -58,7 +60,7 @@ char **com_argv; #define CMDLINE_LENGTH 256 /* johnfitz -- mirrored in cmd.c */ char com_cmdline[CMDLINE_LENGTH]; -qboolean standard_quake = true, rogue, hipnotic; +bool standard_quake = true, rogue, hipnotic; // this graphic needs to be in the pak file to use registered features static unsigned short pop[] = @@ -309,232 +311,6 @@ int q_snprintf(char *str, size_t size, const char *format, ...) { return ret; } -void Q_memset(void *dest, int fill, size_t count) { - size_t i; - - if ((((uintptr_t) dest | count) & 3) == 0) { - count >>= 2; - fill = fill | (fill << 8) | (fill << 16) | (fill << 24); - for (i = 0; i < count; i++) - ((int *) dest)[i] = fill; - } else - for (i = 0; i < count; i++) - ((byte *) dest)[i] = fill; -} - -void Q_memcpy(void *dest, const void *src, size_t count) { - size_t i; - - if ((((uintptr_t) dest | (uintptr_t) src | count) & 3) == 0) { - count >>= 2; - for (i = 0; i < count; i++) - ((int *) dest)[i] = ((int *) src)[i]; - } else - for (i = 0; i < count; i++) - ((byte *) dest)[i] = ((byte *) src)[i]; -} - -int Q_memcmp(const void *m1, const void *m2, size_t count) { - while (count) { - count--; - if (((byte *) m1)[count] != ((byte *) m2)[count]) - return -1; - } - return 0; -} - -void Q_strcpy(char *dest, const char *src) { - while (*src) { - *dest++ = *src++; - } - *dest++ = 0; -} - -void Q_strncpy(char *dest, const char *src, int count) { - while (*src && count--) { - *dest++ = *src++; - } - if (count) - *dest++ = 0; -} - -int Q_strlen(const char *str) { - int count; - - count = 0; - while (str[count]) - count++; - - return count; -} - -char *Q_strrchr(const char *s, char c) { - int len = Q_strlen(s); - s += len; - while (len--) { - if (*--s == c) - return (char *) s; - } - return NULL; -} - -void Q_strcat(char *dest, const char *src) { - dest += Q_strlen(dest); - Q_strcpy(dest, src); -} - -int Q_strcmp(const char *s1, const char *s2) { - while (1) { - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal - s1++; - s2++; - } - - return -1; -} - -int Q_strncmp(const char *s1, const char *s2, int count) { - while (1) { - if (!count--) - return 0; - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal - s1++; - s2++; - } - - return -1; -} - -int Q_atoi(const char *str) { - int val; - int sign; - int c; - - while (q_isspace(*str)) - ++str; - - if (*str == '-') { - sign = -1; - str++; - } else - sign = 1; - - val = 0; - - // - // check for hex - // - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { - str += 2; - while (1) { - c = *str++; - if (c >= '0' && c <= '9') - val = (val << 4) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val << 4) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val << 4) + c - 'A' + 10; - else - return val * sign; - } - } - - // - // check for character - // - if (str[0] == '\'') { - return sign * str[1]; - } - - // - // assume decimal - // - while (1) { - c = *str++; - if (c < '0' || c > '9') - return val * sign; - val = val * 10 + c - '0'; - } - - return 0; -} - - -float Q_atof(const char *str) { - double val; - int sign; - int c; - int decimal, total; - - while (q_isspace(*str)) - ++str; - - if (*str == '-') { - sign = -1; - str++; - } else - sign = 1; - - val = 0; - - // - // check for hex - // - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { - str += 2; - while (1) { - c = *str++; - if (c >= '0' && c <= '9') - val = (val * 16) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val * 16) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val * 16) + c - 'A' + 10; - else - return val * sign; - } - } - - // - // check for character - // - if (str[0] == '\'') { - return sign * str[1]; - } - - // - // assume decimal - // - decimal = -1; - total = 0; - while (1) { - c = *str++; - if (c == '.') { - decimal = total; - continue; - } - if (c < '0' || c > '9') - break; - val = val * 10 + c - '0'; - total++; - } - - if (decimal == -1) - return val * sign; - while (total > decimal) { - val /= 10; - total--; - } - - return val * sign; -} - /* ============================================================================ @@ -543,7 +319,7 @@ float Q_atof(const char *str) { ============================================================================ */ -qboolean host_bigendian; +bool host_bigendian; short (*BigShort)(short l); @@ -680,7 +456,7 @@ void MSG_WriteString(sizebuf_t *sb, const char *s) { if (!s) SZ_Write(sb, "", 1); else - SZ_Write(sb, s, Q_strlen(s) + 1); + SZ_Write(sb, s, std::strlen(s) + 1); } //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 @@ -730,7 +506,7 @@ void MSG_WriteAngle16(sizebuf_t *sb, float f, unsigned int flags) { // reading functions // int msg_readcount; -qboolean msg_badread; +bool msg_badread; void MSG_BeginReading(void) { msg_readcount = 0; @@ -924,18 +700,18 @@ void *SZ_GetSpace(sizebuf_t *buf, int length) { } void SZ_Write(sizebuf_t *buf, const void *data, int length) { - Q_memcpy(SZ_GetSpace(buf, length), data, length); + std::memcpy(SZ_GetSpace(buf, length), data, length); } void SZ_Print(sizebuf_t *buf, const char *data) { - int len = Q_strlen(data) + 1; + int len = std::strlen(data) + 1; if (buf->data[buf->cursize - 1]) { /* no trailing 0 */ - Q_memcpy((byte *) SZ_GetSpace(buf, len), data, len); + std::memcpy(SZ_GetSpace(buf, len), data, len); } else { /* write over trailing 0 */ - Q_memcpy((byte *) SZ_GetSpace(buf, len - 1) - 1, data, len); + std::memcpy(static_cast(SZ_GetSpace(buf, len - 1)) - 1, data, len); } } @@ -1090,6 +866,66 @@ void COM_AddExtension(char *path, const char *extension, size_t len) { namespace common { + + void init() { + int i = 0x12345678; + /* U N I X */ + + /* + BE_ORDER: 12 34 56 78 + U N I X + + LE_ORDER: 78 56 34 12 + X I N U + + PDP_ORDER: 34 12 78 56 + N U X I + */ + if (*reinterpret_cast(&i) == 0x12) { + host_bigendian = true; + } + else if (*reinterpret_cast(&i) == 0x78) { + host_bigendian = false; + } + else { + Sys_Error("Unsupported endianism."); + } + + if (host_bigendian) { + BigShort = ShortNoSwap; + LittleShort = ShortSwap; + BigLong = LongNoSwap; + LittleLong = LongSwap; + BigFloat = FloatNoSwap; + LittleFloat = FloatSwap; + } else /* assumed LITTLE_ENDIAN. */ + { + BigShort = ShortSwap; + LittleShort = ShortNoSwap; + BigLong = LongSwap; + LittleLong = LongNoSwap; + BigFloat = FloatSwap; + LittleFloat = FloatNoSwap; + } + + if (check_param("-fitz").has_value()) { + fitzmode = true; + } + } + + std::optional check_param(std::string_view parm) { + for (auto i = 1; i < com_argc; i++) { + if (!com_argv[i]) { + continue; // NEXTSTEP sometimes clears appkit vars. + } + if (parm == com_argv[i]) { + return i; + } + } + + return std::nullopt; + } + /** * Parses a single token from a string-stream. * @@ -1214,27 +1050,6 @@ namespace common { } -/* -================ -COM_CheckParm - -Returns the position (1 to argc-1) in the program's argument list -where the given parameter apears, or 0 if not present -================ -*/ -int COM_CheckParm(const char *parm) { - int i; - - for (i = 1; i < com_argc; i++) { - if (!com_argv[i]) - continue; // NEXTSTEP sometimes clears appkit vars. - if (!Q_strcmp(parm, com_argv[i])) - return i; - } - - return 0; -} - /* ================ COM_CheckRegistered @@ -1318,73 +1133,25 @@ void COM_InitArgv(int argc, char **argv) { for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) { largv[com_argc] = argv[com_argc]; - if (!Q_strcmp("-safe", argv[com_argc])) + if (!std::strcmp("-safe", argv[com_argc])) safemode = 1; } largv[com_argc] = argvdummy; com_argv = largv; - if (COM_CheckParm("-rogue")) { + if (common::check_param("-rogue").has_value()) { rogue = true; standard_quake = false; } - if (COM_CheckParm("-hipnotic") || COM_CheckParm("-quoth")) //johnfitz -- "-quoth" support + if (common::check_param("-hipnotic").has_value() || common::check_param("-quoth").has_value()) //johnfitz -- "-quoth" support { hipnotic = true; standard_quake = false; } } -/* -================ -COM_Init -================ -*/ -void COM_Init(void) { - int i = 0x12345678; - /* U N I X */ - - /* - BE_ORDER: 12 34 56 78 - U N I X - - LE_ORDER: 78 56 34 12 - X I N U - - PDP_ORDER: 34 12 78 56 - N U X I - */ - if (*(char *) &i == 0x12) - host_bigendian = true; - else if (*(char *) &i == 0x78) - host_bigendian = false; - else /* if ( *(char *)&i == 0x34 ) */ - Sys_Error("Unsupported endianism."); - - if (host_bigendian) { - BigShort = ShortNoSwap; - LittleShort = ShortSwap; - BigLong = LongNoSwap; - LittleLong = LongSwap; - BigFloat = FloatNoSwap; - LittleFloat = FloatSwap; - } else /* assumed LITTLE_ENDIAN. */ - { - BigShort = ShortSwap; - LittleShort = ShortNoSwap; - BigLong = LongSwap; - LittleLong = LongNoSwap; - BigFloat = FloatSwap; - LittleFloat = FloatNoSwap; - } - - if (COM_CheckParm("-fitz")) - fitzmode = true; -} - - /* ============ va @@ -1632,7 +1399,7 @@ COM_FileExists Returns whether the file is found in the quake filesystem. =========== */ -qboolean COM_FileExists(const char *filename, unsigned int *path_id) { +bool COM_FileExists(const char *filename, unsigned int *path_id) { int ret = COM_FindFile(filename, NULL, NULL, path_id); return (ret == -1) ? false : true; } @@ -1927,7 +1694,7 @@ static void COM_AddGameDirectory(const char *base, const char *dir) { searchpath_t *search; pack_t *pak, *qspak; char pakfile[MAX_OSPATH]; - qboolean been_here = false; + bool been_here = false; q_strlcpy(com_gamedir, va("%s/%s", base, dir), sizeof(com_gamedir)); @@ -1951,7 +1718,7 @@ _add_path: if (i != 0 || path_id != 1 || fitzmode) qspak = NULL; else { - qboolean old = com_modified; + bool old = com_modified; if (been_here) base = host_parms->userdir; q_snprintf(pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); qspak = COM_LoadPackFile(pakfile); @@ -2110,8 +1877,8 @@ static void COM_Game_f(void) { Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir)); VID_Lock(); - Cbuf_AddText("exec quake.rc\n"); - Cbuf_AddText("vid_unlock\n"); + command::buffer::add_text("exec quake.rc\n"); + command::buffer::add_text("vid_unlock\n"); } else //Diplay the current gamedir Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir)); } @@ -2123,23 +1890,24 @@ COM_InitFilesystem */ void COM_InitFilesystem(void) //johnfitz -- modified based on topaz's tutorial { - int i, j; - registered.inscribe(); cmdline.inscribe(); command::add("path", COM_Path_f); command::add("game", COM_Game_f); //johnfitz - i = COM_CheckParm("-basedir"); - if (i && i < com_argc - 1) - q_strlcpy(com_basedir, com_argv[i + 1], sizeof(com_basedir)); - else + auto i = common::check_param("-basedir"); + if (i.has_value() && i.value() < com_argc - 1) { + q_strlcpy(com_basedir, com_argv[i.value() + 1], sizeof(com_basedir)); + } + else { q_strlcpy(com_basedir, host_parms->basedir, sizeof(com_basedir)); + } - j = strlen(com_basedir); + const auto j = strlen(com_basedir); if (j < 1) Sys_Error("Bad argument to -basedir"); - if ((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) + if ((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) { com_basedir[j - 1] = 0; + } // start up with GAMENAME by default (id1) COM_AddGameDirectory(com_basedir, GAMENAME); @@ -2151,24 +1919,34 @@ void COM_InitFilesystem(void) //johnfitz -- modified based on topaz's tutorial com_base_searchpaths = com_searchpaths; // add mission pack requests (only one should be specified) - if (COM_CheckParm("-rogue")) + if (common::check_param("-rogue").has_value()) { COM_AddGameDirectory(com_basedir, "rogue"); - if (COM_CheckParm("-hipnotic")) + } + if (common::check_param("-hipnotic").has_value()) { COM_AddGameDirectory(com_basedir, "hipnotic"); - if (COM_CheckParm("-quoth")) + } + if (common::check_param("-quoth").has_value()) { COM_AddGameDirectory(com_basedir, "quoth"); + } - i = COM_CheckParm("-game"); - if (i && i < com_argc - 1) { - const char *p = com_argv[i + 1]; - if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) + i = common::check_param("-game"); + if (i.has_value() && i.value() < com_argc - 1) { + const char *p = com_argv[i.value() + 1]; + if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) { Sys_Error("gamedir should be a single directory name, not a path\n"); + } com_modified = true; // don't load mission packs twice - if (COM_CheckParm("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; - if (p && COM_CheckParm("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; - if (p && COM_CheckParm("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; - if (p != NULL) { + if (common::check_param("-rogue").has_value() && !q_strcasecmp(p, "rogue")) { + p = nullptr; + } + if (p && common::check_param("-hipnotic").has_value() && !q_strcasecmp(p, "hipnotic")) { + p = nullptr; + } + if (p && common::check_param("-quoth").has_value() && !q_strcasecmp(p, "quoth")) { + p = nullptr; + } + if (p != nullptr) { COM_AddGameDirectory(com_basedir, p); // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' if (!q_strcasecmp(p, "rogue")) { @@ -2509,8 +2287,8 @@ void LOC_LoadFile(const char *file) { Con_DPrintf("LOC_LoadFile: malformed comment on line %d\n", lineno); } else if (equals) { char *key_end = equals; - qboolean leading_quote; - qboolean trailing_quote; + bool leading_quote; + bool trailing_quote; locentry_t *entry; char *value_src; char *value_dst; @@ -2675,7 +2453,7 @@ const char *LOC_GetRawString(const char *key) { return NULL; entry = &localization.entries[idx - 1]; - if (!Q_strcmp(entry->key, key)) + if (!std::strcmp(entry->key, key)) return entry->value; ++pos; @@ -2733,7 +2511,7 @@ static int LOC_ParseArg(const char **pstr) { LOC_HasPlaceholders ================ */ -qboolean LOC_HasPlaceholders(const char *str) { +bool LOC_HasPlaceholders(const char *str) { if (!localization.numindices) return false; while (*str) { @@ -2778,14 +2556,14 @@ size_t LOC_Format(const char *format, const char * (*getarg_fn)(int idx, void *u insert = getarg_fn(argindex, userdata); space_left = len - written; - insert_len = Q_strlen(insert); + insert_len = std::strlen(insert); if (insert_len > space_left) { Con_DPrintf("LOC_Format: overflow at argument #%d\n", numargs); insert_len = space_left; } - Q_memcpy(out + written, insert, insert_len); + std::memcpy(out + written, insert, insert_len); written += insert_len; } diff --git a/Quake/common.hpp b/Quake/common.hpp index 27240c3..90ed66e 100644 --- a/Quake/common.hpp +++ b/Quake/common.hpp @@ -79,30 +79,13 @@ GENERIC_TYPES (IMPL_GENERIC_FUNCS, NO_COMMA) #define SELECT_CLAMP(type, suffix) type: clamp_##suffix #define CLAMP(minval, val, maxval) _Generic((minval) + (val) + (maxval), \ GENERIC_TYPES (SELECT_CLAMP, COMMA))(minval, val, maxval) - -#elif defined(__GNUC__) -#define CLAMP(_minval, x, _maxval) ({ \ - const __typeof(x) x_ = (x); \ - const __typeof(_minval) valmin_ = (_minval);\ - const __typeof(_maxval) valmax_ = (_maxval);\ - (void)(&x_ == &valmin_); \ - (void)(&x_ == &valmax_); \ - (x_ < valmin_) ? valmin_ : \ - (x_ > valmax_) ? valmax_ : x_; \ -}) - -#else -#define std::min(a, b) (((a) < (b)) ? (a) : (b)) -#define std::max(a, b) (((a) > (b)) ? (a) : (b)) -#define CLAMP(_minval, x, _maxval) \ - ((x) < (_minval) ? (_minval) : \ - (x) > (_maxval) ? (_maxval) : (x)) #endif +// TODO: Maybe some special casing on an std::vector? typedef struct sizebuf_s { - qboolean allowoverflow; // if false, do a Sys_Error - qboolean overflowed; // set to true if the buffer size failed + bool allowoverflow; // if false, do a Sys_Error + bool overflowed; // set to true if the buffer size failed byte *data; int maxsize; int cursize; @@ -154,7 +137,7 @@ void Vec_Free (void **pvec); //============================================================================ -extern qboolean host_bigendian; +extern bool host_bigendian; extern short (*BigShort) (short l); extern short (*LittleShort) (short l); @@ -176,7 +159,7 @@ void MSG_WriteAngle (sizebuf_t *sb, float f, unsigned int flags); void MSG_WriteAngle16 (sizebuf_t *sb, float f, unsigned int flags); //johnfitz extern int msg_readcount; -extern qboolean msg_badread; // set if a read goes beyond end of message +extern bool msg_badread; // set if a read goes beyond end of message void MSG_BeginReading (void); int MSG_ReadChar (void); @@ -192,18 +175,6 @@ float MSG_ReadAngle16 (unsigned int flags); //johnfitz //============================================================================ -void Q_memset (void *dest, int fill, size_t count); -void Q_memcpy (void *dest, const void *src, size_t count); -int Q_memcmp (const void *m1, const void *m2, size_t count); -void Q_strcpy (char *dest, const char *src); -void Q_strncpy (char *dest, const char *src, int count); -int Q_strlen (const char *str); -char *Q_strrchr (const char *s, char c); -void Q_strcat (char *dest, const char *src); -int Q_strcmp (const char *s1, const char *s2); -int Q_strncmp (const char *s1, const char *s2, int count); -int Q_atoi (const char *str); -float Q_atof (const char *str); #include "strl_fn.hpp" @@ -225,10 +196,14 @@ extern int q_vsnprintf(char *str, size_t size, const char *format, va_list args) //============================================================================ -extern qboolean com_eof; +extern bool com_eof; namespace common { + void init(); + + std::optional check_param(std::string_view parm); + std::optional parse_token(std::istringstream &ss); std::string parse_string_newline(std::istringstream &ss); @@ -247,9 +222,6 @@ extern int safemode; -nomouse, -nojoy, -nolan */ -int COM_CheckParm (const char *parm); - -void COM_Init (void); void COM_InitArgv (int argc, char **argv); void COM_InitFilesystem (void); @@ -274,7 +246,7 @@ void LOC_Init (void); void LOC_Shutdown (void); const char* LOC_GetRawString (const char *key); const char* LOC_GetString (const char *key); -qboolean LOC_HasPlaceholders (const char *str); +bool LOC_HasPlaceholders (const char *str); size_t LOC_Format (const char *format, const char* (*getarg_fn)(int idx, void* userdata), void* userdata, char* out, size_t len); //============================================================================ @@ -317,7 +289,7 @@ extern int file_from_pak; // global indicating that file came from a pak void COM_WriteFile (const char *filename, const void *data, int len); int COM_OpenFile (const char *filename, int *handle, unsigned int *path_id); int COM_FOpenFile (const char *filename, FILE **file, unsigned int *path_id); -qboolean COM_FileExists (const char *filename, unsigned int *path_id); +bool COM_FileExists (const char *filename, unsigned int *path_id); void COM_CloseFile (int h); // these procedures open a file using COM_FindFile and loads it into a proper @@ -359,7 +331,7 @@ byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out); typedef struct _fshandle_t { FILE *file; - qboolean pak; /* is the file read from a pak */ + bool pak; /* is the file read from a pak */ long start; /* file or data start position */ long length; /* file or data size */ long pos; /* current position relative to start */ @@ -378,8 +350,8 @@ long FS_filelength (fshandle_t *fh); extern convar registered; -extern qboolean standard_quake, rogue, hipnotic; -extern qboolean fitzmode; +extern bool standard_quake, rogue, hipnotic; +extern bool fitzmode; /* if true, run in fitzquake mode disabling custom quakespasm hacks */ #endif /* _Q_COMMON_H */ diff --git a/Quake/console.cpp b/Quake/console.cpp index d795591..5946c66 100644 --- a/Quake/console.cpp +++ b/Quake/console.cpp @@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // console.c +#include #include #include #include @@ -33,37 +34,37 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif #include "quakedef.hpp" -int con_linewidth; +int con_linewidth; -float con_cursorspeed = 4; +float con_cursorspeed = 4; #define CON_TEXTSIZE (1024 * 1024) //ericw -- was 65536. johnfitz -- new default size #define CON_MINSIZE 16384 //johnfitz -- old default, now the minimum size -int con_buffersize; //johnfitz -- user can now override default +int con_buffersize; //johnfitz -- user can now override default -qboolean con_forcedup; // because no entities to refresh +bool con_forcedup; // because no entities to refresh -int con_totallines; // total lines in console scrollback -int con_backscroll; // lines up from bottom to display -int con_current; // where next message will be printed -int con_x; // offset in current line for next print -char *con_text = NULL; +int con_totallines; // total lines in console scrollback +int con_backscroll; // lines up from bottom to display +int con_current; // where next message will be printed +int con_x; // offset in current line for next print +char *con_text = NULL; -convar con_notifytime{"con_notifytime","3"}; //seconds -convar con_logcenterprint{"con_logcenterprint", "1"}; //johnfitz +convar con_notifytime{"con_notifytime", "3"}; //seconds +convar con_logcenterprint{"con_logcenterprint", "1"}; //johnfitz -char con_lastcenterstring[1024]; //johnfitz +char con_lastcenterstring[1024]; //johnfitz #define NUM_CON_TIMES 4 -float con_times[NUM_CON_TIMES]; // realtime time the line was generated - // for transparent notify lines +float con_times[NUM_CON_TIMES]; // realtime time the line was generated +// for transparent notify lines -int con_vislines; +int con_vislines; -qboolean con_debuglog = false; +bool con_debuglog = false; -qboolean con_initialized; +bool con_initialized; /* @@ -73,28 +74,25 @@ Con_Quakebar -- johnfitz -- returns a bar of the desired length, but never wider includes a newline, unless len >= con_linewidth. ================ */ -const char *Con_Quakebar (int len) -{ - static char bar[42]; - int i; +const char *Con_Quakebar(int len) { + static char bar[42]; + int i; - len = std::min(len, (int)sizeof(bar) - 2); - len = std::min(len, con_linewidth); + len = std::min(len, (int) sizeof(bar) - 2); + len = std::min(len, con_linewidth); - bar[0] = '\35'; - for (i = 1; i < len - 1; i++) - bar[i] = '\36'; - bar[len-1] = '\37'; + bar[0] = '\35'; + for (i = 1; i < len - 1; i++) + bar[i] = '\36'; + bar[len - 1] = '\37'; - if (len < con_linewidth) - { - bar[len] = '\n'; - bar[len+1] = 0; - } - else - bar[len] = 0; + if (len < con_linewidth) { + bar[len] = '\n'; + bar[len + 1] = 0; + } else + bar[len] = 0; - return bar; + return bar; } /* @@ -104,33 +102,26 @@ Con_ToggleConsole_f */ extern int history_line; //johnfitz -void Con_ToggleConsole_f (void) -{ - if (key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/) - { - key_lines[edit_line][1] = 0; // clear any typing - key_linepos = 1; - con_backscroll = 0; //johnfitz -- toggleconsole should return you to the bottom of the scrollback - history_line = edit_line; //johnfitz -- it should also return you to the bottom of the command history +void Con_ToggleConsole_f(void) { + if (key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/) { + key_lines[edit_line][1] = 0; // clear any typing + key_linepos = 1; + con_backscroll = 0; //johnfitz -- toggleconsole should return you to the bottom of the scrollback + history_line = edit_line; //johnfitz -- it should also return you to the bottom of the command history - if (cls.state == ca_connected) - { - IN_Activate(); - key_dest = key_game; - } - else - { - M_Menu_Main_f (); - } - } - else - { - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_console; - } + if (cls.state == ca_connected) { + IN_Activate(); + key_dest = key_game; + } else { + M_Menu_Main_f(); + } + } else { + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_console; + } - SCR_EndLoadingPlaque (); - memset (con_times, 0, sizeof(con_times)); + SCR_EndLoadingPlaque(); + memset(con_times, 0, sizeof(con_times)); } /* @@ -138,11 +129,10 @@ void Con_ToggleConsole_f (void) Con_Clear_f ================ */ -static void Con_Clear_f (void) -{ - if (con_text) - Q_memset (con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE - con_backscroll = 0; //johnfitz -- if console is empty, being scrolled up is confusing +static void Con_Clear_f(void) { + if (con_text) + std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + con_backscroll = 0; //johnfitz -- if console is empty, being scrolled up is confusing } /* @@ -150,55 +140,50 @@ static void Con_Clear_f (void) Con_Dump_f -- johnfitz -- adapted from quake2 source ================ */ -static void Con_Dump_f (void) -{ - int l, x; - const char *line; - FILE *f; - char buffer[1024]; - char name[MAX_OSPATH]; +static void Con_Dump_f(void) { + int l, x; + const char *line; + FILE *f; + char buffer[1024]; + char name[MAX_OSPATH]; - q_snprintf (name, sizeof(name), "%s/condump.txt", com_gamedir); - COM_CreatePath (name); - f = fopen (name, "w"); - if (!f) - { - Con_Printf ("ERROR: couldn't open file %s.\n", name); - return; - } + q_snprintf(name, sizeof(name), "%s/condump.txt", com_gamedir); + COM_CreatePath(name); + f = fopen(name, "w"); + if (!f) { + Con_Printf("ERROR: couldn't open file %s.\n", name); + return; + } - // skip initial empty lines - for (l = con_current - con_totallines + 1; l <= con_current; l++) - { - line = con_text + (l % con_totallines)*con_linewidth; - for (x = 0; x < con_linewidth; x++) - if (line[x] != ' ') - break; - if (x != con_linewidth) - break; - } + // skip initial empty lines + for (l = con_current - con_totallines + 1; l <= con_current; l++) { + line = con_text + (l % con_totallines) * con_linewidth; + for (x = 0; x < con_linewidth; x++) + if (line[x] != ' ') + break; + if (x != con_linewidth) + break; + } - // write the remaining lines - buffer[con_linewidth] = 0; - for ( ; l <= con_current; l++) - { - line = con_text + (l%con_totallines)*con_linewidth; - strncpy (buffer, line, con_linewidth); - for (x = con_linewidth - 1; x >= 0; x--) - { - if (buffer[x] == ' ') - buffer[x] = 0; - else - break; - } - for (x = 0; buffer[x]; x++) - buffer[x] &= 0x7f; + // write the remaining lines + buffer[con_linewidth] = 0; + for (; l <= con_current; l++) { + line = con_text + (l % con_totallines) * con_linewidth; + strncpy(buffer, line, con_linewidth); + for (x = con_linewidth - 1; x >= 0; x--) { + if (buffer[x] == ' ') + buffer[x] = 0; + else + break; + } + for (x = 0; buffer[x]; x++) + buffer[x] &= 0x7f; - fprintf (f, "%s\n", buffer); - } + fprintf(f, "%s\n", buffer); + } - fclose (f); - Con_Printf ("Dumped console text to %s.\n", name); + fclose(f); + Con_Printf("Dumped console text to %s.\n", name); } /* @@ -206,12 +191,11 @@ static void Con_Dump_f (void) Con_ClearNotify ================ */ -void Con_ClearNotify (void) -{ - int i; +void Con_ClearNotify(void) { + int i; - for (i = 0; i < NUM_CON_TIMES; i++) - con_times[i] = 0; + for (i = 0; i < NUM_CON_TIMES; i++) + con_times[i] = 0; } @@ -220,12 +204,11 @@ void Con_ClearNotify (void) Con_MessageMode_f ================ */ -static void Con_MessageMode_f (void) -{ - if (cls.state != ca_connected || cls.demoplayback) - return; - chat_team = false; - key_dest = key_message; +static void Con_MessageMode_f(void) { + if (cls.state != ca_connected || cls.demoplayback) + return; + chat_team = false; + key_dest = key_message; } /* @@ -233,12 +216,11 @@ static void Con_MessageMode_f (void) Con_MessageMode2_f ================ */ -static void Con_MessageMode2_f (void) -{ - if (cls.state != ca_connected || cls.demoplayback) - return; - chat_team = true; - key_dest = key_message; +static void Con_MessageMode2_f(void) { + if (cls.state != ca_connected || cls.demoplayback) + return; + chat_team = true; + key_dest = key_message; } @@ -249,52 +231,49 @@ Con_CheckResize If the line width has changed, reformat the buffer. ================ */ -void Con_CheckResize (void) -{ - int i, j, width, oldwidth, oldtotallines, numlines, numchars; - char *tbuf; //johnfitz -- tbuf no longer a static array - int mark; //johnfitz +void Con_CheckResize(void) { + int i, j, width, oldwidth, oldtotallines, numlines, numchars; + char *tbuf; //johnfitz -- tbuf no longer a static array + int mark; //johnfitz - width = (vid.conwidth >> 3) - 2; //johnfitz -- use vid.conwidth instead of vid.width + width = (vid.conwidth >> 3) - 2; //johnfitz -- use vid.conwidth instead of vid.width - if (width == con_linewidth) - return; + if (width == con_linewidth) + return; - oldwidth = con_linewidth; - con_linewidth = width; - oldtotallines = con_totallines; - con_totallines = con_buffersize / con_linewidth; //johnfitz -- con_buffersize replaces CON_TEXTSIZE - numlines = oldtotallines; + oldwidth = con_linewidth; + con_linewidth = width; + oldtotallines = con_totallines; + con_totallines = con_buffersize / con_linewidth; //johnfitz -- con_buffersize replaces CON_TEXTSIZE + numlines = oldtotallines; - if (con_totallines < numlines) - numlines = con_totallines; + if (con_totallines < numlines) + numlines = con_totallines; - numchars = oldwidth; + numchars = oldwidth; - if (con_linewidth < numchars) - numchars = con_linewidth; + if (con_linewidth < numchars) + numchars = con_linewidth; - mark = Hunk_LowMark (); //johnfitz - tbuf = (char *) Hunk_Alloc (con_buffersize); //johnfitz + mark = Hunk_LowMark(); //johnfitz + tbuf = (char *) Hunk_Alloc(con_buffersize); //johnfitz - Q_memcpy (tbuf, con_text, con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE - Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE + std::memcpy(tbuf, con_text, con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE - for (i = 0; i < numlines; i++) - { - for (j = 0; j < numchars; j++) - { - con_text[(con_totallines - 1 - i) * con_linewidth + j] = - tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; - } - } + for (i = 0; i < numlines; i++) { + for (j = 0; j < numchars; j++) { + con_text[(con_totallines - 1 - i) * con_linewidth + j] = + tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; + } + } - Hunk_FreeToLowMark (mark); //johnfitz + Hunk_FreeToLowMark(mark); //johnfitz - Con_ClearNotify (); + Con_ClearNotify(); - con_backscroll = 0; - con_current = con_totallines - 1; + con_backscroll = 0; + con_current = con_totallines - 1; } @@ -303,43 +282,39 @@ void Con_CheckResize (void) Con_Init ================ */ -void Con_Init (void) -{ - int i; +void Con_Init(void) { + //johnfitz -- user settable console buffer size + auto i = common::check_param("-consize"); + if (i.has_value() && i.value() < com_argc - 1) { + con_buffersize = std::atoi(com_argv[i.value() + 1]) * 1024; + if (con_buffersize < CON_MINSIZE) + con_buffersize = CON_MINSIZE; + } else + con_buffersize = CON_TEXTSIZE; + //johnfitz - //johnfitz -- user settable console buffer size - i = COM_CheckParm("-consize"); - if (i && i < com_argc-1) { - con_buffersize = Q_atoi(com_argv[i+1])*1024; - if (con_buffersize < CON_MINSIZE) - con_buffersize = CON_MINSIZE; - } - else - con_buffersize = CON_TEXTSIZE; - //johnfitz + con_text = (char *) Hunk_AllocName(con_buffersize, "context"); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + std::memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + con_linewidth = -1; - con_text = (char *) Hunk_AllocName (con_buffersize, "context");//johnfitz -- con_buffersize replaces CON_TEXTSIZE - Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE - con_linewidth = -1; + //johnfitz -- no need to run Con_CheckResize here + con_linewidth = 38; + con_totallines = con_buffersize / con_linewidth; //johnfitz -- con_buffersize replaces CON_TEXTSIZE + con_backscroll = 0; + con_current = con_totallines - 1; + //johnfitz - //johnfitz -- no need to run Con_CheckResize here - con_linewidth = 38; - con_totallines = con_buffersize / con_linewidth;//johnfitz -- con_buffersize replaces CON_TEXTSIZE - con_backscroll = 0; - con_current = con_totallines - 1; - //johnfitz + Con_Printf("Console initialized.\n"); - Con_Printf ("Console initialized.\n"); + con_notifytime.inscribe(); + con_logcenterprint.inscribe(); //johnfitz - con_notifytime.inscribe(); - con_logcenterprint.inscribe(); //johnfitz - - command::add ("toggleconsole", Con_ToggleConsole_f); - command::add ("messagemode", Con_MessageMode_f); - command::add ("messagemode2", Con_MessageMode2_f); - command::add ("clear", Con_Clear_f); - command::add ("condump", Con_Dump_f); //johnfitz - con_initialized = true; + command::add("toggleconsole", Con_ToggleConsole_f); + command::add("messagemode", Con_MessageMode_f); + command::add("messagemode2", Con_MessageMode2_f); + command::add("clear", Con_Clear_f); + command::add("condump", Con_Dump_f); //johnfitz + con_initialized = true; } @@ -348,18 +323,17 @@ void Con_Init (void) Con_Linefeed =============== */ -static void Con_Linefeed (void) -{ - //johnfitz -- improved scrolling - if (con_backscroll) - con_backscroll++; - if (con_backscroll > con_totallines - (glheight>>3) - 1) - con_backscroll = con_totallines - (glheight>>3) - 1; - //johnfitz +static void Con_Linefeed(void) { + //johnfitz -- improved scrolling + if (con_backscroll) + con_backscroll++; + if (con_backscroll > con_totallines - (glheight >> 3) - 1) + con_backscroll = con_totallines - (glheight >> 3) - 1; + //johnfitz - con_x = 0; - con_current++; - Q_memset (&con_text[(con_current%con_totallines)*con_linewidth], ' ', con_linewidth); + con_x = 0; + con_current++; + std::memset(&con_text[(con_current % con_totallines) * con_linewidth], ' ', con_linewidth); } /* @@ -371,113 +345,99 @@ All console printing must go through this in order to be logged to disk If no console is visible, the notify window will pop up. ================ */ -static void Con_Print (const char *txt) -{ - int y; - int c, l; - static int cr; - int mask; - qboolean boundary; +static void Con_Print(const char *txt) { + int y; + int c, l; + static int cr; + int mask; + bool boundary; - //con_backscroll = 0; //johnfitz -- better console scrolling + //con_backscroll = 0; //johnfitz -- better console scrolling - if (txt[0] == 1) - { - mask = 128; // go to colored text - S_LocalSound ("misc/talk.wav"); // play talk wav - txt++; - } - else if (txt[0] == 2) - { - mask = 128; // go to colored text - txt++; - } - else - mask = 0; + if (txt[0] == 1) { + mask = 128; // go to colored text + S_LocalSound("misc/talk.wav"); // play talk wav + txt++; + } else if (txt[0] == 2) { + mask = 128; // go to colored text + txt++; + } else + mask = 0; - boundary = true; + boundary = true; - while ( (c = *txt) ) - { - if (c <= ' ') - { - boundary = true; - } - else if (boundary) - { - // count word length - for (l = 0; l < con_linewidth; l++) - if (txt[l] <= ' ') - break; + while ((c = *txt)) { + if (c <= ' ') { + boundary = true; + } else if (boundary) { + // count word length + for (l = 0; l < con_linewidth; l++) + if (txt[l] <= ' ') + break; - // word wrap - if (l != con_linewidth && (con_x + l > con_linewidth)) - con_x = 0; + // word wrap + if (l != con_linewidth && (con_x + l > con_linewidth)) + con_x = 0; - boundary = false; - } + boundary = false; + } - txt++; + txt++; - if (cr) - { - con_current--; - cr = false; - } + if (cr) { + con_current--; + cr = false; + } - if (!con_x) - { - Con_Linefeed (); - // mark time for transparent overlay - if (con_current >= 0) - con_times[con_current % NUM_CON_TIMES] = realtime; - } + if (!con_x) { + Con_Linefeed(); + // mark time for transparent overlay + if (con_current >= 0) + con_times[con_current % NUM_CON_TIMES] = realtime; + } - switch (c) - { - case '\n': - con_x = 0; - break; + switch (c) { + case '\n': + con_x = 0; + break; - case '\r': - con_x = 0; - cr = 1; - break; + case '\r': + con_x = 0; + cr = 1; + break; - default: // display character and advance - y = con_current % con_totallines; - con_text[y*con_linewidth+con_x] = c | mask; - con_x++; - if (con_x >= con_linewidth) - con_x = 0; - break; - } - } + default: // display character and advance + y = con_current % con_totallines; + con_text[y * con_linewidth + con_x] = c | mask; + con_x++; + if (con_x >= con_linewidth) + con_x = 0; + break; + } + } } // borrowed from uhexen2 by S.A. for new procs, LOG_Init, LOG_Close -static char logfilename[MAX_OSPATH]; // current logfile name -static int log_fd = -1; // log file descriptor +static char logfilename[MAX_OSPATH]; // current logfile name +static int log_fd = -1; // log file descriptor /* ================ Con_DebugLog ================ */ -void Con_DebugLog(const char *msg) -{ - if (log_fd == -1) - return; +void Con_DebugLog(const char *msg) { + if (log_fd == -1) + return; - if (write(log_fd, msg, strlen(msg)) < 0) - { - close (log_fd); - log_fd = -1; - con_debuglog = false; - fprintf (stderr, "Error writing to log file\n"); - } + if (write(log_fd, msg, strlen(msg)) < 0) { + close(log_fd); + log_fd = -1; + con_debuglog = false; + fprintf(stderr, "Error writing to log file\n"); + } } @@ -489,69 +449,66 @@ Handles cursor positioning, line wrapping, etc ================ */ #define MAXPRINTMSG 4096 -void Con_Printf (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; - static qboolean inupdate; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); +void Con_Printf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; + static bool inupdate; -// also echo to debugging console - Sys_Printf ("%s", msg); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); -// log all messages to file - if (con_debuglog) - Con_DebugLog(msg); + // also echo to debugging console + Sys_Printf("%s", msg); - if (!con_initialized) - return; + // log all messages to file + if (con_debuglog) + Con_DebugLog(msg); - if (cls.state == ca_dedicated) - return; // no graphics mode + if (!con_initialized) + return; -// write it to the scrollable buffer - Con_Print (msg); + if (cls.state == ca_dedicated) + return; // no graphics mode -// update the screen if the console is displayed - if (cls.signon != SIGNONS && !scr_disabled_for_loading ) - { - // protect against infinite loop if something in SCR_UpdateScreen calls - // Con_Printd - if (!inupdate) - { - inupdate = true; - SCR_UpdateScreen (); - inupdate = false; - } - } + // write it to the scrollable buffer + Con_Print(msg); + + // update the screen if the console is displayed + if (cls.signon != SIGNONS && !scr_disabled_for_loading) { + // protect against infinite loop if something in SCR_UpdateScreen calls + // Con_Printd + if (!inupdate) { + inupdate = true; + SCR_UpdateScreen(); + inupdate = false; + } + } } /* ================ Con_DWarning -- ericw - + same as Con_Warning, but only prints if "developer" cvar is set. use for "exceeds standard limit of" messages, which are only relevant for developers targetting vanilla engines ================ */ -void Con_DWarning (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; +void Con_DWarning(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - if (!developer.value) - return; // don't confuse non-developers with techie stuff... + if (!developer.value) + return; // don't confuse non-developers with techie stuff... - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("\x02Warning: "); - Con_Printf ("%s", msg); + Con_SafePrintf("\x02Warning: "); + Con_Printf("%s", msg); } /* @@ -559,17 +516,16 @@ void Con_DWarning (const char *fmt, ...) Con_Warning -- johnfitz -- prints a warning to the console ================ */ -void Con_Warning (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; +void Con_Warning(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + std::vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("\x02Warning: "); - Con_Printf ("%s", msg); + Con_SafePrintf("\x02Warning: "); + Con_Printf("%s", msg); } /* @@ -579,19 +535,18 @@ Con_DPrintf A Con_Printf that only shows up if the "developer" cvar is set ================ */ -void Con_DPrintf (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; +void Con_DPrintf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - if (!developer.value) - return; // don't confuse non-developers with techie stuff... + if (!developer.value) + return; // don't confuse non-developers with techie stuff... - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("%s", msg); //johnfitz -- was Con_Printf + Con_SafePrintf("%s", msg); //johnfitz -- was Con_Printf } /* @@ -601,18 +556,16 @@ Con_DPrintf2 -- johnfitz -- only prints if "developer" >= 2 currently not used ================ */ -void Con_DPrintf2 (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; +void Con_DPrintf2(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - if (developer.value >= 2) - { - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); - Con_Printf ("%s", msg); - } + if (developer.value >= 2) { + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); + Con_Printf("%s", msg); + } } @@ -623,20 +576,19 @@ Con_SafePrintf Okay to call even when the screen can't be updated ================== */ -void Con_SafePrintf (const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; - int temp; +void Con_SafePrintf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; + int temp; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - temp = scr_disabled_for_loading; - scr_disabled_for_loading = true; - Con_Printf ("%s", msg); - scr_disabled_for_loading = temp; + temp = scr_disabled_for_loading; + scr_disabled_for_loading = true; + Con_Printf("%s", msg); + scr_disabled_for_loading = temp; } /* @@ -644,41 +596,38 @@ void Con_SafePrintf (const char *fmt, ...) Con_CenterPrintf -- johnfitz -- pad each line with spaces to make it appear centered ================ */ -void Con_CenterPrintf (int linewidth, const char *fmt, ...) FUNC_PRINTF(2,3); -void Con_CenterPrintf (int linewidth, const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; //the original message - char line[MAXPRINTMSG]; //one line from the message - char spaces[21]; //buffer for spaces - char *src, *dst; - int len, s; +void Con_CenterPrintf(int linewidth, const char *fmt, ...) FUNC_PRINTF(2, 3); - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); +void Con_CenterPrintf(int linewidth, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; //the original message + char line[MAXPRINTMSG]; //one line from the message + char spaces[21]; //buffer for spaces + char *src, *dst; + int len, s; - linewidth = std::min(linewidth, con_linewidth); - for (src = msg; *src; ) - { - dst = line; - while (*src && *src != '\n') - *dst++ = *src++; - *dst = 0; - if (*src == '\n') - src++; + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - len = strlen(line); - if (len < linewidth) - { - s = (linewidth-len)/2; - memset (spaces, ' ', s); - spaces[s] = 0; - Con_Printf ("%s%s\n", spaces, line); - } - else - Con_Printf ("%s\n", line); - } + linewidth = std::min(linewidth, con_linewidth); + for (src = msg; *src;) { + dst = line; + while (*src && *src != '\n') + *dst++ = *src++; + *dst = 0; + if (*src == '\n') + src++; + + len = strlen(line); + if (len < linewidth) { + s = (linewidth - len) / 2; + memset(spaces, ' ', s); + spaces[s] = 0; + Con_Printf("%s%s\n", spaces, line); + } else + Con_Printf("%s\n", line); + } } /* @@ -686,23 +635,21 @@ void Con_CenterPrintf (int linewidth, const char *fmt, ...) Con_LogCenterPrint -- johnfitz -- echo centerprint message to the console ================== */ -void Con_LogCenterPrint (const char *str) -{ - if (!strcmp(str, con_lastcenterstring)) - return; //ignore duplicates +void Con_LogCenterPrint(const char *str) { + if (!strcmp(str, con_lastcenterstring)) + return; //ignore duplicates - if (cl.gametype == GAME_DEATHMATCH && con_logcenterprint.value != 2) - return; //don't log in deathmatch + if (cl.gametype == GAME_DEATHMATCH && con_logcenterprint.value != 2) + return; //don't log in deathmatch - strcpy(con_lastcenterstring, str); + strcpy(con_lastcenterstring, str); - if (con_logcenterprint.value) - { - Con_Printf ("%s", Con_Quakebar(40)); - Con_CenterPrintf (40, "%s\n", str); - Con_Printf ("%s", Con_Quakebar(40)); - Con_ClearNotify (); - } + if (con_logcenterprint.value) { + Con_Printf("%s", Con_Quakebar(40)); + Con_CenterPrintf(40, "%s\n", str); + Con_Printf("%s", Con_Quakebar(40)); + Con_ClearNotify(); + } } /* @@ -716,17 +663,18 @@ void Con_LogCenterPrint (const char *str) //johnfitz -- tab completion stuff //unique defs char key_tabpartial[MAXCMDLINE]; -typedef struct tab_s -{ - const char *name; - const char *type; - struct tab_s *next; - struct tab_s *prev; + +typedef struct tab_s { + const char *name; + const char *type; + struct tab_s *next; + struct tab_s *prev; } tab_t; -tab_t *tablist; + +tab_t *tablist; //defs from elsewhere -extern qboolean keydown[256]; +extern bool keydown[256]; #define MAX_ALIAS_NAME 32 /* @@ -739,141 +687,124 @@ tablist is a doubly-linked loop, alphabetized by name // bash_partial is the string that can be expanded, // aka Linux Bash shell. -- S.A. -static char bash_partial[80]; -static qboolean bash_singlematch; +static char bash_partial[80]; +static bool bash_singlematch; -void AddToTabList (const char *name, const char *type) -{ - tab_t *t,*insert; - char *i_bash; - const char *i_name; +void AddToTabList(const char *name, const char *type) { + tab_t *t, *insert; + char *i_bash; + const char *i_name; - if (!*bash_partial) - { - strncpy (bash_partial, name, 79); - bash_partial[79] = '\0'; - } - else - { - bash_singlematch = 0; - // find max common between bash_partial and name - i_bash = bash_partial; - i_name = name; - while (*i_bash && (*i_bash == *i_name)) - { - i_bash++; - i_name++; - } - *i_bash = 0; - } + if (!*bash_partial) { + strncpy(bash_partial, name, 79); + bash_partial[79] = '\0'; + } else { + bash_singlematch = 0; + // find max common between bash_partial and name + i_bash = bash_partial; + i_name = name; + while (*i_bash && (*i_bash == *i_name)) { + i_bash++; + i_name++; + } + *i_bash = 0; + } - t = (tab_t *) Hunk_Alloc(sizeof(tab_t)); - t->name = name; - t->type = type; + t = (tab_t *) Hunk_Alloc(sizeof(tab_t)); + t->name = name; + t->type = type; - if (!tablist) //create list - { - tablist = t; - t->next = t; - t->prev = t; - } - else if (strcmp(name, tablist->name) < 0) //insert at front - { - t->next = tablist; - t->prev = tablist->prev; - t->next->prev = t; - t->prev->next = t; - tablist = t; - } - else //insert later - { - insert = tablist; - do - { - if (strcmp(name, insert->name) < 0) - break; - insert = insert->next; - } while (insert != tablist); + if (!tablist) //create list + { + tablist = t; + t->next = t; + t->prev = t; + } else if (strcmp(name, tablist->name) < 0) //insert at front + { + t->next = tablist; + t->prev = tablist->prev; + t->next->prev = t; + t->prev->next = t; + tablist = t; + } else //insert later + { + insert = tablist; + do { + if (strcmp(name, insert->name) < 0) + break; + insert = insert->next; + } while (insert != tablist); - t->next = insert; - t->prev = insert->prev; - t->next->prev = t; - t->prev->next = t; - } + t->next = insert; + t->prev = insert->prev; + t->next->prev = t; + t->prev->next = t; + } } -typedef struct arg_completion_type_s -{ - const char *command; - filelist_item_t **filelist; +typedef struct arg_completion_type_s { + const char *command; + filelist_item_t **filelist; } arg_completion_type_t; static const arg_completion_type_t arg_completion_types[] = { - { "map ", &extralevels }, - { "changelevel ", &extralevels }, - { "game ", &modlist }, - { "record ", &demolist }, - { "playdemo ", &demolist }, - { "timedemo ", &demolist } + {"map ", &extralevels}, + {"changelevel ", &extralevels}, + {"game ", &modlist}, + {"record ", &demolist}, + {"playdemo ", &demolist}, + {"timedemo ", &demolist} }; -static const int num_arg_completion_types = Q_COUNTOF(arg_completion_types); +static constexpr int num_arg_completion_types = std::size(arg_completion_types); /* ============ FindCompletion -- stevenaaus ============ */ -const char *FindCompletion (const char *partial, filelist_item_t *filelist, int *nummatches_out) -{ - static char matched[40]; - char *i_matched, *i_name; - filelist_item_t *file; - int init, match, plen; +const char *FindCompletion(const char *partial, filelist_item_t *filelist, int *nummatches_out) { + static char matched[40]; + char *i_matched, *i_name; + filelist_item_t *file; + int init, match, plen; - memset(matched, 0, sizeof(matched)); - plen = strlen(partial); - match = 0; + memset(matched, 0, sizeof(matched)); + plen = strlen(partial); + match = 0; - for (file = filelist, init = 0; file; file = file->next) - { - if (!strncmp(file->name, partial, plen)) - { - if (init == 0) - { - init = 1; - strncpy (matched, file->name, sizeof(matched)-1); - matched[sizeof(matched)-1] = '\0'; - } - else - { // find max common - i_matched = matched; - i_name = file->name; - while (*i_matched && (*i_matched == *i_name)) - { - i_matched++; - i_name++; - } - *i_matched = 0; - } - match++; - } - } + for (file = filelist, init = 0; file; file = file->next) { + if (!strncmp(file->name, partial, plen)) { + if (init == 0) { + init = 1; + strncpy(matched, file->name, sizeof(matched) - 1); + matched[sizeof(matched) - 1] = '\0'; + } else { + // find max common + i_matched = matched; + i_name = file->name; + while (*i_matched && (*i_matched == *i_name)) { + i_matched++; + i_name++; + } + *i_matched = 0; + } + match++; + } + } - *nummatches_out = match; + *nummatches_out = match; - if (match > 1) - { - for (file = filelist; file; file = file->next) - { - if (!strncmp(file->name, partial, plen)) - Con_SafePrintf (" %s\n", file->name); - } - Con_SafePrintf ("\n"); - } + if (match > 1) { + for (file = filelist; file; file = file->next) { + if (!strncmp(file->name, partial, plen)) + Con_SafePrintf(" %s\n", file->name); + } + Con_SafePrintf("\n"); + } - return matched; + return matched; } /* @@ -881,27 +812,26 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int BuildTabList -- johnfitz ============ */ -void BuildTabList (const char *partial) -{ - int len; +void BuildTabList(const char *partial) { + int len; - tablist = NULL; - len = strlen(partial); + tablist = NULL; + len = strlen(partial); - bash_partial[0] = 0; - bash_singlematch = 1; + bash_partial[0] = 0; + bash_singlematch = 1; - for (const auto cvar : convar::get_variables()) - if (!Q_strncmp (partial, cvar->name.c_str(), len)) - AddToTabList (cvar->name.c_str(), "cvar"); + for (const auto cvar: convar::get_variables()) + if (!std::strncmp(partial, cvar->name.c_str(), len)) + AddToTabList(cvar->name.c_str(), "cvar"); - for (const auto &ccmd : command::get_commands()) - if (!Q_strncmp (partial,ccmd.name.c_str(), len)) - AddToTabList (ccmd.name.c_str(), "command"); + for (const auto &ccmd: command::get_commands()) + if (!std::strncmp(partial, ccmd.name.c_str(), len)) + AddToTabList(ccmd.name.c_str(), "command"); - for (const auto &alias : command::get_aliases()) - if (!Q_strncmp (partial, alias.name.c_str(), len)) - AddToTabList (alias.name.c_str(), "alias"); + for (const auto &alias: command::get_aliases()) + if (!std::strncmp(partial, alias.name.c_str(), len)) + AddToTabList(alias.name.c_str(), "alias"); } /* @@ -909,144 +839,133 @@ void BuildTabList (const char *partial) Con_TabComplete -- johnfitz ============ */ -void Con_TabComplete (void) -{ - char partial[MAXCMDLINE]; - const char *match; - static char *c; - tab_t *t; - int mark, i, j; +void Con_TabComplete(void) { + char partial[MAXCMDLINE]; + const char *match; + static char *c; + tab_t *t; + int mark, i, j; -// if editline is empty, return - if (key_lines[edit_line][1] == 0) - return; + // if editline is empty, return + if (key_lines[edit_line][1] == 0) + return; -// get partial string (space -> cursor) - if (!key_tabpartial[0]) //first time through, find new insert point. (Otherwise, use previous.) - { - //work back from cursor until you find a space, quote, semicolon, or prompt - c = key_lines[edit_line] + key_linepos - 1; //start one space left of cursor - while (*c!=' ' && *c!='\"' && *c!=';' && c!=key_lines[edit_line]) - c--; - c++; //start 1 char after the separator we just found - } - for (i = 0; c + i < key_lines[edit_line] + key_linepos; i++) - partial[i] = c[i]; - partial[i] = 0; + // get partial string (space -> cursor) + if (!key_tabpartial[0]) //first time through, find new insert point. (Otherwise, use previous.) + { + //work back from cursor until you find a space, quote, semicolon, or prompt + c = key_lines[edit_line] + key_linepos - 1; //start one space left of cursor + while (*c != ' ' && *c != '\"' && *c != ';' && c != key_lines[edit_line]) + c--; + c++; //start 1 char after the separator we just found + } + for (i = 0; c + i < key_lines[edit_line] + key_linepos; i++) + partial[i] = c[i]; + partial[i] = 0; -// Map autocomplete function -- S.A -// Since we don't have argument completion, this hack will do for now... - for (j=0; j= MAXCMDLINE) - key_linepos = MAXCMDLINE - 1; - // if only one match, append a space - if (key_linepos < MAXCMDLINE - 1 && - key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) - { - key_lines[edit_line][key_linepos] = ' '; - key_linepos++; - key_lines[edit_line][key_linepos] = 0; - } - c = key_lines[edit_line] + key_linepos; - return; - } - } + // Map autocomplete function -- S.A + // Since we don't have argument completion, this hack will do for now... + for (j = 0; j < num_arg_completion_types; j++) { + // arg_completion contains a command we can complete the arguments + // for (like "map ") and a list of all the maps. + arg_completion_type_t arg_completion = arg_completion_types[j]; + const char *command_name = arg_completion.command; -//if partial is empty, return - if (partial[0] == 0) - return; + if (!strncmp(key_lines[edit_line] + 1, command_name, strlen(command_name))) { + int nummatches = 0; + const char *matched_map = FindCompletion(partial, *arg_completion.filelist, &nummatches); + if (!*matched_map) + return; + q_strlcpy(partial, matched_map, MAXCMDLINE); + *c = '\0'; + q_strlcat(key_lines[edit_line], partial, MAXCMDLINE); + key_linepos = c - key_lines[edit_line] + std::strlen(matched_map); //set new cursor position + if (key_linepos >= MAXCMDLINE) + key_linepos = MAXCMDLINE - 1; + // if only one match, append a space + if (key_linepos < MAXCMDLINE - 1 && + key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) { + key_lines[edit_line][key_linepos] = ' '; + key_linepos++; + key_lines[edit_line][key_linepos] = 0; + } + c = key_lines[edit_line] + key_linepos; + return; + } + } -//trim trailing space becuase it screws up string comparisons - if (i > 0 && partial[i-1] == ' ') - partial[i-1] = 0; + //if partial is empty, return + if (partial[0] == 0) + return; -// find a match - mark = Hunk_LowMark(); - if (!key_tabpartial[0]) //first time through - { - q_strlcpy (key_tabpartial, partial, MAXCMDLINE); - BuildTabList (key_tabpartial); + //trim trailing space becuase it screws up string comparisons + if (i > 0 && partial[i - 1] == ' ') + partial[i - 1] = 0; - if (!tablist) - return; + // find a match + mark = Hunk_LowMark(); + if (!key_tabpartial[0]) //first time through + { + q_strlcpy(key_tabpartial, partial, MAXCMDLINE); + BuildTabList(key_tabpartial); - // print list if length > 1 - if (tablist->next != tablist) - { - t = tablist; - Con_SafePrintf("\n"); - do - { - Con_SafePrintf(" %s (%s)\n", t->name, t->type); - t = t->next; - } while (t != tablist); - Con_SafePrintf("\n"); - } + if (!tablist) + return; - // match = tablist->name; - // First time, just show maximum matching chars -- S.A. - match = bash_partial; - } - else - { - BuildTabList (key_tabpartial); + // print list if length > 1 + if (tablist->next != tablist) { + t = tablist; + Con_SafePrintf("\n"); + do { + Con_SafePrintf(" %s (%s)\n", t->name, t->type); + t = t->next; + } while (t != tablist); + Con_SafePrintf("\n"); + } - if (!tablist) - return; + // match = tablist->name; + // First time, just show maximum matching chars -- S.A. + match = bash_partial; + } else { + BuildTabList(key_tabpartial); - //find current match -- can't save a pointer because the list will be rebuilt each time - t = tablist; - match = keydown[K_SHIFT] ? t->prev->name : t->name; - do - { - if (!Q_strcmp(t->name, partial)) - { - match = keydown[K_SHIFT] ? t->prev->name : t->next->name; - break; - } - t = t->next; - } while (t != tablist); - } - Hunk_FreeToLowMark(mark); //it's okay to free it here because match is a pointer to persistent data + if (!tablist) + return; -// insert new match into edit line - q_strlcpy (partial, match, MAXCMDLINE); //first copy match string - q_strlcat (partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor - *c = '\0'; //now copy all of this into edit line - q_strlcat (key_lines[edit_line], partial, MAXCMDLINE); - key_linepos = c - key_lines[edit_line] + Q_strlen(match); //set new cursor position - if (key_linepos >= MAXCMDLINE) - key_linepos = MAXCMDLINE - 1; + //find current match -- can't save a pointer because the list will be rebuilt each time + t = tablist; + match = keydown[K_SHIFT] ? t->prev->name : t->name; + do { + if (!std::strcmp(t->name, partial)) { + match = keydown[K_SHIFT] ? t->prev->name : t->next->name; + break; + } + t = t->next; + } while (t != tablist); + } + Hunk_FreeToLowMark(mark); //it's okay to free it here because match is a pointer to persistent data -// if cursor is at end of string, let's append a space to make life easier - if (key_linepos < MAXCMDLINE - 1 && - key_lines[edit_line][key_linepos] == 0 && bash_singlematch) - { - key_lines[edit_line][key_linepos] = ' '; - key_linepos++; - key_lines[edit_line][key_linepos] = 0; - // S.A.: the map argument completion (may be in combination with the bash-style - // display behavior changes, causes weirdness when completing the arguments for - // the changelevel command. the line below "fixes" it, although I'm not sure about - // the reason, yet, neither do I know any possible side effects of it: - c = key_lines[edit_line] + key_linepos; - } + // insert new match into edit line + q_strlcpy(partial, match, MAXCMDLINE); //first copy match string + q_strlcat(partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor + *c = '\0'; //now copy all of this into edit line + q_strlcat(key_lines[edit_line], partial, MAXCMDLINE); + key_linepos = c - key_lines[edit_line] + std::strlen(match); //set new cursor position + if (key_linepos >= MAXCMDLINE) + key_linepos = MAXCMDLINE - 1; + + // if cursor is at end of string, let's append a space to make life easier + if (key_linepos < MAXCMDLINE - 1 && + key_lines[edit_line][key_linepos] == 0 && bash_singlematch) { + key_lines[edit_line][key_linepos] = ' '; + key_linepos++; + key_lines[edit_line][key_linepos] = 0; + // S.A.: the map argument completion (may be in combination with the bash-style + // display behavior changes, causes weirdness when completing the arguments for + // the changelevel command. the line below "fixes" it, although I'm not sure about + // the reason, yet, neither do I know any possible side effects of it: + c = key_lines[edit_line] + key_linepos; + } } /* @@ -1064,69 +983,62 @@ Con_DrawNotify Draws the last few lines of output transparently over the game top ================ */ -void Con_DrawNotify (void) -{ - int i, x, v; - const char *text; - float time; +void Con_DrawNotify(void) { + int i, x, v; + const char *text; + float time; - GL_SetCanvas (CANVAS_CONSOLE); //johnfitz - v = vid.conheight; //johnfitz + GL_SetCanvas(CANVAS_CONSOLE); //johnfitz + v = vid.conheight; //johnfitz - for (i = con_current-NUM_CON_TIMES+1; i <= con_current; i++) - { - if (i < 0) - continue; - time = con_times[i % NUM_CON_TIMES]; - if (time == 0) - continue; - time = realtime - time; - if (time > con_notifytime.value) - continue; - text = con_text + (i % con_totallines)*con_linewidth; + for (i = con_current - NUM_CON_TIMES + 1; i <= con_current; i++) { + if (i < 0) + continue; + time = con_times[i % NUM_CON_TIMES]; + if (time == 0) + continue; + time = realtime - time; + if (time > con_notifytime.value) + continue; + text = con_text + (i % con_totallines) * con_linewidth; - clearnotify = 0; + clearnotify = 0; - for (x = 0; x < con_linewidth; x++) - Draw_Character ((x+1)<<3, v, text[x]); + for (x = 0; x < con_linewidth; x++) + Draw_Character((x + 1) << 3, v, text[x]); - v += 8; + v += 8; - scr_tileclear_updates = 0; //johnfitz - } + scr_tileclear_updates = 0; //johnfitz + } - if (key_dest == key_message) - { - clearnotify = 0; + if (key_dest == key_message) { + clearnotify = 0; - if (chat_team) - { - Draw_String (8, v, "say_team:"); - x = 11; - } - else - { - Draw_String (8, v, "say:"); - x = 6; - } + if (chat_team) { + Draw_String(8, v, "say_team:"); + x = 11; + } else { + Draw_String(8, v, "say:"); + x = 6; + } - text = Key_GetChatBuffer(); - i = Key_GetChatMsgLen(); - if (i > con_linewidth - x - 1) - text += i - con_linewidth + x + 1; + text = Key_GetChatBuffer(); + i = Key_GetChatMsgLen(); + if (i > con_linewidth - x - 1) + text += i - con_linewidth + x + 1; - while (*text) - { - Draw_Character (x<<3, v, *text); - x++; - text++; - } + while (*text) { + Draw_Character(x << 3, v, *text); + x++; + text++; + } - Draw_Character (x<<3, v, 10 + ((int)(realtime*con_cursorspeed)&1)); - v += 8; + Draw_Character(x << 3, v, 10 + ((int) (realtime * con_cursorspeed) & 1)); + v += 8; - scr_tileclear_updates = 0; //johnfitz - } + scr_tileclear_updates = 0; //johnfitz + } } /* @@ -1136,31 +1048,29 @@ Con_DrawInput -- johnfitz -- modified to allow insert editing The input line scrolls horizontally if typing goes beyond the right edge ================ */ -extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling +extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling -void Con_DrawInput (void) -{ - int i, ofs; +void Con_DrawInput(void) { + int i, ofs; - if (key_dest != key_console && !con_forcedup) - return; // don't draw anything + if (key_dest != key_console && !con_forcedup) + return; // don't draw anything -// prestep if horizontally scrolling - if (key_linepos >= con_linewidth) - ofs = 1 + key_linepos - con_linewidth; - else - ofs = 0; + // prestep if horizontally scrolling + if (key_linepos >= con_linewidth) + ofs = 1 + key_linepos - con_linewidth; + else + ofs = 0; -// draw input string - for (i = 0; key_lines[edit_line][i+ofs] && i < con_linewidth; i++) - Draw_Character ((i+1)<<3, vid.conheight - 16, key_lines[edit_line][i+ofs]); + // draw input string + for (i = 0; key_lines[edit_line][i + ofs] && i < con_linewidth; i++) + Draw_Character((i + 1) << 3, vid.conheight - 16, key_lines[edit_line][i + ofs]); -// johnfitz -- new cursor handling - if (!((int)((realtime-key_blinktime)*con_cursorspeed) & 1)) - { - i = key_linepos - ofs; - Draw_Pic ((i+1)<<3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr); - } + // johnfitz -- new cursor handling + if (!((int) ((realtime - key_blinktime) * con_cursorspeed) & 1)) { + i = key_linepos - ofs; + Draw_Pic((i + 1) << 3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr); + } } /* @@ -1171,56 +1081,53 @@ Draws the console with the solid background The typing input line at the bottom should only be drawn if typing is allowed ================ */ -void Con_DrawConsole (int lines, qboolean drawinput) -{ - int i, x, y, j, sb, rows; - const char *text; - char ver[32]; +void Con_DrawConsole(int lines, bool drawinput) { + int i, x, y, j, sb, rows; + const char *text; + char ver[32]; - if (lines <= 0) - return; + if (lines <= 0) + return; - con_vislines = lines * vid.conheight / glheight; - GL_SetCanvas (CANVAS_CONSOLE); + con_vislines = lines * vid.conheight / glheight; + GL_SetCanvas(CANVAS_CONSOLE); -// draw the background - Draw_ConsoleBackground (); + // draw the background + Draw_ConsoleBackground(); -// draw the buffer text - rows = (con_vislines +7)/8; - y = vid.conheight - rows*8; - rows -= 2; //for input and version lines - sb = (con_backscroll) ? 2 : 0; + // draw the buffer text + rows = (con_vislines + 7) / 8; + y = vid.conheight - rows * 8; + rows -= 2; //for input and version lines + sb = (con_backscroll) ? 2 : 0; - for (i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) - { - j = i - con_backscroll; - if (j < 0) - j = 0; - text = con_text + (j % con_totallines)*con_linewidth; + for (i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) { + j = i - con_backscroll; + if (j < 0) + j = 0; + text = con_text + (j % con_totallines) * con_linewidth; - for (x = 0; x < con_linewidth; x++) - Draw_Character ( (x + 1)<<3, y, text[x]); - } + for (x = 0; x < con_linewidth; x++) + Draw_Character((x + 1) << 3, y, text[x]); + } -// draw scrollback arrows - if (con_backscroll) - { - y += 8; // blank line - for (x = 0; x < con_linewidth; x += 4) - Draw_Character ((x + 1)<<3, y, '^'); - y += 8; - } + // draw scrollback arrows + if (con_backscroll) { + y += 8; // blank line + for (x = 0; x < con_linewidth; x += 4) + Draw_Character((x + 1) << 3, y, '^'); + y += 8; + } -// draw the input prompt, user text, and cursor - if (drawinput) - Con_DrawInput (); + // draw the input prompt, user text, and cursor + if (drawinput) + Con_DrawInput(); -//draw version number in bottom right - y += 8; - q_snprintf (ver, sizeof(ver), "QuakeSpasm " QUAKESPASM_VER_STRING); - for (x = 0; x < (int)strlen(ver); x++) - Draw_Character ((con_linewidth - strlen(ver) + x + 2)<<3, y, ver[x] /*+ 128*/); + //draw version number in bottom right + y += 8; + q_snprintf(ver, sizeof(ver), "QuakeSpasm " QUAKESPASM_VER_STRING); + for (x = 0; x < (int) strlen(ver); x++) + Draw_Character((con_linewidth - strlen(ver) + x + 2) << 3, y, ver[x] /*+ 128*/); } @@ -1229,71 +1136,64 @@ void Con_DrawConsole (int lines, qboolean drawinput) Con_NotifyBox ================== */ -void Con_NotifyBox (const char *text) -{ - double t1, t2; - int lastkey, lastchar; +void Con_NotifyBox(const char *text) { + double t1, t2; + int lastkey, lastchar; -// during startup for sound / cd warnings - Con_Printf ("\n\n%s", Con_Quakebar(40)); //johnfitz - Con_Printf ("%s", text); - Con_Printf ("Press a key.\n"); - Con_Printf ("%s", Con_Quakebar(40)); //johnfitz + // during startup for sound / cd warnings + Con_Printf("\n\n%s", Con_Quakebar(40)); //johnfitz + Con_Printf("%s", text); + Con_Printf("Press a key.\n"); + Con_Printf("%s", Con_Quakebar(40)); //johnfitz - IN_Deactivate(modestate == MS_WINDOWED); - key_dest = key_console; + IN_Deactivate(modestate == MS_WINDOWED); + key_dest = key_console; - Key_BeginInputGrab (); - do - { - t1 = Sys_DoubleTime (); - SCR_UpdateScreen (); - Sys_SendKeyEvents (); - Key_GetGrabbedInput (&lastkey, &lastchar); - Sys_Sleep (16); - t2 = Sys_DoubleTime (); - realtime += t2-t1; // make the cursor blink - } while (lastkey == -1 && lastchar == -1); - Key_EndInputGrab (); + Key_BeginInputGrab(); + do { + t1 = Sys_DoubleTime(); + SCR_UpdateScreen(); + Sys_SendKeyEvents(); + Key_GetGrabbedInput(&lastkey, &lastchar); + Sys_Sleep(16); + t2 = Sys_DoubleTime(); + realtime += t2 - t1; // make the cursor blink + } while (lastkey == -1 && lastchar == -1); + Key_EndInputGrab(); - Con_Printf ("\n"); - IN_Activate(); - key_dest = key_game; - realtime = 0; // put the cursor back to invisible + Con_Printf("\n"); + IN_Activate(); + key_dest = key_game; + realtime = 0; // put the cursor back to invisible } -void LOG_Init (quakeparms_t *parms) -{ - time_t inittime; - char session[24]; +void LOG_Init(quakeparms_t *parms) { + time_t inittime; + char session[24]; - if (!COM_CheckParm("-condebug")) - return; + if (!common::check_param("-condebug").has_value()) + return; - inittime = time (NULL); - strftime (session, sizeof(session), "%m/%d/%Y %H:%M:%S", localtime(&inittime)); - q_snprintf (logfilename, sizeof(logfilename), "%s/qconsole.log", parms->basedir); + inittime = time(NULL); + strftime(session, sizeof(session), "%m/%d/%Y %H:%M:%S", localtime(&inittime)); + q_snprintf(logfilename, sizeof(logfilename), "%s/qconsole.log", parms->basedir); -// unlink (logfilename); + // unlink (logfilename); - log_fd = open (logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666); - if (log_fd == -1) - { - fprintf (stderr, "Error: Unable to create log file %s\n", logfilename); - return; - } - - con_debuglog = true; - Con_DebugLog (va("LOG started on: %s \n", session)); + log_fd = open(logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (log_fd == -1) { + fprintf(stderr, "Error: Unable to create log file %s\n", logfilename); + return; + } + con_debuglog = true; + Con_DebugLog(va("LOG started on: %s \n", session)); } -void LOG_Close (void) -{ - if (log_fd == -1) - return; - close (log_fd); - log_fd = -1; +void LOG_Close(void) { + if (log_fd == -1) + return; + close(log_fd); + log_fd = -1; } - diff --git a/Quake/console.hpp b/Quake/console.hpp index 0fa4a8c..2560f36 100644 --- a/Quake/console.hpp +++ b/Quake/console.hpp @@ -28,8 +28,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // extern int con_totallines; extern int con_backscroll; -extern qboolean con_forcedup; // because no entities to refresh -extern qboolean con_initialized; +extern bool con_forcedup; // because no entities to refresh +extern bool con_initialized; extern byte *con_chars; extern char con_lastcenterstring[]; //johnfitz @@ -38,7 +38,7 @@ void Con_DrawCharacter (int cx, int line, int num); void Con_CheckResize (void); void Con_Init (void); -void Con_DrawConsole (int lines, qboolean drawinput); +void Con_DrawConsole (int lines, bool drawinput); void Con_Printf (const char *fmt, ...) FUNC_PRINTF(1,2); void Con_DWarning (const char *fmt, ...) FUNC_PRINTF(1,2); //ericw void Con_Warning (const char *fmt, ...) FUNC_PRINTF(1,2); //johnfitz diff --git a/Quake/convar.cpp b/Quake/convar.cpp index a3000b1..71beab3 100644 --- a/Quake/convar.cpp +++ b/Quake/convar.cpp @@ -50,7 +50,7 @@ void Cvar_List_f() { if (command::argc() > 1) { partial = command::argv(1)->c_str(); - len = Q_strlen(partial); + len = std::strlen(partial); } else { partial = NULL; len = 0; @@ -58,7 +58,7 @@ void Cvar_List_f() { count = 0; for (const auto &[name, var]: CLIENT_VARIABLES) { - if (partial && Q_strncmp(partial, name.c_str(), len)) { + if (partial && std::strncmp(partial, name.c_str(), len) != 0) { continue; } Con_SafePrintf("%s%s %s \"%s\"\n", @@ -91,7 +91,7 @@ void Cvar_Inc_f(void) { convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + 1); break; case 3: - convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + Q_atof(command::argv(2)->c_str())); + convar::set_value(*command::argv(1), convar::variable_value(*command::argv(1)).value_or(0.0) + std::atof(command::argv(2)->c_str())); break; } } @@ -136,11 +136,11 @@ void Cvar_Cycle_f() { //zero is assumed to be a string, even though it could actually be zero. The worst case //is that the first time you call this command, it won't match on zero when it should, but after that, //it will be comparing strings that all had the same source (the user) so it will work. - if (Q_atof(command::argv(i)->c_str()) == 0) { + if (std::atof(command::argv(i)->c_str()) == 0) { if (!strcmp(command::argv(i)->c_str(), convar::variable_string(*command::argv(1)).value_or("").c_str())) break; } else { - if (Q_atof(command::argv(i)->c_str()) == convar::variable_value(*command::argv(1)).value_or(0.0)) + if (std::atof(command::argv(i)->c_str()) == convar::variable_value(*command::argv(1)).value_or(0.0)) break; } } @@ -341,14 +341,14 @@ void convar::set(const std::string &new_value) { const std::size_t len = new_value.length(); - if (len != Q_strlen(this->string)) { + if (len != std::strlen(this->string)) { Z_Free((void *) this->string); this->string = (char *) Z_Malloc(len + 1); } memcpy((char *) this->string, new_value.c_str(), len + 1); } - this->value = Q_atof(this->string); + this->value = std::atof(this->string); //johnfitz -- save initial value for "reset" command if (!this->default_string) @@ -507,7 +507,7 @@ Cvar_Command Handles variable inspection and changing from the console ============ */ -qboolean Cvar_Command() { +bool Cvar_Command() { // check variables auto var = convar::find_var(command::argv(0).value_or("")); if (!var.has_value()) diff --git a/Quake/convar.hpp b/Quake/convar.hpp index 341829b..71530fe 100644 --- a/Quake/convar.hpp +++ b/Quake/convar.hpp @@ -149,6 +149,6 @@ struct convar { static convar_view get_variables(); }; -qboolean Cvar_Command(void); +bool Cvar_Command(void); void Cvar_WriteVariables(FILE *f); diff --git a/Quake/default_cfg.hpp b/Quake/default_cfg.hpp index a83e7ce..9b576ca 100644 --- a/Quake/default_cfg.hpp +++ b/Quake/default_cfg.hpp @@ -1,6 +1,7 @@ // keep in sync with Misc/qs_pak/default.cfg +#pragma once -static const char default_cfg[] = +constexpr char default_cfg[] = "unbindall\n" "bind ALT +strafe\n" diff --git a/Quake/gl_draw.cpp b/Quake/gl_draw.cpp index 4b59faf..aed3694 100644 --- a/Quake/gl_draw.cpp +++ b/Quake/gl_draw.cpp @@ -136,7 +136,7 @@ byte menuplyr_pixels[4096]; int scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT]; //johnfitz -- removed *4 after BLOCK_HEIGHT -qboolean scrap_dirty; +bool scrap_dirty; gltexture_t *scrap_textures[MAX_SCRAPS]; //johnfitz @@ -704,13 +704,13 @@ void GL_SetCanvas (canvastype newcanvas) break; case CANVAS_MENU: s = std::min((float)glwidth / 320.0f, (float)glheight / 200.0f); - s = CLAMP (1.0f, scr_menuscale.value, s); + s = std::clamp(scr_menuscale.value, 1.0f, s); // ericw -- doubled width to 640 to accommodate long keybindings glOrtho (0, 640, 200, 0, -99999, 99999); glViewport (glx + (glwidth - 320*s) / 2, gly + (glheight - 200*s) / 2, 640*s, 200*s); break; - case CANVAS_SBAR: - s = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); + case CANVAS_SBAR: + s = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f); if (cl.gametype == GAME_DEATHMATCH) { glOrtho (0, glwidth / s, 48, 0, -99999, 99999); @@ -727,7 +727,7 @@ void GL_SetCanvas (canvastype newcanvas) glViewport (glx, gly+glheight-gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); break; case CANVAS_CROSSHAIR: //0,0 is center of viewport - s = CLAMP (1.0f, scr_crosshairscale.value, 10.0f); + s = std::clamp(scr_crosshairscale.value, 1.0f, 10.0f); glOrtho (scr_vrect.width/-2/s, scr_vrect.width/2/s, scr_vrect.height/2/s, scr_vrect.height/-2/s, -99999, 99999); glViewport (scr_vrect.x, glheight - scr_vrect.y - scr_vrect.height, scr_vrect.width & ~1, scr_vrect.height & ~1); break; diff --git a/Quake/gl_fog.cpp b/Quake/gl_fog.cpp index 2ae42fc..6c4bfcc 100644 --- a/Quake/gl_fog.cpp +++ b/Quake/gl_fog.cpp @@ -126,15 +126,15 @@ void Fog_FogCommand_f(void) { Con_Printf(" \"blue\" is \"%f\"\n", fog_blue); return; case 2: - d = Q_atof(command::argv(1)->c_str()); + d = std::atof(command::argv(1)->c_str()); t = 0.0f; r = fog_red; g = fog_green; b = fog_blue; break; case 3: //TEST - d = Q_atof(command::argv(1)->c_str()); - t = Q_atof(command::argv(2)->c_str()); + d = std::atof(command::argv(1)->c_str()); + t = std::atof(command::argv(2)->c_str()); r = fog_red; g = fog_green; b = fog_blue; @@ -142,23 +142,23 @@ void Fog_FogCommand_f(void) { case 4: d = fog_density; t = 0.0f; - r = Q_atof(command::argv(1)->c_str()); - g = Q_atof(command::argv(2)->c_str()); - b = Q_atof(command::argv(3)->c_str()); + r = std::atof(command::argv(1)->c_str()); + g = std::atof(command::argv(2)->c_str()); + b = std::atof(command::argv(3)->c_str()); break; case 5: - d = Q_atof(command::argv(1)->c_str()); - r = Q_atof(command::argv(2)->c_str()); - g = Q_atof(command::argv(3)->c_str()); - b = Q_atof(command::argv(4)->c_str()); + d = std::atof(command::argv(1)->c_str()); + r = std::atof(command::argv(2)->c_str()); + g = std::atof(command::argv(3)->c_str()); + b = std::atof(command::argv(4)->c_str()); t = 0.0f; break; case 6: //TEST - d = Q_atof(command::argv(1)->c_str()); - r = Q_atof(command::argv(2)->c_str()); - g = Q_atof(command::argv(3)->c_str()); - b = Q_atof(command::argv(4)->c_str()); - t = Q_atof(command::argv(5)->c_str()); + d = std::atof(command::argv(1)->c_str()); + r = std::atof(command::argv(2)->c_str()); + g = std::atof(command::argv(3)->c_str()); + b = std::atof(command::argv(4)->c_str()); + t = std::atof(command::argv(5)->c_str()); break; } @@ -262,7 +262,7 @@ float *Fog_GetColor(void) { } for (i = 0; i < 3; i++) { - c[i] = CLAMP(0.f, c[i], 1.f); + c[i] = std::clamp(c[i], 0.f, 1.f); } //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly diff --git a/Quake/gl_model.cpp b/Quake/gl_model.cpp index 1d0f415..2488211 100644 --- a/Quake/gl_model.cpp +++ b/Quake/gl_model.cpp @@ -32,7 +32,7 @@ static char loadname[32]; // for hunk tags static void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer); static void Mod_LoadBrushModel (qmodel_t *mod, void *buffer); static void Mod_LoadAliasModel (qmodel_t *mod, void *buffer); -static qmodel_t *Mod_LoadModel (qmodel_t *mod, qboolean crash); +static qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash); static void Mod_Print (void); @@ -312,7 +312,7 @@ Mod_LoadModel Loads a model into the cache ================== */ -static qmodel_t *Mod_LoadModel (qmodel_t *mod, qboolean crash) +static qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash) { byte *buf; byte stackbuf[1024]; // avoid dirtying the cache heap @@ -388,7 +388,7 @@ Mod_ForName Loads in a model for the given name ================== */ -qmodel_t *Mod_ForName (const char *name, qboolean crash) +qmodel_t *Mod_ForName (const char *name, bool crash) { qmodel_t *mod; @@ -413,7 +413,7 @@ static byte *mod_base; Mod_CheckFullbrights -- johnfitz ================= */ -static qboolean Mod_CheckFullbrights (byte *pixels, int count) +static bool Mod_CheckFullbrights (byte *pixels, int count) { int i; for (i = 0; i < count; i++) @@ -432,7 +432,7 @@ Quake64 bsp Check if we have any missing textures in the array ================= */ -static qboolean Mod_CheckAnimTextureArrayQ64(texture_t *anims[], int numTex) +static bool Mod_CheckAnimTextureArrayQ64(texture_t *anims[], int numTex) { int i; @@ -1220,7 +1220,7 @@ static void Mod_CalcSurfaceBounds (msurface_t *s) Mod_LoadFaces ================= */ -static void Mod_LoadFaces (lump_t *l, qboolean bsp2) +static void Mod_LoadFaces (lump_t *l, bool bsp2) { dsface_t *ins; dlface_t *inl; @@ -1705,7 +1705,7 @@ static void Mod_LoadLeafs (lump_t *l, int bsp2) Mod_LoadClipnodes ================= */ -static void Mod_LoadClipnodes (lump_t *l, qboolean bsp2) +static void Mod_LoadClipnodes (lump_t *l, bool bsp2) { dsclipnode_t *ins; dlclipnode_t *inl; @@ -2672,7 +2672,7 @@ static void Mod_CalcAliasBounds (aliashdr_t *a) loadmodel->ymaxs[2] = loadmodel->maxs[2]; } -static qboolean +static bool nameInList(const char *list, const char *name) { const char *s; diff --git a/Quake/gl_model.hpp b/Quake/gl_model.hpp index aca75cc..567cf02 100644 --- a/Quake/gl_model.hpp +++ b/Quake/gl_model.hpp @@ -93,7 +93,7 @@ typedef struct texture_s struct gltexture_s *gltexture; //johnfitz -- pointer to gltexture struct gltexture_s *fullbright; //johnfitz -- fullbright mask texture struct gltexture_s *warpimage; //johnfitz -- for water animation - qboolean update_warp; //johnfitz -- update warp this frame + bool update_warp; //johnfitz -- update warp this frame struct msurface_s *texturechains[2]; // for texture chains int anim_total; // total tenths in sequence ( 0 = no) int anim_min, anim_max; // time for this frame min <=time< max @@ -172,7 +172,7 @@ typedef struct msurface_s int lightmaptexturenum; byte styles[MAXLIGHTMAPS]; int cached_light[MAXLIGHTMAPS]; // values currently used in lightmap - qboolean cached_dlight; // true if dynamic light in cache + bool cached_dlight; // true if dynamic light in cache byte *samples; // [numstyles*surfsize] } msurface_t; @@ -412,7 +412,7 @@ typedef struct qmodel_s char name[MAX_QPATH]; unsigned int path_id; // path id of the game directory // that this model came from - qboolean needload; // bmodels and sprites don't cache normally + bool needload; // bmodels and sprites don't cache normally modtype_t type; int numframes; @@ -431,7 +431,7 @@ typedef struct qmodel_s // // solid volume for clipping // - qboolean clipbox; + bool clipbox; vec3_t clipmins, clipmaxs; // @@ -481,10 +481,10 @@ typedef struct qmodel_s byte *lightdata; char *entities; - qboolean viswarn; // for Mod_DecompressVis() + bool viswarn; // for Mod_DecompressVis() int bspversion; - qboolean haslitwater; + bool haslitwater; // // alias model // @@ -507,7 +507,7 @@ typedef struct qmodel_s void Mod_Init (void); void Mod_ClearAll (void); void Mod_ResetAll (void); // for gamedir changes (Host_Game_f) -qmodel_t *Mod_ForName (const char *name, qboolean crash); +qmodel_t *Mod_ForName (const char *name, bool crash); void *Mod_Extradata (qmodel_t *mod); // handles caching void Mod_TouchModel (const char *name); diff --git a/Quake/gl_rmain.cpp b/Quake/gl_rmain.cpp index a1c59d1..914ce3e 100644 --- a/Quake/gl_rmain.cpp +++ b/Quake/gl_rmain.cpp @@ -114,7 +114,7 @@ convar r_slimealpha{"r_slimealpha", "0"}; float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; -qboolean r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz +bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz convar r_scale{"r_scale", "1", {.archive = true}}; @@ -266,7 +266,7 @@ R_CullBox -- johnfitz -- replaced with new function from lordhavoc Returns true if the box is completely outside the frustum ================= */ -qboolean R_CullBox(vec3_t emins, vec3_t emaxs) { +bool R_CullBox(vec3_t emins, vec3_t emaxs) { int i; mplane_t *p; byte signbits; @@ -289,7 +289,7 @@ qboolean R_CullBox(vec3_t emins, vec3_t emaxs) { R_CullModelForEntity -- johnfitz -- uses correct bounds based on rotation =============== */ -qboolean R_CullModelForEntity(entity_t *e) { +bool R_CullModelForEntity(entity_t *e) { vec3_t mins, maxs; vec_t scalefactor, *minbounds, *maxbounds; @@ -444,7 +444,7 @@ void R_SetupGL(void) { //johnfitz -- rewrote this section glMatrixMode(GL_PROJECTION); glLoadIdentity(); - scale = CLAMP(1, (int)r_scale.value, 4); // ericw -- see R_ScaleView + scale = std::clamp((int)r_scale.value, 1, 4); // ericw -- see R_ScaleView glViewport(glx + r_refdef.vrect.x, gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, r_refdef.vrect.width / scale, @@ -573,7 +573,7 @@ void R_SetupView(void) { R_DrawEntitiesOnList ============= */ -void R_DrawEntitiesOnList(qboolean alphapass) //johnfitz -- added parameter +void R_DrawEntitiesOnList(bool alphapass) //johnfitz -- added parameter { int i; @@ -905,7 +905,7 @@ void R_ScaleView(void) { int srcx, srcy, srcw, srch; // copied from R_SetupGL() - scale = CLAMP(1, (int)r_scale.value, 4); + scale = std::clamp((int)r_scale.value, 1, 4); srcx = glx + r_refdef.vrect.x; srcy = gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height; srcw = r_refdef.vrect.width / scale; @@ -1008,8 +1008,8 @@ void R_RenderView(void) { //johnfitz -- stereo rendering -- full of hacky goodness if (r_stereo.value) { - float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); - float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); + float eyesep = std::clamp(r_stereo.value, -8.0f, 8.0f); + float fdepth = std::clamp(r_stereodepth.value, 32.0f, 1024.0f); AngleVectors(r_refdef.viewangles, vpn, vright, vup); diff --git a/Quake/gl_rmisc.cpp b/Quake/gl_rmisc.cpp index 74b7c3f..fcbf099 100644 --- a/Quake/gl_rmisc.cpp +++ b/Quake/gl_rmisc.cpp @@ -438,7 +438,7 @@ void D_FlushCaches(void) { static GLuint gl_programs[16]; static int gl_num_programs; -static qboolean GL_CheckShader(GLuint shader) { +static bool GL_CheckShader(GLuint shader) { GLint status; GL_GetShaderivFunc(shader, GL_COMPILE_STATUS, &status); @@ -455,7 +455,7 @@ static qboolean GL_CheckShader(GLuint shader) { return true; } -static qboolean GL_CheckProgram(GLuint program) { +static bool GL_CheckProgram(GLuint program) { GLint status; GL_GetProgramivFunc(program, GL_LINK_STATUS, &status); @@ -539,7 +539,7 @@ GLuint GL_CreateProgram(const GLchar *vertSource, const GLchar *fragSource, int GL_DeleteProgramFunc(program); return 0; } else { - if (gl_num_programs == Q_COUNTOF(gl_programs)) + if (gl_num_programs == std::size(gl_programs)) Host_Error("gl_programs overflow"); gl_programs[gl_num_programs] = program; diff --git a/Quake/gl_screen.cpp b/Quake/gl_screen.cpp index bb38400..421cc01 100644 --- a/Quake/gl_screen.cpp +++ b/Quake/gl_screen.cpp @@ -23,6 +23,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // screen.c -- master for refresh, status bar, console, chat, notify, etc +#include + #include "quakedef.hpp" /* @@ -72,54 +74,54 @@ console is: */ -int glx, gly, glwidth, glheight; +int glx, gly, glwidth, glheight; -float scr_con_current; -float scr_conlines; // lines of console to display +float scr_con_current; +float scr_conlines; // lines of console to display //johnfitz -- new cvars -convar scr_menuscale = {"scr_menuscale", "1", {.archive = true}}; -convar scr_sbarscale = {"scr_sbarscale", "1", {.archive = true}}; -convar scr_sbaralpha = {"scr_sbaralpha", "0.75", {.archive = true}}; -convar scr_conwidth = {"scr_conwidth", "0", {.archive = true}}; -convar scr_conscale = {"scr_conscale", "1", {.archive = true}}; -convar scr_crosshairscale = {"scr_crosshairscale", "1", {.archive = true}}; -convar scr_showfps = {"scr_showfps", "0"}; -convar scr_clock = {"scr_clock", "0"}; +convar scr_menuscale = {"scr_menuscale", "1", {.archive = true}}; +convar scr_sbarscale = {"scr_sbarscale", "1", {.archive = true}}; +convar scr_sbaralpha = {"scr_sbaralpha", "0.75", {.archive = true}}; +convar scr_conwidth = {"scr_conwidth", "0", {.archive = true}}; +convar scr_conscale = {"scr_conscale", "1", {.archive = true}}; +convar scr_crosshairscale = {"scr_crosshairscale", "1", {.archive = true}}; +convar scr_showfps = {"scr_showfps", "0"}; +convar scr_clock = {"scr_clock", "0"}; //johnfitz -convar scr_usekfont = {"scr_usekfont", "0"}; // 2021 re-release +convar scr_usekfont = {"scr_usekfont", "0"}; // 2021 re-release -convar scr_viewsize = {"viewsize","100", {.archive = true}}; -convar scr_fov = {"fov","90"}; // 10 - 170 -convar scr_fov_adapt = {"fov_adapt","1",{.archive = true}}; -convar scr_conspeed = {"scr_conspeed","500",{.archive = true}}; -convar scr_centertime = {"scr_centertime","2"}; -convar scr_showturtle = {"showturtle","0"}; -convar scr_showpause = {"showpause","1"}; -convar scr_printspeed = {"scr_printspeed","8"}; -convar gl_triplebuffer = {"gl_triplebuffer", "1", {.archive = true}}; +convar scr_viewsize = {"viewsize", "100", {.archive = true}}; +convar scr_fov = {"fov", "90"}; // 10 - 170 +convar scr_fov_adapt = {"fov_adapt", "1", {.archive = true}}; +convar scr_conspeed = {"scr_conspeed", "500", {.archive = true}}; +convar scr_centertime = {"scr_centertime", "2"}; +convar scr_showturtle = {"showturtle", "0"}; +convar scr_showpause = {"showpause", "1"}; +convar scr_printspeed = {"scr_printspeed", "8"}; +convar gl_triplebuffer = {"gl_triplebuffer", "1", {.archive = true}}; -convar cl_gun_fovscale = {"cl_gun_fovscale","1",{.archive = true}}; // Qrack +convar cl_gun_fovscale = {"cl_gun_fovscale", "1", {.archive = true}}; // Qrack -extern convar crosshair; +extern convar crosshair; -qboolean scr_initialized; // ready to draw +bool scr_initialized; // ready to draw -qpic_t *scr_net; -qpic_t *scr_turtle; +qpic_t *scr_net; +qpic_t *scr_turtle; -int clearconsole; -int clearnotify; +int clearconsole; +int clearnotify; -vrect_t scr_vrect; +vrect_t scr_vrect; -qboolean scr_disabled_for_loading; -qboolean scr_drawloading; -float scr_disabled_time; +bool scr_disabled_for_loading; +bool scr_drawloading; +float scr_disabled_time; -int scr_tileclear_updates = 0; //johnfitz +int scr_tileclear_updates = 0; //johnfitz -void SCR_ScreenShot_f (void); +void SCR_ScreenShot_f(void); /* =============================================================================== @@ -129,12 +131,12 @@ CENTER PRINTING =============================================================================== */ -char scr_centerstring[1024]; -float scr_centertime_start; // for slow victory printing -float scr_centertime_off; -int scr_center_lines; -int scr_erase_lines; -int scr_erase_center; +char scr_centerstring[1024]; +float scr_centertime_start; // for slow victory printing +float scr_centertime_off; +int scr_center_lines; +int scr_erase_lines; +int scr_erase_center; /* ============== @@ -144,89 +146,85 @@ Called for important messages that should stay in the center of the screen for a few moments ============== */ -void SCR_CenterPrint (const char *str) //update centerprint data +void SCR_CenterPrint(const char *str) //update centerprint data { - strncpy (scr_centerstring, str, sizeof(scr_centerstring)-1); - scr_centertime_off = scr_centertime.value; - scr_centertime_start = cl.time; + strncpy(scr_centerstring, str, sizeof(scr_centerstring) - 1); + scr_centertime_off = scr_centertime.value; + scr_centertime_start = cl.time; -// count the number of lines for centering - scr_center_lines = 1; - str = scr_centerstring; - while (*str) - { - if (*str == '\n') - scr_center_lines++; - str++; - } + // count the number of lines for centering + scr_center_lines = 1; + str = scr_centerstring; + while (*str) { + if (*str == '\n') + scr_center_lines++; + str++; + } } -void SCR_DrawCenterString (void) //actually do the drawing +void SCR_DrawCenterString(void) //actually do the drawing { - char *start; - int l; - int j; - int x, y; - int remaining; + char *start; + int l; + int j; + int x, y; + int remaining; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz -// the finale prints the characters one at a time - if (cl.intermission) - remaining = scr_printspeed.value * (cl.time - scr_centertime_start); - else - remaining = 9999; + // the finale prints the characters one at a time + if (cl.intermission) + remaining = scr_printspeed.value * (cl.time - scr_centertime_start); + else + remaining = 9999; - scr_erase_center = 0; - start = scr_centerstring; + scr_erase_center = 0; + start = scr_centerstring; - if (scr_center_lines <= 4) - y = 200*0.35; //johnfitz -- 320x200 coordinate system - else - y = 48; - if (crosshair.value) - y -= 8; + if (scr_center_lines <= 4) + y = 200 * 0.35; //johnfitz -- 320x200 coordinate system + else + y = 48; + if (crosshair.value) + y -= 8; - do - { - // scan the width of the line - for (l=0 ; l<40 ; l++) - if (start[l] == '\n' || !start[l]) - break; - x = (320 - l*8)/2; //johnfitz -- 320x200 coordinate system - for (j=0 ; j scr_erase_lines) - scr_erase_lines = scr_center_lines; +void SCR_CheckDrawCenterString(void) { + if (scr_center_lines > scr_erase_lines) + scr_erase_lines = scr_center_lines; - scr_centertime_off -= host_frametime; + scr_centertime_off -= host_frametime; - if (scr_centertime_off <= 0 && !cl.intermission) - return; - if (key_dest != key_game) - return; - if (cl.paused) //johnfitz -- don't show centerprint during a pause - return; + if (scr_centertime_off <= 0 && !cl.intermission) + return; + if (key_dest != key_game) + return; + if (cl.paused) //johnfitz -- don't show centerprint during a pause + return; - SCR_DrawCenterString (); + SCR_DrawCenterString(); } //============================================================================= @@ -238,20 +236,19 @@ Adapt a 4:3 horizontal FOV to the current screen size using the "Hor+" scaling: 2.0 * atan(width / height * 3.0 / 4.0 * tan(fov_x / 2.0)) ==================== */ -float AdaptFovx (float fov_x, float width, float height) -{ - float a, x; +float AdaptFovx(float fov_x, float width, float height) { + float a, x; - if (fov_x < 1 || fov_x > 179) - Sys_Error ("Bad fov: %f", fov_x); + if (fov_x < 1 || fov_x > 179) + Sys_Error("Bad fov: %f", fov_x); - if (!scr_fov_adapt.value) - return fov_x; - if ((x = height / width) == 0.75) - return fov_x; - a = atan(0.75 / x * tan(fov_x / 360 * M_PI)); - a = a * 360 / M_PI; - return a; + if (!scr_fov_adapt.value) + return fov_x; + if ((x = height / width) == 0.75) + return fov_x; + a = atan(0.75 / x * tan(fov_x / 360 * M_PI)); + a = a * 360 / M_PI; + return a; } /* @@ -259,17 +256,16 @@ float AdaptFovx (float fov_x, float width, float height) CalcFovy ==================== */ -float CalcFovy (float fov_x, float width, float height) -{ - float a, x; +float CalcFovy(float fov_x, float width, float height) { + float a, x; - if (fov_x < 1 || fov_x > 179) - Sys_Error ("Bad fov: %f", fov_x); + if (fov_x < 1 || fov_x > 179) + Sys_Error("Bad fov: %f", fov_x); - x = width / tan(fov_x / 360 * M_PI); - a = atan(height / x); - a = a * 360 / M_PI; - return a; + x = width / tan(fov_x / 360 * M_PI); + a = atan(height / x); + a = a * 360 / M_PI; + return a; } /* @@ -280,54 +276,53 @@ Must be called whenever vid changes Internal use only ================= */ -static void SCR_CalcRefdef (void) -{ - float size, scale; //johnfitz -- scale +static void SCR_CalcRefdef(void) { + float size, scale; //johnfitz -- scale -// force the status bar to redraw - Sbar_Changed (); + // force the status bar to redraw + Sbar_Changed(); - scr_tileclear_updates = 0; //johnfitz + scr_tileclear_updates = 0; //johnfitz -// bound viewsize - if (scr_viewsize.value < 30) - scr_viewsize.set("30"); - if (scr_viewsize.value > 120) - scr_viewsize.set("120"); + // bound viewsize + if (scr_viewsize.value < 30) + scr_viewsize.set("30"); + if (scr_viewsize.value > 120) + scr_viewsize.set("120"); -// bound fov - if (scr_fov.value < 10) - scr_fov.set("10"); - if (scr_fov.value > 170) - scr_fov.set("170"); + // bound fov + if (scr_fov.value < 10) + scr_fov.set("10"); + if (scr_fov.value > 170) + scr_fov.set("170"); - vid.recalc_refdef = 0; + vid.recalc_refdef = 0; - //johnfitz -- rewrote this section - size = scr_viewsize.value; - scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); + //johnfitz -- rewrote this section + size = scr_viewsize.value; + scale = std::clamp(scr_sbarscale.value, 1.0f, (float) glwidth / 320.0f); - if (size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value - sb_lines = 0; - else if (size >= 110) - sb_lines = 24 * scale; - else - sb_lines = 48 * scale; + if (size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value + sb_lines = 0; + else if (size >= 110) + sb_lines = 24 * scale; + else + sb_lines = 48 * scale; - size = std::min(scr_viewsize.value, 100.f) / 100; - //johnfitz + size = std::min(scr_viewsize.value, 100.f) / 100; + //johnfitz - //johnfitz -- rewrote this section - r_refdef.vrect.width = std::max(glwidth * size, 96.0f); //no smaller than 96, for icons - r_refdef.vrect.height = std::min((int)(glheight * size), glheight - sb_lines); //make room for sbar - r_refdef.vrect.x = (glwidth - r_refdef.vrect.width)/2; - r_refdef.vrect.y = (glheight - sb_lines - r_refdef.vrect.height)/2; - //johnfitz + //johnfitz -- rewrote this section + r_refdef.vrect.width = std::max(glwidth * size, 96.0f); //no smaller than 96, for icons + r_refdef.vrect.height = std::min((int) (glheight * size), glheight - sb_lines); //make room for sbar + r_refdef.vrect.x = (glwidth - r_refdef.vrect.width) / 2; + r_refdef.vrect.y = (glheight - sb_lines - r_refdef.vrect.height) / 2; + //johnfitz - r_refdef.fov_x = AdaptFovx(scr_fov.value, vid.width, vid.height); - r_refdef.fov_y = CalcFovy (r_refdef.fov_x, r_refdef.vrect.width, r_refdef.vrect.height); + r_refdef.fov_x = AdaptFovx(scr_fov.value, vid.width, vid.height); + r_refdef.fov_y = CalcFovy(r_refdef.fov_x, r_refdef.vrect.width, r_refdef.vrect.height); - scr_vrect = r_refdef.vrect; + scr_vrect = r_refdef.vrect; } @@ -338,9 +333,8 @@ SCR_SizeUp_f Keybinding command ================= */ -void SCR_SizeUp_f (void) -{ - scr_viewsize.set_value(scr_viewsize.value+10); +void SCR_SizeUp_f(void) { + scr_viewsize.set_value(scr_viewsize.value + 10); } @@ -351,14 +345,12 @@ SCR_SizeDown_f Keybinding command ================= */ -void SCR_SizeDown_f (void) -{ - scr_viewsize.set_value(scr_viewsize.value-10); +void SCR_SizeDown_f(void) { + scr_viewsize.set_value(scr_viewsize.value - 10); } -static void SCR_Callback_refdef (convar *var) -{ - vid.recalc_refdef = 1; +static void SCR_Callback_refdef(convar *var) { + vid.recalc_refdef = 1; } /* @@ -366,13 +358,16 @@ static void SCR_Callback_refdef (convar *var) SCR_Conwidth_f -- johnfitz -- called when scr_conwidth or scr_conscale changes ================== */ -void SCR_Conwidth_f (convar *var) -{ - vid.recalc_refdef = 1; - vid.conwidth = (scr_conwidth.value > 0) ? (int)scr_conwidth.value : (scr_conscale.value > 0) ? (int)(vid.width/scr_conscale.value) : vid.width; - vid.conwidth = CLAMP (320, vid.conwidth, vid.width); - vid.conwidth &= 0xFFFFFFF8; - vid.conheight = vid.conwidth * vid.height / vid.width; +void SCR_Conwidth_f(convar *var) { + vid.recalc_refdef = 1; + vid.conwidth = (scr_conwidth.value > 0) + ? (int) scr_conwidth.value + : (scr_conscale.value > 0) + ? (int) (vid.width / scr_conscale.value) + : vid.width; + vid.conwidth = std::clamp(vid.conwidth, 320, vid.width); + vid.conwidth &= 0xFFFFFFF8; + vid.conheight = vid.conwidth * vid.height / vid.width; } //============================================================================ @@ -382,10 +377,9 @@ void SCR_Conwidth_f (convar *var) SCR_LoadPics -- johnfitz ================== */ -void SCR_LoadPics (void) -{ - scr_net = Draw_PicFromWad ("net"); - scr_turtle = Draw_PicFromWad ("turtle"); +void SCR_LoadPics(void) { + scr_net = Draw_PicFromWad("net"); + scr_turtle = Draw_PicFromWad("turtle"); } /* @@ -393,43 +387,42 @@ void SCR_LoadPics (void) SCR_Init ================== */ -void SCR_Init (void) -{ - //johnfitz -- new cvars - scr_menuscale.inscribe(); - scr_sbarscale.inscribe(); - scr_sbaralpha.set_callback(SCR_Callback_refdef); - scr_sbaralpha.inscribe(); - scr_conwidth.set_callback(&SCR_Conwidth_f); - scr_conscale.set_callback(&SCR_Conwidth_f); - scr_conwidth.inscribe(); - scr_conscale.inscribe(); - scr_crosshairscale.inscribe(); - scr_showfps.inscribe(); - scr_clock.inscribe(); - //johnfitz - scr_usekfont.inscribe(); // 2021 re-release - scr_fov.set_callback(SCR_Callback_refdef); - scr_fov_adapt.set_callback(SCR_Callback_refdef); - scr_viewsize.set_callback(SCR_Callback_refdef); - scr_fov.inscribe(); - scr_fov_adapt.inscribe(); - scr_viewsize.inscribe(); - scr_conspeed.inscribe(); - scr_showturtle.inscribe(); - scr_showpause.inscribe(); - scr_centertime.inscribe(); - scr_printspeed.inscribe(); - gl_triplebuffer.inscribe(); - cl_gun_fovscale.inscribe(); +void SCR_Init(void) { + //johnfitz -- new cvars + scr_menuscale.inscribe(); + scr_sbarscale.inscribe(); + scr_sbaralpha.set_callback(SCR_Callback_refdef); + scr_sbaralpha.inscribe(); + scr_conwidth.set_callback(&SCR_Conwidth_f); + scr_conscale.set_callback(&SCR_Conwidth_f); + scr_conwidth.inscribe(); + scr_conscale.inscribe(); + scr_crosshairscale.inscribe(); + scr_showfps.inscribe(); + scr_clock.inscribe(); + //johnfitz + scr_usekfont.inscribe(); // 2021 re-release + scr_fov.set_callback(SCR_Callback_refdef); + scr_fov_adapt.set_callback(SCR_Callback_refdef); + scr_viewsize.set_callback(SCR_Callback_refdef); + scr_fov.inscribe(); + scr_fov_adapt.inscribe(); + scr_viewsize.inscribe(); + scr_conspeed.inscribe(); + scr_showturtle.inscribe(); + scr_showpause.inscribe(); + scr_centertime.inscribe(); + scr_printspeed.inscribe(); + gl_triplebuffer.inscribe(); + cl_gun_fovscale.inscribe(); - command::add ("screenshot",SCR_ScreenShot_f); - command::add ("sizeup",SCR_SizeUp_f); - command::add ("sizedown",SCR_SizeDown_f); + command::add("screenshot", SCR_ScreenShot_f); + command::add("sizeup", SCR_SizeUp_f); + command::add("sizedown", SCR_SizeDown_f); - SCR_LoadPics (); //johnfitz + SCR_LoadPics(); //johnfitz - scr_initialized = true; + scr_initialized = true; } //============================================================================ @@ -439,43 +432,39 @@ void SCR_Init (void) SCR_DrawFPS -- johnfitz ============== */ -void SCR_DrawFPS (void) -{ - static double oldtime = 0; - static double lastfps = 0; - static int oldframecount = 0; - double elapsed_time; - int frames; +void SCR_DrawFPS(void) { + static double oldtime = 0; + static double lastfps = 0; + static int oldframecount = 0; + double elapsed_time; + int frames; - elapsed_time = realtime - oldtime; - frames = r_framecount - oldframecount; + elapsed_time = realtime - oldtime; + frames = r_framecount - oldframecount; - if (elapsed_time < 0 || frames < 0) - { - oldtime = realtime; - oldframecount = r_framecount; - return; - } - // update value every 3/4 second - if (elapsed_time > 0.75) - { - lastfps = frames / elapsed_time; - oldtime = realtime; - oldframecount = r_framecount; - } + if (elapsed_time < 0 || frames < 0) { + oldtime = realtime; + oldframecount = r_framecount; + return; + } + // update value every 3/4 second + if (elapsed_time > 0.75) { + lastfps = frames / elapsed_time; + oldtime = realtime; + oldframecount = r_framecount; + } - if (scr_showfps.value) - { - char st[16]; - int x, y; - sprintf (st, "%4.0f fps", lastfps); - x = 320 - (strlen(st)<<3); - y = 200 - 8; - if (scr_clock.value) y -= 8; //make room for clock - GL_SetCanvas (CANVAS_BOTTOMRIGHT); - Draw_String (x, y, st); - scr_tileclear_updates = 0; - } + if (scr_showfps.value) { + char st[16]; + int x, y; + sprintf(st, "%4.0f fps", lastfps); + x = 320 - (strlen(st) << 3); + y = 200 - 8; + if (scr_clock.value) y -= 8; //make room for clock + GL_SetCanvas(CANVAS_BOTTOMRIGHT); + Draw_String(x, y, st); + scr_tileclear_updates = 0; + } } /* @@ -483,27 +472,24 @@ void SCR_DrawFPS (void) SCR_DrawClock -- johnfitz ============== */ -void SCR_DrawClock (void) -{ - char str[12]; +void SCR_DrawClock(void) { + char str[12]; - if (scr_clock.value == 1) - { - int minutes, seconds; + if (scr_clock.value == 1) { + int minutes, seconds; - minutes = cl.time / 60; - seconds = ((int)cl.time)%60; + minutes = cl.time / 60; + seconds = ((int) cl.time) % 60; - sprintf (str,"%i:%i%i", minutes, seconds/10, seconds%10); - } - else - return; + sprintf(str, "%i:%i%i", minutes, seconds / 10, seconds % 10); + } else + return; - //draw it - GL_SetCanvas (CANVAS_BOTTOMRIGHT); - Draw_String (320 - (strlen(str)<<3), 200 - 8, str); + //draw it + GL_SetCanvas(CANVAS_BOTTOMRIGHT); + Draw_String(320 - (strlen(str) << 3), 200 - 8, str); - scr_tileclear_updates = 0; + scr_tileclear_updates = 0; } /* @@ -511,45 +497,44 @@ void SCR_DrawClock (void) SCR_DrawDevStats ============== */ -void SCR_DrawDevStats (void) -{ - char str[40]; - int y = 25-9; //9=number of lines to print - int x = 0; //margin +void SCR_DrawDevStats(void) { + char str[40]; + int y = 25 - 9; //9=number of lines to print + int x = 0; //margin - if (!devstats.value) - return; + if (!devstats.value) + return; - GL_SetCanvas (CANVAS_BOTTOMLEFT); + GL_SetCanvas(CANVAS_BOTTOMLEFT); - Draw_Fill (x, y*8, 19*8, 9*8, 0, 0.5); //dark rectangle + Draw_Fill(x, y * 8, 19 * 8, 9 * 8, 0, 0.5); //dark rectangle - sprintf (str, "devstats |Curr Peak"); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "devstats |Curr Peak"); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "---------+---------"); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "---------+---------"); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Edicts |%4i %4i", dev_stats.edicts, dev_peakstats.edicts); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Edicts |%4i %4i", dev_stats.edicts, dev_peakstats.edicts); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Packet |%4i %4i", dev_stats.packetsize, dev_peakstats.packetsize); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Packet |%4i %4i", dev_stats.packetsize, dev_peakstats.packetsize); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Visedicts|%4i %4i", dev_stats.visedicts, dev_peakstats.visedicts); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Visedicts|%4i %4i", dev_stats.visedicts, dev_peakstats.visedicts); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Efrags |%4i %4i", dev_stats.efrags, dev_peakstats.efrags); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Efrags |%4i %4i", dev_stats.efrags, dev_peakstats.efrags); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Dlights |%4i %4i", dev_stats.dlights, dev_peakstats.dlights); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Dlights |%4i %4i", dev_stats.dlights, dev_peakstats.dlights); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Beams |%4i %4i", dev_stats.beams, dev_peakstats.beams); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Beams |%4i %4i", dev_stats.beams, dev_peakstats.beams); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Tempents |%4i %4i", dev_stats.tempents, dev_peakstats.tempents); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Tempents |%4i %4i", dev_stats.tempents, dev_peakstats.tempents); + Draw_String(x, (y++) * 8 - x, str); } /* @@ -557,26 +542,24 @@ void SCR_DrawDevStats (void) SCR_DrawTurtle ============== */ -void SCR_DrawTurtle (void) -{ - static int count; +void SCR_DrawTurtle(void) { + static int count; - if (!scr_showturtle.value) - return; + if (!scr_showturtle.value) + return; - if (host_frametime < 0.1) - { - count = 0; - return; - } + if (host_frametime < 0.1) { + count = 0; + return; + } - count++; - if (count < 3) - return; + count++; + if (count < 3) + return; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz - Draw_Pic (scr_vrect.x, scr_vrect.y, scr_turtle); + Draw_Pic(scr_vrect.x, scr_vrect.y, scr_turtle); } /* @@ -584,16 +567,15 @@ void SCR_DrawTurtle (void) SCR_DrawNet ============== */ -void SCR_DrawNet (void) -{ - if (realtime - cl.last_received_message < 0.3) - return; - if (cls.demoplayback) - return; +void SCR_DrawNet(void) { + if (realtime - cl.last_received_message < 0.3) + return; + if (cls.demoplayback) + return; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz - Draw_Pic (scr_vrect.x+64, scr_vrect.y, scr_net); + Draw_Pic(scr_vrect.x + 64, scr_vrect.y, scr_net); } /* @@ -601,22 +583,21 @@ void SCR_DrawNet (void) DrawPause ============== */ -void SCR_DrawPause (void) -{ - qpic_t *pic; +void SCR_DrawPause(void) { + qpic_t *pic; - if (!cl.paused) - return; + if (!cl.paused) + return; - if (!scr_showpause.value) // turn off for screenshots - return; + if (!scr_showpause.value) // turn off for screenshots + return; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/pause.lmp"); - Draw_Pic ( (320 - pic->width)/2, (240 - 48 - pic->height)/2, pic); //johnfitz -- stretched menus + pic = Draw_CachePic("gfx/pause.lmp"); + Draw_Pic((320 - pic->width) / 2, (240 - 48 - pic->height) / 2, pic); //johnfitz -- stretched menus - scr_tileclear_updates = 0; //johnfitz + scr_tileclear_updates = 0; //johnfitz } /* @@ -624,19 +605,18 @@ void SCR_DrawPause (void) SCR_DrawLoading ============== */ -void SCR_DrawLoading (void) -{ - qpic_t *pic; +void SCR_DrawLoading(void) { + qpic_t *pic; - if (!scr_drawloading) - return; + if (!scr_drawloading) + return; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/loading.lmp"); - Draw_Pic ( (320 - pic->width)/2, (240 - 48 - pic->height)/2, pic); //johnfitz -- stretched menus + pic = Draw_CachePic("gfx/loading.lmp"); + Draw_Pic((320 - pic->width) / 2, (240 - 48 - pic->height) / 2, pic); //johnfitz -- stretched menus - scr_tileclear_updates = 0; //johnfitz + scr_tileclear_updates = 0; //johnfitz } /* @@ -644,17 +624,15 @@ void SCR_DrawLoading (void) SCR_DrawCrosshair -- johnfitz ============== */ -void SCR_DrawCrosshair (void) -{ - if (!crosshair.value) - return; +void SCR_DrawCrosshair(void) { + if (!crosshair.value) + return; - GL_SetCanvas (CANVAS_CROSSHAIR); - Draw_Character (-4, -4, '+'); //0,0 is center of viewport + GL_SetCanvas(CANVAS_CROSSHAIR); + Draw_Character(-4, -4, '+'); //0,0 is center of viewport } - //============================================================================= @@ -663,54 +641,48 @@ void SCR_DrawCrosshair (void) SCR_SetUpToDrawConsole ================== */ -void SCR_SetUpToDrawConsole (void) -{ - //johnfitz -- let's hack away the problem of slow console when host_timescale is <0 - extern convar host_timescale; - float timescale, conspeed; - //johnfitz +void SCR_SetUpToDrawConsole(void) { + //johnfitz -- let's hack away the problem of slow console when host_timescale is <0 + extern convar host_timescale; + float timescale, conspeed; + //johnfitz - Con_CheckResize (); + Con_CheckResize(); - if (scr_drawloading) - return; // never a console with loading plaque + if (scr_drawloading) + return; // never a console with loading plaque -// decide on the height of the console - con_forcedup = !cl.worldmodel || cls.signon != SIGNONS; + // decide on the height of the console + con_forcedup = !cl.worldmodel || cls.signon != SIGNONS; - if (con_forcedup) - { - scr_conlines = glheight; //full screen //johnfitz -- glheight instead of vid.height - scr_con_current = scr_conlines; - } - else if (key_dest == key_console) - scr_conlines = glheight/2; //half screen //johnfitz -- glheight instead of vid.height - else - scr_conlines = 0; //none visible + if (con_forcedup) { + scr_conlines = glheight; //full screen //johnfitz -- glheight instead of vid.height + scr_con_current = scr_conlines; + } else if (key_dest == key_console) + scr_conlines = glheight / 2; //half screen //johnfitz -- glheight instead of vid.height + else + scr_conlines = 0; //none visible - timescale = (host_timescale.value > 0) ? host_timescale.value : 1; //johnfitz -- timescale - conspeed = (scr_conspeed.value > 0) ? scr_conspeed.value : 1e6f; + timescale = (host_timescale.value > 0) ? host_timescale.value : 1; //johnfitz -- timescale + conspeed = (scr_conspeed.value > 0) ? scr_conspeed.value : 1e6f; - if (scr_conlines < scr_con_current) - { - // ericw -- (glheight/600.0) factor makes conspeed resolution independent, using 800x600 as a baseline - scr_con_current -= conspeed*(glheight/600.0)*host_frametime/timescale; //johnfitz -- timescale - if (scr_conlines > scr_con_current) - scr_con_current = scr_conlines; - } - else if (scr_conlines > scr_con_current) - { - // ericw -- (glheight/600.0) - scr_con_current += conspeed*(glheight/600.0)*host_frametime/timescale; //johnfitz -- timescale - if (scr_conlines < scr_con_current) - scr_con_current = scr_conlines; - } + if (scr_conlines < scr_con_current) { + // ericw -- (glheight/600.0) factor makes conspeed resolution independent, using 800x600 as a baseline + scr_con_current -= conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale + if (scr_conlines > scr_con_current) + scr_con_current = scr_conlines; + } else if (scr_conlines > scr_con_current) { + // ericw -- (glheight/600.0) + scr_con_current += conspeed * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale + if (scr_conlines < scr_con_current) + scr_con_current = scr_conlines; + } - if (clearconsole++ < vid.numpages) - Sbar_Changed (); + if (clearconsole++ < vid.numpages) + Sbar_Changed(); - if (!con_forcedup && scr_con_current) - scr_tileclear_updates = 0; //johnfitz + if (!con_forcedup && scr_con_current) + scr_tileclear_updates = 0; //johnfitz } /* @@ -718,18 +690,14 @@ void SCR_SetUpToDrawConsole (void) SCR_DrawConsole ================== */ -void SCR_DrawConsole (void) -{ - if (scr_con_current) - { - Con_DrawConsole (scr_con_current, true); - clearconsole = 0; - } - else - { - if (key_dest == key_game || key_dest == key_message) - Con_DrawNotify (); // only draw notify in game - } +void SCR_DrawConsole(void) { + if (scr_con_current) { + Con_DrawConsole(scr_con_current, true); + clearconsole = 0; + } else { + if (key_dest == key_game || key_dest == key_message) + Con_DrawNotify(); // only draw notify in game + } } @@ -741,12 +709,11 @@ SCREEN SHOTS ============================================================================== */ -static void SCR_ScreenShot_Usage (void) -{ - Con_Printf ("usage: screenshot \n"); - Con_Printf (" format must be \"png\" or \"tga\" or \"jpg\"\n"); - Con_Printf (" quality must be 1-100\n"); - return; +static void SCR_ScreenShot_Usage(void) { + Con_Printf("usage: screenshot \n"); + Con_Printf(" format must be \"png\" or \"tga\" or \"jpg\"\n"); + Con_Printf(" quality must be 1-100\n"); + return; } /* @@ -754,82 +721,75 @@ static void SCR_ScreenShot_Usage (void) SCR_ScreenShot_f -- johnfitz -- rewritten to use Image_WriteTGA ================== */ -void SCR_ScreenShot_f (void) -{ - byte *buffer; - char ext[4]; - char imagename[16]; //johnfitz -- was [80] - char checkname[MAX_OSPATH]; - int i, quality; - qboolean ok; +void SCR_ScreenShot_f(void) { + byte *buffer; + char ext[4]; + char imagename[16]; //johnfitz -- was [80] + char checkname[MAX_OSPATH]; + int i, quality; + bool ok; - Q_strncpy (ext, "png", sizeof(ext)); + std::strncpy(ext, "png", sizeof(ext)); - if (command::argc () >= 2) - { - const char *requested_ext = command::argv (1)->c_str(); + if (command::argc() >= 2) { + const char *requested_ext = command::argv(1)->c_str(); - if (!q_strcasecmp ("png", requested_ext) - || !q_strcasecmp ("tga", requested_ext) - || !q_strcasecmp ("jpg", requested_ext)) - Q_strncpy (ext, requested_ext, sizeof(ext)); - else - { - SCR_ScreenShot_Usage (); - return; - } - } + if (!q_strcasecmp("png", requested_ext) + || !q_strcasecmp("tga", requested_ext) + || !q_strcasecmp("jpg", requested_ext)) + std::strncpy(ext, requested_ext, sizeof(ext)); + else { + SCR_ScreenShot_Usage(); + return; + } + } -// read quality as the 3rd param (only used for JPG) - quality = 90; - if (command::argc () >= 3) - quality = Q_atoi (command::argv(2)->c_str()); - if (quality < 1 || quality > 100) - { - SCR_ScreenShot_Usage (); - return; - } - -// find a file name to save it to - for (i=0; i<10000; i++) - { - q_snprintf (imagename, sizeof(imagename), "spasm%04i.%s", i, ext); // "fitz%04i.tga" - q_snprintf (checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename); - if (Sys_FileType(checkname) == FS_ENT_NONE) - break; // file doesn't exist - } - if (i == 10000) - { - Con_Printf ("SCR_ScreenShot_f: Couldn't find an unused filename\n"); - return; - } + // read quality as the 3rd param (only used for JPG) + quality = 90; + if (command::argc() >= 3) + quality = std::atoi(command::argv(2)->c_str()); + if (quality < 1 || quality > 100) { + SCR_ScreenShot_Usage(); + return; + } -//get data - if (!(buffer = (byte *) malloc(glwidth*glheight*3))) - { - Con_Printf ("SCR_ScreenShot_f: Couldn't allocate memory\n"); - return; - } + // find a file name to save it to + for (i = 0; i < 10000; i++) { + q_snprintf(imagename, sizeof(imagename), "spasm%04i.%s", i, ext); // "fitz%04i.tga" + q_snprintf(checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename); + if (Sys_FileType(checkname) == FS_ENT_NONE) + break; // file doesn't exist + } + if (i == 10000) { + Con_Printf("SCR_ScreenShot_f: Couldn't find an unused filename\n"); + return; + } - glPixelStorei (GL_PACK_ALIGNMENT, 1);/* for widths that aren't a multiple of 4 */ - glReadPixels (glx, gly, glwidth, glheight, GL_RGB, GL_UNSIGNED_BYTE, buffer); + //get data + if (!(buffer = (byte *) malloc(glwidth * glheight * 3))) { + Con_Printf("SCR_ScreenShot_f: Couldn't allocate memory\n"); + return; + } -// now write the file - if (!q_strncasecmp (ext, "png", sizeof(ext))) - ok = Image_WritePNG (imagename, buffer, glwidth, glheight, 24, false); - else if (!q_strncasecmp (ext, "tga", sizeof(ext))) - ok = Image_WriteTGA (imagename, buffer, glwidth, glheight, 24, false); - else if (!q_strncasecmp (ext, "jpg", sizeof(ext))) - ok = Image_WriteJPG (imagename, buffer, glwidth, glheight, 24, quality, false); - else - ok = false; + glPixelStorei(GL_PACK_ALIGNMENT, 1); /* for widths that aren't a multiple of 4 */ + glReadPixels(glx, gly, glwidth, glheight, GL_RGB, GL_UNSIGNED_BYTE, buffer); - if (ok) - Con_Printf ("Wrote %s\n", imagename); - else - Con_Printf ("SCR_ScreenShot_f: Couldn't create %s\n", imagename); + // now write the file + if (!q_strncasecmp(ext, "png", sizeof(ext))) + ok = Image_WritePNG(imagename, buffer, glwidth, glheight, 24, false); + else if (!q_strncasecmp(ext, "tga", sizeof(ext))) + ok = Image_WriteTGA(imagename, buffer, glwidth, glheight, 24, false); + else if (!q_strncasecmp(ext, "jpg", sizeof(ext))) + ok = Image_WriteJPG(imagename, buffer, glwidth, glheight, 24, quality, false); + else + ok = false; - free (buffer); + if (ok) + Con_Printf("Wrote %s\n", imagename); + else + Con_Printf("SCR_ScreenShot_f: Couldn't create %s\n", imagename); + + free(buffer); } @@ -842,27 +802,26 @@ SCR_BeginLoadingPlaque ================ */ -void SCR_BeginLoadingPlaque (void) -{ - S_StopAllSounds (true); +void SCR_BeginLoadingPlaque(void) { + S_StopAllSounds(true); - if (cls.state != ca_connected) - return; - if (cls.signon != SIGNONS) - return; + if (cls.state != ca_connected) + return; + if (cls.signon != SIGNONS) + return; -// redraw with no console and the loading plaque - Con_ClearNotify (); - scr_centertime_off = 0; - scr_con_current = 0; + // redraw with no console and the loading plaque + Con_ClearNotify(); + scr_centertime_off = 0; + scr_con_current = 0; - scr_drawloading = true; - Sbar_Changed (); - SCR_UpdateScreen (); - scr_drawloading = false; + scr_drawloading = true; + Sbar_Changed(); + SCR_UpdateScreen(); + scr_drawloading = false; - scr_disabled_for_loading = true; - scr_disabled_time = realtime; + scr_disabled_for_loading = true; + scr_disabled_time = realtime; } /* @@ -871,49 +830,46 @@ SCR_EndLoadingPlaque ================ */ -void SCR_EndLoadingPlaque (void) -{ - scr_disabled_for_loading = false; - Con_ClearNotify (); +void SCR_EndLoadingPlaque(void) { + scr_disabled_for_loading = false; + Con_ClearNotify(); } //============================================================================= -const char *scr_notifystring; -qboolean scr_drawdialog; +const char *scr_notifystring; +bool scr_drawdialog; -void SCR_DrawNotifyString (void) -{ - const char *start; - int l; - int j; - int x, y; +void SCR_DrawNotifyString(void) { + const char *start; + int l; + int j; + int x, y; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - start = scr_notifystring; + start = scr_notifystring; - y = 200 * 0.35; //johnfitz -- stretched overlays + y = 200 * 0.35; //johnfitz -- stretched overlays - do - { - // scan the width of the line - for (l=0 ; l<40 ; l++) - if (start[l] == '\n' || !start[l]) - break; - x = (320 - l*8)/2; //johnfitz -- stretched overlays - for (j=0 ; j time1) - return false; - //johnfitz + //johnfitz -- timeout + if (time2 > time1) + return false; + //johnfitz - return (lastchar == 'y' || lastchar == 'Y' || lastkey == K_ABUTTON); + return (lastchar == 'y' || lastchar == 'Y' || lastkey == K_ABUTTON); } @@ -983,40 +938,37 @@ johnfitz -- modified to use glwidth/glheight instead of vid.width/vid.height also added scr_tileclear_updates ================== */ -void SCR_TileClear (void) -{ - //ericw -- added check for glsl gamma. TODO: remove this ugly optimization? - if (scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1)) - return; - scr_tileclear_updates++; +void SCR_TileClear(void) { + //ericw -- added check for glsl gamma. TODO: remove this ugly optimization? + if (scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1)) + return; + scr_tileclear_updates++; - if (r_refdef.vrect.x > 0) - { - // left - Draw_TileClear (0, - 0, - r_refdef.vrect.x, - glheight - sb_lines); - // right - Draw_TileClear (r_refdef.vrect.x + r_refdef.vrect.width, - 0, - glwidth - r_refdef.vrect.x - r_refdef.vrect.width, - glheight - sb_lines); - } + if (r_refdef.vrect.x > 0) { + // left + Draw_TileClear(0, + 0, + r_refdef.vrect.x, + glheight - sb_lines); + // right + Draw_TileClear(r_refdef.vrect.x + r_refdef.vrect.width, + 0, + glwidth - r_refdef.vrect.x - r_refdef.vrect.width, + glheight - sb_lines); + } - if (r_refdef.vrect.y > 0) - { - // top - Draw_TileClear (r_refdef.vrect.x, - 0, - r_refdef.vrect.width, - r_refdef.vrect.y); - // bottom - Draw_TileClear (r_refdef.vrect.x, - r_refdef.vrect.y + r_refdef.vrect.height, - r_refdef.vrect.width, - glheight - r_refdef.vrect.y - r_refdef.vrect.height - sb_lines); - } + if (r_refdef.vrect.y > 0) { + // top + Draw_TileClear(r_refdef.vrect.x, + 0, + r_refdef.vrect.width, + r_refdef.vrect.y); + // bottom + Draw_TileClear(r_refdef.vrect.x, + r_refdef.vrect.y + r_refdef.vrect.height, + r_refdef.vrect.width, + glheight - r_refdef.vrect.y - r_refdef.vrect.height - sb_lines); + } } /* @@ -1030,87 +982,77 @@ WARNING: be very careful calling this from elsewhere, because the refresh needs almost the entire 256k of stack space! ================== */ -void SCR_UpdateScreen (void) -{ - vid.numpages = (gl_triplebuffer.value) ? 3 : 2; +void SCR_UpdateScreen(void) { + vid.numpages = (gl_triplebuffer.value) ? 3 : 2; - if (scr_disabled_for_loading) - { - if (realtime - scr_disabled_time > 60) - { - scr_disabled_for_loading = false; - Con_Printf ("load failed.\n"); - } - else - return; - } + if (scr_disabled_for_loading) { + if (realtime - scr_disabled_time > 60) { + scr_disabled_for_loading = false; + Con_Printf("load failed.\n"); + } else + return; + } - if (!scr_initialized || !con_initialized) - return; // not initialized yet + if (!scr_initialized || !con_initialized) + return; // not initialized yet - GL_BeginRendering (&glx, &gly, &glwidth, &glheight); + GL_BeginRendering(&glx, &gly, &glwidth, &glheight); - // - // determine size of refresh window - // - if (vid.recalc_refdef) - SCR_CalcRefdef (); + // + // determine size of refresh window + // + if (vid.recalc_refdef) + SCR_CalcRefdef(); -// -// do 3D refresh drawing, and then update the screen -// - SCR_SetUpToDrawConsole (); + // + // do 3D refresh drawing, and then update the screen + // + SCR_SetUpToDrawConsole(); - V_RenderView (); + V_RenderView(); - GL_Set2D (); + GL_Set2D(); - //FIXME: only call this when needed - SCR_TileClear (); + //FIXME: only call this when needed + SCR_TileClear(); - if (scr_drawdialog) //new game confirm - { - if (con_forcedup) - Draw_ConsoleBackground (); - else - Sbar_Draw (); - Draw_FadeScreen (); - SCR_DrawNotifyString (); - } - else if (scr_drawloading) //loading - { - SCR_DrawLoading (); - Sbar_Draw (); - } - else if (cl.intermission == 1 && key_dest == key_game) //end of level - { - Sbar_IntermissionOverlay (); - } - else if (cl.intermission == 2 && key_dest == key_game) //end of episode - { - Sbar_FinaleOverlay (); - SCR_CheckDrawCenterString (); - } - else - { - SCR_DrawCrosshair (); //johnfitz - SCR_DrawNet (); - SCR_DrawTurtle (); - SCR_DrawPause (); - SCR_CheckDrawCenterString (); - Sbar_Draw (); - SCR_DrawDevStats (); //johnfitz - SCR_DrawFPS (); //johnfitz - SCR_DrawClock (); //johnfitz - SCR_DrawConsole (); - M_Draw (); - } + if (scr_drawdialog) //new game confirm + { + if (con_forcedup) + Draw_ConsoleBackground(); + else + Sbar_Draw(); + Draw_FadeScreen(); + SCR_DrawNotifyString(); + } else if (scr_drawloading) //loading + { + SCR_DrawLoading(); + Sbar_Draw(); + } else if (cl.intermission == 1 && key_dest == key_game) //end of level + { + Sbar_IntermissionOverlay(); + } else if (cl.intermission == 2 && key_dest == key_game) //end of episode + { + Sbar_FinaleOverlay(); + SCR_CheckDrawCenterString(); + } else { + SCR_DrawCrosshair(); //johnfitz + SCR_DrawNet(); + SCR_DrawTurtle(); + SCR_DrawPause(); + SCR_CheckDrawCenterString(); + Sbar_Draw(); + SCR_DrawDevStats(); //johnfitz + SCR_DrawFPS(); //johnfitz + SCR_DrawClock(); //johnfitz + SCR_DrawConsole(); + M_Draw(); + } - V_UpdateBlend (); //johnfitz -- V_UpdatePalette cleaned up and renamed + V_UpdateBlend(); //johnfitz -- V_UpdatePalette cleaned up and renamed - GLSLGamma_GammaCorrect (); + GLSLGamma_GammaCorrect(); - GL_EndRendering (); + GL_EndRendering(); } - diff --git a/Quake/gl_sky.cpp b/Quake/gl_sky.cpp index 4141e43..3c14a71 100644 --- a/Quake/gl_sky.cpp +++ b/Quake/gl_sky.cpp @@ -221,7 +221,7 @@ void Sky_LoadSkyBox (const char *name) int i, mark, width, height; char filename[MAX_OSPATH]; byte *data; - qboolean nonefound = true; + bool nonefound = true; if (strcmp(skybox_name, name) == 0) return; //no change @@ -502,7 +502,7 @@ static void Sky_ClipPoly (int nump, vec3_t vecs, int stage) { const float *norm; float *v; - qboolean front, back; + bool front, back; float d, e; int newc[2]; int i, j; @@ -680,7 +680,7 @@ void Sky_ProcessEntities (void) glpoly_t *p; int i,j,k,mark; float dot; - qboolean rotated; + bool rotated; vec3_t temp, forward, right, up; if (!r_drawentities.value) @@ -838,7 +838,7 @@ void Sky_DrawSkyBox (void) c = Fog_GetColor(); glEnable (GL_BLEND); glDisable (GL_TEXTURE_2D); - glColor4f (c[0],c[1],c[2], CLAMP(0.0f,skyfog,1.0f)); + glColor4f (c[0],c[1],c[2], std::clamp(skyfog,0.0f, 1.0f)); glBegin (GL_QUADS); Sky_EmitSkyBoxVertex (skymins[0][i], skymins[1][i], i); @@ -989,12 +989,13 @@ void Sky_DrawFaceQuad (glpoly_t *p) c = Fog_GetColor(); glEnable (GL_BLEND); glDisable (GL_TEXTURE_2D); - glColor4f (c[0],c[1],c[2], CLAMP(0.0f,skyfog,1.0f)); + glColor4f (c[0],c[1],c[2], std::clamp(skyfog,0.0f, 1.0f)); glBegin (GL_QUADS); for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) glVertex3fv (v); glEnd (); + glColor3f (1, 1, 1); glEnable (GL_TEXTURE_2D); diff --git a/Quake/gl_texmgr.cpp b/Quake/gl_texmgr.cpp index 7aa37a9..1149779 100644 --- a/Quake/gl_texmgr.cpp +++ b/Quake/gl_texmgr.cpp @@ -22,6 +22,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //gl_texmgr.c -- fitzquake's texture manager. manages opengl texture images +#include + #include "quakedef.hpp" static const int gl_solid_format = 3; @@ -68,7 +70,7 @@ static glmode_t glmodes[] = { {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, }; -#define NUM_GLMODES (int)Q_COUNTOF(glmodes) +#define NUM_GLMODES (int)std::size(glmodes) static int glmode_idx = NUM_GLMODES - 1; /* trilinear */ /* @@ -117,7 +119,7 @@ static void TexMgr_TextureMode_f(convar *var) { int i; for (i = 0; i < NUM_GLMODES; i++) { - if (!Q_strcmp(glmodes[i].name, gl_texturemode.string)) { + if (!std::strcmp(glmodes[i].name, gl_texturemode.string)) { if (glmode_idx != i) { glmode_idx = i; for (glt = active_gltextures; glt; glt = glt->next) @@ -306,7 +308,7 @@ gltexture_t *TexMgr_NewTexture(void) { static void GL_DeleteTexture(gltexture_t *texture); //ericw -- workaround for preventing TexMgr_FreeTexture during TexMgr_ReloadImages -static qboolean in_reload_images; +static bool in_reload_images; /* ================ @@ -688,7 +690,7 @@ static unsigned *TexMgr_MipMapH(unsigned *data, int width, int height) { TexMgr_ResampleTexture -- bilinear resample ================ */ -static unsigned *TexMgr_ResampleTexture(unsigned *in, int inwidth, int inheight, qboolean alpha) { +static unsigned *TexMgr_ResampleTexture(unsigned *in, int inwidth, int inheight, bool alpha) { byte *nwpx, *nepx, *swpx, *sepx, *dest; unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump; unsigned *out; @@ -1047,7 +1049,7 @@ TexMgr_LoadImage8 -- handles 8bit source data, then passes it to LoadImage32 */ static void TexMgr_LoadImage8(gltexture_t *glt, byte *data) { extern convar gl_fullbrights; - qboolean padw = false, padh = false; + bool padw = false, padh = false; byte padbyte; unsigned int *usepal; int i; @@ -1129,7 +1131,7 @@ TexMgr_LoadLightmap -- handles lightmap data ================ */ static void TexMgr_LoadLightmap(gltexture_t *glt, byte *data) { - const qboolean wide10bits = !!r_lightmapwide.value; + const bool wide10bits = !!r_lightmapwide.value; const GLenum type = wide10bits ? GL_UNSIGNED_INT_10_10_10_2 : GL_UNSIGNED_BYTE; const GLint internalfmt = wide10bits ? GL_RGB10_A2 : lightmap_bytes; @@ -1381,7 +1383,7 @@ void TexMgr_ReloadNobrightImages(void) { static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; // to avoid unnecessary texture sets static GLenum currenttarget = GL_TEXTURE0_ARB; -qboolean mtexenabled = false; +bool mtexenabled = false; /* ================ diff --git a/Quake/gl_vidsdl.cpp b/Quake/gl_vidsdl.cpp index e861900..dd7c5e3 100644 --- a/Quake/gl_vidsdl.cpp +++ b/Quake/gl_vidsdl.cpp @@ -71,7 +71,7 @@ static char *gl_extensions_nice; static vmode_t modelist[MAX_MODE_LIST]; static int nummodes; -static qboolean vid_initialized = false; +static bool vid_initialized = false; #if defined(USE_SDL2) static SDL_Window *draw_context; @@ -80,8 +80,8 @@ static SDL_GLContext gl_context; static SDL_Surface *draw_context; #endif -static qboolean vid_locked = false; //johnfitz -static qboolean vid_changed = false; +static bool vid_locked = false; //johnfitz +static bool vid_changed = false; static void VID_Menu_Init(void); //johnfitz static void VID_Menu_f(void); //johnfitz @@ -97,21 +97,21 @@ static void GL_SetupState(void); //johnfitz viddef_t vid; // global video state modestate_t modestate = MS_UNINIT; -qboolean scr_skipupdate; +bool scr_skipupdate; -qboolean gl_mtexable = false; -qboolean gl_packed_pixels = false; -qboolean gl_texture_env_combine = false; //johnfitz -qboolean gl_texture_env_add = false; //johnfitz -qboolean gl_swap_control = false; //johnfitz -qboolean gl_anisotropy_able = false; //johnfitz +bool gl_mtexable = false; +bool gl_packed_pixels = false; +bool gl_texture_env_combine = false; //johnfitz +bool gl_texture_env_add = false; //johnfitz +bool gl_swap_control = false; //johnfitz +bool gl_anisotropy_able = false; //johnfitz float gl_max_anisotropy; //johnfitz -qboolean gl_texture_NPOT = false; //ericw -qboolean gl_vbo_able = false; //ericw -qboolean gl_glsl_able = false; //ericw +bool gl_texture_NPOT = false; //ericw +bool gl_vbo_able = false; //ericw +bool gl_glsl_able = false; //ericw GLint gl_max_texture_units = 0; //ericw -qboolean gl_glsl_gamma_able = false; //ericw -qboolean gl_glsl_alias_able = false; //ericw +bool gl_glsl_gamma_able = false; //ericw +bool gl_glsl_alias_able = false; //ericw int gl_stencilbits; PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc = NULL; //johnfitz @@ -184,7 +184,7 @@ static unsigned short vid_sysgamma_green[256]; static unsigned short vid_sysgamma_blue[256]; #endif -static qboolean gammaworks = false; // whether hw-gamma works +static bool gammaworks = false; // whether hw-gamma works static int fsaa; /* @@ -396,7 +396,7 @@ VID_GetFullscreen returns true if we are in regular fullscreen or "desktop fullscren" ==================== */ -static qboolean VID_GetFullscreen(void) { +static bool VID_GetFullscreen(void) { #if defined(USE_SDL2) return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0; #else @@ -411,7 +411,7 @@ VID_GetDesktopFullscreen returns true if we are specifically in "desktop fullscreen" mode ==================== */ -static qboolean VID_GetDesktopFullscreen(void) { +static bool VID_GetDesktopFullscreen(void) { #if defined(USE_SDL2) return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP; #else @@ -424,7 +424,7 @@ static qboolean VID_GetDesktopFullscreen(void) { VID_GetVSync ==================== */ -static qboolean VID_GetVSync(void) { +static bool VID_GetVSync(void) { #if defined(USE_SDL2) return SDL_GL_GetSwapInterval() == 1; #else @@ -455,7 +455,7 @@ void *VID_GetWindow(void) { VID_HasMouseOrInputFocus ==================== */ -qboolean VID_HasMouseOrInputFocus(void) { +bool VID_HasMouseOrInputFocus(void) { #if defined(USE_SDL2) return (SDL_GetWindowFlags(draw_context) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS)) != 0; #else @@ -468,7 +468,7 @@ qboolean VID_HasMouseOrInputFocus(void) { VID_IsMinimized ==================== */ -qboolean VID_IsMinimized(void) { +bool VID_IsMinimized(void) { #if defined(USE_SDL2) return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN); #else @@ -514,7 +514,7 @@ static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int width, int height, int refre VID_ValidMode ================ */ -static qboolean VID_ValidMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { +static bool VID_ValidMode(int width, int height, int refreshrate, int bpp, bool fullscreen) { // ignore width / height / bpp if vid_desktopfullscreen is enabled if (fullscreen && vid_desktopfullscreen.value) return true; @@ -555,7 +555,7 @@ static qboolean VID_ValidMode(int width, int height, int refreshrate, int bpp, q VID_SetMode ================ */ -static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qboolean fullscreen) { +static bool VID_SetMode(int width, int height, int refreshrate, int bpp, bool fullscreen) { int temp; Uint32 flags; char caption[50]; @@ -570,7 +570,7 @@ static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qbo scr_disabled_for_loading = true; CDAudio_Pause(); - BGM_Pause(); + music::pause(); /* z-buffer depth */ if (bpp == 16) { @@ -722,7 +722,7 @@ static qboolean VID_SetMode(int width, int height, int refreshrate, int bpp, qbo modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; CDAudio_Resume(); - BGM_Resume(); + music::resume(); scr_disabled_for_loading = temp; // fix the leftover Alt from any Alt-Tab or the like that switched us away @@ -760,7 +760,7 @@ VID_Restart -- johnfitz -- change video modes on the fly */ static void VID_Restart(void) { int width, height, refreshrate, bpp; - qboolean fullscreen; + bool fullscreen; if (vid_locked || !vid_changed) return; @@ -815,7 +815,7 @@ static void VID_Restart(void) { : (scr_conscale.value > 0) ? (int) (vid.width / scr_conscale.value) : vid.width; - vid.conwidth = CLAMP(320, vid.conwidth, vid.width); + vid.conwidth = std::clamp(vid.conwidth, 320, vid.width); vid.conwidth &= 0xFFFFFFF8; vid.conheight = vid.conwidth * vid.height / vid.width; // @@ -944,7 +944,7 @@ static void GL_Info_f(void) { GL_CheckExtensions =============== */ -static qboolean GL_ParseExtensionList(const char *list, const char *name) { +static bool GL_ParseExtensionList(const char *list, const char *name) { const char *start; const char *where, *terminator; @@ -972,7 +972,7 @@ static void GL_CheckExtensions(void) { // ARB_vertex_buffer_object // - if (COM_CheckParm("-novbo")) + if (common::check_param("-novbo").has_value()) Con_Warning("Vertex buffer objects disabled at command line\n"); else if (gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) Con_Warning("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n"); @@ -993,7 +993,7 @@ static void GL_CheckExtensions(void) { // multitexture // - if (COM_CheckParm("-nomtex")) + if (common::check_param("-nomtex").has_value()) Con_Warning("Mutitexture disabled at command line\n"); else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) { GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); @@ -1015,7 +1015,7 @@ static void GL_CheckExtensions(void) { // texture_env_combine // - if (COM_CheckParm("-nocombine")) + if (common::check_param("-nocombine").has_value()) Con_Warning("texture_env_combine disabled at command line\n"); else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) { Con_Printf("FOUND: ARB_texture_env_combine\n"); @@ -1029,7 +1029,7 @@ static void GL_CheckExtensions(void) { // texture_env_add // - if (COM_CheckParm("-noadd")) + if (common::check_param("-noadd").has_value()) Con_Warning("texture_env_add disabled at command line\n"); else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) { Con_Printf("FOUND: ARB_texture_env_add\n"); @@ -1110,7 +1110,7 @@ static void GL_CheckExtensions(void) { // texture_non_power_of_two // - if (COM_CheckParm("-notexturenpot")) + if (common::check_param("-notexturenpot").has_value()) Con_Warning("texture_non_power_of_two disabled at command line\n"); else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) { Con_Printf("FOUND: ARB_texture_non_power_of_two\n"); @@ -1121,7 +1121,7 @@ static void GL_CheckExtensions(void) { // GLSL // - if (COM_CheckParm("-noglsl")) + if (common::check_param("-noglsl").has_value()) Con_Warning("GLSL disabled at command line\n"); else if (gl_version_major >= 2) { GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader"); @@ -1183,7 +1183,7 @@ static void GL_CheckExtensions(void) { } // GLSL gamma // - if (COM_CheckParm("-noglslgamma")) + if (common::check_param("-noglslgamma").has_value()) Con_Warning("GLSL gamma disabled at command line\n"); else if (gl_glsl_able) { gl_glsl_gamma_able = true; @@ -1193,7 +1193,7 @@ static void GL_CheckExtensions(void) { } // GLSL alias model rendering // - if (COM_CheckParm("-noglslalias")) + if (common::check_param("-noglslalias").has_value()) Con_Warning("GLSL alias model rendering disabled at command line\n"); else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) { gl_glsl_alias_able = true; @@ -1204,7 +1204,7 @@ static void GL_CheckExtensions(void) { // packed_pixels // - if (COM_CheckParm("-nopackedpixels")) + if (common::check_param("-nopackedpixels").has_value()) Con_Warning("EXT_packed_pixels disabled at command line\n"); else if (gl_glsl_alias_able) { gl_packed_pixels = true; @@ -1223,7 +1223,7 @@ static void GL_CheckExtensions(void) { #endif // glGenerateMipmap for warp textures - if (COM_CheckParm("-nowarpmipmaps")) + if (common::check_param("-nowarpmipmaps").has_value()) Con_Warning("glGenerateMipmap disabled at command line\n"); else { if (gl_version_major >= 3 || GL_ParseExtensionList(gl_extensions, "GL_ARB_framebuffer_object")) { @@ -1305,7 +1305,7 @@ static void GL_Init(void) { //johnfitz -- intel video workarounds from Baker if (!strcmp(gl_vendor, "Intel")) { Con_Printf("Intel Display Adapter detected, enabling gl_clear\n"); - Cbuf_AddText("gl_clear 1"); + command::buffer::add_text("gl_clear 1"); } //johnfitz @@ -1474,7 +1474,7 @@ static void VID_InitModelist(void) { // enumerate fullscreen modes flags = DEFAULT_SDL_FLAGS | SDL_FULLSCREEN; - for (i = 0; i < (int) Q_COUNTOF(bpps); i++) { + for (i = 0; i < (int) std::size(bpps); i++) { if (nummodes >= MAX_MODE_LIST) break; @@ -1520,9 +1520,9 @@ VID_Init */ void VID_Init(void) { static char vid_center[] = "SDL_VIDEO_CENTERED=center"; - int p, width, height, refreshrate, bpp; + int width, height, refreshrate, bpp; int display_width, display_height, display_refreshrate, display_bpp; - qboolean fullscreen; + bool fullscreen; const char *read_vars[] = { "vid_fullscreen", "vid_width", @@ -1534,7 +1534,7 @@ void VID_Init(void) { "vid_desktopfullscreen", "vid_borderless" }; -#define num_readvars Q_COUNTOF(read_vars) +#define num_readvars std::size(read_vars) vid_fullscreen.inscribe(); //johnfitz vid_width.inscribe(); //johnfitz @@ -1604,46 +1604,46 @@ void VID_Init(void) { fullscreen = (int) vid_fullscreen.value; fsaa = (int) vid_fsaa.value; - if (COM_CheckParm("-current")) { + if (common::check_param("-current").has_value()) { width = display_width; height = display_height; refreshrate = display_refreshrate; bpp = display_bpp; fullscreen = true; } else { - p = COM_CheckParm("-width"); - if (p && p < com_argc - 1) { - width = Q_atoi(com_argv[p + 1]); + auto p = common::check_param("-width"); + if (p.has_value() && p.value() < com_argc - 1) { + width = std::atoi(com_argv[p.value() + 1]); - if (!COM_CheckParm("-height")) + if (!common::check_param("-height").has_value()) height = width * 3 / 4; } - p = COM_CheckParm("-height"); - if (p && p < com_argc - 1) { - height = Q_atoi(com_argv[p + 1]); + p = common::check_param("-height"); + if (p.has_value() && p.value() < com_argc - 1) { + height = std::atoi(com_argv[p.value() + 1]); - if (!COM_CheckParm("-width")) + if (!common::check_param("-width").has_value()) width = height * 4 / 3; } - p = COM_CheckParm("-refreshrate"); - if (p && p < com_argc - 1) - refreshrate = Q_atoi(com_argv[p + 1]); + p = common::check_param("-refreshrate"); + if (p.has_value() && p.value() < com_argc - 1) + refreshrate = std::atoi(com_argv[p.value() + 1]); - p = COM_CheckParm("-bpp"); - if (p && p < com_argc - 1) - bpp = Q_atoi(com_argv[p + 1]); + p = common::check_param("-bpp"); + if (p.has_value() && p.value() < com_argc - 1) + bpp = std::atoi(com_argv[p.value() + 1]); - if (COM_CheckParm("-window") || COM_CheckParm("-w")) + if (common::check_param("-window").has_value() || common::check_param("-w").has_value()) fullscreen = false; - else if (COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) + else if (common::check_param("-fullscreen").has_value() || common::check_param("-f").has_value()) fullscreen = true; } - p = COM_CheckParm("-fsaa"); - if (p && p < com_argc - 1) - fsaa = atoi(com_argv[p + 1]); + auto p = common::check_param("-fsaa"); + if (p.has_value() && p.value() < com_argc - 1) + fsaa = atoi(com_argv[p.value() + 1]); if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { width = (int) vid_width.value; @@ -1706,8 +1706,8 @@ void VID_Toggle(void) { // TODO: Clear out the dead code, reinstate the fast path using SDL_SetWindowFullscreen // inside VID_SetMode, check window size to fix WinXP issue. This will // keep all the mode changing code in one place. - static qboolean vid_toggle_works = false; - qboolean toggleWorked; + static bool vid_toggle_works = false; + bool toggleWorked; #if defined(USE_SDL2) Uint32 flags = 0; #endif @@ -1756,7 +1756,7 @@ void VID_Toggle(void) { Con_DPrintf("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); vrestart: vid_fullscreen.set(VID_GetFullscreen() ? "0" : "1"); - Cbuf_AddText("vid_restart\n"); + command::buffer::add_text("vid_restart\n"); } } @@ -2074,10 +2074,10 @@ static void VID_MenuKey(int key) { VID_Menu_ChooseNextRate(1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText("toggle vid_fullscreen\n"); + command::buffer::add_text("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText("toggle vid_vsync\n"); // kristian + command::buffer::add_text("toggle vid_vsync\n"); // kristian break; default: break; @@ -2097,10 +2097,10 @@ static void VID_MenuKey(int key) { VID_Menu_ChooseNextRate(-1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText("toggle vid_fullscreen\n"); + command::buffer::add_text("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText("toggle vid_vsync\n"); + command::buffer::add_text("toggle vid_vsync\n"); break; default: break; @@ -2122,16 +2122,16 @@ static void VID_MenuKey(int key) { VID_Menu_ChooseNextRate(1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText("toggle vid_fullscreen\n"); + command::buffer::add_text("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText("toggle vid_vsync\n"); + command::buffer::add_text("toggle vid_vsync\n"); break; case VID_OPT_TEST: - Cbuf_AddText("vid_test\n"); + command::buffer::add_text("vid_test\n"); break; case VID_OPT_APPLY: - Cbuf_AddText("vid_restart\n"); + command::buffer::add_text("vid_restart\n"); key_dest = key_game; m_state = m_none; IN_Activate(); diff --git a/Quake/gl_warp.cpp b/Quake/gl_warp.cpp index aa34be7..f12ece7 100644 --- a/Quake/gl_warp.cpp +++ b/Quake/gl_warp.cpp @@ -229,7 +229,7 @@ void R_UpdateWarpTextures (void) if (r_oldwater.value || cl.paused || r_drawflat_cheatsafe || r_lightmap_cheatsafe) return; - warptess = 128.0f/CLAMP (3.0f, floorf(r_waterquality.value), 64.0f); + warptess = 128.0f/std::clamp(floorf(r_waterquality.value), 3.0f, 64.0f); for (i=0; inumtextures; i++) { diff --git a/Quake/glquake.hpp b/Quake/glquake.hpp index ecfb3fc..41ee343 100644 --- a/Quake/glquake.hpp +++ b/Quake/glquake.hpp @@ -162,8 +162,8 @@ extern float load_subdivide_size; //johnfitz -- remember what subdivide_size val extern int gl_stencilbits; // Multitexture -extern qboolean mtexenabled; -extern qboolean gl_mtexable; +extern bool mtexenabled; +extern bool gl_mtexable; extern PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc; extern PFNGLACTIVETEXTUREARBPROC GL_SelectTextureFunc; extern PFNGLCLIENTACTIVETEXTUREARBPROC GL_ClientActiveTextureFunc; @@ -173,7 +173,7 @@ extern GLint gl_max_texture_units; //ericw #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF extern float gl_max_anisotropy; -extern qboolean gl_anisotropy_able; +extern bool gl_anisotropy_able; //ericw -- VBO extern PFNGLBINDBUFFERARBPROC GL_BindBufferFunc; @@ -181,7 +181,7 @@ extern PFNGLBUFFERDATAARBPROC GL_BufferDataFunc; extern PFNGLBUFFERSUBDATAARBPROC GL_BufferSubDataFunc; extern PFNGLDELETEBUFFERSARBPROC GL_DeleteBuffersFunc; extern PFNGLGENBUFFERSARBPROC GL_GenBuffersFunc; -extern qboolean gl_vbo_able; +extern bool gl_vbo_able; //ericw //ericw -- GLSL @@ -235,16 +235,16 @@ extern QS_PFNGLUNIFORM1IPROC GL_Uniform1iFunc; extern QS_PFNGLUNIFORM1FPROC GL_Uniform1fFunc; extern QS_PFNGLUNIFORM3FPROC GL_Uniform3fFunc; extern QS_PFNGLUNIFORM4FPROC GL_Uniform4fFunc; -extern qboolean gl_glsl_able; -extern qboolean gl_glsl_gamma_able; -extern qboolean gl_glsl_alias_able; +extern bool gl_glsl_able; +extern bool gl_glsl_gamma_able; +extern bool gl_glsl_alias_able; // ericw -- //mipmapped warp textures extern QS_PFNGENERATEMIPMAP GL_GenerateMipmap; //ericw -- NPOT texture support -extern qboolean gl_texture_NPOT; +extern bool gl_texture_NPOT; //johnfitz -- polygon offset #define OFFSET_BMODEL 1 @@ -258,7 +258,7 @@ void GL_PolygonOffset (int); #ifndef GL_UNSIGNED_INT_10_10_10_2 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #endif -extern qboolean gl_packed_pixels; +extern bool gl_packed_pixels; //johnfitz -- GL_EXT_texture_env_combine //the values for GL_ARB_ are identical @@ -273,8 +273,8 @@ extern qboolean gl_packed_pixels; #define GL_SOURCE1_RGB_EXT 0x8581 #define GL_SOURCE0_ALPHA_EXT 0x8588 #define GL_SOURCE1_ALPHA_EXT 0x8589 -extern qboolean gl_texture_env_combine; -extern qboolean gl_texture_env_add; // for GL_EXT_texture_env_add +extern bool gl_texture_env_combine; +extern bool gl_texture_env_add; // for GL_EXT_texture_env_add //johnfitz -- rendering statistics extern int rs_brushpolys, rs_aliaspolys, rs_skypolys; @@ -316,7 +316,7 @@ struct lightmap_s { gltexture_t *texture; glpoly_t *polys; - qboolean modified; + bool modified; glRect_t rectchange; // the lightmap texture data needs to be kept in @@ -328,7 +328,7 @@ extern int lightmap_count; //allocated lightmaps extern int gl_warpimagesize; //johnfitz -- for water warp -extern qboolean r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz +extern bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz typedef struct glsl_attrib_binding_s { const char *name; @@ -357,9 +357,9 @@ void R_NewGame (void); void R_AnimateLight (void); void R_MarkSurfaces (void); -qboolean R_CullBox (vec3_t emins, vec3_t emaxs); +bool R_CullBox (vec3_t emins, vec3_t emaxs); void R_StoreEfrags (efrag_t **ppefrag); -qboolean R_CullModelForEntity (entity_t *e); +bool R_CullModelForEntity (entity_t *e); void R_RotateForEntity (vec3_t origin, vec3_t angles, unsigned char scale); void R_MarkLights (dlight_t *light, int num, mnode_t *node); diff --git a/Quake/host.cpp b/Quake/host.cpp index d2e799e..b3d0878 100644 --- a/Quake/host.cpp +++ b/Quake/host.cpp @@ -39,67 +39,67 @@ Memory is cleared / released when a server or client begins, not when they end. quakeparms_t *host_parms; -qboolean host_initialized; // true if into command execution +bool host_initialized; // true if into command execution -double host_frametime; -double realtime; // without any filtering or bounding -double oldrealtime; // last frame run +double host_frametime; +double realtime; // without any filtering or bounding +double oldrealtime; // last frame run -int host_framecount; +int host_framecount; -int host_hunklevel; +int host_hunklevel; -int minimum_memory; +int minimum_memory; -client_t *host_client; // current client +client_t *host_client; // current client -jmp_buf host_abortserver; +jmp_buf host_abortserver; -byte *host_colormap; +byte *host_colormap; -convar host_framerate = {"host_framerate","0"}; // set for slow motion -convar host_speeds = {"host_speeds","0"}; // set for running times -convar host_maxfps = {"host_maxfps", "72", {.archive = true}}; //johnfitz -convar host_timescale = {"host_timescale", "0"}; //johnfitz -convar max_edicts = {"max_edicts", "8192"}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE +convar host_framerate = {"host_framerate", "0"}; // set for slow motion +convar host_speeds = {"host_speeds", "0"}; // set for running times +convar host_maxfps = {"host_maxfps", "72", {.archive = true}}; //johnfitz +convar host_timescale = {"host_timescale", "0"}; //johnfitz +convar max_edicts = {"max_edicts", "8192"}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE -convar sys_ticrate = {"sys_ticrate","0.05"}; // dedicated server -convar serverprofile = {"serverprofile","0"}; +convar sys_ticrate = {"sys_ticrate", "0.05"}; // dedicated server +convar serverprofile = {"serverprofile", "0"}; -convar fraglimit = {"fraglimit","0",{.notify = true, .server_info = true}}; -convar timelimit = {"timelimit","0", {.notify = true, .server_info = true}}; -convar teamplay = {"teamplay","0",{.notify = true, .server_info = true}}; -convar samelevel = {"samelevel","0"}; -convar noexit = {"noexit","0",{.notify = true, .server_info = true}}; -convar skill = {"skill","1"}; // 0 - 3 -convar deathmatch = {"deathmatch","0"}; // 0, 1, or 2 -convar coop = {"coop","0"}; // 0 or 1 +convar fraglimit = {"fraglimit", "0", {.notify = true, .server_info = true}}; +convar timelimit = {"timelimit", "0", {.notify = true, .server_info = true}}; +convar teamplay = {"teamplay", "0", {.notify = true, .server_info = true}}; +convar samelevel = {"samelevel", "0"}; +convar noexit = {"noexit", "0", {.notify = true, .server_info = true}}; +convar skill = {"skill", "1"}; // 0 - 3 +convar deathmatch = {"deathmatch", "0"}; // 0, 1, or 2 +convar coop = {"coop", "0"}; // 0 or 1 -convar pausable = {"pausable","1"}; +convar pausable = {"pausable", "1"}; -convar developer = {"developer","0"}; +convar developer = {"developer", "0"}; -convar temp1 = {"temp1","0"}; +convar temp1 = {"temp1", "0"}; -convar devstats = {"devstats","0"}; //johnfitz -- track developer statistics that vary every frame +convar devstats = {"devstats", "0"}; //johnfitz -- track developer statistics that vary every frame -convar campaign = {"campaign","0"}; // for the 2021 rerelease -convar horde = {"horde","0"}; // for the 2021 rerelease -convar sv_cheats = {"sv_cheats","0"}; // for the 2021 rerelease +convar campaign = {"campaign", "0"}; // for the 2021 rerelease +convar horde = {"horde", "0"}; // for the 2021 rerelease +convar sv_cheats = {"sv_cheats", "0"}; // for the 2021 rerelease devstats_t dev_stats, dev_peakstats; -overflowtimes_t dev_overflows; //this stores the last time overflow messages were displayed, not the last time overflows occured +overflowtimes_t dev_overflows; +//this stores the last time overflow messages were displayed, not the last time overflows occured /* ================ Max_Edicts_f -- johnfitz ================ */ -static void Max_Edicts_f (convar *var) -{ - //TODO: clamp it here? - if (cls.state == ca_connected || sv.active) - Con_Printf ("Changes to max_edicts will not take effect until the next time a map is loaded.\n"); +static void Max_Edicts_f(convar *var) { + //TODO: clamp it here? + if (cls.state == ca_connected || sv.active) + Con_Printf("Changes to max_edicts will not take effect until the next time a map is loaded.\n"); } /* @@ -107,10 +107,9 @@ static void Max_Edicts_f (convar *var) Max_Fps_f -- ericw ================ */ -static void Max_Fps_f (convar *var) -{ - if (var->value > 72) - Con_Warning ("host_maxfps above 72 breaks physics.\n"); +static void Max_Fps_f(convar *var) { + if (var->value > 72) + Con_Warning("host_maxfps above 72 breaks physics.\n"); } /* @@ -118,28 +117,27 @@ static void Max_Fps_f (convar *var) Host_EndGame ================ */ -void Host_EndGame (const char *message, ...) -{ - va_list argptr; - char string[1024]; +void Host_EndGame(const char *message, ...) { + va_list argptr; + char string[1024]; - va_start (argptr,message); - q_vsnprintf (string, sizeof(string), message, argptr); - va_end (argptr); - Con_DPrintf ("Host_EndGame: %s\n",string); + va_start(argptr, message); + q_vsnprintf(string, sizeof(string), message, argptr); + va_end(argptr); + Con_DPrintf("Host_EndGame: %s\n", string); - if (sv.active) - Host_ShutdownServer (false); + if (sv.active) + Host_ShutdownServer(false); - if (cls.state == ca_dedicated) - Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit + if (cls.state == ca_dedicated) + Sys_Error("Host_EndGame: %s\n", string); // dedicated servers exit - if (cls.demonum != -1 && !cls.timedemo) - CL_NextDemo (); - else - CL_Disconnect (); + if (cls.demonum != -1 && !cls.timedemo) + CL_NextDemo(); + else + CL_Disconnect(); - longjmp (host_abortserver, 1); + longjmp(host_abortserver, 1); } /* @@ -149,36 +147,35 @@ Host_Error This shuts down both the client and server ================ */ -void Host_Error (const char *error, ...) -{ - va_list argptr; - char string[1024]; - static qboolean inerror = false; +void Host_Error(const char *error, ...) { + va_list argptr; + char string[1024]; + static bool inerror = false; - if (inerror) - Sys_Error ("Host_Error: recursively entered"); - inerror = true; + if (inerror) + Sys_Error("Host_Error: recursively entered"); + inerror = true; - SCR_EndLoadingPlaque (); // reenable screen updates + SCR_EndLoadingPlaque(); // reenable screen updates - va_start (argptr,error); - q_vsnprintf (string, sizeof(string), error, argptr); - va_end (argptr); - Con_Printf ("Host_Error: %s\n",string); + va_start(argptr, error); + q_vsnprintf(string, sizeof(string), error, argptr); + va_end(argptr); + Con_Printf("Host_Error: %s\n", string); - if (sv.active) - Host_ShutdownServer (false); + if (sv.active) + Host_ShutdownServer(false); - if (cls.state == ca_dedicated) - Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit + if (cls.state == ca_dedicated) + Sys_Error("Host_Error: %s\n", string); // dedicated servers exit - CL_Disconnect (); - cls.demonum = -1; - cl.intermission = 0; //johnfitz -- for errors during intermissions (changelevel with no map found, etc.) + CL_Disconnect(); + cls.demonum = -1; + cl.intermission = 0; //johnfitz -- for errors during intermissions (changelevel with no map found, etc.) - inerror = false; + inerror = false; - longjmp (host_abortserver, 1); + longjmp(host_abortserver, 1); } /* @@ -186,64 +183,54 @@ void Host_Error (const char *error, ...) Host_FindMaxClients ================ */ -void Host_FindMaxClients (void) -{ - int i; +void Host_FindMaxClients(void) { + svs.maxclients = 1; - svs.maxclients = 1; + auto i = common::check_param("-dedicated"); + if (i.has_value()) { + cls.state = ca_dedicated; + if (i != (com_argc - 1)) { + svs.maxclients = std::atoi(com_argv[i.value() + 1]); + } else + svs.maxclients = 8; + } else + cls.state = ca_disconnected; - i = COM_CheckParm ("-dedicated"); - if (i) - { - cls.state = ca_dedicated; - if (i != (com_argc - 1)) - { - svs.maxclients = Q_atoi (com_argv[i+1]); - } - else - svs.maxclients = 8; - } - else - cls.state = ca_disconnected; + i = common::check_param("-listen"); + if (i.has_value()) { + if (cls.state == ca_dedicated) + Sys_Error("Only one of -dedicated or -listen can be specified"); + if (i != (com_argc - 1)) + svs.maxclients = std::atoi(com_argv[i.value() + 1]); + else + svs.maxclients = 8; + } + if (svs.maxclients < 1) + svs.maxclients = 8; + else if (svs.maxclients > MAX_SCOREBOARD) + svs.maxclients = MAX_SCOREBOARD; - i = COM_CheckParm ("-listen"); - if (i) - { - if (cls.state == ca_dedicated) - Sys_Error ("Only one of -dedicated or -listen can be specified"); - if (i != (com_argc - 1)) - svs.maxclients = Q_atoi (com_argv[i+1]); - else - svs.maxclients = 8; - } - if (svs.maxclients < 1) - svs.maxclients = 8; - else if (svs.maxclients > MAX_SCOREBOARD) - svs.maxclients = MAX_SCOREBOARD; + svs.maxclientslimit = svs.maxclients; + if (svs.maxclientslimit < 4) + svs.maxclientslimit = 4; + svs.clients = (struct client_s *) Hunk_AllocName(svs.maxclientslimit * sizeof(client_t), "clients"); - svs.maxclientslimit = svs.maxclients; - if (svs.maxclientslimit < 4) - svs.maxclientslimit = 4; - svs.clients = (struct client_s *) Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients"); - - if (svs.maxclients > 1) - deathmatch.set("1"); - else - deathmatch.set("0"); + if (svs.maxclients > 1) + deathmatch.set("1"); + else + deathmatch.set("0"); } -void Host_Version_f (void) -{ - Con_Printf ("Quake Version %1.2f\n", VERSION); - Con_Printf ("QuakeSpasm Version " QUAKESPASM_VER_STRING "\n"); - Con_Printf ("Exe: " __TIME__ " " __DATE__ "\n"); +void Host_Version_f(void) { + Con_Printf("Quake Version %1.2f\n", VERSION); + Con_Printf("QuakeSpasm Version " QUAKESPASM_VER_STRING "\n"); + Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); } /* cvar callback functions : */ -void Host_Callback_Notify (convar *var) -{ - if (sv.active) - SV_BroadcastPrintf ("\"%s\" changed to \"%s\"\n", var->name.c_str(), var->string); +void Host_Callback_Notify(convar *var) { + if (sv.active) + SV_BroadcastPrintf("\"%s\" changed to \"%s\"\n", var->name.c_str(), var->string); } /* @@ -251,49 +238,48 @@ void Host_Callback_Notify (convar *var) Host_InitLocal ====================== */ -void Host_InitLocal (void) -{ - command::add ("version", Host_Version_f); +void Host_InitLocal(void) { + command::add("version", Host_Version_f); - Host_InitCommands (); + Host_InitCommands(); - host_framerate.inscribe(); - host_speeds.inscribe(); - host_maxfps.inscribe(); //johnfitz - host_maxfps.set_callback(Max_Fps_f); - host_timescale.inscribe(); //johnfitz + host_framerate.inscribe(); + host_speeds.inscribe(); + host_maxfps.inscribe(); //johnfitz + host_maxfps.set_callback(Max_Fps_f); + host_timescale.inscribe(); //johnfitz - max_edicts.inscribe(); //johnfitz - max_edicts.set_callback(Max_Edicts_f); - devstats.inscribe(); //johnfitz + max_edicts.inscribe(); //johnfitz + max_edicts.set_callback(Max_Edicts_f); + devstats.inscribe(); //johnfitz - sys_ticrate.inscribe(); - sys_throttle.inscribe(); - serverprofile.inscribe(); + sys_ticrate.inscribe(); + sys_throttle.inscribe(); + serverprofile.inscribe(); - fraglimit.inscribe(); - timelimit.inscribe(); - teamplay.inscribe(); - fraglimit.set_callback(Host_Callback_Notify); - timelimit.set_callback(Host_Callback_Notify); - teamplay.set_callback(Host_Callback_Notify); - samelevel.inscribe(); - noexit.inscribe(); - noexit.set_callback(Host_Callback_Notify); - skill.inscribe(); - developer.inscribe(); - coop.inscribe(); - deathmatch.inscribe(); + fraglimit.inscribe(); + timelimit.inscribe(); + teamplay.inscribe(); + fraglimit.set_callback(Host_Callback_Notify); + timelimit.set_callback(Host_Callback_Notify); + teamplay.set_callback(Host_Callback_Notify); + samelevel.inscribe(); + noexit.inscribe(); + noexit.set_callback(Host_Callback_Notify); + skill.inscribe(); + developer.inscribe(); + coop.inscribe(); + deathmatch.inscribe(); - campaign.inscribe(); - horde.inscribe(); - sv_cheats.inscribe(); + campaign.inscribe(); + horde.inscribe(); + sv_cheats.inscribe(); - pausable.inscribe(); + pausable.inscribe(); - temp1.inscribe(); + temp1.inscribe(); - Host_FindMaxClients (); + Host_FindMaxClients(); } @@ -304,33 +290,30 @@ Host_WriteConfiguration Writes key bindings and archived cvars to config.cfg =============== */ -void Host_WriteConfiguration (void) -{ - FILE *f; +void Host_WriteConfiguration(void) { + FILE *f; -// dedicated servers initialize the host but don't parse and set the -// config.cfg cvars - if (host_initialized && !isDedicated && !host_parms->errstate) - { - f = fopen (va("%s/config.cfg", com_gamedir), "w"); - if (!f) - { - Con_Printf ("Couldn't write config.cfg.\n"); - return; - } + // dedicated servers initialize the host but don't parse and set the + // config.cfg cvars + if (host_initialized && !isDedicated && !host_parms->errstate) { + f = fopen(va("%s/config.cfg", com_gamedir), "w"); + if (!f) { + Con_Printf("Couldn't write config.cfg.\n"); + return; + } - //VID_SyncCvars (); //johnfitz -- write actual current mode to config file, in case cvars were messed with + //VID_SyncCvars (); //johnfitz -- write actual current mode to config file, in case cvars were messed with - Key_WriteBindings (f); - Cvar_WriteVariables (f); + Key_WriteBindings(f); + Cvar_WriteVariables(f); - //johnfitz -- extra commands to preserve state - fprintf (f, "vid_restart\n"); - if (in_mlook.state & 1) fprintf (f, "+mlook\n"); - //johnfitz + //johnfitz -- extra commands to preserve state + fprintf(f, "vid_restart\n"); + if (in_mlook.state & 1) fprintf(f, "+mlook\n"); + //johnfitz - fclose (f); - } + fclose(f); + } } @@ -342,17 +325,16 @@ Sends text across to be displayed FIXME: make this just a stuffed echo? ================= */ -void SV_ClientPrintf (const char *fmt, ...) -{ - va_list argptr; - char string[1024]; +void SV_ClientPrintf(const char *fmt, ...) { + va_list argptr; + char string[1024]; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt,argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - MSG_WriteByte (&host_client->message, svc_print); - MSG_WriteString (&host_client->message, string); + MSG_WriteByte(&host_client->message, svc_print); + MSG_WriteString(&host_client->message, string); } /* @@ -362,24 +344,21 @@ SV_BroadcastPrintf Sends text to all active clients ================= */ -void SV_BroadcastPrintf (const char *fmt, ...) -{ - va_list argptr; - char string[1024]; - int i; +void SV_BroadcastPrintf(const char *fmt, ...) { + va_list argptr; + char string[1024]; + int i; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - for (i = 0; i < svs.maxclients; i++) - { - if (svs.clients[i].active && svs.clients[i].spawned) - { - MSG_WriteByte (&svs.clients[i].message, svc_print); - MSG_WriteString (&svs.clients[i].message, string); - } - } + for (i = 0; i < svs.maxclients; i++) { + if (svs.clients[i].active && svs.clients[i].spawned) { + MSG_WriteByte(&svs.clients[i].message, svc_print); + MSG_WriteString(&svs.clients[i].message, string); + } + } } /* @@ -389,17 +368,16 @@ Host_ClientCommands Send text over to the client to be executed ================= */ -void Host_ClientCommands (const char *fmt, ...) -{ - va_list argptr; - char string[1024]; +void Host_ClientCommands(const char *fmt, ...) { + va_list argptr; + char string[1024]; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - MSG_WriteByte (&host_client->message, svc_stufftext); - MSG_WriteString (&host_client->message, string); + MSG_WriteByte(&host_client->message, svc_stufftext); + MSG_WriteString(&host_client->message, string); } /* @@ -410,59 +388,54 @@ Called when the player is getting totally kicked off the host if (crash = true), don't bother sending signofs ===================== */ -void SV_DropClient (qboolean crash) -{ - int saveSelf; - int i; - client_t *client; +void SV_DropClient(bool crash) { + int saveSelf; + int i; + client_t *client; - if (!crash) - { - // send any final messages (don't check for errors) - if (NET_CanSendMessage (host_client->netconnection)) - { - MSG_WriteByte (&host_client->message, svc_disconnect); - NET_SendMessage (host_client->netconnection, &host_client->message); - } + if (!crash) { + // send any final messages (don't check for errors) + if (NET_CanSendMessage(host_client->netconnection)) { + MSG_WriteByte(&host_client->message, svc_disconnect); + NET_SendMessage(host_client->netconnection, &host_client->message); + } - if (host_client->edict && host_client->spawned) - { - // call the prog function for removing a client - // this will set the body to a dead frame, among other things - saveSelf = pr_global_struct->self; - pr_global_struct->self = EDICT_TO_PROG(host_client->edict); - PR_ExecuteProgram (pr_global_struct->ClientDisconnect); - pr_global_struct->self = saveSelf; - } + if (host_client->edict && host_client->spawned) { + // call the prog function for removing a client + // this will set the body to a dead frame, among other things + saveSelf = pr_global_struct->self; + pr_global_struct->self = EDICT_TO_PROG(host_client->edict); + PR_ExecuteProgram(pr_global_struct->ClientDisconnect); + pr_global_struct->self = saveSelf; + } - Sys_Printf ("Client %s removed\n",host_client->name); - } + Sys_Printf("Client %s removed\n", host_client->name); + } -// break the net connection - NET_Close (host_client->netconnection); - host_client->netconnection = NULL; + // break the net connection + NET_Close(host_client->netconnection); + host_client->netconnection = NULL; -// free the client (the body stays around) - host_client->active = false; - host_client->name[0] = 0; - host_client->old_frags = -999999; - net_activeconnections--; + // free the client (the body stays around) + host_client->active = false; + host_client->name[0] = 0; + host_client->old_frags = -999999; + net_activeconnections--; -// send notification to all clients - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) - { - if (!client->active) - continue; - MSG_WriteByte (&client->message, svc_updatename); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteString (&client->message, ""); - MSG_WriteByte (&client->message, svc_updatefrags); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteShort (&client->message, 0); - MSG_WriteByte (&client->message, svc_updatecolors); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteByte (&client->message, 0); - } + // send notification to all clients + for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { + if (!client->active) + continue; + MSG_WriteByte(&client->message, svc_updatename); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteString(&client->message, ""); + MSG_WriteByte(&client->message, svc_updatefrags); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteShort(&client->message, 0); + MSG_WriteByte(&client->message, svc_updatecolors); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteByte(&client->message, 0); + } } /* @@ -472,67 +445,59 @@ Host_ShutdownServer This only happens at the end of a game, not between levels ================== */ -void Host_ShutdownServer(qboolean crash) -{ - int i; - int count; - sizebuf_t buf; - byte message[4]; - double start; +void Host_ShutdownServer(bool crash) { + int i; + int count; + sizebuf_t buf; + byte message[4]; + double start; - if (!sv.active) - return; + if (!sv.active) + return; - sv.active = false; + sv.active = false; -// stop all client sounds immediately - if (cls.state == ca_connected) - CL_Disconnect (); + // stop all client sounds immediately + if (cls.state == ca_connected) + CL_Disconnect(); -// flush any pending messages - like the score!!! - start = Sys_DoubleTime(); - do - { - count = 0; - for (i=0, host_client = svs.clients ; iactive && host_client->message.cursize) - { - if (NET_CanSendMessage (host_client->netconnection)) - { - NET_SendMessage(host_client->netconnection, &host_client->message); - SZ_Clear (&host_client->message); - } - else - { - NET_GetMessage(host_client->netconnection); - count++; - } - } - } - if ((Sys_DoubleTime() - start) > 3.0) - break; - } - while (count); + // flush any pending messages - like the score!!! + start = Sys_DoubleTime(); + do { + count = 0; + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (host_client->active && host_client->message.cursize) { + if (NET_CanSendMessage(host_client->netconnection)) { + NET_SendMessage(host_client->netconnection, &host_client->message); + SZ_Clear(&host_client->message); + } else { + NET_GetMessage(host_client->netconnection); + count++; + } + } + } + if ((Sys_DoubleTime() - start) > 3.0) + break; + } while (count); -// make sure all the clients know we're disconnecting - buf.data = message; - buf.maxsize = 4; - buf.cursize = 0; - MSG_WriteByte(&buf, svc_disconnect); - count = NET_SendToAll(&buf, 5.0); - if (count) - Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count); + // make sure all the clients know we're disconnecting + buf.data = message; + buf.maxsize = 4; + buf.cursize = 0; + MSG_WriteByte(&buf, svc_disconnect); + count = NET_SendToAll(&buf, 5.0); + if (count) + Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count); - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) - if (host_client->active) - SV_DropClient(crash); + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + if (host_client->active) + SV_DropClient(crash); -// -// clear structures -// -// memset (&sv, 0, sizeof(sv)); // ServerSpawn already do this by Host_ClearMemory - memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t)); + // + // clear structures + // + // memset (&sv, 0, sizeof(sv)); // ServerSpawn already do this by Host_ClearMemory + memset(svs.clients, 0, svs.maxclientslimit * sizeof(client_t)); } @@ -544,18 +509,17 @@ This clears all the memory used by both the client and server, but does not reinitialize anything. ================ */ -void Host_ClearMemory (void) -{ - Con_DPrintf ("Clearing memory\n"); - D_FlushCaches (); - Mod_ClearAll (); - Sky_ClearAll(); -/* host_hunklevel MUST be set at this point */ - Hunk_FreeToLowMark (host_hunklevel); - cls.signon = 0; // not CL_ClearSignons() - free(sv.edicts); // ericw -- sv.edicts switched to use malloc() - memset (&sv, 0, sizeof(sv)); - memset (&cl, 0, sizeof(cl)); +void Host_ClearMemory(void) { + Con_DPrintf("Clearing memory\n"); + D_FlushCaches(); + Mod_ClearAll(); + Sky_ClearAll(); + /* host_hunklevel MUST be set at this point */ + Hunk_FreeToLowMark(host_hunklevel); + cls.signon = 0; // not CL_ClearSignons() + free(sv.edicts); // ericw -- sv.edicts switched to use malloc() + memset(&sv, 0, sizeof(sv)); + memset(&cl, 0, sizeof(cl)); } @@ -572,31 +536,30 @@ Host_FilterTime Returns false if the time is too short to run a frame =================== */ -qboolean Host_FilterTime (float time) -{ - float maxfps; //johnfitz +bool Host_FilterTime(float time) { + float maxfps; //johnfitz - realtime += time; + realtime += time; - //johnfitz -- max fps cvar - maxfps = CLAMP (10.f, host_maxfps.value, 1000.f); - if (!cls.timedemo && realtime - oldrealtime < 1.0/maxfps) - return false; // framerate is too high - //johnfitz + //johnfitz -- max fps cvar + maxfps = std::clamp(host_maxfps.value, 10.f, 1000.f); + if (!cls.timedemo && realtime - oldrealtime < 1.0 / maxfps) + return false; // framerate is too high + //johnfitz - host_frametime = realtime - oldrealtime; - oldrealtime = realtime; + host_frametime = realtime - oldrealtime; + oldrealtime = realtime; - //johnfitz -- host_timescale is more intuitive than host_framerate - if (host_timescale.value > 0) - host_frametime *= host_timescale.value; - //johnfitz - else if (host_framerate.value > 0) - host_frametime = host_framerate.value; - else // don't allow really long or short frames - host_frametime = CLAMP (0.001, host_frametime, 0.1); //johnfitz -- use CLAMP + //johnfitz -- host_timescale is more intuitive than host_framerate + if (host_timescale.value > 0) + host_frametime *= host_timescale.value; + //johnfitz + else if (host_framerate.value > 0) + host_frametime = host_framerate.value; + else // don't allow really long or short frames + host_frametime = std::clamp(host_frametime, 0.001, 0.1); //johnfitz -- use CLAMP - return true; + return true; } /* @@ -606,20 +569,18 @@ Host_GetConsoleCommands Add them exactly as if they had been typed at the console =================== */ -void Host_GetConsoleCommands (void) -{ - const char *cmd; +void Host_GetConsoleCommands(void) { + const char *cmd; - if (!isDedicated) - return; // no stdin necessary in graphical mode + if (!isDedicated) + return; // no stdin necessary in graphical mode - while (1) - { - cmd = Sys_ConsoleInput (); - if (!cmd) - break; - Cbuf_AddText (cmd); - } + while (1) { + cmd = Sys_ConsoleInput(); + if (!cmd) + break; + command::buffer::add_text(cmd); + } } /* @@ -627,46 +588,43 @@ void Host_GetConsoleCommands (void) Host_ServerFrame ================== */ -void Host_ServerFrame (void) -{ - int i, active; //johnfitz - edict_t *ent; //johnfitz +void Host_ServerFrame(void) { + int i, active; //johnfitz + edict_t *ent; //johnfitz -// run the world state - pr_global_struct->frametime = host_frametime; + // run the world state + pr_global_struct->frametime = host_frametime; -// set the time and clear the general datagram - SV_ClearDatagram (); + // set the time and clear the general datagram + SV_ClearDatagram(); -// check for new clients - SV_CheckForNewClients (); + // check for new clients + SV_CheckForNewClients(); -// read client messages - SV_RunClients (); + // read client messages + SV_RunClients(); -// move things around and think -// always pause in single player if in console or menus - if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) ) - SV_Physics (); + // move things around and think + // always pause in single player if in console or menus + if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game)) + SV_Physics(); -//johnfitz -- devstats - if (cls.signon == SIGNONS) - { - for (i=0, active=0; ifree) - active++; - } - if (active > 600 && dev_peakstats.edicts <= 600) - Con_DWarning ("%i edicts exceeds standard limit of 600 (max = %d).\n", active, sv.max_edicts); - dev_stats.edicts = active; - dev_peakstats.edicts = std::max(active, dev_peakstats.edicts); - } -//johnfitz + //johnfitz -- devstats + if (cls.signon == SIGNONS) { + for (i = 0, active = 0; i < sv.num_edicts; i++) { + ent = EDICT_NUM(i); + if (!ent->free) + active++; + } + if (active > 600 && dev_peakstats.edicts <= 600) + Con_DWarning("%i edicts exceeds standard limit of 600 (max = %d).\n", active, sv.max_edicts); + dev_stats.edicts = active; + dev_peakstats.edicts = std::max(active, dev_peakstats.edicts); + } + //johnfitz -// send all messages to the clients - SV_SendClientMessages (); + // send all messages to the clients + SV_SendClientMessages(); } /* @@ -676,138 +634,130 @@ Host_Frame Runs all active servers ================== */ -void _Host_Frame (float time) -{ - static double time1 = 0; - static double time2 = 0; - static double time3 = 0; - int pass1, pass2, pass3; +void _Host_Frame(float time) { + static double time1 = 0; + static double time2 = 0; + static double time3 = 0; + int pass1, pass2, pass3; - if (setjmp (host_abortserver) ) - return; // something bad happened, or the server disconnected + if (setjmp(host_abortserver)) + return; // something bad happened, or the server disconnected -// keep the random time dependent - rand (); + // keep the random time dependent + rand(); -// decide the simulation time - if (!Host_FilterTime (time)) - return; // don't run too fast, or packets will flood out + // decide the simulation time + if (!Host_FilterTime(time)) + return; // don't run too fast, or packets will flood out -// get new key events - Key_UpdateForDest (); - IN_UpdateInputMode (); - Sys_SendKeyEvents (); + // get new key events + Key_UpdateForDest(); + IN_UpdateInputMode(); + Sys_SendKeyEvents(); -// allow mice or other external controllers to add commands - IN_Commands (); + // allow mice or other external controllers to add commands + IN_Commands(); -// process console commands - Cbuf_Execute (); + // process console commands + command::buffer::execute(); - NET_Poll(); + NET_Poll(); -// if running the server locally, make intentions now - if (sv.active) - CL_SendCmd (); + // if running the server locally, make intentions now + if (sv.active) + CL_SendCmd(); -//------------------- -// -// server operations -// -//------------------- + //------------------- + // + // server operations + // + //------------------- -// check for commands typed to the host - Host_GetConsoleCommands (); + // check for commands typed to the host + Host_GetConsoleCommands(); - if (sv.active) - Host_ServerFrame (); + if (sv.active) + Host_ServerFrame(); -//------------------- -// -// client operations -// -//------------------- + //------------------- + // + // client operations + // + //------------------- -// if running the server remotely, send intentions now after -// the incoming messages have been read - if (!sv.active) - CL_SendCmd (); + // if running the server remotely, send intentions now after + // the incoming messages have been read + if (!sv.active) + CL_SendCmd(); -// fetch results from server - if (cls.state == ca_connected) - CL_ReadFromServer (); + // fetch results from server + if (cls.state == ca_connected) + CL_ReadFromServer(); -// update video - if (host_speeds.value) - time1 = Sys_DoubleTime (); + // update video + if (host_speeds.value) + time1 = Sys_DoubleTime(); - SCR_UpdateScreen (); + SCR_UpdateScreen(); - CL_RunParticles (); //johnfitz -- seperated from rendering + CL_RunParticles(); //johnfitz -- seperated from rendering - if (host_speeds.value) - time2 = Sys_DoubleTime (); + if (host_speeds.value) + time2 = Sys_DoubleTime(); -// update audio - BGM_Update(); // adds music raw samples and/or advances midi driver - if (cls.signon == SIGNONS) - { - S_Update (r_origin, vpn, vright, vup); - CL_DecayLights (); - } - else - S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin); + // update audio + music::update(); // adds music raw samples and/or advances midi driver + if (cls.signon == SIGNONS) { + S_Update(r_origin, vpn, vright, vup); + CL_DecayLights(); + } else + S_Update(vec3_origin, vec3_origin, vec3_origin, vec3_origin); - CDAudio_Update(); + CDAudio_Update(); - if (host_speeds.value) - { - pass1 = (time1 - time3)*1000; - time3 = Sys_DoubleTime (); - pass2 = (time2 - time1)*1000; - pass3 = (time3 - time2)*1000; - Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n", - pass1+pass2+pass3, pass1, pass2, pass3); - } - - host_framecount++; + if (host_speeds.value) { + pass1 = (time1 - time3) * 1000; + time3 = Sys_DoubleTime(); + pass2 = (time2 - time1) * 1000; + pass3 = (time3 - time2) * 1000; + Con_Printf("%3i tot %3i server %3i gfx %3i snd\n", + pass1 + pass2 + pass3, pass1, pass2, pass3); + } + host_framecount++; } -void Host_Frame (float time) -{ - double time1, time2; - static double timetotal; - static int timecount; - int i, c, m; +void Host_Frame(float time) { + double time1, time2; + static double timetotal; + static int timecount; + int i, c, m; - if (!serverprofile.value) - { - _Host_Frame (time); - return; - } + if (!serverprofile.value) { + _Host_Frame(time); + return; + } - time1 = Sys_DoubleTime (); - _Host_Frame (time); - time2 = Sys_DoubleTime (); + time1 = Sys_DoubleTime(); + _Host_Frame(time); + time2 = Sys_DoubleTime(); - timetotal += time2 - time1; - timecount++; + timetotal += time2 - time1; + timecount++; - if (timecount < 1000) - return; + if (timecount < 1000) + return; - m = timetotal*1000/timecount; - timecount = 0; - timetotal = 0; - c = 0; - for (i = 0; i < svs.maxclients; i++) - { - if (svs.clients[i].active) - c++; - } + m = timetotal * 1000 / timecount; + timecount = 0; + timetotal = 0; + c = 0; + for (i = 0; i < svs.maxclients; i++) { + if (svs.clients[i].active) + c++; + } - Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m); + Con_Printf("serverprofile: %2i clients %2i msec\n", c, m); } /* @@ -815,92 +765,87 @@ void Host_Frame (float time) Host_Init ==================== */ -void Host_Init (void) -{ - if (standard_quake) - minimum_memory = MINIMUM_MEMORY; - else minimum_memory = MINIMUM_MEMORY_LEVELPAK; +void Host_Init(void) { + if (standard_quake) + minimum_memory = MINIMUM_MEMORY; + else minimum_memory = MINIMUM_MEMORY_LEVELPAK; - if (COM_CheckParm ("-minmemory")) - host_parms->memsize = minimum_memory; + if (common::check_param("-minmemory").has_value()) + host_parms->memsize = minimum_memory; - if (host_parms->memsize < minimum_memory) - Sys_Error ("Only %4.1f megs of memory available, can't execute game", host_parms->memsize / (float)0x100000); + if (host_parms->memsize < minimum_memory) + Sys_Error("Only %4.1f megs of memory available, can't execute game", host_parms->memsize / (float) 0x100000); - com_argc = host_parms->argc; - com_argv = host_parms->argv; + com_argc = host_parms->argc; + com_argv = host_parms->argv; - Memory_Init (host_parms->membase, host_parms->memsize); - Cbuf_Init (); - command::init (); - LOG_Init (host_parms); - Cvar_Init (); //johnfitz - COM_Init (); - COM_InitFilesystem (); - Host_InitLocal (); - W_LoadWadFile (); //johnfitz -- filename is now hard-coded for honesty - if (cls.state != ca_dedicated) - { - Key_Init (); - Con_Init (); - } - PR_Init (); - Mod_Init (); - NET_Init (); - SV_Init (); + Memory_Init(host_parms->membase, host_parms->memsize); + command::buffer::init(); + command::init(); + LOG_Init(host_parms); + Cvar_Init(); //johnfitz + common::init(); + COM_InitFilesystem(); + Host_InitLocal(); + W_LoadWadFile(); //johnfitz -- filename is now hard-coded for honesty + if (cls.state != ca_dedicated) { + Key_Init(); + Con_Init(); + } + PR_Init(); + Mod_Init(); + NET_Init(); + SV_Init(); - Con_Printf ("Exe: " __TIME__ " " __DATE__ "\n"); - Con_Printf ("%4.1f megabyte heap\n", host_parms->memsize/ (1024*1024.0)); + Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); + Con_Printf("%4.1f megabyte heap\n", host_parms->memsize / (1024 * 1024.0)); - if (cls.state != ca_dedicated) - { - host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", NULL); - if (!host_colormap) - Sys_Error ("Couldn't load gfx/colormap.lmp"); + if (cls.state != ca_dedicated) { + host_colormap = (byte *) COM_LoadHunkFile("gfx/colormap.lmp", NULL); + if (!host_colormap) + Sys_Error("Couldn't load gfx/colormap.lmp"); - V_Init (); - Chase_Init (); - M_Init (); - ExtraMaps_Init (); //johnfitz - Modlist_Init (); //johnfitz - DemoList_Init (); //ericw - VID_Init (); - IN_Init (); - TexMgr_Init (); //johnfitz - Draw_Init (); - SCR_Init (); - R_Init (); - S_Init (); - CDAudio_Init (); - BGM_Init(); - Sbar_Init (); - CL_Init (); - } + V_Init(); + Chase_Init(); + M_Init(); + ExtraMaps_Init(); //johnfitz + Modlist_Init(); //johnfitz + DemoList_Init(); //ericw + VID_Init(); + IN_Init(); + TexMgr_Init(); //johnfitz + Draw_Init(); + SCR_Init(); + R_Init(); + S_Init(); + CDAudio_Init(); + music::init(); + Sbar_Init(); + CL_Init(); + } - LOC_Init (); // for 2021 rerelease support. + LOC_Init(); // for 2021 rerelease support. - Hunk_AllocName (0, "-HOST_HUNKLEVEL-"); - host_hunklevel = Hunk_LowMark (); + Hunk_AllocName(0, "-HOST_HUNKLEVEL-"); + host_hunklevel = Hunk_LowMark(); - host_initialized = true; - Con_Printf ("\n========= Quake Initialized =========\n\n"); + host_initialized = true; + Con_Printf("\n========= Quake Initialized =========\n\n"); - if (cls.state != ca_dedicated) - { - Cbuf_InsertText ("exec quake.rc\n"); - // johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now. - // note: two leading newlines because the command buffer swallows one of them. - Cbuf_AddText ("\n\nvid_unlock\n"); - } + if (cls.state != ca_dedicated) { + command::buffer::insert_text("exec quake.rc\n"); + // johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now. + // note: two leading newlines because the command buffer swallows one of them. + command::buffer::add_text("\n\nvid_unlock\n"); + } - if (cls.state == ca_dedicated) - { - Cbuf_AddText ("exec autoexec.cfg\n"); - Cbuf_AddText ("stuffcmds"); - Cbuf_Execute (); - if (!sv.active) - Cbuf_AddText ("map start\n"); - } + if (cls.state == ca_dedicated) { + command::buffer::add_text("exec autoexec.cfg\n"); + command::buffer::add_text("stuffcmds"); + command::buffer::execute(); + if (!sv.active) + command::buffer::add_text("map start\n"); + } } @@ -912,36 +857,33 @@ FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better to run quit through here before the final handoff to the sys code. =============== */ -void Host_Shutdown(void) -{ - static qboolean isdown = false; +void Host_Shutdown(void) { + static bool isdown = false; - if (isdown) - { - printf ("recursive shutdown\n"); - return; - } - isdown = true; + if (isdown) { + printf("recursive shutdown\n"); + return; + } + isdown = true; -// keep Con_Printf from trying to update the screen - scr_disabled_for_loading = true; + // keep Con_Printf from trying to update the screen + scr_disabled_for_loading = true; - Host_WriteConfiguration (); + Host_WriteConfiguration(); - NET_Shutdown (); + NET_Shutdown(); - if (cls.state != ca_dedicated) - { - if (con_initialized) - History_Shutdown (); - BGM_Shutdown(); - CDAudio_Shutdown (); - S_Shutdown (); - IN_Shutdown (); - VID_Shutdown(); - } + if (cls.state != ca_dedicated) { + if (con_initialized) + History_Shutdown(); + music::shutdown(); + CDAudio_Shutdown(); + S_Shutdown(); + IN_Shutdown(); + VID_Shutdown(); + } - LOG_Close (); + LOG_Close(); - LOC_Shutdown (); + LOC_Shutdown(); } diff --git a/Quake/host_cmd.cpp b/Quake/host_cmd.cpp index 71edfca..9e70b93 100644 --- a/Quake/host_cmd.cpp +++ b/Quake/host_cmd.cpp @@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include #include #include "quakedef.hpp" @@ -28,26 +29,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include #endif -extern convar pausable; +extern convar pausable; -int current_skill; +int current_skill; /* ================== Host_Quit_f ================== */ -void Host_Quit_f (void) -{ - if (key_dest != key_console && cls.state != ca_dedicated) - { - M_Menu_Quit_f (); - return; - } - CL_Disconnect (); - Host_ShutdownServer(false); +void Host_Quit_f(void) { + if (key_dest != key_console && cls.state != ca_dedicated) { + M_Menu_Quit_f(); + return; + } + CL_Disconnect(); + Host_ShutdownServer(false); - Sys_Quit (); + Sys_Quit(); } //============================================================================== @@ -59,139 +58,123 @@ void Host_Quit_f (void) FileList_Add ================== */ -static void FileList_Add (const char *name, filelist_item_t **list) -{ - filelist_item_t *item,*cursor,*prev; +static void FileList_Add(const char *name, filelist_item_t **list) { + filelist_item_t *item, *cursor, *prev; - // ignore duplicate - for (item = *list; item; item = item->next) - { - if (!Q_strcmp (name, item->name)) - return; - } + // ignore duplicate + for (item = *list; item; item = item->next) { + if (!std::strcmp(name, item->name)) + return; + } - item = (filelist_item_t *) Z_Malloc(sizeof(filelist_item_t)); - q_strlcpy (item->name, name, sizeof(item->name)); + item = (filelist_item_t *) Z_Malloc(sizeof(filelist_item_t)); + q_strlcpy(item->name, name, sizeof(item->name)); - // insert each entry in alphabetical order - if (*list == NULL || - q_strcasecmp(item->name, (*list)->name) < 0) //insert at front - { - item->next = *list; - *list = item; - } - else //insert later - { - prev = *list; - cursor = (*list)->next; - while (cursor && (q_strcasecmp(item->name, cursor->name) > 0)) - { - prev = cursor; - cursor = cursor->next; - } - item->next = prev->next; - prev->next = item; - } + // insert each entry in alphabetical order + if (*list == NULL || + q_strcasecmp(item->name, (*list)->name) < 0) //insert at front + { + item->next = *list; + *list = item; + } else //insert later + { + prev = *list; + cursor = (*list)->next; + while (cursor && (q_strcasecmp(item->name, cursor->name) > 0)) { + prev = cursor; + cursor = cursor->next; + } + item->next = prev->next; + prev->next = item; + } } -static void FileList_Clear (filelist_item_t **list) -{ - filelist_item_t *blah; +static void FileList_Clear(filelist_item_t **list) { + filelist_item_t *blah; - while (*list) - { - blah = (*list)->next; - Z_Free(*list); - *list = blah; - } + while (*list) { + blah = (*list)->next; + Z_Free(*list); + *list = blah; + } } -filelist_item_t *extralevels; +filelist_item_t *extralevels; -static void ExtraMaps_Add (const char *name) -{ - FileList_Add(name, &extralevels); +static void ExtraMaps_Add(const char *name) { + FileList_Add(name, &extralevels); } -void ExtraMaps_Init (void) -{ +void ExtraMaps_Init(void) { #ifdef _WIN32 - WIN32_FIND_DATA fdat; - HANDLE fhnd; + WIN32_FIND_DATA fdat; + HANDLE fhnd; #else - DIR *dir_p; - struct dirent *dir_t; + DIR *dir_p; + struct dirent *dir_t; #endif - char filestring[MAX_OSPATH]; - char mapname[32]; - char ignorepakdir[32]; - searchpath_t *search; - pack_t *pak; - int i; + char filestring[MAX_OSPATH]; + char mapname[32]; + char ignorepakdir[32]; + searchpath_t *search; + pack_t *pak; + int i; - // we don't want to list the maps in id1 pakfiles, - // because these are not "add-on" levels - q_snprintf (ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); + // we don't want to list the maps in id1 pakfiles, + // because these are not "add-on" levels + q_snprintf(ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); - for (search = com_searchpaths; search; search = search->next) - { - if (*search->filename) //directory - { + for (search = com_searchpaths; search; search = search->next) { + if (*search->filename) //directory + { #ifdef _WIN32 - q_snprintf (filestring, sizeof(filestring), "%s/maps/*.bsp", search->filename); - fhnd = FindFirstFile(filestring, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) - continue; - do - { - COM_StripExtension(fdat.cFileName, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); - } while (FindNextFile(fhnd, &fdat)); - FindClose(fhnd); + q_snprintf(filestring, sizeof(filestring), "%s/maps/*.bsp", search->filename); + fhnd = FindFirstFile(filestring, &fdat); + if (fhnd == INVALID_HANDLE_VALUE) + continue; + do { + COM_StripExtension(fdat.cFileName, mapname, sizeof(mapname)); + ExtraMaps_Add(mapname); + } while (FindNextFile(fhnd, &fdat)); + FindClose(fhnd); #else - q_snprintf (filestring, sizeof(filestring), "%s/maps/", search->filename); - dir_p = opendir(filestring); - if (dir_p == NULL) - continue; - while ((dir_t = readdir(dir_p)) != NULL) - { - if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "bsp") != 0) - continue; - COM_StripExtension(dir_t->d_name, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); - } - closedir(dir_p); + q_snprintf(filestring, sizeof(filestring), "%s/maps/", search->filename); + dir_p = opendir(filestring); + if (dir_p == NULL) + continue; + while ((dir_t = readdir(dir_p)) != NULL) { + if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "bsp") != 0) + continue; + COM_StripExtension(dir_t->d_name, mapname, sizeof(mapname)); + ExtraMaps_Add(mapname); + } + closedir(dir_p); #endif - } - else //pakfile - { - if (!strstr(search->pack->filename, ignorepakdir)) - { //don't list standard id maps - for (i = 0, pak = search->pack; i < pak->numfiles; i++) - { - if (!strcmp(COM_FileGetExtension(pak->files[i].name), "bsp")) - { - if (pak->files[i].filelen > 32*1024) - { // don't list files under 32k (ammo boxes etc) - COM_StripExtension(pak->files[i].name + 5, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); - } - } - } - } - } - } + } else //pakfile + { + if (!strstr(search->pack->filename, ignorepakdir)) { + //don't list standard id maps + for (i = 0, pak = search->pack; i < pak->numfiles; i++) { + if (!strcmp(COM_FileGetExtension(pak->files[i].name), "bsp")) { + if (pak->files[i].filelen > 32 * 1024) { + // don't list files under 32k (ammo boxes etc) + COM_StripExtension(pak->files[i].name + 5, mapname, sizeof(mapname)); + ExtraMaps_Add(mapname); + } + } + } + } + } + } } -static void ExtraMaps_Clear (void) -{ - FileList_Clear(&extralevels); +static void ExtraMaps_Clear(void) { + FileList_Clear(&extralevels); } -void ExtraMaps_NewGame (void) -{ - ExtraMaps_Clear (); - ExtraMaps_Init (); +void ExtraMaps_NewGame(void) { + ExtraMaps_Clear(); + ExtraMaps_Init(); } /* @@ -199,86 +182,80 @@ void ExtraMaps_NewGame (void) Host_Maps_f ================== */ -static void Host_Maps_f (void) -{ - int i; - filelist_item_t *level; +static void Host_Maps_f(void) { + int i; + filelist_item_t *level; - for (level = extralevels, i = 0; level; level = level->next, i++) - Con_SafePrintf (" %s\n", level->name); + for (level = extralevels, i = 0; level; level = level->next, i++) + Con_SafePrintf(" %s\n", level->name); - if (i) - Con_SafePrintf ("%i map(s)\n", i); - else - Con_SafePrintf ("no maps found\n"); + if (i) + Con_SafePrintf("%i map(s)\n", i); + else + Con_SafePrintf("no maps found\n"); } //============================================================================== //johnfitz -- modlist management //============================================================================== -filelist_item_t *modlist; +filelist_item_t *modlist; -static void Modlist_Add (const char *name) -{ - FileList_Add(name, &modlist); +static void Modlist_Add(const char *name) { + FileList_Add(name, &modlist); } #ifdef _WIN32 -void Modlist_Init (void) -{ - WIN32_FIND_DATA fdat; - HANDLE fhnd; - DWORD attribs; - char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; +void Modlist_Init(void) { + WIN32_FIND_DATA fdat; + HANDLE fhnd; + DWORD attribs; + char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; - q_snprintf (dir_string, sizeof(dir_string), "%s/*", com_basedir); - fhnd = FindFirstFile(dir_string, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) - return; + q_snprintf(dir_string, sizeof(dir_string), "%s/*", com_basedir); + fhnd = FindFirstFile(dir_string, &fdat); + if (fhnd == INVALID_HANDLE_VALUE) + return; - do - { - if (!strcmp(fdat.cFileName, ".") || !strcmp(fdat.cFileName, "..")) - continue; - q_snprintf (mod_string, sizeof(mod_string), "%s/%s", com_basedir, fdat.cFileName); - attribs = GetFileAttributes (mod_string); - if (attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY)) { - /* don't bother testing for pak files / progs.dat */ - Modlist_Add(fdat.cFileName); - } - } while (FindNextFile(fhnd, &fdat)); + do { + if (!strcmp(fdat.cFileName, ".") || !strcmp(fdat.cFileName, "..")) + continue; + q_snprintf(mod_string, sizeof(mod_string), "%s/%s", com_basedir, fdat.cFileName); + attribs = GetFileAttributes(mod_string); + if (attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY)) { + /* don't bother testing for pak files / progs.dat */ + Modlist_Add(fdat.cFileName); + } + } while (FindNextFile(fhnd, &fdat)); - FindClose(fhnd); + FindClose(fhnd); } #else -void Modlist_Init (void) -{ - DIR *dir_p, *mod_dir_p; - struct dirent *dir_t; - char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; +void Modlist_Init(void) { + DIR *dir_p, *mod_dir_p; + struct dirent *dir_t; + char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; - q_snprintf (dir_string, sizeof(dir_string), "%s/", com_basedir); - dir_p = opendir(dir_string); - if (dir_p == NULL) - return; + q_snprintf(dir_string, sizeof(dir_string), "%s/", com_basedir); + dir_p = opendir(dir_string); + if (dir_p == NULL) + return; - while ((dir_t = readdir(dir_p)) != NULL) - { - if (!strcmp(dir_t->d_name, ".") || !strcmp(dir_t->d_name, "..")) - continue; - if (!q_strcasecmp (COM_FileGetExtension (dir_t->d_name), "app")) // skip .app bundles on macOS - continue; - q_snprintf(mod_string, sizeof(mod_string), "%s%s/", dir_string, dir_t->d_name); - mod_dir_p = opendir(mod_string); - if (mod_dir_p == NULL) - continue; - /* don't bother testing for pak files / progs.dat */ - Modlist_Add(dir_t->d_name); - closedir(mod_dir_p); - } + while ((dir_t = readdir(dir_p)) != NULL) { + if (!strcmp(dir_t->d_name, ".") || !strcmp(dir_t->d_name, "..")) + continue; + if (!q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "app")) // skip .app bundles on macOS + continue; + q_snprintf(mod_string, sizeof(mod_string), "%s%s/", dir_string, dir_t->d_name); + mod_dir_p = opendir(mod_string); + if (mod_dir_p == NULL) + continue; + /* don't bother testing for pak files / progs.dat */ + Modlist_Add(dir_t->d_name); + closedir(mod_dir_p); + } - closedir(dir_p); + closedir(dir_p); } #endif @@ -286,85 +263,76 @@ void Modlist_Init (void) //ericw -- demo list management //============================================================================== -filelist_item_t *demolist; +filelist_item_t *demolist; -static void DemoList_Clear (void) -{ - FileList_Clear (&demolist); +static void DemoList_Clear(void) { + FileList_Clear(&demolist); } -void DemoList_Rebuild (void) -{ - DemoList_Clear (); - DemoList_Init (); +void DemoList_Rebuild(void) { + DemoList_Clear(); + DemoList_Init(); } // TODO: Factor out to a general-purpose file searching function -void DemoList_Init (void) -{ +void DemoList_Init(void) { #ifdef _WIN32 - WIN32_FIND_DATA fdat; - HANDLE fhnd; + WIN32_FIND_DATA fdat; + HANDLE fhnd; #else - DIR *dir_p; - struct dirent *dir_t; + DIR *dir_p; + struct dirent *dir_t; #endif - char filestring[MAX_OSPATH]; - char demname[32]; - char ignorepakdir[32]; - searchpath_t *search; - pack_t *pak; - int i; + char filestring[MAX_OSPATH]; + char demname[32]; + char ignorepakdir[32]; + searchpath_t *search; + pack_t *pak; + int i; - // we don't want to list the demos in id1 pakfiles, - // because these are not "add-on" demos - q_snprintf (ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); - - for (search = com_searchpaths; search; search = search->next) - { - if (*search->filename) //directory - { + // we don't want to list the demos in id1 pakfiles, + // because these are not "add-on" demos + q_snprintf(ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); + + for (search = com_searchpaths; search; search = search->next) { + if (*search->filename) //directory + { #ifdef _WIN32 - q_snprintf (filestring, sizeof(filestring), "%s/*.dem", search->filename); - fhnd = FindFirstFile(filestring, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) - continue; - do - { - COM_StripExtension(fdat.cFileName, demname, sizeof(demname)); - FileList_Add (demname, &demolist); - } while (FindNextFile(fhnd, &fdat)); - FindClose(fhnd); + q_snprintf(filestring, sizeof(filestring), "%s/*.dem", search->filename); + fhnd = FindFirstFile(filestring, &fdat); + if (fhnd == INVALID_HANDLE_VALUE) + continue; + do { + COM_StripExtension(fdat.cFileName, demname, sizeof(demname)); + FileList_Add(demname, &demolist); + } while (FindNextFile(fhnd, &fdat)); + FindClose(fhnd); #else - q_snprintf (filestring, sizeof(filestring), "%s/", search->filename); - dir_p = opendir(filestring); - if (dir_p == NULL) - continue; - while ((dir_t = readdir(dir_p)) != NULL) - { - if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "dem") != 0) - continue; - COM_StripExtension(dir_t->d_name, demname, sizeof(demname)); - FileList_Add (demname, &demolist); - } - closedir(dir_p); + q_snprintf(filestring, sizeof(filestring), "%s/", search->filename); + dir_p = opendir(filestring); + if (dir_p == NULL) + continue; + while ((dir_t = readdir(dir_p)) != NULL) { + if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "dem") != 0) + continue; + COM_StripExtension(dir_t->d_name, demname, sizeof(demname)); + FileList_Add(demname, &demolist); + } + closedir(dir_p); #endif - } - else //pakfile - { - if (!strstr(search->pack->filename, ignorepakdir)) - { //don't list standard id demos - for (i = 0, pak = search->pack; i < pak->numfiles; i++) - { - if (!strcmp(COM_FileGetExtension(pak->files[i].name), "dem")) - { - COM_StripExtension(pak->files[i].name, demname, sizeof(demname)); - FileList_Add (demname, &demolist); - } - } - } - } - } + } else //pakfile + { + if (!strstr(search->pack->filename, ignorepakdir)) { + //don't list standard id demos + for (i = 0, pak = search->pack; i < pak->numfiles; i++) { + if (!strcmp(COM_FileGetExtension(pak->files[i].name), "dem")) { + COM_StripExtension(pak->files[i].name, demname, sizeof(demname)); + FileList_Add(demname, &demolist); + } + } + } + } + } } /* @@ -374,18 +342,17 @@ Host_Mods_f -- johnfitz list all potential mod directories (contain either a pak file or a progs.dat) ================== */ -static void Host_Mods_f (void) -{ - int i; - filelist_item_t *mod; +static void Host_Mods_f(void) { + int i; + filelist_item_t *mod; - for (mod = modlist, i=0; mod; mod = mod->next, i++) - Con_SafePrintf (" %s\n", mod->name); + for (mod = modlist, i = 0; mod; mod = mod->next, i++) + Con_SafePrintf(" %s\n", mod->name); - if (i) - Con_SafePrintf ("%i mod(s)\n", i); - else - Con_SafePrintf ("no mods found\n"); + if (i) + Con_SafePrintf("%i mod(s)\n", i); + else + Con_SafePrintf("no mods found\n"); } //============================================================================== @@ -395,21 +362,18 @@ static void Host_Mods_f (void) Host_Mapname_f -- johnfitz ============= */ -static void Host_Mapname_f (void) -{ - if (sv.active) - { - Con_Printf ("\"mapname\" is \"%s\"\n", sv.name); - return; - } +static void Host_Mapname_f(void) { + if (sv.active) { + Con_Printf("\"mapname\" is \"%s\"\n", sv.name); + return; + } - if (cls.state == ca_connected) - { - Con_Printf ("\"mapname\" is \"%s\"\n", cl.mapname); - return; - } + if (cls.state == ca_connected) { + Con_Printf("\"mapname\" is \"%s\"\n", cl.mapname); + return; + } - Con_Printf ("no map loaded\n"); + Con_Printf("no map loaded\n"); } /* @@ -417,54 +381,48 @@ static void Host_Mapname_f (void) Host_Status_f ================== */ -static void Host_Status_f (void) -{ - void (*print_fn) (const char *fmt, ...) - FUNCP_PRINTF(1,2); - client_t *client; - int seconds; - int minutes; - int hours = 0; - int j; +static void Host_Status_f(void) { + void (*print_fn)(const char *fmt, ...) + FUNCP_PRINTF(1, 2); + client_t *client; + int seconds; + int minutes; + int hours = 0; + int j; - if (command::last_source == command::source::command) - { - if (!sv.active) - { - command::forward_to_server (); - return; - } - print_fn = Con_Printf; - } - else - print_fn = SV_ClientPrintf; + if (command::last_source == command::source::command) { + if (!sv.active) { + command::forward_to_server(); + return; + } + print_fn = Con_Printf; + } else + print_fn = SV_ClientPrintf; - print_fn ("host: %s\n", convar::variable_string("hostname").value_or("").c_str()); - print_fn ("version: %4.2f\n", VERSION); - if (tcpipAvailable) - print_fn ("tcp/ip: %s\n", my_tcpip_address); - if (ipxAvailable) - print_fn ("ipx: %s\n", my_ipx_address); - print_fn ("map: %s\n", sv.name); - print_fn ("players: %i active (%i max)\n\n", net_activeconnections, svs.maxclients); - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) - { - if (!client->active) - continue; - seconds = (int)(net_time - NET_QSocketGetTime(client->netconnection)); - minutes = seconds / 60; - if (minutes) - { - seconds -= (minutes * 60); - hours = minutes / 60; - if (hours) - minutes -= (hours * 60); - } - else - hours = 0; - print_fn ("#%-2u %-16.16s %3i %2i:%02i:%02i\n", j+1, client->name, (int)client->edict->v.frags, hours, minutes, seconds); - print_fn (" %s\n", NET_QSocketGetAddressString(client->netconnection)); - } + print_fn("host: %s\n", convar::variable_string("hostname").value_or("").c_str()); + print_fn("version: %4.2f\n", VERSION); + if (tcpipAvailable) + print_fn("tcp/ip: %s\n", my_tcpip_address); + if (ipxAvailable) + print_fn("ipx: %s\n", my_ipx_address); + print_fn("map: %s\n", sv.name); + print_fn("players: %i active (%i max)\n\n", net_activeconnections, svs.maxclients); + for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { + if (!client->active) + continue; + seconds = (int) (net_time - NET_QSocketGetTime(client->netconnection)); + minutes = seconds / 60; + if (minutes) { + seconds -= (minutes * 60); + hours = minutes / 60; + if (hours) + minutes -= (hours * 60); + } else + hours = 0; + print_fn("#%-2u %-16.16s %3i %2i:%02i:%02i\n", j + 1, client->name, (int) client->edict->v.frags, hours, + minutes, seconds); + print_fn(" %s\n", NET_QSocketGetAddressString(client->netconnection)); + } } /* @@ -474,61 +432,54 @@ Host_God_f Sets client to godmode ================== */ -static void Host_God_f (void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_God_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - //johnfitz -- allow user to explicitly set god mode to on or off - switch (command::argc()) - { - case 1: - sv_player->v.flags = (int)sv_player->v.flags ^ FL_GODMODE; - if (!((int)sv_player->v.flags & FL_GODMODE) ) - SV_ClientPrintf ("godmode OFF\n"); - else - SV_ClientPrintf ("godmode ON\n"); - break; - case 2: - if (Q_atof(command::argv(1)->c_str())) - { - sv_player->v.flags = (int)sv_player->v.flags | FL_GODMODE; - SV_ClientPrintf ("godmode ON\n"); - } - else - { - sv_player->v.flags = (int)sv_player->v.flags & ~FL_GODMODE; - SV_ClientPrintf ("godmode OFF\n"); - } - break; - default: - Con_Printf("god [value] : toggle god mode. values: 0 = off, 1 = on\n"); - break; - } - //johnfitz + //johnfitz -- allow user to explicitly set god mode to on or off + switch (command::argc()) { + case 1: + sv_player->v.flags = (int) sv_player->v.flags ^ FL_GODMODE; + if (!((int) sv_player->v.flags & FL_GODMODE)) + SV_ClientPrintf("godmode OFF\n"); + else + SV_ClientPrintf("godmode ON\n"); + break; + case 2: + if (std::atof(command::argv(1)->c_str())) { + sv_player->v.flags = (int) sv_player->v.flags | FL_GODMODE; + SV_ClientPrintf("godmode ON\n"); + } else { + sv_player->v.flags = (int) sv_player->v.flags & ~FL_GODMODE; + SV_ClientPrintf("godmode OFF\n"); + } + break; + default: + Con_Printf("god [value] : toggle god mode. values: 0 = off, 1 = on\n"); + break; + } + //johnfitz } -static void Host_Buddha_f (void) { - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_Buddha_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - sv_player->v.flags = (int)sv_player->v.flags ^ FL_BUDDHAMODE; - if (!((int)sv_player->v.flags & FL_BUDDHAMODE) ) - SV_ClientPrintf ("buddha mode OFF\n"); - else - SV_ClientPrintf ("buddha mode ON\n"); + sv_player->v.flags = (int) sv_player->v.flags ^ FL_BUDDHAMODE; + if (!((int) sv_player->v.flags & FL_BUDDHAMODE)) + SV_ClientPrintf("buddha mode OFF\n"); + else + SV_ClientPrintf("buddha mode ON\n"); } /* @@ -536,100 +487,85 @@ static void Host_Buddha_f (void) { Host_Notarget_f ================== */ -static void Host_Notarget_f (void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_Notarget_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - //johnfitz -- allow user to explicitly set notarget to on or off - switch (command::argc()) - { - case 1: - sv_player->v.flags = (int)sv_player->v.flags ^ FL_NOTARGET; - if (!((int)sv_player->v.flags & FL_NOTARGET) ) - SV_ClientPrintf ("notarget OFF\n"); - else - SV_ClientPrintf ("notarget ON\n"); - break; - case 2: - if (Q_atof(command::argv(1)->c_str())) - { - sv_player->v.flags = (int)sv_player->v.flags | FL_NOTARGET; - SV_ClientPrintf ("notarget ON\n"); - } - else - { - sv_player->v.flags = (int)sv_player->v.flags & ~FL_NOTARGET; - SV_ClientPrintf ("notarget OFF\n"); - } - break; - default: - Con_Printf("notarget [value] : toggle notarget mode. values: 0 = off, 1 = on\n"); - break; - } - //johnfitz + //johnfitz -- allow user to explicitly set notarget to on or off + switch (command::argc()) { + case 1: + sv_player->v.flags = (int) sv_player->v.flags ^ FL_NOTARGET; + if (!((int) sv_player->v.flags & FL_NOTARGET)) + SV_ClientPrintf("notarget OFF\n"); + else + SV_ClientPrintf("notarget ON\n"); + break; + case 2: + if (std::atof(command::argv(1)->c_str())) { + sv_player->v.flags = (int) sv_player->v.flags | FL_NOTARGET; + SV_ClientPrintf("notarget ON\n"); + } else { + sv_player->v.flags = (int) sv_player->v.flags & ~FL_NOTARGET; + SV_ClientPrintf("notarget OFF\n"); + } + break; + default: + Con_Printf("notarget [value] : toggle notarget mode. values: 0 = off, 1 = on\n"); + break; + } + //johnfitz } -qboolean noclip_anglehack; +bool noclip_anglehack; /* ================== Host_Noclip_f ================== */ -static void Host_Noclip_f (void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_Noclip_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - //johnfitz -- allow user to explicitly set noclip to on or off - switch (command::argc()) - { - case 1: - if (sv_player->v.movetype != MOVETYPE_NOCLIP) - { - noclip_anglehack = true; - sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); - } - else - { - noclip_anglehack = false; - sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("noclip OFF\n"); - } - break; - case 2: - if (Q_atof(command::argv(1)->c_str())) - { - noclip_anglehack = true; - sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); - } - else - { - noclip_anglehack = false; - sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("noclip OFF\n"); - } - break; - default: - Con_Printf("noclip [value] : toggle noclip mode. values: 0 = off, 1 = on\n"); - break; - } - //johnfitz + //johnfitz -- allow user to explicitly set noclip to on or off + switch (command::argc()) { + case 1: + if (sv_player->v.movetype != MOVETYPE_NOCLIP) { + noclip_anglehack = true; + sv_player->v.movetype = MOVETYPE_NOCLIP; + SV_ClientPrintf("noclip ON\n"); + } else { + noclip_anglehack = false; + sv_player->v.movetype = MOVETYPE_WALK; + SV_ClientPrintf("noclip OFF\n"); + } + break; + case 2: + if (std::atof(command::argv(1)->c_str())) { + noclip_anglehack = true; + sv_player->v.movetype = MOVETYPE_NOCLIP; + SV_ClientPrintf("noclip ON\n"); + } else { + noclip_anglehack = false; + sv_player->v.movetype = MOVETYPE_WALK; + SV_ClientPrintf("noclip OFF\n"); + } + break; + default: + Con_Printf("noclip [value] : toggle noclip mode. values: 0 = off, 1 = on\n"); + break; + } + //johnfitz } /* @@ -639,57 +575,52 @@ Host_SetPos_f adapted from fteqw, originally by Alex Shadowalker ==================== */ -static void Host_SetPos_f(void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } - if (pr_global_struct->deathmatch) - return; +static void Host_SetPos_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } + if (pr_global_struct->deathmatch) + return; - if (command::argc() != 7 && command::argc() != 4) - { - SV_ClientPrintf("usage:\n"); - SV_ClientPrintf(" setpos \n"); - SV_ClientPrintf(" setpos \n"); - SV_ClientPrintf("current values:\n"); - SV_ClientPrintf(" %i %i %i %i %i %i\n", - (int)sv_player->v.origin[0], - (int)sv_player->v.origin[1], - (int)sv_player->v.origin[2], - (int)sv_player->v.v_angle[0], - (int)sv_player->v.v_angle[1], - (int)sv_player->v.v_angle[2]); - return; - } + if (command::argc() != 7 && command::argc() != 4) { + SV_ClientPrintf("usage:\n"); + SV_ClientPrintf(" setpos \n"); + SV_ClientPrintf(" setpos \n"); + SV_ClientPrintf("current values:\n"); + SV_ClientPrintf(" %i %i %i %i %i %i\n", + (int) sv_player->v.origin[0], + (int) sv_player->v.origin[1], + (int) sv_player->v.origin[2], + (int) sv_player->v.v_angle[0], + (int) sv_player->v.v_angle[1], + (int) sv_player->v.v_angle[2]); + return; + } - if (sv_player->v.movetype != MOVETYPE_NOCLIP) - { - noclip_anglehack = true; - sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); - } + if (sv_player->v.movetype != MOVETYPE_NOCLIP) { + noclip_anglehack = true; + sv_player->v.movetype = MOVETYPE_NOCLIP; + SV_ClientPrintf("noclip ON\n"); + } - //make sure they're not going to whizz away from it - sv_player->v.velocity[0] = 0; - sv_player->v.velocity[1] = 0; - sv_player->v.velocity[2] = 0; - - sv_player->v.origin[0] = atof(command::argv(1)->c_str()); - sv_player->v.origin[1] = atof(command::argv(2)->c_str()); - sv_player->v.origin[2] = atof(command::argv(3)->c_str()); - - if (command::argc() == 7) - { - sv_player->v.angles[0] = atof(command::argv(4)->c_str()); - sv_player->v.angles[1] = atof(command::argv(5)->c_str()); - sv_player->v.angles[2] = atof(command::argv(6)->c_str()); - sv_player->v.fixangle = 1; - } - - SV_LinkEdict (sv_player, false); + //make sure they're not going to whizz away from it + sv_player->v.velocity[0] = 0; + sv_player->v.velocity[1] = 0; + sv_player->v.velocity[2] = 0; + + sv_player->v.origin[0] = atof(command::argv(1)->c_str()); + sv_player->v.origin[1] = atof(command::argv(2)->c_str()); + sv_player->v.origin[2] = atof(command::argv(3)->c_str()); + + if (command::argc() == 7) { + sv_player->v.angles[0] = atof(command::argv(4)->c_str()); + sv_player->v.angles[1] = atof(command::argv(5)->c_str()); + sv_player->v.angles[2] = atof(command::argv(6)->c_str()); + sv_player->v.fixangle = 1; + } + + SV_LinkEdict(sv_player, false); } /* @@ -699,49 +630,40 @@ Host_Fly_f Sets client to flymode ================== */ -static void Host_Fly_f (void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_Fly_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - //johnfitz -- allow user to explicitly set noclip to on or off - switch (command::argc()) - { - case 1: - if (sv_player->v.movetype != MOVETYPE_FLY) - { - sv_player->v.movetype = MOVETYPE_FLY; - SV_ClientPrintf ("flymode ON\n"); - } - else - { - sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("flymode OFF\n"); - } - break; - case 2: - if (Q_atof(command::argv(1)->c_str())) - { - sv_player->v.movetype = MOVETYPE_FLY; - SV_ClientPrintf ("flymode ON\n"); - } - else - { - sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("flymode OFF\n"); - } - break; - default: - Con_Printf("fly [value] : toggle fly mode. values: 0 = off, 1 = on\n"); - break; - } - //johnfitz + //johnfitz -- allow user to explicitly set noclip to on or off + switch (command::argc()) { + case 1: + if (sv_player->v.movetype != MOVETYPE_FLY) { + sv_player->v.movetype = MOVETYPE_FLY; + SV_ClientPrintf("flymode ON\n"); + } else { + sv_player->v.movetype = MOVETYPE_WALK; + SV_ClientPrintf("flymode OFF\n"); + } + break; + case 2: + if (std::atof(command::argv(1)->c_str())) { + sv_player->v.movetype = MOVETYPE_FLY; + SV_ClientPrintf("flymode ON\n"); + } else { + sv_player->v.movetype = MOVETYPE_WALK; + SV_ClientPrintf("flymode OFF\n"); + } + break; + default: + Con_Printf("fly [value] : toggle fly mode. values: 0 = off, 1 = on\n"); + break; + } + //johnfitz } /* @@ -750,29 +672,26 @@ Host_Ping_f ================== */ -static void Host_Ping_f (void) -{ - int i, j; - float total; - client_t *client; +static void Host_Ping_f(void) { + int i, j; + float total; + client_t *client; - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - SV_ClientPrintf ("Client ping times:\n"); - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) - { - if (!client->active) - continue; - total = 0; - for (j = 0; j < NUM_PING_TIMES; j++) - total+=client->ping_times[j]; - total /= NUM_PING_TIMES; - SV_ClientPrintf ("%4i %s\n", (int)(total*1000), client->name); - } + SV_ClientPrintf("Client ping times:\n"); + for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { + if (!client->active) + continue; + total = 0; + for (j = 0; j < NUM_PING_TIMES; j++) + total += client->ping_times[j]; + total /= NUM_PING_TIMES; + SV_ClientPrintf("%4i %s\n", (int) (total * 1000), client->name); + } } /* @@ -792,67 +711,58 @@ map command from the console. Active clients are kicked off. ====================== */ -static void Host_Map_f (void) -{ - int i; - char name[MAX_QPATH], *p; +static void Host_Map_f(void) { + int i; + char name[MAX_QPATH], *p; - if (command::argc() < 2) //no map name given - { - if (cls.state == ca_dedicated) - { - if (sv.active) - Con_Printf ("Current map: %s\n", sv.name); - else - Con_Printf ("Server not active\n"); - } - else if (cls.state == ca_connected) - { - Con_Printf ("Current map: %s ( %s )\n", cl.levelname, cl.mapname); - } - else - { - Con_Printf ("map : start a new server\n"); - } - return; - } + if (command::argc() < 2) //no map name given + { + if (cls.state == ca_dedicated) { + if (sv.active) + Con_Printf("Current map: %s\n", sv.name); + else + Con_Printf("Server not active\n"); + } else if (cls.state == ca_connected) { + Con_Printf("Current map: %s ( %s )\n", cl.levelname, cl.mapname); + } else { + Con_Printf("map : start a new server\n"); + } + return; + } - if (command::last_source != command::source::command) - { - return; - } + if (command::last_source != command::source::command) { + return; + } - cls.demonum = -1; // stop demo loop in case this fails + cls.demonum = -1; // stop demo loop in case this fails - CL_Disconnect (); - Host_ShutdownServer(false); + CL_Disconnect(); + Host_ShutdownServer(false); - if (cls.state != ca_dedicated) - IN_Activate(); - key_dest = key_game; // remove console or menu - SCR_BeginLoadingPlaque (); + if (cls.state != ca_dedicated) + IN_Activate(); + key_dest = key_game; // remove console or menu + SCR_BeginLoadingPlaque(); - svs.serverflags = 0; // haven't completed an episode yet - q_strlcpy (name, command::argv(1)->c_str(), sizeof(name)); - // remove (any) trailing ".bsp" from mapname -- S.A. - p = strstr(name, ".bsp"); - if (p && p[4] == '\0') - *p = '\0'; - SV_SpawnServer (name); - if (!sv.active) - return; + svs.serverflags = 0; // haven't completed an episode yet + q_strlcpy(name, command::argv(1)->c_str(), sizeof(name)); + // remove (any) trailing ".bsp" from mapname -- S.A. + p = strstr(name, ".bsp"); + if (p && p[4] == '\0') + *p = '\0'; + SV_SpawnServer(name); + if (!sv.active) + return; - if (cls.state != ca_dedicated) - { - memset (cls.spawnparms, 0, MAX_MAPSTRING); - for (i = 2; i < command::argc(); i++) - { - q_strlcat (cls.spawnparms, command::argv(i)->c_str(), MAX_MAPSTRING); - q_strlcat (cls.spawnparms, " ", MAX_MAPSTRING); - } + if (cls.state != ca_dedicated) { + memset(cls.spawnparms, 0, MAX_MAPSTRING); + for (i = 2; i < command::argc(); i++) { + q_strlcat(cls.spawnparms, command::argv(i)->c_str(), MAX_MAPSTRING); + q_strlcat(cls.spawnparms, " ", MAX_MAPSTRING); + } - command::execute_string ("connect local", command::source::command); - } + command::execute_string("connect local", command::source::command); + } } /* @@ -862,34 +772,30 @@ Host_Randmap_f Loads a random map from the "maps" list. ====================== */ -static void Host_Randmap_f (void) -{ - int i, randlevel, numlevels; - filelist_item_t *level; +static void Host_Randmap_f(void) { + int i, randlevel, numlevels; + filelist_item_t *level; - if (command::last_source != command::source::command) - return; + if (command::last_source != command::source::command) + return; - for (level = extralevels, numlevels = 0; level; level = level->next) - numlevels++; + for (level = extralevels, numlevels = 0; level; level = level->next) + numlevels++; - if (numlevels == 0) - { - Con_Printf ("no maps\n"); - return; - } + if (numlevels == 0) { + Con_Printf("no maps\n"); + return; + } - randlevel = (rand() % numlevels); + randlevel = (rand() % numlevels); - for (level = extralevels, i = 0; level; level = level->next, i++) - { - if (i == randlevel) - { - Con_Printf ("Starting map %s...\n", level->name); - Cbuf_AddText (va("map %s\n", level->name)); - return; - } - } + for (level = extralevels, i = 0; level; level = level->next, i++) { + if (i == randlevel) { + Con_Printf("Starting map %s...\n", level->name); + command::buffer::add_text(va("map %s\n", level->name)); + return; + } + } } /* @@ -899,36 +805,33 @@ Host_Changelevel_f Goes to a new map, taking all clients along ================== */ -static void Host_Changelevel_f (void) -{ - char level[MAX_QPATH]; +static void Host_Changelevel_f(void) { + char level[MAX_QPATH]; - if (command::argc() != 2) - { - Con_Printf ("changelevel : continue game on a new level\n"); - return; - } - if (!sv.active || cls.demoplayback) - { - Con_Printf ("Only the server may changelevel\n"); - return; - } + if (command::argc() != 2) { + Con_Printf("changelevel : continue game on a new level\n"); + return; + } + if (!sv.active || cls.demoplayback) { + Con_Printf("Only the server may changelevel\n"); + return; + } - //johnfitz -- check for client having map before anything else - q_snprintf (level, sizeof(level), "maps/%s.bsp", command::argv(1)->c_str()); - if (!COM_FileExists(level, NULL)) - Host_Error ("cannot find map %s", level); - //johnfitz + //johnfitz -- check for client having map before anything else + q_snprintf(level, sizeof(level), "maps/%s.bsp", command::argv(1)->c_str()); + if (!COM_FileExists(level, NULL)) + Host_Error("cannot find map %s", level); + //johnfitz - if (cls.state != ca_dedicated) - IN_Activate(); // -- S.A. - key_dest = key_game; // remove console or menu - SV_SaveSpawnparms (); - q_strlcpy (level, command::argv(1)->c_str(), sizeof(level)); - SV_SpawnServer (level); - // also issue an error if spawn failed -- O.S. - if (!sv.active) - Host_Error ("cannot run map %s", level); + if (cls.state != ca_dedicated) + IN_Activate(); // -- S.A. + key_dest = key_game; // remove console or menu + SV_SaveSpawnparms(); + q_strlcpy(level, command::argv(1)->c_str(), sizeof(level)); + SV_SpawnServer(level); + // also issue an error if spawn failed -- O.S. + if (!sv.active) + Host_Error("cannot run map %s", level); } /* @@ -938,19 +841,18 @@ Host_Restart_f Restarts the current server for a dead player ================== */ -static void Host_Restart_f (void) -{ - char mapname[MAX_QPATH]; +static void Host_Restart_f(void) { + char mapname[MAX_QPATH]; - if (cls.demoplayback || !sv.active) - return; + if (cls.demoplayback || !sv.active) + return; - if (command::last_source != command::source::command) - return; - q_strlcpy (mapname, sv.name, sizeof(mapname)); // mapname gets cleared in spawnserver - SV_SpawnServer (mapname); - if (!sv.active) - Host_Error ("cannot restart map %s", mapname); + if (command::last_source != command::source::command) + return; + q_strlcpy(mapname, sv.name, sizeof(mapname)); // mapname gets cleared in spawnserver + SV_SpawnServer(mapname); + if (!sv.active) + Host_Error("cannot restart map %s", mapname); } /* @@ -961,13 +863,12 @@ This command causes the client to wait for the signon messages again. This is sent just before a server changes levels ================== */ -static void Host_Reconnect_f (void) -{ - if (cls.demoplayback) // cross-map demo playback fix from Baker - return; +static void Host_Reconnect_f(void) { + if (cls.demoplayback) // cross-map demo playback fix from Baker + return; - SCR_BeginLoadingPlaque (); - CL_ClearSignons (); // need new connection messages + SCR_BeginLoadingPlaque(); + CL_ClearSignons(); // need new connection messages } /* @@ -977,19 +878,17 @@ Host_Connect_f User command to connect to server ===================== */ -static void Host_Connect_f (void) -{ - char name[MAX_QPATH]; +static void Host_Connect_f(void) { + char name[MAX_QPATH]; - cls.demonum = -1; // stop demo loop in case this fails - if (cls.demoplayback) - { - CL_StopPlayback (); - CL_Disconnect (); - } - q_strlcpy (name, command::argv(1).value_or("").c_str(), sizeof(name)); - CL_EstablishConnection (name); - Host_Reconnect_f (); + cls.demonum = -1; // stop demo loop in case this fails + if (cls.demoplayback) { + CL_StopPlayback(); + CL_Disconnect(); + } + q_strlcpy(name, command::argv(1).value_or("").c_str(), sizeof(name)); + CL_EstablishConnection(name); + Host_Reconnect_f(); } @@ -1010,36 +909,34 @@ Host_SavegameComment Writes a SAVEGAME_COMMENT_LENGTH character comment describing the current =============== */ -static void Host_SavegameComment (char text[SAVEGAME_COMMENT_LENGTH + 1]) -{ - int i; - char kills[20]; - char *p; +static void Host_SavegameComment(char text[SAVEGAME_COMMENT_LENGTH + 1]) { + int i; + char kills[20]; + char *p; - for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) - text[i] = ' '; - text[SAVEGAME_COMMENT_LENGTH] = '\0'; + for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) + text[i] = ' '; + text[SAVEGAME_COMMENT_LENGTH] = '\0'; - i = (int) strlen(cl.levelname); - if (i > 22) i = 22; - memcpy (text, cl.levelname, (size_t)i); + i = (int) strlen(cl.levelname); + if (i > 22) i = 22; + memcpy(text, cl.levelname, (size_t) i); -// Remove CR/LFs from level name to avoid broken saves, e.g. with autumn_sp map: -// https://celephais.net/board/view_thread.php?id=60452&start=3666 - while ((p = strchr(text, '\n')) != NULL) - *p = ' '; - while ((p = strchr(text, '\r')) != NULL) - *p = ' '; + // Remove CR/LFs from level name to avoid broken saves, e.g. with autumn_sp map: + // https://celephais.net/board/view_thread.php?id=60452&start=3666 + while ((p = strchr(text, '\n')) != NULL) + *p = ' '; + while ((p = strchr(text, '\r')) != NULL) + *p = ' '; - sprintf (kills,"kills:%3i/%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); - memcpy (text+22, kills, strlen(kills)); + sprintf(kills, "kills:%3i/%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); + memcpy(text + 22, kills, strlen(kills)); -// convert space to _ to make stdio happy - for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) - { - if (text[i] == ' ') - text[i] = '_'; - } + // convert space to _ to make stdio happy + for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) { + if (text[i] == ' ') + text[i] = '_'; + } } /* @@ -1047,92 +944,81 @@ static void Host_SavegameComment (char text[SAVEGAME_COMMENT_LENGTH + 1]) Host_Savegame_f =============== */ -static void Host_Savegame_f (void) -{ - char name[MAX_OSPATH]; - FILE *f; - int i; - char comment[SAVEGAME_COMMENT_LENGTH+1]; +static void Host_Savegame_f(void) { + char name[MAX_OSPATH]; + FILE *f; + int i; + char comment[SAVEGAME_COMMENT_LENGTH + 1]; - if (command::last_source != command::source::command) - return; + if (command::last_source != command::source::command) + return; - if (!sv.active) - { - Con_Printf ("Not playing a local game.\n"); - return; - } + if (!sv.active) { + Con_Printf("Not playing a local game.\n"); + return; + } - if (cl.intermission) - { - Con_Printf ("Can't save in intermission.\n"); - return; - } + if (cl.intermission) { + Con_Printf("Can't save in intermission.\n"); + return; + } - if (svs.maxclients != 1) - { - Con_Printf ("Can't save multiplayer games.\n"); - return; - } + if (svs.maxclients != 1) { + Con_Printf("Can't save multiplayer games.\n"); + return; + } - if (command::argc() != 2) - { - Con_Printf ("save : save a game\n"); - return; - } + if (command::argc() != 2) { + Con_Printf("save : save a game\n"); + return; + } - if (strstr(command::argv(1)->c_str(), "..")) - { - Con_Printf ("Relative pathnames are not allowed.\n"); - return; - } + if (strstr(command::argv(1)->c_str(), "..")) { + Con_Printf("Relative pathnames are not allowed.\n"); + return; + } - for (i=0 ; iv.health <= 0) ) - { - Con_Printf ("Can't savegame with a dead player\n"); - return; - } - } + for (i = 0; i < svs.maxclients; i++) { + if (svs.clients[i].active && (svs.clients[i].edict->v.health <= 0)) { + Con_Printf("Can't savegame with a dead player\n"); + return; + } + } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); - COM_AddExtension (name, ".sav", sizeof(name)); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); + COM_AddExtension(name, ".sav", sizeof(name)); - Con_Printf ("Saving game to %s...\n", name); - f = fopen (name, "w"); - if (!f) - { - Con_Printf ("ERROR: couldn't open.\n"); - return; - } + Con_Printf("Saving game to %s...\n", name); + f = fopen(name, "w"); + if (!f) { + Con_Printf("ERROR: couldn't open.\n"); + return; + } - fprintf (f, "%i\n", SAVEGAME_VERSION); - Host_SavegameComment (comment); - fprintf (f, "%s\n", comment); - for (i = 0; i < NUM_SPAWN_PARMS; i++) - fprintf (f, "%f\n", svs.clients->spawn_parms[i]); - fprintf (f, "%d\n", current_skill); - fprintf (f, "%s\n", sv.name); - fprintf (f, "%f\n",sv.time); + fprintf(f, "%i\n", SAVEGAME_VERSION); + Host_SavegameComment(comment); + fprintf(f, "%s\n", comment); + for (i = 0; i < NUM_SPAWN_PARMS; i++) + fprintf(f, "%f\n", svs.clients->spawn_parms[i]); + fprintf(f, "%d\n", current_skill); + fprintf(f, "%s\n", sv.name); + fprintf(f, "%f\n", sv.time); -// write the light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) - { - if (sv.lightstyles[i]) - fprintf (f, "%s\n", sv.lightstyles[i]); - else - fprintf (f,"m\n"); - } + // write the light styles + for (i = 0; i < MAX_LIGHTSTYLES; i++) { + if (sv.lightstyles[i]) + fprintf(f, "%s\n", sv.lightstyles[i]); + else + fprintf(f, "m\n"); + } - ED_WriteGlobals (f); - for (i = 0; i < sv.num_edicts; i++) - { - ED_Write (f, EDICT_NUM(i)); - fflush (f); - } - fclose (f); - Con_Printf ("done.\n"); + ED_WriteGlobals(f); + for (i = 0; i < sv.num_edicts; i++) { + ED_Write(f, EDICT_NUM(i)); + fflush(f); + } + fclose(f); + Con_Printf("done.\n"); } /* @@ -1140,156 +1026,144 @@ static void Host_Savegame_f (void) Host_Loadgame_f =============== */ -static void Host_Loadgame_f (void) -{ - static char *start; - - char name[MAX_OSPATH]; - char mapname[MAX_QPATH]; - int i; - edict_t *ent; - int entnum; - int version; - float spawn_parms[NUM_SPAWN_PARMS]; +static void Host_Loadgame_f(void) { + static char *start; - if (command::last_source != command::source::command) - return; + char name[MAX_OSPATH]; + char mapname[MAX_QPATH]; + int i; + edict_t *ent; + int entnum; + int version; + float spawn_parms[NUM_SPAWN_PARMS]; - if (command::argc() != 2) - { - Con_Printf ("load : load a game\n"); - return; - } - - if (strstr(command::argv(1)->c_str(), "..")) - { - Con_Printf ("Relative pathnames are not allowed.\n"); - return; - } + if (command::last_source != command::source::command) + return; - cls.demonum = -1; // stop demo loop in case this fails + if (command::argc() != 2) { + Con_Printf("load : load a game\n"); + return; + } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); - COM_AddExtension (name, ".sav", sizeof(name)); + if (strstr(command::argv(1)->c_str(), "..")) { + Con_Printf("Relative pathnames are not allowed.\n"); + return; + } -// we can't call SCR_BeginLoadingPlaque, because too much stack space has -// been used. The menu calls it before stuffing loadgame command -// SCR_BeginLoadingPlaque (); + cls.demonum = -1; // stop demo loop in case this fails - Con_Printf ("Loading game from %s...\n", name); - -// avoid leaking if the previous Host_Loadgame_f failed with a Host_Error - if (start != NULL) - free (start); - - start = (char *) COM_LoadMallocFile_TextMode_OSPath(name, NULL); - if (start == NULL) - { - Con_Printf ("ERROR: couldn't open.\n"); - return; - } + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, command::argv(1)->c_str()); + COM_AddExtension(name, ".sav", sizeof(name)); - std::istringstream ss{start}; - version = common::parse_int_newline(ss); - if (version != SAVEGAME_VERSION) - { - free (start); - start = NULL; - Host_Error ("Savegame is version %i, not %i", version, SAVEGAME_VERSION); - return; - } - auto strr = common::parse_string_newline (ss); - for (i = 0; i < NUM_SPAWN_PARMS; i++) - spawn_parms[i] = common::parse_float_newline(ss); -// this silliness is so we can load 1.06 save files, which have float skill values - const float tfloat = common::parse_float_newline(ss); - current_skill = (int)(tfloat + 0.1); - convar::set_value ("skill", (float)current_skill); + // we can't call SCR_BeginLoadingPlaque, because too much stack space has + // been used. The menu calls it before stuffing loadgame command + // SCR_BeginLoadingPlaque (); - strr = common::parse_string_newline(ss); - q_strlcpy (mapname, strr.c_str(), sizeof(mapname)); - const float time = common::parse_float_newline(ss); + Con_Printf("Loading game from %s...\n", name); - CL_Disconnect_f (); + // avoid leaking if the previous Host_Loadgame_f failed with a Host_Error + if (start != NULL) + free(start); - SV_SpawnServer (mapname); + start = (char *) COM_LoadMallocFile_TextMode_OSPath(name, NULL); + if (start == NULL) { + Con_Printf("ERROR: couldn't open.\n"); + return; + } - if (!sv.active) - { - free (start); - start = NULL; - SCR_EndLoadingPlaque (); - Con_Printf ("Couldn't load map\n"); - return; - } - sv.paused = true; // pause until all clients connect - sv.loadgame = true; + std::istringstream ss{start}; + version = common::parse_int_newline(ss); + if (version != SAVEGAME_VERSION) { + free(start); + start = NULL; + Host_Error("Savegame is version %i, not %i", version, SAVEGAME_VERSION); + return; + } + auto strr = common::parse_string_newline(ss); + for (i = 0; i < NUM_SPAWN_PARMS; i++) + spawn_parms[i] = common::parse_float_newline(ss); + // this silliness is so we can load 1.06 save files, which have float skill values + const float tfloat = common::parse_float_newline(ss); + current_skill = (int) (tfloat + 0.1); + convar::set_value("skill", (float) current_skill); -// load the light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) - { - strr = common::parse_string_newline(ss); - sv.lightstyles[i] = (const char *)Hunk_Strdup (strr.c_str(), "lightstyles"); - } + strr = common::parse_string_newline(ss); + q_strlcpy(mapname, strr.c_str(), sizeof(mapname)); + const float time = common::parse_float_newline(ss); -// load the edicts out of the savegame file - entnum = -1; // -1 is the globals - while (!ss.eof()) - { - auto token = common::parse_token(ss); - if (!token.has_value()) - break; // end of file - if (token->front() != '{') - { - Host_Error ("First token isn't a brace"); - } + CL_Disconnect_f(); - if (entnum == -1) - { // parse the global vars - ED_ParseGlobals (ss); - } - else - { // parse an edict - ent = EDICT_NUM(entnum); - if (entnum < sv.num_edicts) { - ent->free = false; - memset (&ent->v, 0, progs->entityfields * 4); - } - else { - memset (ent, 0, pr_edict_size); - ent->baseline.scale = ENTSCALE_DEFAULT; - } - ED_ParseEdict (ss, ent); + SV_SpawnServer(mapname); - // link it into the bsp tree - if (!ent->free) - SV_LinkEdict (ent, false); - } + if (!sv.active) { + free(start); + start = NULL; + SCR_EndLoadingPlaque(); + Con_Printf("Couldn't load map\n"); + return; + } + sv.paused = true; // pause until all clients connect + sv.loadgame = true; - entnum++; - } + // load the light styles + for (i = 0; i < MAX_LIGHTSTYLES; i++) { + strr = common::parse_string_newline(ss); + sv.lightstyles[i] = (const char *) Hunk_Strdup(strr.c_str(), "lightstyles"); + } - // Free edicts allocated during map loading but no longer used after restoring saved game state - for (i = entnum; i < sv.num_edicts; i++) - ED_Free(EDICT_NUM(i)); + // load the edicts out of the savegame file + entnum = -1; // -1 is the globals + while (!ss.eof()) { + auto token = common::parse_token(ss); + if (!token.has_value()) + break; // end of file + if (token->front() != '{') { + Host_Error("First token isn't a brace"); + } - sv.num_edicts = entnum; - sv.time = time; + if (entnum == -1) { + // parse the global vars + ED_ParseGlobals(ss); + } else { + // parse an edict + ent = EDICT_NUM(entnum); + if (entnum < sv.num_edicts) { + ent->free = false; + memset(&ent->v, 0, progs->entityfields * 4); + } else { + memset(ent, 0, pr_edict_size); + ent->baseline.scale = ENTSCALE_DEFAULT; + } + ED_ParseEdict(ss, ent); - free (start); - start = NULL; + // link it into the bsp tree + if (!ent->free) + SV_LinkEdict(ent, false); + } - for (i = 0; i < NUM_SPAWN_PARMS; i++) - svs.clients->spawn_parms[i] = spawn_parms[i]; + entnum++; + } - if (cls.state != ca_dedicated) - { - CL_EstablishConnection ("local"); - Host_Reconnect_f (); - } + // Free edicts allocated during map loading but no longer used after restoring saved game state + for (i = entnum; i < sv.num_edicts; i++) + ED_Free(EDICT_NUM(i)); - if (cls.state != ca_dedicated) - IN_Activate(); // moved to here from M_Load_Key() + sv.num_edicts = entnum; + sv.time = time; + + free(start); + start = NULL; + + for (i = 0; i < NUM_SPAWN_PARMS; i++) + svs.clients->spawn_parms[i] = spawn_parms[i]; + + if (cls.state != ca_dedicated) { + CL_EstablishConnection("local"); + Host_Reconnect_f(); + } + + if (cls.state != ca_dedicated) + IN_Activate(); // moved to here from M_Load_Key() } //============================================================================ @@ -1299,195 +1173,172 @@ static void Host_Loadgame_f (void) Host_Name_f ====================== */ -static void Host_Name_f (void) -{ - char newName[32]; +static void Host_Name_f(void) { + char newName[32]; - if (command::argc () == 1) - { - Con_Printf ("\"name\" is \"%s\"\n", cl_name.string); - return; - } - if (command::argc () == 2) - q_strlcpy(newName, command::argv(1)->c_str(), sizeof(newName)); - else - q_strlcpy(newName, command::args().c_str(), sizeof(newName)); - newName[15] = 0; // client_t structure actually says name[32]. + if (command::argc() == 1) { + Con_Printf("\"name\" is \"%s\"\n", cl_name.string); + return; + } + if (command::argc() == 2) + q_strlcpy(newName, command::argv(1)->c_str(), sizeof(newName)); + else + q_strlcpy(newName, command::args().c_str(), sizeof(newName)); + newName[15] = 0; // client_t structure actually says name[32]. - if (command::last_source == command::source::command) - { - if (Q_strcmp(cl_name.string, newName) == 0) - return; - convar::set("_cl_name", newName); - if (cls.state == ca_connected) - command::forward_to_server (); - return; - } + if (command::last_source == command::source::command) { + if (std::strcmp(cl_name.string, newName) == 0) + return; + convar::set("_cl_name", newName); + if (cls.state == ca_connected) + command::forward_to_server(); + return; + } - if (host_client->name[0] && strcmp(host_client->name, "unconnected") ) - { - if (Q_strcmp(host_client->name, newName) != 0) - Con_Printf ("%s renamed to %s\n", host_client->name, newName); - } - Q_strcpy (host_client->name, newName); - host_client->edict->v.netname = PR_SetEngineString(host_client->name); + if (host_client->name[0] && strcmp(host_client->name, "unconnected")) { + if (std::strcmp(host_client->name, newName) != 0) + Con_Printf("%s renamed to %s\n", host_client->name, newName); + } + std::strcpy(host_client->name, newName); + host_client->edict->v.netname = PR_SetEngineString(host_client->name); -// send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_updatename); - MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients); - MSG_WriteString (&sv.reliable_datagram, host_client->name); + // send notification to all clients + MSG_WriteByte(&sv.reliable_datagram, svc_updatename); + MSG_WriteByte(&sv.reliable_datagram, host_client - svs.clients); + MSG_WriteString(&sv.reliable_datagram, host_client->name); } -static void Host_Say(qboolean teamonly) -{ - int j; - client_t *client; - client_t *save; - char text[MAXCMDLINE], *p2; - qboolean quoted; - qboolean fromServer = false; +static void Host_Say(bool teamonly) { + int j; + client_t *client; + client_t *save; + char text[MAXCMDLINE], *p2; + bool quoted; + bool fromServer = false; - if (command::last_source == command::source::command) - { - if (cls.state != ca_dedicated) - { - command::forward_to_server (); - return; - } - fromServer = true; - teamonly = false; - } + if (command::last_source == command::source::command) { + if (cls.state != ca_dedicated) { + command::forward_to_server(); + return; + } + fromServer = true; + teamonly = false; + } - if (command::argc () < 2) - return; + if (command::argc() < 2) + return; - save = host_client; + save = host_client; - auto args = command::args(); - auto p = args.c_str(); -// remove quotes if present - quoted = false; - if (*p == '\"') - { - p++; - quoted = true; - } -// turn on color set 1 - if (!fromServer) - q_snprintf (text, sizeof(text), "\001%s: %s", save->name, p); - else - q_snprintf (text, sizeof(text), "\001<%s> %s", hostname.string, p); + auto args = command::args(); + auto p = args.c_str(); + // remove quotes if present + quoted = false; + if (*p == '\"') { + p++; + quoted = true; + } + // turn on color set 1 + if (!fromServer) + q_snprintf(text, sizeof(text), "\001%s: %s", save->name, p); + else + q_snprintf(text, sizeof(text), "\001<%s> %s", hostname.string, p); -// check length & truncate if necessary - j = (int) strlen(text); - if (j >= (int) sizeof(text) - 1) - { - text[sizeof(text) - 2] = '\n'; - text[sizeof(text) - 1] = '\0'; - } - else - { - p2 = text + j; - while ((const char *)p2 > (const char *)text && - (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted)) ) - { - if (p2[-1] == '\"' && quoted) - quoted = false; - p2[-1] = '\0'; - p2--; - } - p2[0] = '\n'; - p2[1] = '\0'; - } + // check length & truncate if necessary + j = (int) strlen(text); + if (j >= (int) sizeof(text) - 1) { + text[sizeof(text) - 2] = '\n'; + text[sizeof(text) - 1] = '\0'; + } else { + p2 = text + j; + while ((const char *) p2 > (const char *) text && + (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted))) { + if (p2[-1] == '\"' && quoted) + quoted = false; + p2[-1] = '\0'; + p2--; + } + p2[0] = '\n'; + p2[1] = '\0'; + } - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) - { - if (!client || !client->active || !client->spawned) - continue; - if (teamplay.value && teamonly && client->edict->v.team != save->edict->v.team) - continue; - host_client = client; - SV_ClientPrintf("%s", text); - } - host_client = save; + for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { + if (!client || !client->active || !client->spawned) + continue; + if (teamplay.value && teamonly && client->edict->v.team != save->edict->v.team) + continue; + host_client = client; + SV_ClientPrintf("%s", text); + } + host_client = save; - if (cls.state == ca_dedicated) - Sys_Printf("%s", &text[1]); + if (cls.state == ca_dedicated) + Sys_Printf("%s", &text[1]); } -static void Host_Say_f(void) -{ - Host_Say(false); +static void Host_Say_f(void) { + Host_Say(false); } -static void Host_Say_Team_f(void) -{ - Host_Say(true); +static void Host_Say_Team_f(void) { + Host_Say(true); } -static void Host_Tell_f(void) -{ - int j; - client_t *client; - client_t *save; - const char *p; - char text[MAXCMDLINE], *p2; - qboolean quoted; +static void Host_Tell_f(void) { + int j; + client_t *client; + client_t *save; + const char *p; + char text[MAXCMDLINE], *p2; + bool quoted; - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (command::argc () < 3) - return; + if (command::argc() < 3) + return; - auto args = command::args(); - p = args.c_str(); -// remove quotes if present - quoted = false; - if (*p == '\"') - { - p++; - quoted = true; - } - q_snprintf (text, sizeof(text), "%s: %s", host_client->name, p); + auto args = command::args(); + p = args.c_str(); + // remove quotes if present + quoted = false; + if (*p == '\"') { + p++; + quoted = true; + } + q_snprintf(text, sizeof(text), "%s: %s", host_client->name, p); -// check length & truncate if necessary - j = (int) strlen(text); - if (j >= (int) sizeof(text) - 1) - { - text[sizeof(text) - 2] = '\n'; - text[sizeof(text) - 1] = '\0'; - } - else - { - p2 = text + j; - while ((const char *)p2 > (const char *)text && - (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted)) ) - { - if (p2[-1] == '\"' && quoted) - quoted = false; - p2[-1] = '\0'; - p2--; - } - p2[0] = '\n'; - p2[1] = '\0'; - } + // check length & truncate if necessary + j = (int) strlen(text); + if (j >= (int) sizeof(text) - 1) { + text[sizeof(text) - 2] = '\n'; + text[sizeof(text) - 1] = '\0'; + } else { + p2 = text + j; + while ((const char *) p2 > (const char *) text && + (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted))) { + if (p2[-1] == '\"' && quoted) + quoted = false; + p2[-1] = '\0'; + p2--; + } + p2[0] = '\n'; + p2[1] = '\0'; + } - save = host_client; - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) - { - if (!client->active || !client->spawned) - continue; - if (q_strcasecmp(client->name, command::argv(1)->c_str())) - continue; - host_client = client; - SV_ClientPrintf("%s", text); - break; - } - host_client = save; + save = host_client; + for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { + if (!client->active || !client->spawned) + continue; + if (q_strcasecmp(client->name, command::argv(1)->c_str())) + continue; + host_client = client; + SV_ClientPrintf("%s", text); + break; + } + host_client = save; } /* @@ -1495,50 +1346,46 @@ static void Host_Tell_f(void) Host_Color_f ================== */ -static void Host_Color_f(void) -{ - int top, bottom; - int playercolor; +static void Host_Color_f(void) { + int top, bottom; + int playercolor; - if (command::argc() == 1) - { - Con_Printf ("\"color\" is \"%i %i\"\n", ((int)cl_color.value) >> 4, ((int)cl_color.value) & 0x0f); - Con_Printf ("color <0-13> [0-13]\n"); - return; - } + if (command::argc() == 1) { + Con_Printf("\"color\" is \"%i %i\"\n", ((int) cl_color.value) >> 4, ((int) cl_color.value) & 0x0f); + Con_Printf("color <0-13> [0-13]\n"); + return; + } - if (command::argc() == 2) - top = bottom = atoi(command::argv(1)->c_str()); - else - { - top = atoi(command::argv(1)->c_str()); - bottom = atoi(command::argv(2)->c_str()); - } + if (command::argc() == 2) + top = bottom = atoi(command::argv(1)->c_str()); + else { + top = atoi(command::argv(1)->c_str()); + bottom = atoi(command::argv(2)->c_str()); + } - top &= 15; - if (top > 13) - top = 13; - bottom &= 15; - if (bottom > 13) - bottom = 13; + top &= 15; + if (top > 13) + top = 13; + bottom &= 15; + if (bottom > 13) + bottom = 13; - playercolor = top*16 + bottom; + playercolor = top * 16 + bottom; - if (command::last_source == command::source::command) - { - convar::set_value ("_cl_color", playercolor); - if (cls.state == ca_connected) - command::forward_to_server (); - return; - } + if (command::last_source == command::source::command) { + convar::set_value("_cl_color", playercolor); + if (cls.state == ca_connected) + command::forward_to_server(); + return; + } - host_client->colors = playercolor; - host_client->edict->v.team = bottom + 1; + host_client->colors = playercolor; + host_client->edict->v.team = bottom + 1; -// send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors); - MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients); - MSG_WriteByte (&sv.reliable_datagram, host_client->colors); + // send notification to all clients + MSG_WriteByte(&sv.reliable_datagram, svc_updatecolors); + MSG_WriteByte(&sv.reliable_datagram, host_client - svs.clients); + MSG_WriteByte(&sv.reliable_datagram, host_client->colors); } /* @@ -1546,23 +1393,20 @@ static void Host_Color_f(void) Host_Kill_f ================== */ -static void Host_Kill_f (void) -{ - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } +static void Host_Kill_f(void) { + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (sv_player->v.health <= 0) - { - SV_ClientPrintf ("Can't suicide -- already dead!\n"); - return; - } + if (sv_player->v.health <= 0) { + SV_ClientPrintf("Can't suicide -- already dead!\n"); + return; + } - pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); - PR_ExecuteProgram (pr_global_struct->ClientKill); + pr_global_struct->time = sv.time; + pr_global_struct->self = EDICT_TO_PROG(sv_player); + PR_ExecuteProgram(pr_global_struct->ClientKill); } /* @@ -1570,40 +1414,33 @@ static void Host_Kill_f (void) Host_Pause_f ================== */ -static void Host_Pause_f (void) -{ -//ericw -- demo pause support (inspired by MarkV) - if (cls.demoplayback) - { - cls.demopaused = !cls.demopaused; - cl.paused = cls.demopaused; - return; - } +static void Host_Pause_f(void) { + //ericw -- demo pause support (inspired by MarkV) + if (cls.demoplayback) { + cls.demopaused = !cls.demopaused; + cl.paused = cls.demopaused; + return; + } - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } - if (!pausable.value) - SV_ClientPrintf ("Pause not allowed.\n"); - else - { - sv.paused ^= 1; + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } + if (!pausable.value) + SV_ClientPrintf("Pause not allowed.\n"); + else { + sv.paused ^= 1; - if (sv.paused) - { - SV_BroadcastPrintf ("%s paused the game\n", PR_GetString(sv_player->v.netname)); - } - else - { - SV_BroadcastPrintf ("%s unpaused the game\n",PR_GetString(sv_player->v.netname)); - } + if (sv.paused) { + SV_BroadcastPrintf("%s paused the game\n", PR_GetString(sv_player->v.netname)); + } else { + SV_BroadcastPrintf("%s unpaused the game\n", PR_GetString(sv_player->v.netname)); + } - // send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_setpause); - MSG_WriteByte (&sv.reliable_datagram, sv.paused); - } + // send notification to all clients + MSG_WriteByte(&sv.reliable_datagram, svc_setpause); + MSG_WriteByte(&sv.reliable_datagram, sv.paused); + } } //=========================================================================== @@ -1613,22 +1450,19 @@ static void Host_Pause_f (void) Host_PreSpawn_f ================== */ -static void Host_PreSpawn_f (void) -{ - if (command::last_source == command::source::command) - { - Con_Printf ("prespawn is not valid from the console\n"); - return; - } +static void Host_PreSpawn_f(void) { + if (command::last_source == command::source::command) { + Con_Printf("prespawn is not valid from the console\n"); + return; + } - if (host_client->spawned) - { - Con_Printf ("prespawn not valid -- already spawned\n"); - return; - } + if (host_client->spawned) { + Con_Printf("prespawn not valid -- already spawned\n"); + return; + } - host_client->sendsignon = PRESPAWN_SIGNONBUFS; - host_client->signonidx = 0; + host_client->sendsignon = PRESPAWN_SIGNONBUFS; + host_client->signonidx = 0; } /* @@ -1636,118 +1470,111 @@ static void Host_PreSpawn_f (void) Host_Spawn_f ================== */ -static void Host_Spawn_f (void) -{ - int i; - client_t *client; - edict_t *ent; +static void Host_Spawn_f(void) { + int i; + client_t *client; + edict_t *ent; - if (command::last_source == command::source::command) - { - Con_Printf ("spawn is not valid from the console\n"); - return; - } + if (command::last_source == command::source::command) { + Con_Printf("spawn is not valid from the console\n"); + return; + } - if (host_client->spawned) - { - Con_Printf ("Spawn not valid -- already spawned\n"); - return; - } + if (host_client->spawned) { + Con_Printf("Spawn not valid -- already spawned\n"); + return; + } -// run the entrance script - if (sv.loadgame) - { // loaded games are fully inited already - // if this is the last client to be connected, unpause - sv.paused = false; - } - else - { - // set up the edict - ent = host_client->edict; + // run the entrance script + if (sv.loadgame) { + // loaded games are fully inited already + // if this is the last client to be connected, unpause + sv.paused = false; + } else { + // set up the edict + ent = host_client->edict; - memset (&ent->v, 0, progs->entityfields * 4); - ent->v.colormap = NUM_FOR_EDICT(ent); - ent->v.team = (host_client->colors & 15) + 1; - ent->v.netname = PR_SetEngineString(host_client->name); + memset(&ent->v, 0, progs->entityfields * 4); + ent->v.colormap = NUM_FOR_EDICT(ent); + ent->v.team = (host_client->colors & 15) + 1; + ent->v.netname = PR_SetEngineString(host_client->name); - // copy spawn parms out of the client_t - for (i=0 ; i< NUM_SPAWN_PARMS ; i++) - (&pr_global_struct->parm1)[i] = host_client->spawn_parms[i]; - // call the spawn function - pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); - PR_ExecuteProgram (pr_global_struct->ClientConnect); + // copy spawn parms out of the client_t + for (i = 0; i < NUM_SPAWN_PARMS; i++) + (&pr_global_struct->parm1)[i] = host_client->spawn_parms[i]; + // call the spawn function + pr_global_struct->time = sv.time; + pr_global_struct->self = EDICT_TO_PROG(sv_player); + PR_ExecuteProgram(pr_global_struct->ClientConnect); - if ((Sys_DoubleTime() - NET_QSocketGetTime(host_client->netconnection)) <= sv.time) - Sys_Printf ("%s entered the game\n", host_client->name); + if ((Sys_DoubleTime() - NET_QSocketGetTime(host_client->netconnection)) <= sv.time) + Sys_Printf("%s entered the game\n", host_client->name); - PR_ExecuteProgram (pr_global_struct->PutClientInServer); - } + PR_ExecuteProgram(pr_global_struct->PutClientInServer); + } -// send all current names, colors, and frag counts - SZ_Clear (&host_client->message); + // send all current names, colors, and frag counts + SZ_Clear(&host_client->message); -// send time of update - MSG_WriteByte (&host_client->message, svc_time); - MSG_WriteFloat (&host_client->message, sv.time); + // send time of update + MSG_WriteByte(&host_client->message, svc_time); + MSG_WriteFloat(&host_client->message, sv.time); - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) - { - MSG_WriteByte (&host_client->message, svc_updatename); - MSG_WriteByte (&host_client->message, i); - MSG_WriteString (&host_client->message, client->name); - MSG_WriteByte (&host_client->message, svc_updatefrags); - MSG_WriteByte (&host_client->message, i); - MSG_WriteShort (&host_client->message, client->old_frags); - MSG_WriteByte (&host_client->message, svc_updatecolors); - MSG_WriteByte (&host_client->message, i); - MSG_WriteByte (&host_client->message, client->colors); - } + for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { + MSG_WriteByte(&host_client->message, svc_updatename); + MSG_WriteByte(&host_client->message, i); + MSG_WriteString(&host_client->message, client->name); + MSG_WriteByte(&host_client->message, svc_updatefrags); + MSG_WriteByte(&host_client->message, i); + MSG_WriteShort(&host_client->message, client->old_frags); + MSG_WriteByte(&host_client->message, svc_updatecolors); + MSG_WriteByte(&host_client->message, i); + MSG_WriteByte(&host_client->message, client->colors); + } -// send all current light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) - { - MSG_WriteByte (&host_client->message, svc_lightstyle); - MSG_WriteByte (&host_client->message, (char)i); - MSG_WriteString (&host_client->message, sv.lightstyles[i]); - } + // send all current light styles + for (i = 0; i < MAX_LIGHTSTYLES; i++) { + MSG_WriteByte(&host_client->message, svc_lightstyle); + MSG_WriteByte(&host_client->message, (char) i); + MSG_WriteString(&host_client->message, sv.lightstyles[i]); + } -// -// send some stats -// - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_TOTALSECRETS); - MSG_WriteLong (&host_client->message, pr_global_struct->total_secrets); + // + // send some stats + // + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_TOTALSECRETS); + MSG_WriteLong(&host_client->message, pr_global_struct->total_secrets); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_TOTALMONSTERS); - MSG_WriteLong (&host_client->message, pr_global_struct->total_monsters); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_TOTALMONSTERS); + MSG_WriteLong(&host_client->message, pr_global_struct->total_monsters); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_SECRETS); - MSG_WriteLong (&host_client->message, pr_global_struct->found_secrets); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_SECRETS); + MSG_WriteLong(&host_client->message, pr_global_struct->found_secrets); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_MONSTERS); - MSG_WriteLong (&host_client->message, pr_global_struct->killed_monsters); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_MONSTERS); + MSG_WriteLong(&host_client->message, pr_global_struct->killed_monsters); -// -// send a fixangle -// Never send a roll angle, because savegames can catch the server -// in a state where it is expecting the client to correct the angle -// and it won't happen if the game was just loaded, so you wind up -// with a permanent head tilt - ent = EDICT_NUM( 1 + (host_client - svs.clients) ); - MSG_WriteByte (&host_client->message, svc_setangle); - for (i = 0; i < 2; i++) - MSG_WriteAngle (&host_client->message, ent->v.angles[i], sv.protocolflags ); - MSG_WriteAngle (&host_client->message, 0, sv.protocolflags ); + // + // send a fixangle + // Never send a roll angle, because savegames can catch the server + // in a state where it is expecting the client to correct the angle + // and it won't happen if the game was just loaded, so you wind up + // with a permanent head tilt + ent = EDICT_NUM(1 + (host_client - svs.clients)); + MSG_WriteByte(&host_client->message, svc_setangle); + for (i = 0; i < 2; i++) + MSG_WriteAngle(&host_client->message, ent->v.angles[i], sv.protocolflags); + MSG_WriteAngle(&host_client->message, 0, sv.protocolflags); - SV_WriteClientdataToMessage (sv_player, &host_client->message); + SV_WriteClientdataToMessage(sv_player, &host_client->message); - MSG_WriteByte (&host_client->message, svc_signonnum); - MSG_WriteByte (&host_client->message, 3); - host_client->sendsignon = PRESPAWN_FLUSH; + MSG_WriteByte(&host_client->message, svc_signonnum); + MSG_WriteByte(&host_client->message, 3); + host_client->sendsignon = PRESPAWN_FLUSH; } /* @@ -1755,15 +1582,13 @@ static void Host_Spawn_f (void) Host_Begin_f ================== */ -static void Host_Begin_f (void) -{ - if (command::last_source == command::source::command) - { - Con_Printf ("begin is not valid from the console\n"); - return; - } +static void Host_Begin_f(void) { + if (command::last_source == command::source::command) { + Con_Printf("begin is not valid from the console\n"); + return; + } - host_client->spawned = true; + host_client->spawned = true; } //=========================================================================== @@ -1775,86 +1600,75 @@ Host_Kick_f Kicks a user off of the server ================== */ -static void Host_Kick_f (void) -{ - const char *who; - client_t *save; - int i; - qboolean byNumber = false; +static void Host_Kick_f(void) { + const char *who; + client_t *save; + int i; + bool byNumber = false; - if (command::last_source == command::source::command) - { - if (!sv.active) - { - command::forward_to_server (); - return; - } - } - else if (pr_global_struct->deathmatch) - return; + if (command::last_source == command::source::command) { + if (!sv.active) { + command::forward_to_server(); + return; + } + } else if (pr_global_struct->deathmatch) + return; - save = host_client; + save = host_client; - if (command::argc() > 2 && Q_strcmp(command::argv(1)->c_str(), "#") == 0) - { - i = Q_atof(command::argv(2)->c_str()) - 1; - if (i < 0 || i >= svs.maxclients) - return; - if (!svs.clients[i].active) - return; - host_client = &svs.clients[i]; - byNumber = true; - } - else - { - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) - { - if (!host_client->active) - continue; - if (q_strcasecmp(host_client->name, command::argv(1).value_or("").c_str()) == 0) - break; - } - } + if (command::argc() > 2 && std::strcmp(command::argv(1)->c_str(), "#") == 0) { + i = std::atof(command::argv(2)->c_str()) - 1; + if (i < 0 || i >= svs.maxclients) + return; + if (!svs.clients[i].active) + return; + host_client = &svs.clients[i]; + byNumber = true; + } else { + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (!host_client->active) + continue; + if (q_strcasecmp(host_client->name, command::argv(1).value_or("").c_str()) == 0) + break; + } + } - if (i < svs.maxclients) - { - if (command::last_source == command::source::command) - if (cls.state == ca_dedicated) - who = "Console"; - else - who = cl_name.string; - else - who = save->name; + if (i < svs.maxclients) { + if (command::last_source == command::source::command) + if (cls.state == ca_dedicated) + who = "Console"; + else + who = cl_name.string; + else + who = save->name; - // can't kick yourself! - if (host_client == save) - return; + // can't kick yourself! + if (host_client == save) + return; - std::string message{}; - if (command::argc() > 2) - { - std::istringstream ss{command::args()}; - auto token = common::parse_token(ss); - if (byNumber) - { - ss.get(); - while (ss.peek() == ' ') // skip white space - ss.get(); - ss.seekg(command::argv(2)->length(), std::ios_base::seekdir::_S_cur); // skip the number - } - while (!ss.eof() && ss.peek() == ' ') - ss.get(); + std::string message{}; + if (command::argc() > 2) { + std::istringstream ss{command::args()}; + auto token = common::parse_token(ss); + if (byNumber) { + ss.get(); + while (ss.peek() == ' ') // skip white space + ss.get(); + ss.seekg(command::argv(2)->length(), std::ios_base::seekdir::_S_cur); // skip the number + } + while (!ss.eof() && ss.peek() == ' ') + ss.get(); - message += ss.str().substr(ss.tellg()); - } - if (!message.empty()) - SV_ClientPrintf ("Kicked by %s: %s\n", who, message.c_str()); - else - SV_ClientPrintf ("Kicked by %s\n", who); - SV_DropClient (false); - } + message += ss.str().substr(ss.tellg()); + } + if (!message.empty()) + SV_ClientPrintf("Kicked by %s: %s\n", who, message.c_str()); + else + SV_ClientPrintf("Kicked by %s\n", who); + SV_DropClient(false); + } - host_client = save; + host_client = save; } /* @@ -1870,245 +1684,210 @@ DEBUGGING TOOLS Host_Give_f ================== */ -static void Host_Give_f (void) -{ - const char *t; - int v; - eval_t *val; +static void Host_Give_f(void) { + const char *t; + int v; + eval_t *val; - if (command::last_source == command::source::command) - { - command::forward_to_server(); - return; - } + if (command::last_source == command::source::command) { + command::forward_to_server(); + return; + } - if (pr_global_struct->deathmatch) - return; + if (pr_global_struct->deathmatch) + return; - auto arg1 = command::argv(1).value_or(""); - t = arg1.c_str(); - v = atoi (command::argv(2).value_or("").c_str()); + auto arg1 = command::argv(1).value_or(""); + t = arg1.c_str(); + v = atoi(command::argv(2).value_or("").c_str()); - switch (t[0]) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - // MED 01/04/97 added hipnotic give stuff - if (hipnotic) - { - if (t[0] == '6') - { - if (t[1] == 'a') - sv_player->v.items = (int)sv_player->v.items | HIT_PROXIMITY_GUN; - else - sv_player->v.items = (int)sv_player->v.items | IT_GRENADE_LAUNCHER; - } - else if (t[0] == '9') - sv_player->v.items = (int)sv_player->v.items | HIT_LASER_CANNON; - else if (t[0] == '0') - sv_player->v.items = (int)sv_player->v.items | HIT_MJOLNIR; - else if (t[0] >= '2') - sv_player->v.items = (int)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); - } - else - { - if (t[0] >= '2') - sv_player->v.items = (int)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); - } - break; + switch (t[0]) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + // MED 01/04/97 added hipnotic give stuff + if (hipnotic) { + if (t[0] == '6') { + if (t[1] == 'a') + sv_player->v.items = (int) sv_player->v.items | HIT_PROXIMITY_GUN; + else + sv_player->v.items = (int) sv_player->v.items | IT_GRENADE_LAUNCHER; + } else if (t[0] == '9') + sv_player->v.items = (int) sv_player->v.items | HIT_LASER_CANNON; + else if (t[0] == '0') + sv_player->v.items = (int) sv_player->v.items | HIT_MJOLNIR; + else if (t[0] >= '2') + sv_player->v.items = (int) sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); + } else { + if (t[0] >= '2') + sv_player->v.items = (int) sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); + } + break; - case 's': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_shells1"); - if (val) - val->_float = v; - } - sv_player->v.ammo_shells = v; - break; + case 's': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_shells1"); + if (val) + val->_float = v; + } + sv_player->v.ammo_shells = v; + break; - case 'n': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_nails1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_nails = v; - } - } - else - { - sv_player->v.ammo_nails = v; - } - break; + case 'n': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_nails1"); + if (val) { + val->_float = v; + if (sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_nails = v; + } + } else { + sv_player->v.ammo_nails = v; + } + break; - case 'l': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_lava_nails"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_nails = v; - } - } - break; + case 'l': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_lava_nails"); + if (val) { + val->_float = v; + if (sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_nails = v; + } + } + break; - case 'r': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_rockets1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_rockets = v; - } - } - else - { - sv_player->v.ammo_rockets = v; - } - break; + case 'r': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_rockets1"); + if (val) { + val->_float = v; + if (sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_rockets = v; + } + } else { + sv_player->v.ammo_rockets = v; + } + break; - case 'm': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_multi_rockets"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_rockets = v; - } - } - break; + case 'm': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_multi_rockets"); + if (val) { + val->_float = v; + if (sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_rockets = v; + } + } + break; - case 'h': - sv_player->v.health = v; - break; + case 'h': + sv_player->v.health = v; + break; - case 'c': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_cells1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_cells = v; - } - } - else - { - sv_player->v.ammo_cells = v; - } - break; + case 'c': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_cells1"); + if (val) { + val->_float = v; + if (sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_cells = v; + } + } else { + sv_player->v.ammo_cells = v; + } + break; - case 'p': - if (rogue) - { - val = GetEdictFieldValue(sv_player, "ammo_plasma"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_cells = v; - } - } - break; + case 'p': + if (rogue) { + val = GetEdictFieldValue(sv_player, "ammo_plasma"); + if (val) { + val->_float = v; + if (sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_cells = v; + } + } + break; - //johnfitz -- give armour - case 'a': - if (v > 150) - { - sv_player->v.armortype = 0.8; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int)(sv_player->v.items) & (int)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR3; - } - else if (v > 100) - { - sv_player->v.armortype = 0.6; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int)(sv_player->v.items) & (int)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR2; - } - else if (v >= 0) - { - sv_player->v.armortype = 0.3; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int)(sv_player->v.items) & (int)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR1; - } - break; - //johnfitz - } + //johnfitz -- give armour + case 'a': + if (v > 150) { + sv_player->v.armortype = 0.8; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int) (sv_player->v.items) & (int) (IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR3; + } else if (v > 100) { + sv_player->v.armortype = 0.6; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int) (sv_player->v.items) & (int) (IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR2; + } else if (v >= 0) { + sv_player->v.armortype = 0.3; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int) (sv_player->v.items) & (int) (IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR1; + } + break; + //johnfitz + } - //johnfitz -- update currentammo to match new ammo (so statusbar updates correctly) - switch ((int)(sv_player->v.weapon)) - { - case IT_SHOTGUN: - case IT_SUPER_SHOTGUN: - sv_player->v.currentammo = sv_player->v.ammo_shells; - break; - case IT_NAILGUN: - case IT_SUPER_NAILGUN: - case RIT_LAVA_SUPER_NAILGUN: - sv_player->v.currentammo = sv_player->v.ammo_nails; - break; - case IT_GRENADE_LAUNCHER: - case IT_ROCKET_LAUNCHER: - case RIT_MULTI_GRENADE: - case RIT_MULTI_ROCKET: - sv_player->v.currentammo = sv_player->v.ammo_rockets; - break; - case IT_LIGHTNING: - case HIT_LASER_CANNON: - case HIT_MJOLNIR: - sv_player->v.currentammo = sv_player->v.ammo_cells; - break; - case RIT_LAVA_NAILGUN: //same as IT_AXE - if (rogue) - sv_player->v.currentammo = sv_player->v.ammo_nails; - break; - case RIT_PLASMA_GUN: //same as HIT_PROXIMITY_GUN - if (rogue) - sv_player->v.currentammo = sv_player->v.ammo_cells; - if (hipnotic) - sv_player->v.currentammo = sv_player->v.ammo_rockets; - break; - } - //johnfitz + //johnfitz -- update currentammo to match new ammo (so statusbar updates correctly) + switch ((int) (sv_player->v.weapon)) { + case IT_SHOTGUN: + case IT_SUPER_SHOTGUN: + sv_player->v.currentammo = sv_player->v.ammo_shells; + break; + case IT_NAILGUN: + case IT_SUPER_NAILGUN: + case RIT_LAVA_SUPER_NAILGUN: + sv_player->v.currentammo = sv_player->v.ammo_nails; + break; + case IT_GRENADE_LAUNCHER: + case IT_ROCKET_LAUNCHER: + case RIT_MULTI_GRENADE: + case RIT_MULTI_ROCKET: + sv_player->v.currentammo = sv_player->v.ammo_rockets; + break; + case IT_LIGHTNING: + case HIT_LASER_CANNON: + case HIT_MJOLNIR: + sv_player->v.currentammo = sv_player->v.ammo_cells; + break; + case RIT_LAVA_NAILGUN: //same as IT_AXE + if (rogue) + sv_player->v.currentammo = sv_player->v.ammo_nails; + break; + case RIT_PLASMA_GUN: //same as HIT_PROXIMITY_GUN + if (rogue) + sv_player->v.currentammo = sv_player->v.ammo_cells; + if (hipnotic) + sv_player->v.currentammo = sv_player->v.ammo_rockets; + break; + } + //johnfitz } -static edict_t *FindViewthing (void) -{ - int i; - edict_t *e; +static edict_t *FindViewthing(void) { + int i; + edict_t *e; - for (i=0 ; iv.classname), "viewthing") ) - return e; - } - Con_Printf ("No viewthing on map\n"); - return NULL; + for (i = 0; i < sv.num_edicts; i++) { + e = EDICT_NUM(i); + if (!strcmp(PR_GetString(e->v.classname), "viewthing")) + return e; + } + Con_Printf("No viewthing on map\n"); + return NULL; } /* @@ -2116,24 +1895,22 @@ static edict_t *FindViewthing (void) Host_Viewmodel_f ================== */ -static void Host_Viewmodel_f (void) -{ - edict_t *e; - qmodel_t *m; +static void Host_Viewmodel_f(void) { + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) - return; + e = FindViewthing(); + if (!e) + return; - m = Mod_ForName (command::argv(1).value_or("").c_str(), false); - if (!m) - { - Con_Printf ("Can't load %s\n", command::argv(1).value_or("").c_str()); - return; - } + m = Mod_ForName(command::argv(1).value_or("").c_str(), false); + if (!m) { + Con_Printf("Can't load %s\n", command::argv(1).value_or("").c_str()); + return; + } - e->v.frame = 0; - cl.model_precache[(int)e->v.modelindex] = m; + e->v.frame = 0; + cl.model_precache[(int) e->v.modelindex] = m; } /* @@ -2141,35 +1918,33 @@ static void Host_Viewmodel_f (void) Host_Viewframe_f ================== */ -static void Host_Viewframe_f (void) -{ - edict_t *e; - int f; - qmodel_t *m; +static void Host_Viewframe_f(void) { + edict_t *e; + int f; + qmodel_t *m; - e = FindViewthing (); - if (!e) - return; - m = cl.model_precache[(int)e->v.modelindex]; + e = FindViewthing(); + if (!e) + return; + m = cl.model_precache[(int) e->v.modelindex]; - f = atoi(command::argv(1).value_or("").c_str()); - if (f >= m->numframes) - f = m->numframes - 1; + f = atoi(command::argv(1).value_or("").c_str()); + if (f >= m->numframes) + f = m->numframes - 1; - e->v.frame = f; + e->v.frame = f; } -static void PrintFrameName (qmodel_t *m, int frame) -{ - aliashdr_t *hdr; - maliasframedesc_t *pframedesc; +static void PrintFrameName(qmodel_t *m, int frame) { + aliashdr_t *hdr; + maliasframedesc_t *pframedesc; - hdr = (aliashdr_t *)Mod_Extradata (m); - if (!hdr) - return; - pframedesc = &hdr->frames[frame]; + hdr = (aliashdr_t *) Mod_Extradata(m); + if (!hdr) + return; + pframedesc = &hdr->frames[frame]; - Con_Printf ("frame %i: %s\n", frame, pframedesc->name); + Con_Printf("frame %i: %s\n", frame, pframedesc->name); } /* @@ -2177,21 +1952,20 @@ static void PrintFrameName (qmodel_t *m, int frame) Host_Viewnext_f ================== */ -static void Host_Viewnext_f (void) -{ - edict_t *e; - qmodel_t *m; +static void Host_Viewnext_f(void) { + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) - return; - m = cl.model_precache[(int)e->v.modelindex]; + e = FindViewthing(); + if (!e) + return; + m = cl.model_precache[(int) e->v.modelindex]; - e->v.frame = e->v.frame + 1; - if (e->v.frame >= m->numframes) - e->v.frame = m->numframes - 1; + e->v.frame = e->v.frame + 1; + if (e->v.frame >= m->numframes) + e->v.frame = m->numframes - 1; - PrintFrameName (m, e->v.frame); + PrintFrameName(m, e->v.frame); } /* @@ -2199,22 +1973,21 @@ static void Host_Viewnext_f (void) Host_Viewprev_f ================== */ -static void Host_Viewprev_f (void) -{ - edict_t *e; - qmodel_t *m; +static void Host_Viewprev_f(void) { + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) - return; + e = FindViewthing(); + if (!e) + return; - m = cl.model_precache[(int)e->v.modelindex]; + m = cl.model_precache[(int) e->v.modelindex]; - e->v.frame = e->v.frame - 1; - if (e->v.frame < 0) - e->v.frame = 0; + e->v.frame = e->v.frame - 1; + if (e->v.frame < 0) + e->v.frame = 0; - PrintFrameName (m, e->v.frame); + PrintFrameName(m, e->v.frame); } /* @@ -2230,40 +2003,35 @@ DEMO LOOP CONTROL Host_Startdemos_f ================== */ -static void Host_Startdemos_f (void) -{ - int i, c; +static void Host_Startdemos_f(void) { + int i, c; - if (cls.state == ca_dedicated) - return; + if (cls.state == ca_dedicated) + return; - c = command::argc() - 1; - if (c > MAX_DEMOS) - { - Con_Printf ("Max %i demos in demoloop\n", MAX_DEMOS); - c = MAX_DEMOS; - } - Con_Printf ("%i demo(s) in loop\n", c); + c = command::argc() - 1; + if (c > MAX_DEMOS) { + Con_Printf("Max %i demos in demoloop\n", MAX_DEMOS); + c = MAX_DEMOS; + } + Con_Printf("%i demo(s) in loop\n", c); - for (i = 1; i < c + 1; i++) - q_strlcpy (cls.demos[i-1], command::argv(i)->c_str(), sizeof(cls.demos[0])); + for (i = 1; i < c + 1; i++) + q_strlcpy(cls.demos[i - 1], command::argv(i)->c_str(), sizeof(cls.demos[0])); - if (!sv.active && cls.demonum != -1 && !cls.demoplayback) - { - cls.demonum = 0; - if (!fitzmode && !cl_startdemos.value) - { /* QuakeSpasm customization: */ - /* go straight to menu, no CL_NextDemo */ - cls.demonum = -1; - Cbuf_InsertText("menu_main\n"); - return; - } - CL_NextDemo (); - } - else - { - cls.demonum = -1; - } + if (!sv.active && cls.demonum != -1 && !cls.demoplayback) { + cls.demonum = 0; + if (!fitzmode && !cl_startdemos.value) { + /* QuakeSpasm customization: */ + /* go straight to menu, no CL_NextDemo */ + cls.demonum = -1; + command::buffer::insert_text("menu_main\n"); + return; + } + CL_NextDemo(); + } else { + cls.demonum = -1; + } } /* @@ -2273,14 +2041,13 @@ Host_Demos_f Return to looping demos ================== */ -static void Host_Demos_f (void) -{ - if (cls.state == ca_dedicated) - return; - if (cls.demonum == -1) - cls.demonum = 1; - CL_Disconnect_f (); - CL_NextDemo (); +static void Host_Demos_f(void) { + if (cls.state == ca_dedicated) + return; + if (cls.demonum == -1) + cls.demonum = 1; + CL_Disconnect_f(); + CL_NextDemo(); } /* @@ -2290,14 +2057,13 @@ Host_Stopdemo_f Return to looping demos ================== */ -static void Host_Stopdemo_f (void) -{ - if (cls.state == ca_dedicated) - return; - if (!cls.demoplayback) - return; - CL_StopPlayback (); - CL_Disconnect (); +static void Host_Stopdemo_f(void) { + if (cls.state == ca_dedicated) + return; + if (!cls.demoplayback) + return; + CL_StopPlayback(); + CL_Disconnect(); } /* @@ -2307,10 +2073,9 @@ Host_Resetdemos Clear looping demo list (called on game change) ================== */ -void Host_Resetdemos (void) -{ - memset (cls.demos, 0, sizeof (cls.demos)); - cls.demonum = 0; +void Host_Resetdemos(void) { + memset(cls.demos, 0, sizeof (cls.demos)); + cls.demonum = 0; } //============================================================================= @@ -2320,51 +2085,49 @@ void Host_Resetdemos (void) Host_InitCommands ================== */ -void Host_InitCommands (void) -{ - command::add ("maps", Host_Maps_f); //johnfitz - command::add ("mods", Host_Mods_f); //johnfitz - command::add ("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm - command::add ("mapname", Host_Mapname_f); //johnfitz - command::add ("randmap", Host_Randmap_f); //ericw +void Host_InitCommands(void) { + command::add("maps", Host_Maps_f); //johnfitz + command::add("mods", Host_Mods_f); //johnfitz + command::add("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm + command::add("mapname", Host_Mapname_f); //johnfitz + command::add("randmap", Host_Randmap_f); //ericw - command::add ("status", Host_Status_f); - command::add ("quit", Host_Quit_f); - command::add ("god", Host_God_f); - command::add("buddha", Host_Buddha_f); - command::add ("notarget", Host_Notarget_f); - command::add ("fly", Host_Fly_f); - command::add ("map", Host_Map_f); - command::add ("restart", Host_Restart_f); - command::add ("changelevel", Host_Changelevel_f); - command::add ("connect", Host_Connect_f); - command::add ("reconnect", Host_Reconnect_f); - command::add ("name", Host_Name_f); - command::add ("noclip", Host_Noclip_f); - command::add ("setpos", Host_SetPos_f); //QuakeSpasm + command::add("status", Host_Status_f); + command::add("quit", Host_Quit_f); + command::add("god", Host_God_f); + command::add("buddha", Host_Buddha_f); + command::add("notarget", Host_Notarget_f); + command::add("fly", Host_Fly_f); + command::add("map", Host_Map_f); + command::add("restart", Host_Restart_f); + command::add("changelevel", Host_Changelevel_f); + command::add("connect", Host_Connect_f); + command::add("reconnect", Host_Reconnect_f); + command::add("name", Host_Name_f); + command::add("noclip", Host_Noclip_f); + command::add("setpos", Host_SetPos_f); //QuakeSpasm - command::add ("say", Host_Say_f); - command::add ("say_team", Host_Say_Team_f); - command::add ("tell", Host_Tell_f); - command::add ("color", Host_Color_f); - command::add ("kill", Host_Kill_f); - command::add ("pause", Host_Pause_f); - command::add ("spawn", Host_Spawn_f); - command::add ("begin", Host_Begin_f); - command::add ("prespawn", Host_PreSpawn_f); - command::add ("kick", Host_Kick_f); - command::add ("ping", Host_Ping_f); - command::add ("load", Host_Loadgame_f); - command::add ("save", Host_Savegame_f); - command::add ("give", Host_Give_f); + command::add("say", Host_Say_f); + command::add("say_team", Host_Say_Team_f); + command::add("tell", Host_Tell_f); + command::add("color", Host_Color_f); + command::add("kill", Host_Kill_f); + command::add("pause", Host_Pause_f); + command::add("spawn", Host_Spawn_f); + command::add("begin", Host_Begin_f); + command::add("prespawn", Host_PreSpawn_f); + command::add("kick", Host_Kick_f); + command::add("ping", Host_Ping_f); + command::add("load", Host_Loadgame_f); + command::add("save", Host_Savegame_f); + command::add("give", Host_Give_f); - command::add ("startdemos", Host_Startdemos_f); - command::add ("demos", Host_Demos_f); - command::add ("stopdemo", Host_Stopdemo_f); + command::add("startdemos", Host_Startdemos_f); + command::add("demos", Host_Demos_f); + command::add("stopdemo", Host_Stopdemo_f); - command::add ("viewmodel", Host_Viewmodel_f); - command::add ("viewframe", Host_Viewframe_f); - command::add ("viewnext", Host_Viewnext_f); - command::add ("viewprev", Host_Viewprev_f); + command::add("viewmodel", Host_Viewmodel_f); + command::add("viewframe", Host_Viewframe_f); + command::add("viewnext", Host_Viewnext_f); + command::add("viewprev", Host_Viewprev_f); } - diff --git a/Quake/image.cpp b/Quake/image.cpp index 6369890..ad18974 100644 --- a/Quake/image.cpp +++ b/Quake/image.cpp @@ -31,42 +31,40 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define LODEPNG_NO_COMPILE_CPP #define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS #define LODEPNG_NO_COMPILE_ERROR_TEXT +#include + #include "lodepng.hpp" #include "lodepng.cpp" static char loadfilename[MAX_OSPATH]; //file scope so that error messages can use it typedef struct stdio_buffer_s { - FILE *f; - unsigned char buffer[1024]; - int size; - int pos; + FILE *f; + unsigned char buffer[1024]; + int size; + int pos; } stdio_buffer_t; -static stdio_buffer_t *Buf_Alloc(FILE *f) -{ - stdio_buffer_t *buf = (stdio_buffer_t *) calloc(1, sizeof(stdio_buffer_t)); - buf->f = f; - return buf; +static stdio_buffer_t *Buf_Alloc(FILE *f) { + stdio_buffer_t *buf = (stdio_buffer_t *) calloc(1, sizeof(stdio_buffer_t)); + buf->f = f; + return buf; } -static void Buf_Free(stdio_buffer_t *buf) -{ - free(buf); +static void Buf_Free(stdio_buffer_t *buf) { + free(buf); } -static inline int Buf_GetC(stdio_buffer_t *buf) -{ - if (buf->pos >= buf->size) - { - buf->size = fread(buf->buffer, 1, sizeof(buf->buffer), buf->f); - buf->pos = 0; - - if (buf->size == 0) - return EOF; - } +static inline int Buf_GetC(stdio_buffer_t *buf) { + if (buf->pos >= buf->size) { + buf->size = fread(buf->buffer, 1, sizeof(buf->buffer), buf->f); + buf->pos = 0; - return buf->buffer[buf->pos++]; + if (buf->size == 0) + return EOF; + } + + return buf->buffer[buf->pos++]; } /* @@ -78,21 +76,20 @@ returns a pointer to hunk allocated RGBA data TODO: search order: tga png jpg pcx lmp ============ */ -byte *Image_LoadImage (const char *name, int *width, int *height) -{ - FILE *f; +byte *Image_LoadImage(const char *name, int *width, int *height) { + FILE *f; - q_snprintf (loadfilename, sizeof(loadfilename), "%s.tga", name); - COM_FOpenFile (loadfilename, &f, NULL); - if (f) - return Image_LoadTGA (f, width, height); + q_snprintf(loadfilename, sizeof(loadfilename), "%s.tga", name); + COM_FOpenFile(loadfilename, &f, NULL); + if (f) + return Image_LoadTGA(f, width, height); - q_snprintf (loadfilename, sizeof(loadfilename), "%s.pcx", name); - COM_FOpenFile (loadfilename, &f, NULL); - if (f) - return Image_LoadPCX (f, width, height); + q_snprintf(loadfilename, sizeof(loadfilename), "%s.pcx", name); + COM_FOpenFile(loadfilename, &f, NULL); + if (f) + return Image_LoadPCX(f, width, height); - return NULL; + return NULL; } //============================================================================== @@ -102,35 +99,33 @@ byte *Image_LoadImage (const char *name, int *width, int *height) //============================================================================== typedef struct targaheader_s { - unsigned char id_length, colormap_type, image_type; - unsigned short colormap_index, colormap_length; - unsigned char colormap_size; - unsigned short x_origin, y_origin, width, height; - unsigned char pixel_size, attributes; + unsigned char id_length, colormap_type, image_type; + unsigned short colormap_index, colormap_length; + unsigned char colormap_size; + unsigned short x_origin, y_origin, width, height; + unsigned char pixel_size, attributes; } targaheader_t; #define TARGAHEADERSIZE 18 /* size on disk */ -int fgetLittleShort (FILE *f) -{ - byte b1, b2; +int fgetLittleShort(FILE *f) { + byte b1, b2; - b1 = fgetc(f); - b2 = fgetc(f); + b1 = fgetc(f); + b2 = fgetc(f); - return (short)(b1 + b2*256); + return (short) (b1 + b2 * 256); } -int fgetLittleLong (FILE *f) -{ - byte b1, b2, b3, b4; +int fgetLittleLong(FILE *f) { + byte b1, b2, b3, b4; - b1 = fgetc(f); - b2 = fgetc(f); - b3 = fgetc(f); - b4 = fgetc(f); + b1 = fgetc(f); + b2 = fgetc(f); + b3 = fgetc(f); + b4 = fgetc(f); - return b1 + (b2<<8) + (b3<<16) + (b4<<24); + return b1 + (b2 << 8) + (b3 << 16) + (b4 << 24); } /* @@ -142,43 +137,41 @@ returns true if successful TODO: support BGRA and BGR formats (since opengl can return them, and we don't have to swap) ============ */ -qboolean Image_WriteTGA (const char *name, byte *data, int width, int height, int bpp, qboolean upsidedown) -{ - int handle, i, size, temp, bytes; - char pathname[MAX_OSPATH]; - byte header[TARGAHEADERSIZE]; +bool Image_WriteTGA(const char *name, byte *data, int width, int height, int bpp, bool upsidedown) { + int handle, i, size, temp, bytes; + char pathname[MAX_OSPATH]; + byte header[TARGAHEADERSIZE]; - Sys_mkdir (com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash - q_snprintf (pathname, sizeof(pathname), "%s/%s", com_gamedir, name); - handle = Sys_FileOpenWrite (pathname); - if (handle == -1) - return false; + Sys_mkdir(com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash + q_snprintf(pathname, sizeof(pathname), "%s/%s", com_gamedir, name); + handle = Sys_FileOpenWrite(pathname); + if (handle == -1) + return false; - Q_memset (header, 0, TARGAHEADERSIZE); - header[2] = 2; // uncompressed type - header[12] = width&255; - header[13] = width>>8; - header[14] = height&255; - header[15] = height>>8; - header[16] = bpp; // pixel size - if (upsidedown) - header[17] = 0x20; //upside-down attribute + std::memset(header, 0, TARGAHEADERSIZE); + header[2] = 2; // uncompressed type + header[12] = width & 255; + header[13] = width >> 8; + header[14] = height & 255; + header[15] = height >> 8; + header[16] = bpp; // pixel size + if (upsidedown) + header[17] = 0x20; //upside-down attribute - // swap red and blue bytes - bytes = bpp/8; - size = width*height*bytes; - for (i=0; i 256) - Sys_Error ("Image_LoadTGA: %s has an %ibit palette", loadfilename, targa_header.colormap_type); - } - else - { - if (targa_header.image_type!=2 && targa_header.image_type!=10) - Sys_Error ("Image_LoadTGA: %s is not a type 2 or type 10 targa (%i)", loadfilename, targa_header.image_type); + if (targa_header.image_type == 1) { + if (targa_header.pixel_size != 8 || targa_header.colormap_size != 24 || targa_header.colormap_length > 256) + Sys_Error("Image_LoadTGA: %s has an %ibit palette", loadfilename, targa_header.colormap_type); + } else { + if (targa_header.image_type != 2 && targa_header.image_type != 10) + Sys_Error("Image_LoadTGA: %s is not a type 2 or type 10 targa (%i)", loadfilename, targa_header.image_type); - if (targa_header.colormap_type !=0 || (targa_header.pixel_size!=32 && targa_header.pixel_size!=24)) - Sys_Error ("Image_LoadTGA: %s is not a 24bit or 32bit targa", loadfilename); - } + if (targa_header.colormap_type != 0 || (targa_header.pixel_size != 32 && targa_header.pixel_size != 24)) + Sys_Error("Image_LoadTGA: %s is not a 24bit or 32bit targa", loadfilename); + } - columns = targa_header.width; - rows = targa_header.height; - numPixels = columns * rows; - upside_down = !(targa_header.attributes & 0x20); //johnfitz -- fix for upside-down targas + columns = targa_header.width; + rows = targa_header.height; + numPixels = columns * rows; + upside_down = !(targa_header.attributes & 0x20); //johnfitz -- fix for upside-down targas - targa_rgba = (byte *) Hunk_Alloc (numPixels*4); + targa_rgba = (byte *) Hunk_Alloc(numPixels * 4); - if (targa_header.id_length != 0) - fseek(fin, targa_header.id_length, SEEK_CUR); // skip TARGA image comment + if (targa_header.id_length != 0) + fseek(fin, targa_header.id_length, SEEK_CUR); // skip TARGA image comment - buf = Buf_Alloc(fin); + buf = Buf_Alloc(fin); - if (targa_header.image_type==1) // Uncompressed, paletted images - { - byte palette[256*4]; - int i; - //palette data comes first - for (i = 0; i < targa_header.colormap_length; i++) - { //this palette data is bgr. - palette[i*3+2] = Buf_GetC(buf); - palette[i*3+1] = Buf_GetC(buf); - palette[i*3+0] = Buf_GetC(buf); - palette[i*3+3] = 255; - } - for (i = targa_header.colormap_length*4; i < sizeof(palette); i++) - palette[i] = 0; - for(row=rows-1; row>=0; row--) - { - realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; + if (targa_header.image_type == 1) // Uncompressed, paletted images + { + byte palette[256 * 4]; + int i; + //palette data comes first + for (i = 0; i < targa_header.colormap_length; i++) { + //this palette data is bgr. + palette[i * 3 + 2] = Buf_GetC(buf); + palette[i * 3 + 1] = Buf_GetC(buf); + palette[i * 3 + 0] = Buf_GetC(buf); + palette[i * 3 + 3] = 255; + } + for (i = targa_header.colormap_length * 4; i < sizeof(palette); i++) + palette[i] = 0; + for (row = rows - 1; row >= 0; row--) { + realrow = upside_down ? row : rows - 1 - row; + pixbuf = targa_rgba + realrow * columns * 4; - for(column=0; column=0; row--) - { - //johnfitz -- fix for upside-down targas - realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; - //johnfitz - for(column=0; column=0; row--) - { - //johnfitz -- fix for upside-down targas - realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; - //johnfitz - for(column=0; column= 0; row--) { + //johnfitz -- fix for upside-down targas + realrow = upside_down ? row : rows - 1 - row; + pixbuf = targa_rgba + realrow * columns * 4; + //johnfitz + for (column = 0; column < columns; column++) { + unsigned char red, green, blue, alphabyte; + switch (targa_header.pixel_size) { + case 24: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = 255; + break; + case 32: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + alphabyte = Buf_GetC(buf); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = alphabyte; + break; + } + } + } + } else if (targa_header.image_type == 10) // Runlength encoded RGB images + { + unsigned char red, green, blue, alphabyte, packetHeader, packetSize, j; + for (row = rows - 1; row >= 0; row--) { + //johnfitz -- fix for upside-down targas + realrow = upside_down ? row : rows - 1 - row; + pixbuf = targa_rgba + realrow * columns * 4; + //johnfitz + for (column = 0; column < columns;) { + packetHeader = Buf_GetC(buf); + packetSize = 1 + (packetHeader & 0x7f); + if (packetHeader & 0x80) // run-length packet + { + switch (targa_header.pixel_size) { + case 24: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + alphabyte = 255; + break; + case 32: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + alphabyte = Buf_GetC(buf); + break; + default: /* avoid compiler warnings */ + blue = red = green = alphabyte = 0; + } - for(j=0;j0) - row--; - else - goto breakOut; - //johnfitz -- fix for upside-down targas - realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; - //johnfitz - } - } - } - else // non run-length packet - { - for(j=0;j0) - row--; - else - goto breakOut; - //johnfitz -- fix for upside-down targas - realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; - //johnfitz - } - } - } - } - breakOut:; - } - } + for (j = 0; j < packetSize; j++) { + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = alphabyte; + column++; + if (column == columns) // run spans across rows + { + column = 0; + if (row > 0) + row--; + else + goto breakOut; + //johnfitz -- fix for upside-down targas + realrow = upside_down ? row : rows - 1 - row; + pixbuf = targa_rgba + realrow * columns * 4; + //johnfitz + } + } + } else // non run-length packet + { + for (j = 0; j < packetSize; j++) { + switch (targa_header.pixel_size) { + case 24: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = 255; + break; + case 32: + blue = Buf_GetC(buf); + green = Buf_GetC(buf); + red = Buf_GetC(buf); + alphabyte = Buf_GetC(buf); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = alphabyte; + break; + default: /* avoid compiler warnings */ + blue = red = green = alphabyte = 0; + } + column++; + if (column == columns) // pixel packet run spans across rows + { + column = 0; + if (row > 0) + row--; + else + goto breakOut; + //johnfitz -- fix for upside-down targas + realrow = upside_down ? row : rows - 1 - row; + pixbuf = targa_rgba + realrow * columns * 4; + //johnfitz + } + } + } + } + breakOut:; + } + } - Buf_Free(buf); - fclose(fin); + Buf_Free(buf); + fclose(fin); - *width = (int)(targa_header.width); - *height = (int)(targa_header.height); - return targa_rgba; + *width = (int) (targa_header.width); + *height = (int) (targa_header.height); + return targa_rgba; } //============================================================================== @@ -418,20 +393,19 @@ byte *Image_LoadTGA (FILE *fin, int *width, int *height) // //============================================================================== -typedef struct -{ - char signature; - char version; - char encoding; - char bits_per_pixel; - unsigned short xmin,ymin,xmax,ymax; - unsigned short hdpi,vdpi; - byte colortable[48]; - char reserved; - char color_planes; - unsigned short bytes_per_line; - unsigned short palette_type; - char filler[58]; +typedef struct { + char signature; + char version; + char encoding; + char bits_per_pixel; + unsigned short xmin, ymin, xmax, ymax; + unsigned short hdpi, vdpi; + byte colortable[48]; + char reserved; + char color_planes; + unsigned short bytes_per_line; + unsigned short palette_type; + char filler[58]; } pcxheader_t; /* @@ -439,82 +413,78 @@ typedef struct Image_LoadPCX ============ */ -byte *Image_LoadPCX (FILE *f, int *width, int *height) -{ - pcxheader_t pcx; - int x, y, w, h, readbyte, runlength, start; - byte *p, *data; - byte palette[768]; - stdio_buffer_t *buf; +byte *Image_LoadPCX(FILE *f, int *width, int *height) { + pcxheader_t pcx; + int x, y, w, h, readbyte, runlength, start; + byte *p, *data; + byte palette[768]; + stdio_buffer_t *buf; - start = ftell (f); //save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx) + start = ftell(f); + //save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx) - if (!fread(&pcx, sizeof(pcx), 1, f)) - Sys_Error ("Failed reading header from '%s'", loadfilename); - pcx.xmin = (unsigned short)LittleShort (pcx.xmin); - pcx.ymin = (unsigned short)LittleShort (pcx.ymin); - pcx.xmax = (unsigned short)LittleShort (pcx.xmax); - pcx.ymax = (unsigned short)LittleShort (pcx.ymax); - pcx.bytes_per_line = (unsigned short)LittleShort (pcx.bytes_per_line); + if (!fread(&pcx, sizeof(pcx), 1, f)) + Sys_Error("Failed reading header from '%s'", loadfilename); + pcx.xmin = (unsigned short) LittleShort(pcx.xmin); + pcx.ymin = (unsigned short) LittleShort(pcx.ymin); + pcx.xmax = (unsigned short) LittleShort(pcx.xmax); + pcx.ymax = (unsigned short) LittleShort(pcx.ymax); + pcx.bytes_per_line = (unsigned short) LittleShort(pcx.bytes_per_line); - if (pcx.signature != 0x0A) - Sys_Error ("'%s' is not a valid PCX file", loadfilename); + if (pcx.signature != 0x0A) + Sys_Error("'%s' is not a valid PCX file", loadfilename); - if (pcx.version != 5) - Sys_Error ("'%s' is version %i, should be 5", loadfilename, pcx.version); + if (pcx.version != 5) + Sys_Error("'%s' is version %i, should be 5", loadfilename, pcx.version); - if (pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1) - Sys_Error ("'%s' has wrong encoding or bit depth", loadfilename); + if (pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1) + Sys_Error("'%s' has wrong encoding or bit depth", loadfilename); - w = pcx.xmax - pcx.xmin + 1; - h = pcx.ymax - pcx.ymin + 1; + w = pcx.xmax - pcx.xmin + 1; + h = pcx.ymax - pcx.ymin + 1; - data = (byte *) Hunk_Alloc((w*h+1)*4); //+1 to allow reading padding byte on last line + data = (byte *) Hunk_Alloc((w * h + 1) * 4); //+1 to allow reading padding byte on last line - //load palette - fseek (f, start + com_filesize - 768, SEEK_SET); - if (!fread (palette, 768, 1, f)) - Sys_Error ("Failed reading palette from '%s'", loadfilename); + //load palette + fseek(f, start + com_filesize - 768, SEEK_SET); + if (!fread(palette, 768, 1, f)) + Sys_Error("Failed reading palette from '%s'", loadfilename); - //back to start of image data - fseek (f, start + sizeof(pcx), SEEK_SET); + //back to start of image data + fseek(f, start + sizeof(pcx), SEEK_SET); - buf = Buf_Alloc(f); + buf = Buf_Alloc(f); - for (y=0; y= 0xC0) - { - runlength = readbyte & 0x3F; - readbyte = Buf_GetC(buf); - } - else - runlength = 1; + if (readbyte >= 0xC0) { + runlength = readbyte & 0x3F; + readbyte = Buf_GetC(buf); + } else + runlength = 1; - while(runlength--) - { - p[0] = palette[readbyte*3]; - p[1] = palette[readbyte*3+1]; - p[2] = palette[readbyte*3+2]; - p[3] = 255; - p += 4; - x++; - } - } - } + while (runlength--) { + p[0] = palette[readbyte * 3]; + p[1] = palette[readbyte * 3 + 1]; + p[2] = palette[readbyte * 3 + 2]; + p[3] = 255; + p += 4; + x++; + } + } + } - Buf_Free(buf); - fclose(f); + Buf_Free(buf); + fclose(f); - *width = w; - *height = h; - return data; + *width = w; + *height = h; + return data; } //============================================================================== @@ -523,21 +493,19 @@ byte *Image_LoadPCX (FILE *f, int *width, int *height) // //============================================================================== -static byte *CopyFlipped(const byte *data, int width, int height, int bpp) -{ - int y, rowsize; - byte *flipped; +static byte *CopyFlipped(const byte *data, int width, int height, int bpp) { + int y, rowsize; + byte *flipped; - rowsize = width * (bpp / 8); - flipped = (byte *) malloc(height * rowsize); - if (!flipped) - return NULL; + rowsize = width * (bpp / 8); + flipped = (byte *) malloc(height * rowsize); + if (!flipped) + return NULL; - for (y=0; y Q_COUNTOF(buttonremap)) { + event.button.button > std::size(buttonremap)) { Con_Printf("Ignored event for mouse button %d\n", event.button.button); break; diff --git a/Quake/input.hpp b/Quake/input.hpp index 212d4cb..baf0370 100644 --- a/Quake/input.hpp +++ b/Quake/input.hpp @@ -51,6 +51,6 @@ void IN_ClearStates (void); void IN_Activate (void); // called when the app becomes inactive -void IN_Deactivate (qboolean free_cursor); +void IN_Deactivate (bool free_cursor); #endif diff --git a/Quake/keys.cpp b/Quake/keys.cpp index 78e42db..acac0f9 100644 --- a/Quake/keys.cpp +++ b/Quake/keys.cpp @@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include + #include "quakedef.hpp" #include "arch_def.hpp" @@ -40,9 +42,9 @@ int history_line = 0; keydest_t key_dest; char *keybindings[MAX_KEYS]; -qboolean consolekeys[MAX_KEYS]; // if true, can't be rebound while in console -qboolean menubound[MAX_KEYS]; // if true, can't be rebound while in menu -qboolean keydown[MAX_KEYS]; +bool consolekeys[MAX_KEYS]; // if true, can't be rebound while in console +bool menubound[MAX_KEYS]; // if true, can't be rebound while in menu +bool keydown[MAX_KEYS]; typedef struct { @@ -250,8 +252,8 @@ void Key_Console (int key) case K_ENTER: case K_KP_ENTER: key_tabpartial[0] = 0; - Cbuf_AddText (workline + 1); // skip the prompt - Cbuf_AddText ("\n"); + command::buffer::add_text (workline + 1); // skip the prompt + command::buffer::add_text ("\n"); Con_Printf ("%s\n", workline); // If the last two lines are identical, skip storing this line in history @@ -318,7 +320,7 @@ void Key_Console (int key) if (x != con_linewidth) break; } - con_backscroll = CLAMP(0, con_current-i%con_totallines-2, con_totallines-(glheight>>3)-1); + con_backscroll = std::clamp(con_current-i%con_totallines-2, 0, con_totallines-(glheight>>3)-1); } else key_linepos = 1; return; @@ -370,9 +372,9 @@ void Key_Console (int key) } return; - case K_UPARROW: + case K_UPARROW: if (history_line == edit_line) - Q_strcpy(current, workline); + std::strcpy(current, workline); history_line_last = history_line; do @@ -457,7 +459,7 @@ void Char_Console (int key) if (key_linepos < MAXCMDLINE-1) { - qboolean endpos = !workline[key_linepos]; + bool endpos = !workline[key_linepos]; key_tabpartial[0] = 0; //johnfitz // if inserting, move the text to the right @@ -489,7 +491,7 @@ void Char_Console (int key) //============================================================================ -qboolean chat_team = false; +bool chat_team = false; static char chat_buffer[MAXCMDLINE]; static int chat_bufferlen = 0; @@ -517,11 +519,11 @@ void Key_Message (int key) case K_ENTER: case K_KP_ENTER: if (chat_team) - Cbuf_AddText ("say_team \""); + command::buffer::add_text ("say_team \""); else - Cbuf_AddText ("say \""); - Cbuf_AddText(chat_buffer); - Cbuf_AddText("\"\n"); + command::buffer::add_text ("say \""); + command::buffer::add_text(chat_buffer); + command::buffer::add_text("\"\n"); Key_EndChat (); return; @@ -898,7 +900,7 @@ void Key_Init (void) } static struct { - qboolean active; + bool active; int lastkey; int lastchar; } key_inputgrab = { false, -1, -1 }; @@ -954,7 +956,7 @@ Called by the system between frames for both key up and key down events Should NOT be called during an interrupt! =================== */ -void Key_Event (int key, qboolean down) +void Key_Event (int key, bool down) { Key_EventWithKeycode (key, down, 0); } @@ -969,7 +971,7 @@ keycode parameter should have the key's actual keycode using the current keyboar not necessarily the US-keyboard-based scancode. Pass 0 if not applicable. =================== */ -void Key_EventWithKeycode (int key, qboolean down, int keycode) +void Key_EventWithKeycode (int key, bool down, int keycode) { char *kb; char cmd[1024]; @@ -1053,7 +1055,7 @@ void Key_EventWithKeycode (int key, qboolean down, int keycode) if (kb && kb[0] == '+') { sprintf (cmd, "-%s %i\n", kb+1, key); - Cbuf_AddText (cmd); + command::buffer::add_text (cmd); } return; } @@ -1076,12 +1078,12 @@ void Key_EventWithKeycode (int key, qboolean down, int keycode) if (kb[0] == '+') { // button commands add keynum as a parm sprintf (cmd, "%s %i\n", kb, key); - Cbuf_AddText (cmd); + command::buffer::add_text (cmd); } else { - Cbuf_AddText (kb); - Cbuf_AddText ("\n"); + command::buffer::add_text (kb); + command::buffer::add_text ("\n"); } } return; @@ -1158,7 +1160,7 @@ void Char_Event (int key) Key_TextEntry =================== */ -qboolean Key_TextEntry (void) +bool Key_TextEntry (void) { if (key_inputgrab.active) { @@ -1208,7 +1210,7 @@ Key_UpdateForDest */ void Key_UpdateForDest (void) { - static qboolean forced = false; + static bool forced = false; if (cls.state == ca_dedicated) return; diff --git a/Quake/keys.hpp b/Quake/keys.hpp index 29beddd..cdab0b0 100644 --- a/Quake/keys.hpp +++ b/Quake/keys.hpp @@ -171,7 +171,7 @@ extern int key_linepos; extern int key_insert; extern double key_blinktime; -extern qboolean chat_team; +extern bool chat_team; void Key_Init (void); void Key_ClearStates (void); @@ -181,10 +181,10 @@ void Key_BeginInputGrab (void); void Key_EndInputGrab (void); void Key_GetGrabbedInput (int *lastkey, int *lastchar); -void Key_Event (int key, qboolean down); -void Key_EventWithKeycode (int key, qboolean down, int keycode); +void Key_Event (int key, bool down); +void Key_EventWithKeycode (int key, bool down, int keycode); void Char_Event (int key); -qboolean Key_TextEntry (void); +bool Key_TextEntry (void); void Key_SetBinding (int keynum, const char *binding); const char *Key_KeynumToString (int keynum); diff --git a/Quake/main_sdl.cpp b/Quake/main_sdl.cpp index a530949..3c4da51 100644 --- a/Quake/main_sdl.cpp +++ b/Quake/main_sdl.cpp @@ -33,32 +33,30 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif #include -static void Sys_AtExit (void) -{ - SDL_Quit(); +static void Sys_AtExit(void) { + SDL_Quit(); } -static void Sys_InitSDL (void) -{ +static void Sys_InitSDL(void) { #if defined(USE_SDL2) - SDL_version v; - SDL_version *sdl_version = &v; - SDL_GetVersion(&v); + SDL_version v; + SDL_version *sdl_version = &v; + SDL_GetVersion(&v); #else - const SDL_version *sdl_version = SDL_Linked_Version(); + const SDL_version *sdl_version = SDL_Linked_Version(); #endif - Sys_Printf("Found SDL version %i.%i.%i\n",sdl_version->major,sdl_version->minor,sdl_version->patch); + Sys_Printf("Found SDL version %i.%i.%i\n", sdl_version->major, sdl_version->minor, sdl_version->patch); - if (SDL_Init(0) < 0) { - Sys_Error("Couldn't init SDL: %s", SDL_GetError()); - } - atexit(Sys_AtExit); + if (SDL_Init(0) < 0) { + Sys_Error("Couldn't init SDL: %s", SDL_GetError()); + } + atexit(Sys_AtExit); } #define DEFAULT_MEMORY (256 * 1024 * 1024) // ericw -- was 72MB (64-bit) / 64MB (32-bit) -static quakeparms_t parms; +static quakeparms_t parms; // On OS X we call SDL_main from the launcher, but SDL2 doesn't redefine main // as SDL_main on OS X anymore, so we do it ourselves. @@ -66,92 +64,79 @@ static quakeparms_t parms; #define main SDL_main #endif -int main(int argc, char *argv[]) -{ - int t; - double time, oldtime, newtime; +int main(int argc, char *argv[]) { + double time, oldtime, newtime; - host_parms = &parms; - parms.basedir = "."; + host_parms = &parms; + parms.basedir = "."; - parms.argc = argc; - parms.argv = argv; + parms.argc = argc; + parms.argv = argv; - parms.errstate = 0; + parms.errstate = 0; - COM_InitArgv(parms.argc, parms.argv); + COM_InitArgv(parms.argc, parms.argv); - isDedicated = (COM_CheckParm("-dedicated") != 0); + isDedicated = (common::check_param("-dedicated").has_value()); - Sys_InitSDL (); + Sys_InitSDL(); - Sys_Init(); + Sys_Init(); - Sys_Printf("Initializing QuakeSpasm v%s\n", QUAKESPASM_VER_STRING); + Sys_Printf("Initializing QuakeSpasm v%s\n", QUAKESPASM_VER_STRING); - parms.memsize = DEFAULT_MEMORY; - if (COM_CheckParm("-heapsize")) - { - t = COM_CheckParm("-heapsize") + 1; - if (t < com_argc) - parms.memsize = Q_atoi(com_argv[t]) * 1024; - } + parms.memsize = DEFAULT_MEMORY; + if (common::check_param("-heapsize").has_value()) { + if (const auto t = common::check_param("-heapsize").value() + 1; t < com_argc) + parms.memsize = std::atoi(com_argv[t]) * 1024; + } - parms.membase = malloc (parms.memsize); + parms.membase = malloc(parms.memsize); - if (!parms.membase) - Sys_Error ("Not enough memory free; check disk space\n"); + if (!parms.membase) + Sys_Error("Not enough memory free; check disk space\n"); - Sys_Printf("Host_Init\n"); - Host_Init(); + Sys_Printf("Host_Init\n"); + Host_Init(); - oldtime = Sys_DoubleTime(); - if (isDedicated) - { - while (1) - { - newtime = Sys_DoubleTime (); - time = newtime - oldtime; + oldtime = Sys_DoubleTime(); + if (isDedicated) { + while (1) { + newtime = Sys_DoubleTime(); + time = newtime - oldtime; - while (time < sys_ticrate.value ) - { - SDL_Delay(1); - newtime = Sys_DoubleTime (); - time = newtime - oldtime; - } + while (time < sys_ticrate.value) { + SDL_Delay(1); + newtime = Sys_DoubleTime(); + time = newtime - oldtime; + } - Host_Frame (time); - oldtime = newtime; - } - } - else - while (1) - { - /* If we have no input focus at all, sleep a bit */ - if (!VID_HasMouseOrInputFocus() || cl.paused) - { - SDL_Delay(16); - } - /* If we're minimised, sleep a bit more */ - if (VID_IsMinimized()) - { - scr_skipupdate = 1; - SDL_Delay(32); - } - else - { - scr_skipupdate = 0; - } - newtime = Sys_DoubleTime (); - time = newtime - oldtime; + Host_Frame(time); + oldtime = newtime; + } + } else + while (1) { + /* If we have no input focus at all, sleep a bit */ + if (!VID_HasMouseOrInputFocus() || cl.paused) { + SDL_Delay(16); + } + /* If we're minimised, sleep a bit more */ + if (VID_IsMinimized()) { + scr_skipupdate = 1; + SDL_Delay(32); + } else { + scr_skipupdate = 0; + } + newtime = Sys_DoubleTime(); + time = newtime - oldtime; - Host_Frame (time); + Host_Frame(time); - if (time < sys_throttle.value && !cls.timedemo) - SDL_Delay(1); + if (time < sys_throttle.value && !cls.timedemo) + SDL_Delay(1); - oldtime = newtime; - } + oldtime = newtime; + } - return 0; + return 0; } diff --git a/Quake/menu.cpp b/Quake/menu.cpp index 1c71445..d1e2100 100644 --- a/Quake/menu.cpp +++ b/Quake/menu.cpp @@ -20,6 +20,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include + #include "quakedef.hpp" #include "bgmusic.hpp" @@ -126,12 +128,12 @@ void M_Help_Key(int key); void M_Quit_Key(int key); -qboolean m_entersound; // play after drawing a frame, so caching +bool m_entersound; // play after drawing a frame, so caching // won't disrupt the sound -qboolean m_recursiveDraw; +bool m_recursiveDraw; enum m_state_e m_return_state; -qboolean m_return_onerror; +bool m_return_onerror; char m_return_reason[32]; #define StartingGame (m_multiplayer_cursor == 1) @@ -413,11 +415,11 @@ void M_SinglePlayer_Key(int key) { IN_Activate(); key_dest = key_game; if (sv.active) - Cbuf_AddText("disconnect\n"); - Cbuf_AddText("maxplayers 1\n"); - Cbuf_AddText("deathmatch 0\n"); //johnfitz - Cbuf_AddText("coop 0\n"); //johnfitz - Cbuf_AddText("map start\n"); + command::buffer::add_text("disconnect\n"); + command::buffer::add_text("maxplayers 1\n"); + command::buffer::add_text("deathmatch 0\n"); //johnfitz + command::buffer::add_text("coop 0\n"); //johnfitz + command::buffer::add_text("map start\n"); break; case 1: @@ -548,7 +550,7 @@ void M_Load_Key(int k) { SCR_BeginLoadingPlaque(); // issue the load command - Cbuf_AddText(va("load s%i\n", load_cursor)); + command::buffer::add_text(va("load s%i\n", load_cursor)); return; case K_UPARROW: @@ -583,7 +585,7 @@ void M_Save_Key(int k) { m_state = m_none; IN_Activate(); key_dest = key_game; - Cbuf_AddText(va("save s%i\n", load_cursor)); + command::buffer::add_text(va("save s%i\n", load_cursor)); return; case K_UPARROW: @@ -699,8 +701,8 @@ void M_Menu_Setup_f(void) { key_dest = key_menu; m_state = m_setup; m_entersound = true; - Q_strcpy(setup_myname, cl_name.string); - Q_strcpy(setup_hostname, hostname.string); + std::strcpy(setup_myname, cl_name.string); + std::strcpy(setup_hostname, hostname.string); setup_top = setup_oldtop = ((int) cl_color.value) >> 4; setup_bottom = setup_oldbottom = ((int) cl_color.value) & 15; } @@ -795,12 +797,12 @@ void M_Setup_Key(int k) { goto forward; // setup_cursor == 4 (OK) - if (Q_strcmp(cl_name.string, setup_myname) != 0) - Cbuf_AddText(va("name \"%s\"\n", setup_myname)); - if (Q_strcmp(hostname.string, setup_hostname) != 0) + if (std::strcmp(cl_name.string, setup_myname) != 0) + command::buffer::add_text(va("name \"%s\"\n", setup_myname)); + if (std::strcmp(hostname.string, setup_hostname) != 0) convar::set("hostname", setup_hostname); if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom) - Cbuf_AddText(va("color %i %i\n", setup_top, setup_bottom)); + command::buffer::add_text(va("color %i %i\n", setup_top, setup_bottom)); m_entersound = true; M_Menu_MultiPlayer_f(); break; @@ -851,7 +853,7 @@ void M_Setup_Char(int k) { } -qboolean M_Setup_TextEntry(void) { +bool M_Setup_TextEntry(void) { return (setup_cursor == 0 || setup_cursor == 1); } @@ -1059,7 +1061,7 @@ void M_AdjustSliders(int dir) { convar::set_value("bgmvolume", f); break; case OPT_MUSICEXT: // enable external music vs cdaudio - convar::set("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); + convar::set("bgm_extmusic", music::bgm_extmusic.value ? "0" : "1"); break; case OPT_SNDVOL: // sfx volume f = sfxvolume.value + dir * 0.1; @@ -1100,9 +1102,9 @@ void M_AdjustSliders(int dir) { case OPT_ALWAYSMLOOK: if (in_mlook.state & 1) - Cbuf_AddText("-mlook"); + command::buffer::add_text("-mlook"); else - Cbuf_AddText("+mlook"); + command::buffer::add_text("+mlook"); break; case OPT_LOOKSPRING: // lookspring @@ -1205,7 +1207,7 @@ void M_Options_Draw(void) { // OPT_MUSICEXT: M_Print(16, 32 + 8 * OPT_MUSICEXT, " External Music"); - M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, bgm_extmusic.value); + M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, music::bgm_extmusic.value); // OPT_ALWAYRUN: M_Print(16, 32 + 8 * OPT_ALWAYRUN, " Always Run"); @@ -1263,8 +1265,8 @@ void M_Options_Key(int k) { case OPT_DEFAULTS: if (SCR_ModalMessage("This will reset all controls\n" "and stored cvars. Continue? (y/n)\n", 15.0f)) { - Cbuf_AddText("resetcfg\n"); - Cbuf_AddText("exec default.cfg\n"); + command::buffer::add_text("resetcfg\n"); + command::buffer::add_text("exec default.cfg\n"); } break; case OPT_VIDEO: @@ -1333,10 +1335,10 @@ const char *bindnames[][2] = {"+movedown", "swim down"} }; -#define NUMCOMMANDS Q_COUNTOF(bindnames) +#define NUMCOMMANDS std::size(bindnames) static int keys_cursor; -static qboolean bind_grab; +static bool bind_grab; void M_Menu_Keys_f(void) { IN_Deactivate(modestate == MS_WINDOWED); @@ -1444,7 +1446,7 @@ void M_Keys_Key(int k) { S_LocalSound("misc/menu1.wav"); if ((k != K_ESCAPE) && (k != '`')) { sprintf(cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]); - Cbuf_InsertText(cmd); + command::buffer::insert_text(cmd); } bind_grab = false; @@ -1559,7 +1561,7 @@ void M_Help_Key(int key) { int msgNumber; enum m_state_e m_quit_prevstate; -qboolean wasInMenus; +bool wasInMenus; void M_Menu_Quit_f(void) { if (m_state == m_quit) @@ -1615,7 +1617,7 @@ void M_Quit_Char(int key) { } -qboolean M_Quit_TextEntry(void) { +bool M_Quit_TextEntry(void) { return true; } @@ -1785,7 +1787,7 @@ void M_LanConfig_Key(int key) { IN_Activate(); key_dest = key_game; m_state = m_none; - Cbuf_AddText(va("connect \"%s\"\n", lanConfig_joinname)); + command::buffer::add_text(va("connect \"%s\"\n", lanConfig_joinname)); break; } @@ -1811,7 +1813,7 @@ void M_LanConfig_Key(int key) { lanConfig_cursor = 0; } - l = Q_atoi(lanConfig_portname); + l = std::atoi(lanConfig_portname); if (l > 65535) l = lanConfig_port; else @@ -1844,7 +1846,7 @@ void M_LanConfig_Char(int key) { } -qboolean M_LanConfig_TextEntry(void) { +bool M_LanConfig_TextEntry(void) { return (lanConfig_cursor == 0 || lanConfig_cursor == 2); } @@ -1996,7 +1998,7 @@ episode_t rogueepisodes[] = int startepisode; int startlevel; int maxplayers; -qboolean m_serverInfoMessage = false; +bool m_serverInfoMessage = false; double m_serverInfoMessageTime; void M_Menu_GameOptions_f(void) { @@ -2269,18 +2271,18 @@ void M_GameOptions_Key(int key) { S_LocalSound("misc/menu2.wav"); if (gameoptions_cursor == 0) { if (sv.active) - Cbuf_AddText("disconnect\n"); - Cbuf_AddText("listen 0\n"); // so host_netport will be re-examined - Cbuf_AddText(va("maxplayers %u\n", maxplayers)); + command::buffer::add_text("disconnect\n"); + command::buffer::add_text("listen 0\n"); // so host_netport will be re-examined + command::buffer::add_text(va("maxplayers %u\n", maxplayers)); SCR_BeginLoadingPlaque(); if (hipnotic) - Cbuf_AddText(va( + command::buffer::add_text(va( "map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name)); else if (rogue) - Cbuf_AddText(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name)); + command::buffer::add_text(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name)); else - Cbuf_AddText(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name)); + command::buffer::add_text(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name)); return; } @@ -2293,7 +2295,7 @@ void M_GameOptions_Key(int key) { //============================================================================= /* SEARCH MENU */ -qboolean searchComplete = false; +bool searchComplete = false; double searchCompleteTime; void M_Menu_Search_f(void) { @@ -2348,7 +2350,7 @@ void M_Search_Key(int key) { /* SLIST MENU */ int slist_cursor; -qboolean slist_sorted; +bool slist_sorted; void M_Menu_ServerList_f(void) { IN_Deactivate(modestate == MS_WINDOWED); @@ -2419,7 +2421,7 @@ void M_ServerList_Key(int k) { IN_Activate(); key_dest = key_game; m_state = m_none; - Cbuf_AddText(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor))); + command::buffer::add_text(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor))); break; default: @@ -2643,7 +2645,7 @@ void M_Charinput(int key) { } -qboolean M_TextEntry(void) { +bool M_TextEntry(void) { switch (m_state) { case m_setup: return M_Setup_TextEntry(); @@ -2659,7 +2661,7 @@ qboolean M_TextEntry(void) { void M_ConfigureNetSubsystem(void) { // enable/disable net systems to match desired config - Cbuf_AddText("stopdemo\n"); + command::buffer::add_text("stopdemo\n"); if (IPXConfig || TCPIPConfig) net_hostport = lanConfig_port; diff --git a/Quake/menu.hpp b/Quake/menu.hpp index 6e2c9ef..7fd9799 100644 --- a/Quake/menu.hpp +++ b/Quake/menu.hpp @@ -46,7 +46,7 @@ enum m_state_e { extern enum m_state_e m_state; extern enum m_state_e m_return_state; -extern qboolean m_entersound; +extern bool m_entersound; // // menus @@ -54,7 +54,7 @@ extern qboolean m_entersound; void M_Init (void); void M_Keydown (int key); void M_Charinput (int key); -qboolean M_TextEntry (void); +bool M_TextEntry (void); void M_ToggleMenu_f (void); void M_Menu_Main_f (void); diff --git a/Quake/net.hpp b/Quake/net.hpp index 91295bf..bd2b37e 100644 --- a/Quake/net.hpp +++ b/Quake/net.hpp @@ -58,7 +58,7 @@ struct qsocket_s *NET_Connect (const char *host); double NET_QSocketGetTime (const struct qsocket_s *sock); const char *NET_QSocketGetAddressString (const struct qsocket_s *sock); -qboolean NET_CanSendMessage (struct qsocket_s *sock); +bool NET_CanSendMessage (struct qsocket_s *sock); // Returns true or false if the given qsocket can currently accept a // message to be transmitted. @@ -92,9 +92,9 @@ void NET_Poll (void); // Server list related globals: -extern qboolean slistInProgress; -extern qboolean slistSilent; -extern qboolean slistLocal; +extern bool slistInProgress; +extern bool slistSilent; +extern bool slistLocal; extern int hostCacheCount; @@ -106,8 +106,8 @@ const char *NET_SlistPrintServerName (int n); /* FIXME: driver related, but public: */ -extern qboolean ipxAvailable; -extern qboolean tcpipAvailable; +extern bool ipxAvailable; +extern bool tcpipAvailable; extern char my_ipx_address[NET_NAMELEN]; extern char my_tcpip_address[NET_NAMELEN]; diff --git a/Quake/net_bsd.cpp b/Quake/net_bsd.cpp index ad71637..d05027b 100644 --- a/Quake/net_bsd.cpp +++ b/Quake/net_bsd.cpp @@ -63,7 +63,7 @@ net_driver_t net_drivers[] = } }; -const int net_numdrivers = Q_COUNTOF(net_drivers); +const int net_numdrivers = std::size(net_drivers); #include "net_udp.hpp" @@ -93,4 +93,4 @@ net_landriver_t net_landrivers[] = } }; -const int net_numlandrivers = Q_COUNTOF(net_landrivers); +const int net_numlandrivers = std::size(net_landrivers); diff --git a/Quake/net_defs.hpp b/Quake/net_defs.hpp index 424b85d..a9447b2 100644 --- a/Quake/net_defs.hpp +++ b/Quake/net_defs.hpp @@ -134,9 +134,9 @@ typedef struct qsocket_s double lastMessageTime; double lastSendTime; - qboolean disconnected; - qboolean canSend; - qboolean sendNext; + bool disconnected; + bool canSend; + bool sendNext; int driver; int landriver; @@ -166,11 +166,11 @@ extern int net_numsockets; typedef struct { const char *name; - qboolean initialized; + bool initialized; sys_socket_t controlSock; sys_socket_t (*Init) (void); void (*Shutdown) (void); - void (*Listen) (qboolean state); + void (*Listen) (bool state); sys_socket_t (*Open_Socket) (int port); int (*Close_Socket) (sys_socket_t socketid); int (*Connect) (sys_socket_t socketid, struct qsockaddr *addr); @@ -195,17 +195,17 @@ extern const int net_numlandrivers; typedef struct { const char *name; - qboolean initialized; + bool initialized; int (*Init) (void); - void (*Listen) (qboolean state); - void (*SearchForHosts) (qboolean xmit); + void (*Listen) (bool state); + void (*SearchForHosts) (bool xmit); qsocket_t *(*Connect) (const char *host); qsocket_t *(*CheckNewConnections) (void); int (*QGetMessage) (qsocket_t *sock); int (*QSendMessage) (qsocket_t *sock, sizebuf_t *data); int (*SendUnreliableMessage) (qsocket_t *sock, sizebuf_t *data); - qboolean (*CanSendMessage) (qsocket_t *sock); - qboolean (*CanSendUnreliableMessage) (qsocket_t *sock); + bool (*CanSendMessage) (qsocket_t *sock); + bool (*CanSendUnreliableMessage) (qsocket_t *sock); void (*Close) (qsocket_t *sock); void (*Shutdown) (void); } net_driver_t; diff --git a/Quake/net_dgrm.cpp b/Quake/net_dgrm.cpp index f1ca4c3..17d8f14 100644 --- a/Quake/net_dgrm.cpp +++ b/Quake/net_dgrm.cpp @@ -29,6 +29,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "net_defs.hpp" #include "net_dgrm.hpp" +#include + // these two macros are to make the code more readable #define sfunc net_landrivers[sock->landriver] #define dfunc net_landrivers[net_landriverlevel] @@ -51,7 +53,7 @@ static struct { static int myDriverLevel; -extern qboolean m_return_onerror; +extern bool m_return_onerror; extern char m_return_reason[32]; @@ -91,8 +93,8 @@ static void NET_Ban_f(void) { switch (command::argc()) { case 1: if (banAddr.s_addr != INADDR_ANY) { - Q_strcpy(addrStr, inet_ntoa(banAddr)); - Q_strcpy(maskStr, inet_ntoa(banMask)); + std::strcpy(addrStr, inet_ntoa(banAddr)); + std::strcpy(maskStr, inet_ntoa(banMask)); print_fn("Banning %s [%s]\n", addrStr, maskStr); } else print_fn("Banning not active\n"); @@ -135,7 +137,7 @@ int Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) { Sys_Error("SendMessage: called with canSend == false"); #endif - Q_memcpy(sock->sendMessage, data->data, data->cursize); + std::memcpy(sock->sendMessage, data->data, data->cursize); sock->sendMessageLength = data->cursize; if (data->cursize <= MAX_DATAGRAM) { @@ -149,7 +151,7 @@ int Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) { packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); + std::memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->canSend = false; @@ -178,7 +180,7 @@ static int SendMessageNext(qsocket_t *sock) { packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); + std::memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; @@ -207,7 +209,7 @@ static int ReSendMessage(qsocket_t *sock) { packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence - 1); - Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); + std::memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; @@ -220,7 +222,7 @@ static int ReSendMessage(qsocket_t *sock) { } -qboolean Datagram_CanSendMessage(qsocket_t *sock) { +bool Datagram_CanSendMessage(qsocket_t *sock) { if (sock->sendNext) SendMessageNext(sock); @@ -228,7 +230,7 @@ qboolean Datagram_CanSendMessage(qsocket_t *sock) { } -qboolean Datagram_CanSendUnreliableMessage(qsocket_t *sock) { +bool Datagram_CanSendUnreliableMessage(qsocket_t *sock) { return true; } @@ -248,7 +250,7 @@ int Datagram_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); - Q_memcpy(packetBuffer.data, data->data, data->cursize); + std::memcpy(packetBuffer.data, data->data, data->cursize); if (sfunc.Write(sock->socket, (byte *) &packetBuffer, packetLen, &sock->addr) == -1) return -1; @@ -376,7 +378,7 @@ int Datagram_GetMessage(qsocket_t *sock) { break; } - Q_memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); + std::memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); sock->receiveMessageLength += length; continue; } @@ -410,7 +412,7 @@ static void NET_Stats_f(void) { Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount); Con_Printf("shortPacketCount = %i\n", shortPacketCount); Con_Printf("droppedDatagrams = %i\n", droppedDatagrams); - } else if (Q_strcmp(command::argv(1)->c_str(), "*") == 0) { + } else if (std::strcmp(command::argv(1)->c_str(), "*") == 0) { for (s = net_activeSockets; s; s = s->next) PrintStats(s); for (s = net_freeSockets; s; s = s->next) @@ -446,10 +448,10 @@ static const char *Strip_Port(const char *host) { if (!host || !*host) return host; q_strlcpy(noport, host, sizeof(noport)); - if ((p = Q_strrchr(noport, ':')) == NULL) + if ((p = std::strrchr(noport, ':')) == NULL) return host; *p++ = '\0'; - port = Q_atoi(p); + port = std::atoi(p); if (port > 0 && port < 65536 && port != net_hostport) { net_hostport = port; Con_Printf("Port set to %d\n", net_hostport); @@ -458,7 +460,7 @@ static const char *Strip_Port(const char *host) { } -static qboolean testInProgress = false; +static bool testInProgress = false; static int testPollCount; static int testDriver; static sys_socket_t testSocket; @@ -500,11 +502,11 @@ static void Test_Poll(void *unused) { Sys_Error("Unexpected response to Player Info request\n"); MSG_ReadByte(); /* playerNumber */ - Q_strcpy(name, MSG_ReadString()); + std::strcpy(name, MSG_ReadString()); colors = MSG_ReadLong(); frags = MSG_ReadLong(); connectTime = MSG_ReadLong(); - Q_strcpy(address, MSG_ReadString()); + std::strcpy(address, MSG_ReadString()); Con_Printf("%s\n frags:%3i colors:%d %d time:%d\n %s\n", name, frags, colors >> 4, colors & 0x0f, connectTime / 60, address); @@ -537,7 +539,7 @@ static void Test_f(void) { continue; net_landriverlevel = hostcache[n].ldriver; maxusers = hostcache[n].maxusers; - Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); + std::memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); break; } } @@ -583,7 +585,7 @@ JustDoIt: } -static qboolean test2InProgress = false; +static bool test2InProgress = false; static int test2Driver; static sys_socket_t test2Socket; @@ -620,10 +622,10 @@ static void Test2_Poll(void *unused) { if (MSG_ReadByte() != CCREP_RULE_INFO) goto Error; - Q_strcpy(name, MSG_ReadString()); + std::strcpy(name, MSG_ReadString()); if (name[0] == 0) goto Done; - Q_strcpy(value, MSG_ReadString()); + std::strcpy(value, MSG_ReadString()); Con_Printf("%-16.16s %-16.16s\n", name, value); @@ -664,7 +666,7 @@ static void Test2_f(void) { if (hostcache[n].driver != myDriverLevel) continue; net_landriverlevel = hostcache[n].ldriver; - Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); + std::memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); break; } } @@ -719,7 +721,7 @@ int Datagram_Init(void) { command::add("net_stats", NET_Stats_f); - if (safemode || COM_CheckParm("-nolan")) + if (safemode || common::check_param("-nolan").has_value()) return -1; num_inited = 0; @@ -765,7 +767,7 @@ void Datagram_Close(qsocket_t *sock) { } -void Datagram_Listen(qboolean state) { +void Datagram_Listen(bool state) { int i; for (i = 0; i < net_numlandrivers; i++) { @@ -810,7 +812,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) { command = MSG_ReadByte(); if (command == CCREQ_SERVER_INFO) { - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + if (std::strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; SZ_Clear(&net_message); @@ -893,7 +895,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) { if (command != CCREQ_CONNECT) return NULL; - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + if (std::strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { @@ -987,7 +989,7 @@ static qsocket_t *_Datagram_CheckNewConnections(void) { sock->socket = newsock; sock->landriver = net_landriverlevel; sock->addr = clientaddr; - Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr)); + std::strcpy(sock->address, dfunc.AddrToString(&clientaddr)); // send him back the info about the server connection he has been allocated SZ_Clear(&net_message); @@ -1017,7 +1019,7 @@ qsocket_t *Datagram_CheckNewConnections(void) { } -static void _Datagram_SearchForHosts(qboolean xmit) { +static void _Datagram_SearchForHosts(bool xmit) { int ret; int n; int i; @@ -1077,27 +1079,27 @@ static void _Datagram_SearchForHosts(qboolean xmit) { // add it hostCacheCount++; - Q_strcpy(hostcache[n].name, MSG_ReadString()); - Q_strcpy(hostcache[n].map, MSG_ReadString()); + std::strcpy(hostcache[n].name, MSG_ReadString()); + std::strcpy(hostcache[n].map, MSG_ReadString()); hostcache[n].users = MSG_ReadByte(); hostcache[n].maxusers = MSG_ReadByte(); if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { - Q_strcpy(hostcache[n].cname, hostcache[n].name); + std::strcpy(hostcache[n].cname, hostcache[n].name); hostcache[n].cname[14] = 0; - Q_strcpy(hostcache[n].name, "*"); - Q_strcat(hostcache[n].name, hostcache[n].cname); + std::strcpy(hostcache[n].name, "*"); + std::strcat(hostcache[n].name, hostcache[n].cname); } - Q_memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); + std::memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); hostcache[n].driver = net_driverlevel; hostcache[n].ldriver = net_landriverlevel; - Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); + std::strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); // check for a name conflict for (i = 0; i < hostCacheCount; i++) { if (i == n) continue; if (q_strcasecmp(hostcache[n].name, hostcache[i].name) == 0) { - i = Q_strlen(hostcache[n].name); + i = std::strlen(hostcache[n].name); if (i < 15 && hostcache[n].name[i - 1] > '8') { hostcache[n].name[i] = '0'; hostcache[n].name[i + 1] = 0; @@ -1110,7 +1112,7 @@ static void _Datagram_SearchForHosts(qboolean xmit) { } } -void Datagram_SearchForHosts(qboolean xmit) { +void Datagram_SearchForHosts(bool xmit) { for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { if (hostCacheCount == HOSTCACHESIZE) break; @@ -1216,14 +1218,14 @@ static qsocket_t *_Datagram_Connect(const char *host) { if (ret == 0) { reason = "No Response"; Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); + std::strcpy(m_return_reason, reason); goto ErrorReturn; } if (ret == -1) { reason = "Network Error"; Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); + std::strcpy(m_return_reason, reason); goto ErrorReturn; } @@ -1236,12 +1238,12 @@ static qsocket_t *_Datagram_Connect(const char *host) { } if (ret == CCREP_ACCEPT) { - Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); + std::memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); dfunc.SetSocketPort(&sock->addr, MSG_ReadLong()); } else { reason = "Bad Response"; Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); + std::strcpy(m_return_reason, reason); goto ErrorReturn; } @@ -1254,7 +1256,7 @@ static qsocket_t *_Datagram_Connect(const char *host) { if (dfunc.Connect(newsock, &sock->addr) == -1) { reason = "Connect to Game failed"; Con_Printf("%s\n", reason); - Q_strcpy(m_return_reason, reason); + std::strcpy(m_return_reason, reason); goto ErrorReturn; } diff --git a/Quake/net_dgrm.hpp b/Quake/net_dgrm.hpp index 357a829..ed09dd1 100644 --- a/Quake/net_dgrm.hpp +++ b/Quake/net_dgrm.hpp @@ -23,15 +23,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define __NET_DATAGRAM_H int Datagram_Init (void); -void Datagram_Listen (qboolean state); -void Datagram_SearchForHosts (qboolean xmit); +void Datagram_Listen (bool state); +void Datagram_SearchForHosts (bool xmit); qsocket_t *Datagram_Connect (const char *host); qsocket_t *Datagram_CheckNewConnections (void); int Datagram_GetMessage (qsocket_t *sock); int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data); int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); -qboolean Datagram_CanSendMessage (qsocket_t *sock); -qboolean Datagram_CanSendUnreliableMessage (qsocket_t *sock); +bool Datagram_CanSendMessage (qsocket_t *sock); +bool Datagram_CanSendUnreliableMessage (qsocket_t *sock); void Datagram_Close (qsocket_t *sock); void Datagram_Shutdown (void); diff --git a/Quake/net_loop.cpp b/Quake/net_loop.cpp index b682b98..ed65177 100644 --- a/Quake/net_loop.cpp +++ b/Quake/net_loop.cpp @@ -26,7 +26,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "net_defs.hpp" #include "net_loop.hpp" -static qboolean localconnectpending = false; +#include + +static bool localconnectpending = false; static qsocket_t *loop_client = NULL; static qsocket_t *loop_server = NULL; @@ -43,32 +45,32 @@ void Loop_Shutdown (void) } -void Loop_Listen (qboolean state) +void Loop_Listen (bool state) { } -void Loop_SearchForHosts (qboolean xmit) +void Loop_SearchForHosts (bool xmit) { if (!sv.active) return; hostCacheCount = 1; - if (Q_strcmp(hostname.string, "UNNAMED") == 0) - Q_strcpy(hostcache[0].name, "local"); + if (std::strcmp(hostname.string, "UNNAMED") == 0) + std::strcpy(hostcache[0].name, "local"); else - Q_strcpy(hostcache[0].name, hostname.string); - Q_strcpy(hostcache[0].map, sv.name); + std::strcpy(hostcache[0].name, hostname.string); + std::strcpy(hostcache[0].map, sv.name); hostcache[0].users = net_activeconnections; hostcache[0].maxusers = svs.maxclients; hostcache[0].driver = net_driverlevel; - Q_strcpy(hostcache[0].cname, "local"); + std::strcpy(hostcache[0].cname, "local"); } qsocket_t *Loop_Connect (const char *host) { - if (Q_strcmp(host,"local") != 0) + if (std::strcmp(host,"local") != 0) return NULL; localconnectpending = true; @@ -80,7 +82,7 @@ qsocket_t *Loop_Connect (const char *host) Con_Printf("Loop_Connect: no qsocket available\n"); return NULL; } - Q_strcpy (loop_client->address, "localhost"); + std::strcpy (loop_client->address, "localhost"); } loop_client->receiveMessageLength = 0; loop_client->sendMessageLength = 0; @@ -93,7 +95,7 @@ qsocket_t *Loop_Connect (const char *host) Con_Printf("Loop_Connect: no qsocket available\n"); return NULL; } - Q_strcpy (loop_server->address, "LOCAL"); + std::strcpy (loop_server->address, "LOCAL"); } loop_server->receiveMessageLength = 0; loop_server->sendMessageLength = 0; @@ -181,7 +183,7 @@ int Loop_SendMessage (qsocket_t *sock, sizebuf_t *data) buffer++; // message - Q_memcpy(buffer, data->data, data->cursize); + std::memcpy(buffer, data->data, data->cursize); *bufferLength = IntAlign(*bufferLength + data->cursize + 4); sock->canSend = false; @@ -215,13 +217,13 @@ int Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) buffer++; // message - Q_memcpy(buffer, data->data, data->cursize); + std::memcpy(buffer, data->data, data->cursize); *bufferLength = IntAlign(*bufferLength + data->cursize + 4); return 1; } -qboolean Loop_CanSendMessage (qsocket_t *sock) +bool Loop_CanSendMessage (qsocket_t *sock) { if (!sock->driverdata) return false; @@ -229,7 +231,7 @@ qboolean Loop_CanSendMessage (qsocket_t *sock) } -qboolean Loop_CanSendUnreliableMessage (qsocket_t *sock) +bool Loop_CanSendUnreliableMessage (qsocket_t *sock) { return true; } diff --git a/Quake/net_loop.hpp b/Quake/net_loop.hpp index 267193d..0817a6a 100644 --- a/Quake/net_loop.hpp +++ b/Quake/net_loop.hpp @@ -24,15 +24,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // net_loop.h int Loop_Init (void); -void Loop_Listen (qboolean state); -void Loop_SearchForHosts (qboolean xmit); +void Loop_Listen (bool state); +void Loop_SearchForHosts (bool xmit); qsocket_t *Loop_Connect (const char *host); qsocket_t *Loop_CheckNewConnections (void); int Loop_GetMessage (qsocket_t *sock); int Loop_SendMessage (qsocket_t *sock, sizebuf_t *data); int Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); -qboolean Loop_CanSendMessage (qsocket_t *sock); -qboolean Loop_CanSendUnreliableMessage (qsocket_t *sock); +bool Loop_CanSendMessage (qsocket_t *sock); +bool Loop_CanSendUnreliableMessage (qsocket_t *sock); void Loop_Close (qsocket_t *sock); void Loop_Shutdown (void); diff --git a/Quake/net_main.cpp b/Quake/net_main.cpp index 96894f9..5e6683b 100644 --- a/Quake/net_main.cpp +++ b/Quake/net_main.cpp @@ -19,6 +19,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ +#include + #include "q_stdinc.hpp" #include "arch_def.hpp" #include "net_sys.hpp" @@ -29,8 +31,8 @@ qsocket_t *net_activeSockets = NULL; qsocket_t *net_freeSockets = NULL; int net_numsockets = 0; -qboolean ipxAvailable = false; -qboolean tcpipAvailable = false; +bool ipxAvailable = false; +bool tcpipAvailable = false; int net_hostport; int DEFAULTnet_hostport = 26000; @@ -38,11 +40,11 @@ int DEFAULTnet_hostport = 26000; char my_ipx_address[NET_NAMELEN]; char my_tcpip_address[NET_NAMELEN]; -static qboolean listening = false; +static bool listening = false; -qboolean slistInProgress = false; -qboolean slistSilent = false; -qboolean slistLocal = true; +bool slistInProgress = false; +bool slistSilent = false; +bool slistLocal = true; static double slistStartTime; static int slistLastShown; @@ -106,7 +108,7 @@ qsocket_t *NET_NewQSocket(void) { sock->disconnected = false; sock->connecttime = net_time; - Q_strcpy(sock->address, "UNSET ADDRESS"); + std::strcpy(sock->address, "UNSET ADDRESS"); sock->driver = net_driverlevel; sock->socket = 0; sock->driverdata = NULL; @@ -166,7 +168,7 @@ static void NET_Listen_f(void) { return; } - listening = Q_atoi(command::argv(1)->c_str()) ? true : false; + listening = std::atoi(command::argv(1)->c_str()) ? true : false; for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { if (net_drivers[net_driverlevel].initialized == false) @@ -189,7 +191,7 @@ static void MaxPlayers_f(void) { return; } - n = Q_atoi(command::argv(1)->c_str()); + n = std::atoi(command::argv(1)->c_str()); if (n < 1) n = 1; if (n > svs.maxclientslimit) { @@ -198,10 +200,10 @@ static void MaxPlayers_f(void) { } if ((n == 1) && listening) - Cbuf_AddText("listen 0\n"); + command::buffer::add_text("listen 0\n"); if ((n > 1) && (!listening)) - Cbuf_AddText("listen 1\n"); + command::buffer::add_text("listen 1\n"); svs.maxclients = n; if (n == 1) @@ -219,7 +221,7 @@ static void NET_Port_f(void) { return; } - n = Q_atoi(command::argv(1)->c_str()); + n = std::atoi(command::argv(1)->c_str()); if (n < 1 || n > 65534) { Con_Printf("Bad value, must be between 1 and 65534\n"); return; @@ -230,8 +232,8 @@ static void NET_Port_f(void) { if (listening) { // force a change to the new port - Cbuf_AddText("listen 0\n"); - Cbuf_AddText("listen 1\n"); + command::buffer::add_text("listen 0\n"); + command::buffer::add_text("listen 1\n"); } } @@ -596,7 +598,7 @@ Returns true or false if the given qsocket can currently accept a message to be transmitted. ================== */ -qboolean NET_CanSendMessage(qsocket_t *sock) { +bool NET_CanSendMessage(qsocket_t *sock) { if (!sock) return false; @@ -613,8 +615,8 @@ int NET_SendToAll(sizebuf_t *data, double blocktime) { double start; int i; int count = 0; - qboolean msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ - qboolean msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ + bool msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ + bool msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { /* @@ -679,18 +681,17 @@ NET_Init */ void NET_Init(void) { - int i; qsocket_t *s; - i = COM_CheckParm("-port"); - if (!i) - i = COM_CheckParm("-udpport"); - if (!i) - i = COM_CheckParm("-ipxport"); + auto port = common::check_param("-port"); + if (!port.has_value()) + port = common::check_param("-udpport"); + if (!port.has_value()) + port = common::check_param("-ipxport"); - if (i) { - if (i < com_argc - 1) - DEFAULTnet_hostport = Q_atoi(com_argv[i + 1]); + if (port.has_value()) { + if (port < com_argc - 1) + DEFAULTnet_hostport = std::atoi(com_argv[port.value() + 1]); else Sys_Error("NET_Init: you must specify a number after -port"); } @@ -699,12 +700,12 @@ void NET_Init(void) { net_numsockets = svs.maxclientslimit; if (cls.state != ca_dedicated) net_numsockets++; - if (COM_CheckParm("-listen") || cls.state == ca_dedicated) + if (common::check_param("-listen").has_value() || cls.state == ca_dedicated) listening = true; SetNetTime(); - for (i = 0; i < net_numsockets; i++) { + for (auto i = 0; i < net_numsockets; i++) { s = (qsocket_t *) Hunk_AllocName(sizeof(qsocket_t), "qsocket"); s->next = net_freeSockets; net_freeSockets = s; @@ -722,11 +723,12 @@ void NET_Init(void) { command::add("maxplayers", MaxPlayers_f); command::add("port", NET_Port_f); + int lvl; // initialize all the drivers - for (i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { + for (lvl = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { if (net_drivers[net_driverlevel].Init() == -1) continue; - i++; + lvl++; net_drivers[net_driverlevel].initialized = true; if (listening) net_drivers[net_driverlevel].Listen(true); @@ -734,7 +736,7 @@ void NET_Init(void) { /* Loop_Init() returns -1 for dedicated server case, * therefore the i == 0 check is correct */ - if (i == 0 + if (lvl == 0 && cls.state == ca_dedicated ) { Sys_Error("Network not available!"); diff --git a/Quake/net_udp.cpp b/Quake/net_udp.cpp index a47bc05..8bfae37 100644 --- a/Quake/net_udp.cpp +++ b/Quake/net_udp.cpp @@ -39,13 +39,13 @@ static in_addr_t myAddr; sys_socket_t UDP_Init (void) { - int err, i; + int err; char *tst; char buff[MAXHOSTNAMELEN]; struct hostent *local; struct qsockaddr addr; - if (COM_CheckParm ("-noudp")) + if (common::check_param ("-noudp").has_value()) return INVALID_SOCKET; // determine my name & address @@ -81,15 +81,15 @@ sys_socket_t UDP_Init (void) } else { - i = COM_CheckParm ("-ip"); - if (i) + auto i = common::check_param ("-ip"); + if (i.has_value()) { - if (i < com_argc-1) + if (i.value() < com_argc-1) { - myAddr = inet_addr(com_argv[i + 1]); + myAddr = inet_addr(com_argv[i.value() + 1]); if (myAddr == INADDR_NONE) - Sys_Error ("%s is not a valid IP address", com_argv[i + 1]); - strcpy(my_tcpip_address, com_argv[i + 1]); + Sys_Error ("%s is not a valid IP address", com_argv[i.value() + 1]); + strcpy(my_tcpip_address, com_argv[i.value() + 1]); } else { @@ -134,7 +134,7 @@ void UDP_Shutdown (void) //============================================================================= -void UDP_Listen (qboolean state) +void UDP_Listen (bool state) { // enable listening if (state) diff --git a/Quake/net_udp.hpp b/Quake/net_udp.hpp index 5df71df..13b8fc4 100644 --- a/Quake/net_udp.hpp +++ b/Quake/net_udp.hpp @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. sys_socket_t UDP_Init (void); void UDP_Shutdown (void); -void UDP_Listen (qboolean state); +void UDP_Listen (bool state); sys_socket_t UDP_OpenSocket (int port); int UDP_CloseSocket (sys_socket_t socketid); int UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr); diff --git a/Quake/net_wins.cpp b/Quake/net_wins.cpp index 6be7454..1fa12d8 100644 --- a/Quake/net_wins.cpp +++ b/Quake/net_wins.cpp @@ -194,7 +194,7 @@ void WINS_Shutdown (void) //============================================================================= -void WINS_Listen (qboolean state) +void WINS_Listen (bool state) { // enable listening if (state) @@ -310,7 +310,7 @@ static int PartialIPAddress (const char *in, struct qsockaddr *hostaddr) } if (*b++ == ':') - port = Q_atoi(b); + port = std::atoi(b); else port = net_hostport; diff --git a/Quake/net_wins.hpp b/Quake/net_wins.hpp index 59abda4..65f93e9 100644 --- a/Quake/net_wins.hpp +++ b/Quake/net_wins.hpp @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. sys_socket_t WINS_Init (void); void WINS_Shutdown (void); -void WINS_Listen (qboolean state); +void WINS_Listen (bool state); sys_socket_t WINS_OpenSocket (int port); int WINS_CloseSocket (sys_socket_t socketid); int WINS_Connect (sys_socket_t socketid, struct qsockaddr *addr); diff --git a/Quake/net_wipx.cpp b/Quake/net_wipx.cpp index bd375d1..284922f 100644 --- a/Quake/net_wipx.cpp +++ b/Quake/net_wipx.cpp @@ -120,7 +120,7 @@ void WIPX_Shutdown (void) //============================================================================= -void WIPX_Listen (qboolean state) +void WIPX_Listen (bool state) { // enable listening if (state) diff --git a/Quake/net_wipx.hpp b/Quake/net_wipx.hpp index e8a24d3..ca3b25a 100644 --- a/Quake/net_wipx.hpp +++ b/Quake/net_wipx.hpp @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. sys_socket_t WIPX_Init (void); void WIPX_Shutdown (void); -void WIPX_Listen (qboolean state); +void WIPX_Listen (bool state); sys_socket_t WIPX_OpenSocket (int port); int WIPX_CloseSocket (sys_socket_t socketid); int WIPX_Connect (sys_socket_t socketid, struct qsockaddr *addr); diff --git a/Quake/pr_cmds.cpp b/Quake/pr_cmds.cpp index d11dd80..6238a2c 100644 --- a/Quake/pr_cmds.cpp +++ b/Quake/pr_cmds.cpp @@ -190,7 +190,7 @@ static void PF_setorigin (void) } -static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, qboolean rotate) +static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, bool rotate) { float *angles; vec3_t rmin, rmax; @@ -914,7 +914,7 @@ static void PF_localcmd (void) const char *str; str = G_STRING(OFS_PARM0); - Cbuf_AddText (str); + command::buffer::add_text (str); } /* @@ -1705,7 +1705,7 @@ static void PF_changelevel (void) svs.changelevel_issued = true; s = G_STRING(OFS_PARM0); - Cbuf_AddText (va("changelevel %s\n",s)); + command::buffer::add_text (va("changelevel %s\n",s)); } /* @@ -1855,4 +1855,4 @@ static builtin_t pr_builtin[] = }; const builtin_t *pr_builtins = pr_builtin; -const int pr_numbuiltins = Q_COUNTOF(pr_builtin); +const int pr_numbuiltins = std::size(pr_builtin); diff --git a/Quake/pr_edict.cpp b/Quake/pr_edict.cpp index ce233b8..19168f8 100644 --- a/Quake/pr_edict.cpp +++ b/Quake/pr_edict.cpp @@ -36,7 +36,7 @@ static int pr_numknownstrings; static ddef_t *pr_fielddefs; static ddef_t *pr_globaldefs; -qboolean pr_alpha_supported; //johnfitz +bool pr_alpha_supported; //johnfitz int pr_effects_mask; // only enable 2021 rerelease quad/penta dlights when applicable dstatement_t *pr_statements; @@ -58,7 +58,7 @@ const int type_size[NUM_TYPE_SIZES] = { }; static ddef_t *ED_FieldAtOfs (int ofs); -static qboolean ED_ParseEpair (void *base, ddef_t *key, const char *s); +static bool ED_ParseEpair (void *base, ddef_t *key, const char *s); #define MAX_FIELD_LEN 64 #define GEFV_CACHESIZE 2 @@ -416,7 +416,7 @@ padded to 20 field width const char *PR_GlobalString (int ofs) { static char line[512]; - static const int lastchari = Q_COUNTOF(line) - 2; + static const int lastchari = std::size(line) - 2; const char *s; int i; ddef_t *def; @@ -447,7 +447,7 @@ const char *PR_GlobalString (int ofs) const char *PR_GlobalStringNoContents (int ofs) { static char line[512]; - static const int lastchari = Q_COUNTOF(line) - 2; + static const int lastchari = std::size(line) - 2; int i; ddef_t *def; @@ -621,7 +621,7 @@ static void ED_PrintEdict_f (void) if (!sv.active) return; - i = Q_atoi (command::argv(1).value_or("").c_str()); + i = std::atoi (command::argv(1).value_or("").c_str()); if (i < 0 || i >= sv.num_edicts) { Con_Printf("Bad edict number\n"); @@ -795,7 +795,7 @@ Can parse either fields or globals returns false if error ============= */ -static qboolean ED_ParseEpair (void *base, ddef_t *key, const char *s) +static bool ED_ParseEpair (void *base, ddef_t *key, const char *s) { int i; char string[128]; @@ -886,7 +886,7 @@ Used for initial level load and for savegames. void ED_ParseEdict(std::istringstream &ss, edict_t *ent) { ddef_t *key; - qboolean anglehack, init; + bool anglehack, init; int n; std::string keyname{}; @@ -954,7 +954,7 @@ void ED_ParseEdict(std::istringstream &ss, edict_t *ent) //johnfitz -- hack to support .alpha even when progs.dat doesn't know about it if (keyname == "alpha") - ent->alpha = ENTALPHA_ENCODE(Q_atof(token->c_str())); + ent->alpha = ENTALPHA_ENCODE(std::atof(token->c_str())); //johnfitz key = ED_FindField (keyname.c_str()); @@ -1078,7 +1078,7 @@ void ED_LoadFromFile (const char *data) PR_HasGlobal =============== */ -static qboolean PR_HasGlobal (const char *name, float value) +static bool PR_HasGlobal (const char *name, float value) { ddef_t *g = ED_FindGlobal (name); return g && (g->type & ~DEF_SAVEGLOBAL) == ev_float && G_FLOAT (g->ofs) == value; @@ -1096,7 +1096,7 @@ to avoid conflicts (e.g. Arcane Dimensions uses bit 32 for its explosions) */ static int PR_FindSupportedEffects (void) { - qboolean isqex = + bool isqex = PR_HasGlobal ("EF_QUADLIGHT", EF_QEX_QUADLIGHT) && (PR_HasGlobal ("EF_PENTLIGHT", EF_QEX_PENTALIGHT) || PR_HasGlobal ("EF_PENTALIGHT", EF_QEX_PENTALIGHT)) ; diff --git a/Quake/pr_exec.cpp b/Quake/pr_exec.cpp index e2118b7..4e890f3 100644 --- a/Quake/pr_exec.cpp +++ b/Quake/pr_exec.cpp @@ -35,7 +35,7 @@ static int pr_depth; static int localstack[LOCALSTACK_SIZE]; static int localstack_used; -qboolean pr_trace; +bool pr_trace; dfunction_t *pr_xfunction; int pr_xstatement; int pr_argc; @@ -144,7 +144,7 @@ static void PR_PrintStatement (dstatement_t *s) { int i; - if ((unsigned int)s->op < Q_COUNTOF(pr_opnames)) + if ((unsigned int)s->op < std::size(pr_opnames)) { Con_Printf("%s ", pr_opnames[s->op]); i = strlen(pr_opnames[s->op]); diff --git a/Quake/progs.hpp b/Quake/progs.hpp index b8f1c30..f49f47e 100644 --- a/Quake/progs.hpp +++ b/Quake/progs.hpp @@ -39,7 +39,7 @@ typedef union eval_s #define MAX_ENT_LEAFS 32 typedef struct edict_s { - qboolean free; + bool free; link_t area; /* linked to a division node or leaf */ int num_leafs; @@ -48,7 +48,7 @@ typedef struct edict_s entity_state_t baseline; unsigned char alpha; /* johnfitz -- hack to support alpha since it's not part of entvars_t */ unsigned char scale; /* Quakespasm: added for model scale support. */ - qboolean sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */ + bool sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */ float oldframe; float oldthinktime; @@ -136,7 +136,7 @@ typedef struct { extern int pr_argc; -extern qboolean pr_trace; +extern bool pr_trace; extern dfunction_t *pr_xfunction; extern int pr_xstatement; diff --git a/Quake/protocol.hpp b/Quake/protocol.hpp index a155eee..ac089ad 100644 --- a/Quake/protocol.hpp +++ b/Quake/protocol.hpp @@ -128,11 +128,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define B_SCALE (1<<3) //johnfitz +#include + //johnfitz -- PROTOCOL_FITZQUAKE -- alpha encoding #define ENTALPHA_DEFAULT 0 //entity's alpha is "default" (i.e. water obeys r_wateralpha) -- must be zero so zeroed out memory works #define ENTALPHA_ZERO 1 //entity is invisible (lowest possible alpha) #define ENTALPHA_ONE 255 //entity is fully opaque (highest possible alpha) -#define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(CLAMP(1.0f,(a)*254.0f+1,255.0f))) //server convert to byte to send to client +#define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(std::clamp((float)((a)*254.0f+1), 1.0f, 255.0f))) //server convert to byte to send to client #define ENTALPHA_DECODE(a) (((a)==ENTALPHA_DEFAULT)?1.0f:((float)(a)-1)/(254)) //client convert to float for rendering #define ENTALPHA_TOSAVE(a) (((a)==ENTALPHA_DEFAULT)?0.0f:(((a)==ENTALPHA_ZERO)?-1.0f:((float)(a)-1)/(254))) //server convert to float for savegame //johnfitz diff --git a/Quake/q_sound.hpp b/Quake/q_sound.hpp index 25459ba..0a61a5c 100644 --- a/Quake/q_sound.hpp +++ b/Quake/q_sound.hpp @@ -95,7 +95,7 @@ void S_Shutdown (void); void S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation); void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation); void S_StopSound (int entnum, int entchannel); -void S_StopAllSounds(qboolean clear); +void S_StopAllSounds(bool clear); void S_ClearBuffer (void); void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up); void S_ExtraUpdate (void); @@ -122,7 +122,7 @@ void S_RawSamples(int samples, int rate, int width, int channels, byte * data, f /* Expects data in signed 16 bit, or unsigned 8 bit format. */ /* initializes cycling through a DMA buffer and returns information on it */ -qboolean SNDDMA_Init(dma_t *dma); +bool SNDDMA_Init(dma_t *dma); /* gets the current DMA position */ int SNDDMA_GetDMAPos(void); diff --git a/Quake/q_stdinc.hpp b/Quake/q_stdinc.hpp index c3d4690..a0c918f 100644 --- a/Quake/q_stdinc.hpp +++ b/Quake/q_stdinc.hpp @@ -75,16 +75,6 @@ #endif #endif -#define q_maxCHAR ((char)0x7f) -#define q_maxSHORT ((short)0x7fff) -#define q_maxINT ((int)0x7fffffff) -#define q_maxLONG ((int)0x7fffffff) - -#define q_minCHAR ((char)0x80) -#define q_minSHORT ((short)0x8000) -#define q_minINT ((int)0x80000000) -#define q_minLONG ((int)0x80000000) - #ifndef COMPILE_TIME_ASSERT #if defined(__cplusplus) /* Keep C++ case alone: Some versions of gcc will define __STDC_VERSION__ even when compiling in C++ mode. */ @@ -97,28 +87,21 @@ #define COMPILE_TIME_ASSERT(name, x) _Static_assert(x, #x) #endif #endif /**/ -#ifndef COMPILE_TIME_ASSERT -/* universal, but may trigger -Wunused-local-typedefs */ -#define COMPILE_TIME_ASSERT(name, x) \ - typedef int dummy_ ## name[(x) * 2 - 1] -#endif -COMPILE_TIME_ASSERT(char, sizeof(char) == 1); -COMPILE_TIME_ASSERT(float, sizeof(float) == 4); -COMPILE_TIME_ASSERT(long, sizeof(long) >= 4); -COMPILE_TIME_ASSERT(int, sizeof(int) == 4); -COMPILE_TIME_ASSERT(short, sizeof(short) == 2); +static_assert(sizeof(char) == 1); +static_assert(sizeof(float) == 4); +static_assert(sizeof(long) >= 4); +static_assert(sizeof(int) == 4); +static_assert(sizeof(short) == 2); /* make sure enums are the size of ints for structure packing */ typedef enum { THE_DUMMY_VALUE } THE_DUMMY_ENUM; -COMPILE_TIME_ASSERT(enum, sizeof(THE_DUMMY_ENUM) == sizeof(int)); +static_assert(sizeof(THE_DUMMY_ENUM) == sizeof(int)); /* for array size: */ -#define Q_COUNTOF(x) (sizeof(x) / sizeof((x)[0])) - /* Provide a substitute for offsetof() if we don't have one. * This variant works on most (but not *all*) systems... */ @@ -131,25 +114,6 @@ COMPILE_TIME_ASSERT(enum, sizeof(THE_DUMMY_ENUM) == sizeof(int)); typedef unsigned char byte; -/* some structures have qboolean members and the x86 asm code expect - * those members to be 4 bytes long. i.e.: qboolean must be 32 bits. */ -typedef int qboolean; -#undef true -#undef false -#if !defined(__cplusplus) -#if defined __STDC_VERSION__ && (__STDC_VERSION__ >= 199901L) -#include -#else -enum { - false = 0, - true = 1 -}; -#endif -#endif /* */ -COMPILE_TIME_ASSERT(falsehood, ((1 != 1) == false)); -COMPILE_TIME_ASSERT(truth, ((1 == 1) == true)); -COMPILE_TIME_ASSERT(qboolean, sizeof(qboolean) == 4); - /*==========================================================================*/ /* math */ diff --git a/Quake/quakedef.hpp b/Quake/quakedef.hpp index 7c91bcf..de7ab7f 100644 --- a/Quake/quakedef.hpp +++ b/Quake/quakedef.hpp @@ -268,7 +268,7 @@ typedef struct // command line parms passed to the program, and the amount of memory // available for the program to use -extern qboolean noclip_anglehack; +extern bool noclip_anglehack; // // host @@ -281,7 +281,7 @@ extern convar sys_nostdout; extern convar developer; extern convar max_edicts; //johnfitz -extern qboolean host_initialized; // true if into command execution +extern bool host_initialized; // true if into command execution extern double host_frametime; extern byte *host_colormap; extern int host_framecount; // incremented every frame, never reset @@ -313,7 +313,7 @@ FUNC_NORETURN void Host_EndGame (const char *message, ...) FUNC_PRINTF(1,2); void Host_Frame (float time); void Host_Quit_f (void); void Host_ClientCommands (const char *fmt, ...) FUNC_PRINTF(1,2); -void Host_ShutdownServer (qboolean crash); +void Host_ShutdownServer (bool crash); void Host_WriteConfiguration (void); void Host_Resetdemos (void); @@ -328,7 +328,7 @@ extern int current_skill; // skill level for currently loaded level (in case // the user changes the cvar while the level is // running, this reflects the level actually in use) -extern qboolean isDedicated; +extern bool isDedicated; extern int minimum_memory; diff --git a/Quake/r_alias.cpp b/Quake/r_alias.cpp index 5e213e2..1c9e5bd 100644 --- a/Quake/r_alias.cpp +++ b/Quake/r_alias.cpp @@ -49,9 +49,9 @@ static vec3_t shadevector; static float entalpha; //johnfitz -static qboolean overbright; //johnfitz +static bool overbright; //johnfitz -static qboolean shading = true; //johnfitz -- if false, disable vertex shading for various reasons (fullbright, r_lightmap, showtris, etc) +static bool shading = true; //johnfitz -- if false, disable vertex shading for various reasons (fullbright, r_lightmap, showtris, etc) //johnfitz -- struct for passing lerp information to drawing functions typedef struct { @@ -192,7 +192,7 @@ void GLAlias_CreateShaders (void) if (!gl_glsl_alias_able) return; - r_alias_program = GL_CreateProgram (vertSource, fragSource, Q_COUNTOF(bindings), bindings); + r_alias_program = GL_CreateProgram (vertSource, fragSource, std::size(bindings), bindings); if (r_alias_program != 0) { @@ -302,7 +302,7 @@ void GL_DrawAliasFrame (aliashdr_t *paliashdr, lerpdata_t lerpdata) int count; float u,v; float blend, iblend; - qboolean lerping; + bool lerping; if (lerpdata.pose1 != lerpdata.pose2) { @@ -455,9 +455,9 @@ void R_SetupAliasFrame (aliashdr_t *paliashdr, int frame, lerpdata_t *lerpdata) if (r_lerpmodels.value && !(e->model->flags & MOD_NOLERP && r_lerpmodels.value != 2)) { if (e->lerpflags & LERP_FINISH && numposes == 1) - lerpdata->blend = CLAMP (0.0f, (float)(cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 1.0f); + lerpdata->blend = std::clamp((float)(cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 0.0f, 1.0f); else - lerpdata->blend = CLAMP (0.0f, (float)(cl.time - e->lerpstart) / e->lerptime, 1.0f); + lerpdata->blend = std::clamp((float)(cl.time - e->lerpstart) / e->lerptime, 0.0f, 1.0f); if (lerpdata->blend == 1.0f) e->previouspose = e->currentpose; lerpdata->pose1 = e->previouspose; @@ -505,9 +505,9 @@ void R_SetupEntityTransform (entity_t *e, lerpdata_t *lerpdata) if (r_lerpmove.value && e != &cl.viewent && e->lerpflags & LERP_MOVESTEP) { if (e->lerpflags & LERP_FINISH) - blend = CLAMP (0.0f, (float)(cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 1.0f); + blend = std::clamp((float)(cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 0.0f, 1.0f); else - blend = CLAMP (0.0f, (float)(cl.time - e->movelerpstart) / 0.1f, 1.0f); + blend = std::clamp((float)(cl.time - e->movelerpstart) / 0.1f, 0.0f, 1.0f); //translation VectorSubtract (e->currentorigin, e->previousorigin, d); @@ -636,7 +636,7 @@ void R_DrawAliasModel (entity_t *e) int anim, skinnum; gltexture_t *tx, *fb; lerpdata_t lerpdata; - qboolean alphatest = !!(e->model->flags & MF_HOLEY); + bool alphatest = !!(e->model->flags & MF_HOLEY); float fovscale = 1.0f; // diff --git a/Quake/r_part.cpp b/Quake/r_part.cpp index 6360f92..f5a1637 100644 --- a/Quake/r_part.cpp +++ b/Quake/r_part.cpp @@ -146,13 +146,11 @@ R_InitParticles */ void R_InitParticles (void) { - int i; + auto i = common::check_param ("-particles"); - i = COM_CheckParm ("-particles"); - - if (i && i < com_argc - 1) + if (i.has_value() && i.value() < com_argc - 1) { - r_numparticles = atoi(com_argv[i + 1]); + r_numparticles = atoi(com_argv[i.value() + 1]); if (r_numparticles < ABSOLUTE_MIN_PARTICLES) r_numparticles = ABSOLUTE_MIN_PARTICLES; else if (r_numparticles > ABSOLUTE_MAX_PARTICLES) @@ -870,7 +868,7 @@ void R_DrawParticles (void) color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; - //alpha = CLAMP(0, p->die + 0.5 - cl.time, 1); + //alpha = std::clamp(p->die + 0.5 - cl.time, 0, 1); color[3] = 255; //(int)(alpha * 255); glColor4ubv(color); //johnfitz @@ -913,7 +911,7 @@ void R_DrawParticles (void) color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; - //alpha = CLAMP(0, p->die + 0.5 - cl.time, 1); + //alpha = std::clamp(p->die + 0.5 - cl.time, 0, 1); color[3] = 255; //(int)(alpha * 255); glColor4ubv(color); //johnfitz diff --git a/Quake/r_world.cpp b/Quake/r_world.cpp index 997905a..03f88ed 100644 --- a/Quake/r_world.cpp +++ b/Quake/r_world.cpp @@ -72,7 +72,7 @@ void R_ChainSurface (msurface_t *surf, texchain_t chain) R_BackFaceCull -- johnfitz -- returns true if the surface is facing away from vieworg ================ */ -qboolean R_BackFaceCull (msurface_t *surf) +bool R_BackFaceCull (msurface_t *surf) { double dot; @@ -98,7 +98,7 @@ void R_MarkSurfaces (void) mleaf_t *leaf; msurface_t *surf, **mark; int i, j; - qboolean nearwaterportal; + bool nearwaterportal; // clear lightmap chains for (i=0 ; inumtextures ; i++) { @@ -410,7 +410,7 @@ void R_DrawTextureChains_Multitexture (qmodel_t *model, entity_t *ent, texchain_ msurface_t *s; texture_t *t; float *v; - qboolean bound; + bool bound; for (i=0 ; inumtextures ; i++) { @@ -463,7 +463,7 @@ void R_DrawTextureChains_NoTexture (qmodel_t *model, texchain_t chain) int i; msurface_t *s; texture_t *t; - qboolean bound; + bool bound; for (i=0 ; inumtextures ; i++) { @@ -497,7 +497,7 @@ void R_DrawTextureChains_TextureOnly (qmodel_t *model, entity_t *ent, texchain_t int i; msurface_t *s; texture_t *t; - qboolean bound; + bool bound; for (i=0 ; inumtextures ; i++) { @@ -576,11 +576,11 @@ void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain msurface_t *s; texture_t *t; glpoly_t *p; - qboolean bound; + bool bound; float entalpha; int lastlightmap; - qboolean has_lit_water; - qboolean has_unlit_water; + bool has_lit_water; + bool has_unlit_water; if (r_drawflat_cheatsafe || r_lightmap_cheatsafe) // ericw -- !r_drawworld_cheatsafe check moved to R_DrawWorld_Water () return; @@ -885,7 +885,7 @@ void GLWorld_CreateShaders (void) if (!gl_glsl_alias_able) return; - r_world_program = GL_CreateProgram (vertSource, fragSource, Q_COUNTOF(bindings), bindings); + r_world_program = GL_CreateProgram (vertSource, fragSource, std::size(bindings), bindings); if (r_world_program != 0) { @@ -920,7 +920,7 @@ void R_DrawTextureChains_GLSL (qmodel_t *model, entity_t *ent, texchain_t chain) int i; msurface_t *s; texture_t *t; - qboolean bound; + bool bound; int lastlightmap; gltexture_t *fullbright = NULL; diff --git a/Quake/render.hpp b/Quake/render.hpp index ef600ee..bb7dfe9 100644 --- a/Quake/render.hpp +++ b/Quake/render.hpp @@ -48,7 +48,7 @@ typedef struct efrag_s typedef struct entity_s { - qboolean forcelink; // model changed + bool forcelink; // model changed int update_type; diff --git a/Quake/sbar.cpp b/Quake/sbar.cpp index a54bff6..6b9be20 100644 --- a/Quake/sbar.cpp +++ b/Quake/sbar.cpp @@ -46,7 +46,7 @@ static qpic_t *sb_face_quad; static qpic_t *sb_face_invuln; static qpic_t *sb_face_invis_invuln; -static qboolean sb_showscores; +static bool sb_showscores; int sb_lines; // scan lines to draw @@ -322,7 +322,7 @@ void Sbar_DrawScrollString (int x, int y, int width, const char *str) float scale; int len, ofs, left; - scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); + scale = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f); left = x * scale; if (cl.gametype != GAME_DEATHMATCH) left += (((float)glwidth - 320.0 * scale) / 2); @@ -911,7 +911,7 @@ void Sbar_Draw (void) GL_SetCanvas (CANVAS_DEFAULT); //johnfitz //johnfitz -- don't waste fillrate by clearing the area behind the sbar - w = CLAMP (320.0f, scr_sbarscale.value * 320.0f, (float)glwidth); + w = std::clamp(scr_sbarscale.value * 320.0f, 320.0f, (float)glwidth); if (sb_lines && glwidth > w) { if (scr_sbaralpha.value < 1) @@ -1210,7 +1210,7 @@ void Sbar_MiniDeathmatchOverlay (void) float scale; //johnfitz scoreboard_t *s; - scale = CLAMP (1.0f, scr_sbarscale.value, (float)glwidth / 320.0f); //johnfitz + scale = std::clamp(scr_sbarscale.value, 1.0f, (float)glwidth / 320.0f); //johnfitz //MAX_SCOREBOARDNAME = 32, so total width for this overlay plus sbar is 632, but we can cut off some i guess if (glwidth/scale < 512 || scr_viewsize.value >= 120) //johnfitz -- test should consider scr_sbarscale diff --git a/Quake/screen.hpp b/Quake/screen.hpp index 7196909..779af4f 100644 --- a/Quake/screen.hpp +++ b/Quake/screen.hpp @@ -47,8 +47,8 @@ extern float scr_conlines; // lines of console to display extern int sb_lines; extern int clearnotify; // set to 0 whenever notify text is drawn -extern qboolean scr_disabled_for_loading; -extern qboolean scr_skipupdate; +extern bool scr_disabled_for_loading; +extern bool scr_skipupdate; extern convar scr_viewsize; diff --git a/Quake/server.hpp b/Quake/server.hpp index 7c63a33..5a55026 100644 --- a/Quake/server.hpp +++ b/Quake/server.hpp @@ -31,7 +31,7 @@ typedef struct int maxclientslimit; struct client_s *clients; // [maxclients] int serverflags; // episode completion information - qboolean changelevel_issued; // cleared when at SV_SpawnServer + bool changelevel_issued; // cleared when at SV_SpawnServer } server_static_t; //============================================================================= @@ -42,10 +42,10 @@ typedef enum {ss_loading, ss_active} server_state_t; typedef struct { - qboolean active; // false if only a net client + bool active; // false if only a net client - qboolean paused; - qboolean loadgame; // handle connections specially + bool paused; + bool loadgame; // handle connections specially double time; @@ -94,9 +94,9 @@ enum sendsignon_e typedef struct client_s { - qboolean active; // false = client is free - qboolean spawned; // false = don't send datagrams - qboolean dropasap; // has been told to go to another level + bool active; // false = client is free + bool spawned; // false = don't send datagrams + bool dropasap; // has been told to go to another level enum sendsignon_e sendsignon; // only valid before spawned int signonidx; @@ -212,7 +212,7 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume float attenuation); void SV_LocalSound (client_t *client, const char *sample); // for 2021 rerelease -void SV_DropClient (qboolean crash); +void SV_DropClient (bool crash); void SV_SendClientMessages (void); void SV_ClearDatagram (void); @@ -232,8 +232,8 @@ void SV_BroadcastPrintf (const char *fmt, ...) FUNC_PRINTF(1,2); void SV_Physics (void); -qboolean SV_CheckBottom (edict_t *ent); -qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink); +bool SV_CheckBottom (edict_t *ent); +bool SV_movestep (edict_t *ent, vec3_t move, bool relink); void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg); diff --git a/Quake/snd_codec.cpp b/Quake/snd_codec.cpp index a64eec7..f5160a5 100644 --- a/Quake/snd_codec.cpp +++ b/Quake/snd_codec.cpp @@ -121,7 +121,7 @@ void S_CodecShutdown (void) S_CodecOpenStream ================= */ -snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, qboolean loop) +snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, bool loop) { snd_codec_t *codec; snd_stream_t *stream; @@ -153,7 +153,7 @@ snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, qb return stream; } -snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop) +snd_stream_t *S_CodecOpenStreamExt (const char *filename, bool loop) { snd_codec_t *codec; snd_stream_t *stream; @@ -187,7 +187,7 @@ snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop) return stream; } -snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop) +snd_stream_t *S_CodecOpenStreamAny (const char *filename, bool loop) { snd_codec_t *codec; snd_stream_t *stream; @@ -239,7 +239,7 @@ snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop) } } -qboolean S_CodecForwardStream (snd_stream_t *stream, unsigned int type) +bool S_CodecForwardStream (snd_stream_t *stream, unsigned int type) { snd_codec_t *codec = codecs; @@ -280,11 +280,11 @@ int S_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer) /* Util functions (used by codecs) */ -snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, qboolean loop) +snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, bool loop) { snd_stream_t *stream; FILE *handle; - qboolean pak; + bool pak; long length; /* Try to open the file */ diff --git a/Quake/snd_codec.hpp b/Quake/snd_codec.hpp index fcc9f86..d182879 100644 --- a/Quake/snd_codec.hpp +++ b/Quake/snd_codec.hpp @@ -49,12 +49,12 @@ typedef struct snd_codec_s snd_codec_t; typedef struct snd_stream_s { fshandle_t fh; - qboolean pak; + bool pak; char name[MAX_QPATH]; /* name of the source file */ snd_info_t info; stream_status_t status; snd_codec_t *codec; /* codec handling this stream */ - qboolean loop; + bool loop; void *priv; /* data private to the codec. */ } snd_stream_t; @@ -66,14 +66,14 @@ void S_CodecShutdown (void); * are reponsible for attaching any path to the filename */ snd_stream_t *S_CodecOpenStreamType (const char *filename, unsigned int type, - qboolean loop); + bool loop); /* Decides according to the required type. */ -snd_stream_t *S_CodecOpenStreamAny (const char *filename, qboolean loop); +snd_stream_t *S_CodecOpenStreamAny (const char *filename, bool loop); /* Decides according to file extension. if the * name has no extension, try all available. */ -snd_stream_t *S_CodecOpenStreamExt (const char *filename, qboolean loop); +snd_stream_t *S_CodecOpenStreamExt (const char *filename, bool loop); /* Decides according to file extension. the name * MUST have an extension. */ @@ -82,7 +82,7 @@ int S_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer); int S_CodecRewindStream (snd_stream_t *stream); int S_CodecJumpToOrder (snd_stream_t *stream, int to); -snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, qboolean loop); +snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec, bool loop); void S_CodecUtilClose(snd_stream_t **stream); diff --git a/Quake/snd_codeci.hpp b/Quake/snd_codeci.hpp index 4df7031..89a3b0a 100644 --- a/Quake/snd_codeci.hpp +++ b/Quake/snd_codeci.hpp @@ -27,9 +27,9 @@ #define _SND_CODECI_H_ /* Codec internals */ -typedef qboolean (*CODEC_INIT)(void); +typedef bool (*CODEC_INIT)(void); typedef void (*CODEC_SHUTDOWN)(void); -typedef qboolean (*CODEC_OPEN)(snd_stream_t *stream); +typedef bool (*CODEC_OPEN)(snd_stream_t *stream); typedef int (*CODEC_READ)(snd_stream_t *stream, int bytes, void *buffer); typedef int (*CODEC_REWIND)(snd_stream_t *stream); typedef int (*CODEC_JUMP)(snd_stream_t *stream, int order); @@ -38,7 +38,7 @@ typedef void (*CODEC_CLOSE)(snd_stream_t *stream); struct snd_codec_s { unsigned int type; /* handled data type. (1U << n) */ - qboolean initialized; /* init succeedded */ + bool initialized; /* init succeedded */ const char *ext; /* expected extension */ CODEC_INIT initialize; CODEC_SHUTDOWN shutdown; @@ -50,7 +50,7 @@ struct snd_codec_s snd_codec_t *next; }; -qboolean S_CodecForwardStream (snd_stream_t *stream, unsigned int type); +bool S_CodecForwardStream (snd_stream_t *stream, unsigned int type); /* Forward a stream to another codec of 'type' type. */ #endif /* _SND_CODECI_H_ */ diff --git a/Quake/snd_dma.cpp b/Quake/snd_dma.cpp index 26565f4..95d6627 100644 --- a/Quake/snd_dma.cpp +++ b/Quake/snd_dma.cpp @@ -36,7 +36,7 @@ static void S_SoundList(void); static void S_Update_(void); -void S_StopAllSounds(qboolean clear); +void S_StopAllSounds(bool clear); static void S_StopAllSoundsC(void); @@ -48,7 +48,7 @@ channel_t snd_channels[MAX_CHANNELS]; int total_channels; static int snd_blocked = 0; -static qboolean snd_initialized = false; +static bool snd_initialized = false; static dma_t sn; volatile dma_t *shm = NULL; @@ -73,7 +73,7 @@ static int num_sfx; static sfx_t *ambient_sfx[NUM_AMBIENTS]; -static qboolean sound_started = false; +static bool sound_started = false; convar bgmvolume = {"bgmvolume", "1", {.archive = true}}; convar sfxvolume = {"volume", "0.7", {.archive = true}}; @@ -153,8 +153,6 @@ S_Init ================ */ void S_Init(void) { - int i; - if (snd_initialized) { Con_Printf("Sound is already initialized\n"); return; @@ -174,7 +172,7 @@ void S_Init(void) { snd_mixspeed.inscribe(); snd_filterquality.inscribe(); - if (safemode || COM_CheckParm("-nosound")) + if (safemode || common::check_param("-nosound").has_value()) return; Con_Printf("\nSound Initialization\n"); @@ -185,14 +183,14 @@ void S_Init(void) { command::add("soundlist", S_SoundList); command::add("soundinfo", S_SoundInfo_f); - i = COM_CheckParm("-sndspeed"); - if (i && i < com_argc - 1) { - sndspeed.set(com_argv[i + 1]); + auto i = common::check_param("-sndspeed"); + if (i.has_value() && i.value() < com_argc - 1) { + sndspeed.set(com_argv[i.value() + 1]); } - i = COM_CheckParm("-mixspeed"); - if (i && i < com_argc - 1) { - snd_mixspeed.set(com_argv[i + 1]); + i = common::check_param("-mixspeed"); + if (i.has_value() && i.value() < com_argc - 1) { + snd_mixspeed.set(com_argv[i.value() + 1]); } if (host_parms->memsize < 0x800000) { @@ -497,7 +495,7 @@ void S_StopSound(int entnum, int entchannel) { } } -void S_StopAllSounds(qboolean clear) { +void S_StopAllSounds(bool clear) { int i; if (!sound_started) diff --git a/Quake/snd_flac.cpp b/Quake/snd_flac.cpp index 626b54a..24dfc94 100644 --- a/Quake/snd_flac.cpp +++ b/Quake/snd_flac.cpp @@ -224,7 +224,7 @@ flac_meta_func (const FLAC__StreamDecoder *decoder, } -static qboolean S_FLAC_CodecInitialize (void) +static bool S_FLAC_CodecInitialize (void) { return true; } @@ -233,7 +233,7 @@ static void S_FLAC_CodecShutdown (void) { } -static qboolean S_FLAC_CodecOpenStream (snd_stream_t *stream) +static bool S_FLAC_CodecOpenStream (snd_stream_t *stream) { flacfile_t *ff; int rc; diff --git a/Quake/snd_mikmod.cpp b/Quake/snd_mikmod.cpp index 26561eb..beca840 100644 --- a/Quake/snd_mikmod.cpp +++ b/Quake/snd_mikmod.cpp @@ -81,7 +81,7 @@ static BOOL MIK_Eof (MREADER *r) return FS_feof(((mik_priv_t *)r)->fh); } -static qboolean S_MIKMOD_CodecInitialize (void) +static bool S_MIKMOD_CodecInitialize (void) { if (mikmod_codec.initialized) return true; @@ -129,7 +129,7 @@ static void S_MIKMOD_CodecShutdown (void) } } -static qboolean S_MIKMOD_CodecOpenStream (snd_stream_t *stream) +static bool S_MIKMOD_CodecOpenStream (snd_stream_t *stream) { mik_priv_t *priv; diff --git a/Quake/snd_mix.cpp b/Quake/snd_mix.cpp index 9d29e9b..148e213 100644 --- a/Quake/snd_mix.cpp +++ b/Quake/snd_mix.cpp @@ -407,8 +407,8 @@ void S_PaintChannels (int endtime) // clipping for (i=0; iFrame.header.bitrate; size_t consumed = 0; int vbr = 0; /* Variable Bit Rate, bool */ - qboolean depadded = false; + bool depadded = false; unsigned long to_skip_samples = 0; /* Reset all */ @@ -376,7 +376,7 @@ static int mp3_madseek(snd_stream_t *stream, unsigned long offset) return -1; } -static qboolean S_MP3_CodecInitialize (void) +static bool S_MP3_CodecInitialize (void) { return true; } @@ -385,7 +385,7 @@ static void S_MP3_CodecShutdown (void) { } -static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream) +static bool S_MP3_CodecOpenStream (snd_stream_t *stream) { int err; diff --git a/Quake/snd_mp3tag.cpp b/Quake/snd_mp3tag.cpp index efca6a7..c733bbd 100644 --- a/Quake/snd_mp3tag.cpp +++ b/Quake/snd_mp3tag.cpp @@ -23,14 +23,14 @@ #include "snd_codec.h" #include "q_ctype.h" -static inline qboolean is_id3v1(const unsigned char *data, long length) { +static inline bool is_id3v1(const unsigned char *data, long length) { /* http://id3.org/ID3v1 : 3 bytes "TAG" identifier and 125 bytes tag data */ if (length < 128 || memcmp(data,"TAG",3) != 0) { return false; } return true; } -static qboolean is_id3v2(const unsigned char *data, size_t length) { +static bool is_id3v2(const unsigned char *data, size_t length) { /* ID3v2 header is 10 bytes: http://id3.org/id3v2.4.0-structure */ /* bytes 0-2: "ID3" identifier */ if (length < 10 || memcmp(data,"ID3",3) != 0) { @@ -64,7 +64,7 @@ static long get_id3v2_len(const unsigned char *data, long length) { } return size; } -static qboolean is_apetag(const unsigned char *data, size_t length) { +static bool is_apetag(const unsigned char *data, size_t length) { /* http://wiki.hydrogenaud.io/index.php?title=APEv2_specification * Header/footer is 32 bytes: bytes 0-7 ident, bytes 8-11 version, * bytes 12-17 size. bytes 24-31 are reserved: must be all zeroes. */ @@ -121,13 +121,13 @@ static inline long get_lyrics3v2_len(const unsigned char *data, long length) { if (length != 6) return 0; return strtol((const char *)data, NULL, 10) + 15; } -static inline qboolean verify_lyrics3v2(const unsigned char *data, long length) { +static inline bool verify_lyrics3v2(const unsigned char *data, long length) { if (length < 11) return false; if (memcmp(data,"LYRICSBEGIN",11) == 0) return true; return false; } #define MMTAG_PARANOID -static qboolean is_musicmatch(const unsigned char *data, long length) { +static bool is_musicmatch(const unsigned char *data, long length) { /* From docs/musicmatch.txt in id3lib: https://sourceforge.net/projects/id3lib/ Overall tag structure: diff --git a/Quake/snd_mpg123.cpp b/Quake/snd_mpg123.cpp index 801feb8..a09b96f 100644 --- a/Quake/snd_mpg123.cpp +++ b/Quake/snd_mpg123.cpp @@ -55,7 +55,7 @@ static off_t mp3_seek (void *f, off_t offset, int whence) return (off_t) FS_ftell((fshandle_t *)f); } -static qboolean S_MP3_CodecInitialize (void) +static bool S_MP3_CodecInitialize (void) { if (!mp3_codec.initialized) { @@ -78,7 +78,7 @@ static void S_MP3_CodecShutdown (void) } } -static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream) +static bool S_MP3_CodecOpenStream (snd_stream_t *stream) { long rate = 0; int encoding = 0, channels = 0; diff --git a/Quake/snd_opus.cpp b/Quake/snd_opus.cpp index fbea338..4a4eb79 100644 --- a/Quake/snd_opus.cpp +++ b/Quake/snd_opus.cpp @@ -24,9 +24,9 @@ #include "quakedef.hpp" #if defined(USE_CODEC_OPUS) -#include "snd_codec.h" -#include "snd_codeci.h" -#include "snd_opus.h" +#include "snd_codec.hpp" +#include "snd_codeci.hpp" +#include "snd_opus.hpp" #include #include @@ -74,7 +74,7 @@ static const OpusFileCallbacks opc_qfs = (int (*)(void *)) opc_fclose }; -static qboolean S_OPUS_CodecInitialize (void) +static bool S_OPUS_CodecInitialize (void) { return true; } @@ -83,7 +83,7 @@ static void S_OPUS_CodecShutdown (void) { } -static qboolean S_OPUS_CodecOpenStream (snd_stream_t *stream) +static bool S_OPUS_CodecOpenStream (snd_stream_t *stream) { OggOpusFile *opFile; const OpusHead *op_info; diff --git a/Quake/snd_sdl.cpp b/Quake/snd_sdl.cpp index d8d06b2..464557a 100644 --- a/Quake/snd_sdl.cpp +++ b/Quake/snd_sdl.cpp @@ -78,7 +78,7 @@ static void SDLCALL paint_audio (void *unused, Uint8 *stream, int len) shm->samplepos = 0; } -qboolean SNDDMA_Init (dma_t *dma) +bool SNDDMA_Init (dma_t *dma) { SDL_AudioSpec desired; int tmp, val; diff --git a/Quake/snd_umx.cpp b/Quake/snd_umx.cpp index 50f3704..756a3e4 100644 --- a/Quake/snd_umx.cpp +++ b/Quake/snd_umx.cpp @@ -340,7 +340,7 @@ static int process_upkg (fshandle_t *f, int32_t *ofs, int32_t *objsize) return probe_umx(f, &header, ofs, objsize); } -static qboolean S_UMX_CodecInitialize (void) +static bool S_UMX_CodecInitialize (void) { return true; } @@ -349,7 +349,7 @@ static void S_UMX_CodecShutdown (void) { } -static qboolean S_UMX_CodecOpenStream (snd_stream_t *stream) +static bool S_UMX_CodecOpenStream (snd_stream_t *stream) { int type; int32_t ofs = 0, size = 0; diff --git a/Quake/snd_vorbis.cpp b/Quake/snd_vorbis.cpp index d0853e1..a531c1e 100644 --- a/Quake/snd_vorbis.cpp +++ b/Quake/snd_vorbis.cpp @@ -24,9 +24,9 @@ #include "quakedef.hpp" #if defined(USE_CODEC_VORBIS) -#include "snd_codec.h" -#include "snd_codeci.h" -#include "snd_vorbis.h" +#include "snd_codec.hpp" +#include "snd_codeci.hpp" +#include "snd_vorbis.hpp" #define OV_EXCLUDE_STATIC_CALLBACKS #if defined(VORBIS_USE_TREMOR) @@ -64,7 +64,7 @@ static ov_callbacks ovc_qfs = (long (*)(void *)) FS_ftell }; -static qboolean S_VORBIS_CodecInitialize (void) +static bool S_VORBIS_CodecInitialize (void) { return true; } @@ -73,7 +73,7 @@ static void S_VORBIS_CodecShutdown (void) { } -static qboolean S_VORBIS_CodecOpenStream (snd_stream_t *stream) +static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream) { OggVorbis_File *ovFile; vorbis_info *ovf_info; diff --git a/Quake/snd_wave.cpp b/Quake/snd_wave.cpp index 4855661..06f61a4 100644 --- a/Quake/snd_wave.cpp +++ b/Quake/snd_wave.cpp @@ -110,7 +110,7 @@ static int WAV_FindRIFFChunk(FILE *f, const char *chunk) WAV_ReadRIFFHeader ================= */ -static qboolean WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *info) +static bool WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *info) { char dump[16]; int wav_format; @@ -189,7 +189,7 @@ static qboolean WAV_ReadRIFFHeader(const char *name, FILE *file, snd_info_t *inf S_WAV_CodecOpenStream ================= */ -static qboolean S_WAV_CodecOpenStream(snd_stream_t *stream) +static bool S_WAV_CodecOpenStream(snd_stream_t *stream) { long start = stream->fh.start; @@ -247,7 +247,7 @@ static int S_WAV_CodecRewindStream (snd_stream_t *stream) return 0; } -static qboolean S_WAV_CodecInitialize (void) +static bool S_WAV_CodecInitialize (void) { return true; } diff --git a/Quake/snd_xmp.cpp b/Quake/snd_xmp.cpp index c8826e0..b856315 100644 --- a/Quake/snd_xmp.cpp +++ b/Quake/snd_xmp.cpp @@ -34,7 +34,7 @@ #error libxmp version 4.2 or newer is required #endif -static qboolean S_XMP_CodecInitialize (void) +static bool S_XMP_CodecInitialize (void) { return true; } @@ -58,7 +58,7 @@ static long xmp_ftell(void *f) } #endif -static qboolean S_XMP_CodecOpenStream (snd_stream_t *stream) +static bool S_XMP_CodecOpenStream (snd_stream_t *stream) { /* need to load the whole file into memory and pass it to libxmp * using xmp_load_module_from_memory() which requires libxmp >= 4.2. diff --git a/Quake/sv_main.cpp b/Quake/sv_main.cpp index 4d7b8c0..b072a6d 100644 --- a/Quake/sv_main.cpp +++ b/Quake/sv_main.cpp @@ -21,16 +21,18 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_main.c -- server main program +#include + #include "quakedef.hpp" -server_t sv; -server_static_t svs; +server_t sv; +server_static_t svs; -static char localmodels[MAX_MODELS][8]; // inline model names for precache +static char localmodels[MAX_MODELS][8]; // inline model names for precache -int sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz +int sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz -extern qboolean pr_alpha_supported; //johnfitz +extern bool pr_alpha_supported; //johnfitz extern int pr_effects_mask; //============================================================================ @@ -40,30 +42,27 @@ extern int pr_effects_mask; SV_Protocol_f =============== */ -void SV_Protocol_f (void) -{ - int i; +void SV_Protocol_f(void) { + int i; - switch (command::argc()) - { - case 1: - Con_Printf ("\"sv_protocol\" is \"%i\"\n", sv_protocol); - break; - case 2: - i = atoi(command::argv(1)->c_str()); - if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) - Con_Printf ("sv_protocol must be %i or %i or %i\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); - else - { - sv_protocol = i; - if (sv.active) - Con_Printf ("changes will not take effect until the next level load.\n"); - } - break; - default: - Con_SafePrintf ("usage: sv_protocol \n"); - break; - } + switch (command::argc()) { + case 1: + Con_Printf("\"sv_protocol\" is \"%i\"\n", sv_protocol); + break; + case 2: + i = atoi(command::argv(1)->c_str()); + if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) + Con_Printf("sv_protocol must be %i or %i or %i\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); + else { + sv_protocol = i; + if (sv.active) + Con_Printf("changes will not take effect until the next level load.\n"); + } + break; + default: + Con_SafePrintf("usage: sv_protocol \n"); + break; + } } /* @@ -71,66 +70,62 @@ void SV_Protocol_f (void) SV_Init =============== */ -void SV_Init (void) -{ - int i; - const char *p; - extern convar sv_maxvelocity; - extern convar sv_gravity; - extern convar sv_nostep; - extern convar sv_freezenonclients; - extern convar sv_friction; - extern convar sv_edgefriction; - extern convar sv_stopspeed; - extern convar sv_maxspeed; - extern convar sv_accelerate; - extern convar sv_idealpitchscale; - extern convar sv_aim; - extern convar sv_altnoclip; //johnfitz +void SV_Init(void) { + const char *p; + extern convar sv_maxvelocity; + extern convar sv_gravity; + extern convar sv_nostep; + extern convar sv_freezenonclients; + extern convar sv_friction; + extern convar sv_edgefriction; + extern convar sv_stopspeed; + extern convar sv_maxspeed; + extern convar sv_accelerate; + extern convar sv_idealpitchscale; + extern convar sv_aim; + extern convar sv_altnoclip; //johnfitz - sv.edicts = NULL; // ericw -- sv.edicts switched to use malloc() + sv.edicts = NULL; // ericw -- sv.edicts switched to use malloc() - sv_maxvelocity.inscribe(); - sv_gravity.inscribe(); - sv_friction.inscribe(); - sv_gravity.set_callback(Host_Callback_Notify); - sv_friction.set_callback(Host_Callback_Notify); - sv_edgefriction.inscribe(); - sv_stopspeed.inscribe(); - sv_maxspeed.inscribe(); - sv_maxspeed.set_callback(Host_Callback_Notify); - sv_accelerate.inscribe(); - sv_idealpitchscale.inscribe(); - sv_aim.inscribe(); - sv_nostep.inscribe(); - sv_freezenonclients.inscribe(); - sv_altnoclip.inscribe(); //johnfitz + sv_maxvelocity.inscribe(); + sv_gravity.inscribe(); + sv_friction.inscribe(); + sv_gravity.set_callback(Host_Callback_Notify); + sv_friction.set_callback(Host_Callback_Notify); + sv_edgefriction.inscribe(); + sv_stopspeed.inscribe(); + sv_maxspeed.inscribe(); + sv_maxspeed.set_callback(Host_Callback_Notify); + sv_accelerate.inscribe(); + sv_idealpitchscale.inscribe(); + sv_aim.inscribe(); + sv_nostep.inscribe(); + sv_freezenonclients.inscribe(); + sv_altnoclip.inscribe(); //johnfitz - command::add ("sv_protocol", &SV_Protocol_f); //johnfitz + command::add("sv_protocol", &SV_Protocol_f); //johnfitz - for (i=0 ; i MAX_DATAGRAM-18) - return; - MSG_WriteByte (&sv.datagram, svc_particle); - MSG_WriteCoord (&sv.datagram, org[0], sv.protocolflags); - MSG_WriteCoord (&sv.datagram, org[1], sv.protocolflags); - MSG_WriteCoord (&sv.datagram, org[2], sv.protocolflags); - for (i=0 ; i<3 ; i++) - { - v = dir[i]*16; - if (v > 127) - v = 127; - else if (v < -128) - v = -128; - MSG_WriteChar (&sv.datagram, v); - } - MSG_WriteByte (&sv.datagram, count); - MSG_WriteByte (&sv.datagram, color); + if (sv.datagram.cursize > MAX_DATAGRAM - 18) + return; + MSG_WriteByte(&sv.datagram, svc_particle); + MSG_WriteCoord(&sv.datagram, org[0], sv.protocolflags); + MSG_WriteCoord(&sv.datagram, org[1], sv.protocolflags); + MSG_WriteCoord(&sv.datagram, org[2], sv.protocolflags); + for (i = 0; i < 3; i++) { + v = dir[i] * 16; + if (v > 127) + v = 127; + else if (v < -128) + v = -128; + MSG_WriteChar(&sv.datagram, v); + } + MSG_WriteByte(&sv.datagram, count); + MSG_WriteByte(&sv.datagram, color); } /* @@ -186,86 +179,80 @@ Larger attenuations will drop off. (max 4 attenuation) ================== */ -void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume, float attenuation) -{ - int sound_num, ent; - int i, field_mask; +void SV_StartSound(edict_t *entity, int channel, const char *sample, int volume, float attenuation) { + int sound_num, ent; + int i, field_mask; - if (volume < 0 || volume > 255) - Host_Error ("SV_StartSound: volume = %i", volume); + if (volume < 0 || volume > 255) + Host_Error("SV_StartSound: volume = %i", volume); - if (attenuation < 0 || attenuation > 4) - Host_Error ("SV_StartSound: attenuation = %f", attenuation); + if (attenuation < 0 || attenuation > 4) + Host_Error("SV_StartSound: attenuation = %f", attenuation); - if (channel < 0 || channel > 7) - Host_Error ("SV_StartSound: channel = %i", channel); + if (channel < 0 || channel > 7) + Host_Error("SV_StartSound: channel = %i", channel); - if (sv.datagram.cursize > MAX_DATAGRAM-21) - return; + if (sv.datagram.cursize > MAX_DATAGRAM - 21) + return; -// find precache number for sound - for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) - { - if (!strcmp(sample, sv.sound_precache[sound_num])) - break; - } + // find precache number for sound + for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) { + if (!strcmp(sample, sv.sound_precache[sound_num])) + break; + } - if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) - { - Con_Printf ("SV_StartSound: %s not precached\n", sample); - return; - } + if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) { + Con_Printf("SV_StartSound: %s not precached\n", sample); + return; + } - ent = NUM_FOR_EDICT(entity); + ent = NUM_FOR_EDICT(entity); - field_mask = 0; - if (volume != DEFAULT_SOUND_PACKET_VOLUME) - field_mask |= SND_VOLUME; - if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION) - field_mask |= SND_ATTENUATION; + field_mask = 0; + if (volume != DEFAULT_SOUND_PACKET_VOLUME) + field_mask |= SND_VOLUME; + if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION) + field_mask |= SND_ATTENUATION; - //johnfitz -- PROTOCOL_FITZQUAKE - if (ent >= 8192) - { - if (sv.protocol == PROTOCOL_NETQUAKE) - return; //don't send any info protocol can't support - field_mask |= SND_LARGEENTITY; - } - if (sound_num >= 256 || channel >= 8) - { - if (sv.protocol == PROTOCOL_NETQUAKE) - return; //don't send any info protocol can't support - field_mask |= SND_LARGESOUND; - } - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (ent >= 8192) { + if (sv.protocol == PROTOCOL_NETQUAKE) + return; //don't send any info protocol can't support + field_mask |= SND_LARGEENTITY; + } + if (sound_num >= 256 || channel >= 8) { + if (sv.protocol == PROTOCOL_NETQUAKE) + return; //don't send any info protocol can't support + field_mask |= SND_LARGESOUND; + } + //johnfitz - if (sv.datagram.cursize > MAX_DATAGRAM-21) - return; + if (sv.datagram.cursize > MAX_DATAGRAM - 21) + return; -// directed messages go only to the entity the are targeted on - MSG_WriteByte (&sv.datagram, svc_sound); - MSG_WriteByte (&sv.datagram, field_mask); - if (field_mask & SND_VOLUME) - MSG_WriteByte (&sv.datagram, volume); - if (field_mask & SND_ATTENUATION) - MSG_WriteByte (&sv.datagram, attenuation*64); + // directed messages go only to the entity the are targeted on + MSG_WriteByte(&sv.datagram, svc_sound); + MSG_WriteByte(&sv.datagram, field_mask); + if (field_mask & SND_VOLUME) + MSG_WriteByte(&sv.datagram, volume); + if (field_mask & SND_ATTENUATION) + MSG_WriteByte(&sv.datagram, attenuation * 64); - //johnfitz -- PROTOCOL_FITZQUAKE - if (field_mask & SND_LARGEENTITY) - { - MSG_WriteShort (&sv.datagram, ent); - MSG_WriteByte (&sv.datagram, channel); - } - else - MSG_WriteShort (&sv.datagram, (ent<<3) | channel); - if (field_mask & SND_LARGESOUND) - MSG_WriteShort (&sv.datagram, sound_num); - else - MSG_WriteByte (&sv.datagram, sound_num); - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (field_mask & SND_LARGEENTITY) { + MSG_WriteShort(&sv.datagram, ent); + MSG_WriteByte(&sv.datagram, channel); + } else + MSG_WriteShort(&sv.datagram, (ent << 3) | channel); + if (field_mask & SND_LARGESOUND) + MSG_WriteShort(&sv.datagram, sound_num); + else + MSG_WriteByte(&sv.datagram, sound_num); + //johnfitz - for (i = 0; i < 3; i++) - MSG_WriteCoord (&sv.datagram, entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]), sv.protocolflags); + for (i = 0; i < 3; i++) + MSG_WriteCoord(&sv.datagram, entity->v.origin[i] + 0.5 * (entity->v.mins[i] + entity->v.maxs[i]), + sv.protocolflags); } /* @@ -273,38 +260,34 @@ void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume SV_LocalSound - for 2021 rerelease ================== */ -void SV_LocalSound (client_t *client, const char *sample) -{ - int sound_num, field_mask; +void SV_LocalSound(client_t *client, const char *sample) { + int sound_num, field_mask; - for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) - { - if (!strcmp(sample, sv.sound_precache[sound_num])) - break; - } - if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) - { - Con_Printf ("SV_LocalSound: %s not precached\n", sample); - return; - } + for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) { + if (!strcmp(sample, sv.sound_precache[sound_num])) + break; + } + if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) { + Con_Printf("SV_LocalSound: %s not precached\n", sample); + return; + } - field_mask = 0; - if (sound_num >= 256) - { - if (sv.protocol == PROTOCOL_NETQUAKE) - return; - field_mask = SND_LARGESOUND; - } + field_mask = 0; + if (sound_num >= 256) { + if (sv.protocol == PROTOCOL_NETQUAKE) + return; + field_mask = SND_LARGESOUND; + } - if (client->message.cursize > client->message.maxsize-4) - return; + if (client->message.cursize > client->message.maxsize - 4) + return; - MSG_WriteByte (&client->message, svc_localsound); - MSG_WriteByte (&client->message, field_mask); - if (field_mask & SND_LARGESOUND) - MSG_WriteShort (&client->message, sound_num); - else - MSG_WriteByte (&client->message, sound_num); + MSG_WriteByte(&client->message, svc_localsound); + MSG_WriteByte(&client->message, field_mask); + if (field_mask & SND_LARGESOUND) + MSG_WriteShort(&client->message, sound_num); + else + MSG_WriteByte(&client->message, sound_num); } /* @@ -315,9 +298,8 @@ CLIENT SPAWNING ============================================================================== */ -static qboolean SV_IsLocalClient (client_t *client) -{ - return Q_strcmp (NET_QSocketGetAddressString (client->netconnection), "LOCAL") == 0; +static bool SV_IsLocalClient(client_t *client) { + return std::strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") == 0; } /* @@ -328,60 +310,59 @@ Sends the first message from the server to a connected client. This will be sent on the initial connection and upon each server load. ================ */ -void SV_SendServerinfo (client_t *client) -{ - const char **s; - char message[2048]; - int i; //johnfitz +void SV_SendServerinfo(client_t *client) { + const char **s; + char message[2048]; + int i; //johnfitz - MSG_WriteByte (&client->message, svc_print); - sprintf (message, "%c\nFITZQUAKE %1.2f SERVER (%i CRC)\n", 2, FITZQUAKE_VERSION, pr_crc); //johnfitz -- include fitzquake version - MSG_WriteString (&client->message,message); + MSG_WriteByte(&client->message, svc_print); + sprintf(message, "%c\nFITZQUAKE %1.2f SERVER (%i CRC)\n", 2, FITZQUAKE_VERSION, pr_crc); + //johnfitz -- include fitzquake version + MSG_WriteString(&client->message, message); - MSG_WriteByte (&client->message, svc_serverinfo); - MSG_WriteLong (&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION - - if (sv.protocol == PROTOCOL_RMQ) - { - // mh - now send protocol flags so that the client knows the protocol features to expect - MSG_WriteLong (&client->message, sv.protocolflags); - } - - MSG_WriteByte (&client->message, svs.maxclients); + MSG_WriteByte(&client->message, svc_serverinfo); + MSG_WriteLong(&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION - if (!coop.value && deathmatch.value) - MSG_WriteByte (&client->message, GAME_DEATHMATCH); - else - MSG_WriteByte (&client->message, GAME_COOP); + if (sv.protocol == PROTOCOL_RMQ) { + // mh - now send protocol flags so that the client knows the protocol features to expect + MSG_WriteLong(&client->message, sv.protocolflags); + } - MSG_WriteString (&client->message, PR_GetString(sv.edicts->v.message)); + MSG_WriteByte(&client->message, svs.maxclients); - //johnfitz -- only send the first 256 model and sound precaches if protocol is 15 - for (i = 1, s = sv.model_precache+1; *s; s++,i++) - if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) - MSG_WriteString (&client->message, *s); - MSG_WriteByte (&client->message, 0); + if (!coop.value && deathmatch.value) + MSG_WriteByte(&client->message, GAME_DEATHMATCH); + else + MSG_WriteByte(&client->message, GAME_COOP); - for (i = 1, s = sv.sound_precache+1; *s; s++, i++) - if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) - MSG_WriteString (&client->message, *s); - MSG_WriteByte (&client->message, 0); - //johnfitz + MSG_WriteString(&client->message, PR_GetString(sv.edicts->v.message)); -// send music - MSG_WriteByte (&client->message, svc_cdtrack); - MSG_WriteByte (&client->message, sv.edicts->v.sounds); - MSG_WriteByte (&client->message, sv.edicts->v.sounds); + //johnfitz -- only send the first 256 model and sound precaches if protocol is 15 + for (i = 1, s = sv.model_precache + 1; *s; s++, i++) + if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) + MSG_WriteString(&client->message, *s); + MSG_WriteByte(&client->message, 0); -// set view - MSG_WriteByte (&client->message, svc_setview); - MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict)); + for (i = 1, s = sv.sound_precache + 1; *s; s++, i++) + if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) + MSG_WriteString(&client->message, *s); + MSG_WriteByte(&client->message, 0); + //johnfitz - MSG_WriteByte (&client->message, svc_signonnum); - MSG_WriteByte (&client->message, 1); + // send music + MSG_WriteByte(&client->message, svc_cdtrack); + MSG_WriteByte(&client->message, sv.edicts->v.sounds); + MSG_WriteByte(&client->message, sv.edicts->v.sounds); - client->sendsignon = PRESPAWN_FLUSH; - client->spawned = false; // need prespawn, spawn, etc + // set view + MSG_WriteByte(&client->message, svc_setview); + MSG_WriteShort(&client->message, NUM_FOR_EDICT(client->edict)); + + MSG_WriteByte(&client->message, svc_signonnum); + MSG_WriteByte(&client->message, 1); + + client->sendsignon = PRESPAWN_FLUSH; + client->spawned = false; // need prespawn, spawn, etc } /* @@ -392,50 +373,48 @@ Initializes a client_t for a new net connection. This will only be called once for a player each game, not once for each level change. ================ */ -void SV_ConnectClient (int clientnum) -{ - edict_t *ent; - client_t *client; - int edictnum; - struct qsocket_s *netconnection; - int i; - float spawn_parms[NUM_SPAWN_PARMS]; +void SV_ConnectClient(int clientnum) { + edict_t *ent; + client_t *client; + int edictnum; + struct qsocket_s *netconnection; + int i; + float spawn_parms[NUM_SPAWN_PARMS]; - client = svs.clients + clientnum; + client = svs.clients + clientnum; - Con_DPrintf ("Client %s connected\n", NET_QSocketGetAddressString(client->netconnection)); + Con_DPrintf("Client %s connected\n", NET_QSocketGetAddressString(client->netconnection)); - edictnum = clientnum+1; + edictnum = clientnum + 1; - ent = EDICT_NUM(edictnum); + ent = EDICT_NUM(edictnum); -// set up the client_t - netconnection = client->netconnection; + // set up the client_t + netconnection = client->netconnection; - if (sv.loadgame) - memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms)); - memset (client, 0, sizeof(*client)); - client->netconnection = netconnection; + if (sv.loadgame) + memcpy(spawn_parms, client->spawn_parms, sizeof(spawn_parms)); + memset(client, 0, sizeof(*client)); + client->netconnection = netconnection; - strcpy (client->name, "unconnected"); - client->active = true; - client->spawned = false; - client->edict = ent; - client->message.data = client->msgbuf; - client->message.maxsize = sizeof(client->msgbuf); - client->message.allowoverflow = true; // we can catch it + strcpy(client->name, "unconnected"); + client->active = true; + client->spawned = false; + client->edict = ent; + client->message.data = client->msgbuf; + client->message.maxsize = sizeof(client->msgbuf); + client->message.allowoverflow = true; // we can catch it - if (sv.loadgame) - memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms)); - else - { - // call the progs to get default spawn parms for the new client - PR_ExecuteProgram (pr_global_struct->SetNewParms); - for (i=0 ; ispawn_parms[i] = (&pr_global_struct->parm1)[i]; - } + if (sv.loadgame) + memcpy(client->spawn_parms, spawn_parms, sizeof(spawn_parms)); + else { + // call the progs to get default spawn parms for the new client + PR_ExecuteProgram(pr_global_struct->SetNewParms); + for (i = 0; i < NUM_SPAWN_PARMS; i++) + client->spawn_parms[i] = (&pr_global_struct->parm1)[i]; + } - SV_SendServerinfo (client); + SV_SendServerinfo(client); } @@ -445,34 +424,32 @@ SV_CheckForNewClients =================== */ -void SV_CheckForNewClients (void) -{ - struct qsocket_s *ret; - int i; +void SV_CheckForNewClients(void) { + struct qsocket_s *ret; + int i; -// -// check for new connections -// - while (1) - { - ret = NET_CheckNewConnections (); - if (!ret) - break; + // + // check for new connections + // + while (1) { + ret = NET_CheckNewConnections(); + if (!ret) + break; - // - // init a new client structure - // - for (i=0 ; icontents < 0) - { - if (node->contents != CONTENTS_SOLID) - { - pvs = Mod_LeafPVS ( (mleaf_t *)node, worldmodel); //johnfitz -- worldmodel as a parameter - for (i=0 ; icontents < 0) { + if (node->contents != CONTENTS_SOLID) { + pvs = Mod_LeafPVS((mleaf_t *) node, worldmodel); //johnfitz -- worldmodel as a parameter + for (i = 0; i < fatbytes; i++) + fatpvs[i] |= pvs[i]; + } + return; + } - plane = node->plane; - d = DotProduct (org, plane->normal) - plane->dist; - if (d > 8) - node = node->children[0]; - else if (d < -8) - node = node->children[1]; - else - { // go down both - SV_AddToFatPVS (org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter - node = node->children[1]; - } - } + plane = node->plane; + d = DotProduct(org, plane->normal) - plane->dist; + if (d > 8) + node = node->children[0]; + else if (d < -8) + node = node->children[1]; + else { + // go down both + SV_AddToFatPVS(org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter + node = node->children[1]; + } + } } /* @@ -553,20 +526,19 @@ Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the given point. ============= */ -byte *SV_FatPVS (vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter +byte *SV_FatPVS(vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter { - fatbytes = (worldmodel->numleafs+7)>>3; // ericw -- was +31, assumed to be a bug/typo - if (fatpvs == NULL || fatbytes > fatpvs_capacity) - { - fatpvs_capacity = fatbytes; - fatpvs = (byte *) realloc (fatpvs, fatpvs_capacity); - if (!fatpvs) - Sys_Error ("SV_FatPVS: realloc() failed on %d bytes", fatpvs_capacity); - } - - Q_memset (fatpvs, 0, fatbytes); - SV_AddToFatPVS (org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter - return fatpvs; + fatbytes = (worldmodel->numleafs + 7) >> 3; // ericw -- was +31, assumed to be a bug/typo + if (fatpvs == NULL || fatbytes > fatpvs_capacity) { + fatpvs_capacity = fatbytes; + fatpvs = (byte *) realloc(fatpvs, fatpvs_capacity); + if (!fatpvs) + Sys_Error("SV_FatPVS: realloc() failed on %d bytes", fatpvs_capacity); + } + + std::memset(fatpvs, 0, fatbytes); + SV_AddToFatPVS(org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter + return fatpvs; } /* @@ -576,20 +548,19 @@ SV_VisibleToClient -- johnfitz PVS test encapsulated in a nice function ============= */ -qboolean SV_VisibleToClient (edict_t *client, edict_t *test, qmodel_t *worldmodel) -{ - byte *pvs; - vec3_t org; - int i; +bool SV_VisibleToClient(edict_t *client, edict_t *test, qmodel_t *worldmodel) { + byte *pvs; + vec3_t org; + int i; - VectorAdd (client->v.origin, client->v.view_ofs, org); - pvs = SV_FatPVS (org, worldmodel); + VectorAdd(client->v.origin, client->v.view_ofs, org); + pvs = SV_FatPVS(org, worldmodel); - for (i=0 ; i < test->num_leafs ; i++) - if (pvs[test->leafnums[i] >> 3] & (1 << (test->leafnums[i]&7) )) - return true; + for (i = 0; i < test->num_leafs; i++) + if (pvs[test->leafnums[i] >> 3] & (1 << (test->leafnums[i] & 7))) + return true; - return false; + return false; } //============================================================================= @@ -600,207 +571,198 @@ SV_WriteEntitiesToClient ============= */ -void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg) -{ - int e, i; - int bits; - byte *pvs; - vec3_t org; - float miss; - edict_t *ent; - eval_t *val; +void SV_WriteEntitiesToClient(edict_t *clent, sizebuf_t *msg) { + int e, i; + int bits; + byte *pvs; + vec3_t org; + float miss; + edict_t *ent; + eval_t *val; -// find the client's PVS - VectorAdd (clent->v.origin, clent->v.view_ofs, org); - pvs = SV_FatPVS (org, sv.worldmodel); + // find the client's PVS + VectorAdd(clent->v.origin, clent->v.view_ofs, org); + pvs = SV_FatPVS(org, sv.worldmodel); -// send over all entities (excpet the client) that touch the pvs - ent = NEXT_EDICT(sv.edicts); - for (e=1 ; ev.modelindex || !PR_GetString(ent->v.model)[0]) + continue; - if (ent != clent) // clent is ALLWAYS sent - { - // ignore ents without visible models - if (!ent->v.modelindex || !PR_GetString(ent->v.model)[0]) - continue; + //johnfitz -- don't send model>255 entities if protocol is 15 + if (sv.protocol == PROTOCOL_NETQUAKE && (int) ent->v.modelindex & 0xFF00) + continue; - //johnfitz -- don't send model>255 entities if protocol is 15 - if (sv.protocol == PROTOCOL_NETQUAKE && (int)ent->v.modelindex & 0xFF00) - continue; + // ignore if not touching a PV leaf + for (i = 0; i < ent->num_leafs; i++) + if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i] & 7))) + break; - // ignore if not touching a PV leaf - for (i=0 ; i < ent->num_leafs ; i++) - if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) )) - break; - - // ericw -- added ent->num_leafs < MAX_ENT_LEAFS condition. - // - // if ent->num_leafs == MAX_ENT_LEAFS, the ent is visible from too many leafs - // for us to say whether it's in the PVS, so don't try to vis cull it. - // this commonly happens with rotators, because they often have huge bboxes - // spanning the entire map, or really tall lifts, etc. - if (i == ent->num_leafs && ent->num_leafs < MAX_ENT_LEAFS) - continue; // not visible - } + // ericw -- added ent->num_leafs < MAX_ENT_LEAFS condition. + // + // if ent->num_leafs == MAX_ENT_LEAFS, the ent is visible from too many leafs + // for us to say whether it's in the PVS, so don't try to vis cull it. + // this commonly happens with rotators, because they often have huge bboxes + // spanning the entire map, or really tall lifts, etc. + if (i == ent->num_leafs && ent->num_leafs < MAX_ENT_LEAFS) + continue; // not visible + } - // johnfitz -- max size for protocol 15 is 18 bytes, not 16 as originally - // assumed here. And, for protocol 85 the max size is actually 24 bytes. - // For float coords and angles the limit is 40. - // FIXME: Use tighter limit according to protocol flags and send bits. - if (msg->cursize + 40 > msg->maxsize) - { - //johnfitz -- less spammy overflow message - if (!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime ) - { - Con_Printf ("Packet overflow!\n"); - dev_overflows.packetsize = realtime; - } - goto stats; - //johnfitz - } + // johnfitz -- max size for protocol 15 is 18 bytes, not 16 as originally + // assumed here. And, for protocol 85 the max size is actually 24 bytes. + // For float coords and angles the limit is 40. + // FIXME: Use tighter limit according to protocol flags and send bits. + if (msg->cursize + 40 > msg->maxsize) { + //johnfitz -- less spammy overflow message + if (!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime) { + Con_Printf("Packet overflow!\n"); + dev_overflows.packetsize = realtime; + } + goto stats; + //johnfitz + } -// send an update - bits = 0; + // send an update + bits = 0; - for (i=0 ; i<3 ; i++) - { - miss = ent->v.origin[i] - ent->baseline.origin[i]; - if ( miss < -0.1 || miss > 0.1 ) - bits |= U_ORIGIN1<v.origin[i] - ent->baseline.origin[i]; + if (miss < -0.1 || miss > 0.1) + bits |= U_ORIGIN1 << i; + } - if ( ent->v.angles[0] != ent->baseline.angles[0] ) - bits |= U_ANGLE1; + if (ent->v.angles[0] != ent->baseline.angles[0]) + bits |= U_ANGLE1; - if ( ent->v.angles[1] != ent->baseline.angles[1] ) - bits |= U_ANGLE2; + if (ent->v.angles[1] != ent->baseline.angles[1]) + bits |= U_ANGLE2; - if ( ent->v.angles[2] != ent->baseline.angles[2] ) - bits |= U_ANGLE3; + if (ent->v.angles[2] != ent->baseline.angles[2]) + bits |= U_ANGLE3; - if (ent->v.movetype == MOVETYPE_STEP) - bits |= U_STEP; // don't mess up the step animation + if (ent->v.movetype == MOVETYPE_STEP) + bits |= U_STEP; // don't mess up the step animation - if (ent->baseline.colormap != ent->v.colormap) - bits |= U_COLORMAP; + if (ent->baseline.colormap != ent->v.colormap) + bits |= U_COLORMAP; - if (ent->baseline.skin != ent->v.skin) - bits |= U_SKIN; + if (ent->baseline.skin != ent->v.skin) + bits |= U_SKIN; - if (ent->baseline.frame != ent->v.frame) - bits |= U_FRAME; + if (ent->baseline.frame != ent->v.frame) + bits |= U_FRAME; - if ((ent->baseline.effects ^ (int)ent->v.effects) & pr_effects_mask) - bits |= U_EFFECTS; + if ((ent->baseline.effects ^ (int) ent->v.effects) & pr_effects_mask) + bits |= U_EFFECTS; - if (ent->baseline.modelindex != ent->v.modelindex) - bits |= U_MODEL; + if (ent->baseline.modelindex != ent->v.modelindex) + bits |= U_MODEL; - //johnfitz -- alpha - if (pr_alpha_supported) - { - // TODO: find a cleaner place to put this code - val = GetEdictFieldValue(ent, "alpha"); - if (val) - ent->alpha = ENTALPHA_ENCODE(val->_float); - } + //johnfitz -- alpha + if (pr_alpha_supported) { + // TODO: find a cleaner place to put this code + val = GetEdictFieldValue(ent, "alpha"); + if (val) + ent->alpha = ENTALPHA_ENCODE(val->_float); + } - //don't send invisible entities unless they have effects - if (ent->alpha == ENTALPHA_ZERO && !((int)ent->v.effects & pr_effects_mask)) - continue; - //johnfitz + //don't send invisible entities unless they have effects + if (ent->alpha == ENTALPHA_ZERO && !((int) ent->v.effects & pr_effects_mask)) + continue; + //johnfitz - val = GetEdictFieldValue(ent, "scale"); - if (val) - ent->scale = ENTSCALE_ENCODE(val->_float); - else - ent->scale = ENTSCALE_DEFAULT; + val = GetEdictFieldValue(ent, "scale"); + if (val) + ent->scale = ENTSCALE_ENCODE(val->_float); + else + ent->scale = ENTSCALE_DEFAULT; - //johnfitz -- PROTOCOL_FITZQUAKE - if (sv.protocol != PROTOCOL_NETQUAKE) - { + //johnfitz -- PROTOCOL_FITZQUAKE + if (sv.protocol != PROTOCOL_NETQUAKE) { + if (ent->baseline.alpha != ent->alpha) bits |= U_ALPHA; + if (ent->baseline.scale != ent->scale) bits |= U_SCALE; + if (bits & U_FRAME && (int) ent->v.frame & 0xFF00) bits |= U_FRAME2; + if (bits & U_MODEL && (int) ent->v.modelindex & 0xFF00) bits |= U_MODEL2; + if (ent->sendinterval) bits |= U_LERPFINISH; + if (bits >= 65536) bits |= U_EXTEND1; + if (bits >= 16777216) bits |= U_EXTEND2; + } + //johnfitz - if (ent->baseline.alpha != ent->alpha) bits |= U_ALPHA; - if (ent->baseline.scale != ent->scale) bits |= U_SCALE; - if (bits & U_FRAME && (int)ent->v.frame & 0xFF00) bits |= U_FRAME2; - if (bits & U_MODEL && (int)ent->v.modelindex & 0xFF00) bits |= U_MODEL2; - if (ent->sendinterval) bits |= U_LERPFINISH; - if (bits >= 65536) bits |= U_EXTEND1; - if (bits >= 16777216) bits |= U_EXTEND2; - } - //johnfitz + if (e >= 256) + bits |= U_LONGENTITY; - if (e >= 256) - bits |= U_LONGENTITY; + if (bits >= 256) + bits |= U_MOREBITS; - if (bits >= 256) - bits |= U_MOREBITS; + // + // write the message + // + MSG_WriteByte(msg, bits | U_SIGNAL); - // - // write the message - // - MSG_WriteByte (msg, bits | U_SIGNAL); + if (bits & U_MOREBITS) + MSG_WriteByte(msg, bits >> 8); - if (bits & U_MOREBITS) - MSG_WriteByte (msg, bits>>8); + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits & U_EXTEND1) + MSG_WriteByte(msg, bits >> 16); + if (bits & U_EXTEND2) + MSG_WriteByte(msg, bits >> 24); + //johnfitz - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & U_EXTEND1) - MSG_WriteByte(msg, bits>>16); - if (bits & U_EXTEND2) - MSG_WriteByte(msg, bits>>24); - //johnfitz + if (bits & U_LONGENTITY) + MSG_WriteShort(msg, e); + else + MSG_WriteByte(msg, e); - if (bits & U_LONGENTITY) - MSG_WriteShort (msg,e); - else - MSG_WriteByte (msg,e); + if (bits & U_MODEL) + MSG_WriteByte(msg, ent->v.modelindex); + if (bits & U_FRAME) + MSG_WriteByte(msg, ent->v.frame); + if (bits & U_COLORMAP) + MSG_WriteByte(msg, ent->v.colormap); + if (bits & U_SKIN) + MSG_WriteByte(msg, ent->v.skin); + if (bits & U_EFFECTS) + MSG_WriteByte(msg, (int) ent->v.effects & pr_effects_mask); + if (bits & U_ORIGIN1) + MSG_WriteCoord(msg, ent->v.origin[0], sv.protocolflags); + if (bits & U_ANGLE1) + MSG_WriteAngle(msg, ent->v.angles[0], sv.protocolflags); + if (bits & U_ORIGIN2) + MSG_WriteCoord(msg, ent->v.origin[1], sv.protocolflags); + if (bits & U_ANGLE2) + MSG_WriteAngle(msg, ent->v.angles[1], sv.protocolflags); + if (bits & U_ORIGIN3) + MSG_WriteCoord(msg, ent->v.origin[2], sv.protocolflags); + if (bits & U_ANGLE3) + MSG_WriteAngle(msg, ent->v.angles[2], sv.protocolflags); - if (bits & U_MODEL) - MSG_WriteByte (msg, ent->v.modelindex); - if (bits & U_FRAME) - MSG_WriteByte (msg, ent->v.frame); - if (bits & U_COLORMAP) - MSG_WriteByte (msg, ent->v.colormap); - if (bits & U_SKIN) - MSG_WriteByte (msg, ent->v.skin); - if (bits & U_EFFECTS) - MSG_WriteByte (msg, (int)ent->v.effects & pr_effects_mask); - if (bits & U_ORIGIN1) - MSG_WriteCoord (msg, ent->v.origin[0], sv.protocolflags); - if (bits & U_ANGLE1) - MSG_WriteAngle(msg, ent->v.angles[0], sv.protocolflags); - if (bits & U_ORIGIN2) - MSG_WriteCoord (msg, ent->v.origin[1], sv.protocolflags); - if (bits & U_ANGLE2) - MSG_WriteAngle(msg, ent->v.angles[1], sv.protocolflags); - if (bits & U_ORIGIN3) - MSG_WriteCoord (msg, ent->v.origin[2], sv.protocolflags); - if (bits & U_ANGLE3) - MSG_WriteAngle(msg, ent->v.angles[2], sv.protocolflags); + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits & U_ALPHA) + MSG_WriteByte(msg, ent->alpha); + if (bits & U_SCALE) + MSG_WriteByte(msg, ent->scale); + if (bits & U_FRAME2) + MSG_WriteByte(msg, (int) ent->v.frame >> 8); + if (bits & U_MODEL2) + MSG_WriteByte(msg, (int) ent->v.modelindex >> 8); + if (bits & U_LERPFINISH) + MSG_WriteByte(msg, (byte) (Q_rint((ent->v.nextthink-sv.time)*255))); + //johnfitz + } - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & U_ALPHA) - MSG_WriteByte(msg, ent->alpha); - if (bits & U_SCALE) - MSG_WriteByte(msg, ent->scale); - if (bits & U_FRAME2) - MSG_WriteByte(msg, (int)ent->v.frame >> 8); - if (bits & U_MODEL2) - MSG_WriteByte(msg, (int)ent->v.modelindex >> 8); - if (bits & U_LERPFINISH) - MSG_WriteByte(msg, (byte)(Q_rint((ent->v.nextthink-sv.time)*255))); - //johnfitz - } - - //johnfitz -- devstats + //johnfitz -- devstats stats: - if (msg->cursize > 1024 && dev_peakstats.packetsize <= 1024) - Con_DWarning ("%i byte packet exceeds standard limit of 1024 (max = %d).\n", msg->cursize, msg->maxsize); - dev_stats.packetsize = msg->cursize; - dev_peakstats.packetsize = std::max(msg->cursize, dev_peakstats.packetsize); - //johnfitz + if (msg->cursize > 1024 && dev_peakstats.packetsize <= 1024) + Con_DWarning("%i byte packet exceeds standard limit of 1024 (max = %d).\n", msg->cursize, msg->maxsize); + dev_stats.packetsize = msg->cursize; + dev_peakstats.packetsize = std::max(msg->cursize, dev_peakstats.packetsize); + //johnfitz } /* @@ -809,16 +771,14 @@ SV_CleanupEnts ============= */ -void SV_CleanupEnts (void) -{ - int e; - edict_t *ent; +void SV_CleanupEnts(void) { + int e; + edict_t *ent; - ent = NEXT_EDICT(sv.edicts); - for (e=1 ; ev.effects = (int)ent->v.effects & ~EF_MUZZLEFLASH; - } + ent = NEXT_EDICT(sv.edicts); + for (e = 1; e < sv.num_edicts; e++, ent = NEXT_EDICT(ent)) { + ent->v.effects = (int) ent->v.effects & ~EF_MUZZLEFLASH; + } } /* @@ -827,180 +787,170 @@ SV_WriteClientdataToMessage ================== */ -void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) -{ - int bits; - int i; - edict_t *other; - int items; - eval_t *val; +void SV_WriteClientdataToMessage(edict_t *ent, sizebuf_t *msg) { + int bits; + int i; + edict_t *other; + int items; + eval_t *val; -// -// send a damage message -// - if (ent->v.dmg_take || ent->v.dmg_save) - { - other = PROG_TO_EDICT(ent->v.dmg_inflictor); - MSG_WriteByte (msg, svc_damage); - MSG_WriteByte (msg, ent->v.dmg_save); - MSG_WriteByte (msg, ent->v.dmg_take); - for (i=0 ; i<3 ; i++) - MSG_WriteCoord (msg, other->v.origin[i] + 0.5*(other->v.mins[i] + other->v.maxs[i]), sv.protocolflags ); + // + // send a damage message + // + if (ent->v.dmg_take || ent->v.dmg_save) { + other = PROG_TO_EDICT(ent->v.dmg_inflictor); + MSG_WriteByte(msg, svc_damage); + MSG_WriteByte(msg, ent->v.dmg_save); + MSG_WriteByte(msg, ent->v.dmg_take); + for (i = 0; i < 3; i++) + MSG_WriteCoord(msg, other->v.origin[i] + 0.5 * (other->v.mins[i] + other->v.maxs[i]), sv.protocolflags); - ent->v.dmg_take = 0; - ent->v.dmg_save = 0; - } + ent->v.dmg_take = 0; + ent->v.dmg_save = 0; + } -// -// send the current viewpos offset from the view entity -// - SV_SetIdealPitch (); // how much to look up / down ideally + // + // send the current viewpos offset from the view entity + // + SV_SetIdealPitch(); // how much to look up / down ideally -// a fixangle might get lost in a dropped packet. Oh well. - if ( ent->v.fixangle ) - { - MSG_WriteByte (msg, svc_setangle); - for (i=0 ; i < 3 ; i++) - MSG_WriteAngle (msg, ent->v.angles[i], sv.protocolflags ); - ent->v.fixangle = 0; - } + // a fixangle might get lost in a dropped packet. Oh well. + if (ent->v.fixangle) { + MSG_WriteByte(msg, svc_setangle); + for (i = 0; i < 3; i++) + MSG_WriteAngle(msg, ent->v.angles[i], sv.protocolflags); + ent->v.fixangle = 0; + } - bits = 0; + bits = 0; - if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT) - bits |= SU_VIEWHEIGHT; + if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT) + bits |= SU_VIEWHEIGHT; - if (ent->v.idealpitch) - bits |= SU_IDEALPITCH; + if (ent->v.idealpitch) + bits |= SU_IDEALPITCH; -// stuff the sigil bits into the high bits of items for sbar, or else -// mix in items2 - val = GetEdictFieldValue(ent, "items2"); + // stuff the sigil bits into the high bits of items for sbar, or else + // mix in items2 + val = GetEdictFieldValue(ent, "items2"); - if (val) - items = (int)ent->v.items | ((int)val->_float << 23); - else - items = (int)ent->v.items | ((int)pr_global_struct->serverflags << 28); + if (val) + items = (int) ent->v.items | ((int) val->_float << 23); + else + items = (int) ent->v.items | ((int) pr_global_struct->serverflags << 28); - bits |= SU_ITEMS; + bits |= SU_ITEMS; - if ( (int)ent->v.flags & FL_ONGROUND) - bits |= SU_ONGROUND; + if ((int) ent->v.flags & FL_ONGROUND) + bits |= SU_ONGROUND; - if ( ent->v.waterlevel >= 2) - bits |= SU_INWATER; + if (ent->v.waterlevel >= 2) + bits |= SU_INWATER; - for (i=0 ; i<3 ; i++) - { - if (ent->v.punchangle[i]) - bits |= (SU_PUNCH1<v.velocity[i]) - bits |= (SU_VELOCITY1<v.punchangle[i]) + bits |= (SU_PUNCH1 << i); + if (ent->v.velocity[i]) + bits |= (SU_VELOCITY1 << i); + } - if (ent->v.weaponframe) - bits |= SU_WEAPONFRAME; + if (ent->v.weaponframe) + bits |= SU_WEAPONFRAME; - if (ent->v.armorvalue) - bits |= SU_ARMOR; + if (ent->v.armorvalue) + bits |= SU_ARMOR; -// if (ent->v.weapon) - bits |= SU_WEAPON; + // if (ent->v.weapon) + bits |= SU_WEAPON; - //johnfitz -- PROTOCOL_FITZQUAKE - if (sv.protocol != PROTOCOL_NETQUAKE) - { - if (bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2; - if ((int)ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2; - if ((int)ent->v.currentammo & 0xFF00) bits |= SU_AMMO2; - if ((int)ent->v.ammo_shells & 0xFF00) bits |= SU_SHELLS2; - if ((int)ent->v.ammo_nails & 0xFF00) bits |= SU_NAILS2; - if ((int)ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2; - if ((int)ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2; - if (bits & SU_WEAPONFRAME && (int)ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2; - if (bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA; //for now, weaponalpha = client entity alpha - if (bits >= 65536) bits |= SU_EXTEND1; - if (bits >= 16777216) bits |= SU_EXTEND2; - } - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (sv.protocol != PROTOCOL_NETQUAKE) { + if (bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2; + if ((int) ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2; + if ((int) ent->v.currentammo & 0xFF00) bits |= SU_AMMO2; + if ((int) ent->v.ammo_shells & 0xFF00) bits |= SU_SHELLS2; + if ((int) ent->v.ammo_nails & 0xFF00) bits |= SU_NAILS2; + if ((int) ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2; + if ((int) ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2; + if (bits & SU_WEAPONFRAME && (int) ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2; + if (bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA; + //for now, weaponalpha = client entity alpha + if (bits >= 65536) bits |= SU_EXTEND1; + if (bits >= 16777216) bits |= SU_EXTEND2; + } + //johnfitz -// send the data + // send the data - MSG_WriteByte (msg, svc_clientdata); - MSG_WriteShort (msg, bits); + MSG_WriteByte(msg, svc_clientdata); + MSG_WriteShort(msg, bits); - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & SU_EXTEND1) MSG_WriteByte(msg, bits>>16); - if (bits & SU_EXTEND2) MSG_WriteByte(msg, bits>>24); - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits & SU_EXTEND1) MSG_WriteByte(msg, bits >> 16); + if (bits & SU_EXTEND2) MSG_WriteByte(msg, bits >> 24); + //johnfitz - if (bits & SU_VIEWHEIGHT) - MSG_WriteChar (msg, ent->v.view_ofs[2]); + if (bits & SU_VIEWHEIGHT) + MSG_WriteChar(msg, ent->v.view_ofs[2]); - if (bits & SU_IDEALPITCH) - MSG_WriteChar (msg, ent->v.idealpitch); + if (bits & SU_IDEALPITCH) + MSG_WriteChar(msg, ent->v.idealpitch); - for (i=0 ; i<3 ; i++) - { - if (bits & (SU_PUNCH1<v.punchangle[i]); - if (bits & (SU_VELOCITY1<v.velocity[i]/16); - } + for (i = 0; i < 3; i++) { + if (bits & (SU_PUNCH1 << i)) + MSG_WriteChar(msg, ent->v.punchangle[i]); + if (bits & (SU_VELOCITY1 << i)) + MSG_WriteChar(msg, ent->v.velocity[i] / 16); + } -// [always sent] if (bits & SU_ITEMS) - MSG_WriteLong (msg, items); + // [always sent] if (bits & SU_ITEMS) + MSG_WriteLong(msg, items); - if (bits & SU_WEAPONFRAME) - MSG_WriteByte (msg, ent->v.weaponframe); - if (bits & SU_ARMOR) - MSG_WriteByte (msg, ent->v.armorvalue); - if (bits & SU_WEAPON) - MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel))); + if (bits & SU_WEAPONFRAME) + MSG_WriteByte(msg, ent->v.weaponframe); + if (bits & SU_ARMOR) + MSG_WriteByte(msg, ent->v.armorvalue); + if (bits & SU_WEAPON) + MSG_WriteByte(msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel))); - MSG_WriteShort (msg, ent->v.health); - MSG_WriteByte (msg, ent->v.currentammo); - MSG_WriteByte (msg, ent->v.ammo_shells); - MSG_WriteByte (msg, ent->v.ammo_nails); - MSG_WriteByte (msg, ent->v.ammo_rockets); - MSG_WriteByte (msg, ent->v.ammo_cells); + MSG_WriteShort(msg, ent->v.health); + MSG_WriteByte(msg, ent->v.currentammo); + MSG_WriteByte(msg, ent->v.ammo_shells); + MSG_WriteByte(msg, ent->v.ammo_nails); + MSG_WriteByte(msg, ent->v.ammo_rockets); + MSG_WriteByte(msg, ent->v.ammo_cells); - if (standard_quake) - { - MSG_WriteByte (msg, ent->v.weapon); - } - else - { - for(i=0;i<32;i++) - { - if ( ((int)ent->v.weapon) & (1<v.weapon); + } else { + for (i = 0; i < 32; i++) { + if (((int) ent->v.weapon) & (1 << i)) { + MSG_WriteByte(msg, i); + break; + } + } + } - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & SU_WEAPON2) - MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) >> 8); - if (bits & SU_ARMOR2) - MSG_WriteByte (msg, (int)ent->v.armorvalue >> 8); - if (bits & SU_AMMO2) - MSG_WriteByte (msg, (int)ent->v.currentammo >> 8); - if (bits & SU_SHELLS2) - MSG_WriteByte (msg, (int)ent->v.ammo_shells >> 8); - if (bits & SU_NAILS2) - MSG_WriteByte (msg, (int)ent->v.ammo_nails >> 8); - if (bits & SU_ROCKETS2) - MSG_WriteByte (msg, (int)ent->v.ammo_rockets >> 8); - if (bits & SU_CELLS2) - MSG_WriteByte (msg, (int)ent->v.ammo_cells >> 8); - if (bits & SU_WEAPONFRAME2) - MSG_WriteByte (msg, (int)ent->v.weaponframe >> 8); - if (bits & SU_WEAPONALPHA) - MSG_WriteByte (msg, ent->alpha); //for now, weaponalpha = client entity alpha - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits & SU_WEAPON2) + MSG_WriteByte(msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) >> 8); + if (bits & SU_ARMOR2) + MSG_WriteByte(msg, (int) ent->v.armorvalue >> 8); + if (bits & SU_AMMO2) + MSG_WriteByte(msg, (int) ent->v.currentammo >> 8); + if (bits & SU_SHELLS2) + MSG_WriteByte(msg, (int) ent->v.ammo_shells >> 8); + if (bits & SU_NAILS2) + MSG_WriteByte(msg, (int) ent->v.ammo_nails >> 8); + if (bits & SU_ROCKETS2) + MSG_WriteByte(msg, (int) ent->v.ammo_rockets >> 8); + if (bits & SU_CELLS2) + MSG_WriteByte(msg, (int) ent->v.ammo_cells >> 8); + if (bits & SU_WEAPONFRAME2) + MSG_WriteByte(msg, (int) ent->v.weaponframe >> 8); + if (bits & SU_WEAPONALPHA) + MSG_WriteByte(msg, ent->alpha); //for now, weaponalpha = client entity alpha + //johnfitz } /* @@ -1008,40 +958,38 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) SV_SendClientDatagram ======================= */ -qboolean SV_SendClientDatagram (client_t *client) -{ - byte buf[MAX_DATAGRAM]; - sizebuf_t msg; +bool SV_SendClientDatagram(client_t *client) { + byte buf[MAX_DATAGRAM]; + sizebuf_t msg; - msg.data = buf; - msg.maxsize = sizeof(buf); - msg.cursize = 0; + msg.data = buf; + msg.maxsize = sizeof(buf); + msg.cursize = 0; - //johnfitz -- if client is nonlocal, use smaller max size so packets aren't fragmented - if (Q_strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0) - msg.maxsize = DATAGRAM_MTU; - //johnfitz + //johnfitz -- if client is nonlocal, use smaller max size so packets aren't fragmented + if (std::strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0) + msg.maxsize = DATAGRAM_MTU; + //johnfitz - MSG_WriteByte (&msg, svc_time); - MSG_WriteFloat (&msg, sv.time); + MSG_WriteByte(&msg, svc_time); + MSG_WriteFloat(&msg, sv.time); -// add the client specific data to the datagram - SV_WriteClientdataToMessage (client->edict, &msg); + // add the client specific data to the datagram + SV_WriteClientdataToMessage(client->edict, &msg); - SV_WriteEntitiesToClient (client->edict, &msg); + SV_WriteEntitiesToClient(client->edict, &msg); -// copy the server datagram if there is space - if (msg.cursize + sv.datagram.cursize < msg.maxsize) - SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize); + // copy the server datagram if there is space + if (msg.cursize + sv.datagram.cursize < msg.maxsize) + SZ_Write(&msg, sv.datagram.data, sv.datagram.cursize); -// send the datagram - if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1) - { - SV_DropClient (true);// if the message couldn't send, kick off - return false; - } + // send the datagram + if (NET_SendUnreliableMessage(client->netconnection, &msg) == -1) { + SV_DropClient(true); // if the message couldn't send, kick off + return false; + } - return true; + return true; } /* @@ -1049,37 +997,32 @@ qboolean SV_SendClientDatagram (client_t *client) SV_UpdateToReliableMessages ======================= */ -void SV_UpdateToReliableMessages (void) -{ - int i, j; - client_t *client; +void SV_UpdateToReliableMessages(void) { + int i, j; + client_t *client; -// check for changes to be sent over the reliable streams - for (i=0, host_client = svs.clients ; iold_frags != host_client->edict->v.frags) - { - for (j=0, client = svs.clients ; jactive) - continue; - MSG_WriteByte (&client->message, svc_updatefrags); - MSG_WriteByte (&client->message, i); - MSG_WriteShort (&client->message, host_client->edict->v.frags); - } + // check for changes to be sent over the reliable streams + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (host_client->old_frags != host_client->edict->v.frags) { + for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { + if (!client->active) + continue; + MSG_WriteByte(&client->message, svc_updatefrags); + MSG_WriteByte(&client->message, i); + MSG_WriteShort(&client->message, host_client->edict->v.frags); + } - host_client->old_frags = host_client->edict->v.frags; - } - } + host_client->old_frags = host_client->edict->v.frags; + } + } - for (j=0, client = svs.clients ; jactive) - continue; - SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize); - } + for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { + if (!client->active) + continue; + SZ_Write(&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize); + } - SZ_Clear (&sv.reliable_datagram); + SZ_Clear(&sv.reliable_datagram); } @@ -1091,20 +1034,19 @@ Send a nop message without trashing or sending the accumulated client message buffer ======================= */ -void SV_SendNop (client_t *client) -{ - sizebuf_t msg; - byte buf[4]; +void SV_SendNop(client_t *client) { + sizebuf_t msg; + byte buf[4]; - msg.data = buf; - msg.maxsize = sizeof(buf); - msg.cursize = 0; + msg.data = buf; + msg.maxsize = sizeof(buf); + msg.cursize = 0; - MSG_WriteChar (&msg, svc_nop); + MSG_WriteChar(&msg, svc_nop); - if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1) - SV_DropClient (true); // if the message couldn't send, kick off - client->last_message = realtime; + if (NET_SendUnreliableMessage(client->netconnection, &msg) == -1) + SV_DropClient(true); // if the message couldn't send, kick off + client->last_message = realtime; } /* @@ -1112,103 +1054,89 @@ void SV_SendNop (client_t *client) SV_SendClientMessages ======================= */ -void SV_SendClientMessages (void) -{ - int i; +void SV_SendClientMessages(void) { + int i; -// update frags, names, etc - SV_UpdateToReliableMessages (); + // update frags, names, etc + SV_UpdateToReliableMessages(); -// build individual updates - for (i=0, host_client = svs.clients ; iactive) - continue; + // build individual updates + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (!host_client->active) + continue; - if (host_client->spawned) - { - if (!SV_SendClientDatagram (host_client)) - continue; - } - else - { - // the player isn't totally in the game yet - // send small keepalive messages if too much time has passed - // send a full message when the next signon stage has been requested - // some other message data (name changes, etc) may accumulate - // between signon stages - if (!host_client->sendsignon) - { - if (realtime - host_client->last_message > 5) - SV_SendNop (host_client); - continue; // don't send out non-signon messages - } - if (host_client->sendsignon == PRESPAWN_SIGNONBUFS) - { - qboolean local = SV_IsLocalClient (host_client); - while (host_client->signonidx < sv.num_signon_buffers) - { - sizebuf_t *signon = sv.signon_buffers[host_client->signonidx]; - if (host_client->message.cursize + signon->cursize > host_client->message.maxsize) - break; - SZ_Write (&host_client->message, signon->data, signon->cursize); - host_client->signonidx++; - // only send multiple buffers at once when playing locally, - // otherwise we send one signon at a time to avoid overflowing - // the datagram buffer for clients using a lower limit (e.g. 32000 in QS) - if (!local) - break; - } - if (host_client->signonidx == sv.num_signon_buffers) - host_client->sendsignon = PRESPAWN_SIGNONMSG; - } - if (host_client->sendsignon == PRESPAWN_SIGNONMSG) - { - if (host_client->message.cursize + 2 < host_client->message.maxsize) - { - MSG_WriteByte (&host_client->message, svc_signonnum); - MSG_WriteByte (&host_client->message, 2); - host_client->sendsignon = PRESPAWN_FLUSH; - } - } - } + if (host_client->spawned) { + if (!SV_SendClientDatagram(host_client)) + continue; + } else { + // the player isn't totally in the game yet + // send small keepalive messages if too much time has passed + // send a full message when the next signon stage has been requested + // some other message data (name changes, etc) may accumulate + // between signon stages + if (!host_client->sendsignon) { + if (realtime - host_client->last_message > 5) + SV_SendNop(host_client); + continue; // don't send out non-signon messages + } + if (host_client->sendsignon == PRESPAWN_SIGNONBUFS) { + bool local = SV_IsLocalClient(host_client); + while (host_client->signonidx < sv.num_signon_buffers) { + sizebuf_t *signon = sv.signon_buffers[host_client->signonidx]; + if (host_client->message.cursize + signon->cursize > host_client->message.maxsize) + break; + SZ_Write(&host_client->message, signon->data, signon->cursize); + host_client->signonidx++; + // only send multiple buffers at once when playing locally, + // otherwise we send one signon at a time to avoid overflowing + // the datagram buffer for clients using a lower limit (e.g. 32000 in QS) + if (!local) + break; + } + if (host_client->signonidx == sv.num_signon_buffers) + host_client->sendsignon = PRESPAWN_SIGNONMSG; + } + if (host_client->sendsignon == PRESPAWN_SIGNONMSG) { + if (host_client->message.cursize + 2 < host_client->message.maxsize) { + MSG_WriteByte(&host_client->message, svc_signonnum); + MSG_WriteByte(&host_client->message, 2); + host_client->sendsignon = PRESPAWN_FLUSH; + } + } + } - // check for an overflowed message. Should only happen - // on a very fucked up connection that backs up a lot, then - // changes level - if (host_client->message.overflowed) - { - SV_DropClient (true); - host_client->message.overflowed = false; - continue; - } + // check for an overflowed message. Should only happen + // on a very fucked up connection that backs up a lot, then + // changes level + if (host_client->message.overflowed) { + SV_DropClient(true); + host_client->message.overflowed = false; + continue; + } - if (host_client->message.cursize || host_client->dropasap) - { - if (!NET_CanSendMessage (host_client->netconnection)) - { -// I_Printf ("can't write\n"); - continue; - } + if (host_client->message.cursize || host_client->dropasap) { + if (!NET_CanSendMessage(host_client->netconnection)) { + // I_Printf ("can't write\n"); + continue; + } - if (host_client->dropasap) - SV_DropClient (false); // went to another level - else - { - if (NET_SendMessage (host_client->netconnection - , &host_client->message) == -1) - SV_DropClient (true); // if the message couldn't send, kick off - SZ_Clear (&host_client->message); - host_client->last_message = realtime; - if (host_client->sendsignon == PRESPAWN_FLUSH) - host_client->sendsignon = PRESPAWN_DONE; - } - } - } + if (host_client->dropasap) + SV_DropClient(false); // went to another level + else { + if (NET_SendMessage(host_client->netconnection + , &host_client->message) == -1) + SV_DropClient(true); // if the message couldn't send, kick off + SZ_Clear(&host_client->message); + host_client->last_message = realtime; + if (host_client->sendsignon == PRESPAWN_FLUSH) + host_client->sendsignon = PRESPAWN_DONE; + } + } + } -// clear muzzle flashes - SV_CleanupEnts (); + // clear muzzle flashes + SV_CleanupEnts(); } @@ -1227,17 +1155,16 @@ SERVER SPAWNING SV_AddSignonBuffer ================ */ -static void SV_AddSignonBuffer (void) -{ - sizebuf_t *sb; - if (sv.num_signon_buffers >= MAX_SIGNON_BUFFERS) - Host_Error ("SV_AddSignonBuffer overflow\n"); +static void SV_AddSignonBuffer(void) { + sizebuf_t *sb; + if (sv.num_signon_buffers >= MAX_SIGNON_BUFFERS) + Host_Error("SV_AddSignonBuffer overflow\n"); - sb = (sizebuf_t *) Hunk_AllocName (sizeof (sizebuf_t) + SIGNON_SIZE, "signon"); - sb->data = (byte *)(sb + 1); - sb->maxsize = SIGNON_SIZE; - sv.signon_buffers[sv.num_signon_buffers++] = sb; - sv.signon = sb; + sb = (sizebuf_t *) Hunk_AllocName(sizeof(sizebuf_t) + SIGNON_SIZE, "signon"); + sb->data = (byte *) (sb + 1); + sb->maxsize = SIGNON_SIZE; + sv.signon_buffers[sv.num_signon_buffers++] = sb; + sv.signon = sb; } /* @@ -1245,10 +1172,9 @@ static void SV_AddSignonBuffer (void) SV_ReserveSignonSpace ================ */ -void SV_ReserveSignonSpace (int numbytes) -{ - if (sv.signon->cursize + numbytes > sv.signon->maxsize) - SV_AddSignonBuffer (); +void SV_ReserveSignonSpace(int numbytes) { + if (sv.signon->cursize + numbytes > sv.signon->maxsize) + SV_AddSignonBuffer(); } /* @@ -1257,19 +1183,18 @@ SV_ModelIndex ================ */ -int SV_ModelIndex (const char *name) -{ - int i; +int SV_ModelIndex(const char *name) { + int i; - if (!name || !name[0]) - return 0; + if (!name || !name[0]) + return 0; - for (i=0 ; ifree) - continue; - if (entnum > svs.maxclients && !svent->v.modelindex) - continue; + for (entnum = 0; entnum < sv.num_edicts; entnum++) { + // get the current server version + svent = EDICT_NUM(entnum); + if (svent->free) + continue; + if (entnum > svs.maxclients && !svent->v.modelindex) + continue; - // - // create entity baseline - // - VectorCopy (svent->v.origin, svent->baseline.origin); - VectorCopy (svent->v.angles, svent->baseline.angles); - svent->baseline.frame = svent->v.frame; - svent->baseline.skin = svent->v.skin; - if (entnum > 0 && entnum <= svs.maxclients) - { - svent->baseline.colormap = entnum; - svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl"); - svent->baseline.alpha = ENTALPHA_DEFAULT; //johnfitz -- alpha support - svent->baseline.scale = ENTSCALE_DEFAULT; - } - else - { - svent->baseline.colormap = 0; - svent->baseline.modelindex = SV_ModelIndex(PR_GetString(svent->v.model)); - svent->baseline.alpha = svent->alpha; //johnfitz -- alpha support - svent->baseline.scale = ENTSCALE_DEFAULT; - if (sv.protocol == PROTOCOL_RMQ) - { - eval_t* val; - val = GetEdictFieldValue(svent, "scale"); - if (val) - svent->baseline.scale = ENTSCALE_ENCODE(val->_float); - } - } + // + // create entity baseline + // + VectorCopy(svent->v.origin, svent->baseline.origin); + VectorCopy(svent->v.angles, svent->baseline.angles); + svent->baseline.frame = svent->v.frame; + svent->baseline.skin = svent->v.skin; + if (entnum > 0 && entnum <= svs.maxclients) { + svent->baseline.colormap = entnum; + svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl"); + svent->baseline.alpha = ENTALPHA_DEFAULT; //johnfitz -- alpha support + svent->baseline.scale = ENTSCALE_DEFAULT; + } else { + svent->baseline.colormap = 0; + svent->baseline.modelindex = SV_ModelIndex(PR_GetString(svent->v.model)); + svent->baseline.alpha = svent->alpha; //johnfitz -- alpha support + svent->baseline.scale = ENTSCALE_DEFAULT; + if (sv.protocol == PROTOCOL_RMQ) { + eval_t *val; + val = GetEdictFieldValue(svent, "scale"); + if (val) + svent->baseline.scale = ENTSCALE_ENCODE(val->_float); + } + } - //johnfitz -- PROTOCOL_FITZQUAKE - bits = 0; - if (sv.protocol == PROTOCOL_NETQUAKE) //still want to send baseline in PROTOCOL_NETQUAKE, so reset these values - { - if (svent->baseline.modelindex & 0xFF00) - svent->baseline.modelindex = 0; - if (svent->baseline.frame & 0xFF00) - svent->baseline.frame = 0; - svent->baseline.alpha = ENTALPHA_DEFAULT; - svent->baseline.scale = ENTSCALE_DEFAULT; - } - else //decide which extra data needs to be sent - { - if (svent->baseline.modelindex & 0xFF00) - bits |= B_LARGEMODEL; - if (svent->baseline.frame & 0xFF00) - bits |= B_LARGEFRAME; - if (svent->baseline.alpha != ENTALPHA_DEFAULT) - bits |= B_ALPHA; - if (svent->baseline.scale != ENTSCALE_DEFAULT) - bits |= B_SCALE; - } - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + bits = 0; + if (sv.protocol == PROTOCOL_NETQUAKE) //still want to send baseline in PROTOCOL_NETQUAKE, so reset these values + { + if (svent->baseline.modelindex & 0xFF00) + svent->baseline.modelindex = 0; + if (svent->baseline.frame & 0xFF00) + svent->baseline.frame = 0; + svent->baseline.alpha = ENTALPHA_DEFAULT; + svent->baseline.scale = ENTSCALE_DEFAULT; + } else //decide which extra data needs to be sent + { + if (svent->baseline.modelindex & 0xFF00) + bits |= B_LARGEMODEL; + if (svent->baseline.frame & 0xFF00) + bits |= B_LARGEFRAME; + if (svent->baseline.alpha != ENTALPHA_DEFAULT) + bits |= B_ALPHA; + if (svent->baseline.scale != ENTSCALE_DEFAULT) + bits |= B_SCALE; + } + //johnfitz - // - // add to the message - // - SV_ReserveSignonSpace (35); + // + // add to the message + // + SV_ReserveSignonSpace(35); - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits) - MSG_WriteByte (sv.signon, svc_spawnbaseline2); - else - MSG_WriteByte (sv.signon, svc_spawnbaseline); - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits) + MSG_WriteByte(sv.signon, svc_spawnbaseline2); + else + MSG_WriteByte(sv.signon, svc_spawnbaseline); + //johnfitz - MSG_WriteShort (sv.signon,entnum); + MSG_WriteShort(sv.signon, entnum); - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits) - MSG_WriteByte (sv.signon, bits); + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits) + MSG_WriteByte(sv.signon, bits); - if (bits & B_LARGEMODEL) - MSG_WriteShort (sv.signon, svent->baseline.modelindex); - else - MSG_WriteByte (sv.signon, svent->baseline.modelindex); + if (bits & B_LARGEMODEL) + MSG_WriteShort(sv.signon, svent->baseline.modelindex); + else + MSG_WriteByte(sv.signon, svent->baseline.modelindex); - if (bits & B_LARGEFRAME) - MSG_WriteShort (sv.signon, svent->baseline.frame); - else - MSG_WriteByte (sv.signon, svent->baseline.frame); - //johnfitz + if (bits & B_LARGEFRAME) + MSG_WriteShort(sv.signon, svent->baseline.frame); + else + MSG_WriteByte(sv.signon, svent->baseline.frame); + //johnfitz - MSG_WriteByte (sv.signon, svent->baseline.colormap); - MSG_WriteByte (sv.signon, svent->baseline.skin); - for (i=0 ; i<3 ; i++) - { - MSG_WriteCoord(sv.signon, svent->baseline.origin[i], sv.protocolflags); - MSG_WriteAngle(sv.signon, svent->baseline.angles[i], sv.protocolflags); - } + MSG_WriteByte(sv.signon, svent->baseline.colormap); + MSG_WriteByte(sv.signon, svent->baseline.skin); + for (i = 0; i < 3; i++) { + MSG_WriteCoord(sv.signon, svent->baseline.origin[i], sv.protocolflags); + MSG_WriteAngle(sv.signon, svent->baseline.angles[i], sv.protocolflags); + } - //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & B_ALPHA) - MSG_WriteByte (sv.signon, svent->baseline.alpha); - //johnfitz + //johnfitz -- PROTOCOL_FITZQUAKE + if (bits & B_ALPHA) + MSG_WriteByte(sv.signon, svent->baseline.alpha); + //johnfitz - if (bits & B_SCALE) - MSG_WriteByte (sv.signon, svent->baseline.scale); - } + if (bits & B_SCALE) + MSG_WriteByte(sv.signon, svent->baseline.scale); + } } @@ -1401,21 +1318,20 @@ SV_SendReconnect Tell all the clients that the server is changing levels ================ */ -void SV_SendReconnect (void) -{ - byte data[128]; - sizebuf_t msg; +void SV_SendReconnect(void) { + byte data[128]; + sizebuf_t msg; - msg.data = data; - msg.cursize = 0; - msg.maxsize = sizeof(data); + msg.data = data; + msg.cursize = 0; + msg.maxsize = sizeof(data); - MSG_WriteChar (&msg, svc_stufftext); - MSG_WriteString (&msg, "reconnect\n"); - NET_SendToAll (&msg, 5.0); + MSG_WriteChar(&msg, svc_stufftext); + MSG_WriteString(&msg, "reconnect\n"); + NET_SendToAll(&msg, 5.0); - if (!isDedicated) - command::execute_string ("reconnect\n", command::source::command); + if (!isDedicated) + command::execute_string("reconnect\n", command::source::command); } @@ -1427,23 +1343,21 @@ Grabs the current state of each client for saving across the transition to another level ================ */ -void SV_SaveSpawnparms (void) -{ - int i, j; +void SV_SaveSpawnparms(void) { + int i, j; - svs.serverflags = pr_global_struct->serverflags; + svs.serverflags = pr_global_struct->serverflags; - for (i=0, host_client = svs.clients ; iactive) - continue; + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { + if (!host_client->active) + continue; - // call the progs to get default spawn parms for the new client - pr_global_struct->self = EDICT_TO_PROG(host_client->edict); - PR_ExecuteProgram (pr_global_struct->SetChangeParms); - for (j=0 ; jspawn_parms[j] = (&pr_global_struct->parm1)[j]; - } + // call the progs to get default spawn parms for the new client + pr_global_struct->self = EDICT_TO_PROG(host_client->edict); + PR_ExecuteProgram(pr_global_struct->SetChangeParms); + for (j = 0; j < NUM_SPAWN_PARMS; j++) + host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j]; + } } @@ -1454,167 +1368,161 @@ SV_SpawnServer This is called at the start of each level ================ */ -extern float scr_centertime_off; -void SV_SpawnServer (const char *server) -{ - static char dummy[8] = { 0,0,0,0,0,0,0,0 }; - edict_t *ent; - int i, signonsize; +extern float scr_centertime_off; - // let's not have any servers with no name - if (hostname.string[0] == 0) - convar::set ("hostname", "UNNAMED"); - scr_centertime_off = 0; +void SV_SpawnServer(const char *server) { + static char dummy[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + edict_t *ent; + int i, signonsize; - Con_DPrintf ("SpawnServer: %s\n",server); - svs.changelevel_issued = false; // now safe to issue another + // let's not have any servers with no name + if (hostname.string[0] == 0) + convar::set("hostname", "UNNAMED"); + scr_centertime_off = 0; -// -// tell all connected clients that we are going to a new level -// - if (sv.active) - { - SV_SendReconnect (); - } + Con_DPrintf("SpawnServer: %s\n", server); + svs.changelevel_issued = false; // now safe to issue another -// -// make cvars consistant -// - if (coop.value) - convar::set ("deathmatch", "0"); - current_skill = (int)(skill.value + 0.5); - if (current_skill < 0) - current_skill = 0; - if (current_skill > 3) - current_skill = 3; + // + // tell all connected clients that we are going to a new level + // + if (sv.active) { + SV_SendReconnect(); + } - convar::set_value ("skill", (float)current_skill); + // + // make cvars consistant + // + if (coop.value) + convar::set("deathmatch", "0"); + current_skill = (int) (skill.value + 0.5); + if (current_skill < 0) + current_skill = 0; + if (current_skill > 3) + current_skill = 3; -// -// set up the new server -// - //memset (&sv, 0, sizeof(sv)); - Host_ClearMemory (); + convar::set_value("skill", (float) current_skill); - q_strlcpy (sv.name, server, sizeof(sv.name)); + // + // set up the new server + // + //memset (&sv, 0, sizeof(sv)); + Host_ClearMemory(); - sv.protocol = sv_protocol; // johnfitz - - if (sv.protocol == PROTOCOL_RMQ) - { - // set up the protocol flags used by this server - // (note - these could be cvar-ised so that server admins could choose the protocol features used by their servers) - sv.protocolflags = PRFL_INT32COORD | PRFL_SHORTANGLE; - } - else sv.protocolflags = 0; + q_strlcpy(sv.name, server, sizeof(sv.name)); -// load progs to get entity field count - PR_LoadProgs (); + sv.protocol = sv_protocol; // johnfitz -// allocate server memory - /* Host_ClearMemory() called above already cleared the whole sv structure */ - sv.max_edicts = CLAMP (MIN_EDICTS,(int)max_edicts.value,MAX_EDICTS); //johnfitz -- max_edicts cvar - sv.edicts = (edict_t *) malloc (sv.max_edicts*pr_edict_size); // ericw -- sv.edicts switched to use malloc() + if (sv.protocol == PROTOCOL_RMQ) { + // set up the protocol flags used by this server + // (note - these could be cvar-ised so that server admins could choose the protocol features used by their servers) + sv.protocolflags = PRFL_INT32COORD | PRFL_SHORTANGLE; + } else sv.protocolflags = 0; - sv.datagram.maxsize = sizeof(sv.datagram_buf); - sv.datagram.cursize = 0; - sv.datagram.data = sv.datagram_buf; + // load progs to get entity field count + PR_LoadProgs(); - sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf); - sv.reliable_datagram.cursize = 0; - sv.reliable_datagram.data = sv.reliable_datagram_buf; + // allocate server memory + /* Host_ClearMemory() called above already cleared the whole sv structure */ + sv.max_edicts = std::clamp((int) max_edicts.value,MIN_EDICTS, MAX_EDICTS); //johnfitz -- max_edicts cvar + sv.edicts = (edict_t *) malloc(sv.max_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc() - SV_AddSignonBuffer (); + sv.datagram.maxsize = sizeof(sv.datagram_buf); + sv.datagram.cursize = 0; + sv.datagram.data = sv.datagram_buf; -// leave slots at start for clients only - sv.num_edicts = svs.maxclients+1; - memset(sv.edicts, 0, sv.num_edicts*pr_edict_size); // ericw -- sv.edicts switched to use malloc() - for (i=0 ; inumsubmodels ; i++) - { - sv.model_precache[1+i] = localmodels[i]; - sv.models[i+1] = Mod_ForName (localmodels[i], false); - } + q_strlcpy(sv.name, server, sizeof(sv.name)); + q_snprintf(sv.modelname, sizeof(sv.modelname), "maps/%s.bsp", server); + sv.worldmodel = Mod_ForName(sv.modelname, false); + if (!sv.worldmodel) { + Con_Printf("Couldn't spawn server %s\n", sv.modelname); + sv.active = false; + return; + } + sv.models[1] = sv.worldmodel; -// -// load the rest of the entities -// - ent = EDICT_NUM(0); - memset (&ent->v, 0, progs->entityfields * 4); - ent->free = false; - ent->v.model = PR_SetEngineString(sv.worldmodel->name); - ent->v.modelindex = 1; // world model - ent->v.solid = SOLID_BSP; - ent->v.movetype = MOVETYPE_PUSH; + // + // clear world interaction links + // + SV_ClearWorld(); - if (coop.value) - pr_global_struct->coop = coop.value; - else - pr_global_struct->deathmatch = deathmatch.value; + sv.sound_precache[0] = dummy; + sv.model_precache[0] = dummy; + sv.model_precache[1] = sv.modelname; + for (i = 1; i < sv.worldmodel->numsubmodels; i++) { + sv.model_precache[1 + i] = localmodels[i]; + sv.models[i + 1] = Mod_ForName(localmodels[i], false); + } - pr_global_struct->mapname = PR_SetEngineString(sv.name); + // + // load the rest of the entities + // + ent = EDICT_NUM(0); + memset(&ent->v, 0, progs->entityfields * 4); + ent->free = false; + ent->v.model = PR_SetEngineString(sv.worldmodel->name); + ent->v.modelindex = 1; // world model + ent->v.solid = SOLID_BSP; + ent->v.movetype = MOVETYPE_PUSH; -// serverflags are for cross level information (sigils) - pr_global_struct->serverflags = svs.serverflags; + if (coop.value) + pr_global_struct->coop = coop.value; + else + pr_global_struct->deathmatch = deathmatch.value; - ED_LoadFromFile (sv.worldmodel->entities); + pr_global_struct->mapname = PR_SetEngineString(sv.name); - sv.active = true; + // serverflags are for cross level information (sigils) + pr_global_struct->serverflags = svs.serverflags; -// all setup is completed, any further precache statements are errors - sv.state = ss_active; + ED_LoadFromFile(sv.worldmodel->entities); -// run two frames to allow everything to settle - host_frametime = 0.1; - SV_Physics (); - SV_Physics (); + sv.active = true; -// create a baseline for more efficient communications - SV_CreateBaseline (); + // all setup is completed, any further precache statements are errors + sv.state = ss_active; - //johnfitz -- warn if signon buffer larger than standard server can handle - for (i = 0, signonsize = 0; i < sv.num_signon_buffers; i++) - signonsize += sv.signon_buffers[i]->cursize; - if (signonsize > 64000-2) - Con_DWarning ("%i byte signon buffer exceeds QS limit of 63998.\n", signonsize); - else if (signonsize > 8000-2) //max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end - Con_DWarning ("%i byte signon buffer exceeds standard limit of 7998.\n", signonsize); - //johnfitz + // run two frames to allow everything to settle + host_frametime = 0.1; + SV_Physics(); + SV_Physics(); -// send serverinfo to all connected clients - for (i=0,host_client = svs.clients ; iactive) - SV_SendServerinfo (host_client); + // create a baseline for more efficient communications + SV_CreateBaseline(); - Con_DPrintf ("Server spawned.\n"); + //johnfitz -- warn if signon buffer larger than standard server can handle + for (i = 0, signonsize = 0; i < sv.num_signon_buffers; i++) + signonsize += sv.signon_buffers[i]->cursize; + if (signonsize > 64000 - 2) + Con_DWarning("%i byte signon buffer exceeds QS limit of 63998.\n", signonsize); + else if (signonsize > 8000 - 2) + //max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end + Con_DWarning("%i byte signon buffer exceeds standard limit of 7998.\n", signonsize); + //johnfitz + + // send serverinfo to all connected clients + for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + if (host_client->active) + SV_SendServerinfo(host_client); + + Con_DPrintf("Server spawned.\n"); } - diff --git a/Quake/sv_move.cpp b/Quake/sv_move.cpp index b642515..47771a0 100644 --- a/Quake/sv_move.cpp +++ b/Quake/sv_move.cpp @@ -36,7 +36,7 @@ is not a staircase. */ int c_yes, c_no; -qboolean SV_CheckBottom (edict_t *ent) +bool SV_CheckBottom (edict_t *ent) { vec3_t mins, maxs, start, stop; trace_t trace; @@ -109,7 +109,7 @@ possible, no move is done, false is returned, and pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ -qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) +bool SV_movestep (edict_t *ent, vec3_t move, bool relink) { float dz; vec3_t oldorg, neworg, end; @@ -232,7 +232,7 @@ facing it. ====================== */ void PF_changeyaw (void); -qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) +bool SV_StepDirection (edict_t *ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; @@ -370,7 +370,7 @@ SV_CloseEnough ====================== */ -qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) +bool SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) { int i; diff --git a/Quake/sv_phys.cpp b/Quake/sv_phys.cpp index f3299b3..2d506bd 100644 --- a/Quake/sv_phys.cpp +++ b/Quake/sv_phys.cpp @@ -120,7 +120,7 @@ in a frame. Not used for pushmove objects, because they must be exact. Returns false if the entity removed itself. ============= */ -qboolean SV_RunThink (edict_t *ent) +bool SV_RunThink (edict_t *ent) { float thinktime; @@ -660,7 +660,7 @@ void SV_CheckStuck (edict_t *ent) SV_CheckWater ============= */ -qboolean SV_CheckWater (edict_t *ent) +bool SV_CheckWater (edict_t *ent) { vec3_t point; int cont; @@ -1121,7 +1121,7 @@ will fall if the floor is pulled out from under them. */ void SV_Physics_Step (edict_t *ent) { - qboolean hitsound; + bool hitsound; // freefall if not onground if ( ! ((int)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) ) diff --git a/Quake/sv_user.cpp b/Quake/sv_user.cpp index 52e30d5..26b99e7 100644 --- a/Quake/sv_user.cpp +++ b/Quake/sv_user.cpp @@ -36,7 +36,7 @@ float *angles; float *origin; float *velocity; -qboolean onground; +bool onground; usercmd_t cmd; @@ -479,7 +479,7 @@ SV_ReadClientMessage Returns false if the client should be killed =================== */ -qboolean SV_ReadClientMessage (void) +bool SV_ReadClientMessage (void) { int ret; int ccmd; diff --git a/Quake/sys_sdl_unix.cpp b/Quake/sys_sdl_unix.cpp index 8cc7272..fee2308 100644 --- a/Quake/sys_sdl_unix.cpp +++ b/Quake/sys_sdl_unix.cpp @@ -48,12 +48,12 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif -qboolean isDedicated; +bool isDedicated; convar sys_throttle = {"sys_throttle", "0.02", {.archive = true}}; #define MAX_HANDLES 32 /* johnfitz -- was 10 */ static FILE *sys_handles[MAX_HANDLES]; -static qboolean stdinIsATTY; /* from ioquake3 source */ +static bool stdinIsATTY; /* from ioquake3 source */ static int findhandle (void) @@ -460,7 +460,7 @@ double Sys_DoubleTime (void) const char *Sys_ConsoleInput (void) { - static qboolean con_eof = false; + static bool con_eof = false; static char con_text[256]; static int textlen; char c; diff --git a/Quake/sys_sdl_win.cpp b/Quake/sys_sdl_win.cpp index 2f6f736..584ce15 100644 --- a/Quake/sys_sdl_win.cpp +++ b/Quake/sys_sdl_win.cpp @@ -45,8 +45,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif -qboolean isDedicated; -qboolean Win95, Win95old, WinNT, WinVista; +bool isDedicated; +bool Win95, Win95old, WinNT, WinVista; cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; static HANDLE hinput, houtput; diff --git a/Quake/vid.hpp b/Quake/vid.hpp index 46ae8d6..cdcbadd 100644 --- a/Quake/vid.hpp +++ b/Quake/vid.hpp @@ -85,8 +85,8 @@ void VID_SyncCvars (void); void VID_Toggle (void); void *VID_GetWindow (void); -qboolean VID_HasMouseOrInputFocus (void); -qboolean VID_IsMinimized (void); +bool VID_HasMouseOrInputFocus (void); +bool VID_IsMinimized (void); void VID_Lock (void); #endif /* __VID_DEFS_H */ diff --git a/Quake/view.cpp b/Quake/view.cpp index 7e83a8b..6e35580 100644 --- a/Quake/view.cpp +++ b/Quake/view.cpp @@ -451,7 +451,7 @@ V_UpdateBlend -- johnfitz -- V_UpdatePalette cleaned up and renamed */ void V_UpdateBlend(void) { int i, j; - qboolean blend_changed; + bool blend_changed; V_CalcPowerupCshift(); diff --git a/Quake/world.cpp b/Quake/world.cpp index 8516a67..ebb542f 100644 --- a/Quake/world.cpp +++ b/Quake/world.cpp @@ -429,7 +429,7 @@ SV_LinkEdict =============== */ -void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) +void SV_LinkEdict (edict_t *ent, bool touch_triggers) { areanode_t *node; @@ -603,7 +603,7 @@ SV_RecursiveHullCheck ================== */ -qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) +bool SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) { mclipnode_t *node; //johnfitz -- was dclipnode_t mplane_t *plane; diff --git a/Quake/world.hpp b/Quake/world.hpp index fed90b0..eb36e5d 100644 --- a/Quake/world.hpp +++ b/Quake/world.hpp @@ -31,9 +31,9 @@ typedef struct typedef struct { - qboolean allsolid; // if true, plane is not valid - qboolean startsolid; // if true, the initial point was in a solid area - qboolean inopen, inwater; + bool allsolid; // if true, plane is not valid + bool startsolid; // if true, the initial point was in a solid area + bool inopen, inwater; float fraction; // time completed, 1.0 = didn't hit anything vec3_t endpos; // final position plane_t plane; // surface normal at impact @@ -54,7 +54,7 @@ void SV_UnlinkEdict (edict_t *ent); // so it doesn't clip against itself // flags ent->v.modified -void SV_LinkEdict (edict_t *ent, qboolean touch_triggers); +void SV_LinkEdict (edict_t *ent, bool touch_triggers); // Needs to be called any time an entity changes origin, mins, maxs, or solid // flags ent->v.modified // sets ent->v.absmin and ent->v.absmax @@ -81,7 +81,7 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, e // passedict is explicitly excluded from clipping checks (normally NULL) -qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace); +bool SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace); #endif /* _QUAKE_WORLD_H */ diff --git a/Quake/zone.cpp b/Quake/zone.cpp index 66d16b1..ccad5b9 100644 --- a/Quake/zone.cpp +++ b/Quake/zone.cpp @@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // zone.c +#include + #include "quakedef.hpp" #define DYNAMIC_SIZE (4 * 1024 * 1024) // ericw -- was 512KB (64-bit) / 384KB (32-bit) @@ -203,7 +205,7 @@ void *Z_Malloc (int size) buf = Z_TagMalloc (size, 1); if (!buf) Sys_Error ("Z_Malloc: failed on allocation of %i bytes",size); - Q_memset (buf, 0, size); + std::memset (buf, 0, size); return buf; } @@ -300,7 +302,7 @@ int hunk_size; int hunk_low_used; int hunk_high_used; -qboolean hunk_tempactive; +bool hunk_tempactive; int hunk_tempmark; /* @@ -332,7 +334,7 @@ If "all" is specified, every single allocation is printed. Otherwise, allocations with the same name will be totaled up before printing. ============== */ -void Hunk_Print (qboolean all) +void Hunk_Print (bool all) { hunk_t *h, *next, *endlow, *starthigh, *endhigh; int count, sum; @@ -601,7 +603,7 @@ typedef struct cache_system_s struct cache_system_s *lru_prev, *lru_next; // for LRU flushing } cache_system_t; -cache_system_t *Cache_TryAlloc (int size, qboolean nobottom); +cache_system_t *Cache_TryAlloc (int size, bool nobottom); cache_system_t cache_head; @@ -620,9 +622,9 @@ void Cache_Move ( cache_system_t *c) { // Con_Printf ("cache_move ok\n"); - Q_memcpy ( new_cs+1, c+1, c->size - sizeof(cache_system_t) ); + std::memcpy ( new_cs+1, c+1, c->size - sizeof(cache_system_t) ); new_cs->user = c->user; - Q_memcpy (new_cs->name, c->name, sizeof(new_cs->name)); + std::memcpy (new_cs->name, c->name, sizeof(new_cs->name)); Cache_Free (c->user, false); //johnfitz -- added second argument new_cs->user->data = (void *)(new_cs+1); } @@ -715,7 +717,7 @@ Looks for a free block of memory between the high and low hunk marks Size should already include the header and padding ============ */ -cache_system_t *Cache_TryAlloc (int size, qboolean nobottom) +cache_system_t *Cache_TryAlloc (int size, bool nobottom) { cache_system_t *cs, *new_cs; @@ -848,7 +850,7 @@ Cache_Free Frees the memory and removes it from the LRU list ============== */ -void Cache_Free (cache_user_t *c, qboolean freetextures) //johnfitz -- added second argument +void Cache_Free (cache_user_t *c, bool freetextures) //johnfitz -- added second argument { cache_system_t *cs; @@ -964,7 +966,6 @@ Memory_Init */ void Memory_Init (void *buf, int size) { - int p; int zonesize = DYNAMIC_SIZE; hunk_base = (byte *) buf; @@ -973,11 +974,11 @@ void Memory_Init (void *buf, int size) hunk_high_used = 0; Cache_Init (); - p = COM_CheckParm ("-zone"); - if (p) + auto p = common::check_param ("-zone"); + if (p.has_value()) { if (p < com_argc-1) - zonesize = Q_atoi (com_argv[p+1]) * 1024; + zonesize = std::atoi (com_argv[p.value()+1]) * 1024; else Sys_Error ("Memory_Init: you must specify a size in KB after -zone"); } diff --git a/Quake/zone.hpp b/Quake/zone.hpp index 74da9c7..3ff1e2d 100644 --- a/Quake/zone.hpp +++ b/Quake/zone.hpp @@ -128,7 +128,7 @@ void *Cache_Check (cache_user_t *c); // returns the cached data, and moves to the head of the LRU list // if present, otherwise returns NULL -void Cache_Free (cache_user_t *c, qboolean freetextures); //johnfitz -- added second argument +void Cache_Free (cache_user_t *c, bool freetextures); //johnfitz -- added second argument void *Cache_Alloc (cache_user_t *c, int size, const char *name); // Returns NULL if all purgable data was tossed and there still