UFO: Alien Invasion
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
common.cpp File Reference

Misc functions used in client and server. More...

#include "../shared/autoptr.h"
#include "common.h"
#include "http.h"
#include "../server/server.h"
#include "../shared/parse.h"
#include "../ports/system.h"
#include <set>
#include <vector>
#include <SDL.h>

Go to the source code of this file.

Data Structures

struct  timer
 
class  CompareScheduleEvent
 
struct  debugLevel_s
 

Macros

#define MAXPRINTMSG   4096
 
#define MAX_NUM_ARGVS   50
 
#define TIMER_CHECK_INTERVAL   100
 
#define TIMER_CHECK_LAG   3
 
#define TIMER_LATENESS_HIGH   200
 
#define TIMER_LATENESS_LOW   50
 
#define TIMER_LATENESS_HISTORY   32
 
#define MACRO_CVAR_ID_LENGTH   6
 

Typedefs

typedef std::multiset
< ScheduleEventPtr,
CompareScheduleEvent
EventPriorityQueue
 
typedef struct debugLevel_s debugLevel_t
 

Functions

static void Schedule_Timer (cvar_t *freq, event_func *func, event_check_func *check, void *data)
 
float Com_GrenadeTarget (const vec3_t from, const vec3_t at, float speed, bool launched, bool rolled, vec3_t v0)
 Calculates parabola-type shot. More...
 
void Com_BeginRedirect (struct net_stream *stream, char *buffer, int buffersize)
 Redirect packets/output from server to client. More...
 
void Com_EndRedirect (void)
 End the redirection of packets/output. More...
 
void Com_vPrintf (const char *fmt, va_list ap)
 
void Com_Printf (const char *const fmt,...)
 
void Com_DPrintf (int level, const char *fmt,...)
 A Com_Printf that only shows up if the "developer" cvar is set. More...
 
void Com_Error (int code, const char *fmt,...)
 
void Com_Drop (void)
 
void Com_BreakIntoDebugger (void)
 
void Com_Quit (void)
 
int Com_ServerState (void)
 Check whether we are the server or have a singleplayer tactical mission. More...
 
void Com_SetServerState (int state)
 
int Com_Argc (void)
 Returns the script commandline argument count. More...
 
const char * Com_Argv (int arg)
 Returns an argument of script commandline. More...
 
void Com_ClearArgv (int arg)
 Reset com_argv entry to empty string. More...
 
static void Com_InitArgv (int argc, char **argv)
 
const char * Com_MacroExpandString (const char *text)
 Expands strings with cvar values that are dereferenced by a '*cvar'. More...
 
void Com_UploadCrashDump (const char *crashDumpFile)
 
bool Com_ConsoleCompleteCommand (const char *s, char *target, size_t bufSize, uint32_t *pos, uint32_t offset)
 Console completion for command and variables. More...
 
void Com_SetGameType (void)
 
static void Com_GameTypeList_f (void)
 
bool Com_CheckConfigStringIndex (int index)
 
static void Com_DeveloperSet_f (void)
 
static bool Com_CvarCheckMaxFPS (cvar_t *cvar)
 Watches that the cvar cl_maxfps is never getting lower than 10. More...
 
void Com_WriteConfigToFile (const char *filename)
 
void Com_SetRandomSeed (unsigned int seed)
 
const char * Com_ByteToBinary (byte x)
 
const char * Com_UnsignedIntToBinary (uint32_t x)
 
static void Com_WriteConfig_f (void)
 Write the config file to a specific name. More...
 
static void Cbuf_Execute_timer (int now, void *data)
 
void Qcommon_SetPrintFunction (vPrintfPtr_t func)
 
vPrintfPtr_t Qcommon_GetPrintFunction (void)
 
void Qcommon_Init (int argc, char **argv)
 Init function. More...
 
void Com_ReadFromPipe (void)
 Read whatever is in com_pipefile, if anything, and execute it. More...
 
static void tick_timer (int now, void *data)
 
ScheduleEventPtr Schedule_Event (int when, event_func *func, event_check_func *check, event_clean_func *clean, void *data)
 Schedules an event to run on or after the given time, and when its check function returns true. More...
 
static size_t Delay_Events (int now, EventPriorityQueue::iterator i)
 Delay the following events and return the amount of events delayed. More...
 
ScheduleEventPtr Dequeue_Event (int now)
 Finds and returns the first event in the event_queue that is due. If the event has a check function, we check to see if the event can be run now, and skip it if not (even if it is due). More...
 
int CL_FilterEventQueue (event_filter *filter)
 Filters every event in the queue using the given function. Keeps all events for which the function returns true. More...
 
static bool Event_FilterAll (int when, event_func *func, event_check_func *check, void *data)
 Eventfilter that filter out all events. More...
 
void Qcommon_Frame (void)
 This is the function that is called directly from main() More...
 
void Qcommon_Shutdown (void)
 

Variables

csi_t csi
 
static int com_argc
 
static const char * com_argv [MAX_NUM_ARGVS+1]
 
static vPrintfPtr_t vPrintfPtr = Com_vPrintf
 
cvar_tdeveloper
 
cvar_thttp_proxy
 
cvar_thttp_timeout
 
static const char * consoleLogName = "ufoconsole.log"
 
static cvar_tlogfile_active
 
cvar_tsv_dedicated
 
static cvar_tcl_maxfps
 
cvar_ts_language
 
cvar_tsv_gametype
 
cvar_tmasterserver_url
 
cvar_tport
 
cvar_tsys_priority
 
cvar_tsys_affinity
 
cvar_tsys_os
 
cvar_thwclass
 
static cvar_tuploadcrashdump
 
static qFILE logfile
 
static qFILE pipefile
 
memPool_tcom_aliasSysPool
 
memPool_tcom_cmdSysPool
 
memPool_tcom_cmodelSysPool
 
memPool_tcom_cvarSysPool
 
memPool_tcom_fileSysPool
 
memPool_tcom_genericPool
 
memPool_tcom_networkPool
 
static EventPriorityQueue eventQueue
 
static char * rd_buffer
 
static unsigned int rd_buffersize
 
static struct net_streamrd_stream
 
static const debugLevel_t debugLevels []
 

Detailed Description

Misc functions used in client and server.

Definition in file common.cpp.

Macro Definition Documentation

#define MACRO_CVAR_ID_LENGTH   6

Definition at line 600 of file common.cpp.

Referenced by Com_MacroExpandString().

#define MAX_NUM_ARGVS   50

Definition at line 37 of file common.cpp.

Referenced by Com_InitArgv().

#define MAXPRINTMSG   4096

Definition at line 36 of file common.cpp.

Referenced by Com_BeginRedirect(), Com_Error(), and Com_vPrintf().

#define TIMER_CHECK_INTERVAL   100

Definition at line 76 of file common.cpp.

Referenced by Schedule_Timer(), and tick_timer().

#define TIMER_CHECK_LAG   3

Definition at line 77 of file common.cpp.

Referenced by tick_timer().

#define TIMER_LATENESS_HIGH   200

Definition at line 78 of file common.cpp.

Referenced by tick_timer().

#define TIMER_LATENESS_HISTORY   32

Definition at line 80 of file common.cpp.

Referenced by Schedule_Timer(), and tick_timer().

#define TIMER_LATENESS_LOW   50

Definition at line 79 of file common.cpp.

Referenced by tick_timer().

Typedef Documentation

typedef struct debugLevel_s debugLevel_t

Definition at line 103 of file common.cpp.

Function Documentation

static void Cbuf_Execute_timer ( int  now,
void data 
)
static

Definition at line 1056 of file common.cpp.

References Cbuf_Execute().

Referenced by Qcommon_Init().

int CL_FilterEventQueue ( event_filter filter)

Filters every event in the queue using the given function. Keeps all events for which the function returns true.

