cyberdeck-quake3/code/game/g_main.c
orca d0cedd4f79 Halloween: bones instead of gibs, headless skeletons and a real flying skull
Forced gibs showed regular meat, and the dying player saw their own
skeleton standing (their STAT_HEALTH stayed above gib level). Now nothing
gibs on Halloween: a normal death leaves the costumed skeleton lying
there, with STAT_HEALTH synced. A headshot hides the body and drops a
headless skeleton (Bones lower/upper md3s at the dead1 frame, torso on
tag_torso) while the Bones skull launches, spins and bounces. The md3s
get the "stiff" texture baked in, since entities can't use skins; they
ship in the mod pk3. Verified with an offscreen ioquake3 client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UF9yeTnP76ZWW6ojJ8uJge
2026-10-19 19:14:10 -04:00

2859 lines
83 KiB
C

/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#include "g_local.h"
level_locals_t level;
typedef struct {
vmCvar_t *vmCvar;
char *cvarName;
char *defaultString;
int cvarFlags;
int modificationCount; // for tracking changes
qboolean trackChange; // track this variable, and announce if changed
qboolean teamShader; // track and if changed, update shader state
} cvarTable_t;
gentity_t g_entities[MAX_GENTITIES];
gclient_t g_clients[MAX_CLIENTS];
vmCvar_t g_gametype;
vmCvar_t g_dmflags;
vmCvar_t g_fraglimit;
vmCvar_t g_timelimit;
vmCvar_t g_capturelimit;
vmCvar_t g_friendlyFire;
vmCvar_t g_password;
vmCvar_t g_needpass;
vmCvar_t g_maxclients;
vmCvar_t g_maxGameClients;
vmCvar_t g_dedicated;
vmCvar_t g_speed;
vmCvar_t g_gravity;
vmCvar_t g_cheats;
vmCvar_t g_knockback;
vmCvar_t g_quadfactor;
vmCvar_t g_instagib;
vmCvar_t g_mutators;
vmCvar_t g_botskillmix;
vmCvar_t g_mutatorforce;
vmCvar_t g_botrotate;
vmCvar_t g_weaponmodes;
vmCvar_t g_weaponforce;
vmCvar_t g_mapshuffle;
vmCvar_t g_forcerespawn;
vmCvar_t g_inactivity;
vmCvar_t g_debugMove;
vmCvar_t g_debugDamage;
vmCvar_t g_debugAlloc;
vmCvar_t g_weaponRespawn;
vmCvar_t g_weaponTeamRespawn;
vmCvar_t g_motd;
vmCvar_t g_synchronousClients;
vmCvar_t g_warmup;
vmCvar_t g_doWarmup;
vmCvar_t g_restarted;
vmCvar_t g_logfile;
vmCvar_t g_logfileSync;
vmCvar_t g_blood;
vmCvar_t g_podiumDist;
vmCvar_t g_podiumDrop;
vmCvar_t g_allowVote;
vmCvar_t g_teamAutoJoin;
vmCvar_t g_teamForceBalance;
vmCvar_t g_banIPs;
vmCvar_t g_filterBan;
vmCvar_t g_smoothClients;
vmCvar_t pmove_fixed;
vmCvar_t pmove_msec;
vmCvar_t g_rankings;
vmCvar_t g_listEntity;
vmCvar_t g_localTeamPref;
#ifdef MISSIONPACK
vmCvar_t g_obeliskHealth;
vmCvar_t g_obeliskRegenPeriod;
vmCvar_t g_obeliskRegenAmount;
vmCvar_t g_obeliskRespawnDelay;
vmCvar_t g_cubeTimeout;
vmCvar_t g_redteam;
vmCvar_t g_blueteam;
vmCvar_t g_singlePlayer;
vmCvar_t g_enableDust;
vmCvar_t g_enableBreath;
vmCvar_t g_proxMineTimeout;
#endif
static cvarTable_t gameCvarTable[] = {
// don't override the cheat state set by the system
{ &g_cheats, "sv_cheats", "", 0, 0, qfalse },
// noset vars
{ NULL, "gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
{ NULL, "gamedate", PRODUCT_DATE , CVAR_ROM, 0, qfalse },
{ &g_restarted, "g_restarted", "0", CVAR_ROM, 0, qfalse },
// latched vars
{ &g_gametype, "g_gametype", "0", CVAR_SERVERINFO | CVAR_USERINFO | CVAR_LATCH, 0, qfalse },
{ &g_maxclients, "sv_maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
{ &g_maxGameClients, "g_maxGameClients", "0", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
// change anytime vars
{ &g_dmflags, "dmflags", "0", CVAR_SERVERINFO | CVAR_ARCHIVE, 0, qtrue },
{ &g_fraglimit, "fraglimit", "20", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
{ &g_timelimit, "timelimit", "0", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
{ &g_capturelimit, "capturelimit", "8", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
{ &g_synchronousClients, "g_synchronousClients", "0", CVAR_SYSTEMINFO, 0, qfalse },
{ &g_friendlyFire, "g_friendlyFire", "0", CVAR_ARCHIVE, 0, qtrue },
{ &g_teamAutoJoin, "g_teamAutoJoin", "0", CVAR_ARCHIVE },
{ &g_teamForceBalance, "g_teamForceBalance", "0", CVAR_ARCHIVE },
{ &g_warmup, "g_warmup", "20", CVAR_ARCHIVE, 0, qtrue },
{ &g_doWarmup, "g_doWarmup", "0", CVAR_ARCHIVE, 0, qtrue },
{ &g_logfile, "g_log", "games.log", CVAR_ARCHIVE, 0, qfalse },
{ &g_logfileSync, "g_logsync", "0", CVAR_ARCHIVE, 0, qfalse },
{ &g_password, "g_password", "", CVAR_USERINFO, 0, qfalse },
{ &g_banIPs, "g_banIPs", "", CVAR_ARCHIVE, 0, qfalse },
{ &g_filterBan, "g_filterBan", "1", CVAR_ARCHIVE, 0, qfalse },
{ &g_needpass, "g_needpass", "0", CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
{ &g_dedicated, "dedicated", "0", 0, 0, qfalse },
{ &g_speed, "g_speed", "320", 0, 0, qtrue },
{ &g_gravity, "g_gravity", "800", 0, 0, qtrue },
{ &g_knockback, "g_knockback", "1000", 0, 0, qtrue },
{ &g_quadfactor, "g_quadfactor", "3", 0, 0, qtrue },
// cyberdeck: railgun-only, one-hit kills, no items on the map
{ &g_instagib, "g_instagib", "0", CVAR_SERVERINFO | CVAR_LATCH, 0, qtrue },
// cyberdeck: random mutator per match, per-bot fixed skills, and info for the status query
{ &g_mutators, "g_mutators", "0", 0, 0, qfalse },
{ &g_botskillmix, "g_botskillmix", "0", 0, 0, qfalse },
{ &g_mutatorforce, "g_mutatorforce", "0", 0, 0, qfalse }, // 1-4 picks a mutator instead of random
{ &g_botrotate, "g_botrotate", "0", 0, 0, qfalse }, // fresh random bots on every new map
{ &g_weaponmodes, "g_weaponmodes", "0", 0, 0, qfalse }, // instagib arena: roll a weapon mode per match
{ &g_weaponforce, "g_weaponforce", "0", 0, 0, qfalse }, // 1-6 picks a weapon mode instead of random
{ &g_mapshuffle, "g_mapshuffle", "", 0, 0, qfalse }, // "ig1 ig2 ...": vstr names to play in shuffled order
{ NULL, "g_weaponmode", "", CVAR_SERVERINFO, 0, qfalse },
{ NULL, "g_mutator", "", CVAR_SERVERINFO, 0, qfalse },
{ NULL, "cd_jugg", "", CVAR_SERVERINFO, 0, qfalse },
{ NULL, "cd_teams", "", CVAR_SERVERINFO, 0, qfalse },
{ NULL, "Score_Red", "", CVAR_SERVERINFO, 0, qfalse },
{ NULL, "Score_Blue", "", CVAR_SERVERINFO, 0, qfalse },
{ &g_weaponRespawn, "g_weaponrespawn", "5", 0, 0, qtrue },
{ &g_weaponTeamRespawn, "g_weaponTeamRespawn", "30", 0, 0, qtrue },
{ &g_forcerespawn, "g_forcerespawn", "20", 0, 0, qtrue },
{ &g_inactivity, "g_inactivity", "0", 0, 0, qtrue },
{ &g_debugMove, "g_debugMove", "0", 0, 0, qfalse },
{ &g_debugDamage, "g_debugDamage", "0", 0, 0, qfalse },
{ &g_debugAlloc, "g_debugAlloc", "0", 0, 0, qfalse },
{ &g_motd, "g_motd", "", 0, 0, qfalse },
{ &g_blood, "com_blood", "1", 0, 0, qfalse },
{ &g_podiumDist, "g_podiumDist", "80", 0, 0, qfalse },
{ &g_podiumDrop, "g_podiumDrop", "70", 0, 0, qfalse },
{ &g_allowVote, "g_allowVote", "1", CVAR_ARCHIVE, 0, qfalse },
{ &g_listEntity, "g_listEntity", "0", 0, 0, qfalse },
#ifdef MISSIONPACK
{ &g_obeliskHealth, "g_obeliskHealth", "2500", 0, 0, qfalse },
{ &g_obeliskRegenPeriod, "g_obeliskRegenPeriod", "1", 0, 0, qfalse },
{ &g_obeliskRegenAmount, "g_obeliskRegenAmount", "15", 0, 0, qfalse },
{ &g_obeliskRespawnDelay, "g_obeliskRespawnDelay", "10", CVAR_SERVERINFO, 0, qfalse },
{ &g_cubeTimeout, "g_cubeTimeout", "30", 0, 0, qfalse },
{ &g_redteam, "g_redteam", "Stroggs", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO , 0, qtrue, qtrue },
{ &g_blueteam, "g_blueteam", "Pagans", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO , 0, qtrue, qtrue },
{ &g_singlePlayer, "ui_singlePlayerActive", "", 0, 0, qfalse, qfalse },
{ &g_enableDust, "g_enableDust", "0", CVAR_SERVERINFO, 0, qtrue, qfalse },
{ &g_enableBreath, "g_enableBreath", "0", CVAR_SERVERINFO, 0, qtrue, qfalse },
{ &g_proxMineTimeout, "g_proxMineTimeout", "20000", 0, 0, qfalse },
#endif
{ &g_smoothClients, "g_smoothClients", "1", 0, 0, qfalse},
{ &pmove_fixed, "pmove_fixed", "0", CVAR_SYSTEMINFO, 0, qfalse},
{ &pmove_msec, "pmove_msec", "8", CVAR_SYSTEMINFO, 0, qfalse},
{ &g_rankings, "g_rankings", "0", 0, 0, qfalse},
{ &g_localTeamPref, "g_localTeamPref", "", 0, 0, qfalse }
};
static int gameCvarTableSize = ARRAY_LEN( gameCvarTable );
void G_InitGame( int levelTime, int randomSeed, int restart );
void G_RunFrame( int levelTime );
void G_ShutdownGame( int restart );
void CheckExitRules( void );
/*
================
vmMain
This is the only way control passes into the module.
This must be the very first function compiled into the .q3vm file
================
*/
Q_EXPORT intptr_t vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) {
switch ( command ) {
case GAME_INIT:
G_InitGame( arg0, arg1, arg2 );
return 0;
case GAME_SHUTDOWN:
G_ShutdownGame( arg0 );
return 0;
case GAME_CLIENT_CONNECT:
return (intptr_t)ClientConnect( arg0, arg1, arg2 );
case GAME_CLIENT_THINK:
ClientThink( arg0 );
return 0;
case GAME_CLIENT_USERINFO_CHANGED:
ClientUserinfoChanged( arg0 );
return 0;
case GAME_CLIENT_DISCONNECT:
ClientDisconnect( arg0 );
return 0;
case GAME_CLIENT_BEGIN:
ClientBegin( arg0 );
return 0;
case GAME_CLIENT_COMMAND:
ClientCommand( arg0 );
return 0;
case GAME_RUN_FRAME:
G_RunFrame( arg0 );
return 0;
case GAME_CONSOLE_COMMAND:
return ConsoleCommand();
case BOTAI_START_FRAME:
return BotAIStartFrame( arg0 );
}
return -1;
}
void QDECL G_Printf( const char *fmt, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, fmt);
Q_vsnprintf (text, sizeof(text), fmt, argptr);
va_end (argptr);
trap_Print( text );
}
void QDECL G_Error( const char *fmt, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, fmt);
Q_vsnprintf (text, sizeof(text), fmt, argptr);
va_end (argptr);
trap_Error( text );
}
/*
================
G_FindTeams
Chain together all entities with a matching team field.
Entity teams are used for item groups and multi-entity mover groups.
All but the first will have the FL_TEAMMEMBER flag set and teammaster field set
All but the last will have the teamchain field set to the next one
================
*/
void G_FindTeams( void ) {
gentity_t *e, *e2;
int i, j;
int c, c2;
c = 0;
c2 = 0;
for ( i=MAX_CLIENTS, e=g_entities+i ; i < level.num_entities ; i++,e++ ) {
if (!e->inuse)
continue;
if (!e->team)
continue;
if (e->flags & FL_TEAMMEMBER)
continue;
e->teammaster = e;
c++;
c2++;
for (j=i+1, e2=e+1 ; j < level.num_entities ; j++,e2++)
{
if (!e2->inuse)
continue;
if (!e2->team)
continue;
if (e2->flags & FL_TEAMMEMBER)
continue;
if (!strcmp(e->team, e2->team))
{
c2++;
e2->teamchain = e->teamchain;
e->teamchain = e2;
e2->teammaster = e;
e2->flags |= FL_TEAMMEMBER;
// make sure that targets only point at the master
if ( e2->targetname ) {
e->targetname = e2->targetname;
e2->targetname = NULL;
}
}
}
}
G_Printf ("%i teams with %i entities\n", c, c2);
}
void G_RemapTeamShaders( void ) {
#ifdef MISSIONPACK
char string[1024];
float f = level.time * 0.001;
Com_sprintf( string, sizeof(string), "team_icon/%s_red", g_redteam.string );
AddRemap("textures/ctf2/redteam01", string, f);
AddRemap("textures/ctf2/redteam02", string, f);
Com_sprintf( string, sizeof(string), "team_icon/%s_blue", g_blueteam.string );
AddRemap("textures/ctf2/blueteam01", string, f);
AddRemap("textures/ctf2/blueteam02", string, f);
trap_SetConfigstring(CS_SHADERSTATE, BuildShaderStateConfig());
#endif
}
/*
=================
G_RegisterCvars
=================
*/
void G_RegisterCvars( void ) {
int i;
cvarTable_t *cv;
qboolean remapped = qfalse;
for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
trap_Cvar_Register( cv->vmCvar, cv->cvarName,
cv->defaultString, cv->cvarFlags );
if ( cv->vmCvar )
cv->modificationCount = cv->vmCvar->modificationCount;
if (cv->teamShader) {
remapped = qtrue;
}
}
if (remapped) {
G_RemapTeamShaders();
}
// check some things
if ( g_gametype.integer < 0 || g_gametype.integer >= GT_MAX_GAME_TYPE ) {
G_Printf( "g_gametype %i is out of range, defaulting to 0\n", g_gametype.integer );
trap_Cvar_Set( "g_gametype", "0" );
trap_Cvar_Update( &g_gametype );
}
level.warmupModificationCount = g_warmup.modificationCount;
}
/*
=================
G_UpdateCvars
=================
*/
void G_UpdateCvars( void ) {
int i;
cvarTable_t *cv;
qboolean remapped = qfalse;
for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
if ( cv->vmCvar ) {
trap_Cvar_Update( cv->vmCvar );
if ( cv->modificationCount != cv->vmCvar->modificationCount ) {
cv->modificationCount = cv->vmCvar->modificationCount;
if ( cv->trackChange ) {
trap_SendServerCommand( -1, va("print \"Server: %s changed to %s\n\"",
cv->cvarName, cv->vmCvar->string ) );
}
if (cv->teamShader) {
remapped = qtrue;
}
}
}
}
if (remapped) {
G_RemapTeamShaders();
}
}
/*
============
G_InitGame
============
*/
void G_InitGame( int levelTime, int randomSeed, int restart ) {
int i;
G_Printf ("------- Game Initialization -------\n");
G_Printf ("gamename: %s\n", GAMEVERSION);
G_Printf ("gamedate: %s\n", PRODUCT_DATE);
srand( randomSeed );
G_RegisterCvars();
G_ProcessIPBans();
G_InitMemory();
// set some level globals
memset( &level, 0, sizeof( level ) );
level.cd_juggernaut = -1; // cyberdeck: nobody until someone leads
level.time = levelTime;
level.startTime = levelTime;
level.snd_fry = G_SoundIndex("sound/player/fry.wav"); // FIXME standing in lava / slime
if ( g_gametype.integer != GT_SINGLE_PLAYER && g_logfile.string[0] ) {
if ( g_logfileSync.integer ) {
trap_FS_FOpenFile( g_logfile.string, &level.logFile, FS_APPEND_SYNC );
} else {
trap_FS_FOpenFile( g_logfile.string, &level.logFile, FS_APPEND );
}
if ( !level.logFile ) {
G_Printf( "WARNING: Couldn't open logfile: %s\n", g_logfile.string );
} else {
char serverinfo[MAX_INFO_STRING];
trap_GetServerinfo( serverinfo, sizeof( serverinfo ) );
G_LogPrintf("------------------------------------------------------------\n" );
G_LogPrintf("InitGame: %s\n", serverinfo );
}
} else {
G_Printf( "Not logging to disk.\n" );
}
G_InitWorldSession();
// initialize all entities for this game
memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) );
level.gentities = g_entities;
// initialize all clients for this game
level.maxclients = g_maxclients.integer;
memset( g_clients, 0, MAX_CLIENTS * sizeof(g_clients[0]) );
level.clients = g_clients;
// set client fields on player ents
for ( i=0 ; i<level.maxclients ; i++ ) {
g_entities[i].client = level.clients + i;
}
// always leave room for the max number of clients,
// even if they aren't all used, so numbers inside that
// range are NEVER anything but clients
level.num_entities = MAX_CLIENTS;
for ( i=0 ; i<MAX_CLIENTS ; i++ ) {
g_entities[i].classname = "clientslot";
}
// let the server system know where the entites are
trap_LocateGameData( level.gentities, level.num_entities, sizeof( gentity_t ),
&level.clients[0].ps, sizeof( level.clients[0] ) );
// reserve some spots for dead player bodies
InitBodyQue();
ClearRegisteredItems();
// parse the key/value pairs and spawn gentities
G_SpawnEntitiesFromString();
// general initialization
G_FindTeams();
// make sure we have flags for CTF, etc
if( g_gametype.integer >= GT_TEAM ) {
G_CheckTeamItems();
}
SaveRegisteredItems();
G_Printf ("-----------------------------------\n");
if( g_gametype.integer == GT_SINGLE_PLAYER || trap_Cvar_VariableIntegerValue( "com_buildScript" ) ) {
G_ModelIndex( SP_PODIUM_MODEL );
}
if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
BotAISetup( restart );
BotAILoadMap( restart );
G_InitBots( restart );
}
G_RemapTeamShaders();
CD_InitMutator( restart, randomSeed );
trap_SetConfigstring( CS_INTERMISSION, "" );
}
/*
=================
G_ShutdownGame
=================
*/
void G_ShutdownGame( int restart ) {
G_Printf ("==== ShutdownGame ====\n");
if ( level.logFile ) {
G_LogPrintf("ShutdownGame:\n" );
G_LogPrintf("------------------------------------------------------------\n" );
trap_FS_FCloseFile( level.logFile );
level.logFile = 0;
}
// write all the client session data so we can get it back
G_WriteSessionData();
if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
BotAIShutdown( restart );
}
}
//===================================================================
void QDECL Com_Error ( int logLevel, const char *error, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, error);
Q_vsnprintf (text, sizeof(text), error, argptr);
va_end (argptr);
trap_Error( text );
}
void QDECL Com_Printf( const char *msg, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, msg);
Q_vsnprintf (text, sizeof(text), msg, argptr);
va_end (argptr);
trap_Print( text );
}
/*
========================================================================
PLAYER COUNTING / SCORE SORTING
========================================================================
*/
/*
=============
AddTournamentPlayer
If there are less than two tournament players, put a
spectator in the game and restart
=============
*/
void AddTournamentPlayer( void ) {
int i;
gclient_t *client;
gclient_t *nextInLine;
if ( level.numPlayingClients >= 2 ) {
return;
}
// never change during intermission
if ( level.intermissiontime ) {
return;
}
nextInLine = NULL;
for ( i = 0 ; i < level.maxclients ; i++ ) {
client = &level.clients[i];
if ( client->pers.connected != CON_CONNECTED ) {
continue;
}
if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
continue;
}
// never select the dedicated follow or scoreboard clients
if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ||
client->sess.spectatorClient < 0 ) {
continue;
}
if(!nextInLine || client->sess.spectatorNum > nextInLine->sess.spectatorNum)
nextInLine = client;
}
if ( !nextInLine ) {
return;
}
level.warmupTime = -1;
// set them to free-for-all team
SetTeam( &g_entities[ nextInLine - level.clients ], "f" );
}
/*
=======================
AddTournamentQueue
Add client to end of tournament queue
=======================
*/
void AddTournamentQueue(gclient_t *client)
{
int index;
gclient_t *curclient;
for(index = 0; index < level.maxclients; index++)
{
curclient = &level.clients[index];
if(curclient->pers.connected != CON_DISCONNECTED)
{
if(curclient == client)
curclient->sess.spectatorNum = 0;
else if(curclient->sess.sessionTeam == TEAM_SPECTATOR)
curclient->sess.spectatorNum++;
}
}
}
/*
=======================
RemoveTournamentLoser
Make the loser a spectator at the back of the line
=======================
*/
void RemoveTournamentLoser( void ) {
int clientNum;
if ( level.numPlayingClients != 2 ) {
return;
}
clientNum = level.sortedClients[1];
if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) {
return;
}
// make them a spectator
SetTeam( &g_entities[ clientNum ], "s" );
}
/*
=======================
RemoveTournamentWinner
=======================
*/
void RemoveTournamentWinner( void ) {
int clientNum;
if ( level.numPlayingClients != 2 ) {
return;
}
clientNum = level.sortedClients[0];
if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) {
return;
}
// make them a spectator
SetTeam( &g_entities[ clientNum ], "s" );
}
/*
=======================
AdjustTournamentScores
=======================
*/
void AdjustTournamentScores( void ) {
int clientNum;
clientNum = level.sortedClients[0];
if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
level.clients[ clientNum ].sess.wins++;
ClientUserinfoChanged( clientNum );
}
clientNum = level.sortedClients[1];
if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
level.clients[ clientNum ].sess.losses++;
ClientUserinfoChanged( clientNum );
}
}
/*
=============
SortRanks
=============
*/
int QDECL SortRanks( const void *a, const void *b ) {
gclient_t *ca, *cb;
ca = &level.clients[*(int *)a];
cb = &level.clients[*(int *)b];
// sort special clients last
if ( ca->sess.spectatorState == SPECTATOR_SCOREBOARD || ca->sess.spectatorClient < 0 ) {
return 1;
}
if ( cb->sess.spectatorState == SPECTATOR_SCOREBOARD || cb->sess.spectatorClient < 0 ) {
return -1;
}
// then connecting clients
if ( ca->pers.connected == CON_CONNECTING ) {
return 1;
}
if ( cb->pers.connected == CON_CONNECTING ) {
return -1;
}
// then spectators
if ( ca->sess.sessionTeam == TEAM_SPECTATOR && cb->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( ca->sess.spectatorNum > cb->sess.spectatorNum ) {
return -1;
}
if ( ca->sess.spectatorNum < cb->sess.spectatorNum ) {
return 1;
}
return 0;
}
if ( ca->sess.sessionTeam == TEAM_SPECTATOR ) {
return 1;
}
if ( cb->sess.sessionTeam == TEAM_SPECTATOR ) {
return -1;
}
// then sort by score
if ( ca->ps.persistant[PERS_SCORE]
> cb->ps.persistant[PERS_SCORE] ) {
return -1;
}
if ( ca->ps.persistant[PERS_SCORE]
< cb->ps.persistant[PERS_SCORE] ) {
return 1;
}
return 0;
}
/*
============
CalculateRanks
Recalculates the score ranks of all players
This will be called on every client connect, begin, disconnect, death,
and team change.
============
*/
void CalculateRanks( void ) {
int i;
int rank;
int score;
int newScore;
gclient_t *cl;
level.follow1 = -1;
level.follow2 = -1;
level.numConnectedClients = 0;
level.numNonSpectatorClients = 0;
level.numPlayingClients = 0;
level.numVotingClients = 0; // don't count bots
for (i = 0; i < ARRAY_LEN(level.numteamVotingClients); i++)
level.numteamVotingClients[i] = 0;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( level.clients[i].pers.connected != CON_DISCONNECTED ) {
level.sortedClients[level.numConnectedClients] = i;
level.numConnectedClients++;
if ( level.clients[i].sess.sessionTeam != TEAM_SPECTATOR ) {
level.numNonSpectatorClients++;
// decide if this should be auto-followed
if ( level.clients[i].pers.connected == CON_CONNECTED ) {
level.numPlayingClients++;
if ( !(g_entities[i].r.svFlags & SVF_BOT) ) {
level.numVotingClients++;
if ( level.clients[i].sess.sessionTeam == TEAM_RED )
level.numteamVotingClients[0]++;
else if ( level.clients[i].sess.sessionTeam == TEAM_BLUE )
level.numteamVotingClients[1]++;
}
if ( level.follow1 == -1 ) {
level.follow1 = i;
} else if ( level.follow2 == -1 ) {
level.follow2 = i;
}
}
}
}
}
qsort( level.sortedClients, level.numConnectedClients,
sizeof(level.sortedClients[0]), SortRanks );
// set the rank value for all clients that are connected and not spectators
if ( g_gametype.integer >= GT_TEAM ) {
// in team games, rank is just the order of the teams, 0=red, 1=blue, 2=tied
for ( i = 0; i < level.numConnectedClients; i++ ) {
cl = &level.clients[ level.sortedClients[i] ];
if ( level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE] ) {
cl->ps.persistant[PERS_RANK] = 2;
} else if ( level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE] ) {
cl->ps.persistant[PERS_RANK] = 0;
} else {
cl->ps.persistant[PERS_RANK] = 1;
}
}
} else {
rank = -1;
score = 0;
for ( i = 0; i < level.numPlayingClients; i++ ) {
cl = &level.clients[ level.sortedClients[i] ];
newScore = cl->ps.persistant[PERS_SCORE];
if ( i == 0 || newScore != score ) {
rank = i;
// assume we aren't tied until the next client is checked
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank;
} else {
// we are tied with the previous client
level.clients[ level.sortedClients[i-1] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
}
score = newScore;
if ( g_gametype.integer == GT_SINGLE_PLAYER && level.numPlayingClients == 1 ) {
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
}
}
}
// set the CS_SCORES1/2 configstrings, which will be visible to everyone
if ( g_gametype.integer >= GT_TEAM ) {
trap_SetConfigstring( CS_SCORES1, va("%i", level.teamScores[TEAM_RED] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", level.teamScores[TEAM_BLUE] ) );
} else {
if ( level.numConnectedClients == 0 ) {
trap_SetConfigstring( CS_SCORES1, va("%i", SCORE_NOT_PRESENT) );
trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
} else if ( level.numConnectedClients == 1 ) {
trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
} else {
trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE] ) );
}
}
CD_UpdateRanks();
// see if it is time to end the level
CheckExitRules();
// if we are at the intermission, send the new info to everyone
if ( level.intermissiontime ) {
SendScoreboardMessageToAllClients();
}
}
/*
========================================================================
MAP CHANGING
========================================================================
*/
/*
========================
SendScoreboardMessageToAllClients
Do this at BeginIntermission time and whenever ranks are recalculated
due to enters/exits/forced team changes
========================
*/
void SendScoreboardMessageToAllClients( void ) {
int i;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( level.clients[ i ].pers.connected == CON_CONNECTED ) {
DeathmatchScoreboardMessage( g_entities + i );
}
}
}
/*
========================
MoveClientToIntermission
When the intermission starts, this will be called for all players.
If a new client connects, this will be called after the spawn function.
========================
*/
void MoveClientToIntermission( gentity_t *ent ) {
// take out of follow mode if needed
if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
StopFollowing( ent );
}
FindIntermissionPoint();
// move to the spot
VectorCopy( level.intermission_origin, ent->s.origin );
VectorCopy( level.intermission_origin, ent->client->ps.origin );
VectorCopy (level.intermission_angle, ent->client->ps.viewangles);
ent->client->ps.pm_type = PM_INTERMISSION;
// clean up powerup info
memset( ent->client->ps.powerups, 0, sizeof(ent->client->ps.powerups) );
ent->client->ps.eFlags = 0;
ent->s.eFlags = 0;
ent->s.eType = ET_GENERAL;
ent->s.modelindex = 0;
ent->s.loopSound = 0;
ent->s.event = 0;
ent->r.contents = 0;
}
/*
==================
FindIntermissionPoint
This is also used for spectator spawns
==================
*/
void FindIntermissionPoint( void ) {
gentity_t *ent, *target;
vec3_t dir;
// find the intermission spot
ent = G_Find (NULL, FOFS(classname), "info_player_intermission");
if ( !ent ) { // the map creator forgot to put in an intermission point...
SelectSpawnPoint ( vec3_origin, level.intermission_origin, level.intermission_angle, qfalse );
} else {
VectorCopy (ent->s.origin, level.intermission_origin);
VectorCopy (ent->s.angles, level.intermission_angle);
// if it has a target, look towards it
if ( ent->target ) {
target = G_PickTarget( ent->target );
if ( target ) {
VectorSubtract( target->s.origin, level.intermission_origin, dir );
vectoangles( dir, level.intermission_angle );
}
}
}
}
/*
==================
BeginIntermission
==================
*/
void BeginIntermission( void ) {
int i;
gentity_t *client;
if ( level.intermissiontime ) {
return; // already active
}
// if in tournement mode, change the wins / losses
if ( g_gametype.integer == GT_TOURNAMENT ) {
AdjustTournamentScores();
}
level.intermissiontime = level.time;
CD_Victory();
// move all clients to the intermission point
for (i=0 ; i< level.maxclients ; i++) {
client = g_entities + i;
if (!client->inuse)
continue;
// respawn if dead
if (client->health <= 0) {
ClientRespawn(client);
}
MoveClientToIntermission( client );
}
#ifdef MISSIONPACK
if (g_singlePlayer.integer) {
trap_Cvar_Set("ui_singlePlayerActive", "0");
UpdateTournamentInfo();
}
#else
// if single player game
if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
UpdateTournamentInfo();
SpawnModelsOnVictoryPads();
}
#endif
// send the current scoring to all clients
SendScoreboardMessageToAllClients();
}
/*
=============
ExitLevel
When the intermission has been exited, the server is either killed
or moved to a new level based on the "nextmap" cvar
=============
*/
void ExitLevel (void) {
int i;
gclient_t *cl;
char nextmap[MAX_STRING_CHARS];
char d1[MAX_STRING_CHARS];
//bot interbreeding
BotInterbreedEndMatch();
// if we are running a tournement map, kick the loser to spectator status,
// which will automatically grab the next spectator and restart
if ( g_gametype.integer == GT_TOURNAMENT ) {
if ( !level.restarted ) {
RemoveTournamentLoser();
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
level.changemap = NULL;
level.intermissiontime = 0;
}
return;
}
trap_Cvar_VariableStringBuffer( "nextmap", nextmap, sizeof(nextmap) );
trap_Cvar_VariableStringBuffer( "d1", d1, sizeof(d1) );
if( !Q_stricmp( nextmap, "map_restart 0" ) && Q_stricmp( d1, "" ) ) {
trap_Cvar_Set( "nextmap", "vstr d2" );
trap_SendConsoleCommand( EXEC_APPEND, "vstr d1\n" );
} else {
trap_SendConsoleCommand( EXEC_APPEND, "vstr nextmap\n" );
}
level.changemap = NULL;
level.intermissiontime = 0;
// reset all the scores so we don't enter the intermission again
level.teamScores[TEAM_RED] = 0;
level.teamScores[TEAM_BLUE] = 0;
for ( i=0 ; i< g_maxclients.integer ; i++ ) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
cl->ps.persistant[PERS_SCORE] = 0;
}
// we need to do this here before changing to CON_CONNECTING
G_WriteSessionData();
// change all client states to connecting, so the early players into the
// next level will know the others aren't done reconnecting
for (i=0 ; i< g_maxclients.integer ; i++) {
if ( level.clients[i].pers.connected == CON_CONNECTED ) {
level.clients[i].pers.connected = CON_CONNECTING;
}
}
}
/*
=================
G_LogPrintf
Print to the logfile with a time stamp if it is open
=================
*/
void QDECL G_LogPrintf( const char *fmt, ... ) {
va_list argptr;
char string[1024];
int min, tens, sec;
sec = ( level.time - level.startTime ) / 1000;
min = sec / 60;
sec -= min * 60;
tens = sec / 10;
sec -= tens * 10;
Com_sprintf( string, sizeof(string), "%3i:%i%i ", min, tens, sec );
va_start( argptr, fmt );
Q_vsnprintf(string + 7, sizeof(string) - 7, fmt, argptr);
va_end( argptr );
if ( g_dedicated.integer ) {
G_Printf( "%s", string + 7 );
}
if ( !level.logFile ) {
return;
}
trap_FS_Write( string, strlen( string ), level.logFile );
}
/*
================
LogExit
Append information about this game to the log file
================
*/
void LogExit( const char *string ) {
int i, numSorted;
gclient_t *cl;
#ifdef MISSIONPACK
qboolean won = qtrue;
team_t team = TEAM_RED;
#endif
G_LogPrintf( "Exit: %s\n", string );
level.intermissionQueued = level.time;
// this will keep the clients from playing any voice sounds
// that will get cut off when the queued intermission starts
trap_SetConfigstring( CS_INTERMISSION, "1" );
// don't send more than 32 scores (FIXME?)
numSorted = level.numConnectedClients;
if ( numSorted > 32 ) {
numSorted = 32;
}
if ( g_gametype.integer >= GT_TEAM ) {
G_LogPrintf( "red:%i blue:%i\n",
level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE] );
}
for (i=0 ; i < numSorted ; i++) {
int ping;
cl = &level.clients[level.sortedClients[i]];
if ( cl->sess.sessionTeam == TEAM_SPECTATOR ) {
continue;
}
if ( cl->pers.connected == CON_CONNECTING ) {
continue;
}
ping = cl->ps.ping < 999 ? cl->ps.ping : 999;
G_LogPrintf( "score: %i ping: %i client: %i %s\n", cl->ps.persistant[PERS_SCORE], ping, level.sortedClients[i], cl->pers.netname );
#ifdef MISSIONPACK
if (g_singlePlayer.integer && !(g_entities[cl - level.clients].r.svFlags & SVF_BOT)) {
team = cl->sess.sessionTeam;
}
if (g_singlePlayer.integer && g_gametype.integer < GT_TEAM) {
if (g_entities[cl - level.clients].r.svFlags & SVF_BOT && cl->ps.persistant[PERS_RANK] == 0) {
won = qfalse;
}
}
#endif
}
#ifdef MISSIONPACK
if (g_singlePlayer.integer) {
if (g_gametype.integer >= GT_TEAM) {
if (team == TEAM_BLUE) {
won = level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED];
} else {
won = level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE];
}
}
trap_SendConsoleCommand( EXEC_APPEND, (won) ? "spWin\n" : "spLose\n" );
}
#endif
}
/*
=================
CheckIntermissionExit
The level will stay at the intermission for a minimum of 5 seconds
If all players wish to continue, the level will then exit.
If one or more players have not acknowledged the continue, the game will
wait 10 seconds before going on.
=================
*/
void CheckIntermissionExit( void ) {
int ready, notReady, playerCount;
int i;
gclient_t *cl;
int readyMask;
if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
return;
}
// see which players are ready
ready = 0;
notReady = 0;
readyMask = 0;
playerCount = 0;
for (i=0 ; i< g_maxclients.integer ; i++) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
if ( g_entities[i].r.svFlags & SVF_BOT ) {
continue;
}
// cyberdeck: spectators (the PiP and highlight cameras) don't hold up the map change
if ( cl->sess.sessionTeam == TEAM_SPECTATOR ) {
continue;
}
playerCount++;
if ( cl->readyToExit ) {
ready++;
if ( i < 16 ) {
readyMask |= 1 << i;
}
} else {
notReady++;
}
}
// copy the readyMask to each player's stats so
// it can be displayed on the scoreboard
for (i=0 ; i< g_maxclients.integer ; i++) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
cl->ps.stats[STAT_CLIENTS_READY] = readyMask;
}
// never exit in less than five seconds
if ( level.time < level.intermissiontime + 5000 ) {
return;
}
// only test ready status when there are real players present
if ( playerCount > 0 ) {
// if nobody wants to go, clear timer
if ( !ready ) {
level.readyToExit = qfalse;
return;
}
// if everyone wants to go, go now
if ( !notReady ) {
ExitLevel();
return;
}
}
// the first person to ready starts the ten second timeout
if ( !level.readyToExit ) {
level.readyToExit = qtrue;
level.exitTime = level.time;
}
// if we have waited ten seconds since at least one player
// wanted to exit, go ahead
if ( level.time < level.exitTime + 10000 ) {
return;
}
ExitLevel();
}
/*
=============
ScoreIsTied
=============
*/
qboolean ScoreIsTied( void ) {
int a, b;
if ( level.numPlayingClients < 2 ) {
return qfalse;
}
if ( g_gametype.integer >= GT_TEAM ) {
return level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE];
}
a = level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE];
b = level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE];
return a == b;
}
/*
=================
CheckExitRules
There will be a delay between the time the exit is qualified for
and the time everyone is moved to the intermission spot, so you
can see the last frag.
=================
*/
void CheckExitRules( void ) {
int i;
gclient_t *cl;
// if at the intermission, wait for all non-bots to
// signal ready, then go to next level
if ( level.intermissiontime ) {
CheckIntermissionExit ();
return;
}
if ( level.intermissionQueued ) {
#ifdef MISSIONPACK
int time = (g_singlePlayer.integer) ? SP_INTERMISSION_DELAY_TIME : INTERMISSION_DELAY_TIME;
if ( level.time - level.intermissionQueued >= time ) {
level.intermissionQueued = 0;
BeginIntermission();
}
#else
if ( level.time - level.intermissionQueued >= INTERMISSION_DELAY_TIME ) {
level.intermissionQueued = 0;
BeginIntermission();
}
#endif
return;
}
// check for sudden death
if ( ScoreIsTied() ) {
// always wait for sudden death
return;
}
if ( g_timelimit.integer < 0 || g_timelimit.integer > INT_MAX / 60000 ) {
G_Printf( "timelimit %i is out of range, defaulting to 0\n", g_timelimit.integer );
trap_Cvar_Set( "timelimit", "0" );
trap_Cvar_Update( &g_timelimit );
}
if ( g_timelimit.integer && !level.warmupTime ) {
if ( level.time - level.startTime >= g_timelimit.integer*60000 ) {
trap_SendServerCommand( -1, "print \"Timelimit hit.\n\"");
LogExit( "Timelimit hit." );
return;
}
}
if ( g_fraglimit.integer < 0 ) {
G_Printf( "fraglimit %i is out of range, defaulting to 0\n", g_fraglimit.integer );
trap_Cvar_Set( "fraglimit", "0" );
trap_Cvar_Update( &g_fraglimit );
}
if ( g_gametype.integer < GT_CTF && g_fraglimit.integer ) {
if ( level.teamScores[TEAM_RED] >= g_fraglimit.integer ) {
trap_SendServerCommand( -1, "print \"Red hit the fraglimit.\n\"" );
LogExit( "Fraglimit hit." );
return;
}
if ( level.teamScores[TEAM_BLUE] >= g_fraglimit.integer ) {
trap_SendServerCommand( -1, "print \"Blue hit the fraglimit.\n\"" );
LogExit( "Fraglimit hit." );
return;
}
for ( i=0 ; i< g_maxclients.integer ; i++ ) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
if ( cl->sess.sessionTeam != TEAM_FREE ) {
continue;
}
if ( cl->ps.persistant[PERS_SCORE] >= g_fraglimit.integer ) {
LogExit( "Fraglimit hit." );
trap_SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " hit the fraglimit.\n\"",
cl->pers.netname ) );
return;
}
}
}
if ( g_capturelimit.integer < 0 ) {
G_Printf( "capturelimit %i is out of range, defaulting to 0\n", g_capturelimit.integer );
trap_Cvar_Set( "capturelimit", "0" );
trap_Cvar_Update( &g_capturelimit );
}
if ( g_gametype.integer >= GT_CTF && g_capturelimit.integer ) {
if ( level.teamScores[TEAM_RED] >= g_capturelimit.integer ) {
trap_SendServerCommand( -1, "print \"Red hit the capturelimit.\n\"" );
LogExit( "Capturelimit hit." );
return;
}
if ( level.teamScores[TEAM_BLUE] >= g_capturelimit.integer ) {
trap_SendServerCommand( -1, "print \"Blue hit the capturelimit.\n\"" );
LogExit( "Capturelimit hit." );
return;
}
}
}
/*
========================================================================
FUNCTIONS CALLED EVERY FRAME
========================================================================
*/
/*
=============
CheckTournament
Once a frame, check for changes in tournement player state
=============
*/
void CheckTournament( void ) {
// check because we run 3 game frames before calling Connect and/or ClientBegin
// for clients on a map_restart
if ( level.numPlayingClients == 0 ) {
return;
}
if ( g_gametype.integer == GT_TOURNAMENT ) {
// pull in a spectator if needed
if ( level.numPlayingClients < 2 ) {
AddTournamentPlayer();
}
// if we don't have two players, go back to "waiting for players"
if ( level.numPlayingClients != 2 ) {
if ( level.warmupTime != -1 ) {
level.warmupTime = -1;
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
G_LogPrintf( "Warmup:\n" );
}
return;
}
if ( level.warmupTime == 0 ) {
return;
}
// if the warmup is changed at the console, restart it
if ( g_warmup.modificationCount != level.warmupModificationCount ) {
level.warmupModificationCount = g_warmup.modificationCount;
level.warmupTime = -1;
}
// if all players have arrived, start the countdown
if ( level.warmupTime < 0 ) {
if ( level.numPlayingClients == 2 ) {
// fudge by -1 to account for extra delays
if ( g_warmup.integer > 1 ) {
level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000;
} else {
level.warmupTime = 0;
}
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
}
return;
}
// if the warmup time has counted down, restart
if ( level.time > level.warmupTime ) {
level.warmupTime += 10000;
trap_Cvar_Set( "g_restarted", "1" );
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
return;
}
} else if ( g_gametype.integer != GT_SINGLE_PLAYER && level.warmupTime != 0 ) {
int counts[TEAM_NUM_TEAMS];
qboolean notEnough = qfalse;
if ( g_gametype.integer >= GT_TEAM ) {
counts[TEAM_BLUE] = TeamCount( -1, TEAM_BLUE );
counts[TEAM_RED] = TeamCount( -1, TEAM_RED );
if (counts[TEAM_RED] < 1 || counts[TEAM_BLUE] < 1) {
notEnough = qtrue;
}
} else if ( level.numPlayingClients < 2 ) {
notEnough = qtrue;
}
if ( notEnough ) {
if ( level.warmupTime != -1 ) {
level.warmupTime = -1;
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
G_LogPrintf( "Warmup:\n" );
}
return; // still waiting for team members
}
if ( level.warmupTime == 0 ) {
return;
}
// if the warmup is changed at the console, restart it
if ( g_warmup.modificationCount != level.warmupModificationCount ) {
level.warmupModificationCount = g_warmup.modificationCount;
level.warmupTime = -1;
}
// if all players have arrived, start the countdown
if ( level.warmupTime < 0 ) {
// fudge by -1 to account for extra delays
if ( g_warmup.integer > 1 ) {
level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000;
} else {
level.warmupTime = 0;
}
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
return;
}
// if the warmup time has counted down, restart
if ( level.time > level.warmupTime ) {
level.warmupTime += 10000;
trap_Cvar_Set( "g_restarted", "1" );
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
return;
}
}
}
/*
==================
CheckVote
==================
*/
void CheckVote( void ) {
if ( level.voteExecuteTime && level.voteExecuteTime < level.time ) {
level.voteExecuteTime = 0;
trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.voteString ) );
}
if ( !level.voteTime ) {
return;
}
if ( level.time - level.voteTime >= VOTE_TIME ) {
trap_SendServerCommand( -1, "print \"Vote failed.\n\"" );
} else {
// ATVI Q3 1.32 Patch #9, WNF
if ( level.voteYes > level.numVotingClients/2 ) {
// execute the command, then remove the vote
trap_SendServerCommand( -1, "print \"Vote passed.\n\"" );
level.voteExecuteTime = level.time + 3000;
} else if ( level.voteNo >= level.numVotingClients/2 ) {
// same behavior as a timeout
trap_SendServerCommand( -1, "print \"Vote failed.\n\"" );
} else {
// still waiting for a majority
return;
}
}
level.voteTime = 0;
trap_SetConfigstring( CS_VOTE_TIME, "" );
}
/*
==================
PrintTeam
==================
*/
void PrintTeam(int team, char *message) {
int i;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].sess.sessionTeam != team)
continue;
trap_SendServerCommand( i, message );
}
}
/*
==================
SetLeader
==================
*/
void SetLeader(int team, int client) {
int i;
if ( level.clients[client].pers.connected == CON_DISCONNECTED ) {
PrintTeam(team, va("print \"%s is not connected\n\"", level.clients[client].pers.netname) );
return;
}
if (level.clients[client].sess.sessionTeam != team) {
PrintTeam(team, va("print \"%s is not on the team anymore\n\"", level.clients[client].pers.netname) );
return;
}
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].sess.sessionTeam != team)
continue;
if (level.clients[i].sess.teamLeader) {
level.clients[i].sess.teamLeader = qfalse;
ClientUserinfoChanged(i);
}
}
level.clients[client].sess.teamLeader = qtrue;
ClientUserinfoChanged( client );
PrintTeam(team, va("print \"%s is the new team leader\n\"", level.clients[client].pers.netname) );
}
/*
==================
CheckTeamLeader
==================
*/
void CheckTeamLeader( int team ) {
int i;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].sess.sessionTeam != team)
continue;
if (level.clients[i].sess.teamLeader)
break;
}
if (i >= level.maxclients) {
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].sess.sessionTeam != team)
continue;
if (!(g_entities[i].r.svFlags & SVF_BOT)) {
level.clients[i].sess.teamLeader = qtrue;
break;
}
}
if (i >= level.maxclients) {
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].sess.sessionTeam != team)
continue;
level.clients[i].sess.teamLeader = qtrue;
break;
}
}
}
}
/*
==================
CheckTeamVote
==================
*/
void CheckTeamVote( int team ) {
int cs_offset;
if ( team == TEAM_RED )
cs_offset = 0;
else if ( team == TEAM_BLUE )
cs_offset = 1;
else
return;
if ( !level.teamVoteTime[cs_offset] ) {
return;
}
if ( level.time - level.teamVoteTime[cs_offset] >= VOTE_TIME ) {
trap_SendServerCommand( -1, "print \"Team vote failed.\n\"" );
} else {
if ( level.teamVoteYes[cs_offset] > level.numteamVotingClients[cs_offset]/2 ) {
// execute the command, then remove the vote
trap_SendServerCommand( -1, "print \"Team vote passed.\n\"" );
//
if ( !Q_strncmp( "leader", level.teamVoteString[cs_offset], 6) ) {
//set the team leader
SetLeader(team, atoi(level.teamVoteString[cs_offset] + 7));
}
else {
trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.teamVoteString[cs_offset] ) );
}
} else if ( level.teamVoteNo[cs_offset] >= level.numteamVotingClients[cs_offset]/2 ) {
// same behavior as a timeout
trap_SendServerCommand( -1, "print \"Team vote failed.\n\"" );
} else {
// still waiting for a majority
return;
}
}
level.teamVoteTime[cs_offset] = 0;
trap_SetConfigstring( CS_TEAMVOTE_TIME + cs_offset, "" );
}
/*
==================
CheckCvars
==================
*/
void CheckCvars( void ) {
static int lastMod = -1;
if ( g_password.modificationCount != lastMod ) {
lastMod = g_password.modificationCount;
if ( *g_password.string && Q_stricmp( g_password.string, "none" ) ) {
trap_Cvar_Set( "g_needpass", "1" );
} else {
trap_Cvar_Set( "g_needpass", "0" );
}
}
}
/*
=============
G_RunThink
Runs thinking code for this frame if necessary
=============
*/
void G_RunThink (gentity_t *ent) {
int thinktime;
thinktime = ent->nextthink;
if (thinktime <= 0) {
return;
}
if (thinktime > level.time) {
return;
}
ent->nextthink = 0;
if (!ent->think) {
G_Error ( "NULL ent->think");
}
ent->think (ent);
}
/*
================
G_RunFrame
Advances the non-player objects in the world
================
*/
void G_RunFrame( int levelTime ) {
int i;
gentity_t *ent;
// if we are waiting for the level to restart, do nothing
if ( level.restarted ) {
return;
}
level.framenum++;
level.previousTime = level.time;
level.time = levelTime;
// get any cvar changes
G_UpdateCvars();
//
// go through all allocated objects
//
ent = &g_entities[0];
for (i=0 ; i<level.num_entities ; i++, ent++) {
if ( !ent->inuse ) {
continue;
}
// clear events that are too old
if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) {
if ( ent->s.event ) {
ent->s.event = 0; // &= EV_EVENT_BITS;
if ( ent->client ) {
ent->client->ps.externalEvent = 0;
// predicted events should never be set to zero
//ent->client->ps.events[0] = 0;
//ent->client->ps.events[1] = 0;
}
}
if ( ent->freeAfterEvent ) {
// tempEntities or dropped items completely go away after their event
G_FreeEntity( ent );
continue;
} else if ( ent->unlinkAfterEvent ) {
// items that will respawn will hide themselves after their pickup event
ent->unlinkAfterEvent = qfalse;
trap_UnlinkEntity( ent );
}
}
// temporary entities don't think
if ( ent->freeAfterEvent ) {
continue;
}
if ( !ent->r.linked && ent->neverFree ) {
continue;
}
if ( ent->s.eType == ET_MISSILE ) {
G_RunMissile( ent );
continue;
}
if ( ent->s.eType == ET_ITEM || ent->physicsObject ) {
G_RunItem( ent );
continue;
}
if ( ent->s.eType == ET_MOVER ) {
G_RunMover( ent );
continue;
}
if ( i < MAX_CLIENTS ) {
G_RunClient( ent );
continue;
}
G_RunThink( ent );
}
// perform final fixups on the players
ent = &g_entities[0];
for (i=0 ; i < level.maxclients ; i++, ent++ ) {
if ( ent->inuse ) {
ClientEndFrame( ent );
}
}
// see if it is time to do a tournement restart
CheckTournament();
// see if it is time to end the level
CheckExitRules();
// update to team status?
CheckTeamStatus();
// cancel vote if timed out
CheckVote();
// check team votes
CheckTeamVote( TEAM_RED );
CheckTeamVote( TEAM_BLUE );
// for tracking changes
CheckCvars();
CD_RunFrame();
if (g_listEntity.integer) {
for (i = 0; i < MAX_GENTITIES; i++) {
G_Printf("%4i: %s\n", i, g_entities[i].classname);
}
trap_Cvar_Set("g_listEntity", "0");
}
}
/*
==============================================================================
CYBERDECK BOT ARENA ADDITIONS
Mutators (one random per match), kill-streak announcements, the FFA
juggernaut, fixed per-bot skills, and serverinfo the herdr scoreboard reads.
"Announce:" and "Mutator:" log lines feed its kill feed and all-time stats.
==============================================================================
*/
#define CD_FOREVER 1000000000
#define CD_MULTI_WINDOW 3000 // ms between kills that chain into a double/triple/multi kill
static const char *cd_mutatorNames[] = { "", "Moon gravity", "Haste", "Ghosts", "Rail push", "Gun Game", "Pinball", "Vampire", "Halloween" };
// seasonal: Halloween only rolls from October 15 to November 1 (server clock)
static qboolean CD_HalloweenSeason( void ) {
qtime_t t;
trap_RealTime( &t );
return ( t.tm_mon == 9 && t.tm_mday >= 15 ) || ( t.tm_mon == 10 && t.tm_mday <= 1 );
}
// the previous match's mutator lives in a small file in the mod's home folder: cvars the game
// creates can be reset when the engine reloads the game code between maps
#define CD_STATE_FILE "cd_lastmutator.txt"
static void CD_LoadState( int *mutator, int *weapon ) {
fileHandle_t f;
char buf[32];
char *space;
int len;
*mutator = *weapon = 0;
memset( buf, 0, sizeof( buf ) );
len = trap_FS_FOpenFile( CD_STATE_FILE, &f, FS_READ );
if ( !f ) {
return;
}
if ( len > 0 ) {
trap_FS_Read( buf, len < (int)sizeof( buf ) - 1 ? len : (int)sizeof( buf ) - 1, f );
}
trap_FS_FCloseFile( f );
*mutator = atoi( buf );
space = strchr( buf, ' ' );
if ( space ) {
*weapon = atoi( space + 1 );
}
}
static void CD_SaveState( int mutator, int weapon ) {
fileHandle_t f;
char *text;
trap_FS_FOpenFile( CD_STATE_FILE, &f, FS_WRITE );
if ( !f ) {
return;
}
text = va( "%i %i\n", mutator, weapon );
trap_FS_Write( text, strlen( text ), f );
trap_FS_FCloseFile( f );
}
// weapon modes: instagib rails, or one normal-damage weapon with infinite ammo and only
// health and armor on the map. Rails weigh 3, the rest 1, never the same mode twice in a
// row: about 30% of matches are instagib and about 14% each are the other five.
static const int cd_modeWeapons[] = { WP_RAILGUN, WP_GAUNTLET, WP_MACHINEGUN, WP_SHOTGUN, WP_ROCKET_LAUNCHER, WP_LIGHTNING };
static const int cd_modeWeights[] = { 3, 1, 1, 1, 1, 1 };
#define CD_NUM_MODES ( (int)( sizeof( cd_modeWeapons ) / sizeof( cd_modeWeapons[0] ) ) )
static const char *CD_WeaponModeName( int weapon ) {
switch ( weapon ) {
case WP_GAUNTLET: return "Gauntlet";
case WP_MACHINEGUN: return "Machine gun";
case WP_SHOTGUN: return "Shotgun";
case WP_ROCKET_LAUNCHER: return "Rockets";
case WP_LIGHTNING: return "Lightning";
default: return "Instagib";
}
}
static const char *CD_WeaponModeBanner( int weapon ) {
switch ( weapon ) {
case WP_GAUNTLET: return "^3GAUNTLET BRAWL";
case WP_MACHINEGUN: return "^3MACHINE GUNS ONLY";
case WP_SHOTGUN: return "^3SHOTGUNS ONLY";
case WP_ROCKET_LAUNCHER: return "^1ROCKET ARENA";
case WP_LIGHTNING: return "^5LIGHTNING GUNS ONLY";
default: return "^1INSTAGIB";
}
}
// gun game replaces the weapon mode, so it names the mode too
static const char *CD_ModeName( void ) {
return level.cd_mutator == CD_MUT_GUNGAME ? "Gun Game" : CD_WeaponModeName( level.cd_weapon );
}
static const char *CD_ModeBanner( void ) {
return level.cd_mutator == CD_MUT_GUNGAME ? "^6GUN GAME" : CD_WeaponModeBanner( level.cd_weapon );
}
static int CD_RollWeapon( int last, int seed ) {
int i, total = 0, pick;
if ( g_weaponforce.integer >= 1 && g_weaponforce.integer <= CD_NUM_MODES ) {
return cd_modeWeapons[ g_weaponforce.integer - 1 ];
}
if ( !g_weaponmodes.integer ) {
return WP_RAILGUN;
}
for ( i = 0; i < CD_NUM_MODES; i++ ) {
if ( cd_modeWeapons[i] != last ) {
total += cd_modeWeights[i];
}
}
pick = (int)( (unsigned int)seed % (unsigned int)total );
for ( i = 0; i < CD_NUM_MODES; i++ ) {
if ( cd_modeWeapons[i] == last ) {
continue;
}
if ( pick < cd_modeWeights[i] ) {
return cd_modeWeapons[i];
}
pick -= cd_modeWeights[i];
}
return WP_RAILGUN;
}
// instagib hides every item (bots still roam to them); the other modes show health and armor
qboolean CD_ItemHidden( const gitem_t *item ) {
if ( !g_instagib.integer || item->giType == IT_TEAM ) {
return qfalse;
}
if ( CD_WEAPON() == WP_RAILGUN && level.cd_mutator != CD_MUT_GUNGAME ) {
return qtrue;
}
return item->giType != IT_HEALTH && item->giType != IT_ARMOR; // gun game plays at normal damage too
}
// map shuffle: g_mapshuffle lists vstr names (each sets the game type, bots and frag limit and
// loads a map). Like a shuffled playlist, every entry plays once before any repeats; a refill
// never starts with the map that just played. The bag lives in a file: "<upcoming> <rest...>".
#define CD_MAPBAG_FILE "cd_mapbag.txt"
#define CD_MAX_MAPS 32
static int CD_SplitWords( char *buf, char *words[], int max ) {
int n = 0;
char *p = buf;
while ( *p && n < max ) {
while ( *p == ' ' || *p == '\n' || *p == '\r' || *p == '\t' ) {
*p++ = 0;
}
if ( !*p ) {
break;
}
words[n++] = p;
while ( *p && *p != ' ' && *p != '\n' && *p != '\r' && *p != '\t' ) {
p++;
}
}
return n;
}
static void CD_PickNextMap( int seed ) {
char all[MAX_CVAR_VALUE_STRING], bag[1024], out[1024];
char *pool[CD_MAX_MAPS], *left[CD_MAX_MAPS], *saved[CD_MAX_MAPS + 1];
int nPool, nLeft = 0, nSaved = 0, i, len, pick;
const char *current = "";
fileHandle_t f;
trap_Cvar_VariableStringBuffer( "g_mapshuffle", all, sizeof( all ) );
nPool = CD_SplitWords( all, pool, CD_MAX_MAPS );
if ( nPool < 2 ) {
return; // no shuffle configured: the vstrs chain themselves with "set nextmap"
}
memset( bag, 0, sizeof( bag ) );
len = trap_FS_FOpenFile( CD_MAPBAG_FILE, &f, FS_READ );
if ( f ) {
if ( len > 0 ) {
trap_FS_Read( bag, len < (int)sizeof( bag ) - 1 ? len : (int)sizeof( bag ) - 1, f );
}
trap_FS_FCloseFile( f );
nSaved = CD_SplitWords( bag, saved, CD_MAX_MAPS + 1 );
}
// which entry is actually on: match the loaded map against each entry's "map <name>". After a
// server restart this differs from the entry we queued (the config always boots the first one).
{
char mapname[MAX_QPATH], def[MAX_CVAR_VALUE_STRING];
trap_Cvar_VariableStringBuffer( "mapname", mapname, sizeof( mapname ) );
for ( i = 0; i < nPool; i++ ) {
char *m;
trap_Cvar_VariableStringBuffer( pool[i], def, sizeof( def ) );
m = strstr( def, "map " );
if ( m && !Q_stricmp( m + 4, mapname ) ) {
current = pool[i];
break;
}
}
}
// a queued entry that didn't get played (restart) goes back in the bag
if ( nSaved && Q_stricmp( saved[0], current ) ) {
for ( i = 0; i < nPool; i++ ) {
if ( !Q_stricmp( saved[0], pool[i] ) ) {
left[nLeft++] = pool[i];
break;
}
}
}
// what's left in the bag (only names still in the pool, in case the list changed)
for ( i = 1; i < nSaved; i++ ) {
int j;
if ( !Q_stricmp( saved[i], current ) ) {
continue; // it's being played right now
}
for ( j = 0; j < nPool; j++ ) {
if ( !Q_stricmp( saved[i], pool[j] ) ) {
left[nLeft++] = pool[j];
break;
}
}
}
if ( !nLeft ) { // refill, but never replay the map that's on now
for ( i = 0; i < nPool; i++ ) {
if ( Q_stricmp( pool[i], current ) ) {
left[nLeft++] = pool[i];
}
}
}
pick = (int)( (unsigned int)seed % (unsigned int)nLeft );
Com_sprintf( out, sizeof( out ), "%s", left[pick] );
for ( i = 0; i < nLeft; i++ ) {
if ( i != pick ) {
Q_strcat( out, sizeof( out ), va( " %s", left[i] ) );
}
}
Q_strcat( out, sizeof( out ), "\n" );
trap_FS_FOpenFile( CD_MAPBAG_FILE, &f, FS_WRITE );
if ( f ) {
trap_FS_Write( out, strlen( out ), f );
trap_FS_FCloseFile( f );
}
trap_Cvar_Set( "nextmap", va( "vstr %s", left[pick] ) );
G_LogPrintf( "NextMap: %s\n", left[pick] );
}
// ------------------------------------------------------------------ trash talk
// The arena companion writes cd_taunts.txt into the mod folder from this season's stats: one line per taunt,
// "K|D <tab> speaker <tab> target <tab> text" (names without colour codes). K: the speaker just fragged the
// target; D: the target just fragged the speaker. Bots say a matching line now and then.
#define CD_TAUNT_FILE "cd_taunts.txt"
#define CD_MAX_TAUNTS 640
static char cd_tauntBuf[65536];
static struct { char kind; const char *speaker, *target, *text; } cd_taunts[CD_MAX_TAUNTS];
static int cd_numTaunts;
static int cd_tauntQuiet; // level.time before which nobody taunts (keeps chat from flooding)
static int cd_spookNext; // level.time of the next Halloween ambient sound (0: schedule one)
static void CD_LoadTaunts( void ) {
fileHandle_t f;
int len;
char *p;
cd_numTaunts = 0;
cd_tauntQuiet = 0;
len = trap_FS_FOpenFile( CD_TAUNT_FILE, &f, FS_READ );
if ( !f ) {
return;
}
if ( len <= 0 || len >= (int)sizeof( cd_tauntBuf ) ) {
trap_FS_FCloseFile( f );
return;
}
trap_FS_Read( cd_tauntBuf, len, f );
trap_FS_FCloseFile( f );
cd_tauntBuf[len] = 0;
p = cd_tauntBuf;
while ( *p && cd_numTaunts < CD_MAX_TAUNTS ) {
char *fields[4], *line = p, *end = strchr( p, '\n' );
int n = 0;
if ( end ) {
*end = 0;
p = end + 1;
} else {
p += strlen( p );
}
fields[n++] = line;
while ( n < 4 && ( line = strchr( line, '\t' ) ) != NULL ) {
*line++ = 0;
fields[n++] = line;
}
if ( n == 4 && ( fields[0][0] == 'K' || fields[0][0] == 'D' ) && fields[3][0] ) {
cd_taunts[cd_numTaunts].kind = fields[0][0];
cd_taunts[cd_numTaunts].speaker = fields[1];
cd_taunts[cd_numTaunts].target = fields[2];
cd_taunts[cd_numTaunts].text = fields[3];
cd_numTaunts++;
}
}
G_Printf( "cyberdeck: %i taunts loaded\n", cd_numTaunts );
}
// a bot (speaker) may say a line about target; humans get talked at far more often than bots
static qboolean CD_Taunt( char kind, gentity_t *speaker, gentity_t *target ) {
char sname[MAX_NETNAME], tname[MAX_NETNAME];
const char *pick[16];
int n = 0, i;
if ( !cd_numTaunts || level.time < cd_tauntQuiet || level.warmupTime || level.intermissiontime ) {
return qfalse;
}
if ( !speaker || !target || !speaker->client || !target->client || speaker == target
|| !( speaker->r.svFlags & SVF_BOT ) || level.time < speaker->client->pers.cd_tauntNext ) {
return qfalse;
}
if ( rand() % 100 >= ( ( target->r.svFlags & SVF_BOT ) ? 10 : 45 ) ) {
return qfalse;
}
Q_strncpyz( sname, speaker->client->pers.netname, sizeof( sname ) );
Q_CleanStr( sname );
Q_strncpyz( tname, target->client->pers.netname, sizeof( tname ) );
Q_CleanStr( tname );
for ( i = 0; i < cd_numTaunts && n < (int)ARRAY_LEN( pick ); i++ ) {
if ( cd_taunts[i].kind == kind && !Q_stricmp( cd_taunts[i].speaker, sname ) && !Q_stricmp( cd_taunts[i].target, tname ) ) {
pick[n++] = cd_taunts[i].text;
}
}
if ( !n ) {
return qfalse;
}
G_Say( speaker, NULL, SAY_ALL, pick[ rand() % n ] );
cd_tauntQuiet = level.time + 8000;
speaker->client->pers.cd_tauntNext = level.time + 45000;
return qtrue;
}
void CD_InitMutator( int restart, int seed ) {
char map[MAX_QPATH];
int pool[32], n = 0, i, last, lastWeapon;
level.cd_mutator = 0;
level.cd_weapon = WP_RAILGUN;
CD_LoadState( &last, &lastWeapon );
CD_LoadTaunts();
cd_spookNext = 0;
if ( g_instagib.integer ) {
// the warmup restart keeps what the warmup announced; a new map rolls again
level.cd_weapon = restart && lastWeapon ? lastWeapon
: CD_RollWeapon( lastWeapon, (int)( (unsigned int)seed / 7u ) );
}
level.cd_juggernaut = -1;
// rotate the roster: on a real map change (not the warmup restart), drop every bot so
// bot_minplayers refills with a random selection; otherwise the same bots play for days
if ( g_botrotate.integer && !restart ) {
trap_SendConsoleCommand( EXEC_APPEND, "kick allbots\n" );
G_LogPrintf( "Roster: rotate\n" );
}
if ( g_mutators.integer && restart ) {
// warmup just ended (map_restart): keep the mutator the warmup announced
level.cd_mutator = last;
} else if ( g_mutators.integer ) {
trap_Cvar_VariableStringBuffer( "mapname", map, sizeof( map ) );
for ( i = CD_MUT_MOON; i <= CD_MUT_LAST; i++ ) {
int weight = 2;
if ( i == last ) {
continue; // never the same twice in a row
}
// gun game replaces the weapon mode with a per-player ladder: free for all only, and
// half as likely as the rest so instagib stays the arena's bread and butter
if ( i == CD_MUT_GUNGAME ) {
if ( g_gametype.integer >= GT_TEAM || !g_instagib.integer ) {
continue;
}
weight = 1;
}
// halloween is seasonal, and in season it comes up often
if ( i == CD_MUT_HALLOWEEN ) {
if ( !CD_HalloweenSeason() ) {
continue;
}
weight = 4;
}
// pinball and vampire need hits that don't kill outright
if ( ( i == CD_MUT_PINBALL || i == CD_MUT_VAMPIRE ) && ( !g_instagib.integer || CD_INSTAGIB() ) ) {
continue;
}
// rail push scores by knocking people into the void, so it needs instagib and a void map
if ( i == CD_MUT_RAILPUSH && ( !CD_INSTAGIB() || Q_stricmp( map, "q3dm17" ) ) ) {
continue;
}
// moon gravity breaks bot navigation in tight maps (paths assume normal gravity); open space only
if ( i == CD_MUT_MOON && Q_stricmp( map, "q3dm17" ) ) {
continue;
}
// haste on the space platforms just sends everyone flying off the edge
if ( i == CD_MUT_HASTE && !Q_stricmp( map, "q3dm17" ) ) {
continue;
}
while ( weight-- > 0 && n < (int)ARRAY_LEN( pool ) ) {
pool[n++] = i;
}
}
if ( n ) {
level.cd_mutator = pool[ (unsigned int)seed % n ]; // engine's per-map random seed
}
if ( g_mutatorforce.integer >= CD_MUT_MOON && g_mutatorforce.integer <= CD_MUT_LAST ) {
level.cd_mutator = g_mutatorforce.integer;
}
}
if ( !restart ) {
CD_SaveState( level.cd_mutator, level.cd_weapon );
CD_PickNextMap( (int)( (unsigned int)seed / 131u ) );
}
trap_Cvar_Set( "g_mutator", cd_mutatorNames[level.cd_mutator] );
trap_Cvar_Set( "g_weaponmode", g_instagib.integer ? CD_ModeName() : "" );
if ( g_instagib.integer ) {
G_LogPrintf( "Weapons: %s\n", CD_ModeName() );
}
if ( level.cd_mutator == CD_MUT_GUNGAME ) {
trap_Cvar_Set( "fraglimit", va( "%i", CD_GUN_TOTAL ) ); // the score is the climb: the top ends it
}
trap_Cvar_Set( "g_gravity", level.cd_mutator == CD_MUT_MOON ? "250" : "800" );
trap_Cvar_Set( "cd_jugg", "" );
trap_Cvar_Set( "Score_Red", "" );
trap_Cvar_Set( "Score_Blue", "" );
if ( level.cd_mutator ) {
G_LogPrintf( "Mutator: %s\n", cd_mutatorNames[level.cd_mutator] );
}
// the intro banner plays when the real match starts (after the warmup countdown, if any)
level.cd_bannerTime = ( restart || !g_doWarmup.integer ) ? level.time + 1200 : 0;
}
static void CD_GlobalSound( const char *path ) {
gentity_t *te = G_TempEntity( vec3_origin, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex( (char *)path );
te->r.svFlags |= SVF_BROADCAST;
}
static void CD_Award( gentity_t *ent, int flag ) {
ent->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP);
ent->client->ps.eFlags |= flag; // the medal floats over their head
ent->client->rewardTime = level.time + REWARD_SPRITE_TIME;
}
static const char *cd_mutatorBanners[] = {
"",
"^5<< MOON GRAVITY >>\n\n^7the jump pads launch you into orbit",
"^3<< HASTE >>\n\n^7everyone moves and fires faster",
"^6<< GHOSTS >>\n\n^7everyone is invisible -- shooting gives you away",
"^2<< RAIL PUSH >>\n\n^7rails don't kill -- they launch\n^7the void does the rest",
"^6<< GUN GAME >>\n\n^7two kills climb a rung: rail, rockets, lightning, plasma,\n^7shotgun, grenades, machine gun -- then the gauntlet\n^7first gauntlet kill at the top wins",
"^2<< PINBALL >>\n\n^7every hit launches -- way, way out",
"^1<< VAMPIRE >>\n\n^7the damage you deal heals you",
"^3<< ^1HALLOWEEN^3 >>\n\n^7everyone's a skeleton -- and every death leaves bones\n^7headshots send skulls flying"
};
// ------------------------------------------------------------------ halloween
const char *CD_Costume( const char *cs, int team ) {
static char buf[MAX_INFO_STRING];
const char *model;
if ( level.cd_mutator != CD_MUT_HALLOWEEN ) {
return cs;
}
model = team == TEAM_RED ? "bones/red" : team == TEAM_BLUE ? "bones/blue" : "bones";
// Info_SetValueForKey prepends "\\key\\value", and player configstrings have no leading backslash: add one,
// or the new pair would glue onto the first key ("\\model\\bonesn\\name...")
Com_sprintf( buf, sizeof( buf ), "\\%s", cs );
Info_SetValueForKey( buf, "model", model );
Info_SetValueForKey( buf, "hmodel", model );
return buf;
}
// Halloween bones: the Bones player model's parts with its bleached "stiff" texture baked in (they can't take
// a skin as plain entities), shipped in the mod pk3 under models/cyberdeck/.
#define CD_BONE_HEAD "models/cyberdeck/bones_head.md3"
#define CD_BONE_UPPER "models/cyberdeck/bones_upper.md3"
#define CD_BONE_LOWER "models/cyberdeck/bones_lower.md3"
#define CD_BONES_DEAD 29 // the "dead1" frame: lying on its back
#define CD_BONES_LIFE 9000
// a flying piece: arcs, bounces off walls and floors, comes to rest, and vanishes after a while
static void CD_BoneThink( gentity_t *ent ) {
vec3_t origin, vel;
trace_t tr;
if ( level.time >= ent->count ) {
G_FreeEntity( ent );
return;
}
ent->nextthink = level.time + 50;
if ( ent->s.pos.trType == TR_STATIONARY ) {
return;
}
BG_EvaluateTrajectory( &ent->s.pos, level.time, origin );
trap_Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ENTITYNUM_NONE, MASK_SOLID );
if ( tr.fraction < 1.0f && !tr.startsolid ) {
float dot;
BG_EvaluateTrajectoryDelta( &ent->s.pos, level.time, vel );
dot = DotProduct( vel, tr.plane.normal );
VectorMA( vel, -2 * dot, tr.plane.normal, vel );
VectorScale( vel, 0.45f, vel );
if ( tr.plane.normal[2] > 0.2f && VectorLength( vel ) < 70 ) {
G_SetOrigin( ent, tr.endpos ); // it comes to rest, upright
ent->s.apos.trType = TR_STATIONARY;
ent->s.apos.trBase[PITCH] = ent->s.apos.trBase[ROLL] = 0;
} else {
VectorCopy( tr.endpos, ent->s.pos.trBase );
VectorCopy( vel, ent->s.pos.trDelta );
ent->s.pos.trTime = level.time;
VectorCopy( tr.endpos, ent->r.currentOrigin );
}
} else {
VectorCopy( origin, ent->r.currentOrigin );
}
trap_LinkEntity( ent );
}
// a still piece of the headless skeleton: model, frame, position and angles as the renderer would pose it
static void CD_BonePiece( const char *model, const vec3_t origin, float pitch, float yaw, float roll ) {
gentity_t *b = G_Spawn();
b->classname = "cd_bones";
b->s.eType = ET_GENERAL;
b->s.modelindex = G_ModelIndex( (char *)model );
b->s.frame = CD_BONES_DEAD;
G_SetOrigin( b, (float *)origin );
VectorSet( b->s.apos.trBase, pitch, yaw, roll );
VectorCopy( b->s.apos.trBase, b->r.currentAngles );
b->think = G_FreeEntity;
b->nextthink = level.time + CD_BONES_LIFE;
trap_LinkEntity( b );
}
void CD_Headshot( gentity_t *victim, gentity_t *killer ) {
gentity_t *skull = G_Spawn();
vec3_t origin, dir, down, torso, legs;
trace_t tr;
float yaw = victim->client->ps.viewangles[YAW], s, c;
// the body: hidden (no gibs), and its own client's view hides it too (STAT_HEALTH at gib level)
victim->takedamage = qfalse;
victim->s.eType = ET_INVISIBLE;
victim->r.contents = 0;
victim->health = GIB_HEALTH - 1;
victim->client->ps.stats[STAT_HEALTH] = victim->health;
// a headless skeleton lying where they fell: the legs on the floor, the torso on the legs' tag_torso
// (offsets and angles from bones/lower.md3 and upper.md3, frame 29), turned to face the victim's way
VectorCopy( victim->r.currentOrigin, legs );
VectorCopy( legs, down );
down[2] -= 512;
trap_Trace( &tr, legs, NULL, NULL, down, victim->s.number, MASK_SOLID );
legs[2] = tr.endpos[2] + 24; // a player's origin sits 24 units above their feet
s = sin( DEG2RAD( yaw ) );
c = cos( DEG2RAD( yaw ) );
torso[0] = legs[0] + c * -7.0f - s * 2.2f;
torso[1] = legs[1] + s * -7.0f + c * 2.2f;
torso[2] = legs[2] - 17.8f;
CD_BonePiece( CD_BONE_LOWER, legs, 0, yaw, 0 );
CD_BonePiece( CD_BONE_UPPER, torso, -88.1f, yaw + 161.2f, 180.0f );
// the skull pops off the neck, spinning, away from the shooter
VectorCopy( victim->r.currentOrigin, origin );
origin[2] += victim->r.maxs[2] - 4;
VectorSubtract( origin, killer->r.currentOrigin, dir );
dir[2] = 0;
VectorNormalize( dir );
skull->classname = "cd_skull";
skull->s.eType = ET_GENERAL;
skull->s.modelindex = G_ModelIndex( CD_BONE_HEAD );
VectorSet( skull->r.mins, -5, -5, -2 );
VectorSet( skull->r.maxs, 5, 5, 8 );
G_SetOrigin( skull, origin );
skull->s.pos.trType = TR_GRAVITY;
skull->s.pos.trTime = level.time;
skull->s.pos.trDelta[0] = dir[0] * 320 + crandom() * 80;
skull->s.pos.trDelta[1] = dir[1] * 320 + crandom() * 80;
skull->s.pos.trDelta[2] = 480 + random() * 160;
skull->s.apos.trType = TR_LINEAR;
skull->s.apos.trTime = level.time;
skull->s.apos.trBase[YAW] = yaw;
VectorSet( skull->s.apos.trDelta, 540 + random() * 360, 720 + random() * 360, 0 );
skull->think = CD_BoneThink;
skull->nextthink = level.time + 50;
skull->count = level.time + CD_BONES_LIFE;
trap_LinkEntity( skull );
trap_SendServerCommand( killer - g_entities, "cp \"^1HEADSHOT\n\"" );
CD_GlobalSound( "sound/player/bones/taunt.wav" );
G_LogPrintf( "Announce: %s got a HEADSHOT on %s\n", killer->client->pers.netname, victim->client->pers.netname );
}
void CD_RunFrame( void ) {
const char *mode;
int i;
// Ghosts: fade back to invisible once the reveal from firing runs out
if ( level.cd_mutator == CD_MUT_GHOSTS ) {
for ( i = 0; i < level.maxclients; i++ ) {
gclient_t *cl = &level.clients[i];
if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR
&& cl->cd_revealUntil && level.time >= cl->cd_revealUntil ) {
cl->cd_revealUntil = 0;
cl->ps.powerups[PW_INVIS] = level.time + CD_FOREVER;
}
}
}
// Halloween: something growls in the dark now and then
if ( level.cd_mutator == CD_MUT_HALLOWEEN && !level.intermissiontime && level.time >= cd_spookNext ) {
static const char *spooks[] = { "sound/world/evil.wav", "sound/world/growl1.wav", "sound/world/growl2.wav",
"sound/world/growl3.wav", "sound/world/demonwind01.wav", "sound/player/bones/taunt.wav" };
if ( cd_spookNext ) {
CD_GlobalSound( spooks[ rand() % ARRAY_LEN( spooks ) ] );
}
cd_spookNext = level.time + 35000 + rand() % 35000;
}
if ( !level.cd_bannerTime || level.time < level.cd_bannerTime || level.intermissiontime ) {
return;
}
level.cd_bannerTime = 0;
if ( g_gametype.integer >= GT_TEAM ) {
mode = g_instagib.integer ? va( "%s ^7// ^1RED ^7vs ^4BLUE", CD_ModeBanner() ) : "^1RED ^7vs ^4BLUE";
} else {
mode = g_instagib.integer ? va( "%s ^7// ^3FREE FOR ALL", CD_ModeBanner() ) : "^3FREE FOR ALL";
}
trap_SendServerCommand( -1, va( "cp \"%s\n\n%s\n\"", mode,
level.cd_mutator ? cd_mutatorBanners[level.cd_mutator] : "^7no mutator -- pure skill" ) );
CD_GlobalSound( "sound/world/1shot_gong.wav" );
}
void CD_ApplySpawn( gentity_t *ent ) {
gclient_t *client = ent->client;
client->cd_streak = 0;
client->cd_multi = 0;
client->cd_revealUntil = 0;
client->cd_pushedTime = 0;
if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
return;
}
if ( level.cd_mutator == CD_MUT_HASTE ) {
client->ps.powerups[PW_HASTE] = level.time + CD_FOREVER;
}
if ( level.cd_mutator == CD_MUT_GHOSTS ) {
client->ps.powerups[PW_INVIS] = level.time + CD_FOREVER;
}
if ( level.cd_juggernaut == client - level.clients ) {
client->ps.powerups[PW_QUAD] = level.time + CD_FOREVER; // the juggernaut glows
client->ps.powerups[PW_REGEN] = level.time + CD_FOREVER; // ...and pulses red
}
}
// hand the juggernaut crown to a client (-1: nobody). The wearer glows and is worth 2 frags.
// announce: the crowning banner and sound (a takedown shows its own combined banner instead).
static void CD_SetJuggernaut( int clientNum, qboolean announce ) {
if ( clientNum == level.cd_juggernaut ) {
return;
}
if ( level.cd_juggernaut >= 0 ) {
level.clients[level.cd_juggernaut].ps.powerups[PW_QUAD] = 0;
level.clients[level.cd_juggernaut].ps.powerups[PW_REGEN] = 0;
}
level.cd_juggernaut = clientNum;
if ( clientNum >= 0 ) {
gclient_t *cl = &level.clients[clientNum];
if ( cl->ps.stats[STAT_HEALTH] > 0 ) {
cl->ps.powerups[PW_QUAD] = level.time + CD_FOREVER; // otherwise CD_ApplySpawn does it
cl->ps.powerups[PW_REGEN] = level.time + CD_FOREVER;
}
if ( announce ) {
trap_SendServerCommand( -1, va( "cp \"^1!! JUGGERNAUT !!\n\n%s\n\n^7worth 2 frags -- hunt them down\n\"", cl->pers.netname ) );
CD_GlobalSound( "sound/feedback/takenlead.wav" );
}
G_LogPrintf( "Announce: %s is the JUGGERNAUT\n", cl->pers.netname );
}
trap_Cvar_Set( "cd_jugg", clientNum >= 0 ? level.clients[clientNum].pers.netname : "" );
}
void CD_UpdateRanks( void ) {
char teams[MAX_CLIENTS + 1];
int i, n = 0;
if ( g_gametype.integer >= GT_TEAM ) {
trap_Cvar_Set( "Score_Red", va( "%i", level.teamScores[TEAM_RED] ) );
trap_Cvar_Set( "Score_Blue", va( "%i", level.teamScores[TEAM_BLUE] ) );
}
// one letter per connected client, in client order (the order getstatus lists players)
for ( i = 0; i < level.maxclients; i++ ) {
gclient_t *cl = &level.clients[i];
if ( cl->pers.connected == CON_DISCONNECTED ) {
continue;
}
teams[n++] = cl->sess.sessionTeam == TEAM_RED ? 'r' : cl->sess.sessionTeam == TEAM_BLUE ? 'b'
: cl->sess.sessionTeam == TEAM_SPECTATOR ? 's' : 'f';
}
teams[n] = 0;
trap_Cvar_Set( "cd_teams", teams );
// juggernaut (FFA): the first clear leader with at least 5 frags gets the crown. After that it only
// moves by slaying its wearer (CD_Frag hands it to the slayer); the leader taking over doesn't.
// If the wearer leaves or spectates, the crown is up for grabs again.
if ( g_gametype.integer >= GT_TEAM || level.cd_mutator == CD_MUT_GUNGAME || level.intermissiontime ) {
return; // (gun game's leader is whoever's furthest up the ladder)
}
if ( level.cd_juggernaut >= 0 ) {
gclient_t *j = &level.clients[level.cd_juggernaut];
if ( j->pers.connected != CON_CONNECTED || j->sess.sessionTeam == TEAM_SPECTATOR ) {
CD_SetJuggernaut( -1, qfalse );
}
}
if ( level.cd_juggernaut < 0 && level.numNonSpectatorClients >= 2 ) {
int a = level.sortedClients[0], b = level.sortedClients[1];
int sa = level.clients[a].ps.persistant[PERS_SCORE], sb = level.clients[b].ps.persistant[PERS_SCORE];
if ( sa >= 5 && sa > sb ) {
CD_SetJuggernaut( a, qtrue );
}
}
}
// ------------------------------------------------------------------ gun game / vampire
static const int cd_gunLadder[CD_GUN_LEVELS] = { WP_RAILGUN, WP_ROCKET_LAUNCHER, WP_LIGHTNING, WP_PLASMAGUN,
WP_SHOTGUN, WP_GRENADE_LAUNCHER, WP_MACHINEGUN, WP_GAUNTLET };
static const char *cd_gunNames[CD_GUN_LEVELS] = { "RAILGUN", "ROCKET LAUNCHER", "LIGHTNING GUN", "PLASMA GUN",
"SHOTGUN", "GRENADE LAUNCHER", "MACHINE GUN", "GAUNTLET" };
static int CD_GunRung( gclient_t *cl ) {
int rung = cl->pers.cd_gunKills / CD_GUN_KILLS;
return rung < CD_GUN_LEVELS ? rung : CD_GUN_LEVELS - 1;
}
int CD_ClientWeapon( gclient_t *cl ) {
if ( level.cd_mutator == CD_MUT_GUNGAME && cl ) {
return cd_gunLadder[ CD_GunRung( cl ) ];
}
return CD_WEAPON();
}
// swap a living player onto their new rung's weapon (they keep the gauntlet, like everyone)
static void CD_GiveGun( gentity_t *ent ) {
gclient_t *cl = ent->client;
int w = CD_ClientWeapon( cl );
cl->ps.stats[STAT_WEAPONS] = ( 1 << WP_GAUNTLET ) | ( 1 << w );
if ( w != WP_GAUNTLET ) {
cl->ps.ammo[w] = 999;
}
cl->ps.weapon = w;
cl->ps.weaponstate = WEAPON_READY;
}
static void CD_GunGameFrag( gentity_t *victim, gentity_t *killer, int mod ) {
gclient_t *k = killer->client, *v = victim->client;
int rung = CD_GunRung( k );
k->pers.cd_gunKills++;
k->ps.persistant[PERS_SCORE] = k->pers.cd_gunKills;
// humiliation: a gauntlet kill knocks the victim down a rung
if ( mod == MOD_GAUNTLET && CD_GunRung( v ) > 0 ) {
v->pers.cd_gunKills = ( CD_GunRung( v ) - 1 ) * CD_GUN_KILLS;
v->ps.persistant[PERS_SCORE] = v->pers.cd_gunKills;
trap_SendServerCommand( v - level.clients, va( "cp \"^1DEMOTED\n\n^7gauntleted back down to the %s\n\"",
cd_gunNames[ CD_GunRung( v ) ] ) );
G_LogPrintf( "Announce: %s was knocked down to the %s\n", v->pers.netname, cd_gunNames[ CD_GunRung( v ) ] );
}
if ( k->pers.cd_gunKills < CD_GUN_TOTAL && CD_GunRung( k ) != rung ) {
CD_GiveGun( killer );
if ( CD_GunRung( k ) == CD_GUN_LEVELS - 1 ) {
trap_SendServerCommand( -1, va( "cp \"%s\n\n^7has the ^3GAUNTLET^7 -- one kill from winning\n\"", k->pers.netname ) );
CD_GlobalSound( "sound/feedback/takenlead.wav" );
G_LogPrintf( "Announce: %s reached the GAUNTLET\n", k->pers.netname );
} else {
trap_SendServerCommand( killer - g_entities, va( "cp \"^3RUNG %i / %i\n\n^7%s\n\"", CD_GunRung( k ) + 1,
CD_GUN_LEVELS, cd_gunNames[ CD_GunRung( k ) ] ) );
}
}
CalculateRanks(); // the winning kill makes the score CD_GUN_TOTAL, the frag limit: CheckExitRules ends it
}
void CD_Vampire( gentity_t *attacker, int dealt ) {
int heal = dealt / 2;
if ( attacker->health <= 0 || heal < 1 ) {
return;
}
attacker->health += heal;
if ( attacker->health > 150 ) {
attacker->health = 150; // over 100 ticks back down, like a mega health
}
attacker->client->ps.stats[STAT_HEALTH] = attacker->health;
}
void CD_Frag( gentity_t *victim, gentity_t *killer, qboolean wasJuggernaut, int mod ) {
static const struct { int n; const char *label; const char *sound; int award; } streaks[] = {
{ 5, "^3KILLING SPREE", "sound/feedback/excellent.wav", EF_AWARD_EXCELLENT },
{ 10, "^1R A M P A G E", "sound/feedback/impressive.wav", EF_AWARD_IMPRESSIVE },
{ 15, "^6U N S T O P P A B L E", "sound/feedback/perfect.wav", EF_AWARD_EXCELLENT },
{ 20, "^5G O D L I K E", "sound/world/xchoir1.wav", EF_AWARD_IMPRESSIVE },
{ 0, NULL, NULL, 0 }
};
int i;
if ( level.cd_mutator == CD_MUT_GUNGAME && !level.warmupTime ) {
CD_GunGameFrag( victim, killer, mod );
}
if ( !CD_Taunt( 'K', killer, victim ) ) { // the killer gloats, or else the victim grumbles
CD_Taunt( 'D', victim, killer );
}
if ( wasJuggernaut ) {
gentity_t *te = G_TempEntity( victim->r.currentOrigin, EV_PLAYER_TELEPORT_IN ); // flash where they fell
te->s.clientNum = victim->s.clientNum;
trap_SendServerCommand( -1, va( "cp \"%s\n\n^7slew the ^1JUGGERNAUT^7 -- and took the crown\n^7worth 2 frags -- hunt them down\n\"",
killer->client->pers.netname ) );
CD_GlobalSound( "sound/feedback/denied.wav" );
CD_Award( killer, EF_AWARD_GAUNTLET );
G_LogPrintf( "Announce: %s took down the JUGGERNAUT %s\n", killer->client->pers.netname,
victim->client->pers.netname );
AddScore( killer, victim->r.currentOrigin, 1 ); // the juggernaut is worth 2
CD_SetJuggernaut( killer->client - level.clients, qfalse ); // ...and the slayer takes the crown
}
killer->client->cd_streak++;
for ( i = 0; streaks[i].n; i++ ) {
if ( killer->client->cd_streak == streaks[i].n ) {
trap_SendServerCommand( -1, va( "cp \"%s\n\n%s\n\n^7%i in a row\n\"", killer->client->pers.netname,
streaks[i].label, streaks[i].n ) );
CD_GlobalSound( streaks[i].sound );
CD_Award( killer, streaks[i].award );
G_LogPrintf( "Announce: %s is on a %s! (%i in a row)\n", killer->client->pers.netname,
streaks[i].label, streaks[i].n );
}
}
if ( level.warmupTime || level.intermissiontime ) {
return; // the warmup's frags don't count
}
// FIRST BLOOD: the match's first kill
if ( !level.cd_firstBlood ) {
level.cd_firstBlood = qtrue;
trap_SendServerCommand( -1, va( "cp \"%s\n\n^1F I R S T B L O O D\n\"", killer->client->pers.netname ) );
CD_GlobalSound( "sound/world/klaxon2.wav" );
G_LogPrintf( "Announce: %s drew FIRST BLOOD\n", killer->client->pers.netname );
}
// multi-kills: kills less than CD_MULTI_WINDOW apart (a rail through two people counts too)
if ( level.time - killer->client->cd_multiTime <= CD_MULTI_WINDOW ) {
killer->client->cd_multi++;
} else {
killer->client->cd_multi = 1;
}
killer->client->cd_multiTime = level.time;
if ( killer->client->cd_multi == 2 ) {
// a double is common in instagib: tell everyone in the feed, but only the killer hears it
gentity_t *te = G_TempEntity( vec3_origin, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex( "sound/feedback/impressive_a.wav" );
te->r.svFlags |= SVF_SINGLECLIENT;
te->r.singleClient = killer->s.number;
trap_SendServerCommand( -1, va( "print \"%s ^3DOUBLE KILL\n\"", killer->client->pers.netname ) );
G_LogPrintf( "Announce: %s got a DOUBLE KILL\n", killer->client->pers.netname );
} else if ( killer->client->cd_multi >= 3 ) {
const char *label = killer->client->cd_multi == 3 ? "TRIPLE KILL" : "MULTI KILL";
trap_SendServerCommand( -1, va( "cp \"%s\n\n^6%s\n\n^7%i kills, back to back\n\"", killer->client->pers.netname,
label, killer->client->cd_multi ) );
CD_GlobalSound( "sound/feedback/voc_holyshit.wav" );
G_LogPrintf( "Announce: %s got a %s\n", killer->client->pers.netname, label );
}
}
// the end of every match: the winner's name, the Q3 victory fanfare and the announcer's
// "<character> wins!" line for their model (FFA), or the winning team (TDM)
void CD_Victory( void ) {
char model[MAX_QPATH], *slash, path[MAX_QPATH];
gclient_t *best = NULL;
fileHandle_t f;
int i;
if ( g_gametype.integer >= GT_TEAM ) {
int red = level.teamScores[TEAM_RED], blue = level.teamScores[TEAM_BLUE];
if ( red == blue ) {
return;
}
trap_SendServerCommand( -1, va( "cp \"%s\n\n^7W I N S\n\"", red > blue ? "^1RED TEAM" : "^4BLUE TEAM" ) );
CD_GlobalSound( "music/win.wav" );
return;
}
for ( i = 0; i < level.numConnectedClients; i++ ) {
gclient_t *cl = &level.clients[ level.sortedClients[i] ];
if ( cl->sess.sessionTeam != TEAM_SPECTATOR ) {
best = cl;
break;
}
}
if ( !best ) {
return;
}
trap_SendServerCommand( -1, va( "cp \"%s\n\n^3W I N S\n\n^7%i frags\n\"", best->pers.netname,
best->ps.persistant[PERS_SCORE] ) );
CD_GlobalSound( "music/win.wav" );
trap_GetUserinfo( best - level.clients, model, sizeof( model ) );
Q_strncpyz( model, Info_ValueForKey( model, "model" ), sizeof( model ) );
if ( ( slash = strchr( model, '/' ) ) != NULL ) {
*slash = 0;
}
Com_sprintf( path, sizeof( path ), "sound/player/announce/%s_wins.wav", Q_strlwr( model ) );
if ( trap_FS_FOpenFile( path, &f, FS_READ ) > 0 ) {
trap_FS_FCloseFile( f );
CD_GlobalSound( path );
}
}
// a fixed skill per bot, so each bot has a consistent level across matches (2 = Bring It On .. 5 = Nightmare!)
float CD_BotSkill( const char *name ) {
unsigned int h = 5381;
for ( ; *name; name++ ) {
int c = *name;
if ( c >= 'A' && c <= 'Z' ) {
c += 'a' - 'A';
}
h = h * 33 + c;
}
return 2 + ( h % 4 );
}