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
49 client_t *host_client; // current client
51 jmp_buf host_abortserver;
56 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
57 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
58 cvar_t slowmo = {"slowmo", "1.0"}; // LordHavoc: framerate independent slowmo
60 cvar_t sys_ticrate = {"sys_ticrate","0.05"};
61 cvar_t serverprofile = {"serverprofile","0"};
63 cvar_t fraglimit = {"fraglimit","0",false,true};
64 cvar_t timelimit = {"timelimit","0",false,true};
65 cvar_t teamplay = {"teamplay","0",false,true};
67 cvar_t samelevel = {"samelevel","0"};
68 cvar_t noexit = {"noexit","0",false,true};
70 cvar_t developer = {"developer","0"};
72 cvar_t skill = {"skill","1"}; // 0 - 3
73 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
74 cvar_t coop = {"coop","0"}; // 0 or 1
76 cvar_t pausable = {"pausable","1"};
78 cvar_t temp1 = {"temp1","0"};
86 void Host_EndGame (char *message, ...)
91 va_start (argptr,message);
92 vsprintf (string,message,argptr);
94 Con_DPrintf ("Host_EndGame: %s\n",string);
97 Host_ShutdownServer (false);
99 if (cls.state == ca_dedicated)
100 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
102 if (cls.demonum != -1)
107 longjmp (host_abortserver, 1);
114 This shuts down both the client and server
117 void Host_Error (char *error, ...)
121 static qboolean inerror = false;
124 Sys_Error ("Host_Error: recursively entered");
127 SCR_EndLoadingPlaque (); // reenable screen updates
129 va_start (argptr,error);
130 vsprintf (string,error,argptr);
132 Con_Printf ("Host_Error: %s\n",string);
135 Host_ShutdownServer (false);
137 if (cls.state == ca_dedicated)
138 Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit
145 longjmp (host_abortserver, 1);
153 void Host_FindMaxClients (void)
159 i = COM_CheckParm ("-dedicated");
162 cls.state = ca_dedicated;
163 if (i != (com_argc - 1))
165 svs.maxclients = atoi (com_argv[i+1]);
171 cls.state = ca_disconnected;
173 i = COM_CheckParm ("-listen");
176 if (cls.state == ca_dedicated)
177 Sys_Error ("Only one of -dedicated or -listen can be specified");
178 if (i != (com_argc - 1))
179 svs.maxclients = atoi (com_argv[i+1]);
183 if (svs.maxclients < 1)
185 else if (svs.maxclients > MAX_SCOREBOARD)
186 svs.maxclients = MAX_SCOREBOARD;
188 svs.maxclientslimit = svs.maxclients;
189 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
190 svs.maxclientslimit = MAX_SCOREBOARD;
191 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
193 if (svs.maxclients > 1)
194 Cvar_SetValue ("deathmatch", 1.0);
196 Cvar_SetValue ("deathmatch", 0.0);
201 =======================
203 ======================
205 void Host_InitLocal (void)
207 Host_InitCommands ();
209 Cvar_RegisterVariable (&host_framerate);
210 Cvar_RegisterVariable (&host_speeds);
211 Cvar_RegisterVariable (&slowmo);
213 Cvar_RegisterVariable (&sys_ticrate);
214 Cvar_RegisterVariable (&serverprofile);
216 Cvar_RegisterVariable (&fraglimit);
217 Cvar_RegisterVariable (&timelimit);
218 Cvar_RegisterVariable (&teamplay);
219 Cvar_RegisterVariable (&samelevel);
220 Cvar_RegisterVariable (&noexit);
221 Cvar_RegisterVariable (&skill);
222 Cvar_RegisterVariable (&developer);
223 Cvar_RegisterVariable (&deathmatch);
224 Cvar_RegisterVariable (&coop);
226 Cvar_RegisterVariable (&pausable);
228 Cvar_RegisterVariable (&temp1);
230 Host_FindMaxClients ();
232 host_time = 1.0; // so a think at time 0 won't get called
238 Host_WriteConfiguration
240 Writes key bindings and archived cvars to config.cfg
243 void Host_WriteConfiguration (void)
247 // dedicated servers initialize the host but don't parse and set the
249 if (host_initialized & !isDedicated)
251 f = fopen (va("%s/config.cfg",com_gamedir), "w");
254 Con_Printf ("Couldn't write config.cfg.\n");
258 Key_WriteBindings (f);
259 Cvar_WriteVariables (f);
270 Sends text across to be displayed
271 FIXME: make this just a stuffed echo?
274 void SV_ClientPrintf (char *fmt, ...)
279 va_start (argptr,fmt);
280 vsprintf (string, fmt,argptr);
283 MSG_WriteByte (&host_client->message, svc_print);
284 MSG_WriteString (&host_client->message, string);
291 Sends text to all active clients
294 void SV_BroadcastPrintf (char *fmt, ...)
300 va_start (argptr,fmt);
301 vsprintf (string, fmt,argptr);
304 for (i=0 ; i<svs.maxclients ; i++)
305 if (svs.clients[i].active && svs.clients[i].spawned)
307 MSG_WriteByte (&svs.clients[i].message, svc_print);
308 MSG_WriteString (&svs.clients[i].message, string);
316 Send text over to the client to be executed
319 void Host_ClientCommands (char *fmt, ...)
324 va_start (argptr,fmt);
325 vsprintf (string, fmt,argptr);
328 MSG_WriteByte (&host_client->message, svc_stufftext);
329 MSG_WriteString (&host_client->message, string);
333 =====================
336 Called when the player is getting totally kicked off the host
337 if (crash = true), don't bother sending signofs
338 =====================
340 void SV_DropClient (qboolean crash)
348 // send any final messages (don't check for errors)
349 if (NET_CanSendMessage (host_client->netconnection))
351 MSG_WriteByte (&host_client->message, svc_disconnect);
352 NET_SendMessage (host_client->netconnection, &host_client->message);
355 if (host_client->edict && host_client->spawned)
357 // call the prog function for removing a client
358 // this will set the body to a dead frame, among other things
359 saveSelf = pr_global_struct->self;
360 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
361 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
362 pr_global_struct->self = saveSelf;
365 Sys_Printf ("Client %s removed\n",host_client->name);
368 // break the net connection
369 NET_Close (host_client->netconnection);
370 host_client->netconnection = NULL;
372 // free the client (the body stays around)
373 host_client->active = false;
374 host_client->name[0] = 0;
375 host_client->old_frags = -999999;
376 net_activeconnections--;
378 // send notification to all clients
379 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
383 MSG_WriteByte (&client->message, svc_updatename);
384 MSG_WriteByte (&client->message, host_client - svs.clients);
385 MSG_WriteString (&client->message, "");
386 MSG_WriteByte (&client->message, svc_updatefrags);
387 MSG_WriteByte (&client->message, host_client - svs.clients);
388 MSG_WriteShort (&client->message, 0);
389 MSG_WriteByte (&client->message, svc_updatecolors);
390 MSG_WriteByte (&client->message, host_client - svs.clients);
391 MSG_WriteByte (&client->message, 0);
399 This only happens at the end of a game, not between levels
402 void Host_ShutdownServer(qboolean crash)
415 // stop all client sounds immediately
416 if (cls.state == ca_connected)
419 // flush any pending messages - like the score!!!
420 start = Sys_FloatTime();
424 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
426 if (host_client->active && host_client->message.cursize)
428 if (NET_CanSendMessage (host_client->netconnection))
430 NET_SendMessage(host_client->netconnection, &host_client->message);
431 SZ_Clear (&host_client->message);
435 NET_GetMessage(host_client->netconnection);
440 if ((Sys_FloatTime() - start) > 3.0)
445 // make sure all the clients know we're disconnecting
449 MSG_WriteByte(&buf, svc_disconnect);
450 count = NET_SendToAll(&buf, 5);
452 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
454 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
455 if (host_client->active)
456 SV_DropClient(crash);
461 memset (&sv, 0, sizeof(sv));
462 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
470 This clears all the memory used by both the client and server, but does
471 not reinitialize anything.
474 void Host_ClearMemory (void)
476 Con_DPrintf ("Clearing memory\n");
480 Hunk_FreeToLowMark (host_hunklevel);
483 memset (&sv, 0, sizeof(sv));
484 memset (&cl, 0, sizeof(cl));
488 //============================================================================
494 Returns false if the time is too short to run a frame
497 qboolean Host_FilterTime (float time)
501 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
502 // return false; // framerate is too high
504 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
505 oldrealtime = realtime;
507 if (host_framerate.value > 0)
508 host_frametime = host_framerate.value;
510 { // don't allow really long or short frames
511 if (host_frametime > 0.1)
512 host_frametime = 0.1;
513 if (host_frametime < 0.001)
514 host_frametime = 0.001;
523 Host_GetConsoleCommands
525 Add them exactly as if they had been typed at the console
528 void Host_GetConsoleCommands (void)
534 cmd = Sys_ConsoleInput ();
550 void _Host_ServerFrame (void)
552 // run the world state
553 pr_global_struct->frametime = host_frametime;
555 // read client messages
558 // move things around and think
559 // always pause in single player if in console or menus
560 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
564 void Host_ServerFrame (void)
566 float save_host_frametime;
567 float temp_host_frametime;
568 static float host_serverframe_timevalue;
570 // run the world state
571 pr_global_struct->frametime = host_frametime;
573 // set the time and clear the general datagram
576 // check for new clients
577 SV_CheckForNewClients ();
579 temp_host_frametime = save_host_frametime = host_frametime;
580 // LordHavoc: the results of my attempts to mangle this code to process no more than sys_ticrate,
581 // when I found that was too choppy, I changed it back to processing at least 20fps,
582 // I consider it a bit of a failure... because I felt a little out of control in singleplayer
584 //if (host_serverframe_timevalue < -0.2) // don't let it get way out of range
585 // host_serverframe_timevalue = -0.2;
586 //host_serverframe_timevalue += host_frametime;
587 // process frames (several if rendering is too slow to run well as a server)
588 while(temp_host_frametime > 0.0)
590 host_frametime = temp_host_frametime;
591 if (host_frametime > 0.05)
592 host_frametime = 0.05;
593 temp_host_frametime -= host_frametime;
594 // host_serverframe_timevalue -= host_frametime;
595 _Host_ServerFrame ();
597 host_frametime = save_host_frametime;
599 // send all messages to the clients
600 SV_SendClientMessages ();
601 // LordHavoc: sadly, this didn't look good to the person running the server in listen mode
603 // wait until enough time has built up when the framerate exceeds sys_ticrate
604 if (host_serverframe_timevalue >= sys_ticrate.value)
606 // while(host_serverframe_timevalue >= sys_ticrate.value)
607 // host_serverframe_timevalue -= sys_ticrate.value;
608 // send all messages to the clients
609 SV_SendClientMessages ();
616 double frametimetotal = 0, lastservertime = 0;
617 void Host_ServerFrame (void)
619 frametimetotal += host_frametime;
620 // LordHavoc: cap server at sys_ticrate in listen games
621 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
623 // run the world state
624 pr_global_struct->frametime = frametimetotal;
626 // pr_global_struct->frametime = host_frametime;
628 // set the time and clear the general datagram
631 // check for new clients
632 SV_CheckForNewClients ();
634 // read client messages
637 // move things around and think
638 // always pause in single player if in console or menus
639 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
642 // send all messages to the clients
643 SV_SendClientMessages ();
653 Runs all active servers
656 void _Host_Frame (float time)
658 static double time1 = 0;
659 static double time2 = 0;
660 static double time3 = 0;
661 int pass1, pass2, pass3;
663 if (setjmp (host_abortserver) )
664 return; // something bad happened, or the server disconnected
666 // keep the random time dependent
669 // decide the simulation time
670 if (!Host_FilterTime (time))
671 return; // don't run too fast, or packets will flood out
673 // get new key events
674 Sys_SendKeyEvents ();
676 // allow mice or other external controllers to add commands
679 // process console commands
684 // if running the server locally, make intentions now
688 //-------------------
692 //-------------------
694 // check for commands typed to the host
695 Host_GetConsoleCommands ();
700 //-------------------
704 //-------------------
706 // if running the server remotely, send intentions now after
707 // the incoming messages have been read
711 host_time += host_frametime;
713 // fetch results from server
714 if (cls.state == ca_connected)
716 CL_ReadFromServer ();
720 if (host_speeds.value)
721 time1 = Sys_FloatTime ();
725 if (host_speeds.value)
726 time2 = Sys_FloatTime ();
729 if (cls.signon == SIGNONS)
731 S_Update (r_origin, vpn, vright, vup);
735 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
739 if (host_speeds.value)
741 pass1 = (time1 - time3)*1000;
742 time3 = Sys_FloatTime ();
743 pass2 = (time2 - time1)*1000;
744 pass3 = (time3 - time2)*1000;
745 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
746 pass1+pass2+pass3, pass1, pass2, pass3);
752 void Host_Frame (float time)
755 static double timetotal;
756 static int timecount;
759 if (!serverprofile.value)
765 time1 = Sys_FloatTime ();
767 time2 = Sys_FloatTime ();
769 timetotal += time2 - time1;
772 if (timecount < 1000)
775 m = timetotal*1000/timecount;
779 for (i=0 ; i<svs.maxclients ; i++)
781 if (svs.clients[i].active)
785 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
788 //============================================================================
792 #define VCR_SIGNATURE 0x56435231
795 void Host_InitVCR (quakeparms_t *parms)
800 if (COM_CheckParm("-playback"))
803 Sys_Error("No other parameters allowed with -playback\n");
805 Sys_FileOpenRead("quake.vcr", &vcrFile);
807 Sys_Error("playback file not found\n");
809 Sys_FileRead (vcrFile, &i, sizeof(int));
810 if (i != VCR_SIGNATURE)
811 Sys_Error("Invalid signature in vcr file\n");
813 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
814 com_argv = malloc(com_argc * sizeof(char *));
815 com_argv[0] = parms->argv[0];
816 for (i = 0; i < com_argc; i++)
818 Sys_FileRead (vcrFile, &len, sizeof(int));
820 Sys_FileRead (vcrFile, p, len);
823 com_argc++; /* add one for arg[0] */
824 parms->argc = com_argc;
825 parms->argv = com_argv;
828 if ( (n = COM_CheckParm("-record")) != 0)
830 vcrFile = Sys_FileOpenWrite("quake.vcr");
833 Sys_FileWrite(vcrFile, &i, sizeof(int));
835 Sys_FileWrite(vcrFile, &i, sizeof(int));
836 for (i = 1; i < com_argc; i++)
841 Sys_FileWrite(vcrFile, &len, sizeof(int));
842 Sys_FileWrite(vcrFile, "-playback", len);
845 len = strlen(com_argv[i]) + 1;
846 Sys_FileWrite(vcrFile, &len, sizeof(int));
847 Sys_FileWrite(vcrFile, com_argv[i], len);
858 void Host_Init (quakeparms_t *parms)
862 minimum_memory = MINIMUM_MEMORY;
864 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
866 if (COM_CheckParm ("-minmemory"))
867 parms->memsize = minimum_memory;
871 if (parms->memsize < minimum_memory)
872 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
874 com_argc = parms->argc;
875 com_argv = parms->argv;
877 Memory_Init (parms->membase, parms->memsize);
882 Host_InitVCR (parms);
883 COM_Init (parms->basedir);
885 W_LoadWadFile ("gfx.wad");
894 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
895 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
897 R_InitTextures (); // needed even for dedicated servers
899 if (cls.state != ca_dedicated)
901 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
903 Sys_Error ("Couldn't load gfx/palette.lmp");
904 host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
906 Sys_Error ("Couldn't load gfx/colormap.lmp");
908 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
911 VID_Init (host_basepal);
917 // on Win32, sound initialization has to come before video initialization, so we
918 // can put up a popup if the sound hardware is in use
922 // FIXME: doesn't use the new one-window approach yet
929 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
934 Cbuf_InsertText ("exec quake.rc\n");
936 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
937 host_hunklevel = Hunk_LowMark ();
939 host_initialized = true;
941 Sys_Printf ("========Quake Initialized=========\n");
949 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
950 to run quit through here before the final handoff to the sys code.
953 void Host_Shutdown(void)
955 static qboolean isdown = false;
959 printf ("recursive shutdown\n");
964 // keep Con_Printf from trying to update the screen
965 scr_disabled_for_loading = true;
967 Host_WriteConfiguration ();
974 if (cls.state != ca_dedicated)