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