Parameters
filterPointer to the filter function. When called with event info, it should return true if the event is to be kept.

Definition at line 1446 of file common.cpp.

References eventQueue, and i.

Referenced by CL_ClearBattlescapeEvents(), and Qcommon_Frame().

int Com_Argc ( void  )

Returns the script commandline argument count.

Definition at line 560 of file common.cpp.

References com_argc.

Referenced by Cbuf_AddEarlyCommands(), and Cbuf_AddLateCommands().

const char* Com_Argv ( int  arg)

Returns an argument of script commandline.

Definition at line 568 of file common.cpp.

References com_argc, and com_argv.

Referenced by Cbuf_AddEarlyCommands(), and Cbuf_AddLateCommands().

void Com_BeginRedirect ( struct net_stream stream,
char *  buffer,
int  buffersize 
)

Redirect packets/output from server to client.

See also
Com_EndRedirect

This is used to redirect printf outputs for rcon commands

Definition at line 308 of file common.cpp.

References Com_Error(), ERR_DROP, MAXPRINTMSG, rd_buffer, and rd_buffersize.

Referenced by SVC_RemoteCommand().

void Com_BreakIntoDebugger ( void  )

Definition at line 470 of file common.cpp.

References buttons, lengthof, OBJZERO, and Sys_Breakpoint().

Referenced by Sys_Backtrace(), and Sys_Error().

const char* Com_ByteToBinary ( byte  x)

Definition at line 1005 of file common.cpp.

Referenced by NET_WriteByte(), NET_WriteChar(), and TEST_F().

bool Com_CheckConfigStringIndex ( int  index)
Parameters
[in]indexThe index of the config string array
Note
Some config strings are using one value over multiple config string slots. These may not be accessed directly.

Definition at line 860 of file common.cpp.

References CS_MODELS, CS_POSITIONS, CS_TILES, and MAX_CONFIGSTRINGS.

Referenced by CL_GetConfigString(), CL_SetConfigString(), SV_Configstring(), SV_GetConfigString(), SV_GetConfigStringLength(), and SV_SetConfigString().

void Com_ClearArgv ( int  arg)

Reset com_argv entry to empty string.

Parameters
[in]argWhich argument in com_argv
See also
Com_InitArgv

Definition at line 580 of file common.cpp.

References com_argc, and com_argv.

Referenced by Cbuf_AddEarlyCommands().

bool Com_ConsoleCompleteCommand ( const char *  s,
char *  target,
size_t  bufSize,
uint32_t *  pos,
uint32_t  offset 
)

Console completion for command and variables.

See also
Key_CompleteCommand
Cmd_CompleteCommand
Cvar_CompleteVariable
Parameters
[in]sThe string to complete
[out]targetThe target buffer of the completed command/cvar
[in]bufSizethe target buffer size - might not be bigger than MAXCMDLINE
[out]posThe position in the buffer after command completion
[in]offsetThe input buffer position to put the completed command to

Definition at line 717 of file common.cpp.

References Cmd_CompleteCommand(), Cmd_CompleteCommandParameters(), Com_Printf(), Cvar_CompleteVariable(), MAX_QPATH, MAXCMDLINE, Q_strcat(), and Q_strncpyz().

Referenced by Key_Console(), Sys_ConsoleEditProc(), and Sys_ConsoleInput().

static bool Com_CvarCheckMaxFPS ( cvar_t cvar)
static

Watches that the cvar cl_maxfps is never getting lower than 10.

Definition at line 971 of file common.cpp.

References Cvar_AssertValue().

Referenced by Qcommon_Init().

static void Com_DeveloperSet_f ( void  )
static
void Com_DPrintf ( int  level,
const char *  fmt,
  ... 
)

A Com_Printf that only shows up if the "developer" cvar is set.

Definition at line 398 of file common.cpp.

References cvar_s::integer, and vPrintfPtr.

Referenced by _wrap_dprint(), InventoryInterface::addInvList(), InventoryInterface::addToInventory(), AI_PrepBestAction(), Inventory::canHoldItem(), Cbuf_AddText(), CL_ActorClientAction(), CL_ActorDoShoot(), CL_ActorPlaySound(), CL_ActorReservedTUs(), CL_ActorResetClientAction(), CL_ActorUse(), CL_ActorUse_f(), CL_AddEdict(), CL_AddMapParticle(), CL_BlockBattlescapeEvents(), CL_CameraAppear(), CL_CheckDefault(), CL_ConnectionlessPacket(), CL_DelayBattlescapeEvent(), CL_EntAppear(), CL_EntPerish(), CL_ExecuteBattlescapeEvent(), CL_Explode(), CL_GetEventTime(), CL_GetLocaleID(), CL_GetNextTime(), CL_Init(), CL_InvAmmo(), CL_LanguageInit(), CL_LanguageTest(), CL_LanguageTryToSet(), CL_ParseConfigString(), CL_ParseEvent(), CL_ParseResults(), CL_ParseServerData(), CL_ParseServerMessage(), CL_ParticleFunction(), CL_ParticleSpawn(), CL_SetClientState(), CL_SoundEvent(), CL_ViewPrecacheModels(), CM_AddMapTile(), CM_LoadMap(), Cmd_AddCommand(), Cmd_Close_f(), Cmd_Open_f(), Cmd_vExecuteString(), CMod_LoadRouting(), CMod_ValidateLump(), Com_AddObjectLinks(), Com_GetMapDefinitionByID(), Com_GiveName(), Com_ParseImplant(), Com_ParseItem(), Com_ParseMapDefinition(), Com_ParseTeam(), Com_SetServerState(), Door_Use(), uiTimerNode::draw(), InventoryInterface::EquipActorNormal(), Inventory::findSpace(), G_ClientTeamInfo(), G_ClientUserinfoChanged(), G_Damage(), G_GetNextActiveTeam(), G_GetTeam(), G_ShootSingle(), G_TouchEdicts(), GAME_GetImportData(), GAME_GetTeamFileName(), GAME_LoadGame(), GAME_MP_ProcessPingReply(), GAME_MP_QueryMasterServerThread(), GAME_NetSendItem(), teamDef_s::getActorSound(), BodyData::getHitBodyPart(), BodyData::getRandomBodyPart(), InventoryInterface::GetUsedSlots(), HUD_DisplayActions(), IN_StartupJoystick(), INVSH_CheckShapeCollision(), Irc_Client_CmdPrivmsg(), Irc_Input_Activate_f(), Irc_Logic_AddChannelName(), Irc_Proto_Msg(), Irc_Proto_ProcessServerMsg(), Key_SetBinding(), LE_AddAmbientSound(), LE_Cleanup(), LE_PlaySoundFileAndParticleForSurface(), M_Change_f(), M_RandomTrack_f(), InventoryInterface::moveInInventory(), NET_DatagramFindFreeSocket(), NET_StreamClose(), NET_StreamGetFree(), NET_Wait(), NET_WriteByte(), NET_WriteChar(), NET_WriteLong(), NET_WriteRawString(), NET_WriteShort(), NET_WriteString(), GAMECvarListener::onGameModeChange(), GAMECmdListener::onGameModeChange(), uiVScrollbarNode::onLoaded(), uiImageNode::onLoaded(), InventoryInterface::PackAmmoAndWeapon(), R_AddLight(), R_AddStaticLight(), R_BindColorAttachments(), R_GenerateTriangleSoup_(), R_LoadMaterials(), R_LoadObjModelLine(), R_LoadShader(), R_ModLoadEdges(), R_ModLoadLeafs(), R_ModLoadNodes(), R_ModLoadPlanes(), R_ModLoadSubmodels(), R_ModLoadSurfaces(), R_ModLoadSurfedges(), R_ModLoadTexinfo(), R_ModLoadVertexes(), R_ParseStage(), R_ProgramVariable(), R_SetupWorldModel(), R_SortSurfacesArrays(), InventoryInterface::removeFromInventory(), InventoryInterface::removeInvList(), S_PlaySample(), SEQ_ExecuteModel(), SEQ_ExecuteMusic(), SEQ_ExecutePrecache(), SetWorkingDirectory(), SP_func_breakable(), SV_AddEvent(), SV_AssembleMap_(), SV_Begin_f(), SV_ClipMoveToEntities(), SV_ConnectionlessPacket(), SV_DoMapAssemble(), SV_ExecuteClientMessage(), SV_ExecuteUserCommand(), SV_GetCvarToken(), SV_LoadGame(), SV_Map(), SV_MapcycleAdd(), SV_New_f(), SV_NextMapcycle(), SV_QueueEvent(), SV_ServerCommand_f(), SV_SetClientState(), SV_StartMatch_f(), SV_UserinfoChanged(), SVC_DirectConnect(), SVC_Info(), SVC_RemoteCommand(), SVC_Status(), SVC_TeamInfo(), tick_timer(), UI_ContainerNodeAutoPlace(), UI_CreateControl(), UI_ParseFont(), UI_ParseNode(), UI_ParseUIModel(), UI_TextScrollEnd(), WEB_AuthResponse(), and WEB_ListCGameFilesCallback().

