]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
changed Sys_Sleep functions to take microseconds instead of milliseconds (this may...
[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 <time.h>
23 #include "quakedef.h"
24 #include "libcurl.h"
25 #include "cdaudio.h"
26 #include "cl_video.h"
27 #include "progsvm.h"
28 #include "csprogs.h"
29
30 /*
31
32 A server can always be started, even if the system started out as a client
33 to a remote system.
34
35 A client can NOT be started if the system started as a dedicated server.
36
37 Memory is cleared / released when a server or client begins, not when they end.
38
39 */
40
41 // how many frames have occurred
42 // (checked by Host_Error and Host_SaveConfig_f)
43 int host_framecount = 0;
44 // LordHavoc: set when quit is executed
45 qboolean host_shuttingdown = false;
46
47 // the real time since application started, without any slowmo or clamping
48 double realtime;
49
50 // current client
51 client_t *host_client;
52
53 jmp_buf host_abortframe;
54
55 // random seed
56 cvar_t sv_random_seed = {0, "sv_random_seed", "", "random seed; when set, on every map start this random seed is used to initialize the random number generator. Don't touch it unless for benchmarking or debugging"};
57
58 // pretend frames take this amount of time (in seconds), 0 = realtime
59 cvar_t host_framerate = {0, "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"};
60 // shows time used by certain subsystems
61 cvar_t host_speeds = {0, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
62 // LordHavoc: framerate independent slowmo
63 cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
64 // LordHavoc: framerate upper cap
65 cvar_t cl_maxfps = {CVAR_SAVE, "cl_maxfps", "1000", "maximum fps cap, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
66
67 // print broadcast messages in dedicated mode
68 cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
69
70 cvar_t sys_ticrate = {CVAR_SAVE, "sys_ticrate","0.05", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players)"};
71 cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "0", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
72
73 cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
74 cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
75 cvar_t teamplay = {CVAR_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
76
77 cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
78 cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
79
80 cvar_t developer = {0, "developer","0", "prints additional debugging messages and information (recommended for modders and level designers)"};
81 cvar_t developer_entityparsing = {0, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
82
83 cvar_t skill = {0, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
84 cvar_t deathmatch = {0, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
85 cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
86
87 cvar_t pausable = {0, "pausable","1", "allow players to pause or not"};
88
89 cvar_t temp1 = {0, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};
90
91 cvar_t timestamps = {CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
92 cvar_t timeformat = {CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
93
94 cvar_t sv_checkforpacketsduringsleep = {0, "sv_checkforpacketsduringsleep", "0", "uses select() function to wait between frames which can be interrupted by packets being received, instead of Sleep()/usleep()/SDL_Sleep() functions which do not check for packets"};
95
96 /*
97 ================
98 Host_AbortCurrentFrame
99
100 aborts the current host frame and goes on with the next one
101 ================
102 */
103 void Host_AbortCurrentFrame(void)
104 {
105         longjmp (host_abortframe, 1);
106 }
107
108 /*
109 ================
110 Host_Error
111
112 This shuts down both the client and server
113 ================
114 */
115 void Host_Error (const char *error, ...)
116 {
117         static char hosterrorstring1[MAX_INPUTLINE];
118         static char hosterrorstring2[MAX_INPUTLINE];
119         static qboolean hosterror = false;
120         va_list argptr;
121
122         // turn off rcon redirect if it was active when the crash occurred
123         rcon_redirect = false;
124
125         va_start (argptr,error);
126         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
127         va_end (argptr);
128
129         Con_Printf("Host_Error: %s\n", hosterrorstring1);
130
131         // LordHavoc: if crashing very early, or currently shutting down, do
132         // Sys_Error instead
133         if (host_framecount < 3 || host_shuttingdown)
134                 Sys_Error ("Host_Error: %s", hosterrorstring1);
135
136         if (hosterror)
137                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
138         hosterror = true;
139
140         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
141
142         CL_Parse_DumpPacket();
143
144         CL_Parse_ErrorCleanUp();
145
146         //PR_Crash();
147
148         // print out where the crash happened, if it was caused by QC (and do a cleanup)
149         PRVM_Crash();
150
151
152         Host_ShutdownServer ();
153
154         if (cls.state == ca_dedicated)
155                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
156
157         CL_Disconnect ();
158         cls.demonum = -1;
159
160         hosterror = false;
161
162         Host_AbortCurrentFrame();
163 }
164
165 void Host_ServerOptions (void)
166 {
167         int i;
168
169         // general default
170         svs.maxclients = 8;
171
172 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
173 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
174         // if no client is in the executable or -dedicated is specified on
175         // commandline, start a dedicated server
176         i = COM_CheckParm ("-dedicated");
177         if (i || !cl_available)
178         {
179                 cls.state = ca_dedicated;
180                 // check for -dedicated specifying how many players
181                 if (i && i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
182                         svs.maxclients = atoi (com_argv[i+1]);
183                 if (COM_CheckParm ("-listen"))
184                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
185                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
186                 Cvar_SetValue("sv_public", 1);
187         }
188         else if (cl_available)
189         {
190                 // client exists and not dedicated, check if -listen is specified
191                 cls.state = ca_disconnected;
192                 i = COM_CheckParm ("-listen");
193                 if (i)
194                 {
195                         // default players unless specified
196                         if (i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
197                                 svs.maxclients = atoi (com_argv[i+1]);
198                 }
199                 else
200                 {
201                         // default players in some games, singleplayer in most
202                         if (gamemode != GAME_GOODVSBAD2 && gamemode != GAME_NEXUIZ && gamemode != GAME_BATTLEMECH)
203                                 svs.maxclients = 1;
204                 }
205         }
206
207         svs.maxclients = bound(1, svs.maxclients, MAX_SCOREBOARD);
208
209         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
210
211         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
212                 Cvar_SetValueQuick(&deathmatch, 1);
213 }
214
215 /*
216 =======================
217 Host_InitLocal
218 ======================
219 */
220 void Host_SaveConfig_f(void);
221 void Host_LoadConfig_f(void);
222 static void Host_InitLocal (void)
223 {
224         Cmd_AddCommand("saveconfig", Host_SaveConfig_f, "save settings to config.cfg immediately (also automatic when quitting)");
225         Cmd_AddCommand("loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
226
227         Cvar_RegisterVariable (&sv_random_seed);
228         Cvar_RegisterVariable (&host_framerate);
229         Cvar_RegisterVariable (&host_speeds);
230         Cvar_RegisterVariable (&slowmo);
231         Cvar_RegisterVariable (&cl_maxfps);
232
233         Cvar_RegisterVariable (&sv_echobprint);
234
235         Cvar_RegisterVariable (&sys_ticrate);
236         Cvar_RegisterVariable (&sv_fixedframeratesingleplayer);
237
238         Cvar_RegisterVariable (&fraglimit);
239         Cvar_RegisterVariable (&timelimit);
240         Cvar_RegisterVariable (&teamplay);
241         Cvar_RegisterVariable (&samelevel);
242         Cvar_RegisterVariable (&noexit);
243         Cvar_RegisterVariable (&skill);
244         Cvar_RegisterVariable (&developer);
245         Cvar_RegisterVariable (&developer_entityparsing);
246         Cvar_RegisterVariable (&deathmatch);
247         Cvar_RegisterVariable (&coop);
248
249         Cvar_RegisterVariable (&pausable);
250
251         Cvar_RegisterVariable (&temp1);
252
253         Cvar_RegisterVariable (&timestamps);
254         Cvar_RegisterVariable (&timeformat);
255
256         Cvar_RegisterVariable (&sv_checkforpacketsduringsleep);
257 }
258
259
260 /*
261 ===============
262 Host_SaveConfig_f
263
264 Writes key bindings and archived cvars to config.cfg
265 ===============
266 */
267 void Host_SaveConfig_f(void)
268 {
269         qfile_t *f;
270
271 // dedicated servers initialize the host but don't parse and set the
272 // config.cfg cvars
273         // LordHavoc: don't save a config if it crashed in startup
274         if (host_framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark"))
275         {
276                 f = FS_Open ("config.cfg", "wb", false, false);
277                 if (!f)
278                 {
279                         Con_Print("Couldn't write config.cfg.\n");
280                         return;
281                 }
282
283                 Key_WriteBindings (f);
284                 Cvar_WriteVariables (f);
285
286                 FS_Close (f);
287         }
288 }
289
290
291 /*
292 ===============
293 Host_LoadConfig_f
294
295 Resets key bindings and cvars to defaults and then reloads scripts
296 ===============
297 */
298 void Host_LoadConfig_f(void)
299 {
300         // unlock the cvar default strings so they can be updated by the new default.cfg
301         Cvar_UnlockDefaults();
302         // reset cvars to their defaults, and then exec startup scripts again
303         Cbuf_InsertText("cvar_resettodefaults_all;exec quake.rc\n");
304 }
305
306 /*
307 =================
308 SV_ClientPrint
309
310 Sends text across to be displayed
311 FIXME: make this just a stuffed echo?
312 =================
313 */
314 void SV_ClientPrint(const char *msg)
315 {
316         if (host_client->netconnection)
317         {
318                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
319                 MSG_WriteString(&host_client->netconnection->message, msg);
320         }
321 }
322
323 /*
324 =================
325 SV_ClientPrintf
326
327 Sends text across to be displayed
328 FIXME: make this just a stuffed echo?
329 =================
330 */
331 void SV_ClientPrintf(const char *fmt, ...)
332 {
333         va_list argptr;
334         char msg[MAX_INPUTLINE];
335
336         va_start(argptr,fmt);
337         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
338         va_end(argptr);
339
340         SV_ClientPrint(msg);
341 }
342
343 /*
344 =================
345 SV_BroadcastPrint
346
347 Sends text to all active clients
348 =================
349 */
350 void SV_BroadcastPrint(const char *msg)
351 {
352         int i;
353         client_t *client;
354
355         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
356         {
357                 if (client->active && client->netconnection)
358                 {
359                         MSG_WriteByte(&client->netconnection->message, svc_print);
360                         MSG_WriteString(&client->netconnection->message, msg);
361                 }
362         }
363
364         if (sv_echobprint.integer && cls.state == ca_dedicated)
365                 Con_Print(msg);
366 }
367
368 /*
369 =================
370 SV_BroadcastPrintf
371
372 Sends text to all active clients
373 =================
374 */
375 void SV_BroadcastPrintf(const char *fmt, ...)
376 {
377         va_list argptr;
378         char msg[MAX_INPUTLINE];
379
380         va_start(argptr,fmt);
381         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
382         va_end(argptr);
383
384         SV_BroadcastPrint(msg);
385 }
386
387 /*
388 =================
389 Host_ClientCommands
390
391 Send text over to the client to be executed
392 =================
393 */
394 void Host_ClientCommands(const char *fmt, ...)
395 {
396         va_list argptr;
397         char string[MAX_INPUTLINE];
398
399         if (!host_client->netconnection)
400                 return;
401
402         va_start(argptr,fmt);
403         dpvsnprintf(string, sizeof(string), fmt, argptr);
404         va_end(argptr);
405
406         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
407         MSG_WriteString(&host_client->netconnection->message, string);
408 }
409
410 /*
411 =====================
412 SV_DropClient
413
414 Called when the player is getting totally kicked off the host
415 if (crash = true), don't bother sending signofs
416 =====================
417 */
418 void SV_DropClient(qboolean crash)
419 {
420         int i;
421         Con_Printf("Client \"%s\" dropped\n", host_client->name);
422
423         // make sure edict is not corrupt (from a level change for example)
424         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
425
426         if (host_client->netconnection)
427         {
428                 // free the client (the body stays around)
429                 if (!crash)
430                 {
431                         // LordHavoc: no opportunity for resending, so use unreliable 3 times
432                         unsigned char bufdata[8];
433                         sizebuf_t buf;
434                         memset(&buf, 0, sizeof(buf));
435                         buf.data = bufdata;
436                         buf.maxsize = sizeof(bufdata);
437                         MSG_WriteByte(&buf, svc_disconnect);
438                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
439                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
440                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
441                 }
442                 // break the net connection
443                 NetConn_Close(host_client->netconnection);
444                 host_client->netconnection = NULL;
445         }
446
447         // call qc ClientDisconnect function
448         // LordHavoc: don't call QC if server is dead (avoids recursive
449         // Host_Error in some mods when they run out of edicts)
450         if (host_client->clientconnectcalled && sv.active && host_client->edict)
451         {
452                 // call the prog function for removing a client
453                 // this will set the body to a dead frame, among other things
454                 int saveSelf = prog->globals.server->self;
455                 host_client->clientconnectcalled = false;
456                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
457                 PRVM_ExecuteProgram(prog->globals.server->ClientDisconnect, "QC function ClientDisconnect is missing");
458                 prog->globals.server->self = saveSelf;
459         }
460
461         // if a download is active, close it
462         if (host_client->download_file)
463         {
464                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
465                 FS_Close(host_client->download_file);
466                 host_client->download_file = NULL;
467                 host_client->download_name[0] = 0;
468                 host_client->download_expectedposition = 0;
469                 host_client->download_started = false;
470         }
471
472         // remove leaving player from scoreboard
473         host_client->name[0] = 0;
474         host_client->colors = 0;
475         host_client->frags = 0;
476         // send notification to all clients
477         // get number of client manually just to make sure we get it right...
478         i = host_client - svs.clients;
479         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
480         MSG_WriteByte (&sv.reliable_datagram, i);
481         MSG_WriteString (&sv.reliable_datagram, host_client->name);
482         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
483         MSG_WriteByte (&sv.reliable_datagram, i);
484         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
485         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
486         MSG_WriteByte (&sv.reliable_datagram, i);
487         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
488
489         // free the client now
490         if (host_client->entitydatabase)
491                 EntityFrame_FreeDatabase(host_client->entitydatabase);
492         if (host_client->entitydatabase4)
493                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
494         if (host_client->entitydatabase5)
495                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
496
497         if (sv.active)
498         {
499                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
500                 PRVM_ED_ClearEdict(host_client->edict);
501         }
502
503         // clear the client struct (this sets active to false)
504         memset(host_client, 0, sizeof(*host_client));
505
506         // update server listing on the master because player count changed
507         // (which the master uses for filtering empty/full servers)
508         NetConn_Heartbeat(1);
509 }
510
511 /*
512 ==================
513 Host_ShutdownServer
514
515 This only happens at the end of a game, not between levels
516 ==================
517 */
518 void Host_ShutdownServer(void)
519 {
520         int i;
521
522         Con_DPrintf("Host_ShutdownServer\n");
523
524         if (!sv.active)
525                 return;
526
527         NetConn_Heartbeat(2);
528         NetConn_Heartbeat(2);
529
530 // make sure all the clients know we're disconnecting
531         SV_VM_Begin();
532         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
533                 if (host_client->active)
534                         SV_DropClient(false); // server shutdown
535         SV_VM_End();
536
537         NetConn_CloseServerPorts();
538
539         sv.active = false;
540 //
541 // clear structures
542 //
543         memset(&sv, 0, sizeof(sv));
544         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
545 }
546
547
548 //============================================================================
549
550 /*
551 ===================
552 Host_GetConsoleCommands
553
554 Add them exactly as if they had been typed at the console
555 ===================
556 */
557 void Host_GetConsoleCommands (void)
558 {
559         char *cmd;
560
561         while (1)
562         {
563                 cmd = Sys_ConsoleInput ();
564                 if (!cmd)
565                         break;
566                 Cbuf_AddText (cmd);
567         }
568 }
569
570 /*
571 ==================
572 Host_Frame
573
574 Runs all active servers
575 ==================
576 */
577 static void Host_Init(void);
578 void Host_Main(void)
579 {
580         static double time1 = 0;
581         static double time2 = 0;
582         static double time3 = 0;
583         // these are static because of setjmp/longjmp warnings in mingw32 gcc 2.95.3
584         static double frameoldtime, framenewtime, framedeltatime, cl_timer, sv_timer;
585         double clframetime;
586         double wait;
587         int pass1, pass2, pass3;
588
589         Host_Init();
590
591         cl_timer = 0;
592         sv_timer = 0;
593
594         framenewtime = Sys_DoubleTime();
595         for (;;)
596         {
597                 if (setjmp(host_abortframe))
598                         continue;                       // something bad happened, or the server disconnected
599
600                 frameoldtime = framenewtime;
601                 framenewtime = Sys_DoubleTime();
602                 framedeltatime = framenewtime - frameoldtime;
603                 realtime += framedeltatime;
604
605                 // accumulate the new frametime into the timers
606                 cl_timer += framedeltatime;
607                 sv_timer += framedeltatime;
608
609                 if (slowmo.value < 0)
610                         Cvar_SetValue("slowmo", 0);
611                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
612                         Cvar_SetValue("host_framerate", 0);
613                 if (cl_maxfps.value < 1)
614                         Cvar_SetValue("cl_maxfps", 1);
615
616                 // keep the random time dependent
617                 if(!*sv_random_seed.string)
618                         rand();
619
620                 cl.islocalgame = NetConn_IsLocalGame();
621
622                 // get new key events
623                 Sys_SendKeyEvents();
624
625                 NetConn_UpdateSockets();
626
627                 // receive packets on each main loop iteration, as the main loop may
628                 // be undersleeping due to select() detecting a new packet
629                 if (sv.active)
630                         NetConn_ServerFrame();
631
632                 Curl_Run();
633
634                 // check for commands typed to the host
635                 Host_GetConsoleCommands();
636
637                 // when a server is running we only execute console commands on server frames
638                 // (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
639                 // otherwise we execute them on all frames
640                 if (sv_timer > 0 || !sv.active)
641                 {
642                         // process console commands
643                         Cbuf_Execute();
644                 }
645
646                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
647
648                 // if the accumulators haven't become positive yet, wait a while
649                 if (cls.state == ca_dedicated)
650                         wait = sv_timer * -1000000.0;
651                 else if (!sv.active)
652                         wait = cl_timer * -1000000.0;
653                 else
654                         wait = max(cl_timer, sv_timer) * -1000000.0;
655                 if (wait > 100000)
656                         wait = 100000;
657                 if (!cls.timedemo && wait > 0)
658                 {
659                         if (sv_checkforpacketsduringsleep.integer)
660                         {
661                                 if (wait >= 1)
662                                         NetConn_SleepMicroseconds((int)wait);
663                         }
664                         else
665                         {
666                                 if (wait >= 1000)
667                                         Sys_Sleep((int)wait / 1000);
668                         }
669                         continue;
670                 }
671
672         //-------------------
673         //
674         // server operations
675         //
676         //-------------------
677
678                 // limit the frametime steps to no more than 100ms each
679                 if (cl_timer > 0.1)
680                         cl_timer = 0.1;
681                 if (sv_timer > 0.1)
682                         sv_timer = 0.1;
683
684                 if (sv.active && sv_timer > 0)
685                 {
686                         // execute one or more server frames, with an upper limit on how much
687                         // execution time to spend on server frames to avoid freezing the game if
688                         // the server is overloaded, this execution time limit means the game will
689                         // slow down if the server is taking too long.
690                         int framecount, framelimit = 1;
691                         double advancetime, aborttime = 0;
692
693                         // run the world state
694                         // don't allow simulation to run too fast or too slow or logic glitches can occur
695
696                         // stop running server frames if the wall time reaches this value
697                         if (sys_ticrate.value <= 0)
698                                 advancetime = sv_timer;
699                         else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
700                         {
701                                 // synchronize to the client frametime, but no less than 10ms and no more than sys_ticrate
702                                 advancetime = bound(0.01, cl_timer, sys_ticrate.value);
703                                 framelimit = 10;
704                                 aborttime = Sys_DoubleTime() + 0.1;
705                         }
706                         else
707                         {
708                                 advancetime = sys_ticrate.value;
709                                 // listen servers can run multiple server frames per client frame
710                                 if (cls.state == ca_connected)
711                                 {
712                                         framelimit = 10;
713                                         aborttime = Sys_DoubleTime() + 0.1;
714                                 }
715                         }
716                         advancetime = min(advancetime, 0.1);
717
718                         // only advance time if not paused
719                         // the game also pauses in singleplayer when menu or console is used
720                         sv.frametime = advancetime * slowmo.value;
721                         if (host_framerate.value)
722                                 sv.frametime = host_framerate.value;
723                         if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive)))
724                                 sv.frametime = 0;
725
726                         // setup the VM frame
727                         SV_VM_Begin();
728
729                         for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
730                         {
731                                 sv_timer -= advancetime;
732
733                                 // move things around and think unless paused
734                                 if (sv.frametime)
735                                         SV_Physics();
736
737                                 // send all messages to the clients
738                                 SV_SendClientMessages();
739
740                                 // clear the general datagram
741                                 SV_ClearDatagram();
742
743                                 // if this server frame took too long, break out of the loop
744                                 if (framelimit > 1 && Sys_DoubleTime() >= aborttime)
745                                         break;
746                         }
747
748                         // end the server VM frame
749                         SV_VM_End();
750
751                         // send an heartbeat if enough time has passed since the last one
752                         NetConn_Heartbeat(0);
753                 }
754
755         //-------------------
756         //
757         // client operations
758         //
759         //-------------------
760
761                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo))
762                 {
763                         // decide the simulation time
764                         if (cls.capturevideo.active)
765                         {
766                                 if (cls.capturevideo.realtime)
767                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
768                                 else
769                                 {
770                                         clframetime = 1.0 / cls.capturevideo.framerate;
771                                         cl.realframetime = max(cl_timer, clframetime);
772                                 }
773                         }
774                         else if (vid_activewindow)
775                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
776                         else
777                                 clframetime = cl.realframetime = 0.1;
778
779                         // apply slowmo scaling
780                         clframetime *= slowmo.value;
781
782                         // host_framerate overrides all else
783                         if (host_framerate.value)
784                                 clframetime = host_framerate.value;
785
786                         if (cls.timedemo)
787                                 clframetime = cl.realframetime = cl_timer;
788
789                         // deduct the frame time from the accumulator
790                         cl_timer -= cl.realframetime;
791
792                         cl.oldtime = cl.time;
793                         cl.time += clframetime;
794
795                         // Collect input into cmd
796                         CL_Input();
797
798                         NetConn_ClientFrame();
799
800                         if (cls.state == ca_connected)
801                         {
802                                 CL_ReadFromServer();
803                                 // if running the server remotely, send intentions now after
804                                 // the incoming messages have been read
805                                 //if (!cl.islocalgame)
806                                 //      CL_SendCmd();
807                         }
808
809                         // update video
810                         if (host_speeds.integer)
811                                 time1 = Sys_DoubleTime();
812
813                         //ui_update();
814
815                         CL_VideoFrame();
816
817                         CL_UpdateScreen();
818
819                         if (host_speeds.integer)
820                                 time2 = Sys_DoubleTime();
821
822                         // update audio
823                         if(csqc_usecsqclistener)
824                         {
825                                 S_Update(&csqc_listenermatrix);
826                                 csqc_usecsqclistener = false;
827                         }
828                         else
829                                 S_Update(&r_view.matrix);
830
831                         CDAudio_Update();
832
833                         if (host_speeds.integer)
834                         {
835                                 pass1 = (int)((time1 - time3)*1000000);
836                                 time3 = Sys_DoubleTime();
837                                 pass2 = (int)((time2 - time1)*1000000);
838                                 pass3 = (int)((time3 - time2)*1000000);
839                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
840                                                         pass1+pass2+pass3, pass1, pass2, pass3);
841                         }
842                 }
843
844                 // if there is some time remaining from this frame, reset the timers
845                 if (cl_timer >= 0)
846                         cl_timer = 0;
847                 if (sv_timer >= 0)
848                         sv_timer = 0;
849
850                 host_framecount++;
851         }
852 }
853
854 //============================================================================
855
856 qboolean vid_opened = false;
857 void Host_StartVideo(void)
858 {
859         if (!vid_opened && cls.state != ca_dedicated)
860         {
861                 vid_opened = true;
862                 VID_Start();
863                 CDAudio_Startup();
864         }
865 }
866
867 char engineversion[128];
868
869 qboolean sys_nostdout = false;
870
871 extern void Render_Init(void);
872 extern void Mathlib_Init(void);
873 extern void FS_Init(void);
874 extern void FS_Shutdown(void);
875 extern void PR_Cmd_Init(void);
876 extern void COM_Init_Commands(void);
877 extern void FS_Init_Commands(void);
878 extern qboolean host_stuffcmdsrun;
879
880 /*
881 ====================
882 Host_Init
883 ====================
884 */
885 static void Host_Init (void)
886 {
887         int i;
888         const char* os;
889
890         // LordHavoc: quake never seeded the random number generator before... heh
891         srand(time(NULL));
892
893         // FIXME: this is evil, but possibly temporary
894 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
895         if (COM_CheckParm("-developer"))
896         {
897                 developer.value = developer.integer = 100;
898                 developer.string = "100";
899         }
900
901         if (COM_CheckParm("-developer2"))
902         {
903                 developer.value = developer.integer = 100;
904                 developer.string = "100";
905                 developer_memory.value = developer_memory.integer = 100;
906                 developer.string = "100";
907                 developer_memorydebug.value = developer_memorydebug.integer = 100;
908                 developer_memorydebug.string = "100";
909         }
910
911 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
912         if (COM_CheckParm("-nostdout"))
913                 sys_nostdout = 1;
914
915         // used by everything
916         Memory_Init();
917
918         // initialize console command/cvar/alias/command execution systems
919         Cmd_Init();
920
921         // initialize memory subsystem cvars/commands
922         Memory_Init_Commands();
923
924         // initialize console and logging and its cvars/commands
925         Con_Init();
926
927         // initialize various cvars that could not be initialized earlier
928         Curl_Init_Commands();
929         Cmd_Init_Commands();
930         Sys_Init_Commands();
931         COM_Init_Commands();
932         FS_Init_Commands();
933
934         // initialize console window (only used by sys_win.c)
935         Sys_InitConsole();
936
937         // detect gamemode from commandline options or executable name
938         COM_InitGameType();
939
940         // construct a version string for the corner of the console
941 #if defined(__linux__)
942         os = "Linux";
943 #elif defined(WIN32)
944         os = "Windows";
945 #elif defined(__FreeBSD__)
946         os = "FreeBSD";
947 #elif defined(__NetBSD__)
948         os = "NetBSD";
949 #elif defined(__OpenBSD__)
950         os = "OpenBSD";
951 #elif defined(MACOSX)
952         os = "Mac OS X";
953 #elif defined(__MORPHOS__)
954         os = "MorphOS";
955 #else
956         os = "Unknown";
957 #endif
958         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
959         Con_Printf("%s\n", engineversion);
960
961         // initialize ixtable
962         Mathlib_Init();
963
964         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
965         FS_Init();
966
967         NetConn_Init();
968         Curl_Init();
969         //PR_Init();
970         //PR_Cmd_Init();
971         PRVM_Init();
972         Mod_Init();
973         World_Init();
974         SV_Init();
975         Host_InitCommands();
976         Host_InitLocal();
977         Host_ServerOptions();
978
979         if (cls.state != ca_dedicated)
980         {
981                 Con_Printf("Initializing client\n");
982
983                 R_Modules_Init();
984                 Palette_Init();
985                 MR_Init_Commands();
986                 VID_Shared_Init();
987                 VID_Init();
988                 Render_Init();
989                 S_Init();
990                 CDAudio_Init();
991                 Key_Init();
992                 V_Init();
993                 CL_Init();
994         }
995
996         // set up the default startmap_sp and startmap_dm aliases (mods can
997         // override these) and then execute the quake.rc startup script
998         if (gamemode == GAME_NEHAHRA)
999                 Cbuf_AddText("alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec quake.rc\n");
1000         else if (gamemode == GAME_TRANSFUSION)
1001                 Cbuf_AddText("alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec quake.rc\n");
1002         else if (gamemode == GAME_TEU)
1003                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
1004         else
1005                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec quake.rc\n");
1006         Cbuf_Execute();
1007
1008         // if stuffcmds wasn't run, then quake.rc is probably missing, use default
1009         if (!host_stuffcmdsrun)
1010         {
1011                 Cbuf_AddText("exec default.cfg\nexec config.cfg\nexec autoexec.cfg\nstuffcmds\n");
1012                 Cbuf_Execute();
1013         }
1014
1015         // put up the loading image so the user doesn't stare at a black screen...
1016         SCR_BeginLoadingPlaque();
1017
1018         // FIXME: put this into some neat design, but the menu should be allowed to crash
1019         // without crashing the whole game, so this should just be a short-time solution
1020
1021         // here comes the not so critical stuff
1022         if (setjmp(host_abortframe)) {
1023                 return;
1024         }
1025
1026         if (cls.state != ca_dedicated)
1027         {
1028                 MR_Init();
1029         }
1030
1031         // check for special benchmark mode
1032 // 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)
1033         i = COM_CheckParm("-benchmark");
1034         if (i && i + 1 < com_argc)
1035         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1036         {
1037                 Cbuf_AddText(va("timedemo %s\n", com_argv[i + 1]));
1038                 Cbuf_Execute();
1039         }
1040
1041         // check for special demo mode
1042 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1043         i = COM_CheckParm("-demo");
1044         if (i && i + 1 < com_argc)
1045         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1046         {
1047                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1048                 Cbuf_Execute();
1049         }
1050
1051         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1052         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1053         {
1054                 Cbuf_AddText("startmap_dm\n");
1055                 Cbuf_Execute();
1056         }
1057
1058         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1059         {
1060                 if (gamemode == GAME_NEXUIZ)
1061                         Cbuf_AddText("togglemenu\nplayvideo logo\ncd loop 1\n");
1062                 else
1063                         Cbuf_AddText("togglemenu\n");
1064                 Cbuf_Execute();
1065         }
1066
1067         Con_DPrint("========Initialized=========\n");
1068
1069         //Host_StartVideo();
1070 }
1071
1072
1073 /*
1074 ===============
1075 Host_Shutdown
1076
1077 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1078 to run quit through here before the final handoff to the sys code.
1079 ===============
1080 */
1081 void Host_Shutdown(void)
1082 {
1083         static qboolean isdown = false;
1084
1085         if (isdown)
1086         {
1087                 Con_Print("recursive shutdown\n");
1088                 return;
1089         }
1090         isdown = true;
1091
1092         // be quiet while shutting down
1093         S_StopAllSounds();
1094
1095         // disconnect client from server if active
1096         CL_Disconnect();
1097
1098         // shut down local server if active
1099         Host_ShutdownServer ();
1100
1101         // Shutdown menu
1102         if(MR_Shutdown)
1103                 MR_Shutdown();
1104
1105         // AK shutdown PRVM
1106         // AK hmm, no PRVM_Shutdown(); yet
1107
1108         CL_Video_Shutdown();
1109
1110         Host_SaveConfig_f();
1111
1112         CDAudio_Shutdown ();
1113         S_Terminate ();
1114         Curl_Shutdown ();
1115         NetConn_Shutdown ();
1116         //PR_Shutdown ();
1117
1118         if (cls.state != ca_dedicated)
1119         {
1120                 R_Modules_Shutdown();
1121                 VID_Shutdown();
1122         }
1123
1124         Cmd_Shutdown();
1125         CL_Shutdown();
1126         Sys_Shutdown();
1127         Log_Close();
1128         FS_Shutdown();
1129         Memory_Shutdown();
1130 }
1131