save key config
[fceu.git] / drivers / common / main.c
1 /* FCE Ultra - NES/Famicom Emulator
2  *
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation; either version 2 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16  */
17
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <signal.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <string.h>
25 #include <strings.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "main.h"
31 #include "throttle.h"
32 #include "config.h"
33 #include "args.h"
34 #include "unixdsp.h"
35 #include "cheat.h"
36 #include "dface.h"
37 #include "platform.h"
38 #include "menu.h"
39 #include "settings.h"
40 #include "../libpicofe/config_file.h"
41
42 #include "../../fce.h"
43 #include "../../cart.h"
44
45
46 // these are now here to try to make compatible configs
47 // between different versions of the emu
48 DSETTINGS Settings;
49 CFGSTRUCT DriverConfig[]={
50         AC(Settings.turbo_rate_add),
51         AC(Settings.sound_rate),
52         AC(Settings.showfps),
53         AC(Settings.scaling),
54         AC(Settings.frameskip),
55         AC(Settings.sstate_confirm),
56         AC(Settings.region_force),
57         AC(Settings.cpuclock),
58         AC(Settings.mmuhack),
59         AC(Settings.ramtimings),
60         AC(Settings.gamma),
61         AC(Settings.perfect_vsync),
62         AC(Settings.accurate_mode),
63         AC(Settings.hw_filter),
64         ENDCFGSTRUCT
65 };
66
67 void CleanSurface(void);
68
69 // internals
70 extern uint8 Exit; // exit emu loop flag
71 extern int FSkip;
72 void CloseGame(void);
73
74 FCEUGI *fceugi = NULL;
75 int ntsccol=0,ntschue=-1,ntsctint=-1;
76 int soundvol=70;
77 int inited=0;
78
79 int srendlinev[2]={8,0};
80 int erendlinev[2]={231,239};
81 int srendline,erendline;
82
83
84 static char BaseDirectory[2048];
85
86 int eoptions=0;
87
88 static void DriverKill(void);
89 static int DriverInitialize(void);
90
91 static int gametype;
92 #include "input.c"
93
94 static void ParseGI(FCEUGI *gi)
95 {
96  gametype=gi->type;
97
98  InputType[0]=UsrInputType[0];
99  InputType[1]=UsrInputType[1];
100  InputTypeFC=UsrInputTypeFC;
101
102  if(gi->input[0]>=0)
103   InputType[0]=gi->input[0];
104  if(gi->input[1]>=0)
105   InputType[1]=gi->input[1];
106  if(gi->inputfc>=0)
107   InputTypeFC=gi->inputfc;
108 }
109
110 void FCEUD_PrintError(char *s)
111 {
112  puts(s);
113 }
114
115 char *cpalette=0;
116 void LoadCPalette(void)
117 {
118  char tmpp[192];
119  FILE *fp;
120
121  if(!(fp=fopen(cpalette,"rb")))
122  {
123   printf(" Error loading custom palette from file: %s\n",cpalette);
124   free(cpalette);
125   cpalette=0;
126   return;
127  }
128  fread(tmpp,1,192,fp);
129  FCEUI_SetPaletteArray((uint8 *)tmpp);
130  fclose(fp);
131 }
132
133 static CFGSTRUCT fceuconfig[]={
134         AC(soundvol),
135         ACS(cpalette),
136         AC(ntsctint),
137         AC(ntschue),
138         AC(ntsccol),
139         AC(UsrInputTypeFC),
140         ACA(UsrInputType),
141         AC(powerpadside),
142         AC(powerpadsc),
143         AC(eoptions),
144         ACA(srendlinev),
145         ACA(erendlinev),
146         ADDCFGSTRUCT(DriverConfig),
147         ENDCFGSTRUCT
148 };
149
150 static const char *skip_path(const char *path)
151 {
152         const char *p;
153         if (path == NULL) return NULL;
154         for (p = path+strlen(path)-1; p > path && *p != '/'; p--);
155         if (*p == '/') p++;
156         return p;
157 }
158
159 int SaveConfig(const char *llgn_path)
160 {
161         const char *name = skip_path(llgn_path);
162         char tdir[2048];
163         FILE *f;
164         int ret;
165
166         if (name)
167              sprintf(tdir,"%s"PSS"cfg"PSS"%s.cfg",BaseDirectory,name);
168         else sprintf(tdir,"%s"PSS"fceu2.cfg",BaseDirectory);
169         printf("saving cfg to %s ... ", tdir); fflush(stdout);
170         FCEUI_GetNTSCTH(&ntsctint, &ntschue);
171         ret=SaveFCEUConfig(tdir,fceuconfig);
172         printf(ret == 0 ? "done\n" : "failed\n");
173
174         // keys
175         if (name)
176              sprintf(tdir,"%s"PSS"cfg"PSS"%s_keys.cfg",BaseDirectory,name);
177         else sprintf(tdir,"%s"PSS"fceu_keys.cfg",BaseDirectory);
178         f=fopen(tdir, "w");
179         if (f!=NULL) {
180          config_write_keys(f);
181          fclose(f);
182         }
183
184         return ret;
185 }
186
187 static int LoadConfig(const char *llgn_path)
188 {
189         const char *name = skip_path(llgn_path);
190         char tdir[2048];
191         FILE *f;
192         int ret, l;
193
194         if (name)
195              sprintf(tdir,"%s"PSS"cfg"PSS"%s.cfg",BaseDirectory,name);
196         else sprintf(tdir,"%s"PSS"fceu2.cfg",BaseDirectory);
197         printf("loading cfg from %s ... ", tdir); fflush(stdout);
198         FCEUI_GetNTSCTH(&ntsctint, &ntschue); /* Get default settings for if no config file exists. */
199         ret=LoadFCEUConfig(tdir,fceuconfig);
200         FCEUI_SetNTSCTH(ntsccol, ntsctint, ntschue);
201         printf(ret == 0 ? "done\n" : "failed\n");
202
203         // keys
204         if (name)
205              sprintf(tdir,"%s"PSS"cfg"PSS"%s_keys.cfg",BaseDirectory,name);
206         else sprintf(tdir,"%s"PSS"fceu_keys.cfg",BaseDirectory);
207         f=fopen(tdir, "r");
208         if (f!=NULL) {
209          l=fread(tdir,1,sizeof(tdir)-1,f);
210          tdir[l]=0;
211          config_read_keys(tdir);
212          fclose(f);
213         }
214
215         return ret;
216 }
217
218 static void LoadLLGN(void)
219 {
220  char tdir[2048];
221  FILE *f;
222  int len;
223  sprintf(tdir,"%s"PSS"last_rom.txt",BaseDirectory);
224  f=fopen(tdir, "r");
225  if(f)
226  {
227   len = fread(lastLoadedGameName, 1, sizeof(lastLoadedGameName)-1, f);
228   lastLoadedGameName[len] = 0;
229   fclose(f);
230  }
231 }
232
233 static void SaveLLGN(void)
234 {
235  // save last loaded game name
236  if (lastLoadedGameName[0] && !(eoptions&EO_NOAUTOWRITE))
237  {
238   char tdir[2048];
239   FILE *f;
240   sprintf(tdir,"%s"PSS"last_rom.txt",BaseDirectory);
241   f=fopen(tdir, "w");
242   if(f)
243   {
244    fwrite(lastLoadedGameName, 1, strlen(lastLoadedGameName), f);
245    fclose(f);
246    sync();
247   }
248  }
249 }
250
251
252 static void CreateDirs(void)
253 {
254  char *subs[]={"fcs","snaps","gameinfo","sav","cheats","cfg","pal"};
255  char tdir[2048];
256  int x;
257
258  mkdir(BaseDirectory,S_IRWXU);
259  for(x=0;x<sizeof(subs)/sizeof(subs[0]);x++)
260  {
261   sprintf(tdir,"%s"PSS"%s",BaseDirectory,subs[x]);
262   mkdir(tdir,S_IRWXU);
263  }
264 }
265
266 static void SetSignals(void (*t)(int))
267 {
268   int sigs[11]={SIGINT,SIGTERM,SIGHUP,SIGPIPE,SIGSEGV,SIGFPE,SIGKILL,SIGALRM,SIGABRT,SIGUSR1,SIGUSR2};
269   int x;
270   for(x=0;x<11;x++)
271    signal(sigs[x],t);
272 }
273
274 static void CloseStuff(int signum)
275 {
276         DriverKill();
277         printf("\nSignal %d has been caught and dealt with...\n",signum);
278         switch(signum)
279         {
280          case SIGINT:printf("How DARE you interrupt me!\n");break;
281          case SIGTERM:printf("MUST TERMINATE ALL HUMANS\n");break;
282          case SIGHUP:printf("Reach out and hang-up on someone.\n");break;
283          case SIGPIPE:printf("The pipe has broken!  Better watch out for floods...\n");break;
284          case SIGSEGV:printf("Iyeeeeeeeee!!!  A segmentation fault has occurred.  Have a fluffy day.\n");break;
285          #if(SIGBUS!=SIGSEGV)
286          case SIGBUS:printf("I told you to be nice to the driver.\n");break;
287          #endif
288          case SIGFPE:printf("Those darn floating points.  Ne'er know when they'll bite!\n");break;
289          case SIGALRM:printf("Don't throw your clock at the meowing cats!\n");break;
290          case SIGABRT:printf("Abort, Retry, Ignore, Fail?\n");break;
291          case SIGUSR1:
292          case SIGUSR2:printf("Killing your processes is not nice.\n");break;
293         }
294         exit(1);
295 }
296
297 static int DoArgs(int argc, char *argv[])
298 {
299         static char *cortab[5]={"none","gamepad","zapper","powerpad","arkanoid"};
300         static int cortabi[5]={SI_NONE,SI_GAMEPAD,
301                                SI_ZAPPER,SI_POWERPADA,SI_ARKANOID};
302         static char *fccortab[5]={"none","arkanoid","shadow","4player","fkb"};
303         static int fccortabi[5]={SIFC_NONE,SIFC_ARKANOID,SIFC_SHADOW,
304                                  SIFC_4PLAYER,SIFC_FKB};
305
306         int x, ret;
307         static char *inputa[2]={0,0};
308         static char *fcexp=0;
309         static int docheckie[4];
310 #ifdef NETWORK
311         static int docheckie2[2]={0,0};
312 #endif
313
314         static ARGPSTRUCT FCEUArgs[]={
315          {"-soundvol",0,&soundvol,0},
316          {"-cpalette",0,&cpalette,0x4001},
317
318          {"-ntsccol",0,&ntsccol,0},
319          {"-pal",&docheckie[0],0,0},
320          {"-input1",0,&inputa[0],0x4001},{"-input2",0,&inputa[1],0x4001},
321          {"-fcexp",0,&fcexp,0x4001},
322
323          {"-gg",0,&eoptions,0x8000|EO_GG},
324          {"-no8lim",0,&eoptions,0x8000|EO_NO8LIM},
325          {"-snapname",0,&eoptions,0x8000|EO_SNAPNAME},
326          {"-nofs",0,&eoptions,0x8000|EO_NOFOURSCORE},
327          {"-clipsides",0,&eoptions,0x8000|EO_CLIPSIDES},
328          {"-nothrottle",0,&eoptions,0x8000|EO_NOTHROTTLE},
329          {"-noautowrite",0,&eoptions,0x8000|EO_NOAUTOWRITE},
330          {"-slstart",0,&srendlinev[0],0},{"-slend",0,&erendlinev[0],0},
331          {"-slstartp",0,&srendlinev[1],0},{"-slendp",0,&erendlinev[1],0},
332          {"-sound",0,&Settings.sound_rate,0},
333          {"-showfps",0,&Settings.showfps,0},
334          #ifdef NETWORK
335          {"-connect",&docheckie2[0],&netplayhost,0x4001},
336          {"-server",&docheckie2[1],0,0},
337          {"-netport",0,&Port,0},
338          #endif
339          {0,(void *)DriverArgs,0,0},
340          {0,0,0,0}
341         };
342
343         memset(docheckie,0,sizeof(docheckie));
344         ret=ParseArguments(argc, argv, FCEUArgs);
345         if(cpalette)
346         {
347          if(cpalette[0]=='0')
348           if(cpalette[1]==0)
349           {
350            free(cpalette);
351            cpalette=0;
352           }
353         }
354         if(docheckie[0])
355          Settings.region_force=2;
356         FCEUI_SetGameGenie(eoptions&EO_GG);
357         FCEUI_DisableSpriteLimitation(eoptions&EO_NO8LIM);
358         FCEUI_SetSnapName(eoptions&EO_SNAPNAME);
359
360         for(x=0;x<2;x++)
361         {
362          if(srendlinev[x]<0 || srendlinev[x]>239) srendlinev[x]=0;
363          if(erendlinev[x]<srendlinev[x] || erendlinev[x]>239) erendlinev[x]=239;
364         }
365
366         FCEUI_SetRenderedLines(srendlinev[0],erendlinev[0],srendlinev[1],erendlinev[1]);
367         FCEUI_SetSoundVolume(80);
368         #ifdef NETWORK
369         if(docheckie2[0])
370          netplay=2;
371         else if(docheckie2[1])
372          netplay=1;
373
374         if(netplay)
375          FCEUI_SetNetworkPlay(netplay);
376         #endif
377         DoDriverArgs();
378
379         if(fcexp)
380         {
381          int y;
382          for(y=0;y<5;y++)
383          {
384           if(!strncmp(fccortab[y],fcexp,8))
385           {
386            UsrInputTypeFC=fccortabi[y];
387            break;
388           }
389          }
390          free(fcexp);
391         }
392         for(x=0;x<2;x++)
393         {
394          int y;
395
396          if(!inputa[x])
397           continue;
398
399          for(y=0;y<5;y++)
400          {
401           if(!strncmp(cortab[y],inputa[x],8))
402           {
403            UsrInputType[x]=cortabi[y];
404            if(y==3)
405            {
406             powerpadside&=~(1<<x);
407             powerpadside|=((((inputa[x][8])-'a')&1)^1)<<x;
408            }
409            free(inputa[x]);
410           }
411          }
412         }
413         return ret;
414 }
415
416
417 #include "usage.h"
418
419 int main(int argc, char *argv[])
420 {
421         int last_arg_parsed, ret;
422         /* TODO if(argc<=1)
423         {
424          ShowUsage(argv[0]);
425          return 1;
426         }*/
427
428         platform_init();
429         if(!DriverInitialize())
430         {
431          return 1;
432         }
433
434         if(!FCEUI_Initialize())
435          return(1);
436         GetBaseDirectory(BaseDirectory);
437         FCEUI_SetBaseDirectory(BaseDirectory);
438         lastLoadedGameName[0] = 0;
439         menu_init();
440         in_init();
441
442         CreateDirs();
443         LoadConfig(NULL);
444         last_arg_parsed=DoArgs(argc-1,&argv[1]);
445         platform_late_init();
446
447         LoadLLGN();
448         FCEUI_SetNTSCTH(ntsccol, ntsctint, ntschue);
449         if(cpalette)
450          LoadCPalette();
451         if(InitSound())
452          inited|=1;
453
454         if (argc > 1 && !last_arg_parsed)
455         {
456          strncpy(lastLoadedGameName, argv[argc-1], sizeof(lastLoadedGameName));
457          lastLoadedGameName[sizeof(lastLoadedGameName)-1] = 0;
458          Exit = 0;
459         }
460         else
461         {
462          Exit = 1;
463         }
464
465         while (1)
466         {
467          if(!Exit)
468          {
469           if (fceugi)
470            CloseGame();
471           ret=LoadConfig(lastLoadedGameName);
472           if (ret != 0)
473           {
474            LoadConfig(NULL);
475           }
476           FCEUI_SetEmuMode(Settings.accurate_mode);
477           fceugi=FCEUI_LoadGame(lastLoadedGameName);
478           if (fceugi)
479           {
480            char infostring[32];
481            if (Settings.region_force)
482             FCEUI_SetVidSystem(Settings.region_force - 1);
483            ParseGI(fceugi);
484            InitOtherInput();
485
486            if ((eoptions&EO_GG) && geniestage == 0) {
487             strcpy(infostring, "gg.rom is missing, GG disabled");
488             eoptions&=~EO_GG;
489             FCEUI_SetGameGenie(0);
490            } else
491             GameInterface(GI_INFOSTRING, infostring);
492            FCEU_DispMessage("%s", infostring);
493           }
494           else
495           {
496            switch(LoadGameLastError) {
497             default: menu_update_msg("failed to load ROM"); break;
498             case  2: menu_update_msg("Can't find a ROM for ips/movie"); break;
499             case 10: menu_update_msg("FDS BIOS ROM is missing, read docs"); break;
500             case 11: menu_update_msg("Error reading auxillary FDS file"); break;
501            }
502           }
503          }
504          if(Exit || !fceugi)
505          {
506           int ret;
507           ret = menu_loop();
508           if (ret == 1) break;          // exit emu
509           if (ret == 2) {               // reload ROM
510            SaveLLGN();
511            Exit = 0;
512            continue;
513           }
514          }
515
516          PrepareOtherInput();
517          FCEUI_GetCurrentVidSystem(&srendline,&erendline);
518          platform_apply_config();
519          CleanSurface();
520          StartSound();
521          RefreshThrottleFPS();
522          FCEUI_Emulate();
523         }
524
525         if (fceugi)
526          CloseGame();
527
528         FCEUI_Kill();
529         DriverKill();
530         platform_finish();
531         return 0;
532 }
533
534 static int DriverInitialize(void)
535 {
536    SetSignals((void *)CloseStuff);
537
538    if(!InitVideo()) return 0;
539    inited|=4;
540    return 1;
541 }
542
543 static void DriverKill(void)
544 {
545  // SaveConfig(NULL); // done explicitly in menu now
546  SetSignals(SIG_DFL);
547
548  if(cpalette) free(cpalette);
549  cpalette=0;
550
551  if(inited&4)
552   KillVideo();
553  if(inited&1)
554   KillSound();
555  inited=0;
556 }
557
558 void FCEUD_Update(uint8 *xbuf, int16 *Buffer, int Count)
559 {
560  FCEUD_UpdateInput();   // must update input before blitting because of save confirmation stuff
561  BlitPrepare(xbuf == NULL);
562  if(!(eoptions&EO_NOTHROTTLE))
563  {
564   if(Count)
565    WriteSound(Buffer,Count);
566   SpeedThrottle();
567  }
568  BlitScreen(xbuf == NULL);
569  // make sure last frame won't get skipped, because we need it for menu bg
570  if (Exit) FSkip=0;
571 }
572
573