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
26 A server can allways be started, even if the system started out as a client
29 A client can NOT be started if the system started as a dedicated server.
31 Memory is cleared / released when a server or client begins, not when they end.
35 quakeparms_t host_parms;
37 qboolean host_initialized; // true if into command execution
39 double host_frametime;
41 double realtime; // without any filtering or bounding
42 double oldrealtime; // last frame run
51 client_t *host_client; // current client
53 jmp_buf host_abortserver;
55 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
56 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
57 cvar_t slowmo = {"slowmo", "1.0"}; // LordHavoc: framerate independent slowmo
59 cvar_t sys_ticrate = {"sys_ticrate","0.05"};
60 cvar_t serverprofile = {"serverprofile","0"};
62 cvar_t fraglimit = {"fraglimit","0",false,true};
63 cvar_t timelimit = {"timelimit","0",false,true};
64 cvar_t teamplay = {"teamplay","0",false,true};
66 cvar_t samelevel = {"samelevel","0"};
67 cvar_t noexit = {"noexit","0",false,true};
69 cvar_t developer = {"developer","0"};
71 cvar_t skill = {"skill","1"}; // 0 - 3
72 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
73 cvar_t coop = {"coop","0"}; // 0 or 1
75 cvar_t pausable = {"pausable","1"};
77 cvar_t temp1 = {"temp1","0"};
79 cvar_t timestamps = {"timestamps", "0", true};
80 cvar_t timeformat = {"timeformat", "[%b %e %X] ", true};
87 void Host_EndGame (char *message, ...)
92 va_start (argptr,message);
93 vsprintf (string,message,argptr);
95 Con_DPrintf ("Host_EndGame: %s\n",string);
98 Host_ShutdownServer (false);
100 if (cls.state == ca_dedicated)
101 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
103 if (cls.demonum != -1)
108 longjmp (host_abortserver, 1);
115 This shuts down both the client and server
118 char hosterrorstring[1024];
119 void Host_Error (char *error, ...)
122 static qboolean inerror = false;
127 va_start (argptr,error);
128 vsprintf (string,error,argptr);
130 Sys_Error ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring, string);
134 SCR_EndLoadingPlaque (); // reenable screen updates
136 va_start (argptr,error);
137 vsprintf (hosterrorstring,error,argptr);
139 Con_Printf ("Host_Error: %s\n",hosterrorstring);
142 Host_ShutdownServer (false);
144 if (cls.state == ca_dedicated)
145 Sys_Error ("Host_Error: %s\n",hosterrorstring); // dedicated servers exit
152 longjmp (host_abortserver, 1);
160 void Host_FindMaxClients (void)
166 i = COM_CheckParm ("-dedicated");
169 cls.state = ca_dedicated;
170 if (i != (com_argc - 1))
172 svs.maxclients = atoi (com_argv[i+1]);
178 cls.state = ca_disconnected;
180 i = COM_CheckParm ("-listen");
183 if (cls.state == ca_dedicated)
184 Sys_Error ("Only one of -dedicated or -listen can be specified");
185 if (i != (com_argc - 1))
186 svs.maxclients = atoi (com_argv[i+1]);
190 if (svs.maxclients < 1)
192 else if (svs.maxclients > MAX_SCOREBOARD)
193 svs.maxclients = MAX_SCOREBOARD;
195 svs.maxclientslimit = svs.maxclients;
196 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
197 svs.maxclientslimit = MAX_SCOREBOARD;
198 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
200 if (svs.maxclients > 1)
201 Cvar_SetValue ("deathmatch", 1.0);
203 Cvar_SetValue ("deathmatch", 0.0);
208 =======================
210 ======================
212 void Host_InitLocal (void)
214 Host_InitCommands ();
216 Cvar_RegisterVariable (&host_framerate);
217 Cvar_RegisterVariable (&host_speeds);
218 Cvar_RegisterVariable (&slowmo);
220 Cvar_RegisterVariable (&sys_ticrate);
221 Cvar_RegisterVariable (&serverprofile);
223 Cvar_RegisterVariable (&fraglimit);
224 Cvar_RegisterVariable (&timelimit);
225 Cvar_RegisterVariable (&teamplay);
226 Cvar_RegisterVariable (&samelevel);
227 Cvar_RegisterVariable (&noexit);
228 Cvar_RegisterVariable (&skill);
229 Cvar_RegisterVariable (&developer);
230 Cvar_RegisterVariable (&deathmatch);
231 Cvar_RegisterVariable (&coop);
233 Cvar_RegisterVariable (&pausable);
235 Cvar_RegisterVariable (&temp1);
237 Cvar_RegisterVariable (×tamps);
238 Cvar_RegisterVariable (&timeformat);
240 Host_FindMaxClients ();
242 host_time = 1.0; // so a think at time 0 won't get called
248 Host_WriteConfiguration
250 Writes key bindings and archived cvars to config.cfg
253 void Host_WriteConfiguration (void)
257 // dedicated servers initialize the host but don't parse and set the
259 if (host_initialized & !isDedicated)
261 f = fopen (va("%s/config.cfg",com_gamedir), "w");
264 Con_Printf ("Couldn't write config.cfg.\n");
268 Key_WriteBindings (f);
269 Cvar_WriteVariables (f);
280 Sends text across to be displayed
281 FIXME: make this just a stuffed echo?
284 void SV_ClientPrintf (char *fmt, ...)
289 va_start (argptr,fmt);
290 vsprintf (string, fmt,argptr);
293 MSG_WriteByte (&host_client->message, svc_print);
294 MSG_WriteString (&host_client->message, string);
301 Sends text to all active clients
304 void SV_BroadcastPrintf (char *fmt, ...)
310 va_start (argptr,fmt);
311 vsprintf (string, fmt,argptr);
314 for (i=0 ; i<svs.maxclients ; i++)
315 if (svs.clients[i].active && svs.clients[i].spawned)
317 MSG_WriteByte (&svs.clients[i].message, svc_print);
318 MSG_WriteString (&svs.clients[i].message, string);
326 Send text over to the client to be executed
329 void Host_ClientCommands (char *fmt, ...)
334 va_start (argptr,fmt);
335 vsprintf (string, fmt,argptr);
338 MSG_WriteByte (&host_client->message, svc_stufftext);
339 MSG_WriteString (&host_client->message, string);
343 =====================
346 Called when the player is getting totally kicked off the host
347 if (crash = true), don't bother sending signofs
348 =====================
350 void SV_DropClient (qboolean crash)
358 // send any final messages (don't check for errors)
359 if (NET_CanSendMessage (host_client->netconnection))
361 MSG_WriteByte (&host_client->message, svc_disconnect);
362 NET_SendMessage (host_client->netconnection, &host_client->message);
365 if (sv.active && host_client->edict && host_client->spawned) // LordHavoc: don't call QC if server is dead (avoids recursive Host_Error in some mods when they run out of edicts)
367 // call the prog function for removing a client
368 // this will set the body to a dead frame, among other things
369 saveSelf = pr_global_struct->self;
370 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
371 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
372 pr_global_struct->self = saveSelf;
375 Sys_Printf ("Client %s removed\n",host_client->name);
378 // break the net connection
379 NET_Close (host_client->netconnection);
380 host_client->netconnection = NULL;
382 // free the client (the body stays around)
383 host_client->active = false;
384 host_client->name[0] = 0;
385 host_client->old_frags = -999999;
386 net_activeconnections--;
388 // send notification to all clients
389 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
393 MSG_WriteByte (&client->message, svc_updatename);
394 MSG_WriteByte (&client->message, host_client - svs.clients);
395 MSG_WriteString (&client->message, "");
396 MSG_WriteByte (&client->message, svc_updatefrags);
397 MSG_WriteByte (&client->message, host_client - svs.clients);
398 MSG_WriteShort (&client->message, 0);
399 MSG_WriteByte (&client->message, svc_updatecolors);
400 MSG_WriteByte (&client->message, host_client - svs.clients);
401 MSG_WriteByte (&client->message, 0);
409 This only happens at the end of a game, not between levels
412 void Host_ShutdownServer(qboolean crash)
425 // stop all client sounds immediately
426 if (cls.state == ca_connected)
429 // flush any pending messages - like the score!!!
430 start = Sys_FloatTime();
434 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
436 if (host_client->active && host_client->message.cursize)
438 if (NET_CanSendMessage (host_client->netconnection))
440 NET_SendMessage(host_client->netconnection, &host_client->message);
441 SZ_Clear (&host_client->message);
445 NET_GetMessage(host_client->netconnection);
450 if ((Sys_FloatTime() - start) > 3.0)
455 // make sure all the clients know we're disconnecting
459 MSG_WriteByte(&buf, svc_disconnect);
460 count = NET_SendToAll(&buf, 5);
462 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
464 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
465 if (host_client->active)
466 SV_DropClient(crash);
471 memset (&sv, 0, sizeof(sv));
472 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
480 This clears all the memory used by both the client and server, but does
481 not reinitialize anything.
484 void Host_ClearMemory (void)
486 Con_DPrintf ("Clearing memory\n");
489 Hunk_FreeToLowMark (host_hunklevel);
492 memset (&sv, 0, sizeof(sv));
493 memset (&cl, 0, sizeof(cl));
497 //============================================================================
503 Returns false if the time is too short to run a frame
506 qboolean Host_FilterTime (float time)
510 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
511 // return false; // framerate is too high
513 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
514 oldrealtime = realtime;
516 if (host_framerate.value > 0)
517 host_frametime = host_framerate.value;
519 { // don't allow really long or short frames
520 if (host_frametime > 0.1)
521 host_frametime = 0.1;
522 if (host_frametime < 0.001)
523 host_frametime = 0.001;
532 Host_GetConsoleCommands
534 Add them exactly as if they had been typed at the console
537 void Host_GetConsoleCommands (void)
543 cmd = Sys_ConsoleInput ();
557 double frametimetotal = 0, lastservertime = 0;
558 void Host_ServerFrame (void)
560 frametimetotal += host_frametime;
561 // LordHavoc: cap server at sys_ticrate in listen games
562 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
564 // run the world state
565 sv_frametime = pr_global_struct->frametime = frametimetotal;
567 // pr_global_struct->frametime = host_frametime;
569 // set the time and clear the general datagram
572 // check for new clients
573 SV_CheckForNewClients ();
575 // read client messages
578 // move things around and think
579 // always pause in single player if in console or menus
580 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
583 // send all messages to the clients
584 SV_SendClientMessages ();
592 Runs all active servers
595 void _Host_Frame (float time)
597 static double time1 = 0;
598 static double time2 = 0;
599 static double time3 = 0;
600 int pass1, pass2, pass3;
602 if (setjmp (host_abortserver) )
603 return; // something bad happened, or the server disconnected
605 // keep the random time dependent
608 // decide the simulation time
609 if (!Host_FilterTime (time))
610 return; // don't run too fast, or packets will flood out
612 // get new key events
613 Sys_SendKeyEvents ();
615 // allow mice or other external controllers to add commands
618 // process console commands
623 // if running the server locally, make intentions now
627 //-------------------
631 //-------------------
633 // check for commands typed to the host
634 Host_GetConsoleCommands ();
639 //-------------------
643 //-------------------
645 // if running the server remotely, send intentions now after
646 // the incoming messages have been read
650 host_time += host_frametime;
652 // fetch results from server
653 if (cls.state == ca_connected)
655 CL_ReadFromServer ();
659 if (host_speeds.value)
660 time1 = Sys_FloatTime ();
664 if (host_speeds.value)
665 time2 = Sys_FloatTime ();
668 if (cls.signon == SIGNONS)
670 S_Update (r_origin, vpn, vright, vup);
674 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
678 if (host_speeds.value)
680 pass1 = (time1 - time3)*1000;
681 time3 = Sys_FloatTime ();
682 pass2 = (time2 - time1)*1000;
683 pass3 = (time3 - time2)*1000;
684 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
685 pass1+pass2+pass3, pass1, pass2, pass3);
691 void Host_Frame (float time)
694 static double timetotal;
695 static int timecount;
698 if (!serverprofile.value)
704 time1 = Sys_FloatTime ();
706 time2 = Sys_FloatTime ();
708 timetotal += time2 - time1;
711 if (timecount < 1000)
714 m = timetotal*1000/timecount;
718 for (i=0 ; i<svs.maxclients ; i++)
720 if (svs.clients[i].active)
724 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
727 //============================================================================
731 #define VCR_SIGNATURE 0x56435231
739 if (COM_CheckParm("-playback"))
742 Sys_Error("No other parameters allowed with -playback\n");
744 Sys_FileOpenRead("quake.vcr", &vcrFile);
746 Sys_Error("playback file not found\n");
748 Sys_FileRead (vcrFile, &i, sizeof(int));
749 if (i != VCR_SIGNATURE)
750 Sys_Error("Invalid signature in vcr file\n");
752 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
753 com_argv = malloc(com_argc * sizeof(char *));
754 com_argv[0] = host_parms.argv[0];
755 for (i = 0; i < com_argc; i++)
757 Sys_FileRead (vcrFile, &len, sizeof(int));
759 Sys_FileRead (vcrFile, p, len);
762 com_argc++; /* add one for arg[0] */
763 host_parms.argc = com_argc;
764 host_parms.argv = com_argv;
767 if ( (n = COM_CheckParm("-record")) != 0)
769 vcrFile = Sys_FileOpenWrite("quake.vcr");
772 Sys_FileWrite(vcrFile, &i, sizeof(int));
774 Sys_FileWrite(vcrFile, &i, sizeof(int));
775 for (i = 1; i < com_argc; i++)
780 Sys_FileWrite(vcrFile, &len, sizeof(int));
781 Sys_FileWrite(vcrFile, "-playback", len);
784 len = strlen(com_argv[i]) + 1;
785 Sys_FileWrite(vcrFile, &len, sizeof(int));
786 Sys_FileWrite(vcrFile, com_argv[i], len);
803 minimum_memory = MINIMUM_MEMORY;
805 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
807 if (COM_CheckParm ("-minmemory"))
808 host_parms.memsize = minimum_memory;
810 if (host_parms.memsize < minimum_memory)
811 Sys_Error ("Only %4.1f megs of memory available, can't execute game", host_parms.memsize / (float)0x100000);
813 com_argc = host_parms.argc;
814 com_argv = host_parms.argv;
816 Memory_Init (host_parms.membase, host_parms.memsize);
822 COM_Init (host_parms.basedir);
824 W_LoadWadFile ("gfx.wad");
833 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
834 Con_Printf ("%4.1f megabyte heap\n",host_parms.memsize/(1024*1024.0));
836 R_InitTextures (); // needed even for dedicated servers
838 if (cls.state != ca_dedicated)
840 Palette_Init("gfx/palette.lmp");
842 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
852 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
857 Cbuf_InsertText ("exec quake.rc\n");
859 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
860 host_hunklevel = Hunk_LowMark ();
862 host_initialized = true;
864 Sys_Printf ("========Quake Initialized=========\n");
872 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
873 to run quit through here before the final handoff to the sys code.
876 void Host_Shutdown(void)
878 static qboolean isdown = false;
882 printf ("recursive shutdown\n");
887 // keep Con_Printf from trying to update the screen
888 scr_disabled_for_loading = true;
890 Host_WriteConfiguration ();
897 if (cls.state != ca_dedicated)