]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
client: Implement CL_Frame. Move client cvars out of host to cl_main
[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 = {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"};
51 cvar_t cl_maxphysicsframesperserverframe = {CVAR_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
52 // shows time used by certain subsystems
53 cvar_t host_speeds = {CVAR_CLIENT | CVAR_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
54 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."};
55
56 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"};
57 cvar_t developer_extra = {CVAR_CLIENT | CVAR_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
58 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!"};
59 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)"};
60 cvar_t developer_loading = {CVAR_CLIENT | CVAR_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
61 cvar_t developer_entityparsing = {CVAR_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
62
63 cvar_t timestamps = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
64 cvar_t timeformat = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
65
66 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 (.)"};
67 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"};
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 qboolean 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 = COM_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 (COM_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 = COM_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 /*
221 =======================
222 Host_InitLocal
223 ======================
224 */
225 void Host_SaveConfig_f(cmd_state_t *cmd);
226 void Host_LoadConfig_f(cmd_state_t *cmd);
227 extern cvar_t sv_writepicture_quality;
228 extern cvar_t r_texture_jpeg_fastpicmip;
229 static void Host_InitLocal (void)
230 {
231         Cmd_AddCommand(CMD_SHARED, "quit", Host_Quit_f, "quit the game");
232         Cmd_AddCommand(CMD_SHARED, "version", Host_Version_f, "print engine version");
233         Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
234         Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
235         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
236         Cvar_RegisterVariable (&host_framerate);
237         Cvar_RegisterVariable (&host_speeds);
238         Cvar_RegisterVariable (&host_maxwait);
239
240         Cvar_RegisterVariable (&developer);
241         Cvar_RegisterVariable (&developer_extra);
242         Cvar_RegisterVariable (&developer_insane);
243         Cvar_RegisterVariable (&developer_loadfile);
244         Cvar_RegisterVariable (&developer_loading);
245         Cvar_RegisterVariable (&developer_entityparsing);
246
247         Cvar_RegisterVariable (&timestamps);
248         Cvar_RegisterVariable (&timeformat);
249
250         Cvar_RegisterVariable (&sv_writepicture_quality);
251         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
252 }
253
254
255 /*
256 ===============
257 Host_SaveConfig_f
258
259 Writes key bindings and archived cvars to config.cfg
260 ===============
261 */
262 static void Host_SaveConfig_to(const char *file)
263 {
264         qfile_t *f;
265
266 // dedicated servers initialize the host but don't parse and set the
267 // config.cfg cvars
268         // LadyHavoc: don't save a config if it crashed in startup
269         if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
270         {
271                 f = FS_OpenRealFile(file, "wb", false);
272                 if (!f)
273                 {
274                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
275                         return;
276                 }
277
278                 Key_WriteBindings (f);
279                 Cvar_WriteVariables (&cvars_all, f);
280
281                 FS_Close (f);
282         }
283 }
284 void Host_SaveConfig(void)
285 {
286         Host_SaveConfig_to(CONFIGFILENAME);
287 }
288 void Host_SaveConfig_f(cmd_state_t *cmd)
289 {
290         const char *file = CONFIGFILENAME;
291
292         if(Cmd_Argc(cmd) >= 2) {
293                 file = Cmd_Argv(cmd, 1);
294                 Con_Printf("Saving to %s\n", file);
295         }
296
297         Host_SaveConfig_to(file);
298 }
299
300 static void Host_AddConfigText(cmd_state_t *cmd)
301 {
302         // set up the default startmap_sp and startmap_dm aliases (mods can
303         // override these) and then execute the quake.rc startup script
304         if (gamemode == GAME_NEHAHRA)
305                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
306         else if (gamemode == GAME_TRANSFUSION)
307                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
308         else if (gamemode == GAME_TEU)
309                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
310         else
311                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
312         Cbuf_Execute(cmd);
313 }
314
315 /*
316 ===============
317 Host_LoadConfig_f
318
319 Resets key bindings and cvars to defaults and then reloads scripts
320 ===============
321 */
322 void Host_LoadConfig_f(cmd_state_t *cmd)
323 {
324         // reset all cvars, commands and aliases to init values
325         Cmd_RestoreInitState();
326 #ifdef CONFIG_MENU
327         // prepend a menu restart command to execute after the config
328         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
329 #endif
330         // reset cvars to their defaults, and then exec startup scripts again
331         Host_AddConfigText(&cmd_client);
332 }
333
334 //============================================================================
335
336 /*
337 ===================
338 Host_GetConsoleCommands
339
340 Add them exactly as if they had been typed at the console
341 ===================
342 */
343 static void Host_GetConsoleCommands (void)
344 {
345         char *line;
346
347         while ((line = Sys_ConsoleInput()))
348         {
349                 if (cls.state == ca_dedicated)
350                         Cbuf_AddText(&cmd_server, line);
351                 else
352                         Cbuf_AddText(&cmd_client, line);
353         }
354 }
355
356 /*
357 ==================
358 Host_TimeReport
359
360 Returns a time report string, for example for
361 ==================
362 */
363 const char *Host_TimingReport(char *buf, size_t buflen)
364 {
365         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);
366 }
367
368 /*
369 ==================
370 Host_Frame
371
372 Runs all active servers
373 ==================
374 */
375 static void Host_Init(void);
376 void Host_Main(void)
377 {
378         double cl_timer = 0, sv_timer = 0;
379         double time, oldtime, newtime;
380         double wait;
381         int i;
382         char vabuf[1024];
383         qboolean playing;
384
385         host.restless = false;
386
387         Host_Init();
388
389         host.realtime = 0;
390         host.sleeptime = 0;
391         host.dirtytime = oldtime = Sys_DirtyTime();
392
393         while(host.state != host_shutdown)
394         {
395                 if (setjmp(host.abortframe))
396                 {
397                         SCR_ClearLoadingScreen(false);
398                         continue;                       // something bad happened, or the server disconnected
399                 }
400
401                 newtime = host.dirtytime = Sys_DirtyTime();
402                 time = newtime - oldtime;
403                 if (time < 0)
404                 {
405                         // warn if it's significant
406                         if (time < -0.01)
407                                 Con_Printf(CON_WARN "Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
408                         time = 0;
409                 }
410                 else if (time >= 1800)
411                 {
412                         Con_Printf(CON_WARN "Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
413                         time = 0;
414                 }
415                 host.realtime += time;
416
417                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
418                         Cvar_SetValueQuick(&host_framerate, 0);
419
420                 TaskQueue_Frame(false);
421
422                 // keep the random time dependent, but not when playing demos/benchmarking
423                 if(!*sv_random_seed.string && !cls.demoplayback)
424                         rand();
425
426                 NetConn_UpdateSockets();
427
428                 Log_DestBuffer_Flush();
429
430                 Curl_Run();
431
432                 // check for commands typed to the host
433                 Host_GetConsoleCommands();
434
435                 // process console commands
436 //              R_TimeReport("preconsole");
437                 CL_VM_PreventInformationLeaks();
438                 Cbuf_Frame(&cmd_client);
439                 Cbuf_Frame(&cmd_server);
440
441                 if(sv.active)
442                         Cbuf_Frame(&cmd_serverfromclient);
443
444 //              R_TimeReport("console");
445
446                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
447
448                 R_TimeReport("---");
449
450         //-------------------
451         //
452         // server operations
453         //
454         //-------------------
455
456                 // limit the frametime steps to no more than 100ms each
457                 if (sv_timer > 0.1)
458                 {
459                         if (!svs.threaded)
460                                 svs.perf_acc_lost += (sv_timer - 0.1);
461                         sv_timer = 0.1;
462                 }
463
464                 if (!svs.threaded)
465                 {
466                         svs.perf_acc_sleeptime = host.sleeptime;
467                         svs.perf_acc_realtime += time;
468
469                         // Look for clients who have spawned
470                         playing = false;
471                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
472                                 if(host_client->begun)
473                                         if(host_client->netconnection)
474                                                 playing = true;
475                         if(sv.time < 10)
476                         {
477                                 // don't accumulate time for the first 10 seconds of a match
478                                 // so things can settle
479                                 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 = host.sleeptime = 0;
480                         }
481                         else if(svs.perf_acc_realtime > 5)
482                         {
483                                 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
484                                 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
485                                 if(svs.perf_acc_offset_samples > 0)
486                                 {
487                                         svs.perf_offset_max = svs.perf_acc_offset_max;
488                                         svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
489                                         svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
490                                 }
491                                 if(svs.perf_lost > 0 && developer_extra.integer)
492                                         if(playing) // only complain if anyone is looking
493                                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
494                                 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 = host.sleeptime = 0;
495                         }
496
497                         if (sv.active && sv_timer > 0)
498                         {
499                                 // execute one or more server frames, with an upper limit on how much
500                                 // execution time to spend on server frames to avoid freezing the game if
501                                 // the server is overloaded, this execution time limit means the game will
502                                 // slow down if the server is taking too long.
503                                 int framecount, framelimit = 1;
504                                 double advancetime, aborttime = 0;
505                                 float offset;
506                                 prvm_prog_t *prog = SVVM_prog;
507                                 // receive packets on each main loop iteration, as the main loop may
508                                 // be undersleeping due to select() detecting a new packet
509                                 if (sv.active && !svs.threaded)
510                                         NetConn_ServerFrame();
511                                 // run the world state
512                                 // don't allow simulation to run too fast or too slow or logic glitches can occur
513
514                                 // stop running server frames if the wall time reaches this value
515                                 if (sys_ticrate.value <= 0)
516                                         advancetime = sv_timer;
517                                 else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
518                                 {
519                                         // synchronize to the client frametime, but no less than 10ms and no more than 100ms
520                                         advancetime = bound(0.01, cl_timer, 0.1);
521                                 }
522                                 else
523                                 {
524                                         advancetime = sys_ticrate.value;
525                                         // listen servers can run multiple server frames per client frame
526                                         framelimit = cl_maxphysicsframesperserverframe.integer;
527                                         aborttime = Sys_DirtyTime() + 0.1;
528                                 }
529                                 if(host_timescale.value > 0 && host_timescale.value < 1)
530                                         advancetime = min(advancetime, 0.1 / host_timescale.value);
531                                 else
532                                         advancetime = min(advancetime, 0.1);
533
534                                 if(advancetime > 0)
535                                 {
536                                         offset = Sys_DirtyTime() - newtime;if (offset < 0 || offset >= 1800) offset = 0;
537                                         offset += sv_timer;
538                                         ++svs.perf_acc_offset_samples;
539                                         svs.perf_acc_offset += offset;
540                                         svs.perf_acc_offset_squared += offset * offset;
541                                         if(svs.perf_acc_offset_max < offset)
542                                                 svs.perf_acc_offset_max = offset;
543                                 }
544
545                                 // only advance time if not paused
546                                 // the game also pauses in singleplayer when menu or console is used
547                                 sv.frametime = advancetime * host_timescale.value;
548                                 if (host_framerate.value)
549                                         sv.frametime = host_framerate.value;
550                                 if (sv.paused || host.paused)
551                                         sv.frametime = 0;
552
553                                 for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
554                                 {
555                                         sv_timer -= advancetime;
556
557                                         // move things around and think unless paused
558                                         if (sv.frametime)
559                                                 SV_Physics();
560
561                                         // if this server frame took too long, break out of the loop
562                                         if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
563                                                 break;
564                                 }
565                                 R_TimeReport("serverphysics");
566
567                                 // send all messages to the clients
568                                 SV_SendClientMessages();
569
570                                 if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
571                                         prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
572                                         PRVM_serverglobalfloat(time) = sv.time;
573                                         prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
574                                 }
575
576                                 // send an heartbeat if enough time has passed since the last one
577                                 NetConn_Heartbeat(0);
578                                 R_TimeReport("servernetwork");
579                         }
580                         else
581                         {
582                                 // don't let r_speeds display jump around
583                                 R_TimeReport("serverphysics");
584                                 R_TimeReport("servernetwork");
585                         }
586                 }
587                 // if there is some time remaining from this frame, reset the timer
588                 if (sv_timer >= 0)
589                 {
590                         if (!svs.threaded)
591                                 svs.perf_acc_lost += sv_timer;
592                         sv_timer = 0;
593                 }
594
595                 sv_timer += time;
596
597         //-------------------
598         //
599         // client operations
600         //
601         //-------------------
602
603                 cl_timer = CL_Frame(cl_timer);
604                 cl_timer += time;
605
606 #if MEMPARANOIA
607                 Mem_CheckSentinelsGlobal();
608 #else
609                 if (developer_memorydebug.integer)
610                         Mem_CheckSentinelsGlobal();
611 #endif
612
613                 // if the accumulators haven't become positive yet, wait a while
614                 wait = max(cl_timer, sv_timer) * -1000000.0;
615
616                 if (!host.restless && wait >= 1)
617                 {
618                         double time0, delta;
619
620                         if(host_maxwait.value <= 0)
621                                 wait = min(wait, 1000000.0);
622                         else
623                                 wait = min(wait, host_maxwait.value * 1000.0);
624                         if(wait < 1)
625                                 wait = 1; // because we cast to int
626
627                         time0 = Sys_DirtyTime();
628                         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
629                                 NetConn_SleepMicroseconds((int)wait);
630                                 if (cls.state != ca_dedicated)
631                                         NetConn_ClientFrame(); // helps server browser get good ping values
632                                 // TODO can we do the same for ServerFrame? Probably not.
633                         }
634                         else
635                                 Sys_Sleep((int)wait);
636                         delta = Sys_DirtyTime() - time0;
637                         if (delta < 0 || delta >= 1800) 
638                                 delta = 0;
639                         host.sleeptime += delta;
640 //                      R_TimeReport("sleep");
641                 }
642
643                 host.framecount++;
644                 oldtime = newtime;
645         }
646
647         Sys_Quit(0);
648 }
649
650 //============================================================================
651
652 qboolean vid_opened = false;
653 void Host_StartVideo(void)
654 {
655         if (!vid_opened && cls.state != ca_dedicated)
656         {
657                 vid_opened = true;
658                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
659                 NetConn_UpdateSockets();
660                 VID_Start();
661                 CDAudio_Startup();
662         }
663 }
664
665 char engineversion[128];
666
667 qboolean sys_nostdout = false;
668
669 static qfile_t *locksession_fh = NULL;
670 static qboolean locksession_run = false;
671 static void Host_InitSession(void)
672 {
673         int i;
674         char *buf;
675         Cvar_RegisterVariable(&sessionid);
676         Cvar_RegisterVariable(&locksession);
677
678         // load the session ID into the read-only cvar
679         if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
680         {
681                 if(sys.argv[i+1][0] == '.')
682                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
683                 else
684                 {
685                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
686                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
687                         Cvar_SetQuick(&sessionid, buf);
688                 }
689         }
690 }
691 void Host_LockSession(void)
692 {
693         if(locksession_run)
694                 return;
695         locksession_run = true;
696         if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
697         {
698                 char vabuf[1024];
699                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
700                 FS_CreatePath(p);
701                 locksession_fh = FS_SysOpen(p, "wl", false);
702                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
703                 if(!locksession_fh)
704                 {
705                         if(locksession.integer == 2)
706                         {
707                                 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);
708                         }
709                         else
710                         {
711                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
712                         }
713                 }
714         }
715 }
716 void Host_UnlockSession(void)
717 {
718         if(!locksession_run)
719                 return;
720         locksession_run = false;
721
722         if(locksession_fh)
723         {
724                 FS_Close(locksession_fh);
725                 // NOTE: we can NOT unlink the lock here, as doing so would
726                 // create a race condition if another process created it
727                 // between our close and our unlink
728                 locksession_fh = NULL;
729         }
730 }
731
732 /*
733 ====================
734 Host_Init
735 ====================
736 */
737 static void Host_Init (void)
738 {
739         int i;
740         const char* os;
741         char vabuf[1024];
742         cmd_state_t *cmd = &cmd_client;
743
744         host.state = host_init;
745
746         if (COM_CheckParm("-profilegameonly"))
747                 Sys_AllowProfiling(false);
748
749         // LadyHavoc: quake never seeded the random number generator before... heh
750         if (COM_CheckParm("-benchmark"))
751                 srand(0); // predictable random sequence for -benchmark
752         else
753                 srand((unsigned int)time(NULL));
754
755         // FIXME: this is evil, but possibly temporary
756         // LadyHavoc: doesn't seem very temporary...
757         // LadyHavoc: made this a saved cvar
758 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
759         if (COM_CheckParm("-developer"))
760         {
761                 developer.value = developer.integer = 1;
762                 developer.string = "1";
763         }
764
765         if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
766         {
767                 developer.value = developer.integer = 1;
768                 developer.string = "1";
769                 developer_extra.value = developer_extra.integer = 1;
770                 developer_extra.string = "1";
771                 developer_insane.value = developer_insane.integer = 1;
772                 developer_insane.string = "1";
773                 developer_memory.value = developer_memory.integer = 1;
774                 developer_memory.string = "1";
775                 developer_memorydebug.value = developer_memorydebug.integer = 1;
776                 developer_memorydebug.string = "1";
777         }
778
779         if (COM_CheckParm("-developer3"))
780         {
781                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
782                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
783         }
784
785 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
786         if (COM_CheckParm("-nostdout"))
787                 sys_nostdout = 1;
788
789         // used by everything
790         Memory_Init();
791
792         // initialize console command/cvar/alias/command execution systems
793         Cmd_Init();
794
795         // initialize memory subsystem cvars/commands
796         Memory_Init_Commands();
797
798         // initialize console and logging and its cvars/commands
799         Con_Init();
800
801         // initialize various cvars that could not be initialized earlier
802         u8_Init();
803         Curl_Init_Commands();
804         Sys_Init_Commands();
805         COM_Init_Commands();
806
807         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
808         FS_Init();
809
810         // construct a version string for the corner of the console
811         os = DP_OS_NAME;
812         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
813         Con_Printf("%s\n", engineversion);
814
815         // initialize process nice level
816         Sys_InitProcessNice();
817
818         // initialize ixtable
819         Mathlib_Init();
820
821         // register the cvars for session locking
822         Host_InitSession();
823
824         // must be after FS_Init
825         Crypto_Init();
826         Crypto_Init_Commands();
827
828         NetConn_Init();
829         Curl_Init();
830         PRVM_Init();
831         Mod_Init();
832         World_Init();
833         SV_Init();
834         V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
835         Host_InitLocal();
836         Host_ServerOptions();
837
838         Thread_Init();
839         TaskQueue_Init();
840
841         CL_Init();
842
843         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
844         // NOTE: menu commands are freed by Cmd_RestoreInitState
845         Cmd_SaveInitState();
846
847         // FIXME: put this into some neat design, but the menu should be allowed to crash
848         // without crashing the whole game, so this should just be a short-time solution
849
850         // here comes the not so critical stuff
851         if (setjmp(host.abortframe)) {
852                 return;
853         }
854
855         Host_AddConfigText(cmd);
856
857         Host_StartVideo();
858
859         // if quake.rc is missing, use default
860         if (!FS_FileExists("quake.rc"))
861         {
862                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
863                 Cbuf_Execute(cmd);
864         }
865
866         host.state = host_active;
867
868         // run stuffcmds now, deferred previously because it can crash if a server starts that early
869         Cbuf_AddText(cmd,"stuffcmds\n");
870         Cbuf_Execute(cmd);
871
872         Log_Start();
873
874         // put up the loading image so the user doesn't stare at a black screen...
875         SCR_BeginLoadingPlaque(true);
876         
877         // check for special benchmark mode
878 // 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)
879         i = COM_CheckParm("-benchmark");
880         if (i && i + 1 < sys.argc)
881         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
882         {
883                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
884                 Cbuf_Execute(&cmd_client);
885         }
886
887         // check for special demo mode
888 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
889         i = COM_CheckParm("-demo");
890         if (i && i + 1 < sys.argc)
891         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
892         {
893                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
894                 Cbuf_Execute(&cmd_client);
895         }
896
897 #ifdef CONFIG_VIDEO_CAPTURE
898 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
899         i = COM_CheckParm("-capturedemo");
900         if (i && i + 1 < sys.argc)
901         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
902         {
903                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
904                 Cbuf_Execute(&cmd_client);
905         }
906 #endif
907
908         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
909         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
910         {
911                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
912                 Cbuf_Execute(&cmd_client);
913         }
914
915         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
916         {
917 #ifdef CONFIG_MENU
918                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
919 #endif
920                 Cbuf_Execute(&cmd_client);
921         }
922
923         Con_DPrint("========Initialized=========\n");
924
925         if (cls.state != ca_dedicated)
926                 SV_StartThread();
927 }
928
929
930 /*
931 ===============
932 Host_Shutdown
933
934 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
935 to run quit through here before the final handoff to the sys code.
936 ===============
937 */
938 void Host_Shutdown(void)
939 {
940         static qboolean isdown = false;
941
942         if (isdown)
943         {
944                 Con_Print("recursive shutdown\n");
945                 return;
946         }
947         if (setjmp(host.abortframe))
948         {
949                 Con_Print("aborted the quitting frame?!?\n");
950                 return;
951         }
952         isdown = true;
953
954         if(cls.state != ca_dedicated)
955                 CL_Shutdown();
956
957         // end the server thread
958         if (svs.threaded)
959                 SV_StopThread();
960
961         // shut down local server if active
962         SV_LockThreadMutex();
963         SV_Shutdown ();
964         SV_UnlockThreadMutex();
965
966         // AK shutdown PRVM
967         // AK hmm, no PRVM_Shutdown(); yet
968
969         Host_SaveConfig();
970
971         Curl_Shutdown ();
972         NetConn_Shutdown ();
973
974         SV_StopThread();
975         TaskQueue_Shutdown();
976         Thread_Shutdown();
977         Cmd_Shutdown();
978         Sys_Shutdown();
979         Log_Close();
980         Crypto_Shutdown();
981
982         Host_UnlockSession();
983
984         Con_Shutdown();
985         Memory_Shutdown();
986 }
987
988 void Host_NoOperation_f(cmd_state_t *cmd)
989 {
990 }