]> icculus.org git repositories - btb/d2x.git/blob - main/inferno.c
This commit was generated by cvs2svn to compensate for changes in r5,
[btb/d2x.git] / main / inferno.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.  
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 char copyright[] = "DESCENT II  COPYRIGHT (C) 1994-1996 PARALLAX SOFTWARE CORPORATION";
15
16 #include <conf.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #include "pstypes.h"
22 #include "strutil.h"
23 #include "console.h"
24 #include "pa_enabl.h"       //$$POLY_ACC
25 #include "gr.h"
26 #include "fix.h"
27 #include "vecmat.h"
28 #include "mono.h"
29 #include "key.h"
30 #include "timer.h"
31 #include "3d.h"
32 #include "bm.h"
33 #include "inferno.h"
34 #include "error.h"
35 #include "game.h"
36 #include "segment.h"            //for Side_to_verts
37 #include "u_mem.h"
38 #include "segpoint.h"
39 #include "screens.h"
40 #include "texmap.h"
41 #include "texmerge.h"
42 #include "menu.h"
43 #include "wall.h"
44 #include "polyobj.h"
45 #include "effects.h"
46 #include "digi.h"
47 #include "iff.h"
48 #include "pcx.h"
49 #include "palette.h"
50 #include "args.h"
51 #include "sounds.h"
52 #include "titles.h"
53 #include "player.h"
54 #include "text.h"
55 #include "ipx.h"
56 #include "newdemo.h"
57 #include "network.h"
58 #include "modem.h"
59 #include "gamefont.h"
60 #include "kconfig.h"
61 #include "mouse.h"
62 #include "joy.h"
63 #include "newmenu.h"
64 #include "desc_id.h"
65 #include "config.h"
66 #include "joydefs.h"
67 #include "multi.h"
68 #include "songs.h"
69 #include "cfile.h"
70 #include "gameseq.h"
71 #include "gamepal.h"
72 #include "mission.h"
73 #include "movie.h"
74 #include "compbit.h"
75
76 // #  include "3dfx_des.h"
77
78 #if defined(POLY_ACC)
79 #include "poly_acc.h"
80 extern int Current_display_mode;        //$$ there's got to be a better way than hacking this.
81 #endif
82
83 #ifdef EDITOR
84 #include "editor\editor.h"
85 #include "editor\kdefs.h"
86 #include "ui.h"
87 #endif
88
89 #include "vers_id.h"
90
91 void mem_init(void);
92 void arch_init(void);
93 void arch_init_start(void);
94
95 //Current version number
96
97 ubyte Version_major = 1;                //FULL VERSION
98 ubyte Version_minor = 2;
99
100 static const char desc_id_checksum_str[] = DESC_ID_CHKSUM_TAG "0000";   //4-byte checksum
101 char desc_id_exit_num = 0;
102
103 int Function_mode=FMODE_MENU;           //game or editor?
104 int Screen_mode=-1;                                     //game screen or editor screen?
105
106 //--unused-- grs_bitmap Inferno_bitmap_title;
107
108 int WVIDEO_running=0;           //debugger can set to 1 if running
109
110 #ifdef EDITOR
111 int Inferno_is_800x600_available = 0;
112 #endif
113
114 //--unused-- int Cyberman_installed=0;                  // SWIFT device present
115 ubyte CybermouseActive=0;
116
117 int __far descent_critical_error_handler( unsigned deverr, unsigned errcode, unsigned __far * devhdr );
118
119 void check_joystick_calibration(void);
120
121
122 //--------------------------------------------------------------------------
123
124 extern int piggy_low_memory;
125
126
127 int descent_critical_error = 0;
128 unsigned descent_critical_deverror = 0;
129 unsigned descent_critical_errcode = 0;
130
131 extern int Network_allow_socket_changes;
132
133 extern void vfx_set_palette_sub(ubyte *);
134
135 extern int VR_low_res;
136
137 extern int Config_vr_type;
138 extern int Config_vr_resolution;
139 extern int Config_vr_tracking;
140 int grd_fades_disabled=1;
141
142 #define LINE_LEN        100
143
144 void do_joystick_init()
145 {
146  
147
148         if (!args_find( "-nojoystick" ))        {
149                 con_printf(CON_VERBOSE, "\n%s", TXT_VERBOSE_6);
150                 joy_init();
151                 if ( args_find( "-joyslow" ))   {
152                         con_printf(CON_VERBOSE, "\n%s", TXT_VERBOSE_7);
153                         joy_set_slow_reading(JOY_SLOW_READINGS);
154                 }
155                 if ( args_find( "-joypolled" )) {
156                         con_printf(CON_VERBOSE, "\n%s", TXT_VERBOSE_8);
157                         joy_set_slow_reading(JOY_POLLED_READINGS);
158                 }
159                 if ( args_find( "-joybios" ))   {
160                         con_printf(CON_VERBOSE, "\n%s", TXT_VERBOSE_9);
161                         joy_set_slow_reading(JOY_BIOS_READINGS);
162                 }
163
164         //      Added from Descent v1.5 by John.  Adapted by Samir.
165         } else {
166                 con_printf(CON_VERBOSE, "\n%s", TXT_VERBOSE_10);
167         }
168 }
169
170 //set this to force game to run in low res
171 int disable_high_res=0;
172
173 void do_register_player(ubyte *title_pal)
174 {
175         Players[Player_num].callsign[0] = '\0';
176
177         if (!Auto_demo)         {
178
179                 key_flush();
180
181                 //now, before we bring up the register player menu, we need to 
182                 //do some stuff to make sure the palette is ok.  First, we need to
183                 //get our current palette into the 2d's array, so the remapping will
184                 //work.  Second, we need to remap the fonts.  Third, we need to fill 
185                 //in part of the fade tables so the darkening of the menu edges works
186
187                 memcpy(gr_palette,title_pal,sizeof(gr_palette));
188                 remap_fonts_and_menus(1);
189                 RegisterPlayer();               //get player's name
190         }
191
192 }
193
194 #ifdef NETWORK
195 void do_network_init()
196 {
197         if (!args_find( "-nonetwork" )) {
198                 int socket=0, showaddress=0, t;
199                 int ipx_error;
200
201                 con_printf(CON_VERBOSE, "\n%s ", TXT_INITIALIZING_NETWORK);
202                 if ((t=args_find("-socket")))
203                         socket = atoi( Args[t+1] );
204                 //@@if ( args_find("-showaddress") ) showaddress=1;
205                 if ((ipx_error=ipx_init(IPX_DEFAULT_SOCKET+socket,showaddress))==0)     {
206                         con_printf(CON_VERBOSE, "%s %d.\n", TXT_IPX_CHANNEL, socket );
207                         Network_active = 1;
208                 } else {
209                         switch( ipx_error )     {
210                         case 3:         con_printf(CON_VERBOSE, "%s\n", TXT_NO_NETWORK); break;
211                         case -2: con_printf(CON_VERBOSE, "%s 0x%x.\n", TXT_SOCKET_ERROR, IPX_DEFAULT_SOCKET+socket); break;
212                         case -4: con_printf(CON_VERBOSE, "%s\n", TXT_MEMORY_IPX ); break;
213                         default:
214                                 con_printf(CON_VERBOSE, "%s %d", TXT_ERROR_IPX, ipx_error );
215                         }
216                         con_printf(CON_VERBOSE, "%s\n",TXT_NETWORK_DISABLED);
217                         Network_active = 0;             // Assume no network
218                 }
219                 ipx_read_user_file( "descent.usr" );
220                 ipx_read_network_file( "descent.net" );
221                 //@@if ( args_find( "-dynamicsockets" ))
222                 //@@    Network_allow_socket_changes = 1;
223                 //@@else
224                 //@@    Network_allow_socket_changes = 0;
225         } else {
226                 con_printf(CON_VERBOSE, "%s\n", TXT_NETWORK_DISABLED);
227                 Network_active = 0;             // Assume no network
228         }
229 }
230 #endif
231
232 #ifdef SHAREARE
233 #define PROGNAME "d2demo"
234 #else
235 #define PROGNAME "d2"
236 #endif
237
238 extern char Language[];
239
240 //can we do highres menus?
241 extern int MenuHiresAvailable;
242
243 #ifdef D2_OEM
244 int intro_played = 0;
245 #endif
246
247 int open_movie_file(char *filename,int must_have);
248
249 #if defined(POLY_ACC)
250 #define MENU_HIRES_MODE SM_640x480x15xPA
251 #else
252 #define MENU_HIRES_MODE SM(640,480)
253 #endif
254
255 //      DESCENT II by Parallax Software
256 //              Descent Main
257
258 //extern ubyte gr_current_pal[];
259
260 #ifdef  EDITOR
261 int     Auto_exit = 0;
262 char    Auto_file[128] = "";
263 #endif
264
265 int main(int argc,char **argv)
266 {
267         int i,t;
268         ubyte title_pal[768];
269
270         
271         con_init();  // Initialise the console
272         mem_init();
273
274         error_init(NULL, NULL);
275
276         args_init( argc,argv );
277
278         if ( args_find( "-debug") )
279         {
280                 con_threshold.value = (float)2;
281
282         } else
283                 if ( args_find( "-verbose" ) ) 
284                 {
285                         con_threshold.value = (float)1;
286                 }
287
288         arch_init_start();
289
290         arch_init();
291
292         //tell cfile about our counter
293         cfile_set_critical_error_counter_ptr(&descent_critical_error);
294
295         #ifdef SHAREWARE
296                 cfile_init("d2demo.hog");                       //specify name of hogfile
297         #else
298         #define HOGNAME "descent2.hog"
299         if (! cfile_init(HOGNAME)) {            //didn't find HOG.  Check on CD
300                 #ifdef RELEASE
301                         Error("Could not find required file <%s>",HOGNAME);
302                 #endif
303         }
304         #endif
305         
306         load_text();
307
308         //print out the banner title
309         con_printf(CON_NORMAL, "\nDESCENT 2 %s v%d.%d",VERSION_TYPE,Version_major,Version_minor);
310         con_printf(CON_NORMAL, "  %s %s\n", __DATE__,__TIME__);
311         con_printf(CON_NORMAL, "%s\n%s\n",TXT_COPYRIGHT,TXT_TRADEMARK); 
312         con_printf(CON_NORMAL, "This is a MODIFIED version of Descent 2. Copyright (c) 1999 Peter Hawkins\n");
313
314
315         if (args_find( "-?" ) || args_find( "-help" ) || args_find( "?" ) ) {
316                 //print_commandline_help();
317                 set_exit_message("");
318                 return(0);
319         }
320
321         con_printf(CON_NORMAL, "\n");
322         con_printf(CON_NORMAL, TXT_HELP, PROGNAME);             //help message has %s for program name
323         con_printf(CON_NORMAL, "\n");
324
325         con_printf(CON_VERBOSE, "\n%s...", "Checking for Descent 2 CD-ROM");
326
327         if ( args_find( "-autodemo" ))
328                 Auto_demo = 1;
329
330         if ( args_find( "-noscreens" ) )
331                 Skip_briefing_screens = 1;
332
333         Lighting_on = 1;
334
335 //      if (init_graphics()) return 1;
336
337         #ifdef EDITOR
338         if (!Inferno_is_800x600_available)      {
339                 con_printf(CON_NORMAL "The editor will not be available, press any key to start game...\n" );
340                 Function_mode = FMODE_MENU;
341         }
342         #endif
343
344         if (!WVIDEO_running)
345                 con_printf(CON_DEBUG,"WVIDEO_running = %d\n",WVIDEO_running);
346
347         con_printf (CON_VERBOSE, "%s", TXT_VERBOSE_1);
348         ReadConfigFile();
349
350 #ifdef NETWORK
351         do_network_init();
352 #endif
353
354 #if defined(POLY_ACC)
355     Current_display_mode = -1;
356     game_init_render_buffers(SM_640x480x15xPA, 640, 480, VR_NONE, VRF_COMPATIBLE_MENUS+VRF_ALLOW_COCKPIT );
357 #else
358
359         if (!VR_offscreen_buffer)       //if hasn't been initialied (by headset init)
360                 set_display_mode(0);            //..then set default display mode
361 #endif
362
363         i = args_find( "-xcontrol" );
364         if ( i > 0 )    {
365                 kconfig_init_external_controls( strtol(Args[i+1], NULL, 0), strtol(Args[i+2], NULL, 0) );
366         }
367
368         con_printf(CON_VERBOSE, "\n%s\n\n", TXT_INITIALIZING_GRAPHICS);
369         if (args_find("-nofade"))
370                 grd_fades_disabled=1;
371         
372         if ((t=gr_init())!=0)                           //doesn't do much
373                 Error(TXT_CANT_INIT_GFX,t);
374
375    #ifdef _3DFX
376    _3dfx_Init();
377    #endif
378
379         // Load the palette stuff. Returns non-zero if error.
380         con_printf(CON_DEBUG, "\nInitializing palette system..." );
381    gr_use_palette_table(DEFAULT_PALETTE );
382
383         con_printf(CON_DEBUG, "\nInitializing font system..." );
384         gamefont_init();        // must load after palette data loaded.
385
386         //determine whether we're using high-res menus & movies
387 #if !defined(POLY_ACC)
388         if (args_find("-nohires") || args_find("-nohighres") || (gr_check_mode(MENU_HIRES_MODE) != 0) || disable_high_res)
389                 MovieHires = MenuHires = MenuHiresAvailable = 0;
390         else
391 #endif
392                 //NOTE LINK TO ABOVE!
393                 MenuHires = MenuHiresAvailable = 1;
394
395         con_printf( CON_DEBUG, "\nInitializing movie libraries..." );
396         init_movies();          //init movie libraries
397
398         con_printf(CON_VERBOSE, "\nGoing into graphics mode...\n");
399 #if defined(POLY_ACC)
400         gr_set_mode(SM_640x480x15xPA);
401 #else
402         gr_set_mode(MovieHires?SM(640,480):SM(320,200));
403 #endif
404
405         #ifndef RELEASE
406         if ( args_find( "-notitles" ) ) 
407                 songs_play_song( SONG_TITLE, 1);
408         else
409         #endif
410         {       //NOTE LINK TO ABOVE!
411                 int played=MOVIE_NOT_PLAYED;    //default is not played
412                 int song_playing = 0;
413
414                 #ifdef D2_OEM
415                 #define MOVIE_REQUIRED 0
416                 #else
417                 #define MOVIE_REQUIRED 1
418                 #endif
419
420 #ifdef D2_OEM   //$$POLY_ACC, jay.
421                 {       //show bundler screens
422                         FILE *tfile;
423                         char filename[FILENAME_LEN];
424
425                         played=MOVIE_NOT_PLAYED;        //default is not played
426
427             played = PlayMovie("pre_i.mve",0);
428
429                         if (!played) {
430                 strcpy(filename,MenuHires?"pre_i1b.pcx":"pre_i1.pcx");
431
432                                 while ((tfile=fopen(filename,"rb")) != NULL) {
433                                         fclose(tfile);
434                                         show_title_screen( filename, 1, 0 );
435                     filename[5]++;
436                                 }
437                         }
438                 }
439 #endif
440
441                 #ifndef SHAREWARE
442                         init_subtitles("intro.tex");
443                         played = PlayMovie("intro.mve",MOVIE_REQUIRED);
444                         close_subtitles();
445                 #endif
446
447                 #ifdef D2_OEM
448                 if (played != MOVIE_NOT_PLAYED)
449                         intro_played = 1;
450                 else {                                          //didn't get intro movie, try titles
451
452                         played = PlayMovie("titles.mve",MOVIE_REQUIRED);
453
454                         if (played == MOVIE_NOT_PLAYED) {
455 #if defined(POLY_ACC)
456             gr_set_mode(SM_640x480x15xPA);
457 #else
458                                 gr_set_mode(MenuHires?SM_640x480V:SM_320x200C);
459 #endif
460                                 con_printf( CON_DEBUG, "\nPlaying title song..." );
461                                 songs_play_song( SONG_TITLE, 1);
462                                 song_playing = 1;
463                                 con_printf( CON_DEBUG, "\nShowing logo screens..." );
464                                 show_title_screen( MenuHires?"iplogo1b.pcx":"iplogo1.pcx", 1, 1 );
465                                 show_title_screen( MenuHires?"logob.pcx":"logo.pcx", 1, 1 );
466                         }
467                 }
468
469                 {       //show bundler movie or screens
470
471                         FILE *tfile;
472                         char filename[FILENAME_LEN];
473                         int movie_handle;
474
475                         played=MOVIE_NOT_PLAYED;        //default is not played
476
477                         //check if OEM movie exists, so we don't stop the music if it doesn't
478                         movie_handle = open_movie_file("oem.mve",0);
479                         if (movie_handle != -1) {
480                                 close(movie_handle);
481                                 played = PlayMovie("oem.mve",0);
482                                 song_playing = 0;               //movie will kill sound
483                         }
484
485                         if (!played) {
486                                 strcpy(filename,MenuHires?"oem1b.pcx":"oem1.pcx");
487
488                                 while ((tfile=fopen(filename,"rb")) != NULL) {
489                                         fclose(tfile);
490                                         show_title_screen( filename, 1, 0 );
491                                         filename[3]++;
492                                 }
493                         }
494                 }
495                 #endif
496
497                 if (!song_playing)
498                         songs_play_song( SONG_TITLE, 1);
499                         
500         }
501
502    PA_DFX (pa_splash());
503
504         con_printf( CON_DEBUG, "\nShowing loading screen..." );
505         {
506                 //grs_bitmap title_bm;
507                 int pcx_error;
508                 char filename[14];
509
510                 #ifdef SHAREWARE
511                 strcpy(filename, "descentd.pcx");
512                 #else
513                 #ifdef D2_OEM
514                 strcpy(filename, MenuHires?"descntob.pcx":"descento.pcx");
515                 #else
516                 strcpy(filename, MenuHires?"descentb.pcx":"descent.pcx");
517                 #endif
518                 #endif
519
520 #if defined(POLY_ACC)
521                 gr_set_mode(SM_640x480x15xPA);
522 #else
523                 gr_set_mode(MenuHires?SM(640,480):SM(320,200));
524 #endif
525
526                 FontHires = MenuHires;
527
528                 if ((pcx_error=pcx_read_bitmap( filename, &grd_curcanv->cv_bitmap, grd_curcanv->cv_bitmap.bm_type, title_pal ))==PCX_ERROR_NONE)        {
529                         //vfx_set_palette_sub( title_pal );
530                         gr_palette_clear();
531                         gr_palette_fade_in( title_pal, 32, 0 );
532                 } else
533                         Error( "Couldn't load pcx file '%s', PCX load error: %s\n",filename, pcx_errormsg(pcx_error));
534         }
535
536         con_printf( CON_DEBUG , "\nDoing bm_init..." );
537         #ifdef EDITOR
538                 bm_init_use_tbl();
539         #else
540                 bm_init();
541         #endif
542
543         #ifdef EDITOR
544         if (args_find("-hoarddata") != 0) {
545                 #define MAX_BITMAPS_PER_BRUSH 30
546                 grs_bitmap * bm[MAX_BITMAPS_PER_BRUSH];
547                 grs_bitmap icon;
548                 int nframes;
549                 short nframes_short;
550                 ubyte palette[256*3];
551                 FILE *ofile;
552                 int iff_error,i;
553                 char *sounds[] = {"selforb.raw","selforb.r22",          //SOUND_YOU_GOT_ORB                     
554                                                                 "teamorb.raw","teamorb.r22",            //SOUND_FRIEND_GOT_ORB                  
555                                                                 "enemyorb.raw","enemyorb.r22",  //SOUND_OPPONENT_GOT_ORB        
556                                                                 "OPSCORE1.raw","OPSCORE1.r22"}; //SOUND_OPPONENT_HAS_SCORED
557
558                 ofile = fopen("hoard.ham","wb");
559
560            iff_error = iff_read_animbrush("orb.abm",bm,MAX_BITMAPS_PER_BRUSH,&nframes,palette);
561                 Assert(iff_error == IFF_NO_ERROR);
562                 nframes_short = nframes;
563                 fwrite(&nframes_short,sizeof(nframes_short),1,ofile);
564                 fwrite(&bm[0]->bm_w,sizeof(short),1,ofile);
565                 fwrite(&bm[0]->bm_h,sizeof(short),1,ofile);
566                 fwrite(palette,3,256,ofile);
567                 for (i=0;i<nframes;i++)
568                         fwrite(bm[i]->bm_data,1,bm[i]->bm_w*bm[i]->bm_h,ofile);
569
570            iff_error = iff_read_animbrush("orbgoal.abm",bm,MAX_BITMAPS_PER_BRUSH,&nframes,palette);
571                 Assert(iff_error == IFF_NO_ERROR);
572                 Assert(bm[0]->bm_w == 64 && bm[0]->bm_h == 64);
573                 nframes_short = nframes;
574                 fwrite(&nframes_short,sizeof(nframes_short),1,ofile);
575                 fwrite(palette,3,256,ofile);
576                 for (i=0;i<nframes;i++)
577                         fwrite(bm[i]->bm_data,1,bm[i]->bm_w*bm[i]->bm_h,ofile);
578
579                 for (i=0;i<2;i++) {
580                         iff_error = iff_read_bitmap(i?"orbb.bbm":"orb.bbm",&icon,BM_LINEAR,palette);
581                         Assert(iff_error == IFF_NO_ERROR);
582                         fwrite(&icon.bm_w,sizeof(short),1,ofile);
583                         fwrite(&icon.bm_h,sizeof(short),1,ofile);
584                         fwrite(palette,3,256,ofile);
585                         fwrite(icon.bm_data,1,icon.bm_w*icon.bm_h,ofile);
586                 }
587
588                 for (i=0;i<sizeof(sounds)/sizeof(*sounds);i++) {
589                         FILE *ifile;
590                         int size;
591                         ubyte *buf;
592                         ifile = fopen(sounds[i],"rb");
593                         Assert(ifile != NULL);
594                         size = filelength(ifile->_handle);
595                         buf = d_malloc(size);
596                         fread(buf,1,size,ifile);
597                         fwrite(&size,sizeof(size),1,ofile);
598                         fwrite(buf,1,size,ofile);
599                         d_free(buf);
600                         fclose(ifile);
601                 }
602
603                 fclose(ofile);
604
605                 exit(1);
606         }
607         #endif
608
609         //the bitmap loading code changes gr_palette, so restore it
610         memcpy(gr_palette,title_pal,sizeof(gr_palette));
611
612         if ( args_find( "-norun" ) )
613                 return(0);
614
615         con_printf( CON_DEBUG, "\nInitializing 3d system..." );
616         g3_init();
617
618         con_printf( CON_DEBUG, "\nInitializing texture caching system..." );
619         texmerge_init( 10 );            // 10 cache bitmaps
620
621         con_printf( CON_DEBUG, "\nRunning game...\n" );
622         set_screen_mode(SCREEN_MENU);
623
624         init_game();
625
626         //      If built with editor, option to auto-load a level and quit game
627         //      to write certain data.
628         #ifdef  EDITOR
629         {       int t;
630         if ( t = args_find( "-autoload" ) ) {
631                 Auto_exit = 1;
632                 strcpy(Auto_file, Args[t+1]);
633         }
634                 
635         }
636
637         if (Auto_exit) {
638                 strcpy(Players[0].callsign, "dummy");
639         } else
640         #endif
641                 do_register_player(title_pal);
642
643         gr_palette_fade_out( title_pal, 32, 0 );
644
645         Game_mode = GM_GAME_OVER;
646
647         if (Auto_demo)  {
648                 newdemo_start_playback("descent.dem");          
649                 if (Newdemo_state == ND_STATE_PLAYBACK )
650                         Function_mode = FMODE_GAME;
651         }
652
653         //do this here because the demo code can do a longjmp when trying to
654         //autostart a demo from the main menu, never having gone into the game
655         setjmp(LeaveGame);
656
657         while (Function_mode != FMODE_EXIT)
658         {
659                 switch( Function_mode ) {
660                 case FMODE_MENU:
661                         set_screen_mode(SCREEN_MENU);
662                         if ( Auto_demo )        {
663                                 newdemo_start_playback(NULL);           // Randomly pick a file
664                                 if (Newdemo_state != ND_STATE_PLAYBACK) 
665                                         Error("No demo files were found for autodemo mode!");
666                         } else {
667                                 #ifdef EDITOR
668                                 if (Auto_exit) {
669                                         strcpy(&Level_names[0], Auto_file);
670                                         LoadLevel(1, 1);
671                                         Function_mode = FMODE_EXIT;
672                                         break;
673                                 }
674                                 #endif
675
676                                 check_joystick_calibration();
677                                 gr_palette_clear();             //I'm not sure why we need this, but we do
678                                 DoMenu();                                                                               
679                                 #ifdef EDITOR
680                                 if ( Function_mode == FMODE_EDITOR )    {
681                                         create_new_mine();
682                                         SetPlayerFromCurseg();
683                                         load_palette(NULL,1,0);
684                                 }
685                                 #endif
686                         }
687                         break;
688                 case FMODE_GAME:
689                         #ifdef EDITOR
690                                 keyd_editor_mode = 0;
691                         #endif
692                         game();
693                         if ( Function_mode == FMODE_MENU )
694                                 songs_play_song( SONG_TITLE, 1 );
695                         break;
696                 #ifdef EDITOR
697                 case FMODE_EDITOR:
698                         keyd_editor_mode = 1;
699                         editor();
700                         _harderr( (void*)descent_critical_error_handler );              // Reinstall game error handler
701                         if ( Function_mode == FMODE_GAME ) {
702                                 Game_mode = GM_EDITOR;
703                                 editor_reset_stuff_on_level();
704                                 N_players = 1;
705                         }
706                         break;
707                 #endif
708                 default:
709                         Error("Invalid function mode %d",Function_mode);
710                 }
711         }
712
713         WriteConfigFile();
714
715         #ifndef RELEASE
716         if (!args_find( "-notitles" ))
717         #endif
718
719         #ifndef NDEBUG
720         if ( args_find( "-showmeminfo" ) )
721                 show_mem_info = 1;              // Make memory statistics show
722         #endif
723
724         return(0);              //presumably successful exit
725 }
726
727
728 void check_joystick_calibration()       {
729         int x1, y1, x2, y2, c;
730         fix t1;
731
732         if ( (Config_control_type!=CONTROL_JOYSTICK) &&
733                   (Config_control_type!=CONTROL_FLIGHTSTICK_PRO) &&
734                   (Config_control_type!=CONTROL_THRUSTMASTER_FCS) &&
735                   (Config_control_type!=CONTROL_GRAVIS_GAMEPAD)
736                 ) return;
737
738         joy_get_pos( &x1, &y1 );
739
740         t1 = timer_get_fixed_seconds();
741         while( timer_get_fixed_seconds() < t1 + F1_0/100 )
742                 ;
743
744         joy_get_pos( &x2, &y2 );
745
746         // If joystick hasn't moved...
747         if ( (abs(x2-x1)<30) &&  (abs(y2-y1)<30) )      {
748                 if ( (abs(x1)>30) || (abs(x2)>30) ||  (abs(y1)>30) || (abs(y2)>30) )    {
749                         c = nm_messagebox( NULL, 2, TXT_CALIBRATE, TXT_SKIP, TXT_JOYSTICK_NOT_CEN );
750                         if ( c==0 )     {
751                                 joydefs_calibrate();
752                         }
753                 }
754         }
755
756 }