void Com_Drop ( void  )

Definition at line 465 of file common.cpp.

Referenced by Com_Error(), and GAME_GetImportData().

void Com_EndRedirect ( void  )

End the redirection of packets/output.

See also
Com_BeginRedirect

Definition at line 325 of file common.cpp.

References NET_OOB_Printf(), rd_buffer, rd_buffersize, and SV_CMD_PRINT.

Referenced by SVC_RemoteCommand().

void Com_Error ( int  code,
const char *  fmt,
  ... 
)
Note
Both client and server can use this, and it will do the appropriate things.

Definition at line 417 of file common.cpp.

References CL_Drop(), CL_Shutdown(), Com_Drop(), Com_Printf(), ERR_DISCONNECT, ERR_DROP, qFILE_s::f, FS_CloseFile(), FS_Gamedir(), FS_RemoveFile(), MAXPRINTMSG, qFILE_s::name, NET_Wait(), Q_vsnprintf(), Qcommon_Shutdown(), SV_Shutdown(), Sys_Backtrace(), Sys_Error(), and va().

Referenced by _LE_NotFoundError(), _wrap_error(), uiBox_t::alignBox(), BEP_Evaluate(), CIN_ROQ_DecodeInfo(), CL_ActorAppear(), CL_ActorDie(), CL_ActorDoMove(), CL_ActorDoMoveTime(), CL_ActorDoShoot(), CL_ActorDoTurn(), CL_ActorGetMuzzle(), CL_ActorRevitalised(), CL_ActorSelect(), CL_ActorStartShoot(), CL_AddActor(), CL_AddBrushModel(), CL_BattlescapeSearchAtGridPos(), CL_CanMultiplayerStart(), CL_DoorClose(), CL_DoorOpen(), CL_ExecuteBattlescapeEvent(), CL_FinishHTTPDownload(), CL_GetConfigString(), CL_GetEvent(), CL_GetHitProbability(), CL_HullForEntity(), CL_InvAdd(), CL_InvDel(), CL_NetReceiveItem(), CL_ParseActorSkin(), CL_ParseEvent(), CL_ParseLanguages(), CL_ParseMapParticle(), CL_ParsePtlCmds(), CL_ParseResults(), CL_ParseSequence(), CL_ParseServerData(), CL_ParseServerMessage(), CL_ParticleFunction(), CL_ParticleGetArt(), CL_ParticleLoadArt(), CL_ParticleSpawnTimed(), CL_SendCommand(), CL_SetClientState(), CL_SetConfigString(), CL_SetHTTPServer(), CL_SetRatioFilter_f(), CL_SpawnParseEntitystring(), CL_ViewLoadMedia(), CM_AddMapTile(), CM_EntCompleteBoxTrace(), CM_EntTestLine(), CM_EntTestLineDM(), CM_InitBoxHull(), CM_InlineModel(), CM_LoadMap(), CMod_LoadBrushSides(), CMod_LoadEntityString(), CMod_LoadLeafs(), CMod_LoadRouting(), CMod_ValidateLump(), Com_BeginRedirect(), Com_GetCharacterValues(), Com_GetGender(), Com_InitArgv(), Com_ParseActorModels(), Com_ParseActorNames(), Com_ParseBodyPart(), Com_ParseEquipment(), Com_ParseTeam(), uiTextNode::doLayout(), GAME_AppendTeamMember(), GAME_ChangeEquip(), GAME_GenerateTeam(), GAME_GetCGameAPI(), GAME_GetCharacter(), GAME_GetImportData(), GAME_LoadInventory(), GAME_NetSendCharacter(), HTTP_ResolvURL(), INV_GetEquipmentDefinitionByID(), Key_Event(), LE_Add(), LE_DoEndPathMove(), LE_GetClipModel(), LE_GetDrawModel(), LE_Lock(), LE_PlaceItem(), LE_Unlock(), LET_StartIdle(), LM_AddModel(), LM_AddToSceneOrder(), LMT_Init(), M_ParseMusic(), MD2GLCmdsRemove(), MD2HeaderCheck(), NET_DatagramBroadcast(), NET_Init(), NET_ReadDir(), NET_SkipFormat(), NET_vReadFormat(), NET_vWriteFormat(), uiText2Node::onLoaded(), R_AddEntity(), R_AliasModelState(), R_AllocModelSlot(), R_CalcTransform(), R_CreateSurfaceLightmap(), R_Draw3DGlobe(), R_DrawFlatGeoscape(), R_DrawInitLocal(), R_EnforceVersion(), R_FindImage(), R_FindModel(), R_FontAnalyze(), R_FontInit(), R_GetEntityLists(), R_GetFont(), R_GetFreeEntity(), R_GetFreeFBOTexture(), R_GetModel(), R_GetSpriteVectors(), R_InitExtensions(), R_InitializeShader(), R_InitImages(), R_LoadImage(), R_LoadImageData(), R_LoadModel(), R_LoadModelAsync(), R_LoadObjModel(), R_LoadObjModelFace(), R_LoadObjModelLine(), R_ModAddMapTile(), R_ModBeginLoading(), R_ModCalcUniqueNormalsAndTangents(), R_ModLoadAliasMD2Mesh(), R_ModLoadAliasMD2MeshIndexed(), R_ModLoadAliasMD2MeshUnindexed(), R_ModLoadAliasMD2Model(), R_ModLoadAliasMD3Model(), R_ModLoadAnims(), R_ModLoadEdges(), R_ModLoadLeafs(), R_ModLoadMDX(), R_ModLoadNodes(), R_ModLoadNormals(), R_ModLoadPlanes(), R_ModLoadSubmodels(), R_ModLoadSurfaces(), R_ModLoadSurfedges(), R_ModLoadTags(), R_ModLoadTexinfo(), R_ModLoadVertexes(), R_PreprocessShaderR(), R_SetBlendMode(), R_SetupSubmodels(), R_SoftenTexture(), R_SortSurfacesArrays_(), R_UploadData(), R_VerifyDriver(), Rimp_Init(), SEQ_ExecuteModel(), SEQ_ExecuteObj2D(), SP_misc_model(), SV_AddEvent(), SV_AddMapTiles(), SV_AddTile(), SV_AssembleMap_(), SV_CreateWorldSector(), SV_error(), SV_GetConfigString(), SV_GetConfigStringLength(), SV_GetCvarToken(), SV_GetGameAPI(), SV_GetServerDataForEdict(), SV_GetTileFromTileSet(), SV_GetTilesFromTileSet(), SV_HullForEntity(), SV_InitGameProgs(), SV_LoadModelAABB(), SV_ParseAssembly(), SV_ParseMapTileSet(), SV_ParseUMP(), SV_QueueEvent(), SV_SetConfigString(), SZ_GetSpace(), tileMask(), TR_BoxTrace(), TR_BuildTracingNode_r(), UI_AllocNodeWithoutNew(), UI_AllocStaticAction(), UI_AllocStaticColor(), UI_AllocStaticFloat(), UI_AllocStaticKeyBinding(), UI_AllocStaticSprite(), UI_AllocStaticString(), UI_AllocTimer(), UI_BuildRadarImageList(), UI_CreateWindow(), UI_DrawModelNode(), UI_DrawString(), UI_ExecuteAction(), UI_ExecuteSetAction(), UI_GetBooleanFromExpression(), UI_GetFloatFromExpression(), UI_GetNodeAbsPos(), UI_GetNodeScreenPos(), UI_GetStringFromExpression(), UI_ImageAlignBoxInBox(), UI_InitializeNodeBehaviour(), UI_InitNodes(), UI_InsertComponent(), UI_InsertWindow(), UI_NodeAbsoluteToRelativePos(), UI_NodeSetPropertyFromRAW(), UI_ParseAndLoadLuaScript(), UI_ParseComponent(), UI_ParseValueExpression(), UI_ParseWindow(), UI_PoolAllocAction(), UI_PopupButton(), UI_PopupList(), UI_RegisterFont(), UI_RegisterNodePropertyPosSize_(), UI_ReleaseVariable(), UI_SetKeyBindingEx(), and UI_SetOneButton().

