Fix for the problem that SDL applications exited
[AROS-Contrib.git] / Games / Quake / host.c
bloba6be46b2bf782ba5d7b9d604d497c3dc9e1ac210
1 /*
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
22 #include <stdio.h>
23 #include "quakedef.h"
24 #include "r_local.h"
28 A server can allways be started, even if the system started out as a client
29 to a remote system.
31 A client can NOT be started if the system started as a dedicated server.
33 Memory is cleared / released when a server or client begins, not when they end.
37 quakeparms_t host_parms;
39 qboolean host_initialized; // true if into command execution
41 double host_frametime;
42 double host_time;
43 double realtime; // without any filtering or bounding
44 double oldrealtime; // last frame run
45 int host_framecount;
47 int host_hunklevel;
49 int minimum_memory;
51 client_t *host_client; // current client
53 jmp_buf host_abortserver;
55 byte *host_basepal;
56 byte *host_colormap;
58 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
59 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
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 #ifdef QUAKE2
72 cvar_t developer = {"developer","1"}; // should be 0 for release!
73 #else
74 cvar_t developer = {"developer","0"};
75 #endif
77 cvar_t skill = {"skill","1"}; // 0 - 3
78 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
79 cvar_t coop = {"coop","0"}; // 0 or 1
81 cvar_t pausable = {"pausable","1"};
83 cvar_t temp1 = {"temp1","0"};
87 ================
88 Host_EndGame
89 ================
91 void Host_EndGame (char *message, ...)
93 va_list argptr;
94 char string[1024];
96 va_start (argptr,message);
97 vsprintf (string,message,argptr);
98 va_end (argptr);
99 Con_DPrintf ("Host_EndGame: %s\n",string);
101 if (sv.active)
102 Host_ShutdownServer (false);
104 if (cls.state == ca_dedicated)
105 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
107 if (cls.demonum != -1)
108 CL_NextDemo ();
109 else
110 CL_Disconnect ();
112 longjmp (host_abortserver, 1);
116 ================
117 Host_Error
119 This shuts down both the client and server
120 ================
122 void Host_Error (char *error, ...)
124 va_list argptr;
125 char string[1024];
126 static qboolean inerror = false;
128 if (inerror)
129 Sys_Error ("Host_Error: recursively entered");
130 inerror = true;
132 SCR_EndLoadingPlaque (); // reenable screen updates
134 va_start (argptr,error);
135 vsprintf (string,error,argptr);
136 va_end (argptr);
137 Con_Printf ("Host_Error: %s\n",string);
139 if (sv.active)
140 Host_ShutdownServer (false);
142 if (cls.state == ca_dedicated)
143 Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit
145 CL_Disconnect ();
146 cls.demonum = -1;
148 inerror = false;
150 longjmp (host_abortserver, 1);
154 ================
155 Host_FindMaxClients
156 ================
158 void Host_FindMaxClients (void)
160 int i;
162 svs.maxclients = 1;
164 i = COM_CheckParm ("-dedicated");
165 if (i)
167 cls.state = ca_dedicated;
168 if (i != (com_argc - 1))
170 svs.maxclients = Q_atoi (com_argv[i+1]);
172 else
173 svs.maxclients = 8;
175 else
176 cls.state = ca_disconnected;
178 i = COM_CheckParm ("-listen");
179 if (i)
181 if (cls.state == ca_dedicated)
182 Sys_Error ("Only one of -dedicated or -listen can be specified");
183 if (i != (com_argc - 1))
184 svs.maxclients = Q_atoi (com_argv[i+1]);
185 else
186 svs.maxclients = 8;
188 if (svs.maxclients < 1)
189 svs.maxclients = 8;
190 else if (svs.maxclients > MAX_SCOREBOARD)
191 svs.maxclients = MAX_SCOREBOARD;
193 svs.maxclientslimit = svs.maxclients;
194 if (svs.maxclientslimit < 4)
195 svs.maxclientslimit = 4;
196 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
198 if (svs.maxclients > 1)
199 Cvar_SetValue ("deathmatch", 1.0);
200 else
201 Cvar_SetValue ("deathmatch", 0.0);
206 =======================
207 Host_InitLocal
208 ======================
210 void Host_InitLocal (void)
212 Host_InitCommands ();
214 Cvar_RegisterVariable (&host_framerate);
215 Cvar_RegisterVariable (&host_speeds);
217 Cvar_RegisterVariable (&sys_ticrate);
218 Cvar_RegisterVariable (&serverprofile);
220 Cvar_RegisterVariable (&fraglimit);
221 Cvar_RegisterVariable (&timelimit);
222 Cvar_RegisterVariable (&teamplay);
223 Cvar_RegisterVariable (&samelevel);
224 Cvar_RegisterVariable (&noexit);
225 Cvar_RegisterVariable (&skill);
226 Cvar_RegisterVariable (&developer);
227 Cvar_RegisterVariable (&deathmatch);
228 Cvar_RegisterVariable (&coop);
230 Cvar_RegisterVariable (&pausable);
232 Cvar_RegisterVariable (&temp1);
234 Host_FindMaxClients ();
236 host_time = 1.0; // so a think at time 0 won't get called
241 ===============
242 Host_WriteConfiguration
244 Writes key bindings and archived cvars to config.cfg
245 ===============
247 void Host_WriteConfiguration (void)
249 FILE *f;
251 // dedicated servers initialize the host but don't parse and set the
252 // config.cfg cvars
253 if (host_initialized & !isDedicated)
255 f = fopen (va("%s/config.cfg",com_gamedir), "w");
256 if (!f)
258 Con_Printf ("Couldn't write config.cfg.\n");
259 return;
262 Key_WriteBindings (f);
263 Cvar_WriteVariables (f);
265 fclose (f);
271 =================
272 SV_ClientPrintf
274 Sends text across to be displayed
275 FIXME: make this just a stuffed echo?
276 =================
278 void SV_ClientPrintf (char *fmt, ...)
280 va_list argptr;
281 char string[1024];
283 va_start (argptr,fmt);
284 vsprintf (string, fmt,argptr);
285 va_end (argptr);
287 MSG_WriteByte (&host_client->message, svc_print);
288 MSG_WriteString (&host_client->message, string);
292 =================
293 SV_BroadcastPrintf
295 Sends text to all active clients
296 =================
298 void SV_BroadcastPrintf (char *fmt, ...)
300 va_list argptr;
301 char string[1024];
302 int i;
304 va_start (argptr,fmt);
305 vsprintf (string, fmt,argptr);
306 va_end (argptr);
308 for (i=0 ; i<svs.maxclients ; i++)
309 if (svs.clients[i].active && svs.clients[i].spawned)
311 MSG_WriteByte (&svs.clients[i].message, svc_print);
312 MSG_WriteString (&svs.clients[i].message, string);
317 =================
318 Host_ClientCommands
320 Send text over to the client to be executed
321 =================
323 void Host_ClientCommands (char *fmt, ...)
325 va_list argptr;
326 char string[1024];
328 va_start (argptr,fmt);
329 vsprintf (string, fmt,argptr);
330 va_end (argptr);
332 MSG_WriteByte (&host_client->message, svc_stufftext);
333 MSG_WriteString (&host_client->message, string);
337 =====================
338 SV_DropClient
340 Called when the player is getting totally kicked off the host
341 if (crash = true), don't bother sending signofs
342 =====================
344 void SV_DropClient (qboolean crash)
346 int saveSelf;
347 int i;
348 client_t *client;
350 if (!crash)
352 // send any final messages (don't check for errors)
353 if (NET_CanSendMessage (host_client->netconnection))
355 MSG_WriteByte (&host_client->message, svc_disconnect);
356 NET_SendMessage (host_client->netconnection, &host_client->message);
359 if (host_client->edict && host_client->spawned)
361 // call the prog function for removing a client
362 // this will set the body to a dead frame, among other things
363 saveSelf = pr_global_struct->self;
364 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
365 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
366 pr_global_struct->self = saveSelf;
369 Sys_Printf ("Client %s removed\n",host_client->name);
372 // break the net connection
373 NET_Close (host_client->netconnection);
374 host_client->netconnection = NULL;
376 // free the client (the body stays around)
377 host_client->active = false;
378 host_client->name[0] = 0;
379 host_client->old_frags = -999999;
380 net_activeconnections--;
382 // send notification to all clients
383 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
385 if (!client->active)
386 continue;
387 MSG_WriteByte (&client->message, svc_updatename);
388 MSG_WriteByte (&client->message, host_client - svs.clients);
389 MSG_WriteString (&client->message, "");
390 MSG_WriteByte (&client->message, svc_updatefrags);
391 MSG_WriteByte (&client->message, host_client - svs.clients);
392 MSG_WriteShort (&client->message, 0);
393 MSG_WriteByte (&client->message, svc_updatecolors);
394 MSG_WriteByte (&client->message, host_client - svs.clients);
395 MSG_WriteByte (&client->message, 0);
400 ==================
401 Host_ShutdownServer
403 This only happens at the end of a game, not between levels
404 ==================
406 void Host_ShutdownServer(qboolean crash)
408 int i;
409 int count;
410 sizebuf_t buf;
411 char message[4];
412 double start;
414 if (!sv.active)
415 return;
417 sv.active = false;
419 // stop all client sounds immediately
420 if (cls.state == ca_connected)
421 CL_Disconnect ();
423 // flush any pending messages - like the score!!!
424 start = Sys_FloatTime();
427 count = 0;
428 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
430 if (host_client->active && host_client->message.cursize)
432 if (NET_CanSendMessage (host_client->netconnection))
434 NET_SendMessage(host_client->netconnection, &host_client->message);
435 SZ_Clear (&host_client->message);
437 else
439 NET_GetMessage(host_client->netconnection);
440 count++;
444 if ((Sys_FloatTime() - start) > 3.0)
445 break;
447 while (count);
449 // make sure all the clients know we're disconnecting
450 buf.data = message;
451 buf.maxsize = 4;
452 buf.cursize = 0;
453 MSG_WriteByte(&buf, svc_disconnect);
454 count = NET_SendToAll(&buf, 5);
455 if (count)
456 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
458 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
459 if (host_client->active)
460 SV_DropClient(crash);
463 // clear structures
465 memset (&sv, 0, sizeof(sv));
466 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
471 ================
472 Host_ClearMemory
474 This clears all the memory used by both the client and server, but does
475 not reinitialize anything.
476 ================
478 void Host_ClearMemory (void)
480 Con_DPrintf ("Clearing memory\n");
481 D_FlushCaches ();
482 Mod_ClearAll ();
483 if (host_hunklevel)
484 Hunk_FreeToLowMark (host_hunklevel);
486 cls.signon = 0;
487 memset (&sv, 0, sizeof(sv));
488 memset (&cl, 0, sizeof(cl));
492 //============================================================================
496 ===================
497 Host_FilterTime
499 Returns false if the time is too short to run a frame
500 ===================
502 qboolean Host_FilterTime (float time)
504 realtime += time;
506 if (!cls.timedemo && realtime - oldrealtime < 1.0/72.0)
507 return false; // framerate is too high
509 host_frametime = realtime - oldrealtime;
510 oldrealtime = realtime;
512 if (host_framerate.value > 0)
513 host_frametime = host_framerate.value;
514 else
515 { // don't allow really long or short frames
516 if (host_frametime > 0.1)
517 host_frametime = 0.1;
518 if (host_frametime < 0.001)
519 host_frametime = 0.001;
522 return true;
527 ===================
528 Host_GetConsoleCommands
530 Add them exactly as if they had been typed at the console
531 ===================
533 void Host_GetConsoleCommands (void)
535 char *cmd;
537 while (1)
539 cmd = Sys_ConsoleInput ();
540 if (!cmd)
541 break;
542 Cbuf_AddText (cmd);
548 ==================
549 Host_ServerFrame
551 ==================
553 #ifdef FPS_20
555 void _Host_ServerFrame (void)
557 // run the world state
558 pr_global_struct->frametime = host_frametime;
560 // read client messages
561 SV_RunClients ();
563 // move things around and think
564 // always pause in single player if in console or menus
565 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
566 SV_Physics ();
569 void Host_ServerFrame (void)
571 float save_host_frametime;
572 float temp_host_frametime;
574 // run the world state
575 pr_global_struct->frametime = host_frametime;
577 // set the time and clear the general datagram
578 SV_ClearDatagram ();
580 // check for new clients
581 SV_CheckForNewClients ();
583 temp_host_frametime = save_host_frametime = host_frametime;
584 while(temp_host_frametime > (1.0/72.0))
586 if (temp_host_frametime > 0.05)
587 host_frametime = 0.05;
588 else
589 host_frametime = temp_host_frametime;
590 temp_host_frametime -= host_frametime;
591 _Host_ServerFrame ();
593 host_frametime = save_host_frametime;
595 // send all messages to the clients
596 SV_SendClientMessages ();
599 #else
601 void Host_ServerFrame (void)
603 // run the world state
604 pr_global_struct->frametime = host_frametime;
606 // set the time and clear the general datagram
607 SV_ClearDatagram ();
609 // check for new clients
610 SV_CheckForNewClients ();
612 // read client messages
613 SV_RunClients ();
615 // move things around and think
616 // always pause in single player if in console or menus
617 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
618 SV_Physics ();
620 // send all messages to the clients
621 SV_SendClientMessages ();
624 #endif
628 ==================
629 Host_Frame
631 Runs all active servers
632 ==================
634 void _Host_Frame (float time)
636 static double time1 = 0;
637 static double time2 = 0;
638 static double time3 = 0;
639 int pass1, pass2, pass3;
641 if (setjmp (host_abortserver) )
642 return; // something bad happened, or the server disconnected
644 // keep the random time dependent
645 rand ();
647 // decide the simulation time
648 if (!Host_FilterTime (time))
649 return; // don't run too fast, or packets will flood out
651 // get new key events
652 Sys_SendKeyEvents ();
654 // allow mice or other external controllers to add commands
655 IN_Commands ();
657 // process console commands
658 Cbuf_Execute ();
660 NET_Poll();
662 // if running the server locally, make intentions now
663 if (sv.active)
664 CL_SendCmd ();
666 //-------------------
668 // server operations
670 //-------------------
672 // check for commands typed to the host
673 Host_GetConsoleCommands ();
675 if (sv.active)
676 Host_ServerFrame ();
678 //-------------------
680 // client operations
682 //-------------------
684 // if running the server remotely, send intentions now after
685 // the incoming messages have been read
686 if (!sv.active)
687 CL_SendCmd ();
689 host_time += host_frametime;
691 // fetch results from server
692 if (cls.state == ca_connected)
694 CL_ReadFromServer ();
697 // update video
698 if (host_speeds.value)
699 time1 = Sys_FloatTime ();
701 SCR_UpdateScreen ();
703 if (host_speeds.value)
704 time2 = Sys_FloatTime ();
706 // update audio
707 if (cls.signon == SIGNONS)
709 S_Update (r_origin, vpn, vright, vup);
710 CL_DecayLights ();
712 else
713 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
715 CDAudio_Update();
717 if (host_speeds.value)
719 pass1 = (time1 - time3)*1000;
720 time3 = Sys_FloatTime ();
721 pass2 = (time2 - time1)*1000;
722 pass3 = (time3 - time2)*1000;
723 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
724 pass1+pass2+pass3, pass1, pass2, pass3);
727 host_framecount++;
730 void Host_Frame (float time)
732 double time1, time2;
733 static double timetotal;
734 static int timecount;
735 int i, c, m;
737 if (!serverprofile.value)
739 _Host_Frame (time);
740 return;
743 time1 = Sys_FloatTime ();
744 _Host_Frame (time);
745 time2 = Sys_FloatTime ();
747 timetotal += time2 - time1;
748 timecount++;
750 if (timecount < 1000)
751 return;
753 m = timetotal*1000/timecount;
754 timecount = 0;
755 timetotal = 0;
756 c = 0;
757 for (i=0 ; i<svs.maxclients ; i++)
759 if (svs.clients[i].active)
760 c++;
763 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
766 //============================================================================
769 extern int vcrFile;
770 #define VCR_SIGNATURE 0x56435231
771 // "VCR1"
773 void Host_InitVCR (quakeparms_t *parms)
775 int i, len, n;
776 char *p;
778 if (COM_CheckParm("-playback"))
780 if (com_argc != 2)
781 Sys_Error("No other parameters allowed with -playback\n");
783 Sys_FileOpenRead("quake.vcr", &vcrFile);
784 if (vcrFile == -1)
785 Sys_Error("playback file not found\n");
787 Sys_FileRead (vcrFile, &i, sizeof(int));
788 if (i != VCR_SIGNATURE)
789 Sys_Error("Invalid signature in vcr file\n");
791 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
792 com_argv = malloc(com_argc * sizeof(char *));
793 com_argv[0] = parms->argv[0];
794 for (i = 0; i < com_argc; i++)
796 Sys_FileRead (vcrFile, &len, sizeof(int));
797 p = malloc(len);
798 Sys_FileRead (vcrFile, p, len);
799 com_argv[i+1] = p;
801 com_argc++; /* add one for arg[0] */
802 parms->argc = com_argc;
803 parms->argv = com_argv;
806 if ( (n = COM_CheckParm("-record")) != 0)
808 vcrFile = Sys_FileOpenWrite("quake.vcr");
810 i = VCR_SIGNATURE;
811 Sys_FileWrite(vcrFile, &i, sizeof(int));
812 i = com_argc - 1;
813 Sys_FileWrite(vcrFile, &i, sizeof(int));
814 for (i = 1; i < com_argc; i++)
816 if (i == n)
818 len = 10;
819 Sys_FileWrite(vcrFile, &len, sizeof(int));
820 Sys_FileWrite(vcrFile, "-playback", len);
821 continue;
823 len = Q_strlen(com_argv[i]) + 1;
824 Sys_FileWrite(vcrFile, &len, sizeof(int));
825 Sys_FileWrite(vcrFile, com_argv[i], len);
832 ====================
833 Host_Init
834 ====================
836 void Host_Init (quakeparms_t *parms)
839 if (standard_quake)
840 minimum_memory = MINIMUM_MEMORY;
841 else
842 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
844 if (COM_CheckParm ("-minmemory"))
845 parms->memsize = minimum_memory;
847 host_parms = *parms;
849 if (parms->memsize < minimum_memory)
850 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
852 com_argc = parms->argc;
853 com_argv = parms->argv;
855 printf("memsize: %d\n", parms->memsize);
856 Memory_Init (parms->membase, parms->memsize);
858 printf("Memroy inited\n");
859 Cbuf_Init ();
860 printf("Cbuf inited\n");
861 Cmd_Init ();
862 printf("Cmd inited\n");
863 V_Init ();
864 printf("V inited\n");
865 Chase_Init ();
866 printf("Chase inited\n");
867 Host_InitVCR (parms);
868 printf("VCR inited\n");
869 COM_Init (parms->basedir);
870 printf("COM inited\n");
871 Host_InitLocal ();
872 printf("Host local inited\n");
873 W_LoadWadFile ("gfx.wad");
874 printf("wadfile loaded\n");
876 Key_Init ();
877 printf("keyboard inited\n");
878 Con_Init ();
879 printf("console inited\n");
880 M_Init ();
881 printf("M inited\n");
882 PR_Init ();
883 printf("PR inited\n");
884 Mod_Init ();
885 printf("Mod inited\n");
886 NET_Init ();
887 printf("Net inited\n");
888 SV_Init ();
889 printf("SV inited\n");
891 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
892 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
894 R_InitTextures (); // needed even for dedicated servers
896 if (cls.state != ca_dedicated)
898 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp");
899 if (!host_basepal)
900 Sys_Error ("Couldn't load gfx/palette.lmp");
901 host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp");
902 if (!host_colormap)
903 Sys_Error ("Couldn't load gfx/colormap.lmp");
905 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
906 IN_Init ();
907 #endif
908 VID_Init (host_basepal);
910 Draw_Init ();
911 SCR_Init ();
912 R_Init ();
913 #ifndef _WIN32
914 // on Win32, sound initialization has to come before video initialization, so we
915 // can put up a popup if the sound hardware is in use
916 printf("Initing sound\n");
917 S_Init ();
918 printf("Sound inited\n");
919 #else
921 #ifdef GLQUAKE
922 // FIXME: doesn't use the new one-window approach yet
923 S_Init ();
924 #endif
926 #endif // _WIN32
927 CDAudio_Init ();
928 Sbar_Init ();
929 CL_Init ();
930 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
931 IN_Init ();
932 #endif
935 Cbuf_InsertText ("exec quake.rc\n");
937 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
938 host_hunklevel = Hunk_LowMark ();
940 host_initialized = true;
942 Sys_Printf ("========Quake Initialized=========\n");
947 ===============
948 Host_Shutdown
950 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
951 to run quit through here before the final handoff to the sys code.
952 ===============
954 void Host_Shutdown(void)
956 static qboolean isdown = false;
958 if (isdown)
960 printf ("recursive shutdown\n");
961 return;
963 isdown = true;
965 // keep Con_Printf from trying to update the screen
966 scr_disabled_for_loading = true;
968 Host_WriteConfiguration ();
970 CDAudio_Shutdown ();
971 NET_Shutdown ();
972 S_Shutdown();
973 IN_Shutdown ();
975 if (cls.state != ca_dedicated)
977 VID_Shutdown();