+// mainloop with window server event handling\r
+// event polling mechnism was taken from\r
+// Peter van Sebille's projects\r
+\r
+// (c) Copyright 2006, notaz\r
+// All Rights Reserved\r
+\r
+#include <e32base.h>\r
+#include <hal.h>\r
+#include <e32keys.h>\r
+#include <w32std.h>\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <sys/time.h>\r
+\r
+#include "debug.h"\r
+#include "../Engine.h"\r
+\r
+#include "../../../pico/picoInt.h"\r
+#include "vid.h"\r
+#include "polledAS.h"\r
+//#include "audio.h"\r
+#include "audio_mediaserver.h"\r
+\r
+#include <EZlib.h>\r
+#include "../../../zlib/gzio_symb.h"\r
+\r
+\r
+//#define BENCHMARK\r
+\r
+\r
+// scancodes we care about\r
+enum TUsedScanCodes {\r
+ EStdKeyM600JogUp = EStdKeyDevice1,\r
+ EStdKeyM600JogDown = EStdKeyDevice2,\r
+};\r
+\r
+static unsigned char keyFlags[256]; // lsb->msb: key_down, pulse_only, ?, ?, ?, ?, not_configurable, disabled\r
+static unsigned char pressedKeys[11]; // List of pressed key scancodes, up to 10\r
+\r
+// list of areas\r
+TPicoAreaConfigEntry areaConfig[] = {\r
+ { TRect( 0, 0, 0, 0) },\r
+ // small corner bottons\r
+ { TRect( 0, 0, 15, 15) },\r
+ { TRect(224, 0, 239, 15) },\r
+ { TRect( 0, 304, 15, 319) },\r
+ { TRect(224, 304, 239, 319) },\r
+ // normal buttons\r
+ { TRect( 0, 0, 79, 63) },\r
+ { TRect( 80, 0, 159, 63) },\r
+ { TRect(160, 0, 239, 63) },\r
+ { TRect( 0, 64, 79, 127) },\r
+ { TRect( 80, 64, 159, 127) },\r
+ { TRect(160, 64, 239, 127) },\r
+ { TRect( 0, 128, 79, 191) },\r
+ { TRect( 80, 128, 159, 191) },\r
+ { TRect(160, 128, 239, 191) },\r
+ { TRect( 0, 192, 79, 255) },\r
+ { TRect( 80, 192, 159, 255) },\r
+ { TRect(160, 192, 239, 255) },\r
+ { TRect( 0, 256, 79, 319) },\r
+ { TRect( 80, 256, 159, 319) },\r
+ { TRect(160, 256, 239, 319) },\r
+ { TRect( 0, 0, 0, 0) }\r
+};\r
+\r
+// PicoPad[] format: SACB RLDU\r
+const char *actionNames[] = {\r
+ "UP", "DOWN", "LEFT", "RIGHT", "B", "C", "A", "START",\r
+ 0, 0, 0, 0, 0, 0, 0, 0, // Z, Y, X, MODE (enabled only when needed), ?, ?, ?, ?\r
+ 0, 0, 0, 0, "VOLUME@UP", "VOLUME@DOWN", "NEXT@SAVE@SLOT", "PREV@SAVE@SLOT", // ?, ?, ?, ?, vol_up, vol_down, next_slot, prev_slot\r
+ 0, 0, "PAUSE@EMU", "SAVE@STATE", "LOAD@STATE", 0, 0, "DONE" // ?, switch_renderer, [...], "FRAMESKIP@8", "AUTO@FRAMESKIP"\r
+};\r
+\r
+\r
+// globals are allowed, so why not to (ab)use them?\r
+//TInt machineUid = 0;\r
+int gamestate = PGS_Paused, gamestate_next = PGS_Paused;\r
+TPicoConfig *currentConfig = 0;\r
+static char noticeMsg[64]; // notice msg to draw\r
+static timeval noticeMsgTime = { 0, 0 }; // when started showing\r
+static CGameAudioMS *gameAudio = 0; // the audio object itself\r
+static int reset_timing, pico_was_reset;\r
+static int state_slot = 0;\r
+extern const char *RomFileName;\r
+extern RSemaphore initSemaphore;\r
+extern RSemaphore pauseSemaphore;\r
+\r
+// some forward declarations\r
+static void MainInit();\r
+static void MainExit();\r
+static void DumpMemInfo();\r
+void MainOldCleanup();\r
+\r
+\r
+class TPicoDirectScreenAccess : public MDirectScreenAccess\r
+{\r
+public: // implements MDirectScreenAccess\r
+ void Restart(RDirectScreenAccess::TTerminationReasons aReason);\r
+public: // implements MAbortDirectScreenAccess\r
+ void AbortNow(RDirectScreenAccess::TTerminationReasons aReason);\r
+};\r
+\r
+\r
+// just for a nicer grouping of WS related stuff\r
+class CGameWindow\r
+{\r
+public:\r
+ static void ConstructResourcesL(void);\r
+ static void FreeResources(void);\r
+ static void DoKeys(void);\r
+ static void DoKeysConfig(TUint &which);\r
+ static void RunEvents(TUint32 which);\r
+\r
+ static RWsSession* iWsSession;\r
+ static RWindowGroup iWsWindowGroup;\r
+ static RWindow iWsWindow;\r
+ static CWsScreenDevice* iWsScreen;\r
+ static CWindowGc* iWindowGc;\r
+ static TRequestStatus iWsEventStatus;\r
+// static TThreadId iLauncherThreadId;\r
+// static RDirectScreenAccess* iDSA;\r
+// static TRequestStatus iDSAstatus;\r
+ static TPicoDirectScreenAccess iPDSA;\r
+ static CDirectScreenAccess* iDSA;\r
+};\r
+\r
+\r
+static int snd_excess_add = 0, snd_excess_cnt = 0; // hack\r
+\r
+static void updateSound(void)\r
+{\r
+ int len = PsndLen;\r
+\r
+ snd_excess_cnt += snd_excess_add;\r
+ if (snd_excess_cnt >= 0x10000) {\r
+ snd_excess_cnt -= 0x10000;\r
+ if (PicoOpt&8) {\r
+ PsndOut[len*2] = PsndOut[len*2-2];\r
+ PsndOut[len*2+1] = PsndOut[len*2-1];\r
+ } else {\r
+ PsndOut[len] = PsndOut[len-1];\r
+ }\r
+ len++;\r
+ }\r
+\r
+ PsndOut = gameAudio->NextFrameL(len);\r
+ if(!PsndOut) { // sound output problems?\r
+ strcpy(noticeMsg, "SOUND@OUTPUT@ERROR;@SOUND@DISABLED");\r
+ gettimeofday(¬iceMsgTime, 0);\r
+ }\r
+}\r
+\r
+\r
+static void SkipFrame(void)\r
+{\r
+ PicoSkipFrame=1;\r
+ PicoFrame();\r
+ PicoSkipFrame=0;\r
+}\r
+\r
+\r
+static void simpleWait(int thissec, int lim_time)\r
+{\r
+ struct timeval tval;\r
+ int sleep = 0;\r
+\r
+ gettimeofday(&tval, 0);\r
+ if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
+\r
+ sleep = lim_time - tval.tv_usec - 2000;\r
+ if (sleep > 0) {\r
+// User::After((sleep = lim_time - tval.tv_usec));\r
+ User::AfterHighRes(sleep);\r
+ }\r
+}\r
+\r
+\r
+static void TargetEpocGameL()\r
+{\r
+ char buff[24]; // fps count c string\r
+ struct timeval tval; // timing\r
+ int thissec = 0, frames_done = 0, frames_shown = 0;\r
+ int target_fps, target_frametime;\r
+ int i, lim_time;\r
+ //TRawEvent blevent;\r
+\r
+ MainInit();\r
+ buff[0] = 0;\r
+\r
+ // just to keep the backlight on (works only on UIQ2)\r
+ //blevent.Set(TRawEvent::EActive);\r
+\r
+ // loop?\r
+ for(;;) {\r
+ if(gamestate == PGS_Running) {\r
+ // switch context to other thread\r
+ User::After(50000);\r
+ // prepare window and stuff\r
+ CGameWindow::ConstructResourcesL();\r
+\r
+ // if the system has something to do, it should better do it now\r
+ User::After(50000);\r
+ //CPolledActiveScheduler::Instance()->Schedule();\r
+\r
+ // pal/ntsc might have changed, reset related stuff\r
+ if(Pico.m.pal) {\r
+ target_fps = 50;\r
+ if(!noticeMsgTime.tv_sec) strcpy(noticeMsg, "PAL@SYSTEM@/@50@FPS");\r
+ } else {\r
+ target_fps = 60;\r
+ if(!noticeMsgTime.tv_sec) strcpy(noticeMsg, "NTSC@SYSTEM@/@60@FPS");\r
+ }\r
+ target_frametime = 1000000/target_fps;\r
+ if(!noticeMsgTime.tv_sec && pico_was_reset)\r
+ gettimeofday(¬iceMsgTime, 0);\r
+\r
+ if (PsndOut) {\r
+ snd_excess_cnt = 0;\r
+ snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;\r
+ }\r
+\r
+ pico_was_reset = 0;\r
+ reset_timing = 1;\r
+\r
+ while(gamestate == PGS_Running) {\r
+ gettimeofday(&tval, 0);\r
+ if(reset_timing) {\r
+ reset_timing = 0;\r
+ thissec = tval.tv_sec;\r
+ frames_done = tval.tv_usec/target_frametime;\r
+ }\r
+\r
+ // show notice message?\r
+ char *notice = 0;\r
+ if(noticeMsgTime.tv_sec) {\r
+ if((tval.tv_sec*1000000+tval.tv_usec) - (noticeMsgTime.tv_sec*1000000+noticeMsgTime.tv_usec) > 2000000) // > 2.0 sec\r
+ noticeMsgTime.tv_sec = noticeMsgTime.tv_usec = 0;\r
+ else notice = noticeMsg;\r
+ }\r
+\r
+ // second changed?\r
+ if(thissec != tval.tv_sec) {\r
+#ifdef BENCHMARK\r
+ static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];\r
+ if(++bench == 10) {\r
+ bench = 0;\r
+ bench_fps_s = bench_fps;\r
+ bf[bfp++ & 3] = bench_fps;\r
+ bench_fps = 0;\r
+ }\r
+ bench_fps += frames_shown;\r
+ sprintf(buff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);\r
+#else\r
+ if(currentConfig->iFlags & 2) \r
+ sprintf(buff, "%02i/%02i", frames_shown, frames_done);\r
+#endif\r
+\r
+\r
+ thissec = tval.tv_sec;\r
+\r
+ if(PsndOut == 0 && currentConfig->iFrameskip >= 0) {\r
+ frames_done = frames_shown = 0;\r
+ } else {\r
+ // it is quite common for this implementation to leave 1 fame unfinished\r
+ // when second changes, but we don't want buffer to starve.\r
+ if(PsndOut && frames_done < target_fps && frames_done > target_fps-5) {\r
+ SkipFrame(); frames_done++;\r
+ }\r
+\r
+ frames_done -= target_fps; if (frames_done < 0) frames_done = 0;\r
+ frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;\r
+ if (frames_shown > frames_done) frames_shown = frames_done;\r
+ }\r
+ }\r
+\r
+\r
+ lim_time = (frames_done+1) * target_frametime;\r
+ if(currentConfig->iFrameskip >= 0) { // frameskip enabled\r
+ for(i = 0; i < currentConfig->iFrameskip; i++) {\r
+ CGameWindow::DoKeys();\r
+ SkipFrame(); frames_done++;\r
+ if (PsndOut) { // do framelimitting if sound is enabled\r
+ gettimeofday(&tval, 0);\r
+ if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
+ if(tval.tv_usec < lim_time) { // we are too fast\r
+ simpleWait(thissec, lim_time);\r
+ }\r
+ }\r
+ lim_time += target_frametime;\r
+ }\r
+ } else if(tval.tv_usec > lim_time) { // auto frameskip\r
+ // no time left for this frame - skip\r
+ CGameWindow::DoKeys();\r
+ SkipFrame(); frames_done++;\r
+ continue;\r
+ }\r
+\r
+ CGameWindow::DoKeys();\r
+ PicoFrame();\r
+\r
+ // check time\r
+ gettimeofday(&tval, 0);\r
+ if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
+\r
+ // sleep if we are still too fast\r
+ if(PsndOut != 0 || currentConfig->iFrameskip < 0)\r
+ {\r
+ // TODO: check if User::After() is accurate\r
+ gettimeofday(&tval, 0);\r
+ if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
+ if(tval.tv_usec < lim_time)\r
+ {\r
+ // we are too fast\r
+ simpleWait(thissec, lim_time);\r
+ }\r
+ }\r
+\r
+ CPolledActiveScheduler::Instance()->Schedule();\r
+\r
+ if (gamestate != PGS_Paused)\r
+ vidDrawFrame(notice, buff, frames_shown);\r
+\r
+ frames_done++; frames_shown++;\r
+ }\r
+\r
+ // save SRAM\r
+ if((currentConfig->iFlags & 1) && SRam.changed) {\r
+ saveLoadGame(0, 1);\r
+ SRam.changed = 0;\r
+ }\r
+ CGameWindow::FreeResources();\r
+ } else if(gamestate == PGS_Paused) {\r
+ DEBUGPRINT(_L("pausing.."));\r
+ pauseSemaphore.Wait();\r
+ } else if(gamestate == PGS_KeyConfig) {\r
+ // switch context to other thread\r
+ User::After(50000);\r
+ // prepare window and stuff\r
+ CGameWindow::ConstructResourcesL();\r
+\r
+ TUint whichAction = 0;\r
+ while(gamestate == PGS_KeyConfig) {\r
+ CGameWindow::DoKeysConfig(whichAction);\r
+ CPolledActiveScheduler::Instance()->Schedule();\r
+ if (gamestate != PGS_Paused)\r
+ vidKeyConfigFrame(whichAction);\r
+ User::After(150000);\r
+ }\r
+\r
+ CGameWindow::FreeResources();\r
+ } else if(gamestate == PGS_DebugHeap) {\r
+ #ifdef __DEBUG_PRINT\r
+ TInt cells = User::CountAllocCells();\r
+ TInt mem;\r
+ User::AllocSize(mem);\r
+ DEBUGPRINT(_L("worker: cels=%d, size=%d KB"), cells, mem/1024);\r
+ gamestate = gamestate_next;\r
+ #endif\r
+ } else if(gamestate == PGS_Quit) {\r
+ break;\r
+ }\r
+ }\r
+\r
+ MainExit();\r
+}\r
+\r
+\r
+// main initialization\r
+static void MainInit()\r
+{\r
+ DEBUGPRINT(_L("\r\n\r\nstarting.."));\r
+\r
+ // our thread might have been crashed previously, so many other objects may be still floating around\r
+ MainOldCleanup();\r
+\r
+ DEBUGPRINT(_L("CPolledActiveScheduler::NewL()"));\r
+ CPolledActiveScheduler::NewL(); // create Polled AS for the sound engine\r
+\r
+// HAL::Get(HALData::EMachineUid, machineUid); // find out the machine UID\r
+\r
+ DumpMemInfo();\r
+\r
+ // try to start pico\r
+ DEBUGPRINT(_L("PicoInit();"));\r
+ PicoInit();\r
+ PicoDrawSetColorFormat(2);\r
+ PicoWriteSound = updateSound;\r
+\r
+// if (pauseSemaphore.Handle() <= 0)\r
+// pauseSemaphore.CreateLocal(0);\r
+ DEBUGPRINT(_L("initSemaphore.Signal()"));\r
+ initSemaphore.Signal();\r
+}\r
+\r
+\r
+// does not return\r
+static void MainExit()\r
+{\r
+ RThread thisThread;\r
+\r
+ DEBUGPRINT(_L("%i: cleaning up.."), (TInt32) thisThread.Id());\r
+\r
+ // save SRAM\r
+ if((currentConfig->iFlags & 1) && SRam.changed) {\r
+ saveLoadGame(0, 1);\r
+ SRam.changed = 0;\r
+ }\r
+\r
+ PicoExit();\r
+// pauseSemaphore.Close();\r
+\r
+ if(gameAudio) delete gameAudio;\r
+\r
+ // Polled AS\r
+ delete CPolledActiveScheduler::Instance();\r
+}\r
+\r
+void MainOldCleanup()\r
+{\r
+ DEBUGPRINT(_L("MainOldCleanup.."));\r
+\r
+ // There was previously a handle leak here, so thread stuff was not cleaned\r
+ // and I thought I would have to do it mself.\r
+\r
+ // clean any resources which might be left after a thread crash\r
+ //CGameWindow::FreeResources(ETrue);\r
+\r
+ //if(CPolledActiveScheduler::Instance())\r
+ // delete CPolledActiveScheduler::Instance();\r
+}\r
+\r
+static void DumpMemInfo()\r
+{\r
+ TInt ramSize, ramSizeFree, romSize;\r
+ \r
+ HAL::Get(HALData::EMemoryRAM, ramSize);\r
+ HAL::Get(HALData::EMemoryRAMFree, ramSizeFree);\r
+ HAL::Get(HALData::EMemoryROM, romSize);\r
+\r
+ DEBUGPRINT(_L("ram=%dKB, ram_free=%dKB, rom=%dKB"), ramSize/1024, ramSizeFree/1024, romSize/1024);\r
+}\r
+\r
+\r
+TInt EmuThreadFunction(TAny*)\r
+{\r
+ const TUint32 exs = KExceptionAbort|KExceptionKill|KExceptionUserInterrupt|KExceptionFpe|KExceptionFault|KExceptionInteger|KExceptionDebug;\r
+ \r
+ DEBUGPRINT(_L("EmuThreadFunction()"));\r
+ User::SetExceptionHandler(ExceptionHandler, exs/*(TUint32) -1*/); // does not work?\r
+\r
+ //TInt pc, sp;\r
+ //asm volatile ("str pc, %0" : "=m" (pc) );\r
+ //asm volatile ("str sp, %0" : "=m" (sp) );\r
+ //RDebug::Print(_L("executing @ 0x%08x, sp=0x%08x"), pc, sp);\r
+\r
+/*\r
+ RDebug::Print(_L("Base Bottom Top Size RW Name"));\r
+ TBuf<4> l_r(_L("R")), l_w(_L("W")), l_d(_L("-"));\r
+ RChunk chunk;\r
+ TFullName chunkname;\r
+ TFindChunk findChunk(_L("*"));\r
+ while( findChunk.Next(chunkname) != KErrNotFound ) {\r
+ chunk.Open(findChunk);\r
+ 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);\r
+ chunk.Close();\r
+ }\r
+*/\r
+\r
+ // can't do that, will crash here\r
+// if(cleanup) {\r
+// DEBUGPRINT(_L("found old CTrapCleanup, deleting.."));\r
+// delete cleanup;\r
+// }\r
+ \r
+ CTrapCleanup *cleanup = CTrapCleanup::New();\r
+\r
+ TRAPD(error, TargetEpocGameL());\r
+\r
+ __ASSERT_ALWAYS(!error, User::Panic(_L("Picosmall"), error));\r
+ delete cleanup;\r
+\r
+ DEBUGPRINT(_L("exitting..")); \r
+ return 1;\r
+}\r
+\r
+\r
+void TPicoDirectScreenAccess::Restart(RDirectScreenAccess::TTerminationReasons aReason)\r
+{\r
+ DEBUGPRINT(_L("TPicoDirectScreenAccess::Restart(%i)"), aReason);\r
+\r
+// if (CGameWindow::iDSA) {\r
+// TRAPD(error, CGameWindow::iDSA->StartL());\r
+// if (error) DEBUGPRINT(_L("iDSA->StartL() error: %i"), error);\r
+// }\r
+}\r
+\r
+\r
+void TPicoDirectScreenAccess::AbortNow(RDirectScreenAccess::TTerminationReasons aReason)\r
+{\r
+ DEBUGPRINT(_L("TPicoDirectScreenAccess::AbortNow(%i)"), aReason);\r
+\r
+ // the WS wants us to stop, so let's obey\r
+ gamestate = PGS_Paused;\r
+}\r
+\r
+\r
+void CGameWindow::ConstructResourcesL()\r
+{\r
+ DEBUGPRINT(_L("ConstructResourcesL()"));\r
+ // connect to window server\r
+ // tried to create it globally and not re-connect everytime,\r
+ // but my window started to lose focus strangely\r
+ iWsSession = new(ELeave) RWsSession();\r
+ User::LeaveIfError(iWsSession->Connect());\r
+\r
+ // * Tell the Window Server not to mess about with our process priority\r
+ // * Also, because of the way legacy games are written, they never sleep\r
+ // * and thus never voluntarily yield the CPU. We set our process priority\r
+ // * to EPriorityForeground and hope that a Telephony application on\r
+ // * this device runs at EPriorityForeground as well. If not, tough! ;-)\r
+\r
+ iWsSession->ComputeMode(RWsSession::EPriorityControlDisabled);\r
+ RProcess me;\r
+ me.SetPriority(EPriorityForeground);\r
+\r
+ iWsScreen = new(ELeave) CWsScreenDevice(*iWsSession);\r
+ User::LeaveIfError(iWsScreen->Construct());\r
+// User::LeaveIfError(iWsScreen->CreateContext(iWindowGc));\r
+\r
+ iWsWindowGroup = RWindowGroup(*iWsSession);\r
+ User::LeaveIfError(iWsWindowGroup.Construct((TUint32)&iWsWindowGroup));\r
+ //iWsWindowGroup.SetOrdinalPosition(0);\r
+ //iWsWindowGroup.SetName(KServerWGName);\r
+ iWsWindowGroup.EnableScreenChangeEvents(); // flip events (EEventScreenDeviceChanged)\r
+ iWsWindowGroup.EnableFocusChangeEvents(); // EEventFocusGroupChanged\r
+ iWsWindowGroup.SetOrdinalPosition(0, 1); // TInt aPos, TInt aOrdinalPriority\r
+\r
+ iWsWindow=RWindow(*iWsSession);\r
+ User::LeaveIfError(iWsWindow.Construct(iWsWindowGroup, (TUint32)&iWsWindow));\r
+ iWsWindow.SetSize(iWsScreen->SizeInPixels());\r
+ iWsWindow.PointerFilter(EPointerFilterDrag, 0);\r
+ iWsWindow.SetPointerGrab(ETrue);\r
+ iWsWindow.SetVisible(ETrue);\r
+ iWsWindow.Activate();\r
+\r
+#if 0\r
+ // request access through RDirectScreenAccess api, but don't care about the result\r
+ // hangs?\r
+ RRegion *dsa_region = 0;\r
+ iDSA = new(ELeave) RDirectScreenAccess(*iWsSession);\r
+ if(iDSA->Construct() == KErrNone)\r
+ iDSA->Request(dsa_region, iDSAstatus, iWsWindow);\r
+ DEBUGPRINT(_L("DSA: %i"), dsa_region ? dsa_region->Count() : -1);\r
+#endif\r
+\r
+ TInt ret;\r
+\r
+ // request access through CDirectScreenAccess\r
+ iDSA = CDirectScreenAccess::NewL(*iWsSession, *iWsScreen, iWsWindow, iPDSA);\r
+\r
+ // now get the screenbuffer\r
+ TScreenInfoV01 screenInfo;\r
+ TPckg<TScreenInfoV01> sI(screenInfo);\r
+ UserSvr::ScreenInfo(sI);\r
+\r
+ if(!screenInfo.iScreenAddressValid)\r
+ User::Leave(KErrNotSupported);\r
+\r
+ DEBUGPRINT(_L("framebuffer=0x%08x (%dx%d)"), screenInfo.iScreenAddress,\r
+ screenInfo.iScreenSize.iWidth, screenInfo.iScreenSize.iHeight);\r
+ \r
+ // vidInit\r
+ DEBUGPRINT(_L("vidInit()"));\r
+ ret = vidInit((void *)screenInfo.iScreenAddress, 0);\r
+ DEBUGPRINT(_L("vidInit() done (%i)"), ret);\r
+\r
+ User::LeaveIfError(ret);\r
+\r
+ memset(keyFlags, 0, 256);\r
+ keyFlags[EStdKeyM600JogUp] = keyFlags[EStdKeyM600JogDown] = 2; // add "pulse only" for jog up/down\r
+ keyFlags[EStdKeyOff] = 0x40; // not configurable\r
+\r
+ // try to start the audio engine\r
+ static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;\r
+\r
+ if(gamestate == PGS_Running && (currentConfig->iFlags & 4)) {\r
+ TInt err = 0;\r
+ if(PsndRate != PsndRate_old || (PicoOpt&11) != (PicoOpt_old&11) || Pico.m.pal != pal_old) {\r
+ // if rate changed, reset all enabled chips, else reset only those chips, which were recently enabled\r
+ //sound_reset(PsndRate != PsndRate_old ? PicoOpt : (PicoOpt&(PicoOpt^PicoOpt_old)));\r
+ sound_rerate();\r
+ }\r
+ if(!gameAudio || PsndRate != PsndRate_old || ((PicoOpt&8) ^ (PicoOpt_old&8)) || Pico.m.pal != pal_old) { // rate or stereo or pal/ntsc changed\r
+ if(gameAudio) delete gameAudio; gameAudio = 0;\r
+ DEBUGPRINT(_L("starting audio: %i len: %i stereo: %i, pal: %i"), PsndRate, PsndLen, PicoOpt&8, Pico.m.pal);\r
+ TRAP(err, gameAudio = CGameAudioMS::NewL(PsndRate, (PicoOpt&8) ? 1 : 0, Pico.m.pal ? 50 : 60));\r
+ }\r
+ if( gameAudio) {\r
+ TRAP(err, PsndOut = gameAudio->ResumeL());\r
+ }\r
+ if(err) {\r
+ if(gameAudio) delete gameAudio;\r
+ gameAudio = 0;\r
+ PsndOut = 0;\r
+ strcpy(noticeMsg, "SOUND@STARTUP@FAILED");\r
+ gettimeofday(¬iceMsgTime, 0);\r
+ }\r
+ PsndRate_old = PsndRate;\r
+ PicoOpt_old = PicoOpt;\r
+ pal_old = Pico.m.pal;\r
+ } else {\r
+ if(gameAudio) delete gameAudio;\r
+ gameAudio = 0;\r
+ PsndOut = 0;\r
+ }\r
+\r
+ CPolledActiveScheduler::Instance()->Schedule();\r
+\r
+ // start key WS event polling\r
+ iWsSession->EventReady(&iWsEventStatus);\r
+\r
+ iWsSession->Flush(); // check: short hang in UIQ2\r
+ User::After(1);\r
+\r
+ // I don't know why but the Window server sometimes hangs completely (hanging the phone too) after calling StartL()\r
+ // Is this a sync broblem? weird bug?\r
+ TRAP(ret, iDSA->StartL());\r
+ if (ret) DEBUGPRINT(_L("iDSA->StartL() error: %i"), ret);\r
+\r
+// User::After(1);\r
+// CPolledActiveScheduler::Instance()->Schedule();\r
+\r
+ DEBUGPRINT(_L("CGameWindow::ConstructResourcesL() finished."));\r
+}\r
+\r
+// this may be run even if there is nothing to free\r
+void CGameWindow::FreeResources()\r
+{\r
+ if(gameAudio) gameAudio->Pause();\r
+\r
+ //DEBUGPRINT(_L("CPolledActiveScheduler::Instance(): %08x"), CPolledActiveScheduler::Instance());\r
+ if(CPolledActiveScheduler::Instance())\r
+ CPolledActiveScheduler::Instance()->Schedule();\r
+\r
+#if 0\r
+ // free RDirectScreenAccess stuff (seems to be deleted automatically after crash?)\r
+ if(iDSA) {\r
+ iDSA->Cancel();\r
+ iDSA->Close();\r
+ delete iDSA;\r
+ }\r
+ iDSA = NULL;\r
+#endif\r
+ if(iDSA) delete iDSA;\r
+ iDSA = 0;\r
+\r
+ if(iWsSession->WsHandle() > 0 && iWsEventStatus != KRequestPending) // TODO: 2 UIQ2 (?)\r
+ iWsSession->EventReadyCancel();\r
+\r
+ if(iWsWindow.WsHandle() > 0)\r
+ iWsWindow.Close();\r
+\r
+ if(iWsWindowGroup.WsHandle() > 0)\r
+ iWsWindowGroup.Close();\r
+\r
+ // these must be deleted before calling iWsSession->Close()\r
+ if(iWsScreen) {\r
+ delete iWsScreen;\r
+ iWsScreen = NULL;\r
+ }\r
+\r
+ if(iWsSession->WsHandle() > 0) {\r
+ iWsSession->Close();\r
+ delete iWsSession;\r
+ }\r
+ \r
+ vidFree();\r
+\r
+ // emu might change renderer by itself, so we may need to sync config\r
+ if(currentConfig && currentConfig->iPicoOpt != PicoOpt) {\r
+ currentConfig->iFlags |= 0x80;\r
+ }\r
+}\r
+\r
+\r
+void CGameWindow::DoKeys(void)\r
+{\r
+ TWsEvent iWsEvent;\r
+ TInt iWsEventType;\r
+ unsigned long allActions = 0;\r
+ static unsigned long areaActions = 0, forceUpdate = 0;\r
+ int i, nEvents;\r
+\r
+ for(nEvents = 0; iWsEventStatus != KRequestPending; nEvents++)\r
+ {\r
+ iWsSession->GetEvent(iWsEvent);\r
+ iWsEventType = iWsEvent.Type();\r
+\r
+ // pointer events?\r
+ if(iWsEventType == EEventPointer) {\r
+ if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Up) {\r
+ areaActions = 0; // remove all directionals\r
+ } else { // if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Down) {\r
+ TPoint p = iWsEvent.Pointer()->iPosition;\r
+ const TPicoAreaConfigEntry *e = areaConfig + 1;\r
+ for(i = 0; !e->rect.IsEmpty(); e++, i++)\r
+ if(e->rect.Contains(p)) {\r
+ areaActions = currentConfig->iAreaBinds[i];\r
+ break;\r
+ }\r
+ //DEBUGPRINT(_L("pointer event: %i %i"), p.iX, p.iY);\r
+ }\r
+ }\r
+ else if(iWsEventType == EEventKeyDown || iWsEventType == EEventKeyUp) {\r
+ TInt iScanCode = iWsEvent.Key()->iScanCode;\r
+ //DEBUGPRINT(_L("key event: 0x%02x"), iScanCode);\r
+\r
+ if(iScanCode < 256)\r
+ {\r
+ if(iWsEventType == EEventKeyDown) {\r
+ keyFlags[iScanCode] |= 1;\r
+ for(i=0; i < 10; i++) {\r
+ if( pressedKeys[i] == (TUint8) iScanCode) break;\r
+ if(!pressedKeys[i]) { pressedKeys[i] = (TUint8) iScanCode; break; }\r
+ }\r
+ } else if(!(keyFlags[iScanCode]&2)) {\r
+ keyFlags[iScanCode] &= ~1;\r
+ for(i=0; i < 10; i++) {\r
+ if(pressedKeys[i] == (TUint8) iScanCode) { pressedKeys[i] = 0; break; }\r
+ }\r
+ }\r
+\r
+ // power?\r
+ if(iScanCode == EStdKeyOff) gamestate = PGS_Paused;\r
+ } else {\r
+ DEBUGPRINT(_L("weird scancode: 0x%02x"), iScanCode);\r
+ }\r
+ }\r
+ else if(iWsEventType == EEventScreenDeviceChanged) {\r
+ // ???\r
+ //User::After(500000);\r
+ //reset_timing = 1;\r
+ DEBUGPRINT(_L("EEventScreenDeviceChanged, focus: %i, our: %i"),\r
+ iWsSession->GetFocusWindowGroup(), iWsWindowGroup.Identifier());\r
+ }\r
+ else if(iWsEventType == EEventFocusGroupChanged) {\r
+ TInt focusGrpId = iWsSession->GetFocusWindowGroup();\r
+ DEBUGPRINT(_L("EEventFocusGroupChanged: %i, our: %i"),\r
+ focusGrpId, iWsWindowGroup.Identifier());\r
+ // if it is not us and not launcher that got focus, pause emu\r
+ if(focusGrpId != iWsWindowGroup.Identifier())\r
+ gamestate = PGS_Paused;\r
+ }\r
+\r
+ iWsEventStatus = KRequestPending;\r
+ iWsSession->EventReady(&iWsEventStatus);\r
+ }\r
+\r
+ if(nEvents || forceUpdate) {\r
+ allActions = areaActions;\r
+ forceUpdate = 0;\r
+\r
+ // add all pushed button actions\r
+ for(i = 9; i >= 0; i--) {\r
+ int scan = pressedKeys[i];\r
+ if(scan) {\r
+ if(keyFlags[scan] & 1) allActions |= currentConfig->iKeyBinds[scan];\r
+ if((keyFlags[scan]& 3)==3) forceUpdate = 1;\r
+ if(keyFlags[scan] & 2) keyFlags[scan] &= ~1;\r
+ }\r
+ }\r
+\r
+ PicoPad[0] = (unsigned short) allActions;\r
+ if(allActions & 0xFFFF0000) {\r
+ RunEvents(allActions >> 16);\r
+ areaActions = 0;\r
+ }\r
+ }\r
+}\r
+\r
+\r
+void CGameWindow::DoKeysConfig(TUint &which)\r
+{\r
+ TWsEvent iWsEvent;\r
+ int i;\r
+\r
+ while(iWsEventStatus != KRequestPending)\r
+ {\r
+ TUint currentActCode = 1 << which;\r
+\r
+ iWsSession->GetEvent(iWsEvent);\r
+\r
+ // pointer events?\r
+ if(iWsEvent.Type() == EEventPointer) {\r
+ TPoint p = iWsEvent.Pointer()->iPosition;\r
+ TRect prev(56, 0, 120, 26);\r
+ TRect next(120, 0, 180, 26);\r
+\r
+ if(iWsEvent.Pointer()->iType == TPointerEvent::EButton1Down) {\r
+ if(prev.Contains(p)) do { which = (which-1) & 0x1F; } while(!actionNames[which]);\r
+ else if(next.Contains(p)) do { which = (which+1) & 0x1F; } while(!actionNames[which]);\r
+ else if(which == 31) gamestate = PGS_Paused; // done\r
+ else {\r
+ const TPicoAreaConfigEntry *e = areaConfig + 1;\r
+ for(i = 0; e->rect != TRect(0,0,0,0); e++, i++)\r
+ if(e->rect.Contains(p)) {\r
+ currentConfig->iAreaBinds[i] ^= currentActCode;\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ else if(iWsEvent.Type() == EEventKeyDown || iWsEvent.Type() == EEventKeyUp)\r
+ {\r
+ TUint scan = (TUint) iWsEvent.Key()->iScanCode;\r
+\r
+ // key events?\r
+ if(iWsEvent.Type() == EEventKeyDown) {\r
+ if(which == 31) {\r
+ gamestate = PGS_Paused;\r
+ } else if (scan < 256) {\r
+ if(!(keyFlags[scan]&0x40)) currentConfig->iKeyBinds[scan] ^= currentActCode;\r
+ }\r
+ }\r
+\r
+ // power?\r
+ if(iWsEvent.Key()->iScanCode == EStdKeyOff) gamestate = PGS_Paused;\r
+ }\r
+ else if(iWsEvent.Type() == EEventFocusGroupChanged) {\r
+ TInt focusGrpId = iWsSession->GetFocusWindowGroup();\r
+ // if we lost focus, exit config mode\r
+ if(focusGrpId != iWsWindowGroup.Identifier())\r
+ gamestate = PGS_Paused;\r
+ }\r
+\r
+// iWsEventStatus = KRequestPending;\r
+ iWsSession->EventReady(&iWsEventStatus);\r
+ }\r
+}\r
+\r
+\r
+void CGameWindow::RunEvents(TUint32 which)\r
+{\r
+ if(which & 0x4000) currentConfig->iFrameskip = -1;\r
+ if(which & 0x2000) currentConfig->iFrameskip = 8;\r
+ if(which & 0x1800) { // save or load (but not both)\r
+ if(PsndOut) gameAudio->Pause(); // this may take a while, so we pause sound output\r
+\r
+ vidDrawNotice((which & 0x1000) ? "LOADING@GAME" : "SAVING@GAME");\r
+ saveLoadGame(which & 0x1000);\r
+\r
+ if(PsndOut) PsndOut = gameAudio->ResumeL();\r
+ reset_timing = 1;\r
+ }\r
+ if(which & 0x0400) gamestate = PGS_Paused;\r
+ if(which & 0x0200) { // switch renderer\r
+ if(!(currentConfig->iScreenMode == TPicoConfig::PMFit &&\r
+ (currentConfig->iScreenRotation == TPicoConfig::PRot0 || currentConfig->iScreenRotation == TPicoConfig::PRot180))) {\r
+\r
+ PicoOpt^=0x10;\r
+ vidInit(0, 1);\r
+\r
+ strcpy(noticeMsg, (PicoOpt&0x10) ? "ALT@RENDERER" : "DEFAULT@RENDERER");\r
+ gettimeofday(¬iceMsgTime, 0);\r
+ }\r
+ }\r
+ if(which & 0x00c0) {\r
+ if(which&0x0080) {\r
+ state_slot -= 1;\r
+ if(state_slot < 0) state_slot = 9;\r
+ } else {\r
+ state_slot += 1;\r
+ if(state_slot > 9) state_slot = 0;\r
+ }\r
+ sprintf(noticeMsg, "SAVE@SLOT@%i@SELECTED", state_slot);\r
+ gettimeofday(¬iceMsgTime, 0);\r
+ }\r
+ if(which & 0x0020) if(gameAudio) gameAudio->ChangeVolume(0);\r
+ if(which & 0x0010) if(gameAudio) gameAudio->ChangeVolume(1);\r
+}\r
+\r
+\r
+// must use wrappers, or else will run into some weird loader error (see pico/area.c)\r
+static size_t fRead2(void *p, size_t _s, size_t _n, void *file)\r
+{\r
+ return fread(p, _s, _n, (FILE *) file);\r
+}\r
+\r
+static size_t fWrite2(void *p, size_t _s, size_t _n, void *file)\r
+{\r
+ return fwrite(p, _s, _n, (FILE *) file);\r
+}\r
+\r
+static size_t gzRead2(void *p, size_t, size_t _n, void *file)\r
+{\r
+ return gzread(file, p, _n);\r
+}\r
+\r
+static size_t gzWrite2(void *p, size_t, size_t _n, void *file)\r
+{\r
+ return gzwrite(file, p, _n);\r
+}\r
+\r
+\r
+// this function is shared between both threads\r
+int saveLoadGame(int load, int sram)\r
+{\r
+ int res = 0;\r
+\r
+ if(!RomFileName) return -1;\r
+\r
+ // make save filename\r
+ char saveFname[KMaxFileName];\r
+ strcpy(saveFname, RomFileName);\r
+ saveFname[KMaxFileName-8] = 0;\r
+ if(saveFname[strlen(saveFname)-4] == '.') saveFname[strlen(saveFname)-4] = 0;\r
+ if(sram) strcat(saveFname, ".srm");\r
+ else {\r
+ if(state_slot > 0 && state_slot < 10) sprintf(saveFname, "%s.%i", saveFname, state_slot);\r
+ strcat(saveFname, ".mds");\r
+ }\r
+\r
+ DEBUGPRINT(_L("saveLoad (%i, %i): %S"), load, sram, DO_CONV(saveFname));\r
+\r
+ if(sram) {\r
+ FILE *sramFile;\r
+ int sram_size = SRam.end-SRam.start+1;\r
+ if(SRam.reg_back & 4) sram_size=0x2000;\r
+ if(!SRam.data) return 0; // SRam forcefully disabled for this game\r
+ if(load) {\r
+ sramFile = fopen(saveFname, "rb");\r
+ if(!sramFile) return -1;\r
+ fread(SRam.data, 1, sram_size, sramFile);\r
+ fclose(sramFile);\r
+ } else {\r
+ // sram save needs some special processing\r
+ // see if we have anything to save\r
+ for(; sram_size > 0; sram_size--)\r
+ if(SRam.data[sram_size-1]) break;\r
+ \r
+ if(sram_size) {\r
+ sramFile = fopen(saveFname, "wb");\r
+ res = fwrite(SRam.data, 1, sram_size, sramFile);\r
+ res = (res != sram_size) ? -1 : 0;\r
+ fclose(sramFile);\r
+ }\r
+ }\r
+ return res;\r
+ } else {\r
+ void *PmovFile = NULL;\r
+ // try gzip first\r
+ if(currentConfig->iFlags & 0x80) {\r
+ strcat(saveFname, ".gz");\r
+ if( (PmovFile = gzopen(saveFname, load ? "rb" : "wb")) ) {\r
+ areaRead = gzRead2;\r
+ areaWrite = gzWrite2;\r
+ if(!load) gzsetparams(PmovFile, 9, Z_DEFAULT_STRATEGY);\r
+ } else\r
+ saveFname[strlen(saveFname)-3] = 0;\r
+ }\r
+ if(!PmovFile) { // gzip failed or was disabled\r
+ if( (PmovFile = fopen(saveFname, load ? "rb" : "wb")) ) {\r
+ areaRead = fRead2;\r
+ areaWrite = fWrite2;\r
+ }\r
+ }\r
+ if(PmovFile) {\r
+ PmovState(load ? 6 : 5, PmovFile); // load/save\r
+ strcpy(noticeMsg, load ? "GAME@LOADED" : "GAME@SAVED");\r
+ if(areaRead == gzRead2)\r
+ gzclose(PmovFile);\r
+ else fclose ((FILE *) PmovFile);\r
+ PmovFile = 0;\r
+ if (load) Pico.m.dirtyPal=1;\r
+ } else {\r
+ strcpy(noticeMsg, load ? "LOAD@FAILED" : "SAVE@FAILED");\r
+ res = -1;\r
+ }\r
+\r
+ gettimeofday(¬iceMsgTime, 0);\r
+ return res;\r
+ }\r
+}\r
+\r
+// static class members\r
+RWsSession* CGameWindow::iWsSession;\r
+RWindowGroup CGameWindow::iWsWindowGroup;\r
+RWindow CGameWindow::iWsWindow;\r
+CWsScreenDevice* CGameWindow::iWsScreen = NULL;\r
+CWindowGc* CGameWindow::iWindowGc = NULL;\r
+TRequestStatus CGameWindow::iWsEventStatus = KRequestPending;\r
+//RDirectScreenAccess* CGameWindow::iDSA;\r
+//TRequestStatus CGameWindow::iDSAstatus = KRequestPending;\r
+TPicoDirectScreenAccess CGameWindow::iPDSA;\r
+CDirectScreenAccess* CGameWindow::iDSA = NULL;\r
+\r