]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
host: Remove redundant check
[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 cvar_t cl_minfps = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps", "40", "minimum fps target - while the rendering performance is below this, it will drift toward lower quality"};
56 cvar_t cl_minfps_fade = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_fade", "1", "how fast the quality adapts to varying framerate"};
57 cvar_t cl_minfps_qualitymax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
58 cvar_t cl_minfps_qualitymin = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
59 cvar_t cl_minfps_qualitymultiply = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymultiply", "0.2", "multiplier for quality changes in quality change per second render time (1 assumes linearity of quality and render time)"};
60 cvar_t cl_minfps_qualityhysteresis = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualityhysteresis", "0.05", "reduce all quality increments by this to reduce flickering"};
61 cvar_t cl_minfps_qualitystepmax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitystepmax", "0.1", "maximum quality change in a single frame"};
62 cvar_t cl_minfps_force = {CVAR_CLIENT, "cl_minfps_force", "0", "also apply quality reductions in timedemo/capturevideo"};
63 cvar_t cl_maxfps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxfps", "0", "maximum fps cap, 0 = unlimited, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
64 cvar_t cl_maxfps_alwayssleep = {CVAR_CLIENT, "cl_maxfps_alwayssleep","1", "gives up some processing time to other applications each frame, value in milliseconds, disabled if cl_maxfps is 0"};
65 cvar_t cl_maxidlefps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxidlefps", "20", "maximum fps cap when the game is not the active window (makes cpu time available to other programs"};
66
67 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"};
68 cvar_t developer_extra = {CVAR_CLIENT | CVAR_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
69 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!"};
70 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)"};
71 cvar_t developer_loading = {CVAR_CLIENT | CVAR_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
72 cvar_t developer_entityparsing = {CVAR_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
73
74 cvar_t timestamps = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
75 cvar_t timeformat = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
76
77 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 (.)"};
78 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"};
79
80 /*
81 ================
82 Host_AbortCurrentFrame
83
84 aborts the current host frame and goes on with the next one
85 ================
86 */
87 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
88 void Host_AbortCurrentFrame(void)
89 {
90         // in case we were previously nice, make us mean again
91         Sys_MakeProcessMean();
92
93         longjmp (host.abortframe, 1);
94 }
95
96 /*
97 ================
98 Host_Error
99
100 This shuts down both the client and server
101 ================
102 */
103 void Host_Error (const char *error, ...)
104 {
105         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
106         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
107         static qboolean hosterror = false;
108         va_list argptr;
109
110         // turn off rcon redirect if it was active when the crash occurred
111         // to prevent loops when it is a networking problem
112         Con_Rcon_Redirect_Abort();
113
114         va_start (argptr,error);
115         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
116         va_end (argptr);
117
118         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
119
120         // LadyHavoc: if crashing very early, or currently shutting down, do
121         // Sys_Error instead
122         if (host.framecount < 3 || host.state == host_shutdown)
123                 Sys_Error ("Host_Error: %s", hosterrorstring1);
124
125         if (hosterror)
126                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
127         hosterror = true;
128
129         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
130
131         CL_Parse_DumpPacket();
132
133         CL_Parse_ErrorCleanUp();
134
135         //PR_Crash();
136
137         // print out where the crash happened, if it was caused by QC (and do a cleanup)
138         PRVM_Crash(SVVM_prog);
139         PRVM_Crash(CLVM_prog);
140 #ifdef CONFIG_MENU
141         PRVM_Crash(MVM_prog);
142 #endif
143
144         cl.csqc_loaded = false;
145         Cvar_SetValueQuick(&csqc_progcrc, -1);
146         Cvar_SetValueQuick(&csqc_progsize, -1);
147
148         SV_LockThreadMutex();
149         SV_Shutdown ();
150         SV_UnlockThreadMutex();
151
152         if (cls.state == ca_dedicated)
153                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
154
155         CL_Disconnect ();
156         cls.demonum = -1;
157
158         hosterror = false;
159
160         Host_AbortCurrentFrame();
161 }
162
163 static void Host_ServerOptions (void)
164 {
165         int i;
166
167         // general default
168         svs.maxclients = 8;
169
170 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
171 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
172         // if no client is in the executable or -dedicated is specified on
173         // commandline, start a dedicated server
174         i = COM_CheckParm ("-dedicated");
175         if (i || !cl_available)
176         {
177                 cls.state = ca_dedicated;
178                 // check for -dedicated specifying how many players
179                 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
180                         svs.maxclients = atoi (sys.argv[i+1]);
181                 if (COM_CheckParm ("-listen"))
182                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
183                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
184                 Cvar_SetValue(&cvars_all, "sv_public", 1);
185         }
186         else if (cl_available)
187         {
188                 // client exists and not dedicated, check if -listen is specified
189                 cls.state = ca_disconnected;
190                 i = COM_CheckParm ("-listen");
191                 if (i)
192                 {
193                         // default players unless specified
194                         if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
195                                 svs.maxclients = atoi (sys.argv[i+1]);
196                 }
197                 else
198                 {
199                         // default players in some games, singleplayer in most
200                         if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
201                                 svs.maxclients = 1;
202                 }
203         }
204
205         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
206
207         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
208
209         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
210                 Cvar_SetValueQuick(&deathmatch, 1);
211 }
212
213 /*
214 ==================
215 Host_Quit_f
216 ==================
217 */
218 void Host_Quit_f(cmd_state_t *cmd)
219 {
220         if(host.state == host_shutdown)
221                 Con_Printf("shutting down already!\n");
222         else
223                 host.state = host_shutdown;
224 }
225
226 static void Host_Version_f(cmd_state_t *cmd)
227 {
228         Con_Printf("Version: %s build %s\n", gamename, buildstring);
229 }
230
231 /*
232 =======================
233 Host_InitLocal
234 ======================
235 */
236 void Host_SaveConfig_f(cmd_state_t *cmd);
237 void Host_LoadConfig_f(cmd_state_t *cmd);
238 extern cvar_t sv_writepicture_quality;
239 extern cvar_t r_texture_jpeg_fastpicmip;
240 static void Host_InitLocal (void)
241 {
242         Cmd_AddCommand(CMD_SHARED, "quit", Host_Quit_f, "quit the game");
243         Cmd_AddCommand(CMD_SHARED, "version", Host_Version_f, "print engine version");
244         Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
245         Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
246         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
247         Cvar_RegisterVariable (&host_framerate);
248         Cvar_RegisterVariable (&host_speeds);
249         Cvar_RegisterVariable (&host_maxwait);
250         Cvar_RegisterVariable (&cl_minfps);
251         Cvar_RegisterVariable (&cl_minfps_fade);
252         Cvar_RegisterVariable (&cl_minfps_qualitymax);
253         Cvar_RegisterVariable (&cl_minfps_qualitymin);
254         Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
255         Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
256         Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
257         Cvar_RegisterVariable (&cl_minfps_force);
258         Cvar_RegisterVariable (&cl_maxfps);
259         Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
260         Cvar_RegisterVariable (&cl_maxidlefps);
261
262         Cvar_RegisterVariable (&developer);
263         Cvar_RegisterVariable (&developer_extra);
264         Cvar_RegisterVariable (&developer_insane);
265         Cvar_RegisterVariable (&developer_loadfile);
266         Cvar_RegisterVariable (&developer_loading);
267         Cvar_RegisterVariable (&developer_entityparsing);
268
269         Cvar_RegisterVariable (&timestamps);
270         Cvar_RegisterVariable (&timeformat);
271
272         Cvar_RegisterVariable (&sv_writepicture_quality);
273         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
274 }
275
276
277 /*
278 ===============
279 Host_SaveConfig_f
280
281 Writes key bindings and archived cvars to config.cfg
282 ===============
283 */
284 static void Host_SaveConfig_to(const char *file)
285 {
286         qfile_t *f;
287
288 // dedicated servers initialize the host but don't parse and set the
289 // config.cfg cvars
290         // LadyHavoc: don't save a config if it crashed in startup
291         if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
292         {
293                 f = FS_OpenRealFile(file, "wb", false);
294                 if (!f)
295                 {
296                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
297                         return;
298                 }
299
300                 Key_WriteBindings (f);
301                 Cvar_WriteVariables (&cvars_all, f);
302
303                 FS_Close (f);
304         }
305 }
306 void Host_SaveConfig(void)
307 {
308         Host_SaveConfig_to(CONFIGFILENAME);
309 }
310 void Host_SaveConfig_f(cmd_state_t *cmd)
311 {
312         const char *file = CONFIGFILENAME;
313
314         if(Cmd_Argc(cmd) >= 2) {
315                 file = Cmd_Argv(cmd, 1);
316                 Con_Printf("Saving to %s\n", file);
317         }
318
319         Host_SaveConfig_to(file);
320 }
321
322 static void Host_AddConfigText(cmd_state_t *cmd)
323 {
324         // set up the default startmap_sp and startmap_dm aliases (mods can
325         // override these) and then execute the quake.rc startup script
326         if (gamemode == GAME_NEHAHRA)
327                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
328         else if (gamemode == GAME_TRANSFUSION)
329                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
330         else if (gamemode == GAME_TEU)
331                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
332         else
333                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
334         Cbuf_Execute(cmd);
335 }
336
337 /*
338 ===============
339 Host_LoadConfig_f
340
341 Resets key bindings and cvars to defaults and then reloads scripts
342 ===============
343 */
344 void Host_LoadConfig_f(cmd_state_t *cmd)
345 {
346         // reset all cvars, commands and aliases to init values
347         Cmd_RestoreInitState();
348 #ifdef CONFIG_MENU
349         // prepend a menu restart command to execute after the config
350         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
351 #endif
352         // reset cvars to their defaults, and then exec startup scripts again
353         Host_AddConfigText(&cmd_client);
354 }
355
356 //============================================================================
357
358 /*
359 ===================
360 Host_GetConsoleCommands
361
362 Add them exactly as if they had been typed at the console
363 ===================
364 */
365 static void Host_GetConsoleCommands (void)
366 {
367         char *line;
368
369         while ((line = Sys_ConsoleInput()))
370         {
371                 if (cls.state == ca_dedicated)
372                         Cbuf_AddText(&cmd_server, line);
373                 else
374                         Cbuf_AddText(&cmd_client, line);
375         }
376 }
377
378 /*
379 ==================
380 Host_TimeReport
381
382 Returns a time report string, for example for
383 ==================
384 */
385 const char *Host_TimingReport(char *buf, size_t buflen)
386 {
387         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);
388 }
389
390 /*
391 ==================
392 Host_Frame
393
394 Runs all active servers
395 ==================
396 */
397 static void Host_Init(void);
398 void Host_Main(void)
399 {
400         double time1 = 0;
401         double time2 = 0;
402         double time3 = 0;
403         double cl_timer = 0, sv_timer = 0;
404         double clframetime, time, oldtime, newtime;
405         double wait;
406         int pass1, pass2, pass3, i;
407         char vabuf[1024];
408         qboolean playing;
409
410         host.restless = false;
411
412         Host_Init();
413
414         host.realtime = 0;
415         host.sleeptime = 0;
416         host.dirtytime = oldtime = Sys_DirtyTime();
417
418         while(host.state != host_shutdown)
419         {
420                 if (setjmp(host.abortframe))
421                 {
422                         SCR_ClearLoadingScreen(false);
423                         continue;                       // something bad happened, or the server disconnected
424                 }
425
426                 newtime = host.dirtytime = Sys_DirtyTime();
427                 time = newtime - oldtime;
428                 if (time < 0)
429                 {
430                         // warn if it's significant
431                         if (time < -0.01)
432                                 Con_Printf(CON_WARN "Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
433                         time = 0;
434                 }
435                 else if (time >= 1800)
436                 {
437                         Con_Printf(CON_WARN "Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
438                         time = 0;
439                 }
440                 host.realtime += time;
441
442                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
443                         Cvar_SetValueQuick(&host_framerate, 0);
444
445                 TaskQueue_Frame(false);
446
447                 // keep the random time dependent, but not when playing demos/benchmarking
448                 if(!*sv_random_seed.string && !cls.demoplayback)
449                         rand();
450
451                 NetConn_UpdateSockets();
452
453                 Log_DestBuffer_Flush();
454
455                 Curl_Run();
456
457                 // check for commands typed to the host
458                 Host_GetConsoleCommands();
459
460                 // process console commands
461 //              R_TimeReport("preconsole");
462                 CL_VM_PreventInformationLeaks();
463                 Cbuf_Frame(&cmd_client);
464                 Cbuf_Frame(&cmd_server);
465
466                 if(sv.active)
467                         Cbuf_Frame(&cmd_serverfromclient);
468
469 //              R_TimeReport("console");
470
471                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
472
473                 R_TimeReport("---");
474
475         //-------------------
476         //
477         // server operations
478         //
479         //-------------------
480
481                 // limit the frametime steps to no more than 100ms each
482                 if (sv_timer > 0.1)
483                 {
484                         if (!svs.threaded)
485                                 svs.perf_acc_lost += (sv_timer - 0.1);
486                         sv_timer = 0.1;
487                 }
488
489                 if (!svs.threaded)
490                 {
491                         svs.perf_acc_sleeptime = host.sleeptime;
492                         svs.perf_acc_realtime += time;
493
494                         // Look for clients who have spawned
495                         playing = false;
496                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
497                                 if(host_client->begun)
498                                         if(host_client->netconnection)
499                                                 playing = true;
500                         if(sv.time < 10)
501                         {
502                                 // don't accumulate time for the first 10 seconds of a match
503                                 // so things can settle
504                                 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;
505                         }
506                         else if(svs.perf_acc_realtime > 5)
507                         {
508                                 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
509                                 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
510                                 if(svs.perf_acc_offset_samples > 0)
511                                 {
512                                         svs.perf_offset_max = svs.perf_acc_offset_max;
513                                         svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
514                                         svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
515                                 }
516                                 if(svs.perf_lost > 0 && developer_extra.integer)
517                                         if(playing) // only complain if anyone is looking
518                                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
519                                 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;
520                         }
521
522                         if (sv.active && sv_timer > 0)
523                         {
524                                 // execute one or more server frames, with an upper limit on how much
525                                 // execution time to spend on server frames to avoid freezing the game if
526                                 // the server is overloaded, this execution time limit means the game will
527                                 // slow down if the server is taking too long.
528                                 int framecount, framelimit = 1;
529                                 double advancetime, aborttime = 0;
530                                 float offset;
531                                 prvm_prog_t *prog = SVVM_prog;
532                                 // receive packets on each main loop iteration, as the main loop may
533                                 // be undersleeping due to select() detecting a new packet
534                                 if (sv.active && !svs.threaded)
535                                         NetConn_ServerFrame();
536                                 // run the world state
537                                 // don't allow simulation to run too fast or too slow or logic glitches can occur
538
539                                 // stop running server frames if the wall time reaches this value
540                                 if (sys_ticrate.value <= 0)
541                                         advancetime = sv_timer;
542                                 else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
543                                 {
544                                         // synchronize to the client frametime, but no less than 10ms and no more than 100ms
545                                         advancetime = bound(0.01, cl_timer, 0.1);
546                                 }
547                                 else
548                                 {
549                                         advancetime = sys_ticrate.value;
550                                         // listen servers can run multiple server frames per client frame
551                                         framelimit = cl_maxphysicsframesperserverframe.integer;
552                                         aborttime = Sys_DirtyTime() + 0.1;
553                                 }
554                                 if(host_timescale.value > 0 && host_timescale.value < 1)
555                                         advancetime = min(advancetime, 0.1 / host_timescale.value);
556                                 else
557                                         advancetime = min(advancetime, 0.1);
558
559                                 if(advancetime > 0)
560                                 {
561                                         offset = Sys_DirtyTime() - newtime;if (offset < 0 || offset >= 1800) offset = 0;
562                                         offset += sv_timer;
563                                         ++svs.perf_acc_offset_samples;
564                                         svs.perf_acc_offset += offset;
565                                         svs.perf_acc_offset_squared += offset * offset;
566                                         if(svs.perf_acc_offset_max < offset)
567                                                 svs.perf_acc_offset_max = offset;
568                                 }
569
570                                 // only advance time if not paused
571                                 // the game also pauses in singleplayer when menu or console is used
572                                 sv.frametime = advancetime * host_timescale.value;
573                                 if (host_framerate.value)
574                                         sv.frametime = host_framerate.value;
575                                 if (sv.paused || host.paused)
576                                         sv.frametime = 0;
577
578                                 for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
579                                 {
580                                         sv_timer -= advancetime;
581
582                                         // move things around and think unless paused
583                                         if (sv.frametime)
584                                                 SV_Physics();
585
586                                         // if this server frame took too long, break out of the loop
587                                         if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
588                                                 break;
589                                 }
590                                 R_TimeReport("serverphysics");
591
592                                 // send all messages to the clients
593                                 SV_SendClientMessages();
594
595                                 if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
596                                         prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
597                                         PRVM_serverglobalfloat(time) = sv.time;
598                                         prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
599                                 }
600
601                                 // send an heartbeat if enough time has passed since the last one
602                                 NetConn_Heartbeat(0);
603                                 R_TimeReport("servernetwork");
604                         }
605                         else
606                         {
607                                 // don't let r_speeds display jump around
608                                 R_TimeReport("serverphysics");
609                                 R_TimeReport("servernetwork");
610                         }
611                 }
612                 // if there is some time remaining from this frame, reset the timer
613                 if (sv_timer >= 0)
614                 {
615                         if (!svs.threaded)
616                                 svs.perf_acc_lost += sv_timer;
617                         sv_timer = 0;
618                 }
619
620                 sv_timer += time;
621
622         //-------------------
623         //
624         // client operations
625         //
626         //-------------------
627
628                 // limit the frametime steps to no more than 100ms each
629                 if (cl_timer > 0.1)
630                         cl_timer = 0.1;
631
632                 // get new key events
633                 Key_EventQueue_Unblock();
634                 SndSys_SendKeyEvents();
635                 Sys_SendKeyEvents();
636
637                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
638                 {
639                         R_TimeReport("---");
640                         Collision_Cache_NewFrame();
641                         R_TimeReport("photoncache");
642 #ifdef CONFIG_VIDEO_CAPTURE
643                         // decide the simulation time
644                         if (cls.capturevideo.active)
645                         {
646                                 //***
647                                 if (cls.capturevideo.realtime)
648                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
649                                 else
650                                 {
651                                         clframetime = 1.0 / cls.capturevideo.framerate;
652                                         cl.realframetime = max(cl_timer, clframetime);
653                                 }
654                         }
655                         else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
656
657 #else
658                         if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
659 #endif
660                         {
661                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
662                                 // when running slow, we need to sleep to keep input responsive
663                                 wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
664                                 if (wait > 0)
665                                         Sys_Sleep((int)wait);
666                         }
667                         else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
668                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
669                         else
670                                 clframetime = cl.realframetime = cl_timer;
671
672                         // apply slowmo scaling
673                         clframetime *= cl.movevars_timescale;
674                         // scale playback speed of demos by slowmo cvar
675                         if (cls.demoplayback)
676                         {
677                                 clframetime *= host_timescale.value;
678                                 // if demo playback is paused, don't advance time at all
679                                 if (cls.demopaused)
680                                         clframetime = 0;
681                         }
682                         else
683                         {
684                                 // host_framerate overrides all else
685                                 if (host_framerate.value)
686                                         clframetime = host_framerate.value;
687
688                                 if (cl.paused || host.paused)
689                                         clframetime = 0;
690                         }
691
692                         if (cls.timedemo)
693                                 clframetime = cl.realframetime = cl_timer;
694
695                         // deduct the frame time from the accumulator
696                         cl_timer -= cl.realframetime;
697
698                         cl.oldtime = cl.time;
699                         cl.time += clframetime;
700
701                         // update video
702                         if (host_speeds.integer)
703                                 time1 = Sys_DirtyTime();
704                         R_TimeReport("pre-input");
705
706                         // Collect input into cmd
707                         CL_Input();
708
709                         R_TimeReport("input");
710
711                         // check for new packets
712                         NetConn_ClientFrame();
713
714                         // read a new frame from a demo if needed
715                         CL_ReadDemoMessage();
716                         R_TimeReport("clientnetwork");
717
718                         // now that packets have been read, send input to server
719                         CL_SendMove();
720                         R_TimeReport("sendmove");
721
722                         // update client world (interpolate entities, create trails, etc)
723                         CL_UpdateWorld();
724                         R_TimeReport("lerpworld");
725
726                         CL_Video_Frame();
727
728                         R_TimeReport("client");
729
730                         CL_UpdateScreen();
731                         R_TimeReport("render");
732
733                         if (host_speeds.integer)
734                                 time2 = Sys_DirtyTime();
735
736                         // update audio
737                         if(cl.csqc_usecsqclistener)
738                         {
739                                 S_Update(&cl.csqc_listenermatrix);
740                                 cl.csqc_usecsqclistener = false;
741                         }
742                         else
743                                 S_Update(&r_refdef.view.matrix);
744
745                         CDAudio_Update();
746                         R_TimeReport("audio");
747
748                         // reset gathering of mouse input
749                         in_mouse_x = in_mouse_y = 0;
750
751                         if (host_speeds.integer)
752                         {
753                                 pass1 = (int)((time1 - time3)*1000000);
754                                 time3 = Sys_DirtyTime();
755                                 pass2 = (int)((time2 - time1)*1000000);
756                                 pass3 = (int)((time3 - time2)*1000000);
757                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
758                                                         pass1+pass2+pass3, pass1, pass2, pass3);
759                         }
760                 }
761
762                 // if there is some time remaining from this frame, reset the timer
763                 if (cl_timer >= 0)
764                         cl_timer = 0;
765
766                 cl_timer += time;
767
768 #if MEMPARANOIA
769                 Mem_CheckSentinelsGlobal();
770 #else
771                 if (developer_memorydebug.integer)
772                         Mem_CheckSentinelsGlobal();
773 #endif
774
775                 // if the accumulators haven't become positive yet, wait a while
776                 wait = max(cl_timer, sv_timer) * -1000000.0;
777
778                 if (!host.restless && wait >= 1)
779                 {
780                         double time0, delta;
781
782                         if(host_maxwait.value <= 0)
783                                 wait = min(wait, 1000000.0);
784                         else
785                                 wait = min(wait, host_maxwait.value * 1000.0);
786                         if(wait < 1)
787                                 wait = 1; // because we cast to int
788
789                         time0 = Sys_DirtyTime();
790                         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
791                                 NetConn_SleepMicroseconds((int)wait);
792                                 if (cls.state != ca_dedicated)
793                                         NetConn_ClientFrame(); // helps server browser get good ping values
794                                 // TODO can we do the same for ServerFrame? Probably not.
795                         }
796                         else
797                                 Sys_Sleep((int)wait);
798                         delta = Sys_DirtyTime() - time0;
799                         if (delta < 0 || delta >= 1800) 
800                                 delta = 0;
801                         host.sleeptime += delta;
802 //                      R_TimeReport("sleep");
803                 }
804
805                 host.framecount++;
806                 oldtime = newtime;
807         }
808
809         Sys_Quit(0);
810 }
811
812 //============================================================================
813
814 qboolean vid_opened = false;
815 void Host_StartVideo(void)
816 {
817         if (!vid_opened && cls.state != ca_dedicated)
818         {
819                 vid_opened = true;
820                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
821                 NetConn_UpdateSockets();
822                 VID_Start();
823                 CDAudio_Startup();
824         }
825 }
826
827 char engineversion[128];
828
829 qboolean sys_nostdout = false;
830
831 static qfile_t *locksession_fh = NULL;
832 static qboolean locksession_run = false;
833 static void Host_InitSession(void)
834 {
835         int i;
836         char *buf;
837         Cvar_RegisterVariable(&sessionid);
838         Cvar_RegisterVariable(&locksession);
839
840         // load the session ID into the read-only cvar
841         if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
842         {
843                 if(sys.argv[i+1][0] == '.')
844                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
845                 else
846                 {
847                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
848                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
849                         Cvar_SetQuick(&sessionid, buf);
850                 }
851         }
852 }
853 void Host_LockSession(void)
854 {
855         if(locksession_run)
856                 return;
857         locksession_run = true;
858         if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
859         {
860                 char vabuf[1024];
861                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
862                 FS_CreatePath(p);
863                 locksession_fh = FS_SysOpen(p, "wl", false);
864                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
865                 if(!locksession_fh)
866                 {
867                         if(locksession.integer == 2)
868                         {
869                                 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);
870                         }
871                         else
872                         {
873                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
874                         }
875                 }
876         }
877 }
878 void Host_UnlockSession(void)
879 {
880         if(!locksession_run)
881                 return;
882         locksession_run = false;
883
884         if(locksession_fh)
885         {
886                 FS_Close(locksession_fh);
887                 // NOTE: we can NOT unlink the lock here, as doing so would
888                 // create a race condition if another process created it
889                 // between our close and our unlink
890                 locksession_fh = NULL;
891         }
892 }
893
894 /*
895 ====================
896 Host_Init
897 ====================
898 */
899 static void Host_Init (void)
900 {
901         int i;
902         const char* os;
903         char vabuf[1024];
904         cmd_state_t *cmd = &cmd_client;
905
906         host.state = host_init;
907
908         if (COM_CheckParm("-profilegameonly"))
909                 Sys_AllowProfiling(false);
910
911         // LadyHavoc: quake never seeded the random number generator before... heh
912         if (COM_CheckParm("-benchmark"))
913                 srand(0); // predictable random sequence for -benchmark
914         else
915                 srand((unsigned int)time(NULL));
916
917         // FIXME: this is evil, but possibly temporary
918         // LadyHavoc: doesn't seem very temporary...
919         // LadyHavoc: made this a saved cvar
920 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
921         if (COM_CheckParm("-developer"))
922         {
923                 developer.value = developer.integer = 1;
924                 developer.string = "1";
925         }
926
927         if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
928         {
929                 developer.value = developer.integer = 1;
930                 developer.string = "1";
931                 developer_extra.value = developer_extra.integer = 1;
932                 developer_extra.string = "1";
933                 developer_insane.value = developer_insane.integer = 1;
934                 developer_insane.string = "1";
935                 developer_memory.value = developer_memory.integer = 1;
936                 developer_memory.string = "1";
937                 developer_memorydebug.value = developer_memorydebug.integer = 1;
938                 developer_memorydebug.string = "1";
939         }
940
941         if (COM_CheckParm("-developer3"))
942         {
943                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
944                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
945         }
946
947 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
948         if (COM_CheckParm("-nostdout"))
949                 sys_nostdout = 1;
950
951         // used by everything
952         Memory_Init();
953
954         // initialize console command/cvar/alias/command execution systems
955         Cmd_Init();
956
957         // initialize memory subsystem cvars/commands
958         Memory_Init_Commands();
959
960         // initialize console and logging and its cvars/commands
961         Con_Init();
962
963         // initialize various cvars that could not be initialized earlier
964         u8_Init();
965         Curl_Init_Commands();
966         Sys_Init_Commands();
967         COM_Init_Commands();
968
969         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
970         FS_Init();
971
972         // construct a version string for the corner of the console
973         os = DP_OS_NAME;
974         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
975         Con_Printf("%s\n", engineversion);
976
977         // initialize process nice level
978         Sys_InitProcessNice();
979
980         // initialize ixtable
981         Mathlib_Init();
982
983         // register the cvars for session locking
984         Host_InitSession();
985
986         // must be after FS_Init
987         Crypto_Init();
988         Crypto_Init_Commands();
989
990         NetConn_Init();
991         Curl_Init();
992         PRVM_Init();
993         Mod_Init();
994         World_Init();
995         SV_Init();
996         V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
997         Host_InitLocal();
998         Host_ServerOptions();
999
1000         Thread_Init();
1001         TaskQueue_Init();
1002
1003         CL_Init();
1004
1005         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
1006         // NOTE: menu commands are freed by Cmd_RestoreInitState
1007         Cmd_SaveInitState();
1008
1009         // FIXME: put this into some neat design, but the menu should be allowed to crash
1010         // without crashing the whole game, so this should just be a short-time solution
1011
1012         // here comes the not so critical stuff
1013         if (setjmp(host.abortframe)) {
1014                 return;
1015         }
1016
1017         Host_AddConfigText(cmd);
1018
1019         Host_StartVideo();
1020
1021         // if quake.rc is missing, use default
1022         if (!FS_FileExists("quake.rc"))
1023         {
1024                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
1025                 Cbuf_Execute(cmd);
1026         }
1027
1028         host.state = host_active;
1029
1030         // run stuffcmds now, deferred previously because it can crash if a server starts that early
1031         Cbuf_AddText(cmd,"stuffcmds\n");
1032         Cbuf_Execute(cmd);
1033
1034         Log_Start();
1035
1036         // put up the loading image so the user doesn't stare at a black screen...
1037         SCR_BeginLoadingPlaque(true);
1038         
1039         // check for special benchmark mode
1040 // 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)
1041         i = COM_CheckParm("-benchmark");
1042         if (i && i + 1 < sys.argc)
1043         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1044         {
1045                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
1046                 Cbuf_Execute(&cmd_client);
1047         }
1048
1049         // check for special demo mode
1050 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1051         i = COM_CheckParm("-demo");
1052         if (i && i + 1 < sys.argc)
1053         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1054         {
1055                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
1056                 Cbuf_Execute(&cmd_client);
1057         }
1058
1059 #ifdef CONFIG_VIDEO_CAPTURE
1060 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1061         i = COM_CheckParm("-capturedemo");
1062         if (i && i + 1 < sys.argc)
1063         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1064         {
1065                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
1066                 Cbuf_Execute(&cmd_client);
1067         }
1068 #endif
1069
1070         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1071         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1072         {
1073                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
1074                 Cbuf_Execute(&cmd_client);
1075         }
1076
1077         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1078         {
1079 #ifdef CONFIG_MENU
1080                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
1081 #endif
1082                 Cbuf_Execute(&cmd_client);
1083         }
1084
1085         Con_DPrint("========Initialized=========\n");
1086
1087         if (cls.state != ca_dedicated)
1088                 SV_StartThread();
1089 }
1090
1091
1092 /*
1093 ===============
1094 Host_Shutdown
1095
1096 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1097 to run quit through here before the final handoff to the sys code.
1098 ===============
1099 */
1100 void Host_Shutdown(void)
1101 {
1102         static qboolean isdown = false;
1103
1104         if (isdown)
1105         {
1106                 Con_Print("recursive shutdown\n");
1107                 return;
1108         }
1109         if (setjmp(host.abortframe))
1110         {
1111                 Con_Print("aborted the quitting frame?!?\n");
1112                 return;
1113         }
1114         isdown = true;
1115
1116         // be quiet while shutting down
1117         S_StopAllSounds();
1118
1119         // end the server thread
1120         if (svs.threaded)
1121                 SV_StopThread();
1122
1123         // disconnect client from server if active
1124         CL_Disconnect();
1125
1126         // shut down local server if active
1127         SV_LockThreadMutex();
1128         SV_Shutdown ();
1129         SV_UnlockThreadMutex();
1130
1131 #ifdef CONFIG_MENU
1132         // Shutdown menu
1133         if(MR_Shutdown)
1134                 MR_Shutdown();
1135 #endif
1136
1137         // AK shutdown PRVM
1138         // AK hmm, no PRVM_Shutdown(); yet
1139
1140         CL_Video_Shutdown();
1141
1142         Host_SaveConfig();
1143
1144         CDAudio_Shutdown ();
1145         S_Terminate ();
1146         Curl_Shutdown ();
1147         NetConn_Shutdown ();
1148
1149         if (cls.state != ca_dedicated)
1150         {
1151                 R_Modules_Shutdown();
1152                 VID_Shutdown();
1153         }
1154
1155         SV_StopThread();
1156         TaskQueue_Shutdown();
1157         Thread_Shutdown();
1158         Cmd_Shutdown();
1159         Key_Shutdown();
1160         CL_Shutdown();
1161         Sys_Shutdown();
1162         Log_Close();
1163         Crypto_Shutdown();
1164
1165         Host_UnlockSession();
1166
1167         S_Shutdown();
1168         Con_Shutdown();
1169         Memory_Shutdown();
1170 }
1171
1172 void Host_NoOperation_f(cmd_state_t *cmd)
1173 {
1174 }