main.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. // mainloop with window server event handling
  2. // event polling mechnism was taken from
  3. // Peter van Sebille's projects
  4. // (c) Copyright 2006, notaz
  5. // All Rights Reserved
  6. #include <e32base.h>
  7. #include <hal.h>
  8. #include <e32keys.h>
  9. #include <w32std.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <sys/time.h>
  13. #include "debug.h"
  14. #include "../Engine.h"
  15. #include <Pico/PicoInt.h>
  16. #include "../../common/emu.h"
  17. #include "../emu.h"
  18. #include "vid.h"
  19. #include "PolledAS.h"
  20. //#include "audio.h"
  21. #include "audio_mediaserver.h"
  22. //#include <ezlib.h>
  23. #include <zlib/zlib.h>
  24. //#define BENCHMARK
  25. // scancodes we care about
  26. enum TUsedScanCodes {
  27. EStdKeyM600JogUp = EStdKeyDevice1,
  28. EStdKeyM600JogDown = EStdKeyDevice2,
  29. };
  30. static unsigned char keyFlags[256]; // lsb->msb: key_down, pulse_only, ?, ?, ?, ?, not_configurable, disabled
  31. static unsigned char pressedKeys[11]; // List of pressed key scancodes, up to 10
  32. // list of areas
  33. TPicoAreaConfigEntry areaConfig[] = {
  34. { TRect( 0, 0, 0, 0) },
  35. // small corner bottons
  36. { TRect( 0, 0, 15, 15) },
  37. { TRect(224, 0, 239, 15) },
  38. { TRect( 0, 304, 15, 319) },
  39. { TRect(224, 304, 239, 319) },
  40. // normal buttons
  41. { TRect( 0, 0, 79, 63) },
  42. { TRect( 80, 0, 159, 63) },
  43. { TRect(160, 0, 239, 63) },
  44. { TRect( 0, 64, 79, 127) },
  45. { TRect( 80, 64, 159, 127) },
  46. { TRect(160, 64, 239, 127) },
  47. { TRect( 0, 128, 79, 191) },
  48. { TRect( 80, 128, 159, 191) },
  49. { TRect(160, 128, 239, 191) },
  50. { TRect( 0, 192, 79, 255) },
  51. { TRect( 80, 192, 159, 255) },
  52. { TRect(160, 192, 239, 255) },
  53. { TRect( 0, 256, 79, 319) },
  54. { TRect( 80, 256, 159, 319) },
  55. { TRect(160, 256, 239, 319) },
  56. { TRect( 0, 0, 0, 0) }
  57. };
  58. // PicoPad[] format: SACB RLDU
  59. const char *actionNames[] = {
  60. "UP", "DOWN", "LEFT", "RIGHT", "B", "C", "A", "START",
  61. 0, 0, 0, 0, 0, 0, 0, 0, // Z, Y, X, MODE (enabled only when needed), ?, ?, ?, ?
  62. 0, 0, 0, 0, "VOLUME@UP", "VOLUME@DOWN", "NEXT@SAVE@SLOT", "PREV@SAVE@SLOT", // ?, ?, ?, ?, vol_up, vol_down, next_slot, prev_slot
  63. 0, 0, "PAUSE@EMU", "SAVE@STATE", "LOAD@STATE", 0, 0, "DONE" // ?, switch_renderer, [...], "FRAMESKIP@8", "AUTO@FRAMESKIP"
  64. };
  65. // globals are allowed, so why not to (ab)use them?
  66. //TInt machineUid = 0;
  67. int gamestate = PGS_Paused, gamestate_next = PGS_Paused;
  68. char *loadrom_fname = NULL;
  69. int loadrom_result = 0;
  70. static timeval noticeMsgTime = { 0, 0 }; // when started showing
  71. static CGameAudioMS *gameAudio = 0; // the audio object itself
  72. static int reset_timing;
  73. extern int pico_was_reset;
  74. extern RSemaphore initSemaphore;
  75. extern RSemaphore pauseSemaphore;
  76. extern RSemaphore loadWaitSemaphore;
  77. // some forward declarations
  78. static void MainInit();
  79. static void MainExit();
  80. static void DumpMemInfo();
  81. class TPicoDirectScreenAccess : public MDirectScreenAccess
  82. {
  83. public: // implements MDirectScreenAccess
  84. void Restart(RDirectScreenAccess::TTerminationReasons aReason);
  85. public: // implements MAbortDirectScreenAccess
  86. void AbortNow(RDirectScreenAccess::TTerminationReasons aReason);
  87. };
  88. // just for a nicer grouping of WS related stuff
  89. class CGameWindow
  90. {
  91. public:
  92. static void ConstructResourcesL(void);
  93. static void FreeResources(void);
  94. static void DoKeys(void);
  95. static void DoKeysConfig(TUint &which);
  96. static void RunEvents(TUint32 which);
  97. static RWsSession* iWsSession;
  98. static RWindowGroup iWsWindowGroup;
  99. static RWindow iWsWindow;
  100. static CWsScreenDevice* iWsScreen;
  101. static CWindowGc* iWindowGc;
  102. static TRequestStatus iWsEventStatus;
  103. // static TThreadId iLauncherThreadId;
  104. // static RDirectScreenAccess* iDSA;
  105. // static TRequestStatus iDSAstatus;
  106. static TPicoDirectScreenAccess iPDSA;
  107. static CDirectScreenAccess* iDSA;
  108. };
  109. static void updateSound(int len)
  110. {
  111. PsndOut = gameAudio->NextFrameL(len);
  112. if(!PsndOut) { // sound output problems?
  113. strcpy(noticeMsg, "SOUND@OUTPUT@ERROR;@SOUND@DISABLED");
  114. gettimeofday(&noticeMsgTime, 0);
  115. }
  116. }
  117. static void SkipFrame(void)
  118. {
  119. PicoSkipFrame=1;
  120. PicoFrame();
  121. PicoSkipFrame=0;
  122. }
  123. static void simpleWait(int thissec, int lim_time)
  124. {
  125. struct timeval tval;
  126. int sleep = 0;
  127. gettimeofday(&tval, 0);
  128. if(thissec != tval.tv_sec) tval.tv_usec+=1000000;
  129. sleep = lim_time - tval.tv_usec - 2000;
  130. if (sleep > 0) {
  131. // User::After((sleep = lim_time - tval.tv_usec));
  132. User::AfterHighRes(sleep);
  133. }
  134. }
  135. static void TargetEpocGameL()
  136. {
  137. char buff[24]; // fps count c string
  138. struct timeval tval; // timing
  139. int thissec = 0, frames_done = 0, frames_shown = 0;
  140. int target_fps, target_frametime;
  141. int i, lim_time;
  142. //TRawEvent blevent;
  143. MainInit();
  144. buff[0] = 0;
  145. PicoInit();
  146. // just to keep the backlight on (works only on UIQ2)
  147. //blevent.Set(TRawEvent::EActive);
  148. // loop?
  149. for(;;)
  150. {
  151. if (gamestate == PGS_Running)
  152. {
  153. // switch context to other thread
  154. User::After(50000);
  155. // prepare window and stuff
  156. CGameWindow::ConstructResourcesL();
  157. // if the system has something to do, it should better do it now
  158. User::After(50000);
  159. //CPolledActiveScheduler::Instance()->Schedule();
  160. // pal/ntsc might have changed, reset related stuff
  161. if(Pico.m.pal) {
  162. target_fps = 50;
  163. if(!noticeMsgTime.tv_sec) strcpy(noticeMsg, "PAL@SYSTEM@/@50@FPS");
  164. } else {
  165. target_fps = 60;
  166. if(!noticeMsgTime.tv_sec) strcpy(noticeMsg, "NTSC@SYSTEM@/@60@FPS");
  167. }
  168. target_frametime = 1000000/target_fps;
  169. if(!noticeMsgTime.tv_sec && pico_was_reset)
  170. gettimeofday(&noticeMsgTime, 0);
  171. // prepare CD buffer
  172. if (PicoAHW & PAHW_MCD) PicoCDBufferInit();
  173. pico_was_reset = 0;
  174. reset_timing = 1;
  175. while (gamestate == PGS_Running)
  176. {
  177. gettimeofday(&tval, 0);
  178. if(reset_timing) {
  179. reset_timing = 0;
  180. thissec = tval.tv_sec;
  181. frames_done = tval.tv_usec/target_frametime;
  182. }
  183. // show notice message?
  184. char *notice = 0;
  185. if(noticeMsgTime.tv_sec) {
  186. if((tval.tv_sec*1000000+tval.tv_usec) - (noticeMsgTime.tv_sec*1000000+noticeMsgTime.tv_usec) > 2000000) // > 2.0 sec
  187. noticeMsgTime.tv_sec = noticeMsgTime.tv_usec = 0;
  188. else notice = noticeMsg;
  189. }
  190. // second changed?
  191. if (thissec != tval.tv_sec)
  192. {
  193. #ifdef BENCHMARK
  194. static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
  195. if(++bench == 10) {
  196. bench = 0;
  197. bench_fps_s = bench_fps;
  198. bf[bfp++ & 3] = bench_fps;
  199. bench_fps = 0;
  200. }
  201. bench_fps += frames_shown;
  202. sprintf(buff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
  203. #else
  204. if (currentConfig.EmuOpt & EOPT_SHOW_FPS)
  205. sprintf(buff, "%02i/%02i", frames_shown, frames_done);
  206. #endif
  207. thissec = tval.tv_sec;
  208. if(PsndOut == 0 && currentConfig.Frameskip >= 0) {
  209. frames_done = frames_shown = 0;
  210. } else {
  211. // it is quite common for this implementation to leave 1 fame unfinished
  212. // when second changes, but we don't want buffer to starve.
  213. if(PsndOut && frames_done < target_fps && frames_done > target_fps-5) {
  214. SkipFrame(); frames_done++;
  215. }
  216. frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
  217. frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
  218. if (frames_shown > frames_done) frames_shown = frames_done;
  219. }
  220. }
  221. lim_time = (frames_done+1) * target_frametime;
  222. if (currentConfig.Frameskip >= 0) // frameskip enabled
  223. {
  224. for (i = 0; i < currentConfig.Frameskip && gamestate == PGS_Running; i++)
  225. {
  226. CGameWindow::DoKeys();
  227. SkipFrame(); frames_done++;
  228. if (PsndOut) { // do framelimitting if sound is enabled
  229. gettimeofday(&tval, 0);
  230. if(thissec != tval.tv_sec) tval.tv_usec+=1000000;
  231. if(tval.tv_usec < lim_time) { // we are too fast
  232. simpleWait(thissec, lim_time);
  233. }
  234. }
  235. lim_time += target_frametime;
  236. }
  237. }
  238. else if(tval.tv_usec > lim_time) { // auto frameskip
  239. // no time left for this frame - skip
  240. CGameWindow::DoKeys();
  241. SkipFrame(); frames_done++;
  242. continue;
  243. }
  244. // we might have lost focus already
  245. if (gamestate != PGS_Running) break;
  246. CGameWindow::DoKeys();
  247. PicoFrame();
  248. // check time
  249. gettimeofday(&tval, 0);
  250. if(thissec != tval.tv_sec) tval.tv_usec+=1000000;
  251. // sleep if we are still too fast
  252. if(PsndOut != 0 || currentConfig.Frameskip < 0)
  253. {
  254. // TODO: check if User::After() is accurate
  255. gettimeofday(&tval, 0);
  256. if(thissec != tval.tv_sec) tval.tv_usec+=1000000;
  257. if(tval.tv_usec < lim_time)
  258. {
  259. // we are too fast
  260. simpleWait(thissec, lim_time);
  261. }
  262. }
  263. CPolledActiveScheduler::Instance()->Schedule();
  264. if (gamestate != PGS_Paused)
  265. vidDrawFrame(notice, buff, frames_shown);
  266. frames_done++; frames_shown++;
  267. } // while
  268. if (PicoAHW & PAHW_MCD) PicoCDBufferFree();
  269. // save SRAM
  270. if ((currentConfig.EmuOpt & EOPT_USE_SRAM) && SRam.changed) {
  271. emu_SaveLoadGame(0, 1);
  272. SRam.changed = 0;
  273. }
  274. CPolledActiveScheduler::Instance()->Schedule();
  275. CGameWindow::FreeResources();
  276. }
  277. else if(gamestate == PGS_ReloadRom)
  278. {
  279. loadrom_result = emu_ReloadRom(loadrom_fname);
  280. pico_was_reset = 1;
  281. if (loadrom_result)
  282. gamestate = PGS_Running;
  283. else
  284. gamestate = PGS_Paused;
  285. DEBUGPRINT(_L("done loading ROM, retval=%i"), loadrom_result);
  286. loadWaitSemaphore.Signal();
  287. User::After(50000);
  288. }
  289. else if(gamestate == PGS_Paused) {
  290. DEBUGPRINT(_L("pausing.."));
  291. pauseSemaphore.Wait();
  292. }
  293. else if(gamestate == PGS_KeyConfig)
  294. {
  295. // switch context to other thread
  296. User::After(50000);
  297. // prepare window and stuff
  298. CGameWindow::ConstructResourcesL();
  299. TUint whichAction = 0;
  300. while(gamestate == PGS_KeyConfig) {
  301. CGameWindow::DoKeysConfig(whichAction);
  302. CPolledActiveScheduler::Instance()->Schedule();
  303. if (gamestate != PGS_Paused)
  304. vidKeyConfigFrame(whichAction);
  305. User::After(150000);
  306. }
  307. CGameWindow::FreeResources();
  308. } else if(gamestate == PGS_DebugHeap) {
  309. #ifdef __DEBUG_PRINT
  310. TInt cells = User::CountAllocCells();
  311. TInt mem;
  312. User::AllocSize(mem);
  313. DEBUGPRINT(_L("worker: cels=%d, size=%d KB"), cells, mem/1024);
  314. gamestate = gamestate_next;
  315. #endif
  316. } else if(gamestate == PGS_Quit) {
  317. break;
  318. }
  319. }
  320. // this thread has to close it's own handles,
  321. // other one will crash trying to do that
  322. PicoExit();
  323. MainExit();
  324. }
  325. // main initialization
  326. static void MainInit()
  327. {
  328. DEBUGPRINT(_L("\r\n\r\nstarting.."));
  329. DEBUGPRINT(_L("CPolledActiveScheduler::NewL()"));
  330. CPolledActiveScheduler::NewL(); // create Polled AS for the sound engine
  331. // HAL::Get(HALData::EMachineUid, machineUid); // find out the machine UID
  332. DumpMemInfo();
  333. // try to start pico
  334. DEBUGPRINT(_L("PicoInit()"));
  335. PicoDrawSetColorFormat(2);
  336. PicoWriteSound = updateSound;
  337. // if (pauseSemaphore.Handle() <= 0)
  338. // pauseSemaphore.CreateLocal(0);
  339. DEBUGPRINT(_L("initSemaphore.Signal()"));
  340. initSemaphore.Signal();
  341. }
  342. // does not return
  343. static void MainExit()
  344. {
  345. RThread thisThread;
  346. DEBUGPRINT(_L("%i: cleaning up.."), (TInt32) thisThread.Id());
  347. // pauseSemaphore.Close();
  348. if(gameAudio) delete gameAudio;
  349. // Polled AS
  350. delete CPolledActiveScheduler::Instance();
  351. }
  352. static void DumpMemInfo()
  353. {
  354. TInt ramSize, ramSizeFree, romSize;
  355. HAL::Get(HALData::EMemoryRAM, ramSize);
  356. HAL::Get(HALData::EMemoryRAMFree, ramSizeFree);
  357. HAL::Get(HALData::EMemoryROM, romSize);
  358. DEBUGPRINT(_L("ram=%dKB, ram_free=%dKB, rom=%dKB"), ramSize/1024, ramSizeFree/1024, romSize/1024);
  359. }
  360. extern "C" TInt my_SetExceptionHandler(TInt, TExceptionHandler, TUint32);
  361. TInt EmuThreadFunction(TAny*)
  362. {
  363. TInt ret;
  364. const TUint32 exs = KExceptionAbort|KExceptionKill|KExceptionUserInterrupt|KExceptionFpe|KExceptionFault|KExceptionInteger|KExceptionDebug;
  365. DEBUGPRINT(_L("EmuThreadFunction(), def ExceptionHandler %08x, my %08x"),
  366. User::ExceptionHandler(), ExceptionHandler);
  367. User::SetJustInTime(1);
  368. ret = User::SetExceptionHandler(ExceptionHandler, exs/*(TUint32) -1*/); // does not work :(
  369. // my_SetExceptionHandler(KCurrentThreadHandle, ExceptionHandler, 0xffffffff);
  370. DEBUGPRINT(_L("SetExceptionHandler %i, %08x"), ret, User::ExceptionHandler());
  371. User::ModifyExceptionMask(0, exs);
  372. //TInt pc, sp;
  373. //asm volatile ("str pc, %0" : "=m" (pc) );
  374. //asm volatile ("str sp, %0" : "=m" (sp) );
  375. //RDebug::Print(_L("executing @ 0x%08x, sp=0x%08x"), pc, sp);
  376. /*
  377. RDebug::Print(_L("Base Bottom Top Size RW Name"));
  378. TBuf<4> l_r(_L("R")), l_w(_L("W")), l_d(_L("-"));
  379. RChunk chunk;
  380. TFullName chunkname;
  381. TFindChunk findChunk(_L("*"));
  382. while( findChunk.Next(chunkname) != KErrNotFound ) {
  383. chunk.Open(findChunk);
  384. RDebug::Print(_L("%08x %08x %08x %08x %S%S %S"), chunk.Base(), chunk.Base()+chunk.Bottom(), chunk.Base()+chunk.Top(), chunk.Size(), chunk.IsReadable() ? &l_r : &l_d, chunk.IsWritable() ? &l_w : &l_d, &chunkname);
  385. chunk.Close();
  386. }
  387. */
  388. // can't do that, will crash here
  389. // if(cleanup) {
  390. // DEBUGPRINT(_L("found old CTrapCleanup, deleting.."));
  391. // delete cleanup;
  392. // }
  393. CTrapCleanup *cleanup = CTrapCleanup::New();
  394. TRAPD(error, TargetEpocGameL());
  395. __ASSERT_ALWAYS(!error, User::Panic(_L("PicoDrive"), error));
  396. delete cleanup;
  397. DEBUGPRINT(_L("exitting.."));
  398. return 1;
  399. }
  400. void TPicoDirectScreenAccess::Restart(RDirectScreenAccess::TTerminationReasons aReason)
  401. {
  402. DEBUGPRINT(_L("TPicoDirectScreenAccess::Restart(%i)"), aReason);
  403. // if (CGameWindow::iDSA) {
  404. // TRAPD(error, CGameWindow::iDSA->StartL());
  405. // if (error) DEBUGPRINT(_L("iDSA->StartL() error: %i"), error);
  406. // }
  407. }
  408. void TPicoDirectScreenAccess::AbortNow(RDirectScreenAccess::TTerminationReasons aReason)
  409. {
  410. DEBUGPRINT(_L("TPicoDirectScreenAccess::AbortNow(%i)"), aReason);
  411. // the WS wants us to stop, so let's obey
  412. gamestate = PGS_Paused;
  413. }
  414. void CGameWindow::ConstructResourcesL()
  415. {
  416. DEBUGPRINT(_L("ConstructResourcesL()"));
  417. // connect to window server
  418. // tried to create it globally and not re-connect everytime,
  419. // but my window started to lose focus strangely
  420. iWsSession = new(ELeave) RWsSession();
  421. User::LeaveIfError(iWsSession->Connect());
  422. // * Tell the Window Server not to mess about with our process priority
  423. // * Also, because of the way legacy games are written, they never sleep
  424. // * and thus never voluntarily yield the CPU. We set our process priority
  425. // * to EPriorityForeground and hope that a Telephony application on
  426. // * this device runs at EPriorityForeground as well. If not, tough! ;-)
  427. iWsSession->ComputeMode(RWsSession::EPriorityControlDisabled);
  428. RProcess me;
  429. me.SetPriority(EPriorityForeground);
  430. iWsScreen = new(ELeave) CWsScreenDevice(*iWsSession);
  431. User::LeaveIfError(iWsScreen->Construct());
  432. // User::LeaveIfError(iWsScreen->CreateContext(iWindowGc));
  433. iWsWindowGroup = RWindowGroup(*iWsSession);
  434. User::LeaveIfError(iWsWindowGroup.Construct((TUint32)&iWsWindowGroup));
  435. //iWsWindowGroup.SetOrdinalPosition(0);
  436. //iWsWindowGroup.SetName(KServerWGName);
  437. iWsWindowGroup.EnableScreenChangeEvents(); // flip events (EEventScreenDeviceChanged)
  438. iWsWindowGroup.EnableFocusChangeEvents(); // EEventFocusGroupChanged
  439. iWsWindowGroup.SetOrdinalPosition(0, 1); // TInt aPos, TInt aOrdinalPriority
  440. iWsWindow=RWindow(*iWsSession);
  441. User::LeaveIfError(iWsWindow.Construct(iWsWindowGroup, (TUint32)&iWsWindow));
  442. iWsWindow.SetSize(iWsScreen->SizeInPixels());
  443. iWsWindow.PointerFilter(EPointerFilterDrag, 0);
  444. iWsWindow.SetPointerGrab(ETrue);
  445. iWsWindow.SetVisible(ETrue);
  446. iWsWindow.Activate();
  447. #if 0
  448. // request access through RDirectScreenAccess api, but don't care about the result
  449. // hangs?
  450. RRegion *dsa_region = 0;
  451. iDSA = new(ELeave) RDirectScreenAccess(*iWsSession);
  452. if(iDSA->Construct() == KErrNone)
  453. iDSA->Request(dsa_region, iDSAstatus, iWsWindow);
  454. DEBUGPRINT(_L("DSA: %i"), dsa_region ? dsa_region->Count() : -1);
  455. #endif
  456. TInt ret;
  457. // request access through CDirectScreenAccess
  458. iDSA = CDirectScreenAccess::NewL(*iWsSession, *iWsScreen, iWsWindow, iPDSA);
  459. // now get the screenbuffer
  460. TScreenInfoV01 screenInfo;
  461. TPckg<TScreenInfoV01> sI(screenInfo);
  462. UserSvr::ScreenInfo(sI);
  463. if(!screenInfo.iScreenAddressValid)
  464. User::Leave(KErrNotSupported);
  465. DEBUGPRINT(_L("framebuffer=0x%08x (%dx%d)"), screenInfo.iScreenAddress,
  466. screenInfo.iScreenSize.iWidth, screenInfo.iScreenSize.iHeight);
  467. // vidInit
  468. DEBUGPRINT(_L("vidInit()"));
  469. ret = vidInit((void *)screenInfo.iScreenAddress, 0);
  470. DEBUGPRINT(_L("vidInit() done (%i)"), ret);
  471. User::LeaveIfError(ret);
  472. memset(keyFlags, 0, 256);
  473. keyFlags[EStdKeyM600JogUp] = keyFlags[EStdKeyM600JogDown] = 2; // add "pulse only" for jog up/down
  474. keyFlags[EStdKeyOff] = 0x40; // not configurable
  475. // try to start the audio engine
  476. static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
  477. if (gamestate == PGS_Running && (currentConfig.EmuOpt & EOPT_EN_SOUND))
  478. {
  479. TInt err = 0;
  480. if(PsndRate != PsndRate_old || (PicoOpt&11) != (PicoOpt_old&11) || Pico.m.pal != pal_old) {
  481. // if rate changed, reset all enabled chips, else reset only those chips, which were recently enabled
  482. //sound_reset(PsndRate != PsndRate_old ? PicoOpt : (PicoOpt&(PicoOpt^PicoOpt_old)));
  483. PsndRerate(1);
  484. }
  485. if(!gameAudio || PsndRate != PsndRate_old || ((PicoOpt&8) ^ (PicoOpt_old&8)) || Pico.m.pal != pal_old) { // rate or stereo or pal/ntsc changed
  486. if(gameAudio) delete gameAudio; gameAudio = 0;
  487. DEBUGPRINT(_L("starting audio: %i len: %i stereo: %i, pal: %i"), PsndRate, PsndLen, PicoOpt&8, Pico.m.pal);
  488. TRAP(err, gameAudio = CGameAudioMS::NewL(PsndRate, (PicoOpt&8) ? 1 : 0,
  489. Pico.m.pal ? 50 : 60, currentConfig.volume));
  490. }
  491. if( gameAudio) {
  492. TRAP(err, PsndOut = gameAudio->ResumeL());
  493. }
  494. if(err) {
  495. if(gameAudio) delete gameAudio;
  496. gameAudio = 0;
  497. PsndOut = 0;
  498. strcpy(noticeMsg, "SOUND@STARTUP@FAILED");
  499. gettimeofday(&noticeMsgTime, 0);
  500. }
  501. PsndRate_old = PsndRate;
  502. PicoOpt_old = PicoOpt;
  503. pal_old = Pico.m.pal;
  504. } else {
  505. if(gameAudio) delete gameAudio;
  506. gameAudio = 0;
  507. PsndOut = 0;
  508. }
  509. CPolledActiveScheduler::Instance()->Schedule();
  510. // start key WS event polling
  511. iWsSession->EventReady(&iWsEventStatus);
  512. iWsSession->Flush(); // check: short hang in UIQ2
  513. User::After(1);
  514. // I don't know why but the Window server sometimes hangs completely (hanging the phone too) after calling StartL()
  515. // Is this a sync broblem? weird bug?
  516. TRAP(ret, iDSA->StartL());
  517. if (ret) DEBUGPRINT(_L("iDSA->StartL() error: %i"), ret);
  518. // User::After(1);
  519. // CPolledActiveScheduler::Instance()->Schedule();
  520. DEBUGPRINT(_L("CGameWindow::ConstructResourcesL() finished."));
  521. }
  522. // this may be run even if there is nothing to free
  523. void CGameWindow::FreeResources()
  524. {
  525. if(gameAudio) gameAudio->Pause();
  526. //DEBUGPRINT(_L("CPolledActiveScheduler::Instance(): %08x"), CPolledActiveScheduler::Instance());
  527. if(CPolledActiveScheduler::Instance())
  528. CPolledActiveScheduler::Instance()->Schedule();
  529. #if 0
  530. // free RDirectScreenAccess stuff (seems to be deleted automatically after crash?)
  531. if(iDSA) {
  532. iDSA->Cancel();
  533. iDSA->Close();
  534. delete iDSA;
  535. }
  536. iDSA = NULL;
  537. #endif
  538. if(iDSA) delete iDSA;
  539. iDSA = 0;
  540. if(iWsSession->WsHandle() > 0 && iWsEventStatus != KRequestPending) // TODO: 2 UIQ2 (?)
  541. iWsSession->EventReadyCancel();
  542. if(iWsWindow.WsHandle() > 0)
  543. iWsWindow.Close();
  544. if(iWsWindowGroup.WsHandle() > 0)
  545. iWsWindowGroup.Close();
  546. // these must be deleted before calling iWsSession->Close()
  547. if(iWsScreen) {
  548. delete iWsScreen;
  549. iWsScreen = NULL;
  550. }
  551. if(iWsSession->WsHandle() > 0) {
  552. iWsSession->Close();
  553. delete iWsSession;
  554. }
  555. vidFree();
  556. }
  557. void CGameWindow::DoKeys(void)
  558. {
  559. TWsEvent iWsEvent;
  560. TInt iWsEventType;
  561. unsigned long allActions = 0;
  562. static unsigned long areaActions = 0, forceUpdate = 0;
  563. int i, nEvents;
  564. for(nEvents = 0; iWsEventStatus != KRequestPending; nEvents++)
  565. {
  566. iWsSession->GetEvent(iWsEvent);
  567. iWsEventType = iWsEvent.Type();
  568. // pointer events?
  569. if(iWsEventType == EEventPointer) {
  570. if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Up) {
  571. areaActions = 0; // remove all directionals
  572. } else { // if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Down) {
  573. TPoint p = iWsEvent.Pointer()->iPosition;
  574. const TPicoAreaConfigEntry *e = areaConfig + 1;
  575. for(i = 0; !e->rect.IsEmpty(); e++, i++)
  576. if(e->rect.Contains(p)) {
  577. areaActions = currentConfig.KeyBinds[i+256];
  578. break;
  579. }
  580. //DEBUGPRINT(_L("pointer event: %i %i"), p.iX, p.iY);
  581. }
  582. }
  583. else if(iWsEventType == EEventKeyDown || iWsEventType == EEventKeyUp) {
  584. TInt iScanCode = iWsEvent.Key()->iScanCode;
  585. //DEBUGPRINT(_L("key event: 0x%02x"), iScanCode);
  586. if(iScanCode < 256)
  587. {
  588. if(iWsEventType == EEventKeyDown) {
  589. keyFlags[iScanCode] |= 1;
  590. for(i=0; i < 10; i++) {
  591. if( pressedKeys[i] == (TUint8) iScanCode) break;
  592. if(!pressedKeys[i]) { pressedKeys[i] = (TUint8) iScanCode; break; }
  593. }
  594. } else if(!(keyFlags[iScanCode]&2)) {
  595. keyFlags[iScanCode] &= ~1;
  596. for(i=0; i < 10; i++) {
  597. if(pressedKeys[i] == (TUint8) iScanCode) { pressedKeys[i] = 0; break; }
  598. }
  599. }
  600. // power?
  601. if(iScanCode == EStdKeyOff) gamestate = PGS_Paused;
  602. } else {
  603. DEBUGPRINT(_L("weird scancode: 0x%02x"), iScanCode);
  604. }
  605. }
  606. else if(iWsEventType == EEventScreenDeviceChanged) {
  607. // ???
  608. //User::After(500000);
  609. //reset_timing = 1;
  610. DEBUGPRINT(_L("EEventScreenDeviceChanged, focus: %i, our: %i"),
  611. iWsSession->GetFocusWindowGroup(), iWsWindowGroup.Identifier());
  612. }
  613. else if(iWsEventType == EEventFocusGroupChanged) {
  614. TInt focusGrpId = iWsSession->GetFocusWindowGroup();
  615. DEBUGPRINT(_L("EEventFocusGroupChanged: %i, our: %i"),
  616. focusGrpId, iWsWindowGroup.Identifier());
  617. // if it is not us and not launcher that got focus, pause emu
  618. if(focusGrpId != iWsWindowGroup.Identifier())
  619. gamestate = PGS_Paused;
  620. }
  621. iWsEventStatus = KRequestPending;
  622. iWsSession->EventReady(&iWsEventStatus);
  623. }
  624. if(nEvents || forceUpdate) {
  625. allActions = areaActions;
  626. forceUpdate = 0;
  627. // add all pushed button actions
  628. for(i = 9; i >= 0; i--) {
  629. int scan = pressedKeys[i];
  630. if(scan) {
  631. if(keyFlags[scan] & 1) allActions |= currentConfig.KeyBinds[scan];
  632. if((keyFlags[scan]& 3)==3) forceUpdate = 1;
  633. if(keyFlags[scan] & 2) keyFlags[scan] &= ~1;
  634. }
  635. }
  636. PicoPad[0] = (unsigned short) allActions;
  637. if(allActions & 0xFFFF0000) {
  638. RunEvents(allActions >> 16);
  639. areaActions = 0;
  640. }
  641. }
  642. }
  643. void CGameWindow::DoKeysConfig(TUint &which)
  644. {
  645. TWsEvent iWsEvent;
  646. int i;
  647. while(iWsEventStatus != KRequestPending)
  648. {
  649. TUint currentActCode = 1 << which;
  650. iWsSession->GetEvent(iWsEvent);
  651. // pointer events?
  652. if(iWsEvent.Type() == EEventPointer) {
  653. TPoint p = iWsEvent.Pointer()->iPosition;
  654. TRect prev(56, 0, 120, 26);
  655. TRect next(120, 0, 180, 26);
  656. if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Down) {
  657. if(prev.Contains(p)) do { which = (which-1) & 0x1F; } while(!actionNames[which]);
  658. else if(next.Contains(p)) do { which = (which+1) & 0x1F; } while(!actionNames[which]);
  659. else if(which == 31) gamestate = PGS_Paused; // done
  660. else {
  661. const TPicoAreaConfigEntry *e = areaConfig + 1;
  662. for(i = 0; e->rect != TRect(0,0,0,0); e++, i++)
  663. if(e->rect.Contains(p)) {
  664. currentConfig.KeyBinds[i+256] ^= currentActCode;
  665. break;
  666. }
  667. }
  668. }
  669. }
  670. else if(iWsEvent.Type() == EEventKeyDown || iWsEvent.Type() == EEventKeyUp)
  671. {
  672. TUint scan = (TUint) iWsEvent.Key()->iScanCode;
  673. // key events?
  674. if(iWsEvent.Type() == EEventKeyDown) {
  675. if(which == 31) {
  676. gamestate = PGS_Paused;
  677. } else if (scan < 256) {
  678. if(!(keyFlags[scan]&0x40)) currentConfig.KeyBinds[scan] ^= currentActCode;
  679. }
  680. }
  681. // power?
  682. if(iWsEvent.Key()->iScanCode == EStdKeyOff) gamestate = PGS_Paused;
  683. }
  684. else if(iWsEvent.Type() == EEventFocusGroupChanged) {
  685. TInt focusGrpId = iWsSession->GetFocusWindowGroup();
  686. // if we lost focus, exit config mode
  687. if(focusGrpId != iWsWindowGroup.Identifier())
  688. gamestate = PGS_Paused;
  689. }
  690. // iWsEventStatus = KRequestPending;
  691. iWsSession->EventReady(&iWsEventStatus);
  692. }
  693. }
  694. void CGameWindow::RunEvents(TUint32 which)
  695. {
  696. if (which & 0x4000) currentConfig.Frameskip = -1;
  697. if (which & 0x2000) currentConfig.Frameskip = 8;
  698. if (which & 0x1800) { // save or load (but not both)
  699. if(PsndOut) gameAudio->Pause(); // this may take a while, so we pause sound output
  700. vidDrawNotice((which & 0x1000) ? "LOADING@GAME" : "SAVING@GAME");
  701. emu_SaveLoadGame(which & 0x1000, 0);
  702. if(PsndOut) PsndOut = gameAudio->ResumeL();
  703. reset_timing = 1;
  704. }
  705. if (which & 0x0400) gamestate = PGS_Paused;
  706. if (which & 0x0200) { // switch renderer
  707. if (!(currentConfig.scaling == TPicoConfig::PMFit &&
  708. (currentConfig.rotation == TPicoConfig::PRot0 || currentConfig.rotation == TPicoConfig::PRot180)))
  709. {
  710. PicoOpt^=0x10;
  711. vidInit(0, 1);
  712. strcpy(noticeMsg, (PicoOpt&0x10) ? "ALT@RENDERER" : "DEFAULT@RENDERER");
  713. gettimeofday(&noticeMsgTime, 0);
  714. }
  715. }
  716. if(which & 0x00c0) {
  717. if(which&0x0080) {
  718. state_slot -= 1;
  719. if(state_slot < 0) state_slot = 9;
  720. } else {
  721. state_slot += 1;
  722. if(state_slot > 9) state_slot = 0;
  723. }
  724. sprintf(noticeMsg, "SAVE@SLOT@%i@SELECTED", state_slot);
  725. gettimeofday(&noticeMsgTime, 0);
  726. }
  727. if(which & 0x0020) if(gameAudio) currentConfig.volume = gameAudio->ChangeVolume(0);
  728. if(which & 0x0010) if(gameAudio) currentConfig.volume = gameAudio->ChangeVolume(1);
  729. }
  730. extern "C" void emu_noticeMsgUpdated(void)
  731. {
  732. char *p = noticeMsg;
  733. while (*p) {
  734. if (*p == ' ') *p = '@';
  735. if (*p < '0' || *p > 'Z') { *p = 0; break; }
  736. p++;
  737. }
  738. gettimeofday(&noticeMsgTime, 0);
  739. }
  740. // static class members
  741. RWsSession* CGameWindow::iWsSession;
  742. RWindowGroup CGameWindow::iWsWindowGroup;
  743. RWindow CGameWindow::iWsWindow;
  744. CWsScreenDevice* CGameWindow::iWsScreen = NULL;
  745. CWindowGc* CGameWindow::iWindowGc = NULL;
  746. TRequestStatus CGameWindow::iWsEventStatus = KRequestPending;
  747. //RDirectScreenAccess* CGameWindow::iDSA;
  748. //TRequestStatus CGameWindow::iDSAstatus = KRequestPending;
  749. TPicoDirectScreenAccess CGameWindow::iPDSA;
  750. CDirectScreenAccess* CGameWindow::iDSA = NULL;