initial import

git-svn-id: file:///home/notaz/opt/svn/PicoDrive@2 be3aeb3a-fb24-0410-a615-afba39da0efa
This commit is contained in:
notaz 2006-12-19 20:53:21 +00:00
parent 2cadbd5e56
commit cc68a136aa
341 changed files with 180839 additions and 0 deletions

View file

@ -0,0 +1,32 @@
/*******************************************************************
*
* File: PolledAS.h
*
* Author: Peter van Sebille (peter@yipton.net)
*
* (c) Copyright 2001, Peter van Sebille
* All Rights Reserved
*
*******************************************************************/
#ifndef __POLLED_AS_H
#define __POLLED_AS_H
class CPrivatePolledActiveScheduler;
class CPolledActiveScheduler : public CBase
{
public:
~CPolledActiveScheduler();
static CPolledActiveScheduler* NewL();
static CPolledActiveScheduler* Instance();
void Schedule();
protected:
CPolledActiveScheduler(){};
void ConstructL();
CPrivatePolledActiveScheduler* iPrivatePolledActiveScheduler;
};
#endif /* __POLLED_AS_H */

View file

@ -0,0 +1,293 @@
/*******************************************************************
*
* File: Audio_mediaserver.cpp
*
* Author: Peter van Sebille (peter@yipton.net)
*
* Modified/adapted for picodriveN by notaz, 2006
*
* (c) Copyright 2006, notaz
* (c) Copyright 2001, Peter van Sebille
* All Rights Reserved
*
*******************************************************************/
#include "audio_mediaserver.h"
#include "debug.h"
//#undef DEBUGPRINT
//#define DEBUGPRINT(x...)
const TInt KUpdatesPerSec = 10;
const TInt KBlockTime = 1000000 / KUpdatesPerSec;
const TInt KMaxLag = 200000; // max sound lag, lower values increase chance of underflow
const TInt KMaxUnderflows = 50; // max underflows/API errors we are going allow in a row (to prevent lockups)
/*******************************************
*
* CGameAudioMS
*
*******************************************/
CGameAudioMS::CGameAudioMS(TInt aRate, TBool aStereo, TInt aWritesPerSec)
: iRate(aRate), iStereo(aStereo), iWritesPerSec(aWritesPerSec)
{
}
CGameAudioMS* CGameAudioMS::NewL(TInt aRate, TBool aStereo, TInt aWritesPerSec)
{
DEBUGPRINT(_L("CGameAudioMS::NewL(%i, %i, %i)"), aRate, aStereo, aWritesPerSec);
CGameAudioMS* self = new(ELeave) CGameAudioMS(aRate, aStereo, aWritesPerSec);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(); // self
return self;
}
CGameAudioMS::~CGameAudioMS()
{
DEBUGPRINT(_L("CGameAudioMS::~CGameAudioMS()"));
if(iMdaAudioOutputStream) {
iScheduler->Schedule(); // let it finish it's stuff
iMdaAudioOutputStream->Stop();
delete iMdaAudioOutputStream;
}
if(iServer) delete iServer;
for (TInt i=0; i<KSoundBuffers; i++)
delete iSoundBuffers[i];
// Polled AS
//if(iScheduler) delete iScheduler;
}
void CGameAudioMS::ConstructL()
{
iServer = CMdaServer::NewL();
// iScheduler = CPolledActiveScheduler::NewL();
iScheduler = CPolledActiveScheduler::Instance();
switch(iRate) {
case 11025: iMdaAudioDataSettings.iSampleRate = TMdaAudioDataSettings::ESampleRate11025Hz; break;
case 16000: iMdaAudioDataSettings.iSampleRate = TMdaAudioDataSettings::ESampleRate16000Hz; break;
case 22050: iMdaAudioDataSettings.iSampleRate = TMdaAudioDataSettings::ESampleRate22050Hz; break;
case 44100: iMdaAudioDataSettings.iSampleRate = TMdaAudioDataSettings::ESampleRate44100Hz; break;
default: iMdaAudioDataSettings.iSampleRate = TMdaAudioDataSettings::ESampleRate8000Hz; break;
}
iMdaAudioDataSettings.iChannels = (iStereo) ? TMdaAudioDataSettings::EChannelsStereo : TMdaAudioDataSettings::EChannelsMono;
iMdaAudioDataSettings.iCaps = TMdaAudioDataSettings::ESampleRateFixed | iMdaAudioDataSettings.iSampleRate;
iMdaAudioDataSettings.iFlags = TMdaAudioDataSettings::ENoNetworkRouting;
int pcmFrames = iRate / iWritesPerSec;
pcmFrames += iRate - (iRate / iWritesPerSec) * iWritesPerSec; // add division remainder too for our buffer size
iBufferedFrames = iWritesPerSec / KUpdatesPerSec;
TInt bytesPerFrame = pcmFrames << (iStereo?2:1);
for (TInt i=0 ; i<KSoundBuffers ; i++)
{
iSoundBuffers[i] = HBufC8::NewL(bytesPerFrame * iBufferedFrames);
iSoundBuffers[i]->Des().FillZ (bytesPerFrame * iBufferedFrames);
}
iCurrentBuffer = 0;
iCurrentBufferSize = 0;
// here we actually test if we can create and open CMdaAudioOutputStream at all, but really create and use it later.
iMdaAudioOutputStream = CMdaAudioOutputStream::NewL(iListener, iServer);
if(iMdaAudioOutputStream) {
iVolume = iMdaAudioOutputStream->MaxVolume();
DEBUGPRINT(_L("MaxVolume: %i"), iVolume);
delete iMdaAudioOutputStream;
iMdaAudioOutputStream = 0;
}
}
// returns a pointer to buffer for next frame,
// to be used when iSoundBuffers are used directly
TInt16 *CGameAudioMS::NextFrameL(TInt aPcmFrames)
{
iCurrentPosition += aPcmFrames << (iStereo?1:0);
iCurrentBufferSize += aPcmFrames << (iStereo?2:1);
if (++iFrameCount == iBufferedFrames)
{
WriteBlockL();
}
iScheduler->Schedule();
if(iListener.iUnderflowed) {
if(iListener.iUnderflowed > KMaxUnderflows) {
delete iMdaAudioOutputStream;
iMdaAudioOutputStream = 0;
return 0;
}
UnderflowedL(); // not again!
}
return iCurrentPosition;
}
void CGameAudioMS::WriteBlockL()
{
iScheduler->Schedule();
// do not write until stream is open
if(!iListener.iIsOpen) WaitForOpenToCompleteL();
//if(!iListener.iHasCopied) WaitForCopyToCompleteL(); // almost never happens anyway and sometimes even deadlocks?
//iListener.iHasCopied = EFalse;
if(!iListener.iUnderflowed) {
TInt64 delta;
// don't write if sound is lagging too much
delta = iTime - iMdaAudioOutputStream->Position().Int64();
if (delta > MAKE_TINT64(0, KMaxLag))
// another query sometimes returns very different result
delta = iTime - iMdaAudioOutputStream->Position().Int64();
if(delta <= MAKE_TINT64(0, KMaxLag)) {
//RDebug::Print(_L("delta: %i"), iTime.Low() - iMdaAudioOutputStream->Position().Int64().Low());
iSoundBuffers[iCurrentBuffer]->Des().SetLength(iCurrentBufferSize);
iMdaAudioOutputStream->WriteL(*iSoundBuffers[iCurrentBuffer]);
iTime += KBlockTime;
} else {
DEBUGPRINT(_L("lag: %i"), I64LOW(delta));
}
}
iFrameCount = 0;
if (++iCurrentBuffer == KSoundBuffers)
iCurrentBuffer = 0;
iCurrentPosition = (TInt16*) iSoundBuffers[iCurrentBuffer]->Ptr();
iCurrentBufferSize = 0;
}
void CGameAudioMS::Pause()
{
if(!iMdaAudioOutputStream) return;
iScheduler->Schedule(); // let it finish it's stuff
iMdaAudioOutputStream->Stop();
delete iMdaAudioOutputStream;
iMdaAudioOutputStream = 0;
}
// call this before doing any playback!
TInt16 *CGameAudioMS::ResumeL()
{
DEBUGPRINT(_L("CGameAudioMS::Resume()"));
iScheduler->Schedule();
// we act a bit strange here: simulate buffer underflow, which actually starts audio
iListener.iIsOpen = ETrue;
iListener.iUnderflowed = 1;
iListener.iLastError = 0;
iFrameCount = 0;
iCurrentBufferSize = 0;
iCurrentPosition = (TInt16*) iSoundBuffers[iCurrentBuffer]->Ptr();
return iCurrentPosition;
}
// handles underflow condition
void CGameAudioMS::UnderflowedL()
{
DEBUGPRINT(_L("UnderflowedL()"));
if (iListener.iLastError != KErrUnderflow)
{
// recreate the stream
//iMdaAudioOutputStream->Stop();
if(iMdaAudioOutputStream) delete iMdaAudioOutputStream;
iMdaAudioOutputStream = CMdaAudioOutputStream::NewL(iListener, iServer);
iMdaAudioOutputStream->Open(&iMdaAudioDataSettings);
iMdaAudioOutputStream->SetAudioPropertiesL(iMdaAudioDataSettings.iSampleRate, iMdaAudioDataSettings.iChannels);
iMdaAudioOutputStream->SetVolume(iVolume); // new in UIQ3
iListener.iIsOpen = EFalse; // wait for it to open
//iListener.iHasCopied = ETrue; // but don't wait for last copy to complete
// let it open and feed some stuff to make it happy
User::After(0);
iScheduler->Schedule();
iListener.iLastError = 0;
if(!iListener.iIsOpen) WaitForOpenToCompleteL();
} else {
iListener.iLastError = iListener.iUnderflowed = 0;
}
iTime = iMdaAudioOutputStream->Position().Int64();
}
void CGameAudioMS::WaitForOpenToCompleteL()
{
DEBUGPRINT(_L("CGameAudioMS::WaitForOpenToCompleteL"));
TInt count = 20; // 2 seconds
TInt waitPeriod = 100 * 1000;
if(!iListener.iIsOpen) {
// it is often enough to do this
User::After(0);
iScheduler->Schedule();
}
while (!iListener.iIsOpen && --count)
{
User::After(waitPeriod);
iScheduler->Schedule();
}
if (!iListener.iIsOpen)
User::LeaveIfError(KErrNotSupported);
}
void CGameAudioMS::ChangeVolume(TInt aUp)
{
//DEBUGPRINT(_L("CGameAudioMS::ChangeVolume(%i)"), aUp);
if (iMdaAudioOutputStream) {
if (aUp) {
if (iVolume < iMdaAudioOutputStream->MaxVolume()) iVolume+=5;
} else {
if (iVolume > 0) iVolume-=5;
}
iMdaAudioOutputStream->SetVolume(iVolume);
}
}
void TGameAudioEventListener::MaoscOpenComplete(TInt aError)
{
DEBUGPRINT(_L("CGameAudioMS::MaoscOpenComplete, error=%d"), aError);
iIsOpen = ETrue;
if(aError) {
iLastError = aError;
iUnderflowed++;
}
else iUnderflowed = 0;
}
void TGameAudioEventListener::MaoscBufferCopied(TInt aError, const TDesC8& aBuffer)
{
if (aError)
DEBUGPRINT(_L("CGameAudioMS::MaoscBufferCopied, error=%d"), aError);
// iHasCopied = ETrue;
if(aError) { // shit!
iLastError = aError;
iUnderflowed++;
}
}
void TGameAudioEventListener::MaoscPlayComplete(TInt aError)
{
DEBUGPRINT(_L("CGameAudioMS::MaoscPlayComplete: %i"), aError);
if(aError) {
iLastError = aError;
iUnderflowed++; // never happened to me while testing, but just in case
}
}

