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