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 //============================================================================
490 extern cvar_t maxfps;
496 Returns false if the time is too short to run a frame
499 qboolean Host_FilterTime (float time)
503 if (maxfps.value < 5) // LordHavoc: sanity checking
505 if (maxfps.value > 1000) // LordHavoc: sanity checking
507 if (!cls.timedemo && realtime - oldrealtime < (1.0 / maxfps.value))
508 return false; // framerate is too high
510 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
511 oldrealtime = realtime;
513 if (host_framerate.value > 0)
514 host_frametime = host_framerate.value;
516 { // don't allow really long or short frames
517 if (host_frametime > 0.1)
518 host_frametime = 0.1;
519 if (host_frametime < 0.001)
520 host_frametime = 0.001;
529 Host_GetConsoleCommands
531 Add them exactly as if they had been typed at the console
534 void Host_GetConsoleCommands (void)
540 cmd = Sys_ConsoleInput ();
556 void _Host_ServerFrame (void)
558 // run the world state
559 pr_global_struct->frametime = host_frametime;
561 // read client messages
564 // move things around and think
565 // always pause in single player if in console or menus
566 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
570 void Host_ServerFrame (void)
572 float save_host_frametime;
573 float temp_host_frametime;
574 static float host_serverframe_timevalue;
576 // run the world state
577 pr_global_struct->frametime = host_frametime;
579 // set the time and clear the general datagram
582 // check for new clients
583 SV_CheckForNewClients ();
585 temp_host_frametime = save_host_frametime = host_frametime;
586 // LordHavoc: the results of my attempts to mangle this code to process no more than sys_ticrate,
587 // when I found that was too choppy, I changed it back to processing at least 20fps,
588 // I consider it a bit of a failure... because I felt a little out of control in singleplayer
590 //if (host_serverframe_timevalue < -0.2) // don't let it get way out of range
591 // host_serverframe_timevalue = -0.2;
592 //host_serverframe_timevalue += host_frametime;
593 // process frames (several if rendering is too slow to run well as a server)
594 while(temp_host_frametime > 0.0)
596 host_frametime = temp_host_frametime;
597 if (host_frametime > 0.05)
598 host_frametime = 0.05;
599 temp_host_frametime -= host_frametime;
600 // host_serverframe_timevalue -= host_frametime;
601 _Host_ServerFrame ();
603 host_frametime = save_host_frametime;
605 // send all messages to the clients
606 SV_SendClientMessages ();
607 // LordHavoc: sadly, this didn't look good to the person running the server in listen mode
609 // wait until enough time has built up when the framerate exceeds sys_ticrate
610 if (host_serverframe_timevalue >= sys_ticrate.value)
612 // while(host_serverframe_timevalue >= sys_ticrate.value)
613 // host_serverframe_timevalue -= sys_ticrate.value;
614 // send all messages to the clients
615 SV_SendClientMessages ();
622 void Host_ServerFrame (void)
624 // run the world state
625 pr_global_struct->frametime = host_frametime;
627 // set the time and clear the general datagram
630 // check for new clients
631 SV_CheckForNewClients ();
633 // read client messages
636 // move things around and think
637 // always pause in single player if in console or menus
638 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
641 // send all messages to the clients
642 SV_SendClientMessages ();
652 Runs all active servers
655 void _Host_Frame (float time)
657 static double time1 = 0;
658 static double time2 = 0;
659 static double time3 = 0;
660 int pass1, pass2, pass3;
662 if (setjmp (host_abortserver) )
663 return; // something bad happened, or the server disconnected
665 // keep the random time dependent
668 // decide the simulation time
669 if (!Host_FilterTime (time))
670 return; // don't run too fast, or packets will flood out
672 // get new key events
673 Sys_SendKeyEvents ();
675 // allow mice or other external controllers to add commands
678 // process console commands
683 // if running the server locally, make intentions now
687 //-------------------
691 //-------------------
693 // check for commands typed to the host
694 Host_GetConsoleCommands ();
699 //-------------------
703 //-------------------
705 // if running the server remotely, send intentions now after
706 // the incoming messages have been read
710 host_time += host_frametime;
712 // fetch results from server
713 if (cls.state == ca_connected)
715 CL_ReadFromServer ();
719 if (host_speeds.value)
720 time1 = Sys_FloatTime ();
724 if (host_speeds.value)
725 time2 = Sys_FloatTime ();
728 if (cls.signon == SIGNONS)
730 S_Update (r_origin, vpn, vright, vup);
734 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
738 if (host_speeds.value)
740 pass1 = (time1 - time3)*1000;
741 time3 = Sys_FloatTime ();
742 pass2 = (time2 - time1)*1000;
743 pass3 = (time3 - time2)*1000;
744 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
745 pass1+pass2+pass3, pass1, pass2, pass3);
751 void Host_Frame (float time)
754 static double timetotal;
755 static int timecount;
758 if (!serverprofile.value)
764 time1 = Sys_FloatTime ();
766 time2 = Sys_FloatTime ();
768 timetotal += time2 - time1;
771 if (timecount < 1000)
774 m = timetotal*1000/timecount;
778 for (i=0 ; i<svs.maxclients ; i++)
780 if (svs.clients[i].active)
784 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
787 //============================================================================
791 #define VCR_SIGNATURE 0x56435231
794 void Host_InitVCR (quakeparms_t *parms)
799 if (COM_CheckParm("-playback"))
802 Sys_Error("No other parameters allowed with -playback\n");
804 Sys_FileOpenRead("quake.vcr", &vcrFile);
806 Sys_Error("playback file not found\n");
808 Sys_FileRead (vcrFile, &i, sizeof(int));
809 if (i != VCR_SIGNATURE)
810 Sys_Error("Invalid signature in vcr file\n");
812 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
813 com_argv = malloc(com_argc * sizeof(char *));
814 com_argv[0] = parms->argv[0];
815 for (i = 0; i < com_argc; i++)
817 Sys_FileRead (vcrFile, &len, sizeof(int));
819 Sys_FileRead (vcrFile, p, len);
822 com_argc++; /* add one for arg[0] */
823 parms->argc = com_argc;
824 parms->argv = com_argv;
827 if ( (n = COM_CheckParm("-record")) != 0)
829 vcrFile = Sys_FileOpenWrite("quake.vcr");
832 Sys_FileWrite(vcrFile, &i, sizeof(int));
834 Sys_FileWrite(vcrFile, &i, sizeof(int));
835 for (i = 1; i < com_argc; i++)
840 Sys_FileWrite(vcrFile, &len, sizeof(int));
841 Sys_FileWrite(vcrFile, "-playback", len);
844 len = strlen(com_argv[i]) + 1;
845 Sys_FileWrite(vcrFile, &len, sizeof(int));
846 Sys_FileWrite(vcrFile, com_argv[i], len);
857 void Host_Init (quakeparms_t *parms)
861 minimum_memory = MINIMUM_MEMORY;
863 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
865 if (COM_CheckParm ("-minmemory"))
866 parms->memsize = minimum_memory;
870 if (parms->memsize < minimum_memory)
871 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
873 com_argc = parms->argc;
874 com_argv = parms->argv;
876 Memory_Init (parms->membase, parms->memsize);
881 Host_InitVCR (parms);
882 COM_Init (parms->basedir);
884 W_LoadWadFile ("gfx.wad");
893 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
894 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
896 R_InitTextures (); // needed even for dedicated servers
898 if (cls.state != ca_dedicated)
900 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
902 Sys_Error ("Couldn't load gfx/palette.lmp");
903 host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
905 Sys_Error ("Couldn't load gfx/colormap.lmp");
907 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
910 VID_Init (host_basepal);
916 // on Win32, sound initialization has to come before video initialization, so we
917 // can put up a popup if the sound hardware is in use
921 // FIXME: doesn't use the new one-window approach yet
928 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
933 Cbuf_InsertText ("exec quake.rc\n");
935 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
936 host_hunklevel = Hunk_LowMark ();
938 host_initialized = true;
940 Sys_Printf ("========Quake Initialized=========\n");
948 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
949 to run quit through here before the final handoff to the sys code.
952 void Host_Shutdown(void)
954 static qboolean isdown = false;
958 printf ("recursive shutdown\n");
963 // keep Con_Printf from trying to update the screen
964 scr_disabled_for_loading = true;
966 Host_WriteConfiguration ();
973 if (cls.state != ca_dedicated)