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