View file

@ -0,0 +1,85 @@
/*******************************************************************
*
* File: Audio_mediaserver.h
*
* Author: Peter van Sebille (peter@yipton.net)
*
* Modified/adapted for picodriveN by notaz, 2006
*
* (c) Copyright 2006, notaz
* (c) Copyright 2001, Peter van Sebille
* All Rights Reserved
*
*******************************************************************/
#ifndef __AUDIO_MEDIASERVER_H
#define __AUDIO_MEDIASERVER_H
#include <Mda\Common\Audio.h>
#include <MdaAudioOutputStream.h>
//#include "audio.h"
#include "polledas.h"
const TInt KSoundBuffers = 4;
class TGameAudioEventListener : public MMdaAudioOutputStreamCallback
{
public: // implements MMdaAudioOutputStreamCallback
void MaoscOpenComplete(TInt aError);
void MaoscBufferCopied(TInt aError, const TDesC8& );
void MaoscPlayComplete(TInt aError);
TBool iIsOpen;
// TBool iHasCopied;
TInt iUnderflowed;
TInt iLastError;
};
class CGameAudioMS // : public IGameAudio // IGameAudio MUST be specified first!
{
public: // implements IGameAudio
TInt16 *NextFrameL(TInt aPcmFrames);
TInt16 *ResumeL();
void Pause();
void ChangeVolume(TInt aUp);
public:
~CGameAudioMS();
CGameAudioMS(TInt aRate, TBool aStereo, TInt aWritesPerSec);
static CGameAudioMS* NewL(TInt aRate, TBool aStereo, TInt aWritesPerSec);
protected:
void WriteBlockL();
void UnderflowedL();
void ConstructL();
protected:
void WaitForOpenToCompleteL();
TInt iRate;
TBool iStereo;
CMdaAudioOutputStream *iMdaAudioOutputStream;
TMdaAudioDataSettings iMdaAudioDataSettings;
TGameAudioEventListener iListener;
CPolledActiveScheduler *iScheduler;
HBufC8* iSoundBuffers[KSoundBuffers];
TInt iWritesPerSec;
TInt iBufferedFrames;
TInt16* iCurrentPosition;
TInt iCurrentBuffer;
TInt iCurrentBufferSize;
TInt iFrameCount;
CMdaServer* iServer;
TInt64 iTime;
TInt iVolume;
};
#endif /* __AUDIO_MEDIASERVER_H */

View file

@ -0,0 +1,34 @@
/*
void vidConvCpyRGB32 (void *to, void *from, int lines, int p240)
{
unsigned short *ps = (unsigned short *) from;
unsigned long *pd = (unsigned long *) to;
int x, y;
int to_x = p240 ? 240 : 224;
if(!p240) pd += 8;
for(y = 0; y < lines; y++) // ps < ps_end; ps++)
for(x = 0; x < to_x; x++, ps++)
// Convert 0000bbb0 ggg0rrr0
// to ..0 rrr00000 ggg00000 bbb00000
*(pd+y*256+x) = ((*ps&0x000F)<<20) | ((*ps&0x00F0)<<8) | ((*ps&0x0F00)>>4);
}
*/
// stubs
void vidConvCpyRGB32 (void *to, void *from, int pixels) {}
void vidConvCpyRGB32sh(void *to, void *from, int pixels) {}
void vidConvCpyRGB32hi(void *to, void *from, int pixels) {}
void vidConvCpy_90 (void *to, void *from, void *pal, int width) {}
void vidConvCpy_270 (void *to, void *from, void *pal, int width) {}
void vidConvCpy_center_0 (void *to, void *from, void *pal) {}
void vidConvCpy_center_180(void *to, void *from, void *pal) {}
void vidConvCpy_center2_40c_0 (void *to, void *from, void *pal, int lines) {}
void vidConvCpy_center2_40c_180(void *to, void *from, void *pal, int lines) {}
void vidConvCpy_center2_32c_0 (void *to, void *from, void *pal, int lines) {}
void vidConvCpy_center2_32c_180(void *to, void *from, void *pal, int lines) {}
void vidClear(void *to, int lines) {}

View file

@ -0,0 +1,22 @@
// (c) Copyright 2006 notaz, All rights reserved.
// Free for non-commercial use.
// For commercial use, separate licencing terms must be obtained.
extern "C"
{
void vidConvCpyRGB32 (void *to, void *from, int pixels);
void vidConvCpyRGB32sh(void *to, void *from, int pixels);
void vidConvCpyRGB32hi(void *to, void *from, int pixels);
void vidConvCpy_90 (void *to, void *from, void *pal, int width);
void vidConvCpy_270 (void *to, void *from, void *pal, int width);
void vidConvCpy_center_0 (void *to, void *from, void *pal);
void vidConvCpy_center_180(void *to, void *from, void *pal);
void vidConvCpy_center2_40c_0 (void *to, void *from, void *pal, int lines);
void vidConvCpy_center2_40c_180(void *to, void *from, void *pal, int lines);
void vidConvCpy_center2_32c_0 (void *to, void *from, void *pal, int lines);
void vidConvCpy_center2_32c_180(void *to, void *from, void *pal, int lines);
void vidClear(void *to, int lines);
}

695
platform/uiq3/engine/blit.s Normal file
View file

