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