static void Com_GameTypeList_f ( void  )
static
float Com_GrenadeTarget ( const vec3_t  from,
const vec3_t  at,
float  speed,
bool  launched,
bool  rolled,
vec3_t  v0 
)

Calculates parabola-type shot.

Grenade Aiming Maths

There are two possibilities when aiming: either we can reach the target at maximum speed or we can't. If we can reach it we would like to reach it with as flat a trajectory as possible. To do this we calculate the angle to hit the target with the projectile traveling at the maximum allowed velocity.

However, if we can't reach it then we'd like the aiming curve to use the smallest possible velocity that would have reached the target.

let d = horizontal distance to target h = vertical distance to target g = gravity v = launch velocity vx = horizontal component of launch velocity vy = vertical component of launch velocity alpha = launch angle t = time

Then using the laws of linear motion and some trig

d = vx * t h = vy * t - 1/2 * g * t^2 vx = v * cos(alpha) vy = v * sin(alpha)

and some trig identities

2*cos^2(x) = 1 + cos(2*x) 2*sin(x)*cos(x) = sin(2*x) a*cos(x) + b*sin(x) = sqrt(a^2 + b^2) * cos(x - atan2(b, a))

it is possible to show that:

alpha = 0.5 * (atan2(d, -h) - theta)

where / 2 2 \ | v h + g d | | -----------— | theta = acos | ________ | | 2 / 2 2 | \ v \/ h + d /

Thus we can calculate the desired aiming angle for any given velocity.

With some more rearrangement we can show:

          ________________________
         /           2
        /         g d

v = / ---------------------— / ________ / / 2 2 \/ \/ h + d cos(theta) - h

Which we can also write as:


/ a f(theta) = / -------------— \/ b cos(theta) - c

where a = g*d^2 b = sqrt(h*h+d*d) c = h

We can imagine a graph of launch velocity versus launch angle. When the angle is near 0 degrees (i.e. totally flat) more and more velocity is needed. Similarly as the angle gets closer and closer to 90 degrees.

Somewhere in the middle is the minimum velocity that we could possibly hit the target with and the 'optimum' angle to fire at. Note that when h = 0 the optimum angle is 45 degrees. We want to find the minimum velocity so we need to take the derivative of f (which I suggest doing with an algebra system!).

f'(theta) = a * b * sin(theta) / junk

the junk is unimportant because we're just going to set f'(theta) = 0 and multiply it out anyway.

0 = a * b * sin(theta)

Neither a nor b can be 0 as long as d does not equal 0 (which is a degenerate case). Thus if we solve for theta we get 'sin(theta) = 0', thus 'theta = 0'. If we recall that:

alpha = 0.5 * (atan2(d, -h) - theta)

then we get our 'optimum' firing angle alpha as

alpha = 1/2 * atan2(d, -h)

and if we substitute back into our equation for v and we get

          _______________
         /        2
        /      g d

vmin = / ------------— / ________ / / 2 2 \/ \/ h + d - h

as the minimum launch velocity for that angle.

Parameters
[in]fromStarting position for calculations.
[in]atEnding position for calculations.
[in]speedLaunch velocity.
[in]launchedSet to true for grenade launchers.
[in]rolledSet to true for "roll" type shoot.
[in,out]v0The velocity vector
Todo:

refactor and move me

Com_GrenadeTarget() is called from CL_TargetingGrenade() with speed param as (fireDef_s) fd->range (gi.GrenadeTarget, too), while it is being used here for speed calculations - a bug or just misleading documentation?

See also
CL_TargetingGrenade

Definition at line 231 of file common.cpp.

References DIST_EPSILON, GRAVITY, len, torad, v, VectorLength(), VectorNormalizeFast(), VectorScale, and VectorSubtract.

Referenced by CL_TargetingGrenade(), and SV_InitGameProgs().

static void Com_InitArgv ( int  argc,
char **  argv 
)
static

Definition at line 587 of file common.cpp.

References com_argc, com_argv, Com_Error(), ERR_FATAL, i, MAX_NUM_ARGVS, and MAX_TOKEN_CHARS.

Referenced by Qcommon_Init().

const char* Com_MacroExpandString ( const char *  text)

Expands strings with cvar values that are dereferenced by a '*cvar'.

Note
There is an overflow check for cvars that also contain a '*cvar'
See also
Cmd_TokenizeString
UI_GetReferenceString

Definition at line 607 of file common.cpp.

References Com_Parse(), Com_Printf(), count, Cvar_GetString(), i, len, MACRO_CVAR_ID_LENGTH, MAX_STRING_CHARS, OBJZERO, and Q_strncpyz().

Referenced by Cmd_TokenizeString(), and UI_GetReferenceString().

void Com_Printf ( const char *const  fmt,
  ... 
)

Definition at line 386 of file common.cpp.

References vPrintfPtr.