@ -0,0 +1,695 @@
@ some color conversion and blitting routines
@ (c) Copyright 2006, notaz
@ All Rights Reserved
@ Convert 0000bbb0 ggg0rrr0 0000bbb0 ggg0rrr0
@ to 00000000 rrr00000 ggg00000 bbb00000 ...
@ lr = 0x00e000e0, out: r3=lower_pix, r2=higher_pix; trashes rin
@ if sh==2, r8=0x00404040 (sh!=0 destroys flags!)
.macro convRGB32_2 rin sh=0
and r2, lr, \rin, lsr #4 @ blue
and r3, \rin, lr
orr r2, r2, r3, lsl #8 @ g0b0g0b0
mov r3, r2, lsl #16 @ g0b00000
and \rin,lr, \rin, ror #12 @ 00r000r0 (reversed)
orr r3, r3, \rin, lsr #16 @ g0b000r0
.if \sh == 1
mov r3, r3, ror #17 @ shadow mode
.elseif \sh == 2
adds r3, r3, #0x40000000 @ green
orrcs r3, r3, #0xe0000000
mov r3, r3, ror #8
adds r3, r3, #0x40000000
orrcs r3, r3, #0xe0000000
mov r3, r3, ror #16
adds r3, r3, #0x40000000
orrcs r3, r3, #0xe0000000
mov r3, r3, ror #24
orr r3, r3, r3, lsr #3
.else
mov r3, r3, ror #16 @ r3=low
orr r3, r3, r3, lsr #3
.endif
str r3, [r0], #4
mov r2, r2, lsr #16
orr r2, r2, \rin, lsl #16
.if \sh == 1
mov r2, r2, lsr #1
.elseif \sh == 2
mov r2, r2, ror #8
adds r2, r2, #0x40000000 @ blue
orrcs r2, r2, #0xe0000000
mov r2, r2, ror #8
adds r2, r2, #0x40000000
orrcs r2, r2, #0xe0000000
mov r2, r2, ror #8
adds r2, r2, #0x40000000
orrcs r2, r2, #0xe0000000
mov r2, r2, ror #8
orr r2, r2, r2, lsr #3
.else
orr r2, r2, r2, lsr #3
.endif
str r2, [r0], #4
.endm
.global vidConvCpyRGB32 @ void *to, void *from, int pixels
vidConvCpyRGB32:
stmfd sp!, {r4-r7,lr}
mov r12, r2, lsr #3 @ repeats
mov lr, #0x00e00000
orr lr, lr, #0x00e0
.loopRGB32:
subs r12, r12, #1
ldmia r1!, {r4-r7}
convRGB32_2 r4
convRGB32_2 r5
convRGB32_2 r6
convRGB32_2 r7
bgt .loopRGB32
ldmfd sp!, {r4-r7,lr}
bx lr
.global vidConvCpyRGB32sh @ void *to, void *from, int pixels
vidConvCpyRGB32sh:
stmfd sp!, {r4-r7,lr}
mov r12, r2, lsr #3 @ repeats
mov lr, #0x00e00000
orr lr, lr, #0x00e0
.loopRGB32sh:
subs r12, r12, #1
ldmia r1!, {r4-r7}
convRGB32_2 r4, 1
convRGB32_2 r5, 1
convRGB32_2 r6, 1
convRGB32_2 r7, 1
bgt .loopRGB32sh
ldmfd sp!, {r4-r7,lr}
bx lr
.global vidConvCpyRGB32hi @ void *to, void *from, int pixels
vidConvCpyRGB32hi:
stmfd sp!, {r4-r7,lr}
mov r12, r2, lsr #3 @ repeats
mov lr, #0x00e00000
orr lr, lr, #0x00e0
.loopRGB32hi:
ldmia r1!, {r4-r7}
convRGB32_2 r4, 2
convRGB32_2 r5, 2
convRGB32_2 r6, 2
convRGB32_2 r7, 2
subs r12, r12, #1
bgt .loopRGB32hi
ldmfd sp!, {r4-r7,lr}
bx lr
@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ -------- M2 stuff ---------
/*
.global vidConvCpy_90 @ void *to, void *from, int width
vidConvCpy_90:
stmfd sp!, {r4-r10,lr}
mov lr, #0x00F00000
orr lr, lr, #0x00F0
mov r12, #224/4 @ row counter
mov r10, r2, lsl #2 @ we do 2 pixel wide copies
add r8, r0, #256*4 @ parallel line
add r1, r1, #0x23000
add r1, r1, #0x00B80 @ r1+=328*223*2+8*2
mov r9, r1
mov r4, #0 @ fill bottom border
mov r5, #0
mov r6, #0
mov r7, #0
stmia r0!, {r4-r7}
stmia r0!, {r4-r7}
stmia r8!, {r4-r7}
stmia r8!, {r4-r7}
.loopM2RGB32_90:
subs r12, r12, #1
@ at first this loop was written differently: src pixels were fetched with ldm's and
@ dest was not sequential. It ran nearly 2 times slower. It seems it is very important
@ to do sequential memory access on those items, which we have more (to offload addressing bus?).
ldr r4, [r1], #-328*2
ldr r5, [r1], #-328*2
ldr r6, [r1], #-328*2
ldr r7, [r1], #-328*2
convRGB32_2 r4, 1
convRGB32_2 r5, 1
convRGB32_2 r6, 1
convRGB32_2 r7, 1
str r4, [r8], #4
str r5, [r8], #4
str r6, [r8], #4
str r7, [r8], #4
bne .loopM2RGB32_90
mov r4, #0 @ top border
mov r5, #0
mov r6, #0
stmia r0!, {r4-r6,r12}
stmia r0!, {r4-r6,r12}
stmia r8!, {r4-r6,r12}
stmia r8!, {r4-r6,r12}
subs r10, r10, #1
ldmeqfd sp!, {r4-r10,pc} @ return
add r0, r8, #16*4 @ set new dst pointer
add r8, r0, #256*4
add r9, r9, #2*2 @ fix src pointer
mov r1, r9
stmia r0!, {r4-r6,r12} @ bottom border
stmia r0!, {r4-r6,r12}
stmia r8!, {r4-r6,r12}
stmia r8!, {r4-r6,r12}
mov r12, #224/4 @ restore row counter
b .loopM2RGB32_90
@ converter for vidConvCpy_270
@ lr = 0x00F000F0, out: r3=lower_pix, r2=higher_pix; trashes rin
.macro convRGB32_3 rin
and r2, lr, \rin, lsr #4 @ blue
and r3, \rin, lr
orr r2, r2, r3, lsl #8 @ g0b0g0b0
mov r3, r2, lsl #16 @ g0b00000
and \rin,lr, \rin, ror #12 @ 00r000r0 (reversed)
orr r3, r3, \rin, lsr #16 @ g0b000r0
mov r2, r2, lsr #16
orr r2, r2, \rin, lsl #16
str r2, [r0], #4
mov \rin,r3, ror #16 @ r3=low
.endm
*/
@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ takes byte-sized pixels from r3-r6, fetches from pal and stores to r7,r8,r10,lr
@ r2=pal
.macro mode2_4pix shift
and r7, r11, r3, lsr #\shift
ldr r7, [r2, r7, lsl #2]
and r8, r11, r4, lsr #\shift
ldr r8, [r2, r8, lsl #2]
and r10,r11, r5, lsr #\shift
ldr r10,[r2, r10,lsl #2]
and lr, r11, r6, lsr #\shift
ldr lr, [r2, lr, lsl #2]
.endm
@ r2=pal, r11=0xff
.macro mode2_4pix_getpix0 dreg sreg
and \dreg, r11, \sreg
ldr \dreg, [r2, \dreg, lsl #2]
.endm
.macro mode2_4pix_getpix1 dreg sreg
and \dreg, r11, \sreg, lsr #8
ldr \dreg, [r2, \dreg, lsl #2]
.endm
.macro mode2_4pix_getpix2 dreg sreg
and \dreg, r11, \sreg, lsr #16
ldr \dreg, [r2, \dreg, lsl #2]
.endm
.macro mode2_4pix_getpix3 dreg sreg
and \dreg, r11, \sreg, lsr #24
ldr \dreg, [r2, \dreg, lsl #2]
.endm
@ takes byte-sized pixels from reg, fetches from pal and stores to r3-r6
@ r11=0xFF, r2=pal
.macro mode2_4pix2_0 reg
mode2_4pix_getpix0 r3, \reg
mode2_4pix_getpix1 r4, \reg
mode2_4pix_getpix2 r5, \reg
mode2_4pix_getpix3 r6, \reg
.endm
@ ...
.macro mode2_4pix2_180 reg
mode2_4pix_getpix3 r3, \reg
mode2_4pix_getpix2 r4, \reg
mode2_4pix_getpix1 r5, \reg
mode2_4pix_getpix0 r6, \reg
.endm
@ takes byte-sized pixels from reg, fetches from pal and stores to r3-r5
@ r11=0xFF, r2=pal, r10=0xfcfcfc, r6=tmp
.macro mode2_4pix_to3 reg is180
.if \is180
mode2_4pix_getpix3 r3, \reg
mode2_4pix_getpix2 r4, \reg
.else
mode2_4pix_getpix0 r3, \reg @ gathering loads cause a weird-hang
mode2_4pix_getpix1 r4, \reg
.endif
sub r3, r3, r3, lsr #2 @ r3 *= 0.75
add r3, r3, r4, lsr #2 @ r3 += r4 * 0.25
and r3, r3, r10
.if \is180
mode2_4pix_getpix1 r5, \reg
mode2_4pix_getpix0 r6, \reg
.else
mode2_4pix_getpix2 r5, \reg
mode2_4pix_getpix3 r6, \reg
.endif
mov r4, r4, lsr #1
add r4, r4, r5, lsr #1 @ r4 = (r4 + r5) / 2;
@ and r4, r4, r10
sub r6, r6, r6, lsr #2 @ r6 *= 0.75
add r5, r6, r5, lsr #2 @ r5 = r6 + r5 * 0.25
and r5, r5, r10
.endm
@ void *to, void *from, void *pal, int width
.macro vidConvCpyM2_landscape is270
stmfd sp!, {r4-r11,lr}
mov r11, #0xff
mov r12, #(224/4-1)<<16 @ row counter
orr r12, r12, r3, lsl #1 @ we do 4 pixel wide copies (right to left)
.if \is270
add r1, r1, #324
.else
add r1, r1, #0x11c00
add r1, r1, #0x00308 @ 328*224+8
.endif
mov r9, r1
mov r3, #0 @ fill top border
mov r4, #0
mov r5, #0
mov r6, #0
stmia r0!, {r3-r6}
stmia r0!, {r3-r6}
add r7, r0, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
add r7, r7, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
add r7, r7, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
0: @ .loopM2RGB32_270:
subs r12, r12, #1<<16
.if \is270
ldr r3, [r1], #328
ldr r4, [r1], #328
ldr r5, [r1], #328
ldr r6, [r1], #328
.else
ldr r3, [r1, #-328]!
ldr r4, [r1, #-328]!
ldr r5, [r1, #-328]!
ldr r6, [r1, #-328]!
.endif
.if \is270
mode2_4pix 24
.else
mode2_4pix 0
.endif
stmia r0, {r7,r8,r10,lr}
add r0, r0, #256*4
.if \is270
mode2_4pix 16
.else
mode2_4pix 8
.endif
stmia r0, {r7,r8,r10,lr}
add r0, r0, #256*4
.if \is270
mode2_4pix 8
.else
mode2_4pix 16
.endif
stmia r0, {r7,r8,r10,lr}
add r0, r0, #256*4
.if \is270
mode2_4pix 0
.else
mode2_4pix 24
.endif
stmia r0!,{r7,r8,r10,lr}
sub r0, r0, #256*4*3
bpl 0b @ .loopM2RGB32_270
mov r3, #0 @ bottom border
mov r4, #0
mov r5, #0
mov r6, #0
stmia r0!, {r3-r6}
stmia r0!, {r3-r6}
add r0, r0, #256*4-8*4
stmia r0!, {r3-r6}
stmia r0!, {r3-r6}
add r0, r0, #256*4-8*4
stmia r0!, {r3-r6}
stmia r0!, {r3-r6}
add r0, r0, #256*4-8*4
stmia r0!, {r3-r6}
nop @ phone crashes if this is commented out. Do I stress it too much?
stmia r0!, {r3-r6}
add r12, r12, #1<<16
subs r12, r12, #1
ldmeqfd sp!, {r4-r11,pc} @ return
add r0, r0, #16*4
.if \is270
sub r9, r9, #4 @ fix src pointer
.else
add r9, r9, #4
.endif
mov r1, r9
stmia r0!, {r3-r6} @ top border
stmia r0!, {r3-r6}
add r7, r0, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
add r7, r7, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
add r7, r7, #256*4-8*4
stmia r7!, {r3-r6}
stmia r7!, {r3-r6}
orr r12, r12, #(224/4-1)<<16 @ restore row counter
b 0b @ .loopM2RGB32_270
.endm
.global vidConvCpy_90 @ void *to, void *from, void *pal, int width
vidConvCpy_90:
vidConvCpyM2_landscape 0
.global vidConvCpy_270 @ void *to, void *from, void *pal, int width
vidConvCpy_270:
vidConvCpyM2_landscape 1
.global vidConvCpy_center_0 @ void *to, void *from, void *pal
vidConvCpy_center_0:
stmfd sp!, {r4-r6,r11,lr}
mov r11, #0xff
add r1, r1, #8 @ not border (centering 32col here)
mov r12, #(240/4-1)<<16
orr r12, r12, #224
.loopRGB32_c0:
ldr lr, [r1], #4
subs r12, r12, #1<<16
mode2_4pix2_0 lr
stmia r0!, {r3-r6}
bpl .loopRGB32_c0
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r6,r11,pc} @ return
add r0, r0, #16*4
add r1, r1, #88
orr r12, #(240/4-1)<<16
b .loopRGB32_c0
.global vidConvCpy_center_180 @ void *to, void *from, void *pal
vidConvCpy_center_180:
stmfd sp!, {r4-r6,r11,lr}
mov r11, #0xff
add r1, r1, #0x11c00
add r1, r1, #0x002B8 @ #328*224-72
mov r12, #(240/4-1)<<16
orr r12, r12, #224
.loopRGB32_c180:
ldr lr, [r1, #-4]!
subs r12, r12, #1<<16
mode2_4pix2_180 lr
stmia r0!, {r3-r6}
bpl .loopRGB32_c180
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r6,r11,pc} @ return
add r0, r0, #16*4
sub r1, r1, #88
orr r12, #(240/4-1)<<16
b .loopRGB32_c180
@ note: the following code assumes that (pal[x] & 0x030303) == 0
.global vidConvCpy_center2_40c_0 @ void *to, void *from, void *pal, int lines
vidConvCpy_center2_40c_0:
stmfd sp!, {r4-r6,r10,r11,lr}
mov r11, #0xff
mov r10, #0xfc
orr r10, r10, lsl #8
orr r10, r10, lsl #8
add r1, r1, #8 @ border
mov r12, #(240/3-1)<<16
orr r12, r12, r3
.loopRGB32_c2_40c_0:
ldr lr, [r1], #4
subs r12, r12, #1<<16
mode2_4pix_to3 lr, 0
stmia r0!, {r3-r5}
bpl .loopRGB32_c2_40c_0
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r6,r10,r11,pc} @ return
add r0, r0, #16*4
add r1, r1, #8
orr r12, #(240/3-1)<<16
b .loopRGB32_c2_40c_0
.global vidConvCpy_center2_40c_180 @ void *to, void *from, void *pal, int lines
vidConvCpy_center2_40c_180:
stmfd sp!, {r4-r6,r10,r11,lr}
mov r11, #0xff
mov r10, #0xfc
orr r10, r10, lsl #8
orr r10, r10, lsl #8
mov r4, #328
mla r1, r3, r4, r1
@ add r1, r1, #0x11000
@ add r1, r1, #0x00f00 @ #328*224
mov r12, #(240/3-1)<<16
orr r12, r12, r3
.loop_c2_40c_180:
ldr lr, [r1, #-4]!
subs r12, r12, #1<<16
mode2_4pix_to3 lr, 1
stmia r0!, {r3-r5}
bpl .loop_c2_40c_180
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r6,r10,r11,pc} @ return
add r0, r0, #16*4
sub r1, r1, #8
orr r12, #(240/3-1)<<16
b .loop_c2_40c_180
.global vidConvCpy_center2_32c_0 @ void *to, void *from, void *pal, int lines
vidConvCpy_center2_32c_0:
stmfd sp!, {r4-r11,lr}
mov r10, #0xfc
orr r10, r10, lsl #8
orr r10, r10, lsl #8
mov r11, #0xff
add r1, r1, #8 @ border
mov r12, #(240/15-1)<<16
orr r12, r12, r3
.loop_c2_32c_0:
ldmia r1!, {r7-r9,lr}
subs r12, r12, #1<<16
mode2_4pix2_0 r7
stmia r0!, {r3-r6}
mode2_4pix2_0 r8
stmia r0!, {r3-r6}
mode2_4pix2_0 r9
stmia r0!, {r3-r6}
mode2_4pix_to3 lr, 0
stmia r0!, {r3-r5}
bpl .loop_c2_32c_0
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r11,pc} @ return
add r0, r0, #16*4
add r1, r1, #64+8
orr r12, #(240/15-1)<<16
b .loop_c2_32c_0
.global vidConvCpy_center2_32c_180 @ void *to, void *from, void *pal, int lines
vidConvCpy_center2_32c_180:
stmfd sp!, {r4-r11,lr}
mov r10, #0xfc
orr r10, r10, lsl #8
orr r10, r10, lsl #8
mov r11, #0xff
mov r4, #328
mla r1, r3, r4, r1
@ add r1, r1, #0x11000
@ add r1, r1, #0x00f00 @ #328*224
mov r12, #(240/15-1)<<16
orr r12, r12, r3
.loop_c2_32c_180:
ldmdb r1!, {r7-r9,lr}
subs r12, r12, #1<<16
mode2_4pix2_180 lr
stmia r0!, {r3-r6}
mode2_4pix2_180 r9
stmia r0!, {r3-r6}
mode2_4pix2_180 r8
stmia r0!, {r3-r6}
mode2_4pix_to3 r7, 1
stmia r0!, {r3-r5}
bpl .loop_c2_32c_180
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {r4-r11,pc} @ return
add r0, r0, #16*4
sub r1, r1, #64+8
orr r12, #(240/15-1)<<16
b .loop_c2_32c_180
@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
.global vidClear @ void *to, int lines
vidClear:
stmfd sp!, {lr}
mov r12, #240/16-1
orr r12, r1, r12, lsl #16
mov r1, #0
mov r2, #0
mov r3, #0
mov lr, #0
.loopVidClear:
subs r12, r12, #1<<16
stmia r0!, {r1-r3,lr}
stmia r0!, {r1-r3,lr}
stmia r0!, {r1-r3,lr}
stmia r0!, {r1-r3,lr}
bpl .loopVidClear
sub r12, r12, #1
adds r12, r12, #1<<16
ldmeqfd sp!, {pc} @ return
add r0, r0, #16*4
orr r12, #(240/16-1)<<16
b .loopVidClear

View file

@ -0,0 +1,259 @@
#include <e32svr.h> // RDebug
#include "debug.h"
#ifdef __WINS__
void ExceptionHandler(TExcType exc) {}
#else
static const wchar_t * const exception_names[] = {
L"General",
L"IntegerDivideByZero",
L"SingleStep",
L"BreakPoint",
L"IntegerOverflow",
L"BoundsCheck",
L"InvalidOpCode",
L"DoubleFault",
L"StackFault",
L"AccessViolation",
L"PrivInstruction",
L"Alignment",
L"PageFault",
L"FloatDenormal",
L"FloatDivideByZero",
L"FloatInexactResult",
L"FloatInvalidOperation",
L"FloatOverflow",
L"FloatStackCheck",
L"FloatUnderflow",
L"Abort",
L"Kill",
L"DataAbort",
L"CodeAbort",
L"MaxNumber",
L"InvalidVector",
L"UserInterrupt",
L"Unknown"
};
static void getASpace(TUint *code_start, TUint *code_end, TUint *stack_start, TUint *stack_end)
{
TUint pc, sp;
RChunk chunk;
TFullName chunkname;
TFindChunk findChunk(_L("*"));
asm volatile ("str pc, %0" : "=m" (pc) );
asm volatile ("str sp, %0" : "=m" (sp) );
while( findChunk.Next(chunkname) != KErrNotFound ) {
chunk.Open(findChunk);
if((TUint)chunk.Base()+chunk.Bottom() < pc && pc < (TUint)chunk.Base()+chunk.Top()) {
if(code_start) *code_start = (TUint)chunk.Base()+chunk.Bottom();
if(code_end) *code_end = (TUint)chunk.Base()+chunk.Top();
} else
if((TUint)chunk.Base()+chunk.Bottom() < sp && sp < (TUint)chunk.Base()+chunk.Top()) {
if(stack_start) *stack_start = (TUint)chunk.Base()+chunk.Bottom();
if(stack_end) *stack_end = (TUint)chunk.Base()+chunk.Top();
}
chunk.Close();
}
}
// tmp
#if defined(__DEBUG_PRINT)
extern "C" char *debugString();
#endif
// our very own exception handler
void ExceptionHandler(TExcType exc)
{
TUint lr, sp, i;
TUint stack_end = 0; // ending address of our stack chunk
TUint code_start = 0, code_end = 0; // starting and ending addresses of our code chunk
TUint guessed_address = 0;
DEBUGPRINT(_L("ExceptionHandler()")); // this seems to never be called
asm volatile ("str lr, %0" : "=m" (lr) );
asm volatile ("str sp, %0" : "=m" (sp) );
// first get some info about the chunks we live in
getASpace(&code_start, &code_end, 0, &stack_end);
// now we begin some black magic tricks
// we go up our stack until we pass our caller address
for(; sp < stack_end; sp += 4)
if(*(TUint *)sp == lr) break;
// there might be mirored caller address
for(i = sp + 4; i < sp + 0x300 && i < stack_end; i += 4)
if(*(TUint *)i == lr) { sp = i; break; }
// aah, it is always 0x9c bytes away from the caller address in my firmware,
// don't know how to detect it in any other way
sp += 0x9c;
guessed_address = *(TUint *)sp;
// output the info
TUint exec_show = exc;
if(exec_show > 27) exec_show = 27;
TPtrC ptrExc((TUint16 *) exception_names[exec_show]);
RDebug::Print(_L("!!!Exception %i (%S) @ 0x%08x (guessed; relative=0x%08x)"), exc, &ptrExc, guessed_address, guessed_address - code_start);
#ifdef __DEBUG_PRINT_FILE
DEBUGPRINT( _L("!!!Exception %i (%S) @ 0x%08x (guessed; relative=0x%08x)"), exc, &ptrExc, guessed_address, guessed_address - code_start);
#endif
TBuf<148> buff1;
TBuf<10> buff2;
buff1.Copy(_L(" guessed stack: "));
for(sp += 4, i = 0; i < 5 && sp < stack_end; sp += 4) {
if((*(TUint *)sp >> 28) == 5) {
if(i++) buff1.Append(_L(", "));
buff2.Format(_L("0x%08x"), *(TUint *)sp);
buff1.Append(buff2);
}
else if(code_start < *(TUint *)sp && *(TUint *)sp < code_end) {
if(i++) buff1.Append(_L(", "));
buff2.Format(_L("0x%08x"), *(TUint *)sp);
buff1.Append(buff2);
buff1.Append(_L(" ("));
buff2.Format(_L("0x%08x"), *(TUint *)sp - code_start);
buff1.Append(buff2);
buff1.Append(_L(")"));
}
}
RDebug::Print(_L("%S"), &buff1);
#ifdef __DEBUG_PRINT_FILE
DEBUGPRINT(_L("%S"), &buff1);
#endif
// tmp
#if defined(__DEBUG_PRINT)
char *ps, *cstr = debugString();
for(ps = cstr; *ps; ps++) {
if(*ps == '\n') {
*ps = 0;
dprintf(cstr);
cstr = ps+1;
}
}
#endif
// RDebug::Print(_L("Stack dump:"));
// asm volatile ("str sp, %0" : "=m" (sp) );
// for(TUint i = sp+0x400; i >= sp-16; i-=4)
// RDebug::Print(_L("%08x: %08x"), i, *(int *)i);
// more descriptive replacement of "KERN-EXEC 3" panic
buff1.Format(_L("K-EX3: %S"), &ptrExc);
User::Panic(buff1, exc);
}
#endif // ifdef __WINS__
#if defined(__DEBUG_PRINT) || defined(__WINS__)
#ifndef __DLL__
// c string dumper for RDebug::Print()
static TBuf<1024> sTextBuffer;
TDesC* DO_CONV(const char* s)
{
TPtrC8 text8((TUint8*) (s));
sTextBuffer.Copy(text8);
return &sTextBuffer;
}
#endif
#ifdef __DEBUG_PRINT_C
#include <stdarg.h> // va_*
#include <stdio.h> // vsprintf
// debug print from c code
extern "C" void dprintf(char *format, ...)
{
va_list args;
char buffer[512];
va_start(args,format);
vsprintf(buffer,format,args);
va_end(args);
DEBUGPRINT(_L("%S"), DO_CONV(buffer));
}
#endif
#ifdef __DEBUG_PRINT_FILE
#include <f32file.h>
//static RFile logFile;
// static TBool logInited = 0;
RMutex logMutex;
static void debugPrintFileInit()
{
// try to open
logMutex.CreateLocal();
RFs fserv;
fserv.Connect();
RFile logFile;
logFile.Replace(fserv, _L("C:\\logs\\pico.log"), EFileWrite|EFileShareAny);
logFile.Close();
fserv.Close();
}
// debug print to file
void debugPrintFile(TRefByValue<const TDesC> aFmt, ...)
{
if (logMutex.Handle() <= 0) debugPrintFileInit();
logMutex.Wait();
RFs fserv;
fserv.Connect();
TTime now; now.UniversalTime();
TBuf<512> tmpBuff;
TBuf8<512> tmpBuff8;
TInt size, res;
RThread thisThread;
RFile logFile;
res = logFile.Open(fserv, _L("C:\\logs\\pico.log"), EFileWrite|EFileShareAny);
if(res) goto fail1;
logFile.Size(size); logFile.Seek(ESeekStart, size);
now.FormatL(tmpBuff, _L("%H:%T:%S.%C: "));
tmpBuff8.Copy(tmpBuff);
logFile.Write(tmpBuff8);
tmpBuff8.Format(TPtr8((TUint8 *)"%03i: ", 6, 6), (TInt32) thisThread.Id());
logFile.Write(tmpBuff8);
VA_LIST args;
VA_START(args, aFmt);
tmpBuff.FormatList(aFmt, args);
VA_END(args);
tmpBuff8.Copy(tmpBuff);
logFile.Write(tmpBuff8);
logFile.Write(TPtrC8((TUint8 const *) "\n"));
logFile.Flush();
logFile.Close();
fail1:
thisThread.Close();
fserv.Close();
logMutex.Signal();
}
#endif
#endif

View file

@ -0,0 +1,27 @@
#include <e32std.h>
#define __DEBUG_PRINT_C
#define __DEBUG_PRINT_FILE
#if defined(__DEBUG_PRINT) || defined(__WINS__)
#include <e32svr.h> // RDebug
#ifdef __DEBUG_PRINT_FILE
void debugPrintFile(TRefByValue<const TDesC> aFmt, ...);
#define DEBUGPRINT debugPrintFile
#else
#define DEBUGPRINT RDebug::Print
#endif
TDesC* DO_CONV(const char* s);
#ifdef __DEBUG_PRINT_C
#ifdef __cplusplus
extern "C"
#endif
void dprintf(char *format, ...);
#endif
#else
#define DEBUGPRINT(x...)
#undef __DEBUG_PRINT_C
#undef __DEBUG_PRINT_FILE
#endif
void ExceptionHandler(TExcType exc);

View file

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

View file

@ -0,0 +1,269 @@
/*******************************************************************
*
* File: PolledAS.cpp
*
* Author: Peter van Sebille (peter@yipton.net)
*
* (c) Copyright 2002, Peter van Sebille
* All Rights Reserved
*
*******************************************************************/
/*
* Oh Lord, forgive me for I have sinned.
* In their infinite wisdom, Symbian Engineers have decided that
* the Active Scheduler's queue of Active Objects is private
* and no getters are provided... sigh.
* This mere mortal will have to excercise the power of C pre-processor
* once more to circumvent the will of the gods.
*/
#include <e32std.h>
// from e32base.h
class CBase
{
public:
/**
Default constructor
*/
inline CBase() {}
IMPORT_C virtual ~CBase();
inline TAny* operator new(TUint aSize, TAny* aBase) __NO_THROW { Mem::FillZ(aBase, aSize); return aBase; }
inline TAny* operator new(TUint aSize) __NO_THROW { return User::AllocZ(aSize); }
inline TAny* operator new(TUint aSize, TLeave) { return User::AllocZL(aSize); }
inline TAny* operator new(TUint aSize, TUint aExtraSize) { return User::AllocZ(aSize + aExtraSize); }
inline TAny* operator new(TUint aSize, TLeave, TUint aExtraSize) { return User::AllocZL(aSize + aExtraSize); }
IMPORT_C static void Delete(CBase* aPtr);
protected:
IMPORT_C virtual TInt Extension_(TUint aExtensionId, TAny*& a0, TAny* a1);
private:
CBase(const CBase&);
CBase& operator=(const CBase&);
private:
};
class TRequestStatusFaked
{
public:
inline TRequestStatusFaked() : iFlags(0) {};
inline TRequestStatusFaked(TInt aVal) : iStatus(aVal), iFlags(aVal==KRequestPending ? TRequestStatusFaked::ERequestPending : 0) {}
/* inline TInt operator=(TInt aVal);
inline TBool operator==(TInt aVal) const;
*/
inline TBool operator!=(TInt aVal) const {return(iStatus!=aVal);}
/*
inline TBool operator>=(TInt aVal) const;
inline TBool operator<=(TInt aVal) const;
inline TBool operator>(TInt aVal) const;
inline TBool operator<(TInt aVal) const;
inline TInt Int() const;
private:
*/
enum
{
EActive = 1, //bit0
ERequestPending = 2, //bit1
};
TInt iStatus;
TUint iFlags;
friend class CActive;
friend class CActiveScheduler;
friend class CServer2;
};
class CActive : public CBase
{
public:
enum TPriority
{
EPriorityIdle=-100,
EPriorityLow=-20,
EPriorityStandard=0,
EPriorityUserInput=10,
EPriorityHigh=20,
};
public:
IMPORT_C ~CActive();
IMPORT_C void Cancel();
IMPORT_C void Deque();
IMPORT_C void SetPriority(TInt aPriority);
inline TBool IsActive() const {return(iStatus.iFlags&TRequestStatus::EActive);}
inline TBool IsAdded() const {return(iLink.iNext!=NULL);}
inline TInt Priority() const {return iLink.iPriority;}
protected:
IMPORT_C CActive(TInt aPriority);
IMPORT_C void SetActive();
virtual void DoCancel() =0;
virtual void RunL() =0;
IMPORT_C virtual TInt RunError(TInt aError);
protected:
IMPORT_C virtual TInt Extension_(TUint aExtensionId, TAny*& a0, TAny* a1);
public:
TRequestStatusFaked iStatus; // hope this will work
private:
// TBool iActive;
TPriQueLink iLink;
TAny* iSpare;
friend class CActiveScheduler;
friend class CServer;
friend class CServer2;
friend class CPrivatePolledActiveScheduler; // added
};
class CActiveScheduler : public CBase
{
friend class CActiveSchedulerWait;
public:
struct TLoop;
typedef TLoop* TLoopOwner;
public:
IMPORT_C CActiveScheduler();
IMPORT_C ~CActiveScheduler();
IMPORT_C static void Install(CActiveScheduler* aScheduler);
IMPORT_C static CActiveScheduler* Current();
IMPORT_C static void Add(CActive* aActive);
IMPORT_C static void Start();
IMPORT_C static void Stop();
IMPORT_C static TBool RunIfReady(TInt& aError, TInt aMinimumPriority);
IMPORT_C static CActiveScheduler* Replace(CActiveScheduler* aNewActiveScheduler);
IMPORT_C virtual void WaitForAnyRequest();
IMPORT_C virtual void Error(TInt aError) const;
IMPORT_C void Halt(TInt aExitCode) const;
IMPORT_C TInt StackDepth() const;
private:
static void Start(TLoopOwner* aOwner);
IMPORT_C virtual void OnStarting();
IMPORT_C virtual void OnStopping();
IMPORT_C virtual void Reserved_1();
IMPORT_C virtual void Reserved_2();
void Run(TLoopOwner* const volatile& aLoop);
void DoRunL(TLoopOwner* const volatile& aLoop, CActive* volatile & aCurrentObj);
friend class CPrivatePolledActiveScheduler; // added
protected:
IMPORT_C virtual TInt Extension_(TUint aExtensionId, TAny*& a0, TAny* a1);
protected:
inline TInt Level() const {return StackDepth();} // deprecated
private:
TLoop* iStack;
TPriQue<CActive> iActiveQ;
TAny* iSpare;
};
class TCleanupItem;
class CleanupStack
{
public:
IMPORT_C static void PushL(TAny* aPtr);
IMPORT_C static void PushL(CBase* aPtr);
IMPORT_C static void PushL(TCleanupItem anItem);
IMPORT_C static void Pop();
IMPORT_C static void Pop(TInt aCount);
IMPORT_C static void PopAndDestroy();
IMPORT_C static void PopAndDestroy(TInt aCount);
IMPORT_C static void Check(TAny* aExpectedItem);
inline static void Pop(TAny* aExpectedItem);
inline static void Pop(TInt aCount, TAny* aLastExpectedItem);
inline static void PopAndDestroy(TAny* aExpectedItem);
inline static void PopAndDestroy(TInt aCount, TAny* aLastExpectedItem);
};
/*
* This will declare CPrivatePolledActiveScheduler as a friend
* of all classes that define a friend. CPrivatePolledActiveScheduler needs to
* be a friend of CActive
*/
//#define friend friend class CPrivatePolledActiveScheduler; friend
/*
* This will change the:
* void DoStart();
* method in CActiveScheduler to:
* void DoStart(); friend class CPrivatePolledActiveScheduler;
* We need this to access the private datamembers in CActiveScheduler.
*/
//#define DoStart() DoStart(); friend class CPrivatePolledActiveScheduler;
//#include <e32base.h>
#include "PolledAS.h"
class CPrivatePolledActiveScheduler : public CActiveScheduler
{
public:
void Schedule();
};
void CPrivatePolledActiveScheduler::Schedule()
{
TDblQueIter<CActive> q(iActiveQ);
q.SetToFirst();
FOREVER
{
CActive *pR=q++;
if (pR)
{
//TRequestStatus::EActive = 1, //bit0
//TRequestStatus::ERequestPending = 2, //bit1
if (pR->IsActive() && pR->iStatus!=KRequestPending)
{
// pR->iActive=EFalse; // won't this cause trouble?
pR->iStatus.iFlags&=~TRequestStatusFaked::EActive;
//debugPrintFile(_L("as: %08x"), pR);
TRAPD(r,pR->RunL());
//pR->iStatus=TRequestStatus::ERequestPending;
break;
}
}
else
break;
}
}
static CPolledActiveScheduler* sPolledActiveScheduler = NULL;
CPolledActiveScheduler::~CPolledActiveScheduler()
{
sPolledActiveScheduler = NULL;
delete iPrivatePolledActiveScheduler;
}
CPolledActiveScheduler* CPolledActiveScheduler::NewL()
{
// if (sPolledActiveScheduler == NULL)
{
sPolledActiveScheduler = new(ELeave)CPolledActiveScheduler;
CleanupStack::PushL(sPolledActiveScheduler);
sPolledActiveScheduler->ConstructL();
CleanupStack::Pop();
}
return sPolledActiveScheduler;
}
void CPolledActiveScheduler::ConstructL()
{
iPrivatePolledActiveScheduler = new(ELeave) CPrivatePolledActiveScheduler;
iPrivatePolledActiveScheduler->Install(iPrivatePolledActiveScheduler);
}
void CPolledActiveScheduler::Schedule()
{
iPrivatePolledActiveScheduler->Schedule();
}
CPolledActiveScheduler* CPolledActiveScheduler::Instance()
{
// return (CPolledActiveScheduler*) CActiveScheduler::Current();
return sPolledActiveScheduler;
}

View file

@ -0,0 +1,645 @@
// EmuScan routines for Pico, also simple text and shape drawing routines.
// (c) Copyright 2006, notaz
// All Rights Reserved
#include "vid.h"
#include "../Engine.h"
#include "../../../pico/picoInt.h"
#include "blit.h"
#include "debug.h"
// global stuff
extern TPicoConfig *currentConfig;
extern TPicoAreaConfigEntry areaConfig[];
extern const char *actionNames[];
// main framebuffer
static void *screenbuff = 0; // pointer to real device video memory
//static
extern "C" { unsigned char *framebuff = 0; } // temporary buffer
const int framebuffsize = (8+320)*(8+240+8)*2+8*2; // actual framebuffer size (in bytes+to support new rendering mode)
// drawer function pointers
static void (*drawTextFps)(const char *text) = 0;
static void (*drawTextNotice)(const char *text) = 0;
// blitter
static void (*vidBlit)(int full) = 0;
// colors
const unsigned short color_red = 0x022F;
const unsigned short color_red_dim = 0x0004;
const unsigned short color_green = 0x01F1;
const unsigned short color_blue = 0x0F11;
const unsigned short color_grey = 0x0222;
// other
int txtheight_fit = 138;
// bitmasks
static const unsigned long mask_numbers[] = {
0x12244800, // 47 2F /
0x69999600, // 48 30 0
0x26222200, // 49 31 1
0x69168F00, // 50 32 2
0x69219600, // 51 33 3
0x266AF200, // 52 34 4
0xF8E11E00, // 53 35 5
0x68E99600, // 54 36 6
0x71222200, // 55 37 7
0x69699600, // 56 38 8
0x69719600, // 57 39 9
0x04004000, // 58 3A :
0x04004400, // 59 3B ;
0x01242100, // 60 3C <
0x00707000, // 61 3D =
0x04212400, // 62 3E >
0x69240400, // 63 3F ?
0x00000000, // 64 40 @ [used instead of space for now]
0x22579900, // 65 41 A
0xE9E99E00, // 66 42 B
0x69889600, // 67 43 C
0xE9999E00, // 68 44 D
0xF8E88F00, // 69 45 E
0xF8E88800, // 70 46 F
0x698B9700, // 71 47 G
0x99F99900, // 72 48 H
0x44444400, // 73 49 I
0x11119600, // 74 4A J
0x9ACCA900, // 75 4B K
0x88888F00, // 76 4C L
0x9F999900, // 77 4D M
0x9DDBB900, // 78 4E N
0x69999600, // 79 4F O
0xE99E8800, // 80 50 P
0x6999A500, // 81 51 Q
0xE99E9900, // 82 52 R
0x69429600, // 83 53 S
0x72222200, // 84 54 T
0x99999600, // 85 55 U
0x55552200, // 86 56 V
0x9999F900, // 87 57 W
0x55225500, // 88 58 X
0x55222200, // 89 59 Y
0xF1248F00, // 90 5A Z
};
////////////////////////////////
// Cram functions
static int EmuCramNull(int cram)
{
User::Panic(_L("Cram called!!"), 0);
return cram;
}
////////////////////////////////
// PicoScan functions
static int EmuScan8(unsigned int num, void *sdata)
{
DrawLineDest = framebuff + 328*(num+1) + 328*8 + 8;
return 0;
}
static int EmuScanFit0(unsigned int num, void *sdata)
{
// 0.75, 168 lines
static int u = 0, num2 = 0;
if(!num) u = num2 = 0;
DrawLineDest = framebuff + 328*(++num2) + 328*8 + 8;
u += 6666;
if(u < 10000) {
// u += 7500;
return 1;
}
u -= 10000;
return 0;
}
////////////////////////////////
// text drawers
// warning: text must be at least 1px away from screen borders
static void drawTextM2(int x, int y, const char *text)
{
unsigned char *vidmem = framebuff + 328*8 + 8;
int charmask, i, cx = x, cy;
unsigned char *l, *le;
// darken the background (left border)
for(l=vidmem+(cx-1)+(y-1)*328, le=l+8*328; l < le; l+=328) *l = 0xE0;
for(const char *p=text; *p; p++) {
cy = y;
charmask = *(mask_numbers + (*p - 0x2F));
for(l = vidmem+cx+(y-1)*328, le = l+8*328; l < le; l+=328-4) {
*l = 0xE0; l++; *l = 0xE0; l++;
*l = 0xE0; l++; *l = 0xE0; l++;
*l = 0xE0;
}
for(i=0; i < 24; i++) {
if(charmask&0x80000000) *( vidmem + (cx+(i&3)) + (cy+(i>>2))*328 ) = 0xf0;
charmask <<= 1;
}
cx += 5;
}
}
static void drawTextM2Fat(int x, int y, const char *text)
{
unsigned char *vidmem = framebuff + 328*8 + 8;
int charmask, i, cx = x&~1, cy;
unsigned short *l, *le;
// darken the background (left border)
for(l=(unsigned short *)(vidmem+(cx-2)+(y-1)*328), le=l+8*328/2; l < le; l+=328/2) *l = 0xE0;
for(const char *p=text; *p; p++) {
cy = y;
for(l = (unsigned short *)(vidmem+cx+(y-1)*328), le = l+8*328/2; l < le; l+=328/2) {
l += 4;
*l-- = 0xe0e0; *l-- = 0xe0e0; *l-- = 0xe0e0; *l-- = 0xe0e0; *l = 0xe0e0;
}
charmask = *(mask_numbers + (*p - 0x2F));
for(i=0; i < 24; i++) {
if(charmask&0x80000000) *(unsigned short *)( vidmem + cx+(i&3)*2 + (cy+(i>>2))*328 ) = 0xf0f0;
charmask <<= 1;
}
cx += 5*2;
}
}
static void drawTextFpsCenter0(const char *text)
{
if(!text) return;
drawTextM2(214, 216, text);
}
static void drawTextFpsFit0(const char *text)
{
if(!text) return;
drawTextM2Fat((Pico.video.reg[12]&1) ? 256-32 : 224-32, 160, text);
}
static void drawTextFpsFit2_0(const char *text)
{
if(!text) return;
drawTextM2Fat((Pico.video.reg[12]&1) ? 256-32 : 224-32, 216, text);
}
static void drawTextFps0(const char *text)
{
if(!text) return;
drawTextM2((Pico.video.reg[12]&1) ? 256 : 224, 216, text);
}
static void drawTextNoticeCenter0(const char *text)
{
if(!text) return;
drawTextM2(2, 216, text);
}
static void drawTextNoticeFit0(const char *text)
{
if(!text) return;
drawTextM2Fat(2, 160, text);
}
static void drawTextNoticeFit2_0(const char *text)
{
if(!text) return;
drawTextM2Fat(2, 216, text);
}
static void drawTextNotice0(const char *text)
{
if(!text) return;
drawTextM2(2, 216, text);
}
// -----------------------------------------------------------------
static int localPal[0x100];
static void fillLocalPal(void)
{
Pico.m.dirtyPal = 0;
if (PicoOpt&0x10) {
// 8bit fast renderer
vidConvCpyRGB32(localPal, Pico.cram, 0x40);
return;
}
// 8bit accurate renderer
if(Pico.video.reg[0xC]&8) { // shadow/hilight mode
vidConvCpyRGB32(localPal, Pico.cram, 0x40);
vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40);
blockcpy(localPal+0xc0, localPal+0x40, 0x40*4);
localPal[0xe0] = 0x00000000; // reserved pixels for OSD
localPal[0xf0] = 0x00ee0000;
} else if (rendstatus & 0x20) { // mid-frame palette changes
vidConvCpyRGB32(localPal, Pico.cram, 0x40);
vidConvCpyRGB32(localPal+0x40, HighPal, 0x40);
vidConvCpyRGB32(localPal+0x80, HighPal+0x40, 0x40);
} else {
vidConvCpyRGB32(localPal, Pico.cram, 0x40);
}
}
// note: the internal 8 pixel border is taken care by asm code
static void vidBlit_90(int full)
{
unsigned char *ps = framebuff+328*8;
unsigned long *pd = (unsigned long *) screenbuff;
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_90(pd, ps, localPal, 320/8);
else {
if(full) vidClear(pd, 32);
pd += 256*32;
vidConvCpy_90(pd, ps, localPal, 256/8);
if(full) vidClear(pd + 256*256, 32);
}
}
static void vidBlit_270(int full)
{
unsigned char *ps = framebuff+328*8;
unsigned long *pd = (unsigned long *) screenbuff;
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_270(pd, ps, localPal, 320/8);
else {
if(full) vidClear(pd, 32);
pd += 256*32;
ps -= 64; // the blitter starts copying from the right border, so we need to adjust
vidConvCpy_270(pd, ps, localPal, 256/8);
if(full) vidClear(pd + 256*256, 32);
}
}
static void vidBlitCenter_0(int full)
{
unsigned char *ps = framebuff+328*8+8;
unsigned long *pd = (unsigned long *) screenbuff;
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1) ps += 32;
vidConvCpy_center_0(pd, ps, localPal);
if(full) vidClear(pd + 224*256, 96);
}
static void vidBlitCenter_180(int full)
{
unsigned char *ps = framebuff+328*8+8;
unsigned long *pd = (unsigned long *) screenbuff;
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1) ps += 32;
vidConvCpy_center_180(pd, ps, localPal);
if(full) vidClear(pd + 224*256, 96);
}
static void vidBlitFit_0(int full)
{
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_center2_40c_0(screenbuff, framebuff+328*8, localPal, 168);
else vidConvCpy_center2_32c_0(screenbuff, framebuff+328*8, localPal, 168);
if(full) vidClear((unsigned long *)screenbuff + 168*256, 320-168);
}
static void vidBlitFit_180(int full)
{
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_center2_40c_180(screenbuff, framebuff+328*8, localPal, 168);
else vidConvCpy_center2_32c_180(screenbuff, framebuff+328*8-64, localPal, 168);
if(full) vidClear((unsigned long *)screenbuff + 168*256, 320-168);
}
static void vidBlitFit2_0(int full)
{
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_center2_40c_0(screenbuff, framebuff+328*8, localPal, 224);
else vidConvCpy_center2_32c_0(screenbuff, framebuff+328*8, localPal, 224);
if(full) vidClear((unsigned long *)screenbuff + 224*256, 96);
}
static void vidBlitFit2_180(int full)
{
if (Pico.m.dirtyPal) fillLocalPal();
if(Pico.video.reg[12]&1)
vidConvCpy_center2_40c_180(screenbuff, framebuff+328*8, localPal, 224);
else vidConvCpy_center2_32c_180(screenbuff, framebuff+328*8-64, localPal, 224);
if(full) vidClear((unsigned long *)screenbuff + 224*256, 96);
}
static void vidBlitCfg(void)
{
unsigned short *ps = (unsigned short *) framebuff;
unsigned long *pd = (unsigned long *) screenbuff;
int i;
// hangs randomly (due to repeated ldms/stms?)
//for (int i = 1; i < 320; i++, ps += 240, pd += 256)
// vidConvCpyRGB32(pd, ps, 240);
for (i = 0; i < 320; i++, pd += 16)
for (int u = 0; u < 240; u++, ps++, pd++)
*pd = ((*ps & 0xf) << 20) | ((*ps & 0xf0) << 8) | ((*ps & 0xf00) >> 4);
}
////////////////////////////////
// main functions
int vidInit(void *vidmem, int reinit)
{
if(!reinit) {
// prepare framebuffer
screenbuff = vidmem;
framebuff = (unsigned char *) malloc(framebuffsize);
if(!screenbuff) return KErrNotSupported;
if(!framebuff) return KErrNoMemory;
memset(framebuff, 0, framebuffsize);
// Cram function: go and hack Pico so it never gets called
PicoCram = EmuCramNull;
}
// select suitable blitters
vidBlit = vidBlit_270;
PicoScan = EmuScan8;
drawTextFps = drawTextFps0;
drawTextNotice = drawTextNotice0;
memset(localPal, 0, 0x100*4);
localPal[0xe0] = 0x00000000; // reserved pixels for OSD
localPal[0xf0] = 0x00ee0000;
// setup all orientation related stuff
if(currentConfig->iScreenRotation == TPicoConfig::PRot0) {
if(currentConfig->iScreenMode == TPicoConfig::PMCenter) {
vidBlit = vidBlitCenter_0;
drawTextFps = drawTextFpsCenter0;
drawTextNotice = drawTextNoticeCenter0;
} else if(currentConfig->iScreenMode == TPicoConfig::PMFit2) {
vidBlit = vidBlitFit2_0;
drawTextFps = drawTextFpsFit2_0;
drawTextNotice = drawTextNoticeFit2_0;
} else {
vidBlit = vidBlitFit_0;
drawTextFps = drawTextFpsFit0;
drawTextNotice = drawTextNoticeFit0;
PicoScan = EmuScanFit0;
}
} else if(currentConfig->iScreenRotation == TPicoConfig::PRot90) {
vidBlit = vidBlit_90;
} else if(currentConfig->iScreenRotation == TPicoConfig::PRot180) {
if(currentConfig->iScreenMode == TPicoConfig::PMCenter) {
vidBlit = vidBlitCenter_180;
drawTextFps = drawTextFpsCenter0;
drawTextNotice = drawTextNoticeCenter0;
} else if(currentConfig->iScreenMode == TPicoConfig::PMFit2) {
vidBlit = vidBlitFit2_180;
drawTextFps = drawTextFpsFit2_0;
drawTextNotice = drawTextNoticeFit2_0;
} else {
vidBlit = vidBlitFit_180;
drawTextFps = drawTextFpsFit0;
drawTextNotice = drawTextNoticeFit0;
PicoScan = EmuScanFit0;
}
} else if(currentConfig->iScreenRotation == TPicoConfig::PRot270) {
vidBlit = vidBlit_270;
}
vidBlit(1);
PicoOpt |= 0x100;
Pico.m.dirtyPal = 1;
return 0;
}
void vidFree()
{
free(framebuff);
framebuff = 0;
}
void vidDrawFrame(char *noticeStr, char *fpsStr, int num)
{
DrawLineDest = framebuff + 328*8 + 8;
// PicoFrame(); // moved to main loop
if(currentConfig->iFlags & 2)
drawTextFps(fpsStr);
drawTextNotice(noticeStr);
vidBlit(!num); // copy full frame once a second
}
// -----------------------------------------------------------------
static void drawText0(int x, int y, const char *text, long color)
{
unsigned short *vidmem=(unsigned short *)framebuff;
int charmask, i, cx = x, cy;
unsigned short *l, *le, dmask=0x0333;
// darken the background (left border)
for(l=vidmem+(cx-1)+(y-1)*240, le=vidmem+(cx-1)+(y+7)*240; l < le; l+=240)
*l = (*l >> 2) & dmask;
for(const char *p=text; *p; p++) {
cy = y;
charmask = *(mask_numbers + (*p - 0x2F));
for(l = vidmem+cx+(y-1)*240, le = vidmem+cx+(y+7)*240; l < le; l+=240-4) {
*l = (*l >> 2) & dmask; l++; *l = (*l >> 2) & dmask; l++;
*l = (*l >> 2) & dmask; l++; *l = (*l >> 2) & dmask; l++;
*l = (*l >> 2) & dmask;
}
for(i=0; i < 24; i++) {
// draw dot. Is this fast?
if(charmask&0x80000000) *( vidmem + (cx+(i&3)) + (cy+(i>>2))*240 ) = color;
charmask <<= 1;
}
cx += 5;
}
}
// draws rect with width - 1 and height - 1
static void drawRect(const TRect &rc, unsigned short color)
{
unsigned short *vidmem=(unsigned short *)framebuff;
if(rc.iTl.iX - rc.iBr.iX && rc.iTl.iY - rc.iBr.iY) {
int stepX = rc.iTl.iX < rc.iBr.iX ? 1 : -1;
int stepY = rc.iTl.iY < rc.iBr.iY ? 1 : -1;
for(int x = rc.iTl.iX;; x += stepX) {
*(vidmem + rc.iTl.iY*240 + x) = *(vidmem + (rc.iBr.iY - stepY)*240 + x) = color;
if(x == rc.iBr.iX - stepX) break;
}
for(int y = rc.iTl.iY;; y += stepY) {
*(vidmem + y*240 + rc.iTl.iX) = *(vidmem + y*240 + rc.iBr.iX - stepX) = color;
if(y == rc.iBr.iY - stepY) break;
}
}
}
// draws fullsize filled rect
static void drawRectFilled(const TRect rc, unsigned short color)
{
unsigned short *vidmem=(unsigned short *)framebuff;
if(rc.iTl.iX - rc.iBr.iX && rc.iTl.iY - rc.iBr.iY) {
int stepX = rc.iTl.iX < rc.iBr.iX ? 1 : -1;
int stepY = rc.iTl.iY < rc.iBr.iY ? 1 : -1;
for(int y = rc.iTl.iY;; y += stepY) {
for(int x = rc.iTl.iX;; x += stepX) {
*(vidmem + y*240 + x) = *(vidmem + y*240 + x) = color;
if(x == rc.iBr.iX) break;
}
if(y == rc.iBr.iY) break;
}
}
}
// direction: -1 left, 1 right
static void drawArrow0(TPoint p, int direction, unsigned short color)
{
unsigned short *vidmem=(unsigned short *)framebuff;
int width = 15;
int x = p.iX;
int y = p.iY;
for(; width > 0; x+=direction, y++, width -=2)
for(int i=0; i < width; i++)
*(vidmem + x + y*240 + i*240) = color;
}
static char *vidGetScanName(int scan)
{
static char buff[32];
if((scan >= '0' && scan <= '9') || (scan >= 'A' && scan <= 'Z')) {
buff[0] = (char) scan; buff[1] = 0;
} else {
switch(scan) {
case 0x01: strcpy(buff, "BSPACE"); break;
case 0x03: strcpy(buff, "OK"); break;
case 0x05: strcpy(buff, "SPACE"); break;
case 0x0e: strcpy(buff, "AST"); break;
case 0x0f: strcpy(buff, "HASH"); break;
case 0x12: strcpy(buff, "SHIFT"); break;
case 0x19: strcpy(buff, "ALT"); break;
case 0x79: strcpy(buff, "PLUS"); break;
case 0x7a: strcpy(buff, "DOT"); break;
case 0xa5: strcpy(buff, "JOG@UP"); break;
case 0xa6: strcpy(buff, "JOG@DOWN"); break;
case 0xb5: strcpy(buff, "INET"); break;
case 0xd4: strcpy(buff, "JOG@PUSH"); break;
case 0xd5: strcpy(buff, "BACK"); break;
default: sprintf(buff, "KEY@%02X", scan); break;
}
}
return buff;
}
void vidKeyConfigFrame(const TUint whichAction)
{
int i;
char buttonNames[128];
buttonNames[0] = 0;
memset(framebuff, 0, framebuffsize);
unsigned long currentActCode = 1 << whichAction;
// draw all "buttons" in reverse order
const TPicoAreaConfigEntry *e = areaConfig + 1; i = 0;
while(e->rect != TRect(0,0,0,0)) { e++; i++; }
for(e--, i--; e->rect != TRect(0,0,0,0); e--, i--)
drawRect(e->rect, (currentConfig->iAreaBinds[i] & currentActCode) ? color_red : color_red_dim);
// action name control
drawRectFilled(TRect(72, 2, 168, 20), color_grey); // 96x14
drawArrow0(TPoint(80, 3), -1, color_green);
drawArrow0(TPoint(160, 3), 1, color_green);
drawText0(86, 9, actionNames[whichAction], color_red);
// draw active button names if there are any
for(i = 0; i < 256; i++) {
if(currentConfig->iKeyBinds[i] & currentActCode) {
if(buttonNames[0]) strcat(buttonNames, ";@");
strcat(buttonNames, vidGetScanName(i));
}
}
if(buttonNames[0]) {
buttonNames[61] = 0; // only 60 chars fit
drawText0(6, 48, buttonNames, color_blue);
}
vidBlitCfg();
}
void vidDrawNotice(const char *txt)
{
if(framebuff) {
drawTextNotice(txt);
vidBlit(1);
}
}

View file

@ -0,0 +1,9 @@
#include <e32base.h>
// let's do it in more c-like way
int vidInit(void *vidmem, int reinit);
void vidFree();
void vidDrawFrame(char *noticeStr, char *fpsStr, int num);
void vidKeyConfigFrame(const TUint whichAction);
void vidDrawFCconfigDone();
void vidDrawNotice(const char *txt); // safe to call anytime, draws text for 1 frame