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;
57 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
58 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
59 cvar_t slowmo = {"slowmo", "1.0"}; // LordHavoc: framerate independent slowmo
61 cvar_t sys_ticrate = {"sys_ticrate","0.05"};
62 cvar_t serverprofile = {"serverprofile","0"};
64 cvar_t fraglimit = {"fraglimit","0",false,true};
65 cvar_t timelimit = {"timelimit","0",false,true};
66 cvar_t teamplay = {"teamplay","0",false,true};
68 cvar_t samelevel = {"samelevel","0"};
69 cvar_t noexit = {"noexit","0",false,true};
71 cvar_t developer = {"developer","0"};
73 cvar_t skill = {"skill","1"}; // 0 - 3
74 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
75 cvar_t coop = {"coop","0"}; // 0 or 1
77 cvar_t pausable = {"pausable","1"};
79 cvar_t temp1 = {"temp1","0"};
81 cvar_t timestamps = {"timestamps", "0", true};
82 cvar_t timeformat = {"timeformat", "[%b %e %X] ", true};
89 void Host_EndGame (char *message, ...)
94 va_start (argptr,message);
95 vsprintf (string,message,argptr);
97 Con_DPrintf ("Host_EndGame: %s\n",string);
100 Host_ShutdownServer (false);
102 if (cls.state == ca_dedicated)
103 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
105 if (cls.demonum != -1)
110 longjmp (host_abortserver, 1);
117 This shuts down both the client and server
120 char hosterrorstring[1024];
121 void Host_Error (char *error, ...)
124 static qboolean inerror = false;
129 va_start (argptr,error);
130 vsprintf (string,error,argptr);
132 Sys_Error ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring, string);
136 SCR_EndLoadingPlaque (); // reenable screen updates
138 va_start (argptr,error);
139 vsprintf (hosterrorstring,error,argptr);
141 Con_Printf ("Host_Error: %s\n",hosterrorstring);
144 Host_ShutdownServer (false);
146 if (cls.state == ca_dedicated)
147 Sys_Error ("Host_Error: %s\n",hosterrorstring); // dedicated servers exit
154 longjmp (host_abortserver, 1);
162 void Host_FindMaxClients (void)
168 i = COM_CheckParm ("-dedicated");
171 cls.state = ca_dedicated;
172 if (i != (com_argc - 1))
174 svs.maxclients = atoi (com_argv[i+1]);
180 cls.state = ca_disconnected;
182 i = COM_CheckParm ("-listen");
185 if (cls.state == ca_dedicated)
186 Sys_Error ("Only one of -dedicated or -listen can be specified");
187 if (i != (com_argc - 1))
188 svs.maxclients = atoi (com_argv[i+1]);
192 if (svs.maxclients < 1)
194 else if (svs.maxclients > MAX_SCOREBOARD)
195 svs.maxclients = MAX_SCOREBOARD;
197 svs.maxclientslimit = svs.maxclients;
198 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
199 svs.maxclientslimit = MAX_SCOREBOARD;
200 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
202 if (svs.maxclients > 1)
203 Cvar_SetValue ("deathmatch", 1.0);
205 Cvar_SetValue ("deathmatch", 0.0);
210 =======================
212 ======================
214 void Host_InitLocal (void)
216 Host_InitCommands ();
218 Cvar_RegisterVariable (&host_framerate);
219 Cvar_RegisterVariable (&host_speeds);
220 Cvar_RegisterVariable (&slowmo);
222 Cvar_RegisterVariable (&sys_ticrate);
223 Cvar_RegisterVariable (&serverprofile);
225 Cvar_RegisterVariable (&fraglimit);
226 Cvar_RegisterVariable (&timelimit);
227 Cvar_RegisterVariable (&teamplay);
228 Cvar_RegisterVariable (&samelevel);
229 Cvar_RegisterVariable (&noexit);
230 Cvar_RegisterVariable (&skill);
231 Cvar_RegisterVariable (&developer);
232 Cvar_RegisterVariable (&deathmatch);
233 Cvar_RegisterVariable (&coop);
235 Cvar_RegisterVariable (&pausable);
237 Cvar_RegisterVariable (&temp1);
239 Cvar_RegisterVariable (×tamps);
240 Cvar_RegisterVariable (&timeformat);
242 Host_FindMaxClients ();
244 host_time = 1.0; // so a think at time 0 won't get called
250 Host_WriteConfiguration
252 Writes key bindings and archived cvars to config.cfg
255 void Host_WriteConfiguration (void)
259 // dedicated servers initialize the host but don't parse and set the
261 if (host_initialized & !isDedicated)
263 f = fopen (va("%s/config.cfg",com_gamedir), "w");
266 Con_Printf ("Couldn't write config.cfg.\n");
270 Key_WriteBindings (f);
271 Cvar_WriteVariables (f);
282 Sends text across to be displayed
283 FIXME: make this just a stuffed echo?
286 void SV_ClientPrintf (char *fmt, ...)
291 va_start (argptr,fmt);
292 vsprintf (string, fmt,argptr);
295 MSG_WriteByte (&host_client->message, svc_print);
296 MSG_WriteString (&host_client->message, string);
303 Sends text to all active clients
306 void SV_BroadcastPrintf (char *fmt, ...)
312 va_start (argptr,fmt);
313 vsprintf (string, fmt,argptr);
316 for (i=0 ; i<svs.maxclients ; i++)
317 if (svs.clients[i].active && svs.clients[i].spawned)
319 MSG_WriteByte (&svs.clients[i].message, svc_print);
320 MSG_WriteString (&svs.clients[i].message, string);
328 Send text over to the client to be executed
331 void Host_ClientCommands (char *fmt, ...)
336 va_start (argptr,fmt);
337 vsprintf (string, fmt,argptr);
340 MSG_WriteByte (&host_client->message, svc_stufftext);
341 MSG_WriteString (&host_client->message, string);
345 =====================
348 Called when the player is getting totally kicked off the host
349 if (crash = true), don't bother sending signofs
350 =====================
352 void SV_DropClient (qboolean crash)
360 // send any final messages (don't check for errors)
361 if (NET_CanSendMessage (host_client->netconnection))
363 MSG_WriteByte (&host_client->message, svc_disconnect);
364 NET_SendMessage (host_client->netconnection, &host_client->message);
367 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)
369 // call the prog function for removing a client
370 // this will set the body to a dead frame, among other things
371 saveSelf = pr_global_struct->self;
372 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
373 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
374 pr_global_struct->self = saveSelf;
377 Sys_Printf ("Client %s removed\n",host_client->name);
380 // break the net connection
381 NET_Close (host_client->netconnection);
382 host_client->netconnection = NULL;
384 // free the client (the body stays around)
385 host_client->active = false;
386 host_client->name[0] = 0;
387 host_client->old_frags = -999999;
388 net_activeconnections--;
390 // send notification to all clients
391 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
395 MSG_WriteByte (&client->message, svc_updatename);
396 MSG_WriteByte (&client->message, host_client - svs.clients);
397 MSG_WriteString (&client->message, "");
398 MSG_WriteByte (&client->message, svc_updatefrags);
399 MSG_WriteByte (&client->message, host_client - svs.clients);
400 MSG_WriteShort (&client->message, 0);
401 MSG_WriteByte (&client->message, svc_updatecolors);
402 MSG_WriteByte (&client->message, host_client - svs.clients);
403 MSG_WriteByte (&client->message, 0);
411 This only happens at the end of a game, not between levels
414 void Host_ShutdownServer(qboolean crash)
427 // stop all client sounds immediately
428 if (cls.state == ca_connected)
431 // flush any pending messages - like the score!!!
432 start = Sys_FloatTime();
436 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
438 if (host_client->active && host_client->message.cursize)
440 if (NET_CanSendMessage (host_client->netconnection))
442 NET_SendMessage(host_client->netconnection, &host_client->message);
443 SZ_Clear (&host_client->message);
447 NET_GetMessage(host_client->netconnection);
452 if ((Sys_FloatTime() - start) > 3.0)
457 // make sure all the clients know we're disconnecting
461 MSG_WriteByte(&buf, svc_disconnect);
462 count = NET_SendToAll(&buf, 5);
464 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
466 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
467 if (host_client->active)
468 SV_DropClient(crash);
473 memset (&sv, 0, sizeof(sv));
474 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
482 This clears all the memory used by both the client and server, but does
483 not reinitialize anything.
486 void Host_ClearMemory (void)
488 Con_DPrintf ("Clearing memory\n");
491 Hunk_FreeToLowMark (host_hunklevel);
494 memset (&sv, 0, sizeof(sv));
495 memset (&cl, 0, sizeof(cl));
499 //============================================================================
505 Returns false if the time is too short to run a frame
508 qboolean Host_FilterTime (float time)
512 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
513 // return false; // framerate is too high
515 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
516 oldrealtime = realtime;
518 if (host_framerate.value > 0)
519 host_frametime = host_framerate.value;
521 { // don't allow really long or short frames
522 if (host_frametime > 0.1)
523 host_frametime = 0.1;
524 if (host_frametime < 0.001)
525 host_frametime = 0.001;
534 Host_GetConsoleCommands
536 Add them exactly as if they had been typed at the console
539 void Host_GetConsoleCommands (void)
545 cmd = Sys_ConsoleInput ();
559 double frametimetotal = 0, lastservertime = 0;
560 void Host_ServerFrame (void)
562 frametimetotal += host_frametime;
563 // LordHavoc: cap server at sys_ticrate in listen games
564 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
566 // run the world state
567 sv_frametime = pr_global_struct->frametime = frametimetotal;
569 // pr_global_struct->frametime = host_frametime;
571 // set the time and clear the general datagram
574 // check for new clients
575 SV_CheckForNewClients ();
577 // read client messages
580 // move things around and think
581 // always pause in single player if in console or menus
582 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
585 // send all messages to the clients
586 SV_SendClientMessages ();
594 Runs all active servers
597 void _Host_Frame (float time)
599 static double time1 = 0;
600 static double time2 = 0;
601 static double time3 = 0;
602 int pass1, pass2, pass3;
604 if (setjmp (host_abortserver) )
605 return; // something bad happened, or the server disconnected
607 // keep the random time dependent
610 // decide the simulation time
611 if (!Host_FilterTime (time))
612 return; // don't run too fast, or packets will flood out
614 // get new key events
615 Sys_SendKeyEvents ();
617 // allow mice or other external controllers to add commands
620 // process console commands
625 // if running the server locally, make intentions now
629 //-------------------
633 //-------------------
635 // check for commands typed to the host
636 Host_GetConsoleCommands ();
641 //-------------------
645 //-------------------
647 // if running the server remotely, send intentions now after
648 // the incoming messages have been read
652 host_time += host_frametime;
654 // fetch results from server
655 if (cls.state == ca_connected)
657 CL_ReadFromServer ();
661 if (host_speeds.value)
662 time1 = Sys_FloatTime ();
666 if (host_speeds.value)
667 time2 = Sys_FloatTime ();
670 if (cls.signon == SIGNONS)
672 S_Update (r_origin, vpn, vright, vup);
676 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
680 if (host_speeds.value)
682 pass1 = (time1 - time3)*1000;
683 time3 = Sys_FloatTime ();
684 pass2 = (time2 - time1)*1000;
685 pass3 = (time3 - time2)*1000;
686 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
687 pass1+pass2+pass3, pass1, pass2, pass3);
693 void Host_Frame (float time)
696 static double timetotal;
697 static int timecount;
700 if (!serverprofile.value)
706 time1 = Sys_FloatTime ();
708 time2 = Sys_FloatTime ();
710 timetotal += time2 - time1;
713 if (timecount < 1000)
716 m = timetotal*1000/timecount;
720 for (i=0 ; i<svs.maxclients ; i++)
722 if (svs.clients[i].active)
726 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
729 //============================================================================
733 #define VCR_SIGNATURE 0x56435231
736 void Host_InitVCR (quakeparms_t *parms)
741 if (COM_CheckParm("-playback"))
744 Sys_Error("No other parameters allowed with -playback\n");
746 Sys_FileOpenRead("quake.vcr", &vcrFile);
748 Sys_Error("playback file not found\n");
750 Sys_FileRead (vcrFile, &i, sizeof(int));
751 if (i != VCR_SIGNATURE)
752 Sys_Error("Invalid signature in vcr file\n");
754 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
755 com_argv = malloc(com_argc * sizeof(char *));
756 com_argv[0] = parms->argv[0];
757 for (i = 0; i < com_argc; i++)
759 Sys_FileRead (vcrFile, &len, sizeof(int));
761 Sys_FileRead (vcrFile, p, len);
764 com_argc++; /* add one for arg[0] */
765 parms->argc = com_argc;
766 parms->argv = com_argv;
769 if ( (n = COM_CheckParm("-record")) != 0)
771 vcrFile = Sys_FileOpenWrite("quake.vcr");
774 Sys_FileWrite(vcrFile, &i, sizeof(int));
776 Sys_FileWrite(vcrFile, &i, sizeof(int));
777 for (i = 1; i < com_argc; i++)
782 Sys_FileWrite(vcrFile, &len, sizeof(int));
783 Sys_FileWrite(vcrFile, "-playback", len);
786 len = strlen(com_argv[i]) + 1;
787 Sys_FileWrite(vcrFile, &len, sizeof(int));
788 Sys_FileWrite(vcrFile, com_argv[i], len);
801 void Host_Init (quakeparms_t *parms)
805 minimum_memory = MINIMUM_MEMORY;
807 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
809 if (COM_CheckParm ("-minmemory"))
810 parms->memsize = minimum_memory;
814 if (parms->memsize < minimum_memory)
815 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
817 com_argc = parms->argc;
818 com_argv = parms->argv;
820 Memory_Init (parms->membase, parms->memsize);
825 Host_InitVCR (parms);
826 COM_Init (parms->basedir);
828 W_LoadWadFile ("gfx.wad");
837 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
838 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
840 R_InitTextures (); // needed even for dedicated servers
842 if (cls.state != ca_dedicated)
844 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
846 Sys_Error ("Couldn't load gfx/palette.lmp");
847 host_basepal[765] = host_basepal[766] = host_basepal[767] = 0; // LordHavoc: force the transparent color to black
849 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
852 VID_Init (host_basepal);
859 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
864 Cbuf_InsertText ("exec quake.rc\n");
866 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
867 host_hunklevel = Hunk_LowMark ();
869 host_initialized = true;
871 Sys_Printf ("========Quake Initialized=========\n");
879 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
880 to run quit through here before the final handoff to the sys code.
883 void Host_Shutdown(void)
885 static qboolean isdown = false;
889 printf ("recursive shutdown\n");
894 // keep Con_Printf from trying to update the screen
895 scr_disabled_for_loading = true;
897 Host_WriteConfiguration ();
904 if (cls.state != ca_dedicated)