Referenced by _Mem_CreatePool(), _wrap_print(), ReactionFireTargets::add(), AngleToDir(), ASE_Process(), BEP_Evaluate(), BrushlistCalcStats(), BuildFacelights(), BuildLights(), Cbuf_AddText(), Check_SidesOverlap(), Check_Stats(), CheckNodraws(), CheckZFighting(), CHRSH_ApplyImplant(), CIN_OGM_OpenCinematic(), CIN_OpenCinematic(), CIN_ROQ_CloseCinematic(), CIN_ROQ_DecodeChunk(), CIN_ROQ_OpenCinematic(), CL_ActorAdd(), CL_ActorAddToTeamList(), CL_ActorAppear(), CL_ActorGetSkillString(), CL_ActorInjuryModifier(), CL_ActorSelect_f(), CL_ActorStartShoot(), CL_ActorStateChange(), CL_ActorStats(), CL_ActorWound(), CL_AddMapParticle(), CL_CamSetAngles_f(), CL_CamSetZoom_f(), CL_CanMultiplayerStart(), CL_CheckAndQueueDownload(), CL_CheckOrDownloadFile(), CL_CompleteRecalcRouting(), CL_Connect(), CL_ConnectionlessPacket(), CL_Disconnect(), CL_DoEndRound(), CL_EntPerish(), CL_Env_f(), CL_ExecuteCallback(), CL_FilterBattlescapeEvents(), CL_FinishHTTPDownload(), CL_ForwardToServer_f(), CL_FreeClientStream(), CL_GetStepTime(), CL_GetTipOfTheDay_f(), CL_LanguageInit(), CL_LanguageTryToSet(), CL_OpenURL_f(), CL_ParseLanguages(), CL_ParseMessageID(), CL_ParseMessageIDs(), CL_ParseParticle(), CL_ParsePtlCmds(), CL_ParseSequence(), CL_ParseServerMessage(), CL_ParseTipOfTheDay(), CL_ParticleAppear(), CL_ParticleLoadArt(), CL_ParticleSpawn(), CL_ParticleSpawnTimed(), CL_PrecacheCharacterModels(), CL_PressKey_f(), CL_Reconnect(), CL_RegisterCallback(), CL_RequestNextDownload(), CL_Reset(), CL_RunHTTPDownloads(), CL_RunMapParticles(), CL_SetRatioFilter_f(), CL_ShowConfigstrings_f(), CL_StartGame(), CL_StartHTTPDownload(), CL_UserInfo_f(), CM_GetVisibility(), Cmd_AddCommand(), Cmd_Alias_f(), Cmd_CompleteCommand(), Cmd_CompleteExecCommand(), Cmd_Echo_f(), Cmd_Exec_f(), Cmd_ForwardToServer(), Cmd_GetUserdata(), Cmd_Help_f(), Cmd_List_f(), Cmd_RemoveCommand(), Cmd_TableCheck(), Cmd_vExecuteString(), CMod_RerouteMap(), Com_ConsoleCompleteCommand(), Com_DeveloperSet_f(), Com_EParse(), Com_EParseValue(), Com_Error(), Com_GameTypeList_f(), Com_GetBodyTemplateByID(), Com_GetCharacterTemplateByID(), Com_GetNameListByID(), Com_GetTeamDefinitionByID(), Com_GetUGVByID(), Com_GiveModel(), Com_MacroExpandString(), Com_ParseActorModels(), Com_ParseActorNames(), Com_ParseActorSounds(), Com_ParseAircraftNames(), Com_ParseArmourOrResistance(), Com_ParseBlock(), Com_ParseBlockToken(), Com_ParseBodyPart(), Com_ParseBodyTemplate(), Com_ParseCharacterTemplate(), Com_ParseDamageTypes(), Com_ParseEquipment(), Com_ParseFire(), Com_ParseFireDefinition(), Com_ParseFireEffect(), Com_ParseGameTypes(), Com_ParseImplant(), Com_ParseInventory(), Com_ParseItem(), Com_ParseItemEffect(), Com_ParseList(), Com_ParseMapDefinition(), Com_ParseObjDefEffect(), Com_ParseScripts(), Com_ParseTeam(), Com_ParseTerrain(), Com_ParseTerrainDefinition(), Com_ParseUGVs(), Com_ParseValue(), Com_RegisterConstInt(), Com_SetGameType(), Com_SetValue(), Com_ValueToStr(), Com_WriteConfig_f(), Com_WriteConfigToFile(), CompareAttributes(), Con_Init(), Con_SaveConsoleHistory(), Cvar_Add_f(), Cvar_AssertValue(), Cvar_Command(), Cvar_CompleteVariable(), Cvar_Copy_f(), Cvar_Define_f(), Cvar_Del_f(), Cvar_Delete(), Cvar_FixCheatVars(), Cvar_Get(), Cvar_List_f(), Cvar_Mod_f(), Cvar_RegisterChangeListener(), Cvar_Set2(), Cvar_Set_f(), Cvar_SetCheckFunction(), Cvar_SetOld_f(), Cvar_Switch_f(), Cvar_UnRegisterChangeListener(), do_accept(), uiPanelNode::doLayout(), uiModelNode::doLayout(), uiTextNode::doLayout(), uiTextListNode::draw(), uiBarNode::draw(), uiSelectBoxNode::drawOverWindow(), InventoryInterface::EquipActor(), ExportLightmap(), ExportLightmaps(), FS_AddGameDirectory(), FS_CopyFile(), FS_CreateOpenPipeFile(), FS_GetFileData(), FS_GetHomeDirectory(), FS_GetMaps(), FS_InitFilesystem(), FS_LoadPackFile(), FS_NextFileFromFileList(), FS_OpenFile(), FS_RemoveFile(), FS_RestartFilesystem(), FS_Shutdown(), FS_Write(), FS_WriteFile(), G_ActorModifyCounters(), G_ClientConnect(), G_ClientEndRound(), G_ClientReadInventory(), G_ClientTeamInfo(), G_CompleteRecalcRouting(), G_MissionThink(), G_SpawnEntities(), GAME_ActorSelect_f(), GAME_AutoTeam_f(), GAME_EndBattlescape(), GAME_GetCGameAPI(), GAME_GetImportData(), GAME_InitUIData(), GAME_LoadCharacter(), GAME_LoadGame(), GAME_LoadInventory(), GAME_LoadItem(), GAME_LoadTeam(), GAME_LoadTeam_f(), GAME_MP_Rcon_f(), GAME_ParseModes(), GAME_SaveTeam(), GAME_SaveTeam_f(), GAME_SetMode(), GAME_SetMode_f(), GAME_SpawnSoldiers(), GAME_TeamDelete_f(), GAME_TeamSlotComments_f(), GAME_ToggleActorForTeam_f(), GAME_UnloadGame(), GenerateFootstepList(), GenerateMaterialFile(), GetUMPName(), Grid_PosToVec(), Grid_RecalcRouting(), HTTP_ExtractComponents(), HTTP_GetURLInternal(), HTTP_PutFile(), HUD_DisplayActions_f(), HUD_DisplayFiremodes_f(), HUD_DisplayImpossibleReaction(), HUD_ExecuteAction_f(), HUD_FireWeapon_f(), HUD_RemainingTUs_f(), HUD_SelectReactionFiremode_f(), HUD_ShotReserve_f(), IN_EventEnqueue(), IN_Frame(), IN_Init(), IN_KeyDown(), IN_PrintKey(), IN_StartupJoystick(), Info_Print(), Info_SetValueForKey(), INV_EquipmentDefSanityCheck(), INV_ItemMatchesFilter(), INV_UpdateActorLoad_f(), INV_UpdateObject_f(), INVSH_CheckShape(), INVSH_GetImplantByID(), INVSH_GetImplantForObjDef(), INVSH_GetItemByID(), INVSH_ShapeSetBit(), Irc_AppendToBuffer(), Irc_Client_CmdPrivmsg(), Irc_Client_Invite_f(), Irc_Client_Join(), Irc_Client_Join_f(), Irc_Client_Kick_f(), Irc_Client_Mode_f(), Irc_Client_Msg_f(), Irc_Client_Names_f(), Irc_Client_Part_f(), Irc_Client_PrivMsg_f(), Irc_Client_Topic_f(), Irc_Client_Who_f(), Irc_Client_Whois_f(), Irc_Client_Whowas_f(), Irc_Connect_f(), Irc_GetExternalIP(), Irc_Logic_Connect(), Irc_Logic_Disconnect(), Irc_Proto_Enqueue(), Irc_Proto_Join(), Irc_Proto_PollServerMsg(), Irc_Proto_ProcessServerMsg(), Key_Bind_f(), Key_Bindlist_f(), Key_CompleteKeyName(), Key_Console(), Key_Unbind_f(), Key_WriteBindings(), Key_WriteBindings_f(), LE_AddAmbientSound(), LET_StartPathMove(), LM_Register(), LoadMapFile(), M_Change_f(), M_CompleteMusic(), M_ParseMusic(), M_PlayRandomByCategory(), M_RandomTrack_f(), M_Start(), MakeBrushWindings(), MakeTreePortals_r(), Master_HeartbeatThread(), MD2GLCmdsRemove(), MD2Info(), MD2SkinEdit(), MD2SkinNum(), InventoryInterface::moveInInventory(), NET_Connect(), NET_ConnectToLoopBack(), NET_DatagramSocketDoNew(), NET_DatagramSocketNew(), NET_DoConnect(), NET_DoStartServer(), NET_GetAddrinfoForNode(), NET_Init(), NET_ShowStreams_f(), NET_SockaddrToStrings(), NET_SocketSetNonBlocking(), NET_StreamClose(), NET_StreamPeerToName(), NET_Wait(), uiRadioButtonNode::onActivate(), uiBarNode::onCapturedMouseMove(), uiConFuncNode::onLoaded(), uiText2Node::onLoaded(), uiFuncNode::onLoaded(), uiTabNode::onWindowOpened(), InventoryInterface::PackAmmoAndWeapon(), ParseBrush(), ParseMapEntity(), ParseUMP(), PrintBSPFileSizes(), mapTiles_s::printTilesAt(), ProcessSubModel(), Q_vsnprintf(), Qcommon_Init(), R_AddBspRRef(), R_AddStaticLight(), R_AliasModelState(), R_AnimAppend(), R_AnimChange(), R_BeginFrame(), R_BindTextureDebug(), R_CheckErrorDebug(), R_CheckExtension(), R_ConstByName(), R_CreateFramebuffer(), R_CvarCheckMaxLightmap(), R_Draw2DMapMarkers(), R_Draw3DMapMarkers(), R_DrawInitLocal(), R_DrawModelDirect(), R_DrawModelParticle(), R_DumpOpenGlState(), R_FindImage(), R_FindModel(), R_FontGenerateTexture(), R_FontInit(), R_FontListCache_f(), R_GenerateGrass(), R_GenerateTriangleSoup(), R_GetFont(), R_GetProcAddressExt(), R_GetTagMatrix(), R_GetTags(), R_ImageList_f(), R_InitExtensions(), R_InitGraphics(), R_InitPrograms(), R_LoadActorSkinsFromModel(), R_LoadAnimImages(), R_LoadImageData(), R_LoadMaterials(), R_LoadProgram(), R_LoadShader(), R_ModLoadAliasMD2MeshIndexed(), R_ModLoadAliasMD2MeshUnindexed(), R_ModLoadLevelOfDetailData(), R_ModLoadTags(), R_ModModellist_f(), R_ParseStage(), R_PreprocessShaderR(), R_PrintInfo(), R_ProgramVariable(), R_ReloadImageData(), R_RestartPrograms_f(), R_ScreenShot(), R_SetMode(), R_SetupWorldModel(), R_SwitchModelMemPoolTag(), R_TextureAlphaMode(), R_TextureMode(), R_TextureSolidMode(), R_UploadAlpha_(), R_UploadLightmapPage(), R_UseFramebuffer(), R_VerifyDriver(), ReactionFireTargets::remove(), InventoryInterface::removeFromInventory(), Rimp_Init(), RT_MicroTrace(), RunEffectForImplant(), RunImplant(), RunStrengthenImplant(), S_CompleteSounds(), S_Init(), S_LoadSampleChunk(), S_MumbleLink(), S_MumbleUnlink(), S_MumbleUpdate(), S_Play_f(), S_Restart_f(), S_StartLocalSample(), SCR_TimeRefresh_f(), SCR_TouchPics(), SCR_UpdateScreen(), SEQ_ExecuteCamera(), SEQ_ExecuteDelete(), SEQ_ExecuteModel(), SEQ_ExecuteObj2D(), SEQ_ExecutePrecache(), SEQ_InitContext(), SetWorkingDirectory(), SL_SliceTheWorld(), SP_misc_model(), SP_worldspawn(), SplitBrush(), SV_AddMapTiles(), SV_AddMissingTiles(), SV_AddMissingTiles_r(), SV_AreaEdicts_r(), SV_AssembleMap_(), SV_Begin_f(), SV_BroadcastPrintf(), SV_BuildMapStrings(), SV_CheckMap(), SV_CompleteMapCommand(), SV_CompleteServerCommand(), SV_ConnectionlessPacket(), SV_DoMapAssemble(), SV_DumpPlaced(), SV_ExecuteClientMessage(), SV_Frame(), SV_GetCvarToken(), SV_GetGameAPI(), SV_GetMapTitle(), SV_GetPlayerClientStructure(), SV_Init(), SV_InitGameProgs(), SV_Kick_f(), SV_ListMaps_f(), SV_LoadGame(), SV_LogPrintOutput(), SV_Map(), SV_Map_f(), SV_MapcycleAdd_f(), SV_MapcycleList_f(), SV_MapcycleNext_f(), SV_New_f(), SV_NextMapcycle(), SV_ParallelSearch(), SV_ParseAssemblySeeds(), SV_ParseMapcycle(), SV_ParseMapTile(), SV_ParseMapTileSet(), SV_ParseUMP(), SV_PrintAssemblyStats(), SV_PrintConfigStrings_f(), SV_RmaPrintMap(), SV_ServerCommand_f(), SV_Serverinfo_f(), SV_SetMaster_f(), SV_Shutdown(), SV_ShutdownGameProgs(), SV_Start(), SV_Status_f(), SV_UnlinkEdict(), SV_UnloadGame(), SV_UserInfo_f(), SVC_DirectConnect(), SVC_RemoteCommand(), Swap_Init(), Sys_ConsoleEditProc(), Sys_ConsoleInit(), Sys_GetHomeDirectory(), Sys_Init(), Sys_Mkdir(), Sys_Mkfifo(), TEST_F(), TEST_GetIntProperty(), TEST_GetLongProperty(), TEST_GetStringProperty(), TEST_ParseScript(), TEST_RegisterProperty(), RandomMapAssemblyTest::testAssembly(), GameTest::testCountSpawnpointsForMap(), GameTest::testCountSpawnpointsForMapInMultiplayerMode(), GameTest::testCountSpawnpointsForMapInSingleplayerMode(), GameTest::testCountSpawnpointsForMapWithAssembly(), GameTest::testCountSpawnpointsForMapWithAssemblyAndAircraft(), GameTest::testCountSpawnpointsForMapWithAssemblyAndAircraftAndUfo(), TR_BuildTracingNode_r(), TR_MakeTracingNode(), TUT_List_f(), TUT_ListClick_f(), TUT_ParseTutorials(), UFO_ExecuteTestWindow(), UI_AbstractNodeCallCreateChild(), UI_AbstractNodeCallDelete(), UI_AbstractNodeCallDeleteTimed(), UI_AbstractNodeCallRemovaAllChild(), UI_AbstractOption_GetCurrentValue(), UI_AddBehaviourMethod(), UI_AddCvarListener_f(), UI_AddLineChartCoord(), UI_AddLineChartLine(), UI_AddListener_f(), UI_AddNodeMethod(), UI_AllocNodeWithoutNew(), UI_AllocStaticStringCondition(), UI_BuildRadarImageList(), UI_CloneNode(), UI_CloseWindow(), UI_CloseWindow_f(), UI_CloseWindowByRef(), UI_ColumnLayout(), UI_CompleteWithWindow(), UI_ContainerNodeGetExistingItem(), UI_CreateComponent(), UI_CreateControl(), UI_CreateWindow(), UI_CvarListenerNodeBind(), UI_DebugListWindows_f(), UI_DebugTree(), UI_DebugTree_f(), UI_DeleteNode(), UI_DisplayNotice(), UI_DrawItem(), UI_DrawModelNode(), UI_DrawModelNodeWithUIModel(), UI_DrawNormImageByName(), UI_EditorNodeExtract_f(), UI_ExecuteAction(), UI_ExecuteActions(), UI_ExecuteCallAction(), UI_ExecuteLuaConFunc(), UI_ExecuteLuaEventScript(), UI_ExecuteLuaEventScript_DragDrop(), UI_ExecuteLuaEventScript_DragDrop_IsDropped(), UI_ExecuteLuaEventScript_DragDrop_XY(), UI_ExecuteLuaEventScript_DxDy(), UI_ExecuteLuaEventScript_Key(), UI_ExecuteLuaEventScript_ParamList(), UI_ExecuteLuaEventScript_ReturnBool(), UI_ExecuteLuaEventScript_XY(), UI_ExecuteLuaMethod(), UI_ExecuteLuaMethod_ByName(), UI_ExecuteSetAction(), UI_GenInjectedString(), UI_GeoscapeNodeScroll_f(), UI_GeoscapeNodeZoom_f(), UI_GetFloatFromExpression(), UI_GetFloatFromNodeProperty(), UI_GetNodeByPath(), UI_GetNodeFromExpression(), UI_GetParam(), UI_GetStringFromExpression(), UI_GetStringFromNodeProperty(), UI_HideNode(), UI_Init(), UI_InitFonts(), UI_InitRadar(), UI_InitRawActionValue(), UI_InitStack_f(), UI_KeyPressedInWindow(), UI_ListUIModels_f(), UI_MaterialEditorChangeValue_f(), UI_MaterialEditorNewStage_f(), UI_MaterialEditorRemoveStage_f(), UI_MaterialEditorSelectStage_f(), UI_MaterialEditorStart_f(), UI_Node_GetText(), UI_NodeGetPoint(), UI_NodeSetProperty(), UI_NodeSetPropertyFromRAW(), UI_OptionTree_SelectValue(), UI_OptionTreeSetSelectedValue(), UI_ParseActionList(), UI_ParseAndLoadLuaScript(), UI_ParseCallAction(), UI_ParseComponent(), UI_ParseEventProperty(), UI_ParseExcludeRect(), UI_ParseExpression(), UI_ParseFont(), UI_ParseNode(), UI_ParseNodeBody(), UI_ParseNodeProperties(), UI_ParseProperty(), UI_ParseSetAction(), UI_ParseSprite(), UI_ParseUIModel(), UI_ParseValueExpression(), UI_ParseWindow(), UI_Popup_f(), UI_PopWindow_f(), UI_PrintNodeTree(), UI_PushChildWindow_f(), UI_PushDropDownWindow_f(), UI_PushWindow(), UI_PushWindow_f(), UI_RemoveCvarListener_f(), UI_RemoveListener(), UI_RemoveListener_f(), UI_RequestMapList_f(), UI_ResetData_f(), UI_Restart_f(), UI_SelectMap_f(), UI_SetKeyBindingEx(), UI_ShowChartDots(), UI_ShowChartLine(), UI_TextScrollEnd(), UI_UnHideNode(), Weather::update(), VID_GetModeInfo(), VID_Restart_f(), WEB_Auth_f(), WEB_CGameDelete(), WEB_CGameDownloadFromUser(), WEB_CGameGetURL(), WEB_CGameListForUser(), WEB_CGameUpload(), WEB_DeleteCGame_f(), WEB_DownloadCGame_f(), WEB_GetToFile(), WEB_GetURL(), WEB_InitStartup(), WEB_ListCGame_f(), WEB_ListCGameFilesCallback(), and WEB_UploadCGame_f().

void Com_Quit ( void  )

Both client and server can use this, and it will do the appropriate things.

Definition at line 511 of file common.cpp.

References CL_Shutdown(), Com_WriteConfigToFile(), qFILE_s::f, FS_CloseFile(), FS_Gamedir(), FS_RemoveFile(), qFILE_s::name, NET_Wait(), SV_Clear(), SV_Shutdown(), Sys_Quit(), and va().

Referenced by CL_Quit_f(), and Qcommon_Init().

void Com_ReadFromPipe ( void  )

Read whatever is in com_pipefile, if anything, and execute it.

Definition at line 1260 of file common.cpp.

References Cmd_ExecuteString(), qFILE_s::f, FS_Read2(), and MAX_STRING_CHARS.

Referenced by SV_Frame().

int Com_ServerState ( void  )
void Com_SetRandomSeed ( unsigned int  seed)

Definition at line 999 of file common.cpp.

Referenced by Qcommon_Init(), SV_AssemblyThread(), and SV_DoMapAssemble().

void Com_SetServerState ( int  state)
const char* Com_UnsignedIntToBinary ( uint32_t  x)

Definition at line 1021 of file common.cpp.

Referenced by SV_AddEvent(), SV_QueueEvent(), and TEST_F().

void Com_UploadCrashDump ( const char *  crashDumpFile)
void Com_vPrintf ( const char *  fmt,
va_list  ap 
)
Note
Both client and server can use this, and it will output to the appropriate place.

Definition at line 338 of file common.cpp.

References Com_MakeTimestamp(), Con_Print(), consoleLogName, qFILE_s::f, FILE_APPEND, FILE_WRITE, FS_OpenFile(), FS_Write(), cvar_s::integer, MAXPRINTMSG, NET_OOB_Printf(), Q_strcat(), Q_vsnprintf(), rd_buffer, rd_buffersize, SV_CMD_PRINT, and Sys_ConsoleOutput().

static void Com_WriteConfig_f ( void  )
static

Write the config file to a specific name.

Definition at line 1042 of file common.cpp.

References Cmd_Argc(), Cmd_Argv(), Com_DefaultExtension(), Com_Printf(), Com_WriteConfigToFile(), MAX_QPATH, and Q_strncpyz().

Referenced by Qcommon_Init().

void Com_WriteConfigToFile ( const char *  filename)
static size_t Delay_Events ( int  now,
EventPriorityQueue::iterator  i 
)
static

Delay the following events and return the amount of events delayed.

Parameters
[in]nowUsually the current system time in millisecs
[in,out]iThe event queue iterator to start the delaying from

Definition at line 1383 of file common.cpp.

References eventQueue, and i.

Referenced by Dequeue_Event().

ScheduleEventPtr Dequeue_Event ( int  now)

Finds and returns the first event in the event_queue that is due. If the event has a check function, we check to see if the event can be run now, and skip it if not (even if it is due).

Returns
Returns a pointer to the event, nullptr if none found.

Definition at line 1415 of file common.cpp.

References Delay_Events(), eventQueue, and i.

Referenced by Qcommon_Frame(), and TEST_F().

static bool Event_FilterAll ( int  when,
event_func func,
event_check_func check,
void data 
)
static

Eventfilter that filter out all events.

See also
CL_FilterEventQueue
Parameters
[in]whenThe time the event should get executed (this is >= now because otherwise the event would have been executed already and would not need any filtering)
[in]funcThe event execute callback
[in]checkThe event check callback that can be used to delay event
[in]dataThe userdata that was given at event scheduling

Definition at line 1480 of file common.cpp.

Referenced by Qcommon_Frame().

vPrintfPtr_t Qcommon_GetPrintFunction ( void  )

Definition at line 1066 of file common.cpp.

References vPrintfPtr.

void Qcommon_SetPrintFunction ( vPrintfPtr_t  func)

Definition at line 1061 of file common.cpp.

References vPrintfPtr.

Referenced by main().

void Qcommon_Shutdown ( void  )
See also
Qcommon_Init
Sys_Quit
Note
Don't call anything that depends on cvars, command system, or any other subsystem that is allocated in the mem pools and maybe already freed

Definition at line 1537 of file common.cpp.

References Cmd_Shutdown(), Com_Shutdown(), Cvar_Shutdown(), FS_Shutdown(), HTTP_Cleanup(), Mem_Shutdown(), and NET_Shutdown().

Referenced by Com_Error(), Qcommon_Frame(), and Sys_Quit().

ScheduleEventPtr Schedule_Event ( int  when,
event_func func,
event_check_func check,
event_clean_func clean,
void data 
)

Schedules an event to run on or after the given time, and when its check function returns true.

Parameters
whenThe earliest time the event can run
funcThe function to call when running the event
checkA function that should return true when the event is safe to run. It should have no side-effects, as it might be called many times.
cleanA function that should cleanup any memory allocated for the event in the case that it is not executed. Either this function or func will be called, but never both.
dataArbitrary data to be passed to the check and event functions. This is needed e.g. for battlescape events to not play events too fast because the beginning of the event queue was blocked.

Definition at line 1362 of file common.cpp.

References eventQueue, and timer::func.

Referenced by CL_ParseEvent(), Schedule_Timer(), TEST_F(), and tick_timer().

Variable Documentation

cvar_t* cl_maxfps
static

Definition at line 53 of file common.cpp.

memPool_t* com_aliasSysPool

Definition at line 68 of file common.cpp.

Referenced by Cmd_Alias_f(), Com_RegisterConstInt(), TEST_Init(), and TEST_Shutdown().

int com_argc
static

Definition at line 41 of file common.cpp.

Referenced by Com_Argc(), Com_Argv(), Com_ClearArgv(), and Com_InitArgv().

const char* com_argv[MAX_NUM_ARGVS+1]
static

Definition at line 42 of file common.cpp.

Referenced by Com_Argv(), Com_ClearArgv(), and Com_InitArgv().

memPool_t* com_cmdSysPool

Definition at line 69 of file common.cpp.

Referenced by Cmd_AddCommand(), Cmd_Shutdown(), Cmd_TokenizeString(), TEST_Init(), and TEST_Shutdown().

const char* consoleLogName = "ufoconsole.log"
static

Definition at line 49 of file common.cpp.

Referenced by Com_UploadCrashDump(), and Com_vPrintf().

csi_t csi

Definition at line 39 of file common.cpp.

Referenced by CL_ActorAdd(), CL_ActorAppear(), CL_CanMultiplayerStart(), CL_InitAfter(), CL_PrecacheCharacterModels(), CL_TeamDefInitMenu(), CL_ViewLoadMedia(), CL_ViewPrecacheModels(), Com_AddObjectLinks(), Com_GetBodyTemplateByID(), Com_GetCharacterTemplateByID(), Com_GetMapDefByIDX(), Com_GetMapDefNumber(), Com_GetNameListByID(), Com_GetTeamDefinitionByID(), Com_GetUGVByID(), Com_GetUGVByIDSilent(), Com_ParseActorNames(), Com_ParseArmourOrResistance(), Com_ParseBodyTemplate(), Com_ParseCharacterTemplate(), Com_ParseDamageTypes(), Com_ParseEquipment(), Com_ParseGameTypes(), Com_ParseImplant(), Com_ParseInventory(), Com_ParseItem(), Com_ParseMapDefinition(), Com_ParseScripts(), Com_ParseTeam(), Com_ParseTerrainDefinition(), Com_ParseUGVs(), Com_ParseValue(), Com_ValueToStr(), GAME_ChangeEquip(), GAME_GetImportData(), GAME_LoadItem(), GAME_SaveTeam(), GAME_SetMode(), GAME_Spawn(), GAME_SwitchCurrentSelectedMap(), INV_EquipmentDefSanityCheck(), INV_GetEquipmentDefinitionByID(), INV_ItemDescription(), INV_UpdateObject_f(), LE_AddProjectile(), LET_Projectile(), PR_UpdateProductionList(), ResetInventoryList(), RS_InitTree(), S_PrecacheSamples(), SV_InitGameProgs(), SV_Map(), TEST_F(), TEST_Init(), GameTest::testCountSpawnpointsForMapInMultiplayerMode(), UI_BaseInventoryNodeDrawItems(), UI_BaseInventoryNodeGetItem(), UI_ContainerItemIteratorNext(), UI_ContainerNodeUpdateEquipment(), UI_MapInfo(), UI_MapInfoGetNext(), UI_RequestMapList_f(), and UI_SelectMap_f().

const debugLevel_t debugLevels[]
static
Initial value:
= {
{"DEBUG_ALL", DEBUG_ALL},
{"DEBUG_ENGINE", DEBUG_ENGINE},
{"DEBUG_SHARED", DEBUG_SHARED},
{"DEBUG_SYSTEM", DEBUG_SYSTEM},
{"DEBUG_COMMANDS", DEBUG_COMMANDS},
{"DEBUG_CLIENT", DEBUG_CLIENT},
{"DEBUG_EVENTSYS", DEBUG_EVENTSYS},
{"DEBUG_ROUTING", DEBUG_ROUTING},
{"DEBUG_SERVER", DEBUG_SERVER},
{"DEBUG_GAME", DEBUG_GAME},
{"DEBUG_RENDERER", DEBUG_RENDERER},
{"DEBUG_SOUND", DEBUG_SOUND},
{nullptr, 0}
}
#define DEBUG_EVENTSYS
Definition: defines.h:64
#define DEBUG_SERVER
Definition: defines.h:60
#define DEBUG_ALL
Definition: defines.h:54
#define DEBUG_SYSTEM
Definition: defines.h:57
#define DEBUG_ROUTING
Definition: defines.h:66
#define DEBUG_CLIENT
Definition: defines.h:59
#define DEBUG_ENGINE
Definition: defines.h:56
#define DEBUG_SOUND
Definition: defines.h:63
#define DEBUG_SHARED
Definition: defines.h:55
#define DEBUG_RENDERER
Definition: defines.h:62
#define DEBUG_COMMANDS
Definition: defines.h:58
#define DEBUG_GAME
Definition: defines.h:61

Definition at line 910 of file common.cpp.

cvar_t* developer

Definition at line 46 of file common.cpp.

Referenced by TEST_Shutdown().

EventPriorityQueue eventQueue
static
cvar_t* http_proxy

Definition at line 47 of file common.cpp.

Referenced by CL_StartHTTPDownload(), HTTP_GetURLInternal(), and TEST_Init().

cvar_t* http_timeout

Definition at line 48 of file common.cpp.

Referenced by CL_StartHTTPDownload(), HTTP_GetURLInternal(), HTTP_PutFile(), and TEST_Init().

cvar_t* hwclass

Definition at line 62 of file common.cpp.

Referenced by Com_ParseMapDefinition(), and TEST_Init().

qFILE logfile
static

Definition at line 65 of file common.cpp.

cvar_t* logfile_active
static

Definition at line 50 of file common.cpp.

qFILE pipefile
static

Definition at line 66 of file common.cpp.

char* rd_buffer
static

Definition at line 298 of file common.cpp.

Referenced by Com_BeginRedirect(), Com_EndRedirect(), and Com_vPrintf().

unsigned int rd_buffersize
static

Definition at line 299 of file common.cpp.

Referenced by Com_BeginRedirect(), Com_EndRedirect(), and Com_vPrintf().

struct net_stream* rd_stream
static

Definition at line 300 of file common.cpp.

cvar_t* s_language

Definition at line 54 of file common.cpp.

Referenced by CL_LanguageInit(), CL_LanguageInitMenu(), CL_LanguageTryToSet(), and CL_SlowFrame().

cvar_t* sv_gametype

Definition at line 56 of file common.cpp.

Referenced by SV_Frame(), SV_NextMapcycle(), and SVC_Info().

cvar_t* sys_affinity

Definition at line 60 of file common.cpp.

Referenced by CL_Frame(), and Sys_Init().

cvar_t* sys_os

Definition at line 61 of file common.cpp.

Referenced by Sys_Init().

cvar_t* sys_priority

Definition at line 59 of file common.cpp.

Referenced by CL_Frame(), and Sys_Init().

cvar_t* uploadcrashdump
static

Definition at line 63 of file common.cpp.

vPrintfPtr_t vPrintfPtr = Com_vPrintf
static