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