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