]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Remove commented out code/unused prototype
[xonotic/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // host.c -- coordinates spawning and killing of local servers
21
22 #include "quakedef.h"
23
24 #include <time.h>
25 #include "libcurl.h"
26 #include "cdaudio.h"
27 #include "cl_video.h"
28 #include "progsvm.h"
29 #include "csprogs.h"
30 #include "sv_demo.h"
31 #include "snd_main.h"
32 #include "taskqueue.h"
33 #include "thread.h"
34 #include "utf8lib.h"
35
36 /*
37
38 A server can always be started, even if the system started out as a client
39 to a remote system.
40
41 A client can NOT be started if the system started as a dedicated server.
42
43 Memory is cleared / released when a server or client begins, not when they end.
44
45 */
46
47 // current client
48 client_t *host_client;
49
50 host_t host;
51
52 // pretend frames take this amount of time (in seconds), 0 = realtime
53 cvar_t host_framerate = {CVAR_CLIENT | CVAR_SERVER, "host_framerate","0", "locks frame timing to this value in seconds, 0.05 is 20fps for example, note that this can easily run too fast, use cl_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
54 cvar_t cl_maxphysicsframesperserverframe = {CVAR_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
55 // shows time used by certain subsystems
56 cvar_t host_speeds = {CVAR_CLIENT | CVAR_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
57 cvar_t host_maxwait = {CVAR_CLIENT | CVAR_SERVER, "host_maxwait","1000", "maximum sleep time requested from the operating system in millisecond. Larger sleeps will be done using multiple host_maxwait length sleeps. Lowering this value will increase CPU load, but may help working around problems with accuracy of sleep times."};
58 cvar_t cl_minfps = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps", "40", "minimum fps target - while the rendering performance is below this, it will drift toward lower quality"};
59 cvar_t cl_minfps_fade = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_fade", "1", "how fast the quality adapts to varying framerate"};
60 cvar_t cl_minfps_qualitymax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
61 cvar_t cl_minfps_qualitymin = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
62 cvar_t cl_minfps_qualitymultiply = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymultiply", "0.2", "multiplier for quality changes in quality change per second render time (1 assumes linearity of quality and render time)"};
63 cvar_t cl_minfps_qualityhysteresis = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualityhysteresis", "0.05", "reduce all quality increments by this to reduce flickering"};
64 cvar_t cl_minfps_qualitystepmax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitystepmax", "0.1", "maximum quality change in a single frame"};
65 cvar_t cl_minfps_force = {CVAR_CLIENT, "cl_minfps_force", "0", "also apply quality reductions in timedemo/capturevideo"};
66 cvar_t cl_maxfps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxfps", "0", "maximum fps cap, 0 = unlimited, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
67 cvar_t cl_maxfps_alwayssleep = {CVAR_CLIENT, "cl_maxfps_alwayssleep","1", "gives up some processing time to other applications each frame, value in milliseconds, disabled if cl_maxfps is 0"};
68 cvar_t cl_maxidlefps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxidlefps", "20", "maximum fps cap when the game is not the active window (makes cpu time available to other programs"};
69
70 cvar_t developer = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
71 cvar_t developer_extra = {CVAR_CLIENT | CVAR_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
72 cvar_t developer_insane = {CVAR_CLIENT | CVAR_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc.  Not recommended!"};
73 cvar_t developer_loadfile = {CVAR_CLIENT | CVAR_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
74 cvar_t developer_loading = {CVAR_CLIENT | CVAR_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
75 cvar_t developer_entityparsing = {CVAR_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
76
77 cvar_t timestamps = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
78 cvar_t timeformat = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
79
80 cvar_t sessionid = {CVAR_CLIENT | CVAR_SERVER | CVAR_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
81 cvar_t locksession = {CVAR_CLIENT | CVAR_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
82
83 /*
84 ================
85 Host_AbortCurrentFrame
86
87 aborts the current host frame and goes on with the next one
88 ================
89 */
90 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
91 void Host_AbortCurrentFrame(void)
92 {
93         // in case we were previously nice, make us mean again
94         Sys_MakeProcessMean();
95
96         longjmp (host.abortframe, 1);
97 }
98
99 /*
100 ================
101 Host_Error
102
103 This shuts down both the client and server
104 ================
105 */
106 void Host_Error (const char *error, ...)
107 {
108         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
109         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
110         static qboolean hosterror = false;
111         va_list argptr;
112
113         // turn off rcon redirect if it was active when the crash occurred
114         // to prevent loops when it is a networking problem
115         Con_Rcon_Redirect_Abort();
116
117         va_start (argptr,error);
118         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
119         va_end (argptr);
120
121         Con_Errorf("Host_Error: %s\n", hosterrorstring1);
122
123         // LadyHavoc: if crashing very early, or currently shutting down, do
124         // Sys_Error instead
125         if (host.framecount < 3 || host.state == host_shutdown)
126                 Sys_Error ("Host_Error: %s", hosterrorstring1);
127
128         if (hosterror)
129                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
130         hosterror = true;
131
132         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
133
134         CL_Parse_DumpPacket();
135
136         CL_Parse_ErrorCleanUp();
137
138         //PR_Crash();
139
140         // print out where the crash happened, if it was caused by QC (and do a cleanup)
141         PRVM_Crash(SVVM_prog);
142         PRVM_Crash(CLVM_prog);
143 #ifdef CONFIG_MENU
144         PRVM_Crash(MVM_prog);
145 #endif
146
147         cl.csqc_loaded = false;
148         Cvar_SetValueQuick(&csqc_progcrc, -1);
149         Cvar_SetValueQuick(&csqc_progsize, -1);
150
151         SV_LockThreadMutex();
152         Host_ShutdownServer ();
153         SV_UnlockThreadMutex();
154
155         if (cls.state == ca_dedicated)
156                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
157
158         CL_Disconnect ();
159         cls.demonum = -1;
160
161         hosterror = false;
162
163         Host_AbortCurrentFrame();
164 }
165
166 static void Host_ServerOptions (void)
167 {
168         int i;
169
170         // general default
171         svs.maxclients = 8;
172
173 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
174 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
175         // if no client is in the executable or -dedicated is specified on
176         // commandline, start a dedicated server
177         i = COM_CheckParm ("-dedicated");
178         if (i || !cl_available)
179         {
180                 cls.state = ca_dedicated;
181                 // check for -dedicated specifying how many players
182                 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
183                         svs.maxclients = atoi (sys.argv[i+1]);
184                 if (COM_CheckParm ("-listen"))
185                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
186                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
187                 Cvar_SetValue(&cvars_all, "sv_public", 1);
188         }
189         else if (cl_available)
190         {
191                 // client exists and not dedicated, check if -listen is specified
192                 cls.state = ca_disconnected;
193                 i = COM_CheckParm ("-listen");
194                 if (i)
195                 {
196                         // default players unless specified
197                         if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
198                                 svs.maxclients = atoi (sys.argv[i+1]);
199                 }
200                 else
201                 {
202                         // default players in some games, singleplayer in most
203                         if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
204                                 svs.maxclients = 1;
205                 }
206         }
207
208         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
209
210         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
211
212         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
213                 Cvar_SetValueQuick(&deathmatch, 1);
214 }
215
216 /*
217 =======================
218 Host_InitLocal
219 ======================
220 */
221 void Host_SaveConfig_f(cmd_state_t *cmd);
222 void Host_LoadConfig_f(cmd_state_t *cmd);
223 extern cvar_t sv_writepicture_quality;
224 extern cvar_t r_texture_jpeg_fastpicmip;
225 static void Host_InitLocal (void)
226 {
227         Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
228         Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
229         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
230         Cvar_RegisterVariable (&host_framerate);
231         Cvar_RegisterVariable (&host_speeds);
232         Cvar_RegisterVariable (&host_maxwait);
233         Cvar_RegisterVariable (&cl_minfps);
234         Cvar_RegisterVariable (&cl_minfps_fade);
235         Cvar_RegisterVariable (&cl_minfps_qualitymax);
236         Cvar_RegisterVariable (&cl_minfps_qualitymin);
237         Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
238         Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
239         Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
240         Cvar_RegisterVariable (&cl_minfps_force);
241         Cvar_RegisterVariable (&cl_maxfps);
242         Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
243         Cvar_RegisterVariable (&cl_maxidlefps);
244
245         Cvar_RegisterVariable (&developer);
246         Cvar_RegisterVariable (&developer_extra);
247         Cvar_RegisterVariable (&developer_insane);
248         Cvar_RegisterVariable (&developer_loadfile);
249         Cvar_RegisterVariable (&developer_loading);
250         Cvar_RegisterVariable (&developer_entityparsing);
251
252         Cvar_RegisterVariable (&timestamps);
253         Cvar_RegisterVariable (&timeformat);
254
255         Cvar_RegisterVariable (&sv_writepicture_quality);
256         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
257 }
258
259
260 /*
261 ===============
262 Host_SaveConfig_f
263
264 Writes key bindings and archived cvars to config.cfg
265 ===============
266 */
267 static void Host_SaveConfig_to(const char *file)
268 {
269         qfile_t *f;
270
271 // dedicated servers initialize the host but don't parse and set the
272 // config.cfg cvars
273         // LadyHavoc: don't save a config if it crashed in startup
274         if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
275         {
276                 f = FS_OpenRealFile(file, "wb", false);
277                 if (!f)
278                 {
279                         Con_Errorf("Couldn't write %s.\n", file);
280                         return;
281                 }
282
283                 Key_WriteBindings (f);
284                 Cvar_WriteVariables (&cvars_all, f);
285
286                 FS_Close (f);
287         }
288 }
289 void Host_SaveConfig(void)
290 {
291         Host_SaveConfig_to(CONFIGFILENAME);
292 }
293 void Host_SaveConfig_f(cmd_state_t *cmd)
294 {
295         const char *file = CONFIGFILENAME;
296
297         if(Cmd_Argc(cmd) >= 2) {
298                 file = Cmd_Argv(cmd, 1);
299                 Con_Printf("Saving to %s\n", file);
300         }
301
302         Host_SaveConfig_to(file);
303 }
304
305 static void Host_AddConfigText(cmd_state_t *cmd)
306 {
307         // set up the default startmap_sp and startmap_dm aliases (mods can
308         // override these) and then execute the quake.rc startup script
309         if (gamemode == GAME_NEHAHRA)
310                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
311         else if (gamemode == GAME_TRANSFUSION)
312                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
313         else if (gamemode == GAME_TEU)
314                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
315         else
316                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
317         Cbuf_Execute(cmd);
318 }
319
320 /*
321 ===============
322 Host_LoadConfig_f
323
324 Resets key bindings and cvars to defaults and then reloads scripts
325 ===============
326 */
327 void Host_LoadConfig_f(cmd_state_t *cmd)
328 {
329         // reset all cvars, commands and aliases to init values
330         Cmd_RestoreInitState();
331 #ifdef CONFIG_MENU
332         // prepend a menu restart command to execute after the config
333         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
334 #endif
335         // reset cvars to their defaults, and then exec startup scripts again
336         Host_AddConfigText(&cmd_client);
337 }
338
339 /*
340 =================
341 SV_ClientPrint
342
343 Sends text across to be displayed
344 FIXME: make this just a stuffed echo?
345 =================
346 */
347 void SV_ClientPrint(const char *msg)
348 {
349         if (host_client->netconnection)
350         {
351                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
352                 MSG_WriteString(&host_client->netconnection->message, msg);
353         }
354 }
355
356 /*
357 =================
358 SV_ClientPrintf
359
360 Sends text across to be displayed
361 FIXME: make this just a stuffed echo?
362 =================
363 */
364 void SV_ClientPrintf(const char *fmt, ...)
365 {
366         va_list argptr;
367         char msg[MAX_INPUTLINE];
368
369         va_start(argptr,fmt);
370         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
371         va_end(argptr);
372
373         SV_ClientPrint(msg);
374 }
375
376 /*
377 =================
378 SV_BroadcastPrint
379
380 Sends text to all active clients
381 =================
382 */
383 void SV_BroadcastPrint(const char *msg)
384 {
385         int i;
386         client_t *client;
387
388         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
389         {
390                 if (client->active && client->netconnection)
391                 {
392                         MSG_WriteByte(&client->netconnection->message, svc_print);
393                         MSG_WriteString(&client->netconnection->message, msg);
394                 }
395         }
396
397         if (sv_echobprint.integer && cls.state == ca_dedicated)
398                 Con_Print(msg);
399 }
400
401 /*
402 =================
403 SV_BroadcastPrintf
404
405 Sends text to all active clients
406 =================
407 */
408 void SV_BroadcastPrintf(const char *fmt, ...)
409 {
410         va_list argptr;
411         char msg[MAX_INPUTLINE];
412
413         va_start(argptr,fmt);
414         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
415         va_end(argptr);
416
417         SV_BroadcastPrint(msg);
418 }
419
420 /*
421 =================
422 Host_ClientCommands
423
424 Send text over to the client to be executed
425 =================
426 */
427 void Host_ClientCommands(const char *fmt, ...)
428 {
429         va_list argptr;
430         char string[MAX_INPUTLINE];
431
432         if (!host_client->netconnection)
433                 return;
434
435         va_start(argptr,fmt);
436         dpvsnprintf(string, sizeof(string), fmt, argptr);
437         va_end(argptr);
438
439         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
440         MSG_WriteString(&host_client->netconnection->message, string);
441 }
442
443 /*
444 =====================
445 SV_DropClient
446
447 Called when the player is getting totally kicked off the host
448 if (crash = true), don't bother sending signofs
449 =====================
450 */
451 void SV_DropClient(qboolean crash)
452 {
453         prvm_prog_t *prog = SVVM_prog;
454         int i;
455         Con_Printf("Client \"%s\" dropped\n", host_client->name);
456
457         SV_StopDemoRecording(host_client);
458
459         // make sure edict is not corrupt (from a level change for example)
460         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
461
462         if (host_client->netconnection)
463         {
464                 // tell the client to be gone
465                 if (!crash)
466                 {
467                         // LadyHavoc: no opportunity for resending, so use unreliable 3 times
468                         unsigned char bufdata[8];
469                         sizebuf_t buf;
470                         memset(&buf, 0, sizeof(buf));
471                         buf.data = bufdata;
472                         buf.maxsize = sizeof(bufdata);
473                         MSG_WriteByte(&buf, svc_disconnect);
474                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
475                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
476                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
477                 }
478         }
479
480         // call qc ClientDisconnect function
481         // LadyHavoc: don't call QC if server is dead (avoids recursive
482         // Host_Error in some mods when they run out of edicts)
483         if (host_client->clientconnectcalled && sv.active && host_client->edict)
484         {
485                 // call the prog function for removing a client
486                 // this will set the body to a dead frame, among other things
487                 int saveSelf = PRVM_serverglobaledict(self);
488                 host_client->clientconnectcalled = false;
489                 PRVM_serverglobalfloat(time) = sv.time;
490                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
491                 prog->ExecuteProgram(prog, PRVM_serverfunction(ClientDisconnect), "QC function ClientDisconnect is missing");
492                 PRVM_serverglobaledict(self) = saveSelf;
493         }
494
495         if (host_client->netconnection)
496         {
497                 // break the net connection
498                 NetConn_Close(host_client->netconnection);
499                 host_client->netconnection = NULL;
500         }
501
502         // if a download is active, close it
503         if (host_client->download_file)
504         {
505                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
506                 FS_Close(host_client->download_file);
507                 host_client->download_file = NULL;
508                 host_client->download_name[0] = 0;
509                 host_client->download_expectedposition = 0;
510                 host_client->download_started = false;
511         }
512
513         // remove leaving player from scoreboard
514         host_client->name[0] = 0;
515         host_client->colors = 0;
516         host_client->frags = 0;
517         // send notification to all clients
518         // get number of client manually just to make sure we get it right...
519         i = host_client - svs.clients;
520         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
521         MSG_WriteByte (&sv.reliable_datagram, i);
522         MSG_WriteString (&sv.reliable_datagram, host_client->name);
523         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
524         MSG_WriteByte (&sv.reliable_datagram, i);
525         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
526         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
527         MSG_WriteByte (&sv.reliable_datagram, i);
528         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
529
530         // free the client now
531         if (host_client->entitydatabase)
532                 EntityFrame_FreeDatabase(host_client->entitydatabase);
533         if (host_client->entitydatabase4)
534                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
535         if (host_client->entitydatabase5)
536                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
537
538         if (sv.active)
539         {
540                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
541                 PRVM_ED_ClearEdict(prog, host_client->edict);
542         }
543
544         // clear the client struct (this sets active to false)
545         memset(host_client, 0, sizeof(*host_client));
546
547         // update server listing on the master because player count changed
548         // (which the master uses for filtering empty/full servers)
549         NetConn_Heartbeat(1);
550
551         if (sv.loadgame)
552         {
553                 for (i = 0;i < svs.maxclients;i++)
554                         if (svs.clients[i].active && !svs.clients[i].spawned)
555                                 break;
556                 if (i == svs.maxclients)
557                 {
558                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
559                         sv.paused = sv.loadgame = false; // we're basically done with loading now
560                 }
561         }
562 }
563
564 /*
565 ==================
566 Host_ShutdownServer
567
568 This only happens at the end of a game, not between levels
569 ==================
570 */
571 void Host_ShutdownServer(void)
572 {
573         prvm_prog_t *prog = SVVM_prog;
574         int i;
575
576         Con_DPrintf("Host_ShutdownServer\n");
577
578         if (!sv.active)
579                 return;
580
581         NetConn_Heartbeat(2);
582         NetConn_Heartbeat(2);
583
584 // make sure all the clients know we're disconnecting
585         World_End(&sv.world);
586         if(prog->loaded)
587         {
588                 if(PRVM_serverfunction(SV_Shutdown))
589                 {
590                         func_t s = PRVM_serverfunction(SV_Shutdown);
591                         PRVM_serverglobalfloat(time) = sv.time;
592                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
593                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
594                 }
595         }
596         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
597                 if (host_client->active)
598                         SV_DropClient(false); // server shutdown
599
600         NetConn_CloseServerPorts();
601
602         sv.active = false;
603 //
604 // clear structures
605 //
606         memset(&sv, 0, sizeof(sv));
607         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
608
609         cl.islocalgame = false;
610 }
611
612
613 //============================================================================
614
615 /*
616 ===================
617 Host_GetConsoleCommands
618
619 Add them exactly as if they had been typed at the console
620 ===================
621 */
622 static void Host_GetConsoleCommands (void)
623 {
624         char *line;
625
626         while ((line = Sys_ConsoleInput()))
627         {
628                 if (cls.state == ca_dedicated)
629                         Cbuf_AddText(&cmd_server, line);
630                 else
631                         Cbuf_AddText(&cmd_client, line);
632         }
633 }
634
635 /*
636 ==================
637 Host_TimeReport
638
639 Returns a time report string, for example for
640 ==================
641 */
642 const char *Host_TimingReport(char *buf, size_t buflen)
643 {
644         return va(buf, buflen, "%.1f%% CPU, %.2f%% lost, offset avg %.1fms, max %.1fms, sdev %.1fms", svs.perf_cpuload * 100, svs.perf_lost * 100, svs.perf_offset_avg * 1000, svs.perf_offset_max * 1000, svs.perf_offset_sdev * 1000);
645 }
646
647 /*
648 ==================
649 Host_Frame
650
651 Runs all active servers
652 ==================
653 */
654 static void Host_Init(void);
655 void Host_Main(void)
656 {
657         double time1 = 0;
658         double time2 = 0;
659         double time3 = 0;
660         double cl_timer = 0, sv_timer = 0;
661         double clframetime, time, oldtime, newtime;
662         double wait;
663         int pass1, pass2, pass3, i;
664         char vabuf[1024];
665         qboolean playing;
666
667         Host_Init();
668
669         host.realtime = 0;
670         host.dirtytime = Sys_DirtyTime();
671
672         while(host.state != host_shutdown)
673         {
674                 if (setjmp(host.abortframe))
675                 {
676                         SCR_ClearLoadingScreen(false);
677                         continue;                       // something bad happened, or the server disconnected
678                 }
679
680                 oldtime = host.dirtytime;
681                 newtime = Sys_DirtyTime();
682                 time = newtime - oldtime;
683                 if (time < 0)
684                 {
685                         // warn if it's significant
686                         if (time < -0.01)
687                                 Con_Warnf("Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
688                         time = 0;
689                 }
690                 else if (time >= 1800)
691                 {
692                         Con_Warnf("Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
693                         time = 0;
694                 }
695                 host.realtime += time;
696                 host.dirtytime = newtime;
697
698                 cl_timer += time;
699                 sv_timer += time;
700
701                 if (!svs.threaded)
702                 {
703                         svs.perf_acc_realtime += time;
704
705                         // Look for clients who have spawned
706                         playing = false;
707                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
708                                 if(host_client->begun)
709                                         if(host_client->netconnection)
710                                                 playing = true;
711                         if(sv.time < 10)
712                         {
713                                 // don't accumulate time for the first 10 seconds of a match
714                                 // so things can settle
715                                 svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
716                         }
717                         else if(svs.perf_acc_realtime > 5)
718                         {
719                                 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
720                                 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
721                                 if(svs.perf_acc_offset_samples > 0)
722                                 {
723                                         svs.perf_offset_max = svs.perf_acc_offset_max;
724                                         svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
725                                         svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
726                                 }
727                                 if(svs.perf_lost > 0 && developer_extra.integer)
728                                         if(playing) // only complain if anyone is looking
729                                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
730                                 svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
731                         }
732                 }
733
734                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
735                         Cvar_SetValueQuick(&host_framerate, 0);
736
737                 TaskQueue_Frame(false);
738
739                 // keep the random time dependent, but not when playing demos/benchmarking
740                 if(!*sv_random_seed.string && !cls.demoplayback)
741                         rand();
742
743                 // get new key events
744                 Key_EventQueue_Unblock();
745                 SndSys_SendKeyEvents();
746                 Sys_SendKeyEvents();
747
748                 NetConn_UpdateSockets();
749
750                 Log_DestBuffer_Flush();
751
752                 // receive packets on each main loop iteration, as the main loop may
753                 // be undersleeping due to select() detecting a new packet
754                 if (sv.active && !svs.threaded)
755                         NetConn_ServerFrame();
756
757                 Curl_Run();
758
759                 // check for commands typed to the host
760                 Host_GetConsoleCommands();
761
762                 // process console commands
763 //              R_TimeReport("preconsole");
764                 CL_VM_PreventInformationLeaks();
765                 Cbuf_Frame(&cmd_client);
766                 Cbuf_Frame(&cmd_server);
767
768                 if(sv.active)
769                         Cbuf_Frame(&cmd_serverfromclient);
770
771 //              R_TimeReport("console");
772
773                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
774
775                 // if the accumulators haven't become positive yet, wait a while
776                 if (cls.state == ca_dedicated)
777                         wait = sv_timer * -1000000.0;
778                 else if (!sv.active || svs.threaded)
779                         wait = cl_timer * -1000000.0;
780                 else
781                         wait = max(cl_timer, sv_timer) * -1000000.0;
782
783                 if (!cls.timedemo && wait >= 1)
784                 {
785                         double time0, delta;
786
787                         if(host_maxwait.value <= 0)
788                                 wait = min(wait, 1000000.0);
789                         else
790                                 wait = min(wait, host_maxwait.value * 1000.0);
791                         if(wait < 1)
792                                 wait = 1; // because we cast to int
793
794                         time0 = Sys_DirtyTime();
795                         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
796                                 NetConn_SleepMicroseconds((int)wait);
797                                 if (cls.state != ca_dedicated)
798                                         NetConn_ClientFrame(); // helps server browser get good ping values
799                                 // TODO can we do the same for ServerFrame? Probably not.
800                         }
801                         else
802                                 Sys_Sleep((int)wait);
803                         delta = Sys_DirtyTime() - time0;
804                         if (delta < 0 || delta >= 1800) delta = 0;
805                         if (!svs.threaded)
806                                 svs.perf_acc_sleeptime += delta;
807 //                      R_TimeReport("sleep");
808                         continue;
809                 }
810
811                 // limit the frametime steps to no more than 100ms each
812                 if (cl_timer > 0.1)
813                         cl_timer = 0.1;
814                 if (sv_timer > 0.1)
815                 {
816                         if (!svs.threaded)
817                                 svs.perf_acc_lost += (sv_timer - 0.1);
818                         sv_timer = 0.1;
819                 }
820
821                 R_TimeReport("---");
822
823         //-------------------
824         //
825         // server operations
826         //
827         //-------------------
828
829                 // limit the frametime steps to no more than 100ms each
830                 if (sv.active && sv_timer > 0 && !svs.threaded)
831                 {
832                         // execute one or more server frames, with an upper limit on how much
833                         // execution time to spend on server frames to avoid freezing the game if
834                         // the server is overloaded, this execution time limit means the game will
835                         // slow down if the server is taking too long.
836                         int framecount, framelimit = 1;
837                         double advancetime, aborttime = 0;
838                         float offset;
839                         prvm_prog_t *prog = SVVM_prog;
840
841                         // run the world state
842                         // don't allow simulation to run too fast or too slow or logic glitches can occur
843
844                         // stop running server frames if the wall time reaches this value
845                         if (sys_ticrate.value <= 0)
846                                 advancetime = sv_timer;
847                         else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
848                         {
849                                 // synchronize to the client frametime, but no less than 10ms and no more than 100ms
850                                 advancetime = bound(0.01, cl_timer, 0.1);
851                         }
852                         else
853                         {
854                                 advancetime = sys_ticrate.value;
855                                 // listen servers can run multiple server frames per client frame
856                                 framelimit = cl_maxphysicsframesperserverframe.integer;
857                                 aborttime = Sys_DirtyTime() + 0.1;
858                         }
859                         if(host_timescale.value > 0 && host_timescale.value < 1)
860                                 advancetime = min(advancetime, 0.1 / host_timescale.value);
861                         else
862                                 advancetime = min(advancetime, 0.1);
863
864                         if(advancetime > 0)
865                         {
866                                 offset = Sys_DirtyTime() - newtime;if (offset < 0 || offset >= 1800) offset = 0;
867                                 offset += sv_timer;
868                                 ++svs.perf_acc_offset_samples;
869                                 svs.perf_acc_offset += offset;
870                                 svs.perf_acc_offset_squared += offset * offset;
871                                 if(svs.perf_acc_offset_max < offset)
872                                         svs.perf_acc_offset_max = offset;
873                         }
874
875                         // only advance time if not paused
876                         // the game also pauses in singleplayer when menu or console is used
877                         sv.frametime = advancetime * host_timescale.value;
878                         if (host_framerate.value)
879                                 sv.frametime = host_framerate.value;
880                         if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
881                                 sv.frametime = 0;
882
883                         for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
884                         {
885                                 sv_timer -= advancetime;
886
887                                 // move things around and think unless paused
888                                 if (sv.frametime)
889                                         SV_Physics();
890
891                                 // if this server frame took too long, break out of the loop
892                                 if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
893                                         break;
894                         }
895                         R_TimeReport("serverphysics");
896
897                         // send all messages to the clients
898                         SV_SendClientMessages();
899
900                         if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
901                                 prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
902                                 PRVM_serverglobalfloat(time) = sv.time;
903                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
904                         }
905
906                         // send an heartbeat if enough time has passed since the last one
907                         NetConn_Heartbeat(0);
908                         R_TimeReport("servernetwork");
909                 }
910                 else if (!svs.threaded)
911                 {
912                         // don't let r_speeds display jump around
913                         R_TimeReport("serverphysics");
914                         R_TimeReport("servernetwork");
915                 }
916
917         //-------------------
918         //
919         // client operations
920         //
921         //-------------------
922
923                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
924                 {
925                         R_TimeReport("---");
926                         Collision_Cache_NewFrame();
927                         R_TimeReport("photoncache");
928 #ifdef CONFIG_VIDEO_CAPTURE
929                         // decide the simulation time
930                         if (cls.capturevideo.active)
931                         {
932                                 //***
933                                 if (cls.capturevideo.realtime)
934                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
935                                 else
936                                 {
937                                         clframetime = 1.0 / cls.capturevideo.framerate;
938                                         cl.realframetime = max(cl_timer, clframetime);
939                                 }
940                         }
941                         else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
942
943 #else
944                         if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
945 #endif
946                         {
947                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
948                                 // when running slow, we need to sleep to keep input responsive
949                                 wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
950                                 if (wait > 0)
951                                         Sys_Sleep((int)wait);
952                         }
953                         else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
954                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
955                         else
956                                 clframetime = cl.realframetime = cl_timer;
957
958                         // apply slowmo scaling
959                         clframetime *= cl.movevars_timescale;
960                         // scale playback speed of demos by slowmo cvar
961                         if (cls.demoplayback)
962                         {
963                                 clframetime *= host_timescale.value;
964                                 // if demo playback is paused, don't advance time at all
965                                 if (cls.demopaused)
966                                         clframetime = 0;
967                         }
968                         else
969                         {
970                                 // host_framerate overrides all else
971                                 if (host_framerate.value)
972                                         clframetime = host_framerate.value;
973
974                                 if (cl.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
975                                         clframetime = 0;
976                         }
977
978                         if (cls.timedemo)
979                                 clframetime = cl.realframetime = cl_timer;
980
981                         // deduct the frame time from the accumulator
982                         cl_timer -= cl.realframetime;
983
984                         cl.oldtime = cl.time;
985                         cl.time += clframetime;
986
987                         // update video
988                         if (host_speeds.integer)
989                                 time1 = Sys_DirtyTime();
990                         R_TimeReport("pre-input");
991
992                         // Collect input into cmd
993                         CL_Input();
994
995                         R_TimeReport("input");
996
997                         // check for new packets
998                         NetConn_ClientFrame();
999
1000                         // read a new frame from a demo if needed
1001                         CL_ReadDemoMessage();
1002                         R_TimeReport("clientnetwork");
1003
1004                         // now that packets have been read, send input to server
1005                         CL_SendMove();
1006                         R_TimeReport("sendmove");
1007
1008                         // update client world (interpolate entities, create trails, etc)
1009                         CL_UpdateWorld();
1010                         R_TimeReport("lerpworld");
1011
1012                         CL_Video_Frame();
1013
1014                         R_TimeReport("client");
1015
1016                         CL_UpdateScreen();
1017                         R_TimeReport("render");
1018
1019                         if (host_speeds.integer)
1020                                 time2 = Sys_DirtyTime();
1021
1022                         // update audio
1023                         if(cl.csqc_usecsqclistener)
1024                         {
1025                                 S_Update(&cl.csqc_listenermatrix);
1026                                 cl.csqc_usecsqclistener = false;
1027                         }
1028                         else
1029                                 S_Update(&r_refdef.view.matrix);
1030
1031                         CDAudio_Update();
1032                         R_TimeReport("audio");
1033
1034                         // reset gathering of mouse input
1035                         in_mouse_x = in_mouse_y = 0;
1036
1037                         if (host_speeds.integer)
1038                         {
1039                                 pass1 = (int)((time1 - time3)*1000000);
1040                                 time3 = Sys_DirtyTime();
1041                                 pass2 = (int)((time2 - time1)*1000000);
1042                                 pass3 = (int)((time3 - time2)*1000000);
1043                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
1044                                                         pass1+pass2+pass3, pass1, pass2, pass3);
1045                         }
1046                 }
1047
1048 #if MEMPARANOIA
1049                 Mem_CheckSentinelsGlobal();
1050 #else
1051                 if (developer_memorydebug.integer)
1052                         Mem_CheckSentinelsGlobal();
1053 #endif
1054
1055                 // if there is some time remaining from this frame, reset the timers
1056                 if (cl_timer >= 0)
1057                         cl_timer = 0;
1058                 if (sv_timer >= 0)
1059                 {
1060                         if (!svs.threaded)
1061                                 svs.perf_acc_lost += sv_timer;
1062                         sv_timer = 0;
1063                 }
1064
1065                 host.framecount++;
1066         }
1067
1068         Sys_Quit(0);
1069 }
1070
1071 //============================================================================
1072
1073 qboolean vid_opened = false;
1074 void Host_StartVideo(void)
1075 {
1076         if (!vid_opened && cls.state != ca_dedicated)
1077         {
1078                 vid_opened = true;
1079                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
1080                 NetConn_UpdateSockets();
1081                 VID_Start();
1082                 CDAudio_Startup();
1083         }
1084 }
1085
1086 char engineversion[128];
1087
1088 qboolean sys_nostdout = false;
1089
1090 static qfile_t *locksession_fh = NULL;
1091 static qboolean locksession_run = false;
1092 static void Host_InitSession(void)
1093 {
1094         int i;
1095         char *buf;
1096         Cvar_RegisterVariable(&sessionid);
1097         Cvar_RegisterVariable(&locksession);
1098
1099         // load the session ID into the read-only cvar
1100         if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
1101         {
1102                 if(sys.argv[i+1][0] == '.')
1103                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
1104                 else
1105                 {
1106                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
1107                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
1108                         Cvar_SetQuick(&sessionid, buf);
1109                 }
1110         }
1111 }
1112 void Host_LockSession(void)
1113 {
1114         if(locksession_run)
1115                 return;
1116         locksession_run = true;
1117         if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
1118         {
1119                 char vabuf[1024];
1120                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
1121                 FS_CreatePath(p);
1122                 locksession_fh = FS_SysOpen(p, "wl", false);
1123                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
1124                 if(!locksession_fh)
1125                 {
1126                         if(locksession.integer == 2)
1127                         {
1128                                 Con_Warnf("WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
1129                         }
1130                         else
1131                         {
1132                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
1133                         }
1134                 }
1135         }
1136 }
1137 void Host_UnlockSession(void)
1138 {
1139         if(!locksession_run)
1140                 return;
1141         locksession_run = false;
1142
1143         if(locksession_fh)
1144         {
1145                 FS_Close(locksession_fh);
1146                 // NOTE: we can NOT unlink the lock here, as doing so would
1147                 // create a race condition if another process created it
1148                 // between our close and our unlink
1149                 locksession_fh = NULL;
1150         }
1151 }
1152
1153 /*
1154 ====================
1155 Host_Init
1156 ====================
1157 */
1158 static void Host_Init (void)
1159 {
1160         int i;
1161         const char* os;
1162         char vabuf[1024];
1163         qboolean dedicated_server = COM_CheckParm("-dedicated") || !cl_available;
1164         cmd_state_t *cmd = &cmd_client;
1165
1166         host.state = host_init;
1167
1168         if (COM_CheckParm("-profilegameonly"))
1169                 Sys_AllowProfiling(false);
1170
1171         // LadyHavoc: quake never seeded the random number generator before... heh
1172         if (COM_CheckParm("-benchmark"))
1173                 srand(0); // predictable random sequence for -benchmark
1174         else
1175                 srand((unsigned int)time(NULL));
1176
1177         // FIXME: this is evil, but possibly temporary
1178         // LadyHavoc: doesn't seem very temporary...
1179         // LadyHavoc: made this a saved cvar
1180 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
1181         if (COM_CheckParm("-developer"))
1182         {
1183                 developer.value = developer.integer = 1;
1184                 developer.string = "1";
1185         }
1186
1187         if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
1188         {
1189                 developer.value = developer.integer = 1;
1190                 developer.string = "1";
1191                 developer_extra.value = developer_extra.integer = 1;
1192                 developer_extra.string = "1";
1193                 developer_insane.value = developer_insane.integer = 1;
1194                 developer_insane.string = "1";
1195                 developer_memory.value = developer_memory.integer = 1;
1196                 developer_memory.string = "1";
1197                 developer_memorydebug.value = developer_memorydebug.integer = 1;
1198                 developer_memorydebug.string = "1";
1199         }
1200
1201         if (COM_CheckParm("-developer3"))
1202         {
1203                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
1204                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
1205         }
1206
1207 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1208         if (COM_CheckParm("-nostdout"))
1209                 sys_nostdout = 1;
1210
1211         // used by everything
1212         Memory_Init();
1213
1214         // initialize console command/cvar/alias/command execution systems
1215         Cmd_Init();
1216
1217         Cmd_Init_Commands(dedicated_server);
1218
1219         // initialize memory subsystem cvars/commands
1220         Memory_Init_Commands();
1221
1222         // initialize console and logging and its cvars/commands
1223         Con_Init();
1224
1225         // initialize various cvars that could not be initialized earlier
1226         u8_Init();
1227         Curl_Init_Commands();
1228         Sys_Init_Commands();
1229         COM_Init_Commands();
1230         FS_Init_Commands();
1231
1232         // initialize console window (only used by sys_win.c)
1233         Sys_InitConsole();
1234
1235         // initialize the self-pack (must be before COM_InitGameType as it may add command line options)
1236         FS_Init_SelfPack();
1237
1238         // detect gamemode from commandline options or executable name
1239         COM_InitGameType();
1240
1241         // construct a version string for the corner of the console
1242         os = DP_OS_NAME;
1243         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
1244         Con_Printf("%s\n", engineversion);
1245
1246         // initialize process nice level
1247         Sys_InitProcessNice();
1248
1249         // initialize ixtable
1250         Mathlib_Init();
1251
1252         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
1253         FS_Init();
1254
1255         // register the cvars for session locking
1256         Host_InitSession();
1257
1258         // must be after FS_Init
1259         Crypto_Init();
1260         Crypto_Init_Commands();
1261
1262         NetConn_Init();
1263         Curl_Init();
1264         PRVM_Init();
1265         Mod_Init();
1266         World_Init();
1267         SV_Init();
1268         V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
1269         Host_InitCommands();
1270         Host_InitLocal();
1271         Host_ServerOptions();
1272
1273         Thread_Init();
1274         TaskQueue_Init();
1275
1276         CL_Init();
1277
1278         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
1279         // NOTE: menu commands are freed by Cmd_RestoreInitState
1280         Cmd_SaveInitState();
1281
1282         // FIXME: put this into some neat design, but the menu should be allowed to crash
1283         // without crashing the whole game, so this should just be a short-time solution
1284
1285         // here comes the not so critical stuff
1286         if (setjmp(host.abortframe)) {
1287                 return;
1288         }
1289
1290         Host_AddConfigText(cmd);
1291
1292         // if quake.rc is missing, use default
1293         if (!FS_FileExists("quake.rc"))
1294         {
1295                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
1296                 Cbuf_Execute(cmd);
1297         }
1298
1299         host.state = host_active;
1300
1301         Log_Start();
1302
1303         // check for special benchmark mode
1304 // COMMANDLINEOPTION: Client: -benchmark <demoname> runs a timedemo and quits, results of any timedemo can be found in gamedir/benchmark.log (for example id1/benchmark.log)
1305         i = COM_CheckParm("-benchmark");
1306         if (i && i + 1 < sys.argc)
1307         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1308         {
1309                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
1310                 Cbuf_Execute(&cmd_client);
1311         }
1312
1313         // check for special demo mode
1314 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1315         i = COM_CheckParm("-demo");
1316         if (i && i + 1 < sys.argc)
1317         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1318         {
1319                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
1320                 Cbuf_Execute(&cmd_client);
1321         }
1322
1323 #ifdef CONFIG_VIDEO_CAPTURE
1324 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1325         i = COM_CheckParm("-capturedemo");
1326         if (i && i + 1 < sys.argc)
1327         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1328         {
1329                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
1330                 Cbuf_Execute(&cmd_client);
1331         }
1332 #endif
1333
1334         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1335         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1336         {
1337                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
1338                 Cbuf_Execute(&cmd_client);
1339         }
1340
1341         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1342         {
1343 #ifdef CONFIG_MENU
1344                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
1345 #endif
1346                 Cbuf_Execute(&cmd_client);
1347         }
1348
1349         Con_DPrint("========Initialized=========\n");
1350
1351         if (cls.state != ca_dedicated)
1352                 SV_StartThread();
1353 }
1354
1355
1356 /*
1357 ===============
1358 Host_Shutdown
1359
1360 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1361 to run quit through here before the final handoff to the sys code.
1362 ===============
1363 */
1364 void Host_Shutdown(void)
1365 {
1366         static qboolean isdown = false;
1367
1368         if (isdown)
1369         {
1370                 Con_Print("recursive shutdown\n");
1371                 return;
1372         }
1373         if (setjmp(host.abortframe))
1374         {
1375                 Con_Print("aborted the quitting frame?!?\n");
1376                 return;
1377         }
1378         isdown = true;
1379
1380         // be quiet while shutting down
1381         S_StopAllSounds();
1382
1383         // end the server thread
1384         if (svs.threaded)
1385                 SV_StopThread();
1386
1387         // disconnect client from server if active
1388         CL_Disconnect();
1389
1390         // shut down local server if active
1391         SV_LockThreadMutex();
1392         Host_ShutdownServer ();
1393         SV_UnlockThreadMutex();
1394
1395 #ifdef CONFIG_MENU
1396         // Shutdown menu
1397         if(MR_Shutdown)
1398                 MR_Shutdown();
1399 #endif
1400
1401         // AK shutdown PRVM
1402         // AK hmm, no PRVM_Shutdown(); yet
1403
1404         CL_Video_Shutdown();
1405
1406         Host_SaveConfig();
1407
1408         CDAudio_Shutdown ();
1409         S_Terminate ();
1410         Curl_Shutdown ();
1411         NetConn_Shutdown ();
1412
1413         if (cls.state != ca_dedicated)
1414         {
1415                 R_Modules_Shutdown();
1416                 VID_Shutdown();
1417         }
1418
1419         SV_StopThread();
1420         TaskQueue_Shutdown();
1421         Thread_Shutdown();
1422         Cmd_Shutdown();
1423         Key_Shutdown();
1424         CL_Shutdown();
1425         Sys_Shutdown();
1426         Log_Close();
1427         Crypto_Shutdown();
1428
1429         Host_UnlockSession();
1430
1431         S_Shutdown();
1432         Con_Shutdown();
1433         Memory_Shutdown();
1434 }
1435