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