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