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