]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
2c3bcd46ec3681d5c38fc497fe66c2019890c3ef
[xonotic/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.  
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // host.c -- coordinates spawning and killing of local servers
21
22 #include "quakedef.h"
23
24 /*
25
26 A server can allways be started, even if the system started out as a client
27 to a remote system.
28
29 A client can NOT be started if the system started as a dedicated server.
30
31 Memory is cleared / released when a server or client begins, not when they end.
32
33 */
34
35 quakeparms_t host_parms;
36
37 qboolean        host_initialized;               // true if into command execution
38
39 double          host_frametime;
40 double          host_time;
41 double          realtime;                               // without any filtering or bounding
42 double          oldrealtime;                    // last frame run
43 int                     host_framecount;
44
45 int                     host_hunklevel;
46
47 int                     minimum_memory;
48
49 client_t        *host_client;                   // current client
50
51 jmp_buf         host_abortserver;
52
53 byte            *host_basepal;
54 byte            *host_colormap;
55
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
59
60 cvar_t  sys_ticrate = {"sys_ticrate","0.05"};
61 cvar_t  serverprofile = {"serverprofile","0"};
62
63 cvar_t  fraglimit = {"fraglimit","0",false,true};
64 cvar_t  timelimit = {"timelimit","0",false,true};
65 cvar_t  teamplay = {"teamplay","0",false,true};
66
67 cvar_t  samelevel = {"samelevel","0"};
68 cvar_t  noexit = {"noexit","0",false,true};
69
70 cvar_t  developer = {"developer","0"};
71
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
75
76 cvar_t  pausable = {"pausable","1"};
77
78 cvar_t  temp1 = {"temp1","0"};
79
80
81 /*
82 ================
83 Host_EndGame
84 ================
85 */
86 void Host_EndGame (char *message, ...)
87 {
88         va_list         argptr;
89         char            string[1024];
90         
91         va_start (argptr,message);
92         vsprintf (string,message,argptr);
93         va_end (argptr);
94         Con_DPrintf ("Host_EndGame: %s\n",string);
95         
96         if (sv.active)
97                 Host_ShutdownServer (false);
98
99         if (cls.state == ca_dedicated)
100                 Sys_Error ("Host_EndGame: %s\n",string);        // dedicated servers exit
101         
102         if (cls.demonum != -1)
103                 CL_NextDemo ();
104         else
105                 CL_Disconnect ();
106
107         longjmp (host_abortserver, 1);
108 }
109
110 /*
111 ================
112 Host_Error
113
114 This shuts down both the client and server
115 ================
116 */
117 void Host_Error (char *error, ...)
118 {
119         va_list         argptr;
120         char            string[1024];
121         static  qboolean inerror = false;
122         
123         if (inerror)
124                 Sys_Error ("Host_Error: recursively entered");
125         inerror = true;
126         
127         SCR_EndLoadingPlaque ();                // reenable screen updates
128
129         va_start (argptr,error);
130         vsprintf (string,error,argptr);
131         va_end (argptr);
132         Con_Printf ("Host_Error: %s\n",string);
133         
134         if (sv.active)
135                 Host_ShutdownServer (false);
136
137         if (cls.state == ca_dedicated)
138                 Sys_Error ("Host_Error: %s\n",string);  // dedicated servers exit
139
140         CL_Disconnect ();
141         cls.demonum = -1;
142
143         inerror = false;
144
145         longjmp (host_abortserver, 1);
146 }
147
148 /*
149 ================
150 Host_FindMaxClients
151 ================
152 */
153 void    Host_FindMaxClients (void)
154 {
155         int             i;
156
157         svs.maxclients = 1;
158                 
159         i = COM_CheckParm ("-dedicated");
160         if (i)
161         {
162                 cls.state = ca_dedicated;
163                 if (i != (com_argc - 1))
164                 {
165                         svs.maxclients = atoi (com_argv[i+1]);
166                 }
167                 else
168                         svs.maxclients = 8;
169         }
170         else
171                 cls.state = ca_disconnected;
172
173         i = COM_CheckParm ("-listen");
174         if (i)
175         {
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]);
180                 else
181                         svs.maxclients = 8;
182         }
183         if (svs.maxclients < 1)
184                 svs.maxclients = 8;
185         else if (svs.maxclients > MAX_SCOREBOARD)
186                 svs.maxclients = MAX_SCOREBOARD;
187
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");
192
193         if (svs.maxclients > 1)
194                 Cvar_SetValue ("deathmatch", 1.0);
195         else
196                 Cvar_SetValue ("deathmatch", 0.0);
197 }
198
199
200 /*
201 =======================
202 Host_InitLocal
203 ======================
204 */
205 void Host_InitLocal (void)
206 {
207         Host_InitCommands ();
208         
209         Cvar_RegisterVariable (&host_framerate);
210         Cvar_RegisterVariable (&host_speeds);
211         Cvar_RegisterVariable (&slowmo);
212
213         Cvar_RegisterVariable (&sys_ticrate);
214         Cvar_RegisterVariable (&serverprofile);
215
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);
225
226         Cvar_RegisterVariable (&pausable);
227
228         Cvar_RegisterVariable (&temp1);
229
230         Host_FindMaxClients ();
231         
232         host_time = 1.0;                // so a think at time 0 won't get called
233 }
234
235
236 /*
237 ===============
238 Host_WriteConfiguration
239
240 Writes key bindings and archived cvars to config.cfg
241 ===============
242 */
243 void Host_WriteConfiguration (void)
244 {
245         FILE    *f;
246
247 // dedicated servers initialize the host but don't parse and set the
248 // config.cfg cvars
249         if (host_initialized & !isDedicated)
250         {
251                 f = fopen (va("%s/config.cfg",com_gamedir), "w");
252                 if (!f)
253                 {
254                         Con_Printf ("Couldn't write config.cfg.\n");
255                         return;
256                 }
257                 
258                 Key_WriteBindings (f);
259                 Cvar_WriteVariables (f);
260
261                 fclose (f);
262         }
263 }
264
265
266 /*
267 =================
268 SV_ClientPrintf
269
270 Sends text across to be displayed 
271 FIXME: make this just a stuffed echo?
272 =================
273 */
274 void SV_ClientPrintf (char *fmt, ...)
275 {
276         va_list         argptr;
277         char            string[1024];
278         
279         va_start (argptr,fmt);
280         vsprintf (string, fmt,argptr);
281         va_end (argptr);
282         
283         MSG_WriteByte (&host_client->message, svc_print);
284         MSG_WriteString (&host_client->message, string);
285 }
286
287 /*
288 =================
289 SV_BroadcastPrintf
290
291 Sends text to all active clients
292 =================
293 */
294 void SV_BroadcastPrintf (char *fmt, ...)
295 {
296         va_list         argptr;
297         char            string[1024];
298         int                     i;
299         
300         va_start (argptr,fmt);
301         vsprintf (string, fmt,argptr);
302         va_end (argptr);
303         
304         for (i=0 ; i<svs.maxclients ; i++)
305                 if (svs.clients[i].active && svs.clients[i].spawned)
306                 {
307                         MSG_WriteByte (&svs.clients[i].message, svc_print);
308                         MSG_WriteString (&svs.clients[i].message, string);
309                 }
310 }
311
312 /*
313 =================
314 Host_ClientCommands
315
316 Send text over to the client to be executed
317 =================
318 */
319 void Host_ClientCommands (char *fmt, ...)
320 {
321         va_list         argptr;
322         char            string[1024];
323         
324         va_start (argptr,fmt);
325         vsprintf (string, fmt,argptr);
326         va_end (argptr);
327         
328         MSG_WriteByte (&host_client->message, svc_stufftext);
329         MSG_WriteString (&host_client->message, string);
330 }
331
332 /*
333 =====================
334 SV_DropClient
335
336 Called when the player is getting totally kicked off the host
337 if (crash = true), don't bother sending signofs
338 =====================
339 */
340 void SV_DropClient (qboolean crash)
341 {
342         int             saveSelf;
343         int             i;
344         client_t *client;
345
346         if (!crash)
347         {
348                 // send any final messages (don't check for errors)
349                 if (NET_CanSendMessage (host_client->netconnection))
350                 {
351                         MSG_WriteByte (&host_client->message, svc_disconnect);
352                         NET_SendMessage (host_client->netconnection, &host_client->message);
353                 }
354         
355                 if (host_client->edict && host_client->spawned)
356                 {
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;
363                 }
364
365                 Sys_Printf ("Client %s removed\n",host_client->name);
366         }
367
368 // break the net connection
369         NET_Close (host_client->netconnection);
370         host_client->netconnection = NULL;
371
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--;
377
378 // send notification to all clients
379         for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
380         {
381                 if (!client->active)
382                         continue;
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);
392         }
393 }
394
395 /*
396 ==================
397 Host_ShutdownServer
398
399 This only happens at the end of a game, not between levels
400 ==================
401 */
402 void Host_ShutdownServer(qboolean crash)
403 {
404         int             i;
405         int             count;
406         sizebuf_t       buf;
407         char            message[4];
408         double  start;
409
410         if (!sv.active)
411                 return;
412
413         sv.active = false;
414
415 // stop all client sounds immediately
416         if (cls.state == ca_connected)
417                 CL_Disconnect ();
418
419 // flush any pending messages - like the score!!!
420         start = Sys_FloatTime();
421         do
422         {
423                 count = 0;
424                 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
425                 {
426                         if (host_client->active && host_client->message.cursize)
427                         {
428                                 if (NET_CanSendMessage (host_client->netconnection))
429                                 {
430                                         NET_SendMessage(host_client->netconnection, &host_client->message);
431                                         SZ_Clear (&host_client->message);
432                                 }
433                                 else
434                                 {
435                                         NET_GetMessage(host_client->netconnection);
436                                         count++;
437                                 }
438                         }
439                 }
440                 if ((Sys_FloatTime() - start) > 3.0)
441                         break;
442         }
443         while (count);
444
445 // make sure all the clients know we're disconnecting
446         buf.data = message;
447         buf.maxsize = 4;
448         buf.cursize = 0;
449         MSG_WriteByte(&buf, svc_disconnect);
450         count = NET_SendToAll(&buf, 5);
451         if (count)
452                 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
453
454         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
455                 if (host_client->active)
456                         SV_DropClient(crash);
457
458 //
459 // clear structures
460 //
461         memset (&sv, 0, sizeof(sv));
462         memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
463 }
464
465
466 /*
467 ================
468 Host_ClearMemory
469
470 This clears all the memory used by both the client and server, but does
471 not reinitialize anything.
472 ================
473 */
474 void Host_ClearMemory (void)
475 {
476         Con_DPrintf ("Clearing memory\n");
477         D_FlushCaches ();
478         Mod_ClearAll ();
479         if (host_hunklevel)
480                 Hunk_FreeToLowMark (host_hunklevel);
481
482         cls.signon = 0;
483         memset (&sv, 0, sizeof(sv));
484         memset (&cl, 0, sizeof(cl));
485 }
486
487
488 //============================================================================
489
490 /*
491 ===================
492 Host_FilterTime
493
494 Returns false if the time is too short to run a frame
495 ===================
496 */
497 qboolean Host_FilterTime (float time)
498 {
499         realtime += time;
500
501 //      if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
502 //              return false;           // framerate is too high
503
504         host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
505         oldrealtime = realtime;
506
507         if (host_framerate.value > 0)
508                 host_frametime = host_framerate.value;
509         else
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;
515         }
516         
517         return true;
518 }
519
520
521 /*
522 ===================
523 Host_GetConsoleCommands
524
525 Add them exactly as if they had been typed at the console
526 ===================
527 */
528 void Host_GetConsoleCommands (void)
529 {
530         char    *cmd;
531
532         while (1)
533         {
534                 cmd = Sys_ConsoleInput ();
535                 if (!cmd)
536                         break;
537                 Cbuf_AddText (cmd);
538         }
539 }
540
541
542 /*
543 ==================
544 Host_ServerFrame
545
546 ==================
547 */
548 #ifdef FPS_20
549
550 void _Host_ServerFrame (void)
551 {
552 // run the world state  
553         pr_global_struct->frametime = host_frametime;
554
555 // read client messages
556         SV_RunClients ();
557         
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) )
561                 SV_Physics ();
562 }
563
564 void Host_ServerFrame (void)
565 {
566         float   save_host_frametime;
567         float   temp_host_frametime;
568         static float    host_serverframe_timevalue;
569
570 // run the world state  
571         pr_global_struct->frametime = host_frametime;
572
573 // set the time and clear the general datagram
574         SV_ClearDatagram ();
575                 
576 // check for new clients
577         SV_CheckForNewClients ();
578
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
583         // (sliding around)
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)
589         {
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 ();
596         }
597         host_frametime = save_host_frametime;
598
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
602         /*
603 // wait until enough time has built up when the framerate exceeds sys_ticrate
604         if (host_serverframe_timevalue >= sys_ticrate.value)
605         //{
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 ();
610         }
611         */
612 }
613
614 #else
615
616 double frametimetotal = 0, lastservertime = 0;
617 void Host_ServerFrame (void)
618 {
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))
622                 return;
623 // run the world state
624         pr_global_struct->frametime = frametimetotal;
625         frametimetotal = 0;
626 //      pr_global_struct->frametime = host_frametime;
627
628 // set the time and clear the general datagram
629         SV_ClearDatagram ();
630         
631 // check for new clients
632         SV_CheckForNewClients ();
633
634 // read client messages
635         SV_RunClients ();
636         
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) )
640                 SV_Physics ();
641
642 // send all messages to the clients
643         SV_SendClientMessages ();
644 }
645
646 #endif
647
648
649 /*
650 ==================
651 Host_Frame
652
653 Runs all active servers
654 ==================
655 */
656 void _Host_Frame (float time)
657 {
658         static double           time1 = 0;
659         static double           time2 = 0;
660         static double           time3 = 0;
661         int                     pass1, pass2, pass3;
662
663         if (setjmp (host_abortserver) )
664                 return;                 // something bad happened, or the server disconnected
665
666 // keep the random time dependent
667         rand ();
668         
669 // decide the simulation time
670         if (!Host_FilterTime (time))
671                 return;                 // don't run too fast, or packets will flood out
672                 
673 // get new key events
674         Sys_SendKeyEvents ();
675
676 // allow mice or other external controllers to add commands
677         IN_Commands ();
678
679 // process console commands
680         Cbuf_Execute ();
681
682         NET_Poll();
683
684 // if running the server locally, make intentions now
685         if (sv.active)
686                 CL_SendCmd ();
687         
688 //-------------------
689 //
690 // server operations
691 //
692 //-------------------
693
694 // check for commands typed to the host
695         Host_GetConsoleCommands ();
696         
697         if (sv.active)
698                 Host_ServerFrame ();
699
700 //-------------------
701 //
702 // client operations
703 //
704 //-------------------
705
706 // if running the server remotely, send intentions now after
707 // the incoming messages have been read
708         if (!sv.active)
709                 CL_SendCmd ();
710
711         host_time += host_frametime;
712
713 // fetch results from server
714         if (cls.state == ca_connected)
715         {
716                 CL_ReadFromServer ();
717         }
718
719 // update video
720         if (host_speeds.value)
721                 time1 = Sys_FloatTime ();
722                 
723         SCR_UpdateScreen ();
724
725         if (host_speeds.value)
726                 time2 = Sys_FloatTime ();
727                 
728 // update audio
729         if (cls.signon == SIGNONS)
730         {
731                 S_Update (r_origin, vpn, vright, vup);
732                 CL_DecayLights ();
733         }
734         else
735                 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
736         
737         CDAudio_Update();
738
739         if (host_speeds.value)
740         {
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);
747         }
748         
749         host_framecount++;
750 }
751
752 void Host_Frame (float time)
753 {
754         double  time1, time2;
755         static double   timetotal;
756         static int              timecount;
757         int             i, c, m;
758
759         if (!serverprofile.value)
760         {
761                 _Host_Frame (time);
762                 return;
763         }
764         
765         time1 = Sys_FloatTime ();
766         _Host_Frame (time);
767         time2 = Sys_FloatTime ();       
768         
769         timetotal += time2 - time1;
770         timecount++;
771         
772         if (timecount < 1000)
773                 return;
774
775         m = timetotal*1000/timecount;
776         timecount = 0;
777         timetotal = 0;
778         c = 0;
779         for (i=0 ; i<svs.maxclients ; i++)
780         {
781                 if (svs.clients[i].active)
782                         c++;
783         }
784
785         Con_Printf ("serverprofile: %2i clients %2i msec\n",  c,  m);
786 }
787
788 //============================================================================
789
790
791 extern int vcrFile;
792 #define VCR_SIGNATURE   0x56435231
793 // "VCR1"
794
795 void Host_InitVCR (quakeparms_t *parms)
796 {
797         int             i, len, n;
798         char    *p;
799         
800         if (COM_CheckParm("-playback"))
801         {
802                 if (com_argc != 2)
803                         Sys_Error("No other parameters allowed with -playback\n");
804
805                 Sys_FileOpenRead("quake.vcr", &vcrFile);
806                 if (vcrFile == -1)
807                         Sys_Error("playback file not found\n");
808
809                 Sys_FileRead (vcrFile, &i, sizeof(int));
810                 if (i != VCR_SIGNATURE)
811                         Sys_Error("Invalid signature in vcr file\n");
812
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++)
817                 {
818                         Sys_FileRead (vcrFile, &len, sizeof(int));
819                         p = malloc(len);
820                         Sys_FileRead (vcrFile, p, len);
821                         com_argv[i+1] = p;
822                 }
823                 com_argc++; /* add one for arg[0] */
824                 parms->argc = com_argc;
825                 parms->argv = com_argv;
826         }
827
828         if ( (n = COM_CheckParm("-record")) != 0)
829         {
830                 vcrFile = Sys_FileOpenWrite("quake.vcr");
831
832                 i = VCR_SIGNATURE;
833                 Sys_FileWrite(vcrFile, &i, sizeof(int));
834                 i = com_argc - 1;
835                 Sys_FileWrite(vcrFile, &i, sizeof(int));
836                 for (i = 1; i < com_argc; i++)
837                 {
838                         if (i == n)
839                         {
840                                 len = 10;
841                                 Sys_FileWrite(vcrFile, &len, sizeof(int));
842                                 Sys_FileWrite(vcrFile, "-playback", len);
843                                 continue;
844                         }
845                         len = strlen(com_argv[i]) + 1;
846                         Sys_FileWrite(vcrFile, &len, sizeof(int));
847                         Sys_FileWrite(vcrFile, com_argv[i], len);
848                 }
849         }
850         
851 }
852
853 /*
854 ====================
855 Host_Init
856 ====================
857 */
858 void Host_Init (quakeparms_t *parms)
859 {
860
861         if (standard_quake)
862                 minimum_memory = MINIMUM_MEMORY;
863         else
864                 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
865
866         if (COM_CheckParm ("-minmemory"))
867                 parms->memsize = minimum_memory;
868
869         host_parms = *parms;
870
871         if (parms->memsize < minimum_memory)
872                 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
873
874         com_argc = parms->argc;
875         com_argv = parms->argv;
876
877         Memory_Init (parms->membase, parms->memsize);
878         Cbuf_Init ();
879         Cmd_Init ();    
880         V_Init ();
881         Chase_Init ();
882         Host_InitVCR (parms);
883         COM_Init (parms->basedir);
884         Host_InitLocal ();
885         W_LoadWadFile ("gfx.wad");
886         Key_Init ();
887         Con_Init ();    
888         M_Init ();      
889         PR_Init ();
890         Mod_Init ();
891         NET_Init ();
892         SV_Init ();
893
894         Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
895         Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
896         
897         R_InitTextures ();              // needed even for dedicated servers
898  
899         if (cls.state != ca_dedicated)
900         {
901                 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
902                 if (!host_basepal)
903                         Sys_Error ("Couldn't load gfx/palette.lmp");
904                 host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
905                 if (!host_colormap)
906                         Sys_Error ("Couldn't load gfx/colormap.lmp");
907
908 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
909                 IN_Init ();
910 #endif
911                 VID_Init (host_basepal);
912
913                 Draw_Init ();
914                 SCR_Init ();
915                 R_Init ();
916 #ifndef _WIN32
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
919                 S_Init ();
920 #else
921
922         // FIXME: doesn't use the new one-window approach yet
923                 S_Init ();
924
925 #endif  // _WIN32
926                 CDAudio_Init ();
927                 Sbar_Init ();
928                 CL_Init ();
929 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
930                 IN_Init ();
931 #endif
932         }
933
934         Cbuf_InsertText ("exec quake.rc\n");
935
936         Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
937         host_hunklevel = Hunk_LowMark ();
938
939         host_initialized = true;
940         
941         Sys_Printf ("========Quake Initialized=========\n");    
942 }
943
944
945 /*
946 ===============
947 Host_Shutdown
948
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.
951 ===============
952 */
953 void Host_Shutdown(void)
954 {
955         static qboolean isdown = false;
956         
957         if (isdown)
958         {
959                 printf ("recursive shutdown\n");
960                 return;
961         }
962         isdown = true;
963
964 // keep Con_Printf from trying to update the screen
965         scr_disabled_for_loading = true;
966
967         Host_WriteConfiguration (); 
968
969         CDAudio_Shutdown ();
970         NET_Shutdown ();
971         S_Shutdown();
972         IN_Shutdown ();
973
974         if (cls.state != ca_dedicated)
975         {
976                 VID_Shutdown();
977         }
978 }
979