2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // host.c -- coordinates spawning and killing of local servers
30 A server can always be started, even if the system started out as a client
33 A client can NOT be started if the system started as a dedicated server.
35 Memory is cleared / released when a server or client begins, not when they end.
39 // true if into command execution
40 qboolean host_initialized;
41 // LordHavoc: used to turn Host_Error into Sys_Error if starting up or shutting down
42 qboolean host_loopactive = false;
43 // LordHavoc: set when quit is executed
44 qboolean host_shuttingdown = false;
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
51 // realtime from previous frame
53 // how many frames have occurred
56 // used for -developer commandline parameter, hacky hacky
60 client_t *host_client;
62 jmp_buf host_abortserver;
64 // pretend frames take this amount of time (in seconds), 0 = realtime
65 cvar_t host_framerate = {0, "host_framerate","0"};
66 // shows time used by certain subsystems
67 cvar_t host_speeds = {0, "host_speeds","0"};
68 // LordHavoc: framerate independent slowmo
69 cvar_t slowmo = {0, "slowmo", "1.0"};
70 // LordHavoc: framerate upper cap
71 cvar_t cl_maxfps = {CVAR_SAVE, "cl_maxfps", "1000"};
73 // print broadcast messages in dedicated mode
74 cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1"};
76 cvar_t sys_ticrate = {CVAR_SAVE, "sys_ticrate","0.05"};
77 cvar_t serverprofile = {0, "serverprofile","0"};
79 cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0"};
80 cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0"};
81 cvar_t teamplay = {CVAR_NOTIFY, "teamplay","0"};
83 cvar_t samelevel = {0, "samelevel","0"};
84 cvar_t noexit = {CVAR_NOTIFY, "noexit","0"};
86 cvar_t developer = {0, "developer","0"};
88 cvar_t skill = {0, "skill","1"};
89 cvar_t deathmatch = {0, "deathmatch","0"};
90 cvar_t coop = {0, "coop","0"};
92 cvar_t pausable = {0, "pausable","1"};
94 cvar_t temp1 = {0, "temp1","0"};
96 cvar_t timestamps = {CVAR_SAVE, "timestamps", "0"};
97 cvar_t timeformat = {CVAR_SAVE, "timeformat", "[%b %e %X] "};
103 This shuts down both the client and server
106 void PRVM_ProcessError(void);
107 static char hosterrorstring1[4096];
108 static char hosterrorstring2[4096];
109 static qboolean hosterror = false;
110 void Host_Error (const char *error, ...)
114 va_start (argptr,error);
115 vsprintf (hosterrorstring1,error,argptr);
118 Con_Printf("Host_Error: %s\n", hosterrorstring1);
120 // LordHavoc: if first frame has not been shown, or currently shutting
121 // down, do Sys_Error instead
122 if (!host_loopactive || host_shuttingdown)
123 Sys_Error ("Host_Error: %s", hosterrorstring1);
126 Sys_Error ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring2, hosterrorstring1);
129 strcpy(hosterrorstring2, hosterrorstring1);
131 CL_Parse_DumpPacket();
135 //PRVM_Crash(); // crash current prog
137 // crash all prvm progs
142 Host_ShutdownServer (false);
144 if (cls.state == ca_dedicated)
145 Sys_Error ("Host_Error: %s\n",hosterrorstring2); // dedicated servers exit
152 longjmp (host_abortserver, 1);
155 mempool_t *sv_clients_mempool = NULL;
157 void Host_ServerOptions (void)
164 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
165 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
168 // client exists, check what mode the user wants
169 i = COM_CheckParm ("-dedicated");
172 cls.state = ca_dedicated;
173 // default players unless specified
174 if (i != (com_argc - 1))
175 numplayers = atoi (com_argv[i+1]);
176 if (COM_CheckParm ("-listen"))
177 Sys_Error ("Only one of -dedicated or -listen can be specified");
181 cls.state = ca_disconnected;
182 i = COM_CheckParm ("-listen");
185 // default players unless specified
186 if (i != (com_argc - 1))
187 numplayers = atoi (com_argv[i+1]);
191 // default players in some games, singleplayer in most
192 if (gamemode != GAME_TRANSFUSION && gamemode != GAME_GOODVSBAD2 && gamemode != GAME_NEXUIZ && gamemode != GAME_BATTLEMECH)
199 // no client in the executable, always start dedicated server
200 if (COM_CheckParm ("-listen"))
201 Sys_Error ("-listen not available in a dedicated server executable");
202 cls.state = ca_dedicated;
203 // check for -dedicated specifying how many players
204 i = COM_CheckParm ("-dedicated");
205 // default players unless specified
206 if (i && i != (com_argc - 1))
207 numplayers = atoi (com_argv[i+1]);
213 numplayers = bound(1, numplayers, MAX_SCOREBOARD);
215 if (numplayers > 1 && !deathmatch.integer)
216 Cvar_SetValueQuick(&deathmatch, 1);
218 svs.maxclients = numplayers;
219 sv_clients_mempool = Mem_AllocPool("server clients", 0, NULL);
220 svs.clients = Mem_Alloc(sv_clients_mempool, sizeof(client_t) * svs.maxclients);
224 =======================
226 ======================
228 void Host_SaveConfig_f(void);
229 void Host_InitLocal (void)
231 Host_InitCommands ();
233 Cmd_AddCommand("saveconfig", Host_SaveConfig_f);
235 Cvar_RegisterVariable (&host_framerate);
236 Cvar_RegisterVariable (&host_speeds);
237 Cvar_RegisterVariable (&slowmo);
238 Cvar_RegisterVariable (&cl_maxfps);
240 Cvar_RegisterVariable (&sv_echobprint);
242 Cvar_RegisterVariable (&sys_ticrate);
243 Cvar_RegisterVariable (&serverprofile);
245 Cvar_RegisterVariable (&fraglimit);
246 Cvar_RegisterVariable (&timelimit);
247 Cvar_RegisterVariable (&teamplay);
248 Cvar_RegisterVariable (&samelevel);
249 Cvar_RegisterVariable (&noexit);
250 Cvar_RegisterVariable (&skill);
251 Cvar_RegisterVariable (&developer);
252 if (forcedeveloper) // make it real now that the cvar is registered
253 Cvar_SetValue("developer", 1);
254 Cvar_RegisterVariable (&deathmatch);
255 Cvar_RegisterVariable (&coop);
257 Cvar_RegisterVariable (&pausable);
259 Cvar_RegisterVariable (&temp1);
261 Cvar_RegisterVariable (×tamps);
262 Cvar_RegisterVariable (&timeformat);
264 Host_ServerOptions ();
272 Writes key bindings and archived cvars to config.cfg
275 void Host_SaveConfig_f(void)
279 // dedicated servers initialize the host but don't parse and set the
281 if (host_initialized && cls.state != ca_dedicated)
283 f = FS_Open ("config.cfg", "w", false);
286 Con_Print("Couldn't write config.cfg.\n");
290 Key_WriteBindings (f);
291 Cvar_WriteVariables (f);
302 Sends text across to be displayed
303 FIXME: make this just a stuffed echo?
306 void SV_ClientPrint(const char *msg)
308 MSG_WriteByte(&host_client->message, svc_print);
309 MSG_WriteString(&host_client->message, msg);
316 Sends text across to be displayed
317 FIXME: make this just a stuffed echo?
320 void SV_ClientPrintf(const char *fmt, ...)
325 va_start(argptr,fmt);
326 vsnprintf(msg,sizeof(msg),fmt,argptr);
336 Sends text to all active clients
339 void SV_BroadcastPrint(const char *msg)
344 for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
348 MSG_WriteByte(&client->message, svc_print);
349 MSG_WriteString(&client->message, msg);
353 if (sv_echobprint.integer && cls.state == ca_dedicated)
361 Sends text to all active clients
364 void SV_BroadcastPrintf(const char *fmt, ...)
369 va_start(argptr,fmt);
370 vsnprintf(msg,sizeof(msg),fmt,argptr);
373 SV_BroadcastPrint(msg);
380 Send text over to the client to be executed
383 void Host_ClientCommands(const char *fmt, ...)
388 va_start(argptr,fmt);
389 vsprintf(string, fmt,argptr);
392 MSG_WriteByte(&host_client->message, svc_stufftext);
393 MSG_WriteString(&host_client->message, string);
397 =====================
400 Called when the player is getting totally kicked off the host
401 if (crash = true), don't bother sending signofs
402 =====================
404 void SV_DropClient(qboolean crash)
407 Con_Printf("Client \"%s\" dropped\n", host_client->name);
409 // make sure edict is not corrupt (from a level change for example)
410 host_client->edict = EDICT_NUM(host_client - svs.clients + 1);
412 if (host_client->netconnection)
414 // free the client (the body stays around)
417 // LordHavoc: no opportunity for resending, so use unreliable
418 MSG_WriteByte(&host_client->message, svc_disconnect);
419 NetConn_SendUnreliableMessage(host_client->netconnection, &host_client->message);
421 // break the net connection
422 NetConn_Close(host_client->netconnection);
423 host_client->netconnection = NULL;
426 // call qc ClientDisconnect function
427 // LordHavoc: don't call QC if server is dead (avoids recursive
428 // Host_Error in some mods when they run out of edicts)
429 if (host_client->active && sv.active && host_client->edict && host_client->spawned)
431 // call the prog function for removing a client
432 // this will set the body to a dead frame, among other things
433 int saveSelf = pr_global_struct->self;
434 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
435 PR_ExecuteProgram(pr_global_struct->ClientDisconnect, "QC function ClientDisconnect is missing");
436 pr_global_struct->self = saveSelf;
439 // remove leaving player from scoreboard
440 //host_client->edict->v->netname = PR_SetString(host_client->name);
441 //if ((val = GETEDICTFIELDVALUE(host_client->edict, eval_clientcolors)))
443 //host_client->edict->v->frags = 0;
444 host_client->name[0] = 0;
445 host_client->colors = 0;
446 host_client->frags = 0;
447 // send notification to all clients
448 // get number of client manually just to make sure we get it right...
449 i = host_client - svs.clients;
450 MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
451 MSG_WriteByte (&sv.reliable_datagram, i);
452 MSG_WriteString (&sv.reliable_datagram, host_client->name);
453 MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
454 MSG_WriteByte (&sv.reliable_datagram, i);
455 MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
456 MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
457 MSG_WriteByte (&sv.reliable_datagram, i);
458 MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
460 // free the client now
461 if (host_client->entitydatabase)
462 EntityFrame_FreeDatabase(host_client->entitydatabase);
463 if (host_client->entitydatabase4)
464 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
465 if (host_client->entitydatabase5)
466 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
470 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
471 ED_ClearEdict(host_client->edict);
474 // clear the client struct (this sets active to false)
475 memset(host_client, 0, sizeof(*host_client));
477 // update server listing on the master because player count changed
478 // (which the master uses for filtering empty/full servers)
479 NetConn_Heartbeat(1);
486 This only happens at the end of a game, not between levels
489 void Host_ShutdownServer(qboolean crash)
495 Con_DPrintf("Host_ShutdownServer\n");
500 // print out where the crash happened, if it was caused by QC
503 NetConn_Heartbeat(2);
504 NetConn_Heartbeat(2);
506 // make sure all the clients know we're disconnecting
510 MSG_WriteByte(&buf, svc_disconnect);
511 count = NetConn_SendToAll(&buf, 5);
513 Con_Printf("Host_ShutdownServer: NetConn_SendToAll failed for %u clients\n", count);
515 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
516 if (host_client->active)
517 SV_DropClient(crash); // server shutdown
519 NetConn_CloseServerPorts();
526 memset(&sv, 0, sizeof(sv));
527 memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
535 This clears all the memory used by both the client and server, but does
536 not reinitialize anything.
539 void Host_ClearMemory (void)
541 Con_DPrint("Clearing memory\n");
545 memset (&sv, 0, sizeof(sv));
546 memset (&cl, 0, sizeof(cl));
550 //============================================================================
556 Returns false if the time is too short to run a frame
559 extern qboolean cl_capturevideo_active;
560 extern double cl_capturevideo_framerate;
561 qboolean Host_FilterTime (double time)
563 double timecap, timeleft;
566 if (sys_ticrate.value < 0.01 || sys_ticrate.value > 0.1)
567 Cvar_SetValue("sys_ticrate", bound(0.01, sys_ticrate.value, 0.1));
568 if (slowmo.value < 0)
569 Cvar_SetValue("slowmo", 0);
570 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
571 Cvar_SetValue("host_framerate", 0);
572 if (cl_maxfps.value < 1)
573 Cvar_SetValue("cl_maxfps", 1);
577 // disable time effects during timedemo
578 cl.frametime = host_realframetime = host_frametime = realtime - oldrealtime;
579 oldrealtime = realtime;
583 // check if framerate is too high
584 // default to sys_ticrate (server framerate - presumably low) unless we
585 // have a good reason to run faster
586 timecap = host_framerate.value;
588 timecap = sys_ticrate.value;
589 if (cls.state != ca_dedicated)
591 if (cl_capturevideo_active)
592 timecap = 1.0 / cl_capturevideo_framerate;
593 else if (vid_activewindow)
594 timecap = 1.0 / cl_maxfps.value;
597 timeleft = (oldrealtime - realtime) + timecap;
601 // don't totally hog the CPU
602 if (cls.state == ca_dedicated)
604 // if dedicated, try to use as little cpu as possible by waiting
605 // just a little longer than necessary
606 // (yes this means it doesn't quite keep up with the framerate)
607 msleft = (int)ceil(timeleft * 1000);
611 // if not dedicated, try to hit exactly a steady framerate by not
612 // sleeping the full amount
613 msleft = (int)floor(timeleft * 1000);
620 // LordHavoc: copy into host_realframetime as well
621 host_realframetime = host_frametime = realtime - oldrealtime;
622 oldrealtime = realtime;
624 // apply slowmo scaling
625 host_frametime *= slowmo.value;
627 // host_framerate overrides all else
628 if (host_framerate.value)
629 host_frametime = host_framerate.value;
631 // never run a frame longer than 1 second
632 if (host_frametime > 1)
635 cl.frametime = host_frametime;
643 Host_GetConsoleCommands
645 Add them exactly as if they had been typed at the console
648 void Host_GetConsoleCommands (void)
654 cmd = Sys_ConsoleInput ();
668 void Host_ServerFrame (void)
670 // never run more than 20 frames at a time as a sanity limit
671 int framecount, framelimit = 20;
673 static double frametimetotal = 0, lastservertime = 0;
674 frametimetotal += host_frametime;
675 // LordHavoc: cap server at sys_ticrate in networked games
676 if (frametimetotal < 0.001 || (!cl.islocalgame && cls.state == ca_connected && sv.active && ((realtime - lastservertime) < sys_ticrate.value)))
678 lastservertime = realtime;
680 // set the time and clear the general datagram
683 // run the world state
684 // don't allow simulation to run too fast or too slow or logic glitches can occur
685 for (framecount = 0;framecount < framelimit && frametimetotal > 0;framecount++, frametimetotal -= advancetime)
687 advancetime = min(frametimetotal, sys_ticrate.value);
689 // only advance time if not paused
690 // the game also pauses in singleplayer when menu or console is used
691 if (!sv.paused && (!cl.islocalgame || (key_dest == key_game && !key_consoleactive)))
692 sv.frametime = advancetime;
696 pr_global_struct->frametime = sv.frametime;
698 // check for network packets to the server each world step incase they
699 // come in midframe (particularly if host is running really slow)
700 NetConn_ServerFrame();
702 // read client messages
705 // move things around and think unless paused
710 // send all messages to the clients
711 SV_SendClientMessages();
713 // send an heartbeat if enough time has passed since the last one
714 NetConn_Heartbeat(0);
722 Runs all active servers
725 void _Host_Frame (float time)
727 static double time1 = 0;
728 static double time2 = 0;
729 static double time3 = 0;
730 int pass1, pass2, pass3;
731 usercmd_t cmd; // Used for receiving input
733 if (setjmp(host_abortserver))
734 return; // something bad happened, or the server disconnected
736 // decide the simulation time
737 if (!Host_FilterTime(time))
740 // keep the random time dependent
743 cl.islocalgame = NetConn_IsLocalGame();
745 // get new key events
748 // allow mice or other external controllers to add commands
751 // Collect input into cmd
752 IN_ProcessMove(&cmd);
754 // process console commands
757 // if running the server locally, make intentions now
758 if (cls.state == ca_connected && sv.active)
761 //-------------------
765 //-------------------
767 // check for commands typed to the host
768 Host_GetConsoleCommands();
773 //-------------------
777 //-------------------
779 cl.oldtime = cl.time;
780 cl.time += cl.frametime;
782 NetConn_ClientFrame();
784 if (cls.state == ca_connected)
786 // if running the server remotely, send intentions now after
787 // the incoming messages have been read
798 if (host_speeds.integer)
799 time1 = Sys_DoubleTime();
803 if (host_speeds.integer)
804 time2 = Sys_DoubleTime();
807 if (cls.signon == SIGNONS && cl.viewentity >= 0 && cl.viewentity < MAX_EDICTS && cl_entities[cl.viewentity].state_current.active)
809 // LordHavoc: this used to use renderer variables (eww)
810 S_Update(&cl_entities[cl.viewentity].render.matrix);
813 S_Update(&identitymatrix);
817 if (host_speeds.integer)
819 pass1 = (time1 - time3)*1000000;
820 time3 = Sys_DoubleTime();
821 pass2 = (time2 - time1)*1000000;
822 pass3 = (time3 - time2)*1000000;
823 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
824 pass1+pass2+pass3, pass1, pass2, pass3);
828 host_loopactive = true;
832 void Host_Frame (float time)
835 static double timetotal;
836 static int timecount;
839 if (!serverprofile.integer)
845 time1 = Sys_DoubleTime ();
847 time2 = Sys_DoubleTime ();
849 timetotal += time2 - time1;
852 if (timecount < 1000)
855 m = timetotal*1000/timecount;
859 for (i=0 ; i<svs.maxclients ; i++)
861 if (svs.clients[i].active)
865 Con_Printf("serverprofile: %2i clients %2i msec\n", c, m);
868 //============================================================================
870 void Render_Init(void);
877 void Host_Init (void)
881 // LordHavoc: quake never seeded the random number generator before... heh
884 // FIXME: this is evil, but possibly temporary
885 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
886 if (COM_CheckParm("-developer"))
888 forcedeveloper = true;
889 developer.integer = 1;
894 Memory_Init_Commands();
908 Con_Printf("Builddate: %s\n", buildstring);
910 if (cls.state != ca_dedicated)
923 // only cvars are executed when host_initialized == false
924 if (gamemode == GAME_TEU)
925 Cbuf_InsertText("exec teu.rc\n");
927 Cbuf_InsertText("exec quake.rc\n");
930 host_initialized = true;
932 Con_DPrint("========Initialized=========\n");
934 if (cls.state != ca_dedicated)
937 CL_InitTEnts (); // We must wait after sound startup to load tent sounds
938 SCR_BeginLoadingPlaque();
942 // stuff it again so the first host frame will execute it again, this time
944 if (gamemode == GAME_TEU)
945 Cbuf_InsertText("exec teu.rc\n");
947 Cbuf_InsertText("exec quake.rc\n");
949 if (!sv.active && (cls.state == ca_dedicated || COM_CheckParm("-listen")))
951 if (gamemode == GAME_TRANSFUSION)
952 Cbuf_InsertText ("map bb1\n");
953 else if (gamemode == GAME_NEXUIZ)
954 Cbuf_InsertText ("map nexdm01\n");
956 Cbuf_InsertText ("map start\n");
959 // check for special benchmark mode
960 // 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)
961 i = COM_CheckParm("-benchmark");
962 if (i && i + 1 < com_argc)
963 Cbuf_InsertText(va("timedemo %s\n", com_argv[i + 1]));
967 // We must wait for the log_file cvar to be initialized to start the log
976 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
977 to run quit through here before the final handoff to the sys code.
980 void Host_Shutdown(void)
982 static qboolean isdown = false;
986 Con_Print("recursive shutdown\n");
991 // disconnect client from server if active
994 // shut down local server if active
995 Host_ShutdownServer (false);
1002 // AK hmm, no PRVM_Shutdown(); yet
1005 Host_SaveConfig_f();
1007 CDAudio_Shutdown ();
1008 NetConn_Shutdown ();
1010 if (cls.state != ca_dedicated)
1012 R_Modules_Shutdown();