]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Restore old video init behavior, pending better solution. Fixes Steel Storm crash...
[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 host_t host;
48
49 // pretend frames take this amount of time (in seconds), 0 = realtime
50 cvar_t host_framerate = {CF_CLIENT | CF_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"};
51 cvar_t cl_maxphysicsframesperserverframe = {CF_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
52 // shows time used by certain subsystems
53 cvar_t host_speeds = {CF_CLIENT | CF_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
54 cvar_t host_maxwait = {CF_CLIENT | CF_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."};
55
56 cvar_t developer = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
57 cvar_t developer_extra = {CF_CLIENT | CF_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
58 cvar_t developer_insane = {CF_CLIENT | CF_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc.  Not recommended!"};
59 cvar_t developer_loadfile = {CF_CLIENT | CF_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
60 cvar_t developer_loading = {CF_CLIENT | CF_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
61 cvar_t developer_entityparsing = {CF_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
62
63 cvar_t timestamps = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timestamps", "0", "prints timestamps on console messages"};
64 cvar_t timeformat = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
65
66 cvar_t sessionid = {CF_CLIENT | CF_SERVER | CF_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
67 cvar_t locksession = {CF_CLIENT | CF_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
68
69 /*
70 ================
71 Host_AbortCurrentFrame
72
73 aborts the current host frame and goes on with the next one
74 ================
75 */
76 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
77 void Host_AbortCurrentFrame(void)
78 {
79         // in case we were previously nice, make us mean again
80         Sys_MakeProcessMean();
81
82         longjmp (host.abortframe, 1);
83 }
84
85 /*
86 ================
87 Host_Error
88
89 This shuts down both the client and server
90 ================
91 */
92 void Host_Error (const char *error, ...)
93 {
94         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
95         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
96         static qbool hosterror = false;
97         va_list argptr;
98
99         // turn off rcon redirect if it was active when the crash occurred
100         // to prevent loops when it is a networking problem
101         Con_Rcon_Redirect_Abort();
102
103         va_start (argptr,error);
104         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
105         va_end (argptr);
106
107         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
108
109         // LadyHavoc: if crashing very early, or currently shutting down, do
110         // Sys_Error instead
111         if (host.framecount < 3 || host.state == host_shutdown)
112                 Sys_Error ("Host_Error: %s", hosterrorstring1);
113
114         if (hosterror)
115                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
116         hosterror = true;
117
118         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
119
120         CL_Parse_DumpPacket();
121
122         CL_Parse_ErrorCleanUp();
123
124         //PR_Crash();
125
126         // print out where the crash happened, if it was caused by QC (and do a cleanup)
127         PRVM_Crash(SVVM_prog);
128         PRVM_Crash(CLVM_prog);
129 #ifdef CONFIG_MENU
130         PRVM_Crash(MVM_prog);
131 #endif
132
133         cl.csqc_loaded = false;
134         Cvar_SetValueQuick(&csqc_progcrc, -1);
135         Cvar_SetValueQuick(&csqc_progsize, -1);
136
137         SV_LockThreadMutex();
138         SV_Shutdown ();
139         SV_UnlockThreadMutex();
140
141         if (cls.state == ca_dedicated)
142                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
143
144         CL_Disconnect ();
145         cls.demonum = -1;
146
147         hosterror = false;
148
149         Host_AbortCurrentFrame();
150 }
151
152 static void Host_ServerOptions (void)
153 {
154         int i;
155
156         // general default
157         svs.maxclients = 8;
158
159 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
160 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
161         // if no client is in the executable or -dedicated is specified on
162         // commandline, start a dedicated server
163         i = Sys_CheckParm ("-dedicated");
164         if (i || !cl_available)
165         {
166                 cls.state = ca_dedicated;
167                 // check for -dedicated specifying how many players
168                 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
169                         svs.maxclients = atoi (sys.argv[i+1]);
170                 if (Sys_CheckParm ("-listen"))
171                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
172                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
173                 Cvar_SetValue(&cvars_all, "sv_public", 1);
174         }
175         else if (cl_available)
176         {
177                 // client exists and not dedicated, check if -listen is specified
178                 cls.state = ca_disconnected;
179                 i = Sys_CheckParm ("-listen");
180                 if (i)
181                 {
182                         // default players unless specified
183                         if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
184                                 svs.maxclients = atoi (sys.argv[i+1]);
185                 }
186                 else
187                 {
188                         // default players in some games, singleplayer in most
189                         if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
190                                 svs.maxclients = 1;
191                 }
192         }
193
194         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
195
196         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
197
198         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
199                 Cvar_SetValueQuick(&deathmatch, 1);
200 }
201
202 /*
203 ==================
204 Host_Quit_f
205 ==================
206 */
207 void Host_Quit_f(cmd_state_t *cmd)
208 {
209         if(host.state == host_shutdown)
210                 Con_Printf("shutting down already!\n");
211         else
212                 host.state = host_shutdown;
213 }
214
215 static void Host_Version_f(cmd_state_t *cmd)
216 {
217         Con_Printf("Version: %s build %s\n", gamename, buildstring);
218 }
219
220 static void Host_Framerate_c(cvar_t *var)
221 {
222         if (var->value < 0.00001 && var->value != 0)
223                 Cvar_SetValueQuick(var, 0);
224 }
225
226 /*
227 =======================
228 Host_InitLocal
229 ======================
230 */
231 void Host_SaveConfig_f(cmd_state_t *cmd);
232 void Host_LoadConfig_f(cmd_state_t *cmd);
233 extern cvar_t sv_writepicture_quality;
234 extern cvar_t r_texture_jpeg_fastpicmip;
235 static void Host_InitLocal (void)
236 {
237         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
238         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
239         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
240         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
241         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
242         Cvar_RegisterVariable (&host_framerate);
243         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
244         Cvar_RegisterVariable (&host_speeds);
245         Cvar_RegisterVariable (&host_maxwait);
246
247         Cvar_RegisterVariable (&developer);
248         Cvar_RegisterVariable (&developer_extra);
249         Cvar_RegisterVariable (&developer_insane);
250         Cvar_RegisterVariable (&developer_loadfile);
251         Cvar_RegisterVariable (&developer_loading);
252         Cvar_RegisterVariable (&developer_entityparsing);
253
254         Cvar_RegisterVariable (&timestamps);
255         Cvar_RegisterVariable (&timeformat);
256
257         Cvar_RegisterVariable (&sv_writepicture_quality);
258         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
259 }
260
261
262 /*
263 ===============
264 Host_SaveConfig_f
265
266 Writes key bindings and archived cvars to config.cfg
267 ===============
268 */
269 static void Host_SaveConfig_to(const char *file)
270 {
271         qfile_t *f;
272
273 // dedicated servers initialize the host but don't parse and set the
274 // config.cfg cvars
275         // LadyHavoc: don't save a config if it crashed in startup
276         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
277         {
278                 f = FS_OpenRealFile(file, "wb", false);
279                 if (!f)
280                 {
281                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
282                         return;
283                 }
284
285                 Key_WriteBindings (f);
286                 Cvar_WriteVariables (&cvars_all, f);
287
288                 FS_Close (f);
289         }
290 }
291 void Host_SaveConfig(void)
292 {
293         Host_SaveConfig_to(CONFIGFILENAME);
294 }
295 void Host_SaveConfig_f(cmd_state_t *cmd)
296 {
297         const char *file = CONFIGFILENAME;
298
299         if(Cmd_Argc(cmd) >= 2) {
300                 file = Cmd_Argv(cmd, 1);
301                 Con_Printf("Saving to %s\n", file);
302         }
303
304         Host_SaveConfig_to(file);
305 }
306
307 static void Host_AddConfigText(cmd_state_t *cmd)
308 {
309         // set up the default startmap_sp and startmap_dm aliases (mods can
310         // override these) and then execute the quake.rc startup script
311         if (gamemode == GAME_NEHAHRA)
312                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
313         else if (gamemode == GAME_TRANSFUSION)
314                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
315         else if (gamemode == GAME_TEU)
316                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
317         else
318                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
319         Cbuf_Execute(cmd->cbuf);
320 }
321
322 /*
323 ===============
324 Host_LoadConfig_f
325
326 Resets key bindings and cvars to defaults and then reloads scripts
327 ===============
328 */
329 void Host_LoadConfig_f(cmd_state_t *cmd)
330 {
331         // reset all cvars, commands and aliases to init values
332         Cmd_RestoreInitState();
333 #ifdef CONFIG_MENU
334         // prepend a menu restart command to execute after the config
335         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
336 #endif
337         // reset cvars to their defaults, and then exec startup scripts again
338         Host_AddConfigText(&cmd_client);
339 }
340
341 //============================================================================
342
343 /*
344 ===================
345 Host_GetConsoleCommands
346
347 Add them exactly as if they had been typed at the console
348 ===================
349 */
350 static void Host_GetConsoleCommands (void)
351 {
352         char *line;
353
354         while ((line = Sys_ConsoleInput()))
355         {
356                 if (cls.state == ca_dedicated)
357                         Cbuf_AddText(&cmd_server, line);
358                 else
359                         Cbuf_AddText(&cmd_client, line);
360         }
361 }
362
363 /*
364 ==================
365 Host_TimeReport
366
367 Returns a time report string, for example for
368 ==================
369 */
370 const char *Host_TimingReport(char *buf, size_t buflen)
371 {
372         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);
373 }
374
375 /*
376 ==================
377 Host_Frame
378
379 Runs all active servers
380 ==================
381 */
382 static void Host_Init(void);
383 double Host_Frame(double time)
384 {
385         double cl_timer = 0;
386         double sv_timer = 0;
387         static double wait;
388
389         TaskQueue_Frame(false);
390
391         // keep the random time dependent, but not when playing demos/benchmarking
392         if(!*sv_random_seed.string && !host.restless)
393                 rand();
394
395         NetConn_UpdateSockets();
396
397         Log_DestBuffer_Flush();
398
399         Curl_Run();
400
401         // check for commands typed to the host
402         Host_GetConsoleCommands();
403
404         // process console commands
405 //              R_TimeReport("preconsole");
406
407         Cbuf_Frame(host.cbuf);
408
409 //              R_TimeReport("console");
410
411         //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
412
413         R_TimeReport("---");
414
415         sv_timer = SV_Frame(time);
416         cl_timer = CL_Frame(time);
417
418         Mem_CheckSentinelsGlobal();
419
420         // if the accumulators haven't become positive yet, wait a while
421         if (cls.state == ca_dedicated)
422                 wait = sv_timer * -1000000.0; // dedicated
423         else if (!sv.active || svs.threaded)
424                 wait = cl_timer * -1000000.0; // connected to server, main menu, or server is on different thread
425         else
426                 wait = max(cl_timer, sv_timer) * -1000000.0; // listen server or singleplayer
427
428         if (!host.restless && wait >= 1)
429                 return wait;
430         else
431                 return 0;
432 }
433
434 static inline void Host_Sleep(double time)
435 {
436         static double delta;
437         double time0;
438
439         if(host_maxwait.value <= 0)
440                 time = min(time, 1000000.0);
441         else
442                 time = min(time, host_maxwait.value * 1000.0);
443         if(time < 1)
444                 time = 1; // because we cast to int
445
446         time0 = Sys_DirtyTime();
447         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
448                 NetConn_SleepMicroseconds((int)time);
449                 if (cls.state != ca_dedicated)
450                         NetConn_ClientFrame(); // helps server browser get good ping values
451                 // TODO can we do the same for ServerFrame? Probably not.
452         }
453         else
454                 Sys_Sleep((int)time);
455         delta = Sys_DirtyTime() - time0;
456         if (delta < 0 || delta >= 1800) 
457                 delta = 0;
458         host.sleeptime += delta;
459 //                      R_TimeReport("sleep");
460         return;
461 }
462
463 // Cloudwalk: Most overpowered function declaration...
464 static inline double Host_UpdateTime (double newtime, double oldtime)
465 {
466         double time = newtime - oldtime;
467
468         if (time < 0)
469         {
470                 // warn if it's significant
471                 if (time < -0.01)
472                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
473                 time = 0;
474         }
475         else if (time >= 1800)
476         {
477                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
478                 time = 0;
479         }
480
481         return time;
482 }
483
484 void Host_Main(void)
485 {
486         double time, newtime, oldtime, sleeptime;
487
488         Host_Init(); // Start!
489
490         host.realtime = 0;
491         oldtime = Sys_DirtyTime();
492
493         // Main event loop
494         while(host.state != host_shutdown)
495         {
496                 // Something bad happened, or the server disconnected
497                 if (setjmp(host.abortframe))
498                 {
499                         host.state = host_active; // In case we were loading
500                         continue;
501                 }
502
503                 newtime = host.dirtytime = Sys_DirtyTime();
504                 host.realtime += time = Host_UpdateTime(newtime, oldtime);
505
506                 sleeptime = Host_Frame(time);
507                 oldtime = newtime;
508
509                 if (sleeptime)
510                 {
511                         Host_Sleep(sleeptime);
512                         continue;
513                 }
514
515                 host.framecount++;
516         }
517
518         return;
519 }
520
521 //============================================================================
522
523 qbool vid_opened = false;
524 void Host_StartVideo(void)
525 {
526         if (!vid_opened && cls.state != ca_dedicated)
527         {
528                 vid_opened = true;
529 #ifdef WIN32
530                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
531                 NetConn_UpdateSockets();
532 #endif
533                 VID_Start();
534                 CDAudio_Startup();
535         }
536 }
537
538 char engineversion[128];
539
540 qbool sys_nostdout = false;
541
542 static qfile_t *locksession_fh = NULL;
543 static qbool locksession_run = false;
544 static void Host_InitSession(void)
545 {
546         int i;
547         char *buf;
548         Cvar_RegisterVariable(&sessionid);
549         Cvar_RegisterVariable(&locksession);
550
551         // load the session ID into the read-only cvar
552         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
553         {
554                 if(sys.argv[i+1][0] == '.')
555                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
556                 else
557                 {
558                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
559                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
560                         Cvar_SetQuick(&sessionid, buf);
561                 }
562         }
563 }
564 void Host_LockSession(void)
565 {
566         if(locksession_run)
567                 return;
568         locksession_run = true;
569         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
570         {
571                 char vabuf[1024];
572                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
573                 FS_CreatePath(p);
574                 locksession_fh = FS_SysOpen(p, "wl", false);
575                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
576                 if(!locksession_fh)
577                 {
578                         if(locksession.integer == 2)
579                         {
580                                 Con_Printf(CON_WARN "WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
581                         }
582                         else
583                         {
584                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
585                         }
586                 }
587         }
588 }
589 void Host_UnlockSession(void)
590 {
591         if(!locksession_run)
592                 return;
593         locksession_run = false;
594
595         if(locksession_fh)
596         {
597                 FS_Close(locksession_fh);
598                 // NOTE: we can NOT unlink the lock here, as doing so would
599                 // create a race condition if another process created it
600                 // between our close and our unlink
601                 locksession_fh = NULL;
602         }
603 }
604
605 /*
606 ====================
607 Host_Init
608 ====================
609 */
610 static void Host_Init (void)
611 {
612         int i;
613         const char* os;
614         char vabuf[1024];
615         cmd_state_t *cmd = &cmd_client;
616
617         host.state = host_init;
618
619         if (Sys_CheckParm("-profilegameonly"))
620                 Sys_AllowProfiling(false);
621
622         // LadyHavoc: quake never seeded the random number generator before... heh
623         if (Sys_CheckParm("-benchmark"))
624                 srand(0); // predictable random sequence for -benchmark
625         else
626                 srand((unsigned int)time(NULL));
627
628         // FIXME: this is evil, but possibly temporary
629         // LadyHavoc: doesn't seem very temporary...
630         // LadyHavoc: made this a saved cvar
631 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
632         if (Sys_CheckParm("-developer"))
633         {
634                 developer.value = developer.integer = 1;
635                 developer.string = "1";
636         }
637
638         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
639         {
640                 developer.value = developer.integer = 1;
641                 developer.string = "1";
642                 developer_extra.value = developer_extra.integer = 1;
643                 developer_extra.string = "1";
644                 developer_insane.value = developer_insane.integer = 1;
645                 developer_insane.string = "1";
646                 developer_memory.value = developer_memory.integer = 1;
647                 developer_memory.string = "1";
648                 developer_memorydebug.value = developer_memorydebug.integer = 1;
649                 developer_memorydebug.string = "1";
650         }
651
652         if (Sys_CheckParm("-developer3"))
653         {
654                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
655                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
656         }
657
658 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
659         if (Sys_CheckParm("-nostdout"))
660                 sys_nostdout = 1;
661
662         // initialize console command/cvar/alias/command execution systems
663         Cmd_Init();
664
665         // initialize memory subsystem cvars/commands
666         Memory_Init_Commands();
667
668         // initialize console and logging and its cvars/commands
669         Con_Init();
670
671         // initialize various cvars that could not be initialized earlier
672         u8_Init();
673         Curl_Init_Commands();
674         Sys_Init_Commands();
675         COM_Init_Commands();
676
677         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
678         FS_Init();
679
680         // construct a version string for the corner of the console
681         os = DP_OS_NAME;
682         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
683         Con_Printf("%s\n", engineversion);
684
685         // initialize process nice level
686         Sys_InitProcessNice();
687
688         // initialize ixtable
689         Mathlib_Init();
690
691         // register the cvars for session locking
692         Host_InitSession();
693
694         // must be after FS_Init
695         Crypto_Init();
696         Crypto_Init_Commands();
697
698         NetConn_Init();
699         Curl_Init();
700         PRVM_Init();
701         Mod_Init();
702         World_Init();
703         SV_Init();
704         Host_InitLocal();
705         Host_ServerOptions();
706
707         Thread_Init();
708         TaskQueue_Init();
709
710         CL_Init();
711
712         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
713         // NOTE: menu commands are freed by Cmd_RestoreInitState
714         Cmd_SaveInitState();
715
716         // FIXME: put this into some neat design, but the menu should be allowed to crash
717         // without crashing the whole game, so this should just be a short-time solution
718
719         // here comes the not so critical stuff
720         if (setjmp(host.abortframe)) {
721                 return;
722         }
723
724         Host_AddConfigText(cmd);
725
726         // if quake.rc is missing, use default
727         if (!FS_FileExists("quake.rc"))
728         {
729                 Cbuf_AddText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
730                 Cbuf_Execute(cmd->cbuf);
731         }
732
733         host.state = host_active;
734
735         Host_StartVideo();
736
737         Log_Start();
738
739         // put up the loading image so the user doesn't stare at a black screen...
740         SCR_BeginLoadingPlaque(true);
741 #ifdef CONFIG_MENU
742         if (cls.state != ca_dedicated)
743                 MR_Init();
744 #endif
745         // check for special benchmark mode
746 // 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)
747         i = Sys_CheckParm("-benchmark");
748         if (i && i + 1 < sys.argc)
749         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
750         {
751                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
752                 Cbuf_Execute((&cmd_client)->cbuf);
753         }
754
755         // check for special demo mode
756 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
757         i = Sys_CheckParm("-demo");
758         if (i && i + 1 < sys.argc)
759         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
760         {
761                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
762                 Cbuf_Execute((&cmd_client)->cbuf);
763         }
764
765 #ifdef CONFIG_VIDEO_CAPTURE
766 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
767         i = Sys_CheckParm("-capturedemo");
768         if (i && i + 1 < sys.argc)
769         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
770         {
771                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
772                 Cbuf_Execute((&cmd_client)->cbuf);
773         }
774 #endif
775
776         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
777         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
778         {
779                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
780                 Cbuf_Execute((&cmd_client)->cbuf);
781         }
782
783         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
784         {
785 #ifdef CONFIG_MENU
786                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
787 #endif
788                 Cbuf_Execute((&cmd_client)->cbuf);
789         }
790
791         Con_DPrint("========Initialized=========\n");
792
793         if (cls.state != ca_dedicated)
794                 SV_StartThread();
795 }
796
797
798 /*
799 ===============
800 Host_Shutdown
801
802 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
803 to run quit through here before the final handoff to the sys code.
804 ===============
805 */
806 void Host_Shutdown(void)
807 {
808         static qbool isdown = false;
809
810         if (isdown)
811         {
812                 Con_Print("recursive shutdown\n");
813                 return;
814         }
815         if (setjmp(host.abortframe))
816         {
817                 Con_Print("aborted the quitting frame?!?\n");
818                 return;
819         }
820         isdown = true;
821
822         if(cls.state != ca_dedicated)
823                 CL_Shutdown();
824
825         // end the server thread
826         if (svs.threaded)
827                 SV_StopThread();
828
829         // shut down local server if active
830         SV_LockThreadMutex();
831         SV_Shutdown ();
832         SV_UnlockThreadMutex();
833
834         // AK shutdown PRVM
835         // AK hmm, no PRVM_Shutdown(); yet
836
837         Host_SaveConfig();
838
839         Curl_Shutdown ();
840         NetConn_Shutdown ();
841
842         SV_StopThread();
843         TaskQueue_Shutdown();
844         Thread_Shutdown();
845         Cmd_Shutdown();
846         Sys_Shutdown();
847         Log_Close();
848         Crypto_Shutdown();
849
850         Host_UnlockSession();
851
852         Con_Shutdown();
853         Memory_Shutdown();
854 }
855
856 void Host_NoOperation_f(cmd_state_t *cmd)
857 {
858 }