SWORD25: Enforced code formatting rules in rest of the engine

svn-id: r53626
This commit is contained in:
Eugene Sandulenko 2010-10-19 21:03:33 +00:00
parent ae78107e2a
commit 6629efc676
54 changed files with 1520 additions and 1991 deletions

View file

@ -65,11 +65,11 @@ MoviePlayer::~MoviePlayer() {
bool MoviePlayer::loadMovie(const Common::String &filename, uint z) { bool MoviePlayer::loadMovie(const Common::String &filename, uint z) {
// Get the file and load it into the decoder // Get the file and load it into the decoder
Common::SeekableReadStream *in = Kernel::GetInstance()->GetPackage()->getStream(filename); Common::SeekableReadStream *in = Kernel::getInstance()->getPackage()->getStream(filename);
_decoder.load(in); _decoder.load(in);
// Ausgabebitmap erstellen // Ausgabebitmap erstellen
GraphicEngine *pGfx = Kernel::GetInstance()->GetGfx(); GraphicEngine *pGfx = Kernel::getInstance()->getGfx();
#if INDIRECTRENDERING #if INDIRECTRENDERING
_outputBitmap = pGfx->getMainPanel()->addDynamicBitmap(_decoder.getWidth(), _decoder.getHeight()); _outputBitmap = pGfx->getMainPanel()->addDynamicBitmap(_decoder.getWidth(), _decoder.getHeight());
@ -167,7 +167,7 @@ void MoviePlayer::setScaleFactor(float scaleFactor) {
_outputBitmap->setScaleFactor(scaleFactor); _outputBitmap->setScaleFactor(scaleFactor);
// Ausgabebitmap auf dem Bildschirm zentrieren // Ausgabebitmap auf dem Bildschirm zentrieren
GraphicEngine *gfxPtr = Kernel::GetInstance()->GetGfx(); GraphicEngine *gfxPtr = Kernel::getInstance()->getGfx();
_outputBitmap->setX((gfxPtr->getDisplayWidth() - _outputBitmap->getWidth()) / 2); _outputBitmap->setX((gfxPtr->getDisplayWidth() - _outputBitmap->getWidth()) / 2);
_outputBitmap->setY((gfxPtr->getDisplayHeight() - _outputBitmap->getHeight()) / 2); _outputBitmap->setY((gfxPtr->getDisplayHeight() - _outputBitmap->getHeight()) / 2);
} }

View file

@ -44,7 +44,7 @@
namespace Sword25 { namespace Sword25 {
int loadMovie(lua_State *L) { int loadMovie(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->loadMovie(luaL_checkstring(L, 1), lua_gettop(L) == 2 ? static_cast<uint>(luaL_checknumber(L, 2)) : 10)); lua_pushbooleancpp(L, FMVPtr->loadMovie(luaL_checkstring(L, 1), lua_gettop(L) == 2 ? static_cast<uint>(luaL_checknumber(L, 2)) : 10));
@ -53,7 +53,7 @@ int loadMovie(lua_State *L) {
} }
int unloadMovie(lua_State *L) { int unloadMovie(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->unloadMovie()); lua_pushbooleancpp(L, FMVPtr->unloadMovie());
@ -62,7 +62,7 @@ int unloadMovie(lua_State *L) {
} }
int play(lua_State *L) { int play(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->play()); lua_pushbooleancpp(L, FMVPtr->play());
@ -71,7 +71,7 @@ int play(lua_State *L) {
} }
int pause(lua_State *L) { int pause(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->pause()); lua_pushbooleancpp(L, FMVPtr->pause());
@ -80,7 +80,7 @@ int pause(lua_State *L) {
} }
int update(lua_State *L) { int update(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
FMVPtr->update(); FMVPtr->update();
@ -89,7 +89,7 @@ int update(lua_State *L) {
} }
int isMovieLoaded(lua_State *L) { int isMovieLoaded(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->isMovieLoaded()); lua_pushbooleancpp(L, FMVPtr->isMovieLoaded());
@ -98,7 +98,7 @@ int isMovieLoaded(lua_State *L) {
} }
int isPaused(lua_State *L) { int isPaused(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushbooleancpp(L, FMVPtr->isPaused()); lua_pushbooleancpp(L, FMVPtr->isPaused());
@ -107,7 +107,7 @@ int isPaused(lua_State *L) {
} }
int getScaleFactor(lua_State *L) { int getScaleFactor(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushnumber(L, FMVPtr->getScaleFactor()); lua_pushnumber(L, FMVPtr->getScaleFactor());
@ -116,7 +116,7 @@ int getScaleFactor(lua_State *L) {
} }
int setScaleFactor(lua_State *L) { int setScaleFactor(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
FMVPtr->setScaleFactor(static_cast<float>(luaL_checknumber(L, 1))); FMVPtr->setScaleFactor(static_cast<float>(luaL_checknumber(L, 1)));
@ -125,7 +125,7 @@ int setScaleFactor(lua_State *L) {
} }
int getTime(lua_State *L) { int getTime(lua_State *L) {
MoviePlayer *FMVPtr = Kernel::GetInstance()->GetFMV(); MoviePlayer *FMVPtr = Kernel::getInstance()->getFMV();
BS_ASSERT(FMVPtr); BS_ASSERT(FMVPtr);
lua_pushnumber(L, FMVPtr->getTime()); lua_pushnumber(L, FMVPtr->getTime());
@ -150,7 +150,7 @@ const luaL_reg LIBRARY_FUNCTIONS[] = {
}; };
bool MoviePlayer::registerScriptBindings() { bool MoviePlayer::registerScriptBindings() {
ScriptEngine *pScript = Kernel::GetInstance()->GetScript(); ScriptEngine *pScript = Kernel::getInstance()->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -99,8 +99,8 @@ Animation::Animation(InputPersistenceBlock &reader, RenderObjectPtr<RenderObject
void Animation::initializeAnimationResource(const Common::String &fileName) { void Animation::initializeAnimationResource(const Common::String &fileName) {
// Die Resource wird für die gesamte Lebensdauer des Animations-Objektes gelockt. // Die Resource wird für die gesamte Lebensdauer des Animations-Objektes gelockt.
Resource *resourcePtr = Kernel::GetInstance()->GetResourceManager()->RequestResource(fileName); Resource *resourcePtr = Kernel::getInstance()->getResourceManager()->requestResource(fileName);
if (resourcePtr && resourcePtr->GetType() == Resource::TYPE_ANIMATION) if (resourcePtr && resourcePtr->getType() == Resource::TYPE_ANIMATION)
_animationResourcePtr = static_cast<AnimationResource *>(resourcePtr); _animationResourcePtr = static_cast<AnimationResource *>(resourcePtr);
else { else {
BS_LOG_ERRORLN("The resource \"%s\" could not be requested. The Animation can't be created.", fileName.c_str()); BS_LOG_ERRORLN("The resource \"%s\" could not be requested. The Animation can't be created.", fileName.c_str());
@ -182,13 +182,13 @@ bool Animation::doRender() {
BS_ASSERT(_currentFrame < animationDescriptionPtr->getFrameCount()); BS_ASSERT(_currentFrame < animationDescriptionPtr->getFrameCount());
// Bitmap des aktuellen Frames holen // Bitmap des aktuellen Frames holen
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(animationDescriptionPtr->getFrame(_currentFrame).fileName); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(animationDescriptionPtr->getFrame(_currentFrame).fileName);
BS_ASSERT(pResource); BS_ASSERT(pResource);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
BitmapResource *pBitmapResource = static_cast<BitmapResource *>(pResource); BitmapResource *pBitmapResource = static_cast<BitmapResource *>(pResource);
// Framebufferobjekt holen // Framebufferobjekt holen
GraphicEngine *pGfx = Kernel::GetInstance()->GetGfx(); GraphicEngine *pGfx = Kernel::getInstance()->getGfx();
BS_ASSERT(pGfx); BS_ASSERT(pGfx);
// Bitmap zeichnen // Bitmap zeichnen
@ -315,9 +315,9 @@ void Animation::computeCurrentCharacteristics() {
BS_ASSERT(animationDescriptionPtr); BS_ASSERT(animationDescriptionPtr);
const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame); const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame);
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(curFrame.fileName); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(curFrame.fileName);
BS_ASSERT(pResource); BS_ASSERT(pResource);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource); BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource);
// Größe des Bitmaps auf die Animation übertragen // Größe des Bitmaps auf die Animation übertragen
@ -338,7 +338,7 @@ bool Animation::lockAllFrames() {
AnimationDescription *animationDescriptionPtr = getAnimationDescription(); AnimationDescription *animationDescriptionPtr = getAnimationDescription();
BS_ASSERT(animationDescriptionPtr); BS_ASSERT(animationDescriptionPtr);
for (uint i = 0; i < animationDescriptionPtr->getFrameCount(); ++i) { for (uint i = 0; i < animationDescriptionPtr->getFrameCount(); ++i) {
if (!Kernel::GetInstance()->GetResourceManager()->RequestResource(animationDescriptionPtr->getFrame(i).fileName)) { if (!Kernel::getInstance()->getResourceManager()->requestResource(animationDescriptionPtr->getFrame(i).fileName)) {
BS_LOG_ERRORLN("Could not lock all animation frames."); BS_LOG_ERRORLN("Could not lock all animation frames.");
return false; return false;
} }
@ -356,14 +356,14 @@ bool Animation::unlockAllFrames() {
BS_ASSERT(animationDescriptionPtr); BS_ASSERT(animationDescriptionPtr);
for (uint i = 0; i < animationDescriptionPtr->getFrameCount(); ++i) { for (uint i = 0; i < animationDescriptionPtr->getFrameCount(); ++i) {
Resource *pResource; Resource *pResource;
if (!(pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(animationDescriptionPtr->getFrame(i).fileName))) { if (!(pResource = Kernel::getInstance()->getResourceManager()->requestResource(animationDescriptionPtr->getFrame(i).fileName))) {
BS_LOG_ERRORLN("Could not unlock all animation frames."); BS_LOG_ERRORLN("Could not unlock all animation frames.");
return false; return false;
} }
// Zwei mal freigeben um den Request von LockAllFrames() und den jetzigen Request aufzuheben // Zwei mal freigeben um den Request von LockAllFrames() und den jetzigen Request aufzuheben
pResource->release(); pResource->release();
if (pResource->GetLockCount()) if (pResource->getLockCount())
pResource->release(); pResource->release();
} }
@ -524,9 +524,9 @@ int Animation::computeXModifier() const {
BS_ASSERT(animationDescriptionPtr); BS_ASSERT(animationDescriptionPtr);
const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame); const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame);
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(curFrame.fileName); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(curFrame.fileName);
BS_ASSERT(pResource); BS_ASSERT(pResource);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource); BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource);
int result = curFrame.flipV ? - static_cast<int>((pBitmap->getWidth() - 1 - curFrame.hotspotX) * _scaleFactorX) : int result = curFrame.flipV ? - static_cast<int>((pBitmap->getWidth() - 1 - curFrame.hotspotX) * _scaleFactorX) :
@ -542,9 +542,9 @@ int Animation::computeYModifier() const {
BS_ASSERT(animationDescriptionPtr); BS_ASSERT(animationDescriptionPtr);
const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame); const AnimationResource::Frame &curFrame = animationDescriptionPtr->getFrame(_currentFrame);
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(curFrame.fileName); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(curFrame.fileName);
BS_ASSERT(pResource); BS_ASSERT(pResource);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource); BitmapResource *pBitmap = static_cast<BitmapResource *>(pResource);
int result = curFrame.flipH ? - static_cast<int>((pBitmap->getHeight() - 1 - curFrame.hotspotY) * _scaleFactorY) : int result = curFrame.flipH ? - static_cast<int>((pBitmap->getHeight() - 1 - curFrame.hotspotY) * _scaleFactorY) :

View file

@ -54,7 +54,7 @@ AnimationResource::AnimationResource(const Common::String &filename) :
Common::XMLParser(), Common::XMLParser(),
_valid(false) { _valid(false) {
// Get a pointer to the package manager // Get a pointer to the package manager
_pPackage = Kernel::GetInstance()->GetPackage(); _pPackage = Kernel::getInstance()->getPackage();
BS_ASSERT(_pPackage); BS_ASSERT(_pPackage);
// Switch to the folder the specified Xml fiile is in // Switch to the folder the specified Xml fiile is in
@ -211,7 +211,7 @@ AnimationResource::~AnimationResource() {
bool AnimationResource::precacheAllFrames() const { bool AnimationResource::precacheAllFrames() const {
Common::Array<Frame>::const_iterator iter = _frames.begin(); Common::Array<Frame>::const_iterator iter = _frames.begin();
for (; iter != _frames.end(); ++iter) { for (; iter != _frames.end(); ++iter) {
if (!Kernel::GetInstance()->GetResourceManager()->PrecacheResource((*iter).fileName)) { if (!Kernel::getInstance()->getResourceManager()->precacheResource((*iter).fileName)) {
BS_LOG_ERRORLN("Could not precache \"%s\".", (*iter).fileName.c_str()); BS_LOG_ERRORLN("Could not precache \"%s\".", (*iter).fileName.c_str());
return false; return false;
} }
@ -232,7 +232,7 @@ bool AnimationResource::computeFeatures() {
Common::Array<Frame>::const_iterator iter = _frames.begin(); Common::Array<Frame>::const_iterator iter = _frames.begin();
for (; iter != _frames.end(); ++iter) { for (; iter != _frames.end(); ++iter) {
BitmapResource *pBitmap; BitmapResource *pBitmap;
if (!(pBitmap = static_cast<BitmapResource *>(Kernel::GetInstance()->GetResourceManager()->RequestResource((*iter).fileName)))) { if (!(pBitmap = static_cast<BitmapResource *>(Kernel::getInstance()->getResourceManager()->requestResource((*iter).fileName)))) {
BS_LOG_ERRORLN("Could not request \"%s\".", (*iter).fileName.c_str()); BS_LOG_ERRORLN("Could not request \"%s\".", (*iter).fileName.c_str());
return false; return false;
} }

View file

@ -125,9 +125,9 @@ AnimationTemplate::AnimationTemplate(InputPersistenceBlock &reader, uint handle)
} }
AnimationResource *AnimationTemplate::requestSourceAnimation(const Common::String &sourceAnimation) const { AnimationResource *AnimationTemplate::requestSourceAnimation(const Common::String &sourceAnimation) const {
ResourceManager *RMPtr = Kernel::GetInstance()->GetResourceManager(); ResourceManager *RMPtr = Kernel::getInstance()->getResourceManager();
Resource *resourcePtr; Resource *resourcePtr;
if (NULL == (resourcePtr = RMPtr->RequestResource(sourceAnimation)) || resourcePtr->GetType() != Resource::TYPE_ANIMATION) { if (NULL == (resourcePtr = RMPtr->requestResource(sourceAnimation)) || resourcePtr->getType() != Resource::TYPE_ANIMATION) {
BS_LOG_ERRORLN("The resource \"%s\" could not be requested or is has an invalid type. The animation template can't be created.", sourceAnimation.c_str()); BS_LOG_ERRORLN("The resource \"%s\" could not be requested or is has an invalid type. The animation template can't be created.", sourceAnimation.c_str());
return 0; return 0;
} }

View file

@ -77,7 +77,7 @@ uint DynamicBitmap::getPixel(int x, int y) const {
bool DynamicBitmap::doRender() { bool DynamicBitmap::doRender() {
// Framebufferobjekt holen // Framebufferobjekt holen
GraphicEngine *pGfx = Kernel::GetInstance()->GetGfx(); GraphicEngine *pGfx = Kernel::getInstance()->getGfx();
BS_ASSERT(pGfx); BS_ASSERT(pGfx);
// Bitmap zeichnen // Bitmap zeichnen

View file

@ -55,7 +55,7 @@ FontResource::FontResource(Kernel *pKernel, const Common::String &fileName) :
// Get a pointer to the package manager // Get a pointer to the package manager
BS_ASSERT(_pKernel); BS_ASSERT(_pKernel);
PackageManager *pPackage = _pKernel->GetPackage(); PackageManager *pPackage = _pKernel->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
// Load the contents of the file // Load the contents of the file
@ -93,7 +93,7 @@ bool FontResource::parserCallback_font(ParserNode *node) {
// Get a reference to the package manager // Get a reference to the package manager
BS_ASSERT(_pKernel); BS_ASSERT(_pKernel);
PackageManager *pPackage = _pKernel->GetPackage(); PackageManager *pPackage = _pKernel->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
// Get the full path and filename for the bitmap resource // Get the full path and filename for the bitmap resource
@ -104,7 +104,7 @@ bool FontResource::parserCallback_font(ParserNode *node) {
} }
// Pre-cache the resource // Pre-cache the resource
if (!_pKernel->GetResourceManager()->PrecacheResource(_bitmapFileName)) { if (!_pKernel->getResourceManager()->precacheResource(_bitmapFileName)) {
BS_LOG_ERRORLN("Could not precache \"%s\".", _bitmapFileName.c_str()); BS_LOG_ERRORLN("Could not precache \"%s\".", _bitmapFileName.c_str());
} }

View file

@ -306,7 +306,7 @@ Resource *GraphicEngine::loadResource(const Common::String &filename) {
debug(2, "VectorImage: %s", filename.c_str()); debug(2, "VectorImage: %s", filename.c_str());
// Pointer auf Package-Manager holen // Pointer auf Package-Manager holen
PackageManager *pPackage = Kernel::GetInstance()->GetPackage(); PackageManager *pPackage = Kernel::getInstance()->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
// Datei laden // Datei laden
@ -349,7 +349,7 @@ Resource *GraphicEngine::loadResource(const Common::String &filename) {
// Load font // Load font
if (filename.hasSuffix("_fnt.xml")) { if (filename.hasSuffix("_fnt.xml")) {
FontResource *pResource = new FontResource(Kernel::GetInstance(), filename); FontResource *pResource = new FontResource(Kernel::getInstance(), filename);
if (pResource->isValid()) if (pResource->isValid())
return pResource; return pResource;
else { else {
@ -383,7 +383,7 @@ void GraphicEngine::drawDebugLine(const Vertex &start, const Vertex &end, uint c
void GraphicEngine::updateLastFrameDuration() { void GraphicEngine::updateLastFrameDuration() {
// Record current time // Record current time
const uint currentTime = Kernel::GetInstance()->GetMilliTicks(); const uint currentTime = Kernel::getInstance()->getMilliTicks();
// Compute the elapsed time since the last frame and prevent too big ( > 250 msecs) time jumps. // Compute the elapsed time since the last frame and prevent too big ( > 250 msecs) time jumps.
// These can occur when loading save states, during debugging or due to hardware inaccuracies. // These can occur when loading save states, during debugging or due to hardware inaccuracies.

View file

@ -209,9 +209,9 @@ static const luaL_reg ANIMATION_TEMPLATE_METHODS[] = {
}; };
static GraphicEngine *getGE() { static GraphicEngine *getGE() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
GraphicEngine *pGE = pKernel->GetGfx(); GraphicEngine *pGE = pKernel->getGfx();
BS_ASSERT(pGE); BS_ASSERT(pGE);
return pGE; return pGE;
} }
@ -1039,7 +1039,7 @@ static int a_isPlaying(lua_State *L) {
} }
static bool animationLoopPointCallback(uint handle) { static bool animationLoopPointCallback(uint handle) {
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject()); lua_State *L = static_cast<lua_State *>(Kernel::getInstance()->getScript()->getScriptObject());
loopPointCallbackPtr->invokeCallbackFunctions(L, handle); loopPointCallbackPtr->invokeCallbackFunctions(L, handle);
return true; return true;
@ -1071,7 +1071,7 @@ static bool animationActionCallback(uint Handle) {
RenderObjectPtr<Animation> animationPtr(Handle); RenderObjectPtr<Animation> animationPtr(Handle);
if (animationPtr.isValid()) { if (animationPtr.isValid()) {
actionCallbackPtr->Action = animationPtr->getCurrentAction(); actionCallbackPtr->Action = animationPtr->getCurrentAction();
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject()); lua_State *L = static_cast<lua_State *>(Kernel::getInstance()->getScript()->getScriptObject());
actionCallbackPtr->invokeCallbackFunctions(L, animationPtr->getHandle()); actionCallbackPtr->invokeCallbackFunctions(L, animationPtr->getHandle());
} }
@ -1101,7 +1101,7 @@ static int a_unregisterActionCallback(lua_State *L) {
} }
static bool animationDeleteCallback(uint Handle) { static bool animationDeleteCallback(uint Handle) {
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject()); lua_State *L = static_cast<lua_State *>(Kernel::getInstance()->getScript()->getScriptObject());
loopPointCallbackPtr->removeAllObjectCallbacks(L, Handle); loopPointCallbackPtr->removeAllObjectCallbacks(L, Handle);
return true; return true;
@ -1268,9 +1268,9 @@ static const luaL_reg TEXT_METHODS[] = {
}; };
bool GraphicEngine::registerScriptBindings() { bool GraphicEngine::registerScriptBindings() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pScript = pKernel->GetScript(); ScriptEngine *pScript = pKernel->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -56,10 +56,10 @@ RenderedImage::RenderedImage(const Common::String &filename, bool &result) :
_height(0) { _height(0) {
result = false; result = false;
PackageManager *pPackage = Kernel::GetInstance()->GetPackage(); PackageManager *pPackage = Kernel::getInstance()->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
_backSurface = Kernel::GetInstance()->GetGfx()->getSurface(); _backSurface = Kernel::getInstance()->getGfx()->getSurface();
// Datei laden // Datei laden
byte *pFileData; byte *pFileData;
@ -103,7 +103,7 @@ RenderedImage::RenderedImage(uint width, uint height, bool &result) :
_data = new byte[width * height * 4]; _data = new byte[width * height * 4];
Common::set_to(_data, &_data[width * height * 4], 0); Common::set_to(_data, &_data[width * height * 4], 0);
_backSurface = Kernel::GetInstance()->GetGfx()->getSurface(); _backSurface = Kernel::getInstance()->getGfx()->getSurface();
_doCleanup = true; _doCleanup = true;
@ -112,7 +112,7 @@ RenderedImage::RenderedImage(uint width, uint height, bool &result) :
} }
RenderedImage::RenderedImage() : _width(0), _height(0), _data(0) { RenderedImage::RenderedImage() : _width(0), _height(0), _data(0) {
_backSurface = Kernel::GetInstance()->GetGfx()->getSurface(); _backSurface = Kernel::getInstance()->getGfx()->getSurface();
_doCleanup = false; _doCleanup = false;

View file

@ -47,7 +47,7 @@ SWImage::SWImage(const Common::String &filename, bool &result) :
_height(0) { _height(0) {
result = false; result = false;
PackageManager *pPackage = Kernel::GetInstance()->GetPackage(); PackageManager *pPackage = Kernel::getInstance()->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
// Datei laden // Datei laden

View file

@ -77,7 +77,7 @@ bool Panel::doRender() {
if (_color >> 24 == 0) if (_color >> 24 == 0)
return true; return true;
GraphicEngine *gfxPtr = Kernel::GetInstance()->GetGfx(); GraphicEngine *gfxPtr = Kernel::getInstance()->getGfx();
BS_ASSERT(gfxPtr); BS_ASSERT(gfxPtr);
return gfxPtr->fill(&_bbox, _color); return gfxPtr->fill(&_bbox, _color);

View file

@ -63,7 +63,7 @@ void RenderObjectManager::startFrame() {
_frameStarted = true; _frameStarted = true;
// Verstrichene Zeit bestimmen // Verstrichene Zeit bestimmen
int timeElapsed = Kernel::GetInstance()->GetGfx()->getLastFrameDurationMicro(); int timeElapsed = Kernel::getInstance()->getGfx()->getLastFrameDurationMicro();
// Alle BS_TimedRenderObject Objekte über den Framestart und die verstrichene Zeit in Kenntnis setzen // Alle BS_TimedRenderObject Objekte über den Framestart und die verstrichene Zeit in Kenntnis setzen
RenderObjectList::iterator iter = _timedRenderObjects.begin(); RenderObjectList::iterator iter = _timedRenderObjects.begin();

View file

@ -58,12 +58,12 @@ StaticBitmap::StaticBitmap(InputPersistenceBlock &reader, RenderObjectPtr<Render
bool StaticBitmap::initBitmapResource(const Common::String &filename) { bool StaticBitmap::initBitmapResource(const Common::String &filename) {
// Bild-Resource laden // Bild-Resource laden
Resource *resourcePtr = Kernel::GetInstance()->GetResourceManager()->RequestResource(filename); Resource *resourcePtr = Kernel::getInstance()->getResourceManager()->requestResource(filename);
if (!resourcePtr) { if (!resourcePtr) {
BS_LOG_ERRORLN("Could not request resource \"%s\".", filename.c_str()); BS_LOG_ERRORLN("Could not request resource \"%s\".", filename.c_str());
return false; return false;
} }
if (resourcePtr->GetType() != Resource::TYPE_BITMAP) { if (resourcePtr->getType() != Resource::TYPE_BITMAP) {
BS_LOG_ERRORLN("Requested resource \"%s\" is not a bitmap.", filename.c_str()); BS_LOG_ERRORLN("Requested resource \"%s\" is not a bitmap.", filename.c_str());
return false; return false;
} }
@ -88,13 +88,13 @@ StaticBitmap::~StaticBitmap() {
bool StaticBitmap::doRender() { bool StaticBitmap::doRender() {
// Bitmap holen // Bitmap holen
Resource *resourcePtr = Kernel::GetInstance()->GetResourceManager()->RequestResource(_resourceFilename); Resource *resourcePtr = Kernel::getInstance()->getResourceManager()->requestResource(_resourceFilename);
BS_ASSERT(resourcePtr); BS_ASSERT(resourcePtr);
BS_ASSERT(resourcePtr->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(resourcePtr->getType() == Resource::TYPE_BITMAP);
BitmapResource *bitmapResourcePtr = static_cast<BitmapResource *>(resourcePtr); BitmapResource *bitmapResourcePtr = static_cast<BitmapResource *>(resourcePtr);
// Framebufferobjekt holen // Framebufferobjekt holen
GraphicEngine *gfxPtr = Kernel::GetInstance()->GetGfx(); GraphicEngine *gfxPtr = Kernel::getInstance()->getGfx();
BS_ASSERT(gfxPtr); BS_ASSERT(gfxPtr);
// Bitmap zeichnen // Bitmap zeichnen
@ -121,8 +121,8 @@ uint StaticBitmap::getPixel(int x, int y) const {
BS_ASSERT(x >= 0 && x < _width); BS_ASSERT(x >= 0 && x < _width);
BS_ASSERT(y >= 0 && y < _height); BS_ASSERT(y >= 0 && y < _height);
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(_resourceFilename); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(_resourceFilename);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
BitmapResource *pBitmapResource = static_cast<BitmapResource *>(pResource); BitmapResource *pBitmapResource = static_cast<BitmapResource *>(pResource);
uint result = pBitmapResource->getPixel(x, y); uint result = pBitmapResource->getPixel(x, y);
pResource->release(); pResource->release();
@ -135,24 +135,24 @@ bool StaticBitmap::setContent(const byte *pixeldata, uint size, uint offset, uin
} }
bool StaticBitmap::isAlphaAllowed() const { bool StaticBitmap::isAlphaAllowed() const {
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(_resourceFilename); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(_resourceFilename);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
bool result = static_cast<BitmapResource *>(pResource)->isAlphaAllowed(); bool result = static_cast<BitmapResource *>(pResource)->isAlphaAllowed();
pResource->release(); pResource->release();
return result; return result;
} }
bool StaticBitmap::isColorModulationAllowed() const { bool StaticBitmap::isColorModulationAllowed() const {
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(_resourceFilename); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(_resourceFilename);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
bool result = static_cast<BitmapResource *>(pResource)->isColorModulationAllowed(); bool result = static_cast<BitmapResource *>(pResource)->isColorModulationAllowed();
pResource->release(); pResource->release();
return result; return result;
} }
bool StaticBitmap::isScalingAllowed() const { bool StaticBitmap::isScalingAllowed() const {
Resource *pResource = Kernel::GetInstance()->GetResourceManager()->RequestResource(_resourceFilename); Resource *pResource = Kernel::getInstance()->getResourceManager()->requestResource(_resourceFilename);
BS_ASSERT(pResource->GetType() == Resource::TYPE_BITMAP); BS_ASSERT(pResource->getType() == Resource::TYPE_BITMAP);
bool result = static_cast<BitmapResource *>(pResource)->isScalingAllowed(); bool result = static_cast<BitmapResource *>(pResource)->isScalingAllowed();
pResource->release(); pResource->release();
return result; return result;

View file

@ -73,7 +73,7 @@ Text::Text(InputPersistenceBlock &reader, RenderObjectPtr<RenderObject> parentPt
bool Text::setFont(const Common::String &font) { bool Text::setFont(const Common::String &font) {
// Font precachen. // Font precachen.
if (getResourceManager()->PrecacheResource(font)) { if (getResourceManager()->precacheResource(font)) {
_font = font; _font = font;
updateFormat(); updateFormat();
forceRefresh(); forceRefresh();
@ -134,12 +134,12 @@ bool Text::doRender() {
ResourceManager *rmPtr = getResourceManager(); ResourceManager *rmPtr = getResourceManager();
BitmapResource *charMapPtr; BitmapResource *charMapPtr;
{ {
Resource *pResource = rmPtr->RequestResource(fontPtr->getCharactermapFileName()); Resource *pResource = rmPtr->requestResource(fontPtr->getCharactermapFileName());
if (!pResource) { if (!pResource) {
BS_LOG_ERRORLN("Could not request resource \"%s\".", fontPtr->getCharactermapFileName().c_str()); BS_LOG_ERRORLN("Could not request resource \"%s\".", fontPtr->getCharactermapFileName().c_str());
return false; return false;
} }
if (pResource->GetType() != Resource::TYPE_BITMAP) { if (pResource->getType() != Resource::TYPE_BITMAP) {
BS_LOG_ERRORLN("Requested resource \"%s\" is not a bitmap.", fontPtr->getCharactermapFileName().c_str()); BS_LOG_ERRORLN("Requested resource \"%s\" is not a bitmap.", fontPtr->getCharactermapFileName().c_str());
return false; return false;
} }
@ -148,7 +148,7 @@ bool Text::doRender() {
} }
// Framebufferobjekt holen. // Framebufferobjekt holen.
GraphicEngine *gfxPtr = Kernel::GetInstance()->GetGfx(); GraphicEngine *gfxPtr = Kernel::getInstance()->getGfx();
BS_ASSERT(gfxPtr); BS_ASSERT(gfxPtr);
bool result = true; bool result = true;
@ -187,7 +187,7 @@ bool Text::doRender() {
ResourceManager *Text::getResourceManager() { ResourceManager *Text::getResourceManager() {
// Pointer auf den Resource-Manager holen. // Pointer auf den Resource-Manager holen.
return Kernel::GetInstance()->GetResourceManager(); return Kernel::getInstance()->getResourceManager();
} }
FontResource *Text::lockFontResource() { FontResource *Text::lockFontResource() {
@ -196,12 +196,12 @@ FontResource *Text::lockFontResource() {
// Font-Resource locken. // Font-Resource locken.
FontResource *fontPtr; FontResource *fontPtr;
{ {
Resource *resourcePtr = rmPtr->RequestResource(_font); Resource *resourcePtr = rmPtr->requestResource(_font);
if (!resourcePtr) { if (!resourcePtr) {
BS_LOG_ERRORLN("Could not request resource \"%s\".", _font.c_str()); BS_LOG_ERRORLN("Could not request resource \"%s\".", _font.c_str());
return NULL; return NULL;
} }
if (resourcePtr->GetType() != Resource::TYPE_FONT) { if (resourcePtr->getType() != Resource::TYPE_FONT) {
BS_LOG_ERRORLN("Requested resource \"%s\" is not a font.", _font.c_str()); BS_LOG_ERRORLN("Requested resource \"%s\" is not a font.", _font.c_str());
return NULL; return NULL;
} }

View file

@ -51,24 +51,24 @@ namespace Sword25 {
InputEngine::InputEngine(Kernel *pKernel) : InputEngine::InputEngine(Kernel *pKernel) :
Service(pKernel), Service(pKernel),
m_CurrentState(0), _currentState(0),
m_LeftMouseDown(false), _leftMouseDown(false),
m_RightMouseDown(false), _rightMouseDown(false),
m_MouseX(0), _mouseX(0),
m_MouseY(0), _mouseY(0),
m_LeftDoubleClick(false), _leftDoubleClick(false),
m_DoubleClickTime(DOUBLE_CLICK_TIME), _doubleClickTime(DOUBLE_CLICK_TIME),
m_DoubleClickRectWidth(DOUBLE_CLICK_RECT_SIZE), _doubleClickRectWidth(DOUBLE_CLICK_RECT_SIZE),
m_DoubleClickRectHeight(DOUBLE_CLICK_RECT_SIZE), _doubleClickRectHeight(DOUBLE_CLICK_RECT_SIZE),
m_LastLeftClickTime(0), _lastLeftClickTime(0),
m_LastLeftClickMouseX(0), _lastLeftClickMouseX(0),
m_LastLeftClickMouseY(0) { _lastLeftClickMouseY(0) {
memset(m_KeyboardState[0], 0, sizeof(m_KeyboardState[0])); memset(_keyboardState[0], 0, sizeof(_keyboardState[0]));
memset(m_KeyboardState[1], 0, sizeof(m_KeyboardState[1])); memset(_keyboardState[1], 0, sizeof(_keyboardState[1]));
m_LeftMouseState[0] = false; _leftMouseState[0] = false;
m_LeftMouseState[1] = false; _leftMouseState[1] = false;
m_RightMouseState[0] = false; _rightMouseState[0] = false;
m_RightMouseState[1] = false; _rightMouseState[1] = false;
if (!registerScriptBindings()) if (!registerScriptBindings())
BS_LOG_ERRORLN("Script bindings could not be registered."); BS_LOG_ERRORLN("Script bindings could not be registered.");
@ -80,18 +80,14 @@ Service *InputEngine_CreateObject(Kernel *pKernel) {
return new InputEngine(pKernel); return new InputEngine(pKernel);
} }
// ----------------------------------------------------------------------------- bool InputEngine::init() {
bool InputEngine::Init() {
// No initialisation needed // No initialisation needed
return true; return true;
} }
// ----------------------------------------------------------------------------- void InputEngine::update() {
void InputEngine::Update() {
Common::Event event; Common::Event event;
m_CurrentState ^= 1; _currentState ^= 1;
// Loop through processing any pending events // Loop through processing any pending events
bool handleEvents = true; bool handleEvents = true;
@ -99,31 +95,31 @@ void InputEngine::Update() {
switch (event.type) { switch (event.type) {
case Common::EVENT_LBUTTONDOWN: case Common::EVENT_LBUTTONDOWN:
case Common::EVENT_LBUTTONUP: case Common::EVENT_LBUTTONUP:
m_LeftMouseDown = event.type == Common::EVENT_LBUTTONDOWN; _leftMouseDown = event.type == Common::EVENT_LBUTTONDOWN;
m_MouseX = event.mouse.x; _mouseX = event.mouse.x;
m_MouseY = event.mouse.y; _mouseY = event.mouse.y;
handleEvents = false; handleEvents = false;
break; break;
case Common::EVENT_RBUTTONDOWN: case Common::EVENT_RBUTTONDOWN:
case Common::EVENT_RBUTTONUP: case Common::EVENT_RBUTTONUP:
m_RightMouseDown = event.type == Common::EVENT_RBUTTONDOWN; _rightMouseDown = event.type == Common::EVENT_RBUTTONDOWN;
m_MouseX = event.mouse.x; _mouseX = event.mouse.x;
m_MouseY = event.mouse.y; _mouseY = event.mouse.y;
handleEvents = false; handleEvents = false;
break; break;
case Common::EVENT_MOUSEMOVE: case Common::EVENT_MOUSEMOVE:
m_MouseX = event.mouse.x; _mouseX = event.mouse.x;
m_MouseY = event.mouse.y; _mouseY = event.mouse.y;
break; break;
case Common::EVENT_KEYDOWN: case Common::EVENT_KEYDOWN:
case Common::EVENT_KEYUP: case Common::EVENT_KEYUP:
AlterKeyboardState(event.kbd.keycode, (event.type == Common::EVENT_KEYDOWN) ? 0x80 : 0); alterKeyboardState(event.kbd.keycode, (event.type == Common::EVENT_KEYDOWN) ? 0x80 : 0);
break; break;
case Common::EVENT_QUIT: case Common::EVENT_QUIT:
Kernel::GetInstance()->GetWindow()->SetWindowAlive(false); Kernel::getInstance()->getWindow()->setWindowAlive(false);
break; break;
default: default:
@ -131,125 +127,97 @@ void InputEngine::Update() {
} }
} }
m_LeftMouseState[m_CurrentState] = m_LeftMouseDown; _leftMouseState[_currentState] = _leftMouseDown;
m_RightMouseState[m_CurrentState] = m_RightMouseDown; _rightMouseState[_currentState] = _rightMouseDown;
TestForLeftDoubleClick(); testForLeftDoubleClick();
} }
// ----------------------------------------------------------------------------- bool InputEngine::isLeftMouseDown() {
return _leftMouseDown;
bool InputEngine::IsLeftMouseDown() {
return m_LeftMouseDown;
} }
// ----------------------------------------------------------------------------- bool InputEngine::isRightMouseDown() {
return _rightMouseDown;
bool InputEngine::IsRightMouseDown() {
return m_RightMouseDown;
} }
// ----------------------------------------------------------------------------- void InputEngine::testForLeftDoubleClick() {
_leftDoubleClick = false;
void InputEngine::TestForLeftDoubleClick() {
m_LeftDoubleClick = false;
// Only bother checking for a double click if the left mouse button was clicked // Only bother checking for a double click if the left mouse button was clicked
if (WasLeftMouseDown()) { if (wasLeftMouseDown()) {
// Get the time now // Get the time now
uint Now = Kernel::GetInstance()->GetMilliTicks(); uint now = Kernel::getInstance()->getMilliTicks();
// A double click is signalled if // A double click is signalled if
// 1. The two clicks are close enough together // 1. The two clicks are close enough together
// 2. The mouse cursor hasn't moved much // 2. The mouse cursor hasn't moved much
if (Now - m_LastLeftClickTime <= m_DoubleClickTime && if (now - _lastLeftClickTime <= _doubleClickTime &&
ABS(m_MouseX - m_LastLeftClickMouseX) <= m_DoubleClickRectWidth / 2 && ABS(_mouseX - _lastLeftClickMouseX) <= _doubleClickRectWidth / 2 &&
ABS(m_MouseY - m_LastLeftClickMouseY) <= m_DoubleClickRectHeight / 2) { ABS(_mouseY - _lastLeftClickMouseY) <= _doubleClickRectHeight / 2) {
m_LeftDoubleClick = true; _leftDoubleClick = true;
// Reset the time and position of the last click, so that clicking is not // Reset the time and position of the last click, so that clicking is not
// interpreted as the first click of a further double-click // interpreted as the first click of a further double-click
m_LastLeftClickTime = 0; _lastLeftClickTime = 0;
m_LastLeftClickMouseX = 0; _lastLeftClickMouseX = 0;
m_LastLeftClickMouseY = 0; _lastLeftClickMouseY = 0;
} else { } else {
// There is no double click. Remember the position and time of the click, // There is no double click. Remember the position and time of the click,
// in case it's the first click of a double-click sequence // in case it's the first click of a double-click sequence
m_LastLeftClickTime = Now; _lastLeftClickTime = now;
m_LastLeftClickMouseX = m_MouseX; _lastLeftClickMouseX = _mouseX;
m_LastLeftClickMouseY = m_MouseY; _lastLeftClickMouseY = _mouseY;
} }
} }
} }
// ----------------------------------------------------------------------------- void InputEngine::alterKeyboardState(int keycode, byte newState) {
_keyboardState[_currentState][keycode] = newState;
void InputEngine::AlterKeyboardState(int keycode, byte newState) {
m_KeyboardState[m_CurrentState][keycode] = newState;
} }
// ----------------------------------------------------------------------------- bool InputEngine::isLeftDoubleClick() {
return _leftDoubleClick;
bool InputEngine::IsLeftDoubleClick() {
return m_LeftDoubleClick;
} }
// ----------------------------------------------------------------------------- bool InputEngine::wasLeftMouseDown() {
return (_leftMouseState[_currentState] == false) && (_leftMouseState[_currentState ^ 1] == true);
bool InputEngine::WasLeftMouseDown() {
return (m_LeftMouseState[m_CurrentState] == false) && (m_LeftMouseState[m_CurrentState ^ 1] == true);
} }
// ----------------------------------------------------------------------------- bool InputEngine::wasRightMouseDown() {
return (_rightMouseState[_currentState] == false) && (_rightMouseState[_currentState ^ 1] == true);
bool InputEngine::WasRightMouseDown() {
return (m_RightMouseState[m_CurrentState] == false) && (m_RightMouseState[m_CurrentState ^ 1] == true);
} }
// ----------------------------------------------------------------------------- int InputEngine::getMouseX() {
return _mouseX;
int InputEngine::GetMouseX() {
return m_MouseX;
} }
// ----------------------------------------------------------------------------- int InputEngine::getMouseY() {
return _mouseY;
int InputEngine::GetMouseY() {
return m_MouseY;
} }
// ----------------------------------------------------------------------------- bool InputEngine::isKeyDown(uint keyCode) {
return (_keyboardState[_currentState][keyCode] & 0x80) != 0;
bool InputEngine::IsKeyDown(uint KeyCode) {
return (m_KeyboardState[m_CurrentState][KeyCode] & 0x80) != 0;
} }
// ----------------------------------------------------------------------------- bool InputEngine::wasKeyDown(uint keyCode) {
return ((_keyboardState[_currentState][keyCode] & 0x80) == 0) &&
bool InputEngine::WasKeyDown(uint KeyCode) { ((_keyboardState[_currentState ^ 1][keyCode] & 0x80) != 0);
return ((m_KeyboardState[m_CurrentState][KeyCode] & 0x80) == 0) &&
((m_KeyboardState[m_CurrentState ^ 1][KeyCode] & 0x80) != 0);
} }
// ----------------------------------------------------------------------------- void InputEngine::setMouseX(int posX) {
_mouseX = posX;
void InputEngine::SetMouseX(int PosX) { g_system->warpMouse(_mouseX, _mouseY);
m_MouseX = PosX;
g_system->warpMouse(m_MouseX, m_MouseY);
} }
// ----------------------------------------------------------------------------- void InputEngine::setMouseY(int posY) {
_mouseY = posY;
void InputEngine::SetMouseY(int PosY) { g_system->warpMouse(_mouseX, _mouseY);
m_MouseY = PosY;
g_system->warpMouse(m_MouseX, m_MouseY);
} }
// ----------------------------------------------------------------------------- bool InputEngine::registerCharacterCallback(CharacterCallback callback) {
if (Common::find(_characterCallbacks.begin(), _characterCallbacks.end(), callback) == _characterCallbacks.end()) {
bool InputEngine::RegisterCharacterCallback(CharacterCallback Callback) { _characterCallbacks.push_back(callback);
if (Common::find(m_CharacterCallbacks.begin(), m_CharacterCallbacks.end(), Callback) == m_CharacterCallbacks.end()) {
m_CharacterCallbacks.push_back(Callback);
return true; return true;
} else { } else {
BS_LOG_WARNINGLN("Tried to register an CharacterCallback that was already registered."); BS_LOG_WARNINGLN("Tried to register an CharacterCallback that was already registered.");
@ -257,13 +225,11 @@ bool InputEngine::RegisterCharacterCallback(CharacterCallback Callback) {
} }
} }
// ----------------------------------------------------------------------------- bool InputEngine::unregisterCharacterCallback(CharacterCallback callback) {
Common::List<CharacterCallback>::iterator callbackIter = Common::find(_characterCallbacks.begin(),
bool InputEngine::UnregisterCharacterCallback(CharacterCallback Callback) { _characterCallbacks.end(), callback);
Common::List<CharacterCallback>::iterator CallbackIter = Common::find(m_CharacterCallbacks.begin(), if (callbackIter != _characterCallbacks.end()) {
m_CharacterCallbacks.end(), Callback); _characterCallbacks.erase(callbackIter);
if (CallbackIter != m_CharacterCallbacks.end()) {
m_CharacterCallbacks.erase(CallbackIter);
return true; return true;
} else { } else {
BS_LOG_WARNINGLN("Tried to unregister an CharacterCallback that was not previously registered."); BS_LOG_WARNINGLN("Tried to unregister an CharacterCallback that was not previously registered.");
@ -271,11 +237,9 @@ bool InputEngine::UnregisterCharacterCallback(CharacterCallback Callback) {
} }
} }
// ----------------------------------------------------------------------------- bool InputEngine::registerCommandCallback(CommandCallback callback) {
if (Common::find(_commandCallbacks.begin(), _commandCallbacks.end(), callback) == _commandCallbacks.end()) {
bool InputEngine::RegisterCommandCallback(CommandCallback Callback) { _commandCallbacks.push_back(callback);
if (Common::find(m_CommandCallbacks.begin(), m_CommandCallbacks.end(), Callback) == m_CommandCallbacks.end()) {
m_CommandCallbacks.push_back(Callback);
return true; return true;
} else { } else {
BS_LOG_WARNINGLN("Tried to register an CommandCallback that was already registered."); BS_LOG_WARNINGLN("Tried to register an CommandCallback that was already registered.");
@ -283,13 +247,11 @@ bool InputEngine::RegisterCommandCallback(CommandCallback Callback) {
} }
} }
// ----------------------------------------------------------------------------- bool InputEngine::unregisterCommandCallback(CommandCallback callback) {
Common::List<CommandCallback>::iterator callbackIter =
bool InputEngine::UnregisterCommandCallback(CommandCallback Callback) { Common::find(_commandCallbacks.begin(), _commandCallbacks.end(), callback);
Common::List<CommandCallback>::iterator CallbackIter = if (callbackIter != _commandCallbacks.end()) {
Common::find(m_CommandCallbacks.begin(), m_CommandCallbacks.end(), Callback); _commandCallbacks.erase(callbackIter);
if (CallbackIter != m_CommandCallbacks.end()) {
m_CommandCallbacks.erase(CallbackIter);
return true; return true;
} else { } else {
BS_LOG_WARNINGLN("Tried to unregister an CommandCallback that was not previously registered."); BS_LOG_WARNINGLN("Tried to unregister an CommandCallback that was not previously registered.");
@ -297,60 +259,52 @@ bool InputEngine::UnregisterCommandCallback(CommandCallback Callback) {
} }
} }
// ----------------------------------------------------------------------------- void InputEngine::reportCharacter(byte character) {
Common::List<CharacterCallback>::const_iterator callbackIter = _characterCallbacks.begin();
void InputEngine::ReportCharacter(byte Character) { while (callbackIter != _characterCallbacks.end()) {
Common::List<CharacterCallback>::const_iterator CallbackIter = m_CharacterCallbacks.begin();
while (CallbackIter != m_CharacterCallbacks.end()) {
// Iterator vor dem Aufruf erhöhen und im Folgendem auf einer Kopie arbeiten. // Iterator vor dem Aufruf erhöhen und im Folgendem auf einer Kopie arbeiten.
// Dieses Vorgehen ist notwendig da der Iterator möglicherweise von der Callbackfunktion durch das Deregistrieren des Callbacks // Dieses Vorgehen ist notwendig da der Iterator möglicherweise von der Callbackfunktion durch das Deregistrieren des Callbacks
// invalidiert wird. // invalidiert wird.
Common::List<CharacterCallback>::const_iterator CurCallbackIter = CallbackIter; Common::List<CharacterCallback>::const_iterator curCallbackIter = callbackIter;
++CallbackIter; ++callbackIter;
(*CurCallbackIter)(Character); (*curCallbackIter)(character);
} }
} }
// ----------------------------------------------------------------------------- void InputEngine::reportCommand(KEY_COMMANDS command) {
Common::List<CommandCallback>::const_iterator callbackIter = _commandCallbacks.begin();
void InputEngine::ReportCommand(KEY_COMMANDS Command) { while (callbackIter != _commandCallbacks.end()) {
Common::List<CommandCallback>::const_iterator CallbackIter = m_CommandCallbacks.begin();
while (CallbackIter != m_CommandCallbacks.end()) {
// Iterator vor dem Aufruf erhöhen und im Folgendem auf einer Kopie arbeiten. // Iterator vor dem Aufruf erhöhen und im Folgendem auf einer Kopie arbeiten.
// Dieses Vorgehen ist notwendig da der Iterator möglicherweise von der Callbackfunktion durch das Deregistrieren des Callbacks // Dieses Vorgehen ist notwendig da der Iterator möglicherweise von der Callbackfunktion durch das Deregistrieren des Callbacks
// invalidiert wird. // invalidiert wird.
Common::List<CommandCallback>::const_iterator CurCallbackIter = CallbackIter; Common::List<CommandCallback>::const_iterator curCallbackIter = callbackIter;
++CallbackIter; ++callbackIter;
(*CurCallbackIter)(Command); (*curCallbackIter)(command);
} }
} }
// -----------------------------------------------------------------------------
// Persistenz
// -----------------------------------------------------------------------------
bool InputEngine::persist(OutputPersistenceBlock &writer) { bool InputEngine::persist(OutputPersistenceBlock &writer) {
// Anzahl an Command-Callbacks persistieren. // Anzahl an Command-Callbacks persistieren.
writer.write(m_CommandCallbacks.size()); writer.write(_commandCallbacks.size());
// Alle Command-Callbacks einzeln persistieren. // Alle Command-Callbacks einzeln persistieren.
{ {
Common::List<CommandCallback>::const_iterator It = m_CommandCallbacks.begin(); Common::List<CommandCallback>::const_iterator It = _commandCallbacks.begin();
while (It != m_CommandCallbacks.end()) { while (It != _commandCallbacks.end()) {
writer.write(CallbackRegistry::instance().resolveCallbackPointer(*It)); writer.write(CallbackRegistry::instance().resolveCallbackPointer(*It));
++It; ++It;
} }
} }
// Anzahl an Character-Callbacks persistieren. // Anzahl an Character-Callbacks persistieren.
writer.write(m_CharacterCallbacks.size()); writer.write(_characterCallbacks.size());
// Alle Character-Callbacks einzeln persistieren. // Alle Character-Callbacks einzeln persistieren.
{ {
Common::List<CharacterCallback>::const_iterator It = m_CharacterCallbacks.begin(); Common::List<CharacterCallback>::const_iterator It = _characterCallbacks.begin();
while (It != m_CharacterCallbacks.end()) { while (It != _characterCallbacks.end()) {
writer.write(CallbackRegistry::instance().resolveCallbackPointer(*It)); writer.write(CallbackRegistry::instance().resolveCallbackPointer(*It));
++It; ++It;
} }
@ -359,38 +313,36 @@ bool InputEngine::persist(OutputPersistenceBlock &writer) {
return true; return true;
} }
// -----------------------------------------------------------------------------
bool InputEngine::unpersist(InputPersistenceBlock &reader) { bool InputEngine::unpersist(InputPersistenceBlock &reader) {
// Command-Callbackliste leeren. // Command-Callbackliste leeren.
m_CommandCallbacks.clear(); _commandCallbacks.clear();
// Anzahl an Command-Callbacks lesen. // Anzahl an Command-Callbacks lesen.
uint CommandCallbackCount; uint commandCallbackCount;
reader.read(CommandCallbackCount); reader.read(commandCallbackCount);
// Alle Command-Callbacks wieder herstellen. // Alle Command-Callbacks wieder herstellen.
for (uint i = 0; i < CommandCallbackCount; ++i) { for (uint i = 0; i < commandCallbackCount; ++i) {
Common::String CallbackFunctionName; Common::String callbackFunctionName;
reader.read(CallbackFunctionName); reader.read(callbackFunctionName);
m_CommandCallbacks.push_back(reinterpret_cast<CommandCallback>( _commandCallbacks.push_back(reinterpret_cast<CommandCallback>(
CallbackRegistry::instance().resolveCallbackFunction(CallbackFunctionName))); CallbackRegistry::instance().resolveCallbackFunction(callbackFunctionName)));
} }
// Character-Callbackliste leeren. // Character-Callbackliste leeren.
m_CharacterCallbacks.clear(); _characterCallbacks.clear();
// Anzahl an Character-Callbacks lesen. // Anzahl an Character-Callbacks lesen.
uint CharacterCallbackCount; uint characterCallbackCount;
reader.read(CharacterCallbackCount); reader.read(characterCallbackCount);
// Alle Character-Callbacks wieder herstellen. // Alle Character-Callbacks wieder herstellen.
for (uint i = 0; i < CharacterCallbackCount; ++i) { for (uint i = 0; i < characterCallbackCount; ++i) {
Common::String CallbackFunctionName; Common::String callbackFunctionName;
reader.read(CallbackFunctionName); reader.read(callbackFunctionName);
m_CharacterCallbacks.push_back(reinterpret_cast<CharacterCallback>(CallbackRegistry::instance().resolveCallbackFunction(CallbackFunctionName))); _characterCallbacks.push_back(reinterpret_cast<CharacterCallback>(CallbackRegistry::instance().resolveCallbackFunction(callbackFunctionName)));
} }
return reader.isGood(); return reader.isGood();

View file

@ -45,7 +45,6 @@
#ifndef SWORD25_INPUTENGINE_H #ifndef SWORD25_INPUTENGINE_H
#define SWORD25_INPUTENGINE_H #define SWORD25_INPUTENGINE_H
/// Includes
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/service.h" #include "sword25/kernel/service.h"
#include "sword25/kernel/persistable.h" #include "sword25/kernel/persistable.h"
@ -176,7 +175,7 @@ public:
* Initialises the input engine * Initialises the input engine
* @return Returns a true on success, otherwise false. * @return Returns a true on success, otherwise false.
*/ */
bool Init(); bool init();
/** /**
* Performs a "tick" of the input engine. * Performs a "tick" of the input engine.
@ -185,17 +184,17 @@ public:
* of the input engine that are not running in their own thread, or to perform * of the input engine that are not running in their own thread, or to perform
* additional administrative tasks that are needed. * additional administrative tasks that are needed.
*/ */
void Update(); void update();
/** /**
* Returns true if the left mouse button is pressed * Returns true if the left mouse button is pressed
*/ */
bool IsLeftMouseDown(); bool isLeftMouseDown();
/** /**
* Returns true if the right mouse button is pressed. * Returns true if the right mouse button is pressed.
*/ */
bool IsRightMouseDown(); bool isRightMouseDown();
/** /**
* Returns true if the left mouse button was pressed and released. * Returns true if the left mouse button was pressed and released.
@ -203,7 +202,7 @@ public:
* The difference between this and IsLeftMouseDown() is that this only returns * The difference between this and IsLeftMouseDown() is that this only returns
* true when the left mouse button is released. * true when the left mouse button is released.
*/ */
bool WasLeftMouseDown(); bool wasLeftMouseDown();
/** /**
* Returns true if the right mouse button was pressed and released. * Returns true if the right mouse button was pressed and released.
@ -211,39 +210,39 @@ public:
* The difference between this and IsRightMouseDown() is that this only returns * The difference between this and IsRightMouseDown() is that this only returns
* true when the right mouse button is released. * true when the right mouse button is released.
*/ */
bool WasRightMouseDown(); bool wasRightMouseDown();
/** /**
* Returns true if the left mouse button double click was done * Returns true if the left mouse button double click was done
*/ */
bool IsLeftDoubleClick(); bool isLeftDoubleClick();
/** /**
* Returns the X position of the cursor in pixels * Returns the X position of the cursor in pixels
*/ */
int GetMouseX(); int getMouseX();
/** /**
* Returns the Y position of the cursor in pixels * Returns the Y position of the cursor in pixels
*/ */
int GetMouseY(); int getMouseY();
/** /**
* Sets the X position of the cursor in pixels * Sets the X position of the cursor in pixels
*/ */
void SetMouseX(int PosX); void setMouseX(int posX);
/** /**
* Sets the Y position of the cursor in pixels * Sets the Y position of the cursor in pixels
*/ */
void SetMouseY(int PosY); void setMouseY(int posY);
/** /**
* Returns true if a given key was pressed * Returns true if a given key was pressed
* @param KeyCode The key code to be checked * @param KeyCode The key code to be checked
* @return Returns true if the given key is done, otherwise false. * @return Returns true if the given key is done, otherwise false.
*/ */
bool IsKeyDown(uint KeyCode); bool isKeyDown(uint keyCode);
/** /**
* Returns true if a certain key was pushed and released. * Returns true if a certain key was pushed and released.
@ -253,7 +252,7 @@ public:
* strings that users type. * strings that users type.
* @param KeyCode The key code to be checked * @param KeyCode The key code to be checked
*/ */
bool WasKeyDown(uint KeyCode); bool wasKeyDown(uint keyCode);
typedef CallbackPtr CharacterCallback; typedef CallbackPtr CharacterCallback;
@ -269,13 +268,13 @@ public:
* The input of strings by the user through use of callbacks should be implemented. * The input of strings by the user through use of callbacks should be implemented.
* @return Returns true if the function was registered, otherwise false. * @return Returns true if the function was registered, otherwise false.
*/ */
bool RegisterCharacterCallback(CallbackPtr Callback); bool registerCharacterCallback(CallbackPtr callback);
/** /**
* De-registeres a previously registered callback function. * De-registeres a previously registered callback function.
* @return Returns true if the function could be de-registered, otherwise false. * @return Returns true if the function could be de-registered, otherwise false.
*/ */
bool UnregisterCharacterCallback(CallbackPtr Callback); bool unregisterCharacterCallback(CallbackPtr callback);
typedef CallbackPtr CommandCallback; typedef CallbackPtr CommandCallback;
@ -288,16 +287,16 @@ public:
* The input of strings by the user through the use of callbacks should be implemented. * The input of strings by the user through the use of callbacks should be implemented.
* @return Returns true if the function was registered, otherwise false. * @return Returns true if the function was registered, otherwise false.
*/ */
bool RegisterCommandCallback(CallbackPtr Callback); bool registerCommandCallback(CallbackPtr callback);
/** /**
* Un-register a callback function for the input of commands that can have an influence on the string input. * Un-register a callback function for the input of commands that can have an influence on the string input.
* @return Returns true if the function could be de-registered, otherwise false. * @return Returns true if the function could be de-registered, otherwise false.
*/ */
bool UnregisterCommandCallback(CommandCallback Callback); bool unregisterCommandCallback(CommandCallback callback);
void ReportCharacter(byte Character); void reportCharacter(byte character);
void ReportCommand(KEY_COMMANDS Command); void reportCommand(KEY_COMMANDS command);
bool persist(OutputPersistenceBlock &writer); bool persist(OutputPersistenceBlock &writer);
bool unpersist(InputPersistenceBlock &reader); bool unpersist(InputPersistenceBlock &reader);
@ -306,26 +305,26 @@ private:
bool registerScriptBindings(); bool registerScriptBindings();
private: private:
void TestForLeftDoubleClick(); void testForLeftDoubleClick();
void AlterKeyboardState(int keycode, byte newState); void alterKeyboardState(int keycode, byte newState);
byte m_KeyboardState[2][256]; byte _keyboardState[2][256];
bool m_LeftMouseState[2]; bool _leftMouseState[2];
bool m_RightMouseState[2]; bool _rightMouseState[2];
uint m_CurrentState; uint _currentState;
int m_MouseX; int _mouseX;
int m_MouseY; int _mouseY;
bool m_LeftMouseDown; bool _leftMouseDown;
bool m_RightMouseDown; bool _rightMouseDown;
bool m_LeftDoubleClick; bool _leftDoubleClick;
uint m_DoubleClickTime; uint _doubleClickTime;
int m_DoubleClickRectWidth; int _doubleClickRectWidth;
int m_DoubleClickRectHeight; int _doubleClickRectHeight;
uint m_LastLeftClickTime; uint _lastLeftClickTime;
int m_LastLeftClickMouseX; int _lastLeftClickMouseX;
int m_LastLeftClickMouseY; int _lastLeftClickMouseY;
Common::List<CommandCallback> m_CommandCallbacks; Common::List<CommandCallback> _commandCallbacks;
Common::List<CharacterCallback> m_CharacterCallbacks; Common::List<CharacterCallback> _characterCallbacks;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -32,10 +32,6 @@
* *
*/ */
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/ptr.h" #include "common/ptr.h"
#include "common/str.h" #include "common/str.h"
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
@ -51,268 +47,218 @@
namespace Sword25 { namespace Sword25 {
// ----------------------------------------------------------------------------- static void theCharacterCallback(int character);
// Callback-Objekte static void theCommandCallback(int command);
// -----------------------------------------------------------------------------
static void TheCharacterCallback(int Character);
static void TheCommandCallback(int Command);
namespace { namespace {
class CharacterCallbackClass : public LuaCallback { class CharacterCallbackClass : public LuaCallback {
public: public:
CharacterCallbackClass(lua_State *L) : LuaCallback(L) {} CharacterCallbackClass(lua_State *L) : LuaCallback(L) {}
Common::String Character; Common::String _character;
protected: protected:
int PreFunctionInvokation(lua_State *L) { int PreFunctionInvokation(lua_State *L) {
lua_pushstring(L, Character.c_str()); lua_pushstring(L, _character.c_str());
return 1; return 1;
} }
}; };
Common::SharedPtr<CharacterCallbackClass> CharacterCallbackPtr; Common::SharedPtr<CharacterCallbackClass> characterCallbackPtr;
// -----------------------------------------------------------------------------
class CommandCallbackClass : public LuaCallback { class CommandCallbackClass : public LuaCallback {
public: public:
CommandCallbackClass(lua_State *L) : LuaCallback(L) { CommandCallbackClass(lua_State *L) : LuaCallback(L) {
Command = InputEngine::KEY_COMMAND_BACKSPACE; _command = InputEngine::KEY_COMMAND_BACKSPACE;
} }
InputEngine::KEY_COMMANDS Command; InputEngine::KEY_COMMANDS _command;
protected: protected:
int PreFunctionInvokation(lua_State *L) { int preFunctionInvokation(lua_State *L) {
lua_pushnumber(L, Command); lua_pushnumber(L, _command);
return 1; return 1;
} }
}; };
Common::SharedPtr<CommandCallbackClass> CommandCallbackPtr; Common::SharedPtr<CommandCallbackClass> commandCallbackPtr;
// -------------------------------------------------------------------------
struct CallbackfunctionRegisterer { struct CallbackfunctionRegisterer {
CallbackfunctionRegisterer() { CallbackfunctionRegisterer() {
CallbackRegistry::instance().registerCallbackFunction("LuaCommandCB", TheCommandCallback); CallbackRegistry::instance().registerCallbackFunction("LuaCommandCB", theCommandCallback);
CallbackRegistry::instance().registerCallbackFunction("LuaCharacterCB", TheCharacterCallback); CallbackRegistry::instance().registerCallbackFunction("LuaCharacterCB", theCharacterCallback);
} }
}; };
static CallbackfunctionRegisterer Instance; static CallbackfunctionRegisterer instance;
} }
// ----------------------------------------------------------------------------- static InputEngine *getIE() {
Kernel *pKernel = Kernel::getInstance();
static InputEngine *GetIE() {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
InputEngine *pIE = pKernel->GetInput(); InputEngine *pIE = pKernel->getInput();
BS_ASSERT(pIE); BS_ASSERT(pIE);
return pIE; return pIE;
} }
// ----------------------------------------------------------------------------- static int init(lua_State *L) {
InputEngine *pIE = getIE();
static int Init(lua_State *L) { lua_pushbooleancpp(L, pIE->init());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->Init());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int update(lua_State *L) {
InputEngine *pIE = getIE();
static int Update(lua_State *L) {
InputEngine *pIE = GetIE();
// Beim ersten Aufruf der Update()-Methode werden die beiden Callbacks am Input-Objekt registriert. // Beim ersten Aufruf der Update()-Methode werden die beiden Callbacks am Input-Objekt registriert.
// Dieses kann nicht in _RegisterScriptBindings() passieren, da diese Funktion vom Konstruktor der abstrakten Basisklasse aufgerufen wird und die // Dieses kann nicht in _RegisterScriptBindings() passieren, da diese Funktion vom Konstruktor der abstrakten Basisklasse aufgerufen wird und die
// Register...()-Methoden abstrakt sind, im Konstruktor der Basisklasse also nicht aufgerufen werden können. // Register...()-Methoden abstrakt sind, im Konstruktor der Basisklasse also nicht aufgerufen werden können.
static bool FirstCall = true; static bool firstCall = true;
if (FirstCall) { if (firstCall) {
FirstCall = false; firstCall = false;
pIE->RegisterCharacterCallback(TheCharacterCallback); pIE->registerCharacterCallback(theCharacterCallback);
pIE->RegisterCommandCallback(TheCommandCallback); pIE->registerCommandCallback(theCommandCallback);
} }
pIE->Update(); pIE->update();
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int isLeftMouseDown(lua_State *L) {
InputEngine *pIE = getIE();
static int IsLeftMouseDown(lua_State *L) { lua_pushbooleancpp(L, pIE->isLeftMouseDown());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->IsLeftMouseDown());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int isRightMouseDown(lua_State *L) {
InputEngine *pIE = getIE();
static int IsRightMouseDown(lua_State *L) { lua_pushbooleancpp(L, pIE->isRightMouseDown());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->IsRightMouseDown());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int wasLeftMouseDown(lua_State *L) {
InputEngine *pIE = getIE();
static int WasLeftMouseDown(lua_State *L) { lua_pushbooleancpp(L, pIE->wasLeftMouseDown());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->WasLeftMouseDown());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int wasRightMouseDown(lua_State *L) {
InputEngine *pIE = getIE();
static int WasRightMouseDown(lua_State *L) { lua_pushbooleancpp(L, pIE->wasRightMouseDown());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->WasRightMouseDown());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int isLeftDoubleClick(lua_State *L) {
InputEngine *pIE = getIE();
static int IsLeftDoubleClick(lua_State *L) { lua_pushbooleancpp(L, pIE->isLeftDoubleClick());
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->IsLeftDoubleClick());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getMouseX(lua_State *L) {
InputEngine *pIE = getIE();
static int GetMouseX(lua_State *L) { lua_pushnumber(L, pIE->getMouseX());
InputEngine *pIE = GetIE();
lua_pushnumber(L, pIE->GetMouseX());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getMouseY(lua_State *L) {
InputEngine *pIE = getIE();
static int GetMouseY(lua_State *L) { lua_pushnumber(L, pIE->getMouseY());
InputEngine *pIE = GetIE();
lua_pushnumber(L, pIE->GetMouseY());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int isKeyDown(lua_State *L) {
InputEngine *pIE = getIE();
static int IsKeyDown(lua_State *L) { lua_pushbooleancpp(L, pIE->isKeyDown((uint)luaL_checknumber(L, 1)));
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->IsKeyDown((uint) luaL_checknumber(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int wasKeyDown(lua_State *L) {
InputEngine *pIE = getIE();
static int WasKeyDown(lua_State *L) { lua_pushbooleancpp(L, pIE->wasKeyDown((uint)luaL_checknumber(L, 1)));
InputEngine *pIE = GetIE();
lua_pushbooleancpp(L, pIE->WasKeyDown((uint) luaL_checknumber(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setMouseX(lua_State *L) {
InputEngine *pIE = getIE();
static int SetMouseX(lua_State *L) { pIE->setMouseX((int)luaL_checknumber(L, 1));
InputEngine *pIE = GetIE();
pIE->SetMouseX((int) luaL_checknumber(L, 1));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int setMouseY(lua_State *L) {
InputEngine *pIE = getIE();
static int SetMouseY(lua_State *L) { pIE->setMouseY((int)luaL_checknumber(L, 1));
InputEngine *pIE = GetIE();
pIE->SetMouseY((int) luaL_checknumber(L, 1));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static void theCharacterCallback(int character) {
characterCallbackPtr->_character = static_cast<byte>(character);
static void TheCharacterCallback(int Character) { lua_State *L = static_cast<lua_State *>(Kernel::getInstance()->getScript()->getScriptObject());
CharacterCallbackPtr->Character = static_cast<byte>(Character); characterCallbackPtr->invokeCallbackFunctions(L, 1);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
CharacterCallbackPtr->invokeCallbackFunctions(L, 1);
} }
// ----------------------------------------------------------------------------- static int registerCharacterCallback(lua_State *L) {
static int RegisterCharacterCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION); luaL_checktype(L, 1, LUA_TFUNCTION);
CharacterCallbackPtr->registerCallbackFunction(L, 1); characterCallbackPtr->registerCallbackFunction(L, 1);
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int unregisterCharacterCallback(lua_State *L) {
static int UnregisterCharacterCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION); luaL_checktype(L, 1, LUA_TFUNCTION);
CharacterCallbackPtr->unregisterCallbackFunction(L, 1); characterCallbackPtr->unregisterCallbackFunction(L, 1);
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static void theCommandCallback(int command) {
commandCallbackPtr->_command = static_cast<InputEngine::KEY_COMMANDS>(command);
static void TheCommandCallback(int Command) { lua_State *L = static_cast<lua_State *>(Kernel::getInstance()->getScript()->getScriptObject());
CommandCallbackPtr->Command = static_cast<InputEngine::KEY_COMMANDS>(Command); commandCallbackPtr->invokeCallbackFunctions(L, 1);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
CommandCallbackPtr->invokeCallbackFunctions(L, 1);
} }
// ----------------------------------------------------------------------------- static int registerCommandCallback(lua_State *L) {
static int RegisterCommandCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION); luaL_checktype(L, 1, LUA_TFUNCTION);
CommandCallbackPtr->registerCallbackFunction(L, 1); commandCallbackPtr->registerCallbackFunction(L, 1);
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int unregisterCommandCallback(lua_State *L) {
static int UnregisterCommandCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION); luaL_checktype(L, 1, LUA_TFUNCTION);
CommandCallbackPtr->unregisterCallbackFunction(L, 1); commandCallbackPtr->unregisterCallbackFunction(L, 1);
return 0; return 0;
} }
// -----------------------------------------------------------------------------
static const char *PACKAGE_LIBRARY_NAME = "Input"; static const char *PACKAGE_LIBRARY_NAME = "Input";
static const luaL_reg PACKAGE_FUNCTIONS[] = { static const luaL_reg PACKAGE_FUNCTIONS[] = {
{"Init", Init}, {"Init", init},
{"Update", Update}, {"Update", update},
{"IsLeftMouseDown", IsLeftMouseDown}, {"IsLeftMouseDown", isLeftMouseDown},
{"IsRightMouseDown", IsRightMouseDown}, {"IsRightMouseDown", isRightMouseDown},
{"WasLeftMouseDown", WasLeftMouseDown}, {"WasLeftMouseDown", wasLeftMouseDown},
{"WasRightMouseDown", WasRightMouseDown}, {"WasRightMouseDown", wasRightMouseDown},
{"IsLeftDoubleClick", IsLeftDoubleClick}, {"IsLeftDoubleClick", isLeftDoubleClick},
{"GetMouseX", GetMouseX}, {"GetMouseX", getMouseX},
{"GetMouseY", GetMouseY}, {"GetMouseY", getMouseY},
{"SetMouseX", SetMouseX}, {"SetMouseX", setMouseX},
{"SetMouseY", SetMouseY}, {"SetMouseY", setMouseY},
{"IsKeyDown", IsKeyDown}, {"IsKeyDown", isKeyDown},
{"WasKeyDown", WasKeyDown}, {"WasKeyDown", wasKeyDown},
{"RegisterCharacterCallback", RegisterCharacterCallback}, {"RegisterCharacterCallback", registerCharacterCallback},
{"UnregisterCharacterCallback", UnregisterCharacterCallback}, {"UnregisterCharacterCallback", unregisterCharacterCallback},
{"RegisterCommandCallback", RegisterCommandCallback}, {"RegisterCommandCallback", registerCommandCallback},
{"UnregisterCommandCallback", UnregisterCommandCallback}, {"UnregisterCommandCallback", unregisterCommandCallback},
{0, 0} {0, 0}
}; };
@ -334,9 +280,9 @@ static const lua_constant_reg PACKAGE_CONSTANTS[] = {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool InputEngine::registerScriptBindings() { bool InputEngine::registerScriptBindings() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pScript = pKernel->GetScript(); ScriptEngine *pScript = pKernel->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);
@ -344,8 +290,8 @@ bool InputEngine::registerScriptBindings() {
if (!LuaBindhelper::addFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS)) return false; if (!LuaBindhelper::addFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS)) return false;
if (!LuaBindhelper::addConstantsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_CONSTANTS)) return false; if (!LuaBindhelper::addConstantsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_CONSTANTS)) return false;
CharacterCallbackPtr = Common::SharedPtr<CharacterCallbackClass>(new CharacterCallbackClass(L)); characterCallbackPtr = Common::SharedPtr<CharacterCallbackClass>(new CharacterCallbackClass(L));
CommandCallbackPtr = Common::SharedPtr<CommandCallbackClass>(new CommandCallbackClass(L)); commandCallbackPtr = Common::SharedPtr<CommandCallbackClass>(new CommandCallbackClass(L));
return true; return true;
} }

View file

@ -44,22 +44,12 @@
// Pointer gespeichert war, stürtzt das Programm beim Äufrufen dieser Callbackfunktion ab. Durch das Auflösungverfahren wird beim Laden der // Pointer gespeichert war, stürtzt das Programm beim Äufrufen dieser Callbackfunktion ab. Durch das Auflösungverfahren wird beim Laden der
// Callbackbezeichner in den neuen Funktionspointer umgewandelt und der Aufruf kann erfolgen. // Callbackbezeichner in den neuen Funktionspointer umgewandelt und der Aufruf kann erfolgen.
// -----------------------------------------------------------------------------
// Logging
// -----------------------------------------------------------------------------
#define BS_LOG_PREFIX "CALLBACKREGISTRY" #define BS_LOG_PREFIX "CALLBACKREGISTRY"
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/callbackregistry.h" #include "sword25/kernel/callbackregistry.h"
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
bool CallbackRegistry::registerCallbackFunction(const Common::String &name, CallbackPtr ptr) { bool CallbackRegistry::registerCallbackFunction(const Common::String &name, CallbackPtr ptr) {
if (name == "") { if (name == "") {
BS_LOG_ERRORLN("The empty string is not allowed as a callback function name."); BS_LOG_ERRORLN("The empty string is not allowed as a callback function name.");
@ -80,8 +70,6 @@ bool CallbackRegistry::registerCallbackFunction(const Common::String &name, Call
return true; return true;
} }
// -----------------------------------------------------------------------------
CallbackPtr CallbackRegistry::resolveCallbackFunction(const Common::String &name) const { CallbackPtr CallbackRegistry::resolveCallbackFunction(const Common::String &name) const {
CallbackPtr result = findPtrByName(name); CallbackPtr result = findPtrByName(name);
@ -92,8 +80,6 @@ CallbackPtr CallbackRegistry::resolveCallbackFunction(const Common::String &name
return result; return result;
} }
// -----------------------------------------------------------------------------
Common::String CallbackRegistry::resolveCallbackPointer(CallbackPtr ptr) const { Common::String CallbackRegistry::resolveCallbackPointer(CallbackPtr ptr) const {
const Common::String &result = findNameByPtr(ptr); const Common::String &result = findNameByPtr(ptr);
@ -104,24 +90,18 @@ Common::String CallbackRegistry::resolveCallbackPointer(CallbackPtr ptr) const {
return result; return result;
} }
// -----------------------------------------------------------------------------
CallbackPtr CallbackRegistry::findPtrByName(const Common::String &name) const { CallbackPtr CallbackRegistry::findPtrByName(const Common::String &name) const {
// Eintrag in der Map finden und den Pointer zurückgeben. // Eintrag in der Map finden und den Pointer zurückgeben.
NameToPtrMap::const_iterator it = _nameToPtrMap.find(name); NameToPtrMap::const_iterator it = _nameToPtrMap.find(name);
return it == _nameToPtrMap.end() ? 0 : it->_value; return it == _nameToPtrMap.end() ? 0 : it->_value;
} }
// -----------------------------------------------------------------------------
Common::String CallbackRegistry::findNameByPtr(CallbackPtr ptr) const { Common::String CallbackRegistry::findNameByPtr(CallbackPtr ptr) const {
// Eintrag in der Map finden und den Namen zurückgeben. // Eintrag in der Map finden und den Namen zurückgeben.
PtrToNameMap::const_iterator it = _ptrToNameMap.find(ptr); PtrToNameMap::const_iterator it = _ptrToNameMap.find(ptr);
return it == _ptrToNameMap.end() ? "" : it->_value; return it == _ptrToNameMap.end() ? "" : it->_value;
} }
// -----------------------------------------------------------------------------
void CallbackRegistry::storeCallbackFunction(const Common::String &name, CallbackPtr ptr) { void CallbackRegistry::storeCallbackFunction(const Common::String &name, CallbackPtr ptr) {
// Callback-Funktion in beide Maps eintragen. // Callback-Funktion in beide Maps eintragen.
_nameToPtrMap[name] = ptr; _nameToPtrMap[name] = ptr;

View file

@ -35,10 +35,6 @@
#ifndef SWORD25_CALLBACK_REGISTRY_H #ifndef SWORD25_CALLBACK_REGISTRY_H
#define SWORD25_CALLBACK_REGISTRY_H #define SWORD25_CALLBACK_REGISTRY_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/scummsys.h" #include "common/scummsys.h"
#include "common/str.h" #include "common/str.h"
#include "common/hash-str.h" #include "common/hash-str.h"
@ -47,10 +43,6 @@
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Klassendeklaration
// -----------------------------------------------------------------------------
typedef void (*CallbackPtr)(int command); typedef void (*CallbackPtr)(int command);
class CallbackRegistry { class CallbackRegistry {

View file

@ -32,10 +32,6 @@
* *
*/ */
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/config-manager.h" #include "common/config-manager.h"
#include "common/fs.h" #include "common/fs.h"
#include "common/savefile.h" #include "common/savefile.h"
@ -47,12 +43,8 @@ namespace Sword25 {
#define BS_LOG_PREFIX "FILESYSTEMUTIL" #define BS_LOG_PREFIX "FILESYSTEMUTIL"
// ----------------------------------------------------------------------------- Common::String getAbsolutePath(const Common::String &path) {
// Constants and utility functions Common::FSNode node(path);
// -----------------------------------------------------------------------------
Common::String GetAbsolutePath(const Common::String &Path) {
Common::FSNode node(Path);
if (!node.exists()) { if (!node.exists()) {
// An error has occurred finding the node // An error has occurred finding the node
@ -65,13 +57,9 @@ Common::String GetAbsolutePath(const Common::String &Path) {
return node.getPath(); return node.getPath();
} }
// -----------------------------------------------------------------------------
// Class definitions
// -----------------------------------------------------------------------------
class BS_FileSystemUtilScummVM : public FileSystemUtil { class BS_FileSystemUtilScummVM : public FileSystemUtil {
public: public:
virtual Common::String GetUserdataDirectory() { virtual Common::String getUserdataDirectory() {
Common::String path = ConfMan.get("savepath"); Common::String path = ConfMan.get("savepath");
if (path.empty()) { if (path.empty()) {
@ -83,12 +71,12 @@ public:
return path; return path;
} }
virtual Common::String GetPathSeparator() { virtual Common::String getPathSeparator() {
return Common::String("/"); return Common::String("/");
} }
virtual int32 GetFileSize(const Common::String &Filename) { virtual int32 getFileSize(const Common::String &filename) {
Common::FSNode node(Filename); Common::FSNode node(filename);
// If the file does not exist, return -1 as a result // If the file does not exist, return -1 as a result
if (!node.exists()) if (!node.exists())
@ -103,7 +91,7 @@ public:
return size; return size;
} }
virtual TimeDate GetFileTime(const Common::String &Filename) { virtual TimeDate getFileTime(const Common::String &filename) {
// TODO: There isn't any way in ScummVM to get a file's modified date/time. We will need to check // TODO: There isn't any way in ScummVM to get a file's modified date/time. We will need to check
// what code makes use of it. If it's only the save game code, for example, we may be able to // what code makes use of it. If it's only the save game code, for example, we may be able to
// encode the date/time inside the savegame files themselves. // encode the date/time inside the savegame files themselves.
@ -112,41 +100,37 @@ public:
return result; return result;
} }
virtual bool FileExists(const Common::String &Filename) { virtual bool fileExists(const Common::String &filename) {
Common::File f; Common::File f;
if (f.exists(Filename)) if (f.exists(filename))
return true; return true;
// Check if the file exists in the save folder // Check if the file exists in the save folder
Common::FSNode folder(PersistenceService::GetSavegameDirectory()); Common::FSNode folder(PersistenceService::getSavegameDirectory());
Common::FSNode fileNode = folder.getChild(FileSystemUtil::GetInstance().GetPathFilename(Filename)); Common::FSNode fileNode = folder.getChild(FileSystemUtil::getInstance().getPathFilename(filename));
return fileNode.exists(); return fileNode.exists();
} }
virtual bool CreateDirectory(const Common::String &DirectoryName) { virtual bool createDirectory(const Common::String &sirectoryName) {
// ScummVM doesn't support creating folders, so this is only a stub // ScummVM doesn't support creating folders, so this is only a stub
BS_LOG_ERRORLN("CreateDirectory method called"); BS_LOG_ERRORLN("CreateDirectory method called");
return false; return false;
} }
virtual Common::String GetPathFilename(const Common::String &Path) { virtual Common::String getPathFilename(const Common::String &path) {
for (int i = Path.size() - 1; i >= 0; --i) { for (int i = path.size() - 1; i >= 0; --i) {
if ((Path[i] == '/') || (Path[i] == '\\')) { if ((path[i] == '/') || (path[i] == '\\')) {
return Common::String(&Path.c_str()[i + 1]); return Common::String(&path.c_str()[i + 1]);
} }
} }
return Path; return path;
} }
}; };
// ----------------------------------------------------------------------------- FileSystemUtil &FileSystemUtil::getInstance() {
// Singleton method of parent class static BS_FileSystemUtilScummVM instance;
// ----------------------------------------------------------------------------- return instance;
FileSystemUtil &FileSystemUtil::GetInstance() {
static BS_FileSystemUtilScummVM Instance;
return Instance;
} }
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -61,7 +61,7 @@ namespace Sword25 {
class FileSystemUtil { class FileSystemUtil {
public: public:
static FileSystemUtil &GetInstance(); static FileSystemUtil &getInstance();
virtual ~FileSystemUtil() {} virtual ~FileSystemUtil() {}
/** /**
@ -70,27 +70,27 @@ public:
* These are for example Screenshots, game saves, configuration files, log files, ... * These are for example Screenshots, game saves, configuration files, log files, ...
* @return Returns the name of the directory for user data. * @return Returns the name of the directory for user data.
*/ */
virtual Common::String GetUserdataDirectory() = 0; virtual Common::String getUserdataDirectory() = 0;
/** /**
* @return Returns the path seperator * @return Returns the path seperator
*/ */
virtual Common::String GetPathSeparator() = 0; virtual Common::String getPathSeparator() = 0;
/** /**
* @param Filename The path to a file. * @param Filename The path to a file.
* @return Returns the size of the specified file. If the size could not be * @return Returns the size of the specified file. If the size could not be
* determined, or the file does not exist, returns -1 * determined, or the file does not exist, returns -1
*/ */
virtual int32 GetFileSize(const Common::String &Filename) = 0; virtual int32 getFileSize(const Common::String &filename) = 0;
/** /**
* @param Filename The path to a file. * @param Filename The path to a file.
* @return Returns the timestamp of the specified file. * @return Returns the timestamp of the specified file.
*/ */
virtual TimeDate GetFileTime(const Common::String &Filename) = 0; virtual TimeDate getFileTime(const Common::String &filename) = 0;
/** /**
* @param Filename The path to a file. * @param Filename The path to a file.
* @return Returns true if the file exists. * @return Returns true if the file exists.
*/ */
virtual bool FileExists(const Common::String &Filename) = 0; virtual bool fileExists(const Common::String &filename) = 0;
/** /**
* This function creates a directory * This function creates a directory
* *
@ -99,13 +99,13 @@ public:
* @param DirectoryName The name of the directory to be created * @param DirectoryName The name of the directory to be created
* @return Returns true if the folder(s) could be created, otherwise false. * @return Returns true if the folder(s) could be created, otherwise false.
*/ */
virtual bool CreateDirectory(const Common::String &DirectoryName) = 0; virtual bool createDirectory(const Common::String &directoryName) = 0;
/** /**
* Gets the filename from a path and filename * Gets the filename from a path and filename
* @param Filename The full path and filename * @param Filename The full path and filename
* @return Returns just the filename * @return Returns just the filename
*/ */
virtual Common::String GetPathFilename(const Common::String &Path) = 0; virtual Common::String getPathFilename(const Common::String &path) = 0;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -34,146 +34,116 @@
#define BS_LOG_PREFIX "INPUTPERSISTENCEBLOCK" #define BS_LOG_PREFIX "INPUTPERSISTENCEBLOCK"
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/inputpersistenceblock.h" #include "sword25/kernel/inputpersistenceblock.h"
namespace Sword25 { namespace Sword25 {
// ----------------------------------------------------------------------------- InputPersistenceBlock::InputPersistenceBlock(const void *data, uint dataLength) :
// Constructor / Destructor _data(static_cast<const byte *>(data), dataLength),
// ----------------------------------------------------------------------------- _errorState(NONE) {
_iter = _data.begin();
InputPersistenceBlock::InputPersistenceBlock(const void *Data, uint DataLength) :
m_Data(static_cast<const byte *>(Data), DataLength),
m_ErrorState(NONE) {
m_Iter = m_Data.begin();
} }
// -----------------------------------------------------------------------------
InputPersistenceBlock::~InputPersistenceBlock() { InputPersistenceBlock::~InputPersistenceBlock() {
if (m_Iter != m_Data.end()) BS_LOG_WARNINGLN("Persistence block was not read to the end."); if (_iter != _data.end())
BS_LOG_WARNINGLN("Persistence block was not read to the end.");
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(int16 &value) {
// Reading
// -----------------------------------------------------------------------------
void InputPersistenceBlock::read(int16 &Value) {
signed int v; signed int v;
read(v); read(v);
Value = static_cast<int16>(v); value = static_cast<int16>(v);
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(signed int &value) {
if (checkMarker(SINT_MARKER)) {
void InputPersistenceBlock::read(signed int &Value) { rawRead(&value, sizeof(signed int));
if (CheckMarker(SINT_MARKER)) { value = convertEndianessFromStorageToSystem(value);
RawRead(&Value, sizeof(signed int));
Value = ConvertEndianessFromStorageToSystem(Value);
} else { } else {
Value = 0; value = 0;
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(uint &value) {
if (checkMarker(UINT_MARKER)) {
void InputPersistenceBlock::read(uint &Value) { rawRead(&value, sizeof(uint));
if (CheckMarker(UINT_MARKER)) { value = convertEndianessFromStorageToSystem(value);
RawRead(&Value, sizeof(uint));
Value = ConvertEndianessFromStorageToSystem(Value);
} else { } else {
Value = 0; value = 0;
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(float &value) {
if (checkMarker(FLOAT_MARKER)) {
void InputPersistenceBlock::read(float &Value) { rawRead(&value, sizeof(float));
if (CheckMarker(FLOAT_MARKER)) { value = convertEndianessFromStorageToSystem(value);
RawRead(&Value, sizeof(float));
Value = ConvertEndianessFromStorageToSystem(Value);
} else { } else {
Value = 0.0f; value = 0.0f;
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(bool &value) {
if (checkMarker(BOOL_MARKER)) {
void InputPersistenceBlock::read(bool &Value) { uint uintBool;
if (CheckMarker(BOOL_MARKER)) { rawRead(&uintBool, sizeof(float));
uint UIntBool; uintBool = convertEndianessFromStorageToSystem(uintBool);
RawRead(&UIntBool, sizeof(float)); value = uintBool == 0 ? false : true;
UIntBool = ConvertEndianessFromStorageToSystem(UIntBool);
Value = UIntBool == 0 ? false : true;
} else { } else {
Value = 0.0f; value = 0.0f;
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(Common::String &value) {
value = "";
void InputPersistenceBlock::read(Common::String &Value) { if (checkMarker(STRING_MARKER)) {
Value = ""; uint size;
read(size);
if (CheckMarker(STRING_MARKER)) { if (checkBlockSize(size)) {
uint Size; value = Common::String(reinterpret_cast<const char *>(&*_iter), size);
read(Size); _iter += size;
if (CheckBlockSize(Size)) {
Value = Common::String(reinterpret_cast<const char *>(&*m_Iter), Size);
m_Iter += Size;
} }
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::read(Common::Array<byte> &value) {
if (checkMarker(BLOCK_MARKER)) {
uint size;
read(size);
void InputPersistenceBlock::read(Common::Array<byte> &Value) { if (checkBlockSize(size)) {
if (CheckMarker(BLOCK_MARKER)) { value = Common::Array<byte>(_iter, size);
uint Size; _iter += size;
read(Size);
if (CheckBlockSize(Size)) {
Value = Common::Array<byte>(m_Iter, Size);
m_Iter += Size;
} }
} }
} }
// ----------------------------------------------------------------------------- void InputPersistenceBlock::rawRead(void *destPtr, size_t size) {
if (checkBlockSize(size)) {
void InputPersistenceBlock::RawRead(void *DestPtr, size_t Size) { memcpy(destPtr, &*_iter, size);
if (CheckBlockSize(Size)) { _iter += size;
memcpy(DestPtr, &*m_Iter, Size);
m_Iter += Size;
} }
} }
// ----------------------------------------------------------------------------- bool InputPersistenceBlock::checkBlockSize(int size) {
if (_data.end() - _iter >= size) {
bool InputPersistenceBlock::CheckBlockSize(int Size) {
if (m_Data.end() - m_Iter >= Size) {
return true; return true;
} else { } else {
m_ErrorState = END_OF_DATA; _errorState = END_OF_DATA;
BS_LOG_ERRORLN("Unexpected end of persistence block."); BS_LOG_ERRORLN("Unexpected end of persistence block.");
return false; return false;
} }
} }
// ----------------------------------------------------------------------------- bool InputPersistenceBlock::checkMarker(byte marker) {
if (!isGood() || !checkBlockSize(1))
return false;
bool InputPersistenceBlock::CheckMarker(byte Marker) { if (*_iter++ == marker) {
if (!isGood() || !CheckBlockSize(1)) return false;
if (*m_Iter++ == Marker) {
return true; return true;
} else { } else {
m_ErrorState = OUT_OF_SYNC; _errorState = OUT_OF_SYNC;
BS_LOG_ERRORLN("Wrong type marker found in persistence block."); BS_LOG_ERRORLN("Wrong type marker found in persistence block.");
return false; return false;
} }

View file

@ -35,20 +35,12 @@
#ifndef SWORD25_INPUTPERSISTENCEBLOCK_H #ifndef SWORD25_INPUTPERSISTENCEBLOCK_H
#define SWORD25_INPUTPERSISTENCEBLOCK_H #define SWORD25_INPUTPERSISTENCEBLOCK_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/array.h" #include "common/array.h"
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/persistenceblock.h" #include "sword25/kernel/persistenceblock.h"
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Class declaration
// -----------------------------------------------------------------------------
class InputPersistenceBlock : public PersistenceBlock { class InputPersistenceBlock : public PersistenceBlock {
public: public:
enum ErrorState { enum ErrorState {
@ -57,32 +49,32 @@ public:
OUT_OF_SYNC OUT_OF_SYNC
}; };
InputPersistenceBlock(const void *Data, uint DataLength); InputPersistenceBlock(const void *data, uint dataLength);
virtual ~InputPersistenceBlock(); virtual ~InputPersistenceBlock();
void read(int16 &Value); void read(int16 &value);
void read(signed int &Value); void read(signed int &value);
void read(uint &Value); void read(uint &value);
void read(float &Value); void read(float &value);
void read(bool &Value); void read(bool &value);
void read(Common::String &Value); void read(Common::String &value);
void read(Common::Array<byte> &Value); void read(Common::Array<byte> &value);
bool isGood() const { bool isGood() const {
return m_ErrorState == NONE; return _errorState == NONE;
} }
ErrorState GetErrorState() const { ErrorState getErrorState() const {
return m_ErrorState; return _errorState;
} }
private: private:
bool CheckMarker(byte Marker); bool checkMarker(byte marker);
bool CheckBlockSize(int Size); bool checkBlockSize(int size);
void RawRead(void *DestPtr, size_t Size); void rawRead(void *destPtr, size_t size);
Common::Array<byte> m_Data; Common::Array<byte> _data;
Common::Array<byte>::const_iterator m_Iter; Common::Array<byte>::const_iterator _iter;
ErrorState m_ErrorState; ErrorState _errorState;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -47,14 +47,13 @@ namespace Sword25 {
#define BS_LOG_PREFIX "KERNEL" #define BS_LOG_PREFIX "KERNEL"
Kernel *Kernel::_instance = 0;
Kernel *Kernel::_Instance = 0;
Kernel::Kernel() : Kernel::Kernel() :
_pWindow(NULL), _pWindow(NULL),
_Running(false), _running(false),
_pResourceManager(NULL), _pResourceManager(NULL),
_InitSuccess(false) { _initSuccess(false) {
// Log that the kernel is beign created // Log that the kernel is beign created
BS_LOGLN("created."); BS_LOGLN("created.");
@ -63,10 +62,10 @@ Kernel::Kernel() :
for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) { for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) {
// Is the superclass already registered? // Is the superclass already registered?
Superclass *pCurSuperclass = NULL; Superclass *pCurSuperclass = NULL;
Common::Array<Superclass *>::iterator Iter; Common::Array<Superclass *>::iterator iter;
for (Iter = _superclasses.begin(); Iter != _superclasses.end(); ++Iter) for (iter = _superclasses.begin(); iter != _superclasses.end(); ++iter)
if ((*Iter)->GetIdentifier() == BS_SERVICE_TABLE[i].superclassId) { if ((*iter)->getIdentifier() == BS_SERVICE_TABLE[i].superclassId) {
pCurSuperclass = *Iter; pCurSuperclass = *iter;
break; break;
} }
@ -76,7 +75,7 @@ Kernel::Kernel() :
} }
// Create window object // Create window object
_pWindow = Window::CreateBSWindow(0, 0, 0, 0, false); _pWindow = Window::createBSWindow(0, 0, 0, 0, false);
if (!_pWindow) { if (!_pWindow) {
BS_LOG_ERRORLN("Failed to create the window."); BS_LOG_ERRORLN("Failed to create the window.");
} else } else
@ -86,29 +85,30 @@ Kernel::Kernel() :
_pResourceManager = new ResourceManager(this); _pResourceManager = new ResourceManager(this);
// Initialise the script engine // Initialise the script engine
ScriptEngine *pScript = static_cast<ScriptEngine *>(NewService("script", "lua")); ScriptEngine *pScript = static_cast<ScriptEngine *>(newService("script", "lua"));
if (!pScript || !pScript->init()) { if (!pScript || !pScript->init()) {
_InitSuccess = false; _initSuccess = false;
return; return;
} }
// Register kernel script bindings // Register kernel script bindings
if (!_RegisterScriptBindings()) { if (!registerScriptBindings()) {
BS_LOG_ERRORLN("Script bindings could not be registered."); BS_LOG_ERRORLN("Script bindings could not be registered.");
_InitSuccess = false; _initSuccess = false;
return; return;
} }
BS_LOGLN("Script bindings registered."); BS_LOGLN("Script bindings registered.");
_InitSuccess = true; _initSuccess = true;
} }
Kernel::~Kernel() { Kernel::~Kernel() {
// Services are de-registered in reverse order of creation // Services are de-registered in reverse order of creation
while (!_ServiceCreationOrder.empty()) { while (!_serviceCreationOrder.empty()) {
Superclass *superclass = GetSuperclassByIdentifier(_ServiceCreationOrder.top()); Superclass *superclass = getSuperclassByIdentifier(_serviceCreationOrder.top());
if (superclass) superclass->DisconnectService(); if (superclass)
_ServiceCreationOrder.pop(); superclass->disconnectService();
_serviceCreationOrder.pop();
} }
// Empty the Superclass list // Empty the Superclass list
@ -127,21 +127,18 @@ Kernel::~Kernel() {
BS_LOGLN("destroyed."); BS_LOGLN("destroyed.");
} }
// Service Methoden Kernel::Superclass::Superclass(Kernel *pKernel, const Common::String &identifier) :
// ----------------
Kernel::Superclass::Superclass(Kernel *pKernel, const Common::String &Identifier) :
_pKernel(pKernel), _pKernel(pKernel),
_Identifier(Identifier), _identifier(identifier),
_ServiceCount(0), _serviceCount(0),
_ActiveService(NULL) { _activeService(NULL) {
for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++)
if (BS_SERVICE_TABLE[i].superclassId == _Identifier) if (BS_SERVICE_TABLE[i].superclassId == _identifier)
_ServiceCount++; _serviceCount++;
} }
Kernel::Superclass::~Superclass() { Kernel::Superclass::~Superclass() {
DisconnectService(); disconnectService();
} }
/** /**
@ -153,16 +150,17 @@ Kernel::Superclass::~Superclass() {
* Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen * Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen
* 0 und GetServiceCount() - 1 sein. * 0 und GetServiceCount() - 1 sein.
*/ */
Common::String Kernel::Superclass::GetServiceIdentifier(uint Number) { Common::String Kernel::Superclass::getServiceIdentifier(uint number) {
if (Number > _ServiceCount) return NULL; if (number > _serviceCount)
return NULL;
uint CurServiceOrd = 0; uint curServiceOrd = 0;
for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) { for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) {
if (BS_SERVICE_TABLE[i].superclassId == _Identifier) { if (BS_SERVICE_TABLE[i].superclassId == _identifier) {
if (Number == CurServiceOrd) if (number == curServiceOrd)
return BS_SERVICE_TABLE[i].serviceId; return BS_SERVICE_TABLE[i].serviceId;
else else
CurServiceOrd++; curServiceOrd++;
} }
} }
@ -178,25 +176,25 @@ Common::String Kernel::Superclass::GetServiceIdentifier(uint Number) {
* @param serviceId The name of the service * @param serviceId The name of the service
* For the superclass "sfx" an example could be "Fmod" or "directsound" * For the superclass "sfx" an example could be "Fmod" or "directsound"
*/ */
Service *Kernel::Superclass::NewService(const Common::String &serviceId) { Service *Kernel::Superclass::newService(const Common::String &serviceId) {
for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++) for (uint i = 0; i < ARRAYSIZE(BS_SERVICE_TABLE); i++)
if (BS_SERVICE_TABLE[i].superclassId == _Identifier && if (BS_SERVICE_TABLE[i].superclassId == _identifier &&
BS_SERVICE_TABLE[i].serviceId == serviceId) { BS_SERVICE_TABLE[i].serviceId == serviceId) {
Service *newService = BS_SERVICE_TABLE[i].create(_pKernel); Service *newService_ = BS_SERVICE_TABLE[i].create(_pKernel);
if (newService) { if (newService_) {
DisconnectService(); disconnectService();
BS_LOGLN("Service '%s' created from superclass '%s'.", serviceId.c_str(), _Identifier.c_str()); BS_LOGLN("Service '%s' created from superclass '%s'.", serviceId.c_str(), _identifier.c_str());
_ActiveService = newService; _activeService = newService_;
_ActiveServiceName = BS_SERVICE_TABLE[i].serviceId; _activeServiceName = BS_SERVICE_TABLE[i].serviceId;
return _ActiveService; return _activeService;
} else { } else {
BS_LOG_ERRORLN("Failed to create service '%s' from superclass '%s'.", serviceId.c_str(), _Identifier.c_str()); BS_LOG_ERRORLN("Failed to create service '%s' from superclass '%s'.", serviceId.c_str(), _identifier.c_str());
return NULL; return NULL;
} }
} }
BS_LOG_ERRORLN("Service '%s' is not avaliable from superclass '%s'.", serviceId.c_str(), _Identifier.c_str()); BS_LOG_ERRORLN("Service '%s' is not avaliable from superclass '%s'.", serviceId.c_str(), _identifier.c_str());
return NULL; return NULL;
} }
@ -206,32 +204,32 @@ Service *Kernel::Superclass::NewService(const Common::String &serviceId) {
* @param superclassId The name of the superclass which is to be disconnected * @param superclassId The name of the superclass which is to be disconnected
* e.g.: "sfx", "gfx", "package" ... * e.g.: "sfx", "gfx", "package" ...
*/ */
bool Kernel::Superclass::DisconnectService() { bool Kernel::Superclass::disconnectService() {
if (_ActiveService) { if (_activeService) {
delete _ActiveService; delete _activeService;
_ActiveService = 0; _activeService = 0;
BS_LOGLN("Active service '%s' disconnected from superclass '%s'.", _ActiveServiceName.c_str(), _Identifier.c_str()); BS_LOGLN("Active service '%s' disconnected from superclass '%s'.", _activeServiceName.c_str(), _identifier.c_str());
return true; return true;
} }
return false; return false;
} }
Kernel::Superclass *Kernel::GetSuperclassByIdentifier(const Common::String &Identifier) const { Kernel::Superclass *Kernel::getSuperclassByIdentifier(const Common::String &identifier) const {
Common::Array<Superclass *>::const_iterator Iter; Common::Array<Superclass *>::const_iterator iter;
for (Iter = _superclasses.begin(); Iter != _superclasses.end(); ++Iter) { for (iter = _superclasses.begin(); iter != _superclasses.end(); ++iter) {
if ((*Iter)->GetIdentifier() == Identifier) if ((*iter)->getIdentifier() == identifier)
return *Iter; return *iter;
} }
// BS_LOG_ERRORLN("Superclass '%s' does not exist.", Identifier.c_str()); // BS_LOG_ERRORLN("Superclass '%s' does not exist.", identifier.c_str());
return NULL; return NULL;
} }
/** /**
* Returns the number of register superclasses * Returns the number of register superclasses
*/ */
uint Kernel::GetSuperclassCount() const { uint Kernel::getSuperclassCount() const {
return _superclasses.size(); return _superclasses.size();
} }
@ -241,17 +239,17 @@ uint Kernel::GetSuperclassCount() const {
* @param Number The number of the superclass to return the identifier for. * @param Number The number of the superclass to return the identifier for.
* It should be noted that the number should be between 0 und GetSuperclassCount() - 1. * It should be noted that the number should be between 0 und GetSuperclassCount() - 1.
*/ */
Common::String Kernel::GetSuperclassIdentifier(uint Number) const { Common::String Kernel::getSuperclassIdentifier(uint number) const {
if (Number > _superclasses.size()) if (number > _superclasses.size())
return NULL; return NULL;
uint CurSuperclassOrd = 0; uint curSuperclassOrd = 0;
Common::Array<Superclass *>::const_iterator Iter; Common::Array<Superclass *>::const_iterator iter;
for (Iter = _superclasses.begin(); Iter != _superclasses.end(); ++Iter) { for (iter = _superclasses.begin(); iter != _superclasses.end(); ++iter) {
if (CurSuperclassOrd == Number) if (curSuperclassOrd == number)
return ((*Iter)->GetIdentifier()); return ((*iter)->getIdentifier());
CurSuperclassOrd++; curSuperclassOrd++;
} }
return Common::String(); return Common::String();
@ -262,12 +260,12 @@ Common::String Kernel::GetSuperclassIdentifier(uint Number) const {
* @param superclassId The name of the superclass * @param superclassId The name of the superclass
* e.g.: "sfx", "gfx", "package" ... * e.g.: "sfx", "gfx", "package" ...
*/ */
uint Kernel::GetServiceCount(const Common::String &superclassId) const { uint Kernel::getServiceCount(const Common::String &superclassId) const {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return 0; return 0;
return pSuperclass->GetServiceCount(); return pSuperclass->getServiceCount();
} }
@ -280,12 +278,12 @@ uint Kernel::GetServiceCount(const Common::String &superclassId) const {
* Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen * Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen
* 0 und GetServiceCount() - 1 sein. * 0 und GetServiceCount() - 1 sein.
*/ */
Common::String Kernel::GetServiceIdentifier(const Common::String &superclassId, uint Number) const { Common::String Kernel::getServiceIdentifier(const Common::String &superclassId, uint number) const {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return NULL; return NULL;
return (pSuperclass->GetServiceIdentifier(Number)); return (pSuperclass->getServiceIdentifier(number));
} }
/** /**
@ -297,15 +295,15 @@ Common::String Kernel::GetServiceIdentifier(const Common::String &superclassId,
* @param serviceId The name of the service * @param serviceId The name of the service
* For the superclass "sfx" an example could be "Fmod" or "directsound" * For the superclass "sfx" an example could be "Fmod" or "directsound"
*/ */
Service *Kernel::NewService(const Common::String &superclassId, const Common::String &serviceId) { Service *Kernel::newService(const Common::String &superclassId, const Common::String &serviceId) {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return NULL; return NULL;
// Die Reihenfolge merken, in der Services erstellt werden, damit sie später in umgekehrter Reihenfolge entladen werden können. // Die Reihenfolge merken, in der Services erstellt werden, damit sie später in umgekehrter Reihenfolge entladen werden können.
_ServiceCreationOrder.push(superclassId); _serviceCreationOrder.push(superclassId);
return pSuperclass->NewService(serviceId); return pSuperclass->newService(serviceId);
} }
/** /**
@ -314,12 +312,12 @@ Service *Kernel::NewService(const Common::String &superclassId, const Common::St
* e.g.: "sfx", "gfx", "package" ... * e.g.: "sfx", "gfx", "package" ...
* @return true on success, and false if the superclass does not exist or if not service was active. * @return true on success, and false if the superclass does not exist or if not service was active.
*/ */
bool Kernel::DisconnectService(const Common::String &superclassId) { bool Kernel::disconnectService(const Common::String &superclassId) {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return false; return false;
return pSuperclass->DisconnectService(); return pSuperclass->disconnectService();
} }
/** /**
@ -327,12 +325,12 @@ bool Kernel::DisconnectService(const Common::String &superclassId) {
* @param superclassId The name of the superclass * @param superclassId The name of the superclass
* e.g.: "sfx", "gfx", "package" ... * e.g.: "sfx", "gfx", "package" ...
*/ */
Service *Kernel::GetService(const Common::String &superclassId) { Service *Kernel::getService(const Common::String &superclassId) {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return NULL; return NULL;
return (pSuperclass->GetActiveService()); return (pSuperclass->getActiveService());
} }
/** /**
@ -341,113 +339,83 @@ Service *Kernel::GetService(const Common::String &superclassId) {
* @param superclassId The name of the superclass * @param superclassId The name of the superclass
* e.g.: "sfx", "gfx", "package" ... * e.g.: "sfx", "gfx", "package" ...
*/ */
Common::String Kernel::GetActiveServiceIdentifier(const Common::String &superclassId) { Common::String Kernel::getActiveServiceIdentifier(const Common::String &superclassId) {
Superclass *pSuperclass = GetSuperclassByIdentifier(superclassId); Superclass *pSuperclass = getSuperclassByIdentifier(superclassId);
if (!pSuperclass) if (!pSuperclass)
return Common::String(); return Common::String();
return pSuperclass->GetActiveServiceName(); return pSuperclass->getActiveServiceName();
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a random number * Returns a random number
* @param Min The minimum allowed value * @param Min The minimum allowed value
* @param Max The maximum allowed value * @param Max The maximum allowed value
*/ */
int Kernel::GetRandomNumber(int Min, int Max) { int Kernel::getRandomNumber(int min, int max) {
BS_ASSERT(Min <= Max); BS_ASSERT(min <= max);
return Min + _rnd.getRandomNumber(Max - Min + 1); return min + _rnd.getRandomNumber(max - min + 1);
} }
/** /**
* Returns the elapsed time since startup in milliseconds * Returns the elapsed time since startup in milliseconds
*/ */
uint Kernel::GetMilliTicks() { uint Kernel::getMilliTicks() {
return g_system->getMillis(); return g_system->getMillis();
} }
// Other methods
// -----------------
/** /**
* Returns how much memory is being used * Returns how much memory is being used
*/ */
size_t Kernel::GetUsedMemory() { size_t Kernel::getUsedMemory() {
return 0; return 0;
#ifdef SCUMMVM_DISABLED_CODE
PROCESS_MEMORY_COUNTERS pmc;
pmc.cb = sizeof(pmc);
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) {
return pmc.WorkingSetSize;
} else {
BS_LOG_ERRORLN("Call to GetProcessMemoryInfo() failed. Error code: %d", GetLastError());
return 0;
}
#endif
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the active Gfx Service, or NULL if no Gfx service is active. * Returns a pointer to the active Gfx Service, or NULL if no Gfx service is active.
*/ */
GraphicEngine *Kernel::GetGfx() { GraphicEngine *Kernel::getGfx() {
return static_cast<GraphicEngine *>(GetService("gfx")); return static_cast<GraphicEngine *>(getService("gfx"));
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the active Sfx Service, or NULL if no Sfx service is active. * Returns a pointer to the active Sfx Service, or NULL if no Sfx service is active.
*/ */
SoundEngine *Kernel::GetSfx() { SoundEngine *Kernel::getSfx() {
return static_cast<SoundEngine *>(GetService("sfx")); return static_cast<SoundEngine *>(getService("sfx"));
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the active input service, or NULL if no input service is active. * Returns a pointer to the active input service, or NULL if no input service is active.
*/ */
InputEngine *Kernel::GetInput() { InputEngine *Kernel::getInput() {
return static_cast<InputEngine *>(GetService("input")); return static_cast<InputEngine *>(getService("input"));
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the active package manager, or NULL if no manager is active. * Returns a pointer to the active package manager, or NULL if no manager is active.
*/ */
PackageManager *Kernel::GetPackage() { PackageManager *Kernel::getPackage() {
return static_cast<PackageManager *>(GetService("package")); return static_cast<PackageManager *>(getService("package"));
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the script engine, or NULL if it is not active. * Returns a pointer to the script engine, or NULL if it is not active.
*/ */
ScriptEngine *Kernel::GetScript() { ScriptEngine *Kernel::getScript() {
return static_cast<ScriptEngine *>(GetService("script")); return static_cast<ScriptEngine *>(getService("script"));
} }
// -----------------------------------------------------------------------------
/** /**
* Returns a pointer to the movie player, or NULL if it is not active. * Returns a pointer to the movie player, or NULL if it is not active.
*/ */
MoviePlayer *Kernel::GetFMV() { MoviePlayer *Kernel::getFMV() {
return static_cast<MoviePlayer *>(GetService("fmv")); return static_cast<MoviePlayer *>(getService("fmv"));
} }
// ----------------------------------------------------------------------------- void Kernel::sleep(uint msecs) const {
g_system->delayMillis(msecs);
void Kernel::Sleep(uint Msecs) const {
g_system->delayMillis(Msecs);
} }
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -45,7 +45,6 @@
#ifndef SWORD25_KERNEL_H #ifndef SWORD25_KERNEL_H
#define SWORD25_KERNEL_H #define SWORD25_KERNEL_H
// Includes
#include "common/scummsys.h" #include "common/scummsys.h"
#include "common/random.h" #include "common/random.h"
#include "common/stack.h" #include "common/stack.h"
@ -81,7 +80,7 @@ public:
/** /**
* Returns a pointer to the window object * Returns a pointer to the window object
*/ */
Window *GetWindow() { Window *getWindow() {
return _pWindow; return _pWindow;
} }
@ -97,7 +96,7 @@ public:
* @param ServiceIdentifier The name of the service * @param ServiceIdentifier The name of the service
* For the superclass "sfx" an example could be "Fmod" or "directsound" * For the superclass "sfx" an example could be "Fmod" or "directsound"
*/ */
Service *NewService(const Common::String &SuperclassIdentifier, const Common::String &ServiceIdentifier); Service *newService(const Common::String &superclassIdentifier, const Common::String &serviceIdentifier);
/** /**
* Ends the current service of a superclass. Returns true on success, and false if the superclass * Ends the current service of a superclass. Returns true on success, and false if the superclass
@ -105,14 +104,14 @@ public:
* @param SuperclassIdentfier The name of the superclass which is to be disconnected * @param SuperclassIdentfier The name of the superclass which is to be disconnected
* z.B: "sfx", "gfx", "package" ... * z.B: "sfx", "gfx", "package" ...
*/ */
bool DisconnectService(const Common::String &SuperclassIdentifier); bool disconnectService(const Common::String &superclassIdentifier);
/** /**
* Returns a pointer to the currently active service object of a superclass * Returns a pointer to the currently active service object of a superclass
* @param SuperclassIdentfier The name of the superclass * @param SuperclassIdentfier The name of the superclass
* z.B: "sfx", "gfx", "package" ... * z.B: "sfx", "gfx", "package" ...
*/ */
Service *GetService(const Common::String &SuperclassIdentifier); Service *getService(const Common::String &superclassIdentifier);
/** /**
* Returns the name of the currentl active service object of a superclass. * Returns the name of the currentl active service object of a superclass.
@ -120,12 +119,12 @@ public:
* @param SuperclassIdentfier The name of the superclass * @param SuperclassIdentfier The name of the superclass
* z.B: "sfx", "gfx", "package" ... * z.B: "sfx", "gfx", "package" ...
*/ */
Common::String GetActiveServiceIdentifier(const Common::String &SuperclassIdentifier); Common::String getActiveServiceIdentifier(const Common::String &superclassIdentifier);
/** /**
* Returns the number of register superclasses * Returns the number of register superclasses
*/ */
uint GetSuperclassCount() const; uint getSuperclassCount() const;
/** /**
* Returns the name of a superclass with the specified index. * Returns the name of a superclass with the specified index.
@ -133,14 +132,14 @@ public:
* @param Number The number of the superclass to return the identifier for. * @param Number The number of the superclass to return the identifier for.
* It should be noted that the number should be between 0 und GetSuperclassCount() - 1. * It should be noted that the number should be between 0 und GetSuperclassCount() - 1.
*/ */
Common::String GetSuperclassIdentifier(uint Number) const; Common::String getSuperclassIdentifier(uint number) const;
/** /**
* Returns the number of services registered with a given superclass * Returns the number of services registered with a given superclass
* @param SuperclassIdentifier The name of the superclass * @param SuperclassIdentifier The name of the superclass
* z.B: "sfx", "gfx", "package" ... * z.B: "sfx", "gfx", "package" ...
*/ */
uint GetServiceCount(const Common::String &SuperclassIdentifier) const; uint getServiceCount(const Common::String &superclassIdentifier) const;
/** /**
* Gets the identifier of a service with a given superclass. * Gets the identifier of a service with a given superclass.
@ -151,73 +150,74 @@ public:
* Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen * Hierbei ist zu beachten, dass der erste Service die Nummer 0 erhält. Number muss also eine Zahl zwischen
* 0 und GetServiceCount() - 1 sein. * 0 und GetServiceCount() - 1 sein.
*/ */
Common::String GetServiceIdentifier(const Common::String &SuperclassIdentifier, uint Number) const; Common::String getServiceIdentifier(const Common::String &superclassIdentifier, uint number) const;
/** /**
* Returns the elapsed time since startup in milliseconds * Returns the elapsed time since startup in milliseconds
*/ */
uint GetMilliTicks(); uint getMilliTicks();
/** /**
* Specifies whether the kernel was successfully initialised * Specifies whether the kernel was successfully initialised
*/ */
bool GetInitSuccess() const { bool getInitSuccess() const {
return _InitSuccess; return _initSuccess;
} }
/** /**
* Returns a pointer to the BS_ResourceManager * Returns a pointer to the BS_ResourceManager
*/ */
ResourceManager *GetResourceManager() { ResourceManager *getResourceManager() {
return _pResourceManager; return _pResourceManager;
} }
/** /**
* Returns how much memory is being used * Returns how much memory is being used
*/ */
size_t GetUsedMemory(); size_t getUsedMemory();
/** /**
* Returns a random number * Returns a random number
* @param Min The minimum allowed value * @param Min The minimum allowed value
* @param Max The maximum allowed value * @param Max The maximum allowed value
*/ */
int GetRandomNumber(int Min, int Max); int getRandomNumber(int min, int max);
/** /**
* Returns a pointer to the active Gfx Service, or NULL if no Gfx service is active * Returns a pointer to the active Gfx Service, or NULL if no Gfx service is active
*/ */
GraphicEngine *GetGfx(); GraphicEngine *getGfx();
/** /**
* Returns a pointer to the active Sfx Service, or NULL if no Sfx service is active * Returns a pointer to the active Sfx Service, or NULL if no Sfx service is active
*/ */
SoundEngine *GetSfx(); SoundEngine *getSfx();
/** /**
* Returns a pointer to the active input service, or NULL if no input service is active * Returns a pointer to the active input service, or NULL if no input service is active
*/ */
InputEngine *GetInput(); InputEngine *getInput();
/** /**
* Returns a pointer to the active package manager, or NULL if no manager is active * Returns a pointer to the active package manager, or NULL if no manager is active
*/ */
PackageManager *GetPackage(); PackageManager *getPackage();
/** /**
* Returns a pointer to the script engine, or NULL if it is not active * Returns a pointer to the script engine, or NULL if it is not active
*/ */
ScriptEngine *GetScript(); ScriptEngine *getScript();
/** /**
* Returns a pointer to the movie player, or NULL if it is not active * Returns a pointer to the movie player, or NULL if it is not active
*/ */
MoviePlayer *GetFMV(); MoviePlayer *getFMV();
/** /**
* Pauses for the specified amount of time * Pauses for the specified amount of time
* @param Msecs The amount of time in milliseconds * @param Msecs The amount of time in milliseconds
*/ */
void Sleep(uint Msecs) const; void sleep(uint msecs) const;
/** /**
* Returns the singleton instance for the kernel * Returns the singleton instance for the kernel
*/ */
static Kernel *GetInstance() { static Kernel *getInstance() {
if (!_Instance) _Instance = new Kernel(); if (!_instance)
return _Instance; _instance = new Kernel();
return _instance;
} }
/** /**
@ -225,18 +225,18 @@ public:
* This method should only be called when the game is ended. No subsequent calls to any kernel * This method should only be called when the game is ended. No subsequent calls to any kernel
* methods should be done after calling this method. * methods should be done after calling this method.
*/ */
static void DeleteInstance() { static void deleteInstance() {
if (_Instance) { if (_instance) {
delete _Instance; delete _instance;
_Instance = NULL; _instance = NULL;
} }
} }
/** /**
* Raises an error. This method is used in crashing testing. * Raises an error. This method is used in crashing testing.
*/ */
void Crash() const { void crash() const {
error("BS_Kernel::Crash"); error("Kernel::Crash");
} }
private: private:
@ -251,45 +251,45 @@ private:
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Singleton instance // Singleton instance
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static Kernel *_Instance; static Kernel *_instance;
// Superclass class // Superclass class
// ---------------- // ----------------
class Superclass { class Superclass {
private: private:
Kernel *_pKernel; Kernel *_pKernel;
uint _ServiceCount; uint _serviceCount;
Common::String _Identifier; Common::String _identifier;
Service *_ActiveService; Service *_activeService;
Common::String _ActiveServiceName; Common::String _activeServiceName;
public: public:
Superclass(Kernel *pKernel, const Common::String &Identifier); Superclass(Kernel *pKernel, const Common::String &identifier);
~Superclass(); ~Superclass();
uint GetServiceCount() const { uint getServiceCount() const {
return _ServiceCount; return _serviceCount;
} }
Common::String GetIdentifier() const { Common::String getIdentifier() const {
return _Identifier; return _identifier;
} }
Service *GetActiveService() const { Service *getActiveService() const {
return _ActiveService; return _activeService;
} }
Common::String GetActiveServiceName() const { Common::String getActiveServiceName() const {
return _ActiveServiceName; return _activeServiceName;
} }
Common::String GetServiceIdentifier(uint Number); Common::String getServiceIdentifier(uint number);
Service *NewService(const Common::String &ServiceIdentifier); Service *newService(const Common::String &serviceIdentifier);
bool DisconnectService(); bool disconnectService();
}; };
Common::Array<Superclass *> _superclasses; Common::Array<Superclass *> _superclasses;
Common::Stack<Common::String> _ServiceCreationOrder; Common::Stack<Common::String> _serviceCreationOrder;
Superclass *GetSuperclassByIdentifier(const Common::String &Identifier) const; Superclass *getSuperclassByIdentifier(const Common::String &identifier) const;
bool _InitSuccess; // Specifies whether the engine was set up correctly bool _initSuccess; // Specifies whether the engine was set up correctly
bool _Running; // Specifies whether the application should keep running on the next main loop iteration bool _running; // Specifies whether the application should keep running on the next main loop iteration
// Active window // Active window
// ------------- // -------------
@ -299,34 +299,11 @@ private:
// ----------------------- // -----------------------
Common::RandomSource _rnd; Common::RandomSource _rnd;
/*
// Features variables and methods
// ----------------------------------
enum _CPU_FEATURES_BITMASKS
{
_MMX_BITMASK = (1 << 23),
_SSE_BITMASK = (1 << 25),
_SSE2_BITMASK = (1 << 26),
_3DNOW_BITMASK = (1 << 30),
_3DNOWEXT_BITMASK = (1 << 31)
};
bool _DetectCPU();
bool _MMXPresent;
bool _SSEPresent;
bool _SSE2Present;
bool _3DNowPresent;
bool _3DNowExtPresent;
CPU_TYPES _CPUType;
Common::String _CPUVendorID;
*/
// Resourcemanager // Resourcemanager
// --------------- // ---------------
ResourceManager *_pResourceManager; ResourceManager *_pResourceManager;
bool _RegisterScriptBindings(); bool registerScriptBindings();
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -32,10 +32,6 @@
* *
*/ */
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/kernel.h" #include "sword25/kernel/kernel.h"
#include "sword25/kernel/filesystemutil.h" #include "sword25/kernel/filesystemutil.h"
@ -47,131 +43,107 @@
namespace Sword25 { namespace Sword25 {
// ----------------------------------------------------------------------------- static int disconnectService(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int DisconnectService(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushboolean(L, pKernel->DisconnectService(luaL_checkstring(L, 1))); lua_pushboolean(L, pKernel->disconnectService(luaL_checkstring(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getActiveServiceIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetActiveServiceIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushstring(L, pKernel->GetActiveServiceIdentifier(luaL_checkstring(L, 1)).c_str()); lua_pushstring(L, pKernel->getActiveServiceIdentifier(luaL_checkstring(L, 1)).c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSuperclassCount(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetSuperclassCount(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushnumber(L, pKernel->GetSuperclassCount()); lua_pushnumber(L, pKernel->getSuperclassCount());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSuperclassIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetSuperclassIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushstring(L, pKernel->GetSuperclassIdentifier( lua_pushstring(L, pKernel->getSuperclassIdentifier(
static_cast<uint>(luaL_checknumber(L, 1))).c_str()); static_cast<uint>(luaL_checknumber(L, 1))).c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getServiceCount(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetServiceCount(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushnumber(L, pKernel->GetServiceCount(luaL_checkstring(L, 1))); lua_pushnumber(L, pKernel->getServiceCount(luaL_checkstring(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getServiceIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetServiceIdentifier(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushstring(L, pKernel->GetServiceIdentifier(luaL_checkstring(L, 1), lua_pushstring(L, pKernel->getServiceIdentifier(luaL_checkstring(L, 1),
static_cast<uint>(luaL_checknumber(L, 2))).c_str()); static_cast<uint>(luaL_checknumber(L, 2))).c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getMilliTicks(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetMilliTicks(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushnumber(L, pKernel->GetMilliTicks()); lua_pushnumber(L, pKernel->getMilliTicks());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getTimer(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetTimer(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushnumber(L, static_cast<lua_Number>(pKernel->GetMilliTicks()) / 1000.0); lua_pushnumber(L, static_cast<lua_Number>(pKernel->getMilliTicks()) / 1000.0);
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int startService(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int StartService(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
lua_pushbooleancpp(L, pKernel->NewService(luaL_checkstring(L, 1), luaL_checkstring(L, 2)) != NULL); lua_pushbooleancpp(L, pKernel->newService(luaL_checkstring(L, 1), luaL_checkstring(L, 2)) != NULL);
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int sleep(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int Sleep(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
pKernel->Sleep(static_cast<uint>(luaL_checknumber(L, 1) * 1000)); pKernel->sleep(static_cast<uint>(luaL_checknumber(L, 1) * 1000));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int crash(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int Crash(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
pKernel->Crash(); pKernel->crash();
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int executeFile(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int ExecuteFile(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pSE = pKernel->GetScript(); ScriptEngine *pSE = pKernel->getScript();
BS_ASSERT(pSE); BS_ASSERT(pSE);
lua_pushbooleancpp(L, pSE->executeFile(luaL_checkstring(L, 1))); lua_pushbooleancpp(L, pSE->executeFile(luaL_checkstring(L, 1)));
@ -179,551 +151,456 @@ static int ExecuteFile(lua_State *L) {
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int getUserdataDirectory(lua_State *L) {
lua_pushstring(L, FileSystemUtil::getInstance().getUserdataDirectory().c_str());
static int GetUserdataDirectory(lua_State *L) {
lua_pushstring(L, FileSystemUtil::GetInstance().GetUserdataDirectory().c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getPathSeparator(lua_State *L) {
lua_pushstring(L, FileSystemUtil::getInstance().getPathSeparator().c_str());
static int GetPathSeparator(lua_State *L) {
lua_pushstring(L, FileSystemUtil::GetInstance().GetPathSeparator().c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int fileExists(lua_State *L) {
lua_pushbooleancpp(L, FileSystemUtil::getInstance().fileExists(luaL_checkstring(L, 1)));
static int FileExists(lua_State *L) {
lua_pushbooleancpp(L, FileSystemUtil::GetInstance().FileExists(luaL_checkstring(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int createDirectory(lua_State *L) {
lua_pushbooleancpp(L, FileSystemUtil::getInstance().createDirectory(luaL_checkstring(L, 1)));
static int CreateDirectory(lua_State *L) {
lua_pushbooleancpp(L, FileSystemUtil::GetInstance().CreateDirectory(luaL_checkstring(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getWinCode(lua_State *L) {
static int GetWinCode(lua_State *L) {
lua_pushstring(L, "ScummVM"); lua_pushstring(L, "ScummVM");
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSubversionRevision(lua_State *L) {
static int GetSubversionRevision(lua_State *L) {
// ScummVM is 1337 // ScummVM is 1337
lua_pushnumber(L, 1337); lua_pushnumber(L, 1337);
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getUsedMemory(lua_State *L) {
lua_pushnumber(L, Kernel::getInstance()->getUsedMemory());
static int GetUsedMemory(lua_State *L) {
lua_pushnumber(L, Kernel::GetInstance()->GetUsedMemory());
return 1; return 1;
} }
// -----------------------------------------------------------------------------
static const char *KERNEL_LIBRARY_NAME = "Kernel"; static const char *KERNEL_LIBRARY_NAME = "Kernel";
static const luaL_reg KERNEL_FUNCTIONS[] = { static const luaL_reg KERNEL_FUNCTIONS[] = {
{"DisconnectService", DisconnectService}, {"DisconnectService", disconnectService},
{"GetActiveServiceIdentifier", GetActiveServiceIdentifier}, {"GetActiveServiceIdentifier", getActiveServiceIdentifier},
{"GetSuperclassCount", GetSuperclassCount}, {"GetSuperclassCount", getSuperclassCount},
{"GetSuperclassIdentifier", GetSuperclassIdentifier}, {"GetSuperclassIdentifier", getSuperclassIdentifier},
{"GetServiceCount", GetServiceCount}, {"GetServiceCount", getServiceCount},
{"GetServiceIdentifier", GetServiceIdentifier}, {"GetServiceIdentifier", getServiceIdentifier},
{"GetMilliTicks", GetMilliTicks}, {"GetMilliTicks", getMilliTicks},
{"GetTimer", GetTimer}, {"GetTimer", getTimer},
{"StartService", StartService}, {"StartService", startService},
{"Sleep", Sleep}, {"Sleep", sleep},
{"Crash", Crash}, {"Crash", crash},
{"ExecuteFile", ExecuteFile}, {"ExecuteFile", executeFile},
{"GetUserdataDirectory", GetUserdataDirectory}, {"GetUserdataDirectory", getUserdataDirectory},
{"GetPathSeparator", GetPathSeparator}, {"GetPathSeparator", getPathSeparator},
{"FileExists", FileExists}, {"FileExists", fileExists},
{"CreateDirectory", CreateDirectory}, {"CreateDirectory", createDirectory},
{"GetWinCode", GetWinCode}, {"GetWinCode", getWinCode},
{"GetSubversionRevision", GetSubversionRevision}, {"GetSubversionRevision", getSubversionRevision},
{"GetUsedMemory", GetUsedMemory}, {"GetUsedMemory", getUsedMemory},
{0, 0} {0, 0}
}; };
// ----------------------------------------------------------------------------- static int isVisible(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int IsVisible(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushbooleancpp(L, pWindow->IsVisible()); lua_pushbooleancpp(L, pWindow->isVisible());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setVisible(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetVisible(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetVisible(lua_tobooleancpp(L, 1)); pWindow->setVisible(lua_tobooleancpp(L, 1));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int getX(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetX(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetX()); lua_pushnumber(L, pWindow->getX());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getY(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetY(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetY()); lua_pushnumber(L, pWindow->getY());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setX(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetX(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetX(static_cast<int>(luaL_checknumber(L, 1))); pWindow->setX(static_cast<int>(luaL_checknumber(L, 1)));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int setY(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetY(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetY(static_cast<int>(luaL_checknumber(L, 1))); pWindow->setY(static_cast<int>(luaL_checknumber(L, 1)));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int getClientX(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetClientX(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetClientX()); lua_pushnumber(L, pWindow->getClientX());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getClientY(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetClientY(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetClientY()); lua_pushnumber(L, pWindow->getClientY());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getWidth(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetWidth(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetWidth()); lua_pushnumber(L, pWindow->getWidth());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getHeight(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetHeight(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushnumber(L, pWindow->GetHeight()); lua_pushnumber(L, pWindow->getHeight());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setWidth(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetWidth(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetWidth(static_cast<int>(luaL_checknumber(L, 1))); pWindow->setWidth(static_cast<int>(luaL_checknumber(L, 1)));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int setHeight(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetHeight(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetHeight(static_cast<int>(luaL_checknumber(L, 1))); pWindow->setHeight(static_cast<int>(luaL_checknumber(L, 1)));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int getTitle(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetTitle(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushstring(L, pWindow->GetTitle().c_str()); lua_pushstring(L, pWindow->getTitle().c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setTitle(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetTitle(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
pWindow->SetTitle(luaL_checkstring(L, 1)); pWindow->setTitle(luaL_checkstring(L, 1));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int processMessages(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int ProcessMessages(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushbooleancpp(L, pWindow->ProcessMessages()); lua_pushbooleancpp(L, pWindow->processMessages());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int closeWanted(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int CloseWanted(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushbooleancpp(L, pWindow->CloseWanted()); lua_pushbooleancpp(L, pWindow->closeWanted());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int waitForFocus(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int WaitForFocus(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushbooleancpp(L, pWindow->WaitForFocus()); lua_pushbooleancpp(L, pWindow->waitForFocus());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int hasFocus(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int HasFocus(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
Window *pWindow = pKernel->GetWindow(); Window *pWindow = pKernel->getWindow();
BS_ASSERT(pWindow); BS_ASSERT(pWindow);
lua_pushbooleancpp(L, pWindow->HasFocus()); lua_pushbooleancpp(L, pWindow->hasFocus());
return 1; return 1;
} }
// -----------------------------------------------------------------------------
static const char *WINDOW_LIBRARY_NAME = "Window"; static const char *WINDOW_LIBRARY_NAME = "Window";
static const luaL_reg WINDOW_FUNCTIONS[] = { static const luaL_reg WINDOW_FUNCTIONS[] = {
{"IsVisible", IsVisible}, {"IsVisible", isVisible},
{"SetVisible", SetVisible}, {"SetVisible", setVisible},
{"GetX", GetX}, {"GetX", getX},
{"SetX", SetX}, {"SetX", setX},
{"GetY", GetY}, {"GetY", getY},
{"SetY", SetY}, {"SetY", setY},
{"GetClientX", GetClientX}, {"GetClientX", getClientX},
{"GetClientY", GetClientY}, {"GetClientY", getClientY},
{"GetWidth", GetWidth}, {"GetWidth", getWidth},
{"GetHeight", GetHeight}, {"GetHeight", getHeight},
{"SetWidth", SetWidth}, {"SetWidth", setWidth},
{"SetHeight", SetHeight}, {"SetHeight", setHeight},
{"GetTitle", GetTitle}, {"GetTitle", getTitle},
{"SetTitle", SetTitle}, {"SetTitle", setTitle},
{"ProcessMessages", ProcessMessages}, {"ProcessMessages", processMessages},
{"CloseWanted", CloseWanted}, {"CloseWanted", closeWanted},
{"WaitForFocus", WaitForFocus}, {"WaitForFocus", waitForFocus},
{"HasFocus", HasFocus}, {"HasFocus", hasFocus},
{0, 0} {0, 0}
}; };
// ----------------------------------------------------------------------------- static int precacheResource(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int PrecacheResource(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
lua_pushbooleancpp(L, pResource->PrecacheResource(luaL_checkstring(L, 1))); lua_pushbooleancpp(L, pResource->precacheResource(luaL_checkstring(L, 1)));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int forcePrecacheResource(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int ForcePrecacheResource(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
lua_pushbooleancpp(L, pResource->PrecacheResource(luaL_checkstring(L, 1), true)); lua_pushbooleancpp(L, pResource->precacheResource(luaL_checkstring(L, 1), true));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getMaxMemoryUsage(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int GetMaxMemoryUsage(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
lua_pushnumber(L, pResource->GetMaxMemoryUsage()); lua_pushnumber(L, pResource->getMaxMemoryUsage());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setMaxMemoryUsage(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetMaxMemoryUsage(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
pResource->SetMaxMemoryUsage(static_cast<uint>(lua_tonumber(L, 1))); pResource->setMaxMemoryUsage(static_cast<uint>(lua_tonumber(L, 1)));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int emptyCache(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int EmptyCache(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
pResource->EmptyCache(); pResource->emptyCache();
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int isLogCacheMiss(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int IsLogCacheMiss(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
lua_pushbooleancpp(L, pResource->IsLogCacheMiss()); lua_pushbooleancpp(L, pResource->isLogCacheMiss());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int setLogCacheMiss(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int SetLogCacheMiss(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
pResource->SetLogCacheMiss(lua_tobooleancpp(L, 1)); pResource->setLogCacheMiss(lua_tobooleancpp(L, 1));
return 0; return 0;
} }
// ----------------------------------------------------------------------------- static int dumpLockedResources(lua_State *L) {
Kernel *pKernel = Kernel::getInstance();
static int DumpLockedResources(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
BS_ASSERT(pResource); BS_ASSERT(pResource);
pResource->DumpLockedResources(); pResource->dumpLockedResources();
return 0; return 0;
} }
// -----------------------------------------------------------------------------
static const char *RESOURCE_LIBRARY_NAME = "Resource"; static const char *RESOURCE_LIBRARY_NAME = "Resource";
static const luaL_reg RESOURCE_FUNCTIONS[] = { static const luaL_reg RESOURCE_FUNCTIONS[] = {
{"PrecacheResource", PrecacheResource}, {"PrecacheResource", precacheResource},
{"ForcePrecacheResource", ForcePrecacheResource}, {"ForcePrecacheResource", forcePrecacheResource},
{"GetMaxMemoryUsage", GetMaxMemoryUsage}, {"GetMaxMemoryUsage", getMaxMemoryUsage},
{"SetMaxMemoryUsage", SetMaxMemoryUsage}, {"SetMaxMemoryUsage", setMaxMemoryUsage},
{"EmptyCache", EmptyCache}, {"EmptyCache", emptyCache},
{"IsLogCacheMiss", IsLogCacheMiss}, {"IsLogCacheMiss", isLogCacheMiss},
{"SetLogCacheMiss", SetLogCacheMiss}, {"SetLogCacheMiss", setLogCacheMiss},
{"DumpLockedResources", DumpLockedResources}, {"DumpLockedResources", dumpLockedResources},
{0, 0} {0, 0}
}; };
// ----------------------------------------------------------------------------- static int reloadSlots(lua_State *L) {
PersistenceService::getInstance().reloadSlots();
static int ReloadSlots(lua_State *L) {
PersistenceService::GetInstance().ReloadSlots();
lua_pushnil(L); lua_pushnil(L);
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSlotCount(lua_State *L) {
lua_pushnumber(L, PersistenceService::getInstance().getSlotCount());
static int GetSlotCount(lua_State *L) {
lua_pushnumber(L, PersistenceService::GetInstance().GetSlotCount());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int isSlotOccupied(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::getInstance().isSlotOccupied(static_cast<uint>(luaL_checknumber(L, 1)) - 1));
return 1;
}
static int IsSlotOccupied(lua_State *L) { static int getSavegameDirectory(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::GetInstance().IsSlotOccupied( lua_pushstring(L, PersistenceService::getInstance().getSavegameDirectory().c_str());
return 1;
}
static int isSavegameCompatible(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::getInstance().isSavegameCompatible(
static_cast<uint>(luaL_checknumber(L, 1)) - 1)); static_cast<uint>(luaL_checknumber(L, 1)) - 1));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSavegameDescription(lua_State *L) {
lua_pushstring(L, PersistenceService::getInstance().getSavegameDescription(
static int GetSavegameDirectory(lua_State *L) {
lua_pushstring(L, PersistenceService::GetInstance().GetSavegameDirectory().c_str());
return 1;
}
// -----------------------------------------------------------------------------
static int IsSavegameCompatible(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::GetInstance().IsSavegameCompatible(
static_cast<uint>(luaL_checknumber(L, 1)) - 1));
return 1;
}
// -----------------------------------------------------------------------------
static int GetSavegameDescription(lua_State *L) {
lua_pushstring(L, PersistenceService::GetInstance().GetSavegameDescription(
static_cast<uint>(luaL_checknumber(L, 1)) - 1).c_str()); static_cast<uint>(luaL_checknumber(L, 1)) - 1).c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int getSavegameFilename(lua_State *L) {
lua_pushstring(L, PersistenceService::getInstance().getSavegameFilename(static_cast<uint>(luaL_checknumber(L, 1)) - 1).c_str());
static int GetSavegameFilename(lua_State *L) {
lua_pushstring(L, PersistenceService::GetInstance().GetSavegameFilename(static_cast<uint>(luaL_checknumber(L, 1)) - 1).c_str());
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int loadGame(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::getInstance().loadGame(static_cast<uint>(luaL_checknumber(L, 1)) - 1));
static int LoadGame(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::GetInstance().LoadGame(static_cast<uint>(luaL_checknumber(L, 1)) - 1));
return 1; return 1;
} }
// ----------------------------------------------------------------------------- static int saveGame(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::getInstance().saveGame(static_cast<uint>(luaL_checknumber(L, 1)) - 1, luaL_checkstring(L, 2)));
static int SaveGame(lua_State *L) {
lua_pushbooleancpp(L, PersistenceService::GetInstance().SaveGame(static_cast<uint>(luaL_checknumber(L, 1)) - 1, luaL_checkstring(L, 2)));
return 1; return 1;
} }
// -----------------------------------------------------------------------------
static const char *PERSISTENCE_LIBRARY_NAME = "Persistence"; static const char *PERSISTENCE_LIBRARY_NAME = "Persistence";
static const luaL_reg PERSISTENCE_FUNCTIONS[] = { static const luaL_reg PERSISTENCE_FUNCTIONS[] = {
{"ReloadSlots", ReloadSlots}, {"ReloadSlots", reloadSlots},
{"GetSlotCount", GetSlotCount}, {"GetSlotCount", getSlotCount},
{"IsSlotOccupied", IsSlotOccupied}, {"IsSlotOccupied", isSlotOccupied},
{"GetSavegameDirectory", GetSavegameDirectory}, {"GetSavegameDirectory", getSavegameDirectory},
{"IsSavegameCompatible", IsSavegameCompatible}, {"IsSavegameCompatible", isSavegameCompatible},
{"GetSavegameDescription", GetSavegameDescription}, {"GetSavegameDescription", getSavegameDescription},
{"GetSavegameFilename", GetSavegameFilename}, {"GetSavegameFilename", getSavegameFilename},
{"LoadGame", LoadGame}, {"LoadGame", loadGame},
{"SaveGame", SaveGame}, {"SaveGame", saveGame},
{0, 0} {0, 0}
}; };
// ----------------------------------------------------------------------------- bool Kernel::registerScriptBindings() {
ScriptEngine *pScript = getScript();
bool Kernel::_RegisterScriptBindings() {
ScriptEngine *pScript = GetScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -39,32 +39,31 @@
namespace Sword25 { namespace Sword25 {
// Constants
static const char *BF_LOG_FILENAME = "log.txt"; static const char *BF_LOG_FILENAME = "log.txt";
static const size_t LOG_BUFFERSIZE = 1024 * 16; static const size_t LOG_BUFFERSIZE = 1024 * 16;
// Logging will take place only when it's activated // Logging will take place only when it's activated
#ifdef BS_ACTIVATE_LOGGING #ifdef BS_ACTIVATE_LOGGING
Common::WriteStream *BS_Log::_LogFile = NULL; Common::WriteStream *BS_Log::_logFile = NULL;
bool BS_Log::_LineBegin = true; bool BS_Log::_lineBegin = true;
const char *BS_Log::_Prefix = NULL; const char *BS_Log::_prefix = NULL;
const char *BS_Log::_File = NULL; const char *BS_Log::_file = NULL;
int BS_Log::_Line = 0; int BS_Log::_line = 0;
bool BS_Log::_AutoNewline = false; bool BS_Log::_autoNewline = false;
bool BS_Log::_CreateLog() { bool BS_Log::createLog() {
// Open the log file // Open the log file
Common::FSNode dataDir(ConfMan.get("path")); Common::FSNode dataDir(ConfMan.get("path"));
Common::FSNode file = dataDir.getChild(BF_LOG_FILENAME); Common::FSNode file = dataDir.getChild(BF_LOG_FILENAME);
// Open the file for saving // Open the file for saving
_LogFile = file.createWriteStream(); _logFile = file.createWriteStream();
if (_LogFile) { if (_logFile) {
// Add a title into the log file // Add a title into the log file
Log("Broken Sword 2.5 Engine - Build: %s - %s - VersionID: %s\n", __DATE__, __TIME__, gScummVMFullVersion); log("Broken Sword 2.5 Engine - Build: %s - %s - VersionID: %s\n", __DATE__, __TIME__, gScummVMFullVersion);
Log("-----------------------------------------------------------------------------------------------------\n"); log("-----------------------------------------------------------------------------------------------------\n");
return true; return true;
} }
@ -73,141 +72,142 @@ bool BS_Log::_CreateLog() {
return false; return false;
} }
void BS_Log::_CloseLog() { void BS_Log::closeLog() {
delete _LogFile; delete _logFile;
_LogFile = NULL; _logFile = NULL;
} }
void BS_Log::Log(const char *Format, ...) { void BS_Log::log(const char *format, ...) {
char Message[LOG_BUFFERSIZE]; char message[LOG_BUFFERSIZE];
// Create the message // Create the message
va_list ArgList; va_list argList;
va_start(ArgList, Format); va_start(argList, format);
vsnprintf(Message, sizeof(Message), Format, ArgList); vsnprintf(message, sizeof(message), format, argList);
// Log the message // Log the message
_WriteLog(Message); writeLog(message);
_FlushLog(); flushLog();
} }
void BS_Log::LogPrefix(const char *Prefix, const char *Format, ...) { void BS_Log::logPrefix(const char *prefix, const char *format, ...) {
char Message[LOG_BUFFERSIZE]; char message[LOG_BUFFERSIZE];
char ExtFormat[LOG_BUFFERSIZE]; char extFormat[LOG_BUFFERSIZE];
// If the issue has ceased at the beginning of a new line, the new issue to begin with the prefix // If the issue has ceased at the beginning of a new line, the new issue to begin with the prefix
ExtFormat[0] = 0; extFormat[0] = 0;
if (_LineBegin) { if (_lineBegin) {
snprintf(ExtFormat, sizeof(ExtFormat), "%s: ", Prefix); snprintf(extFormat, sizeof(extFormat), "%s: ", prefix);
_LineBegin = false; _lineBegin = false;
} }
// Format String pass line by line and each line with the initial prefix // Format String pass line by line and each line with the initial prefix
for (;;) { for (;;) {
const char *NextLine = strstr(Format, "\n"); const char *nextLine = strstr(format, "\n");
if (!NextLine || *(NextLine + strlen("\n")) == 0) { if (!nextLine || *(nextLine + strlen("\n")) == 0) {
Common::strlcat(ExtFormat, Format, sizeof(ExtFormat)); Common::strlcat(extFormat, format, sizeof(extFormat));
if (NextLine) _LineBegin = true; if (nextLine)
_lineBegin = true;
break; break;
} else { } else {
strncat(ExtFormat, Format, (NextLine - Format) + strlen("\n")); strncat(extFormat, format, (nextLine - format) + strlen("\n"));
Common::strlcat(ExtFormat, Prefix, sizeof(ExtFormat)); Common::strlcat(extFormat, prefix, sizeof(extFormat));
Common::strlcat(ExtFormat, ": ", sizeof(ExtFormat)); Common::strlcat(extFormat, ": ", sizeof(extFormat));
} }
Format = NextLine + strlen("\n"); format = nextLine + strlen("\n");
} }
// Create message // Create message
va_list ArgList; va_list argList;
va_start(ArgList, Format); va_start(argList, format);
vsnprintf(Message, sizeof(Message), ExtFormat, ArgList); vsnprintf(message, sizeof(message), extFormat, argList);
// Log the message // Log the message
_WriteLog(Message); writeLog(message);
_FlushLog(); flushLog();
} }
void BS_Log::LogDecorated(const char *Format, ...) { void BS_Log::logDecorated(const char *format, ...) {
// Nachricht erzeugen // Nachricht erzeugen
char Message[LOG_BUFFERSIZE]; char message[LOG_BUFFERSIZE];
va_list ArgList; va_list argList;
va_start(ArgList, Format); va_start(argList, format);
vsnprintf(Message, sizeof(Message), Format, ArgList); vsnprintf(message, sizeof(message), format, argList);
// Zweiten Prefix erzeugen, falls gewünscht // Zweiten prefix erzeugen, falls gewünscht
char SecondaryPrefix[1024]; char secondaryPrefix[1024];
if (_File && _Line) if (_file && _line)
snprintf(SecondaryPrefix, sizeof(SecondaryPrefix), "(file: %s, line: %d) - ", _File, _Line); snprintf(secondaryPrefix, sizeof(secondaryPrefix), "(file: %s, line: %d) - ", _file, _line);
// Nachricht zeilenweise ausgeben und an jeden Zeilenanfang das Präfix setzen // Nachricht zeilenweise ausgeben und an jeden Zeilenanfang das Präfix setzen
char *MessageWalker = Message; char *messageWalker = message;
for (;;) { for (;;) {
char *NextLine = strstr(MessageWalker, "\n"); char *nextLine = strstr(messageWalker, "\n");
if (NextLine) { if (nextLine) {
*NextLine = 0; *nextLine = 0;
if (_LineBegin) { if (_lineBegin) {
_WriteLog(_Prefix); writeLog(_prefix);
if (_File && _Line) if (_file && _line)
_WriteLog(SecondaryPrefix); writeLog(secondaryPrefix);
} }
_WriteLog(MessageWalker); writeLog(messageWalker);
_WriteLog("\n"); writeLog("\n");
MessageWalker = NextLine + sizeof("\n") - 1; messageWalker = nextLine + sizeof("\n") - 1;
_LineBegin = true; _lineBegin = true;
} else { } else {
if (_LineBegin) { if (_lineBegin) {
_WriteLog(_Prefix); writeLog(_prefix);
if (_File && _Line) if (_file && _line)
_WriteLog(SecondaryPrefix); writeLog(secondaryPrefix);
} }
_WriteLog(MessageWalker); writeLog(messageWalker);
_LineBegin = false; _lineBegin = false;
break; break;
} }
} }
// Falls gewünscht, wird ans Ende der Nachricht automatisch ein Newline angehängt. // Falls gewünscht, wird ans Ende der Nachricht automatisch ein Newline angehängt.
if (_AutoNewline) { if (_autoNewline) {
_WriteLog("\n"); writeLog("\n");
_LineBegin = true; _lineBegin = true;
} }
// Pseudoparameter zurücksetzen // Pseudoparameter zurücksetzen
_Prefix = NULL; _prefix = NULL;
_File = 0; _file = 0;
_Line = 0; _line = 0;
_AutoNewline = false; _autoNewline = false;
_FlushLog(); flushLog();
} }
int BS_Log::_WriteLog(const char *Message) { int BS_Log::writeLog(const char *message) {
if (!_LogFile && !_CreateLog()) if (!_logFile && !createLog())
return false; return false;
debugN(0, "%s", Message); debugN(0, "%s", message);
_LogFile->writeString(Message); _logFile->writeString(message);
return true; return true;
} }
void BS_Log::_FlushLog() { void BS_Log::flushLog() {
if (_LogFile) if (_logFile)
_LogFile->flush(); _logFile->flush();
} }
void (*BS_LogPtr)(const char *, ...) = BS_Log::Log; void (*BS_LogPtr)(const char *, ...) = BS_Log::log;
void BS_Log_C(const char *Message) { void BS_Log_C(const char *message) {
BS_LogPtr(Message); BS_LogPtr(message);
} }
#else #else
void BS_Log_C(const char *Message) {}; void BS_Log_C(const char *message) {};
#endif #endif

View file

@ -46,50 +46,50 @@ namespace Sword25 {
#ifdef BS_ACTIVATE_LOGGING #ifdef BS_ACTIVATE_LOGGING
// Logging-Makros // Logging-Makros
#define BS_LOG BS_Log::SetPrefix(BS_LOG_PREFIX ": "), BS_Log::LogDecorated #define BS_LOG BS_Log::setPrefix(BS_LOG_PREFIX ": "), BS_Log::logDecorated
#define BS_LOGLN BS_Log::SetPrefix(BS_LOG_PREFIX ": "), BS_Log::SetAutoNewline(true), BS_Log::LogDecorated #define BS_LOGLN BS_Log::setPrefix(BS_LOG_PREFIX ": "), BS_Log::setAutoNewline(true), BS_Log::logDecorated
#define BS_LOG_WARNING BS_Log::SetPrefix(BS_LOG_PREFIX ": WARNING - "), BS_Log::LogDecorated #define BS_LOG_WARNING BS_Log::setPrefix(BS_LOG_PREFIX ": WARNING - "), BS_Log::logDecorated
#define BS_LOG_WARNINGLN BS_Log::SetPrefix(BS_LOG_PREFIX ": WARNING - "), BS_Log::SetAutoNewline(true), BS_Log::LogDecorated #define BS_LOG_WARNINGLN BS_Log::setPrefix(BS_LOG_PREFIX ": WARNING - "), BS_Log::setAutoNewline(true), BS_Log::logDecorated
#define BS_LOG_ERROR BS_Log::SetPrefix(BS_LOG_PREFIX ": ERROR - "), BS_Log::LogDecorated #define BS_LOG_ERROR BS_Log::setPrefix(BS_LOG_PREFIX ": ERROR - "), BS_Log::logDecorated
#define BS_LOG_ERRORLN BS_Log::SetPrefix(BS_LOG_PREFIX ": ERROR - "), BS_Log::SetAutoNewline(true), BS_Log::LogDecorated #define BS_LOG_ERRORLN BS_Log::setPrefix(BS_LOG_PREFIX ": ERROR - "), BS_Log::setAutoNewline(true), BS_Log::logDecorated
#define BS_LOG_EXTERROR BS_Log::SetPrefix(BS_LOG_PREFIX ": ERROR "), BS_Log::SetFile(__FILE__), BS_Log::SetLine(__LINE__), BS_Log::LogDecorated #define BS_LOG_EXTERROR BS_Log::setPrefix(BS_LOG_PREFIX ": ERROR "), BS_Log::setFile(__FILE__), BS_Log::setLine(__LINE__), BS_Log::logDecorated
#define BS_LOG_EXTERRORLN BS_Log::SetPrefix(BS_LOG_PREFIX ": ERROR "), BS_Log::SetFile(__FILE__), BS_Log::SetLine(__LINE__), BS_Log::SetAutoNewline(true), BS_Log::LogDecorated #define BS_LOG_EXTERRORLN BS_Log::setPrefix(BS_LOG_PREFIX ": ERROR "), BS_Log::setFile(__FILE__), BS_Log::setLine(__LINE__), BS_Log::setAutoNewline(true), BS_Log::logDecorated
// Die Version der Logging-Klasse mit aktiviertem Logging // Die Version der Logging-Klasse mit aktiviertem Logging
class BS_Log { class BS_Log {
public: public:
static void Clear(); static void clear();
static void Log(const char *Format, ...); static void log(const char *format, ...);
static void LogPrefix(const char *Prefix, const char *Format, ...); static void logPrefix(const char *prefix, const char *format, ...);
static void LogDecorated(const char *Format, ...); static void logDecorated(const char *format, ...);
static void SetPrefix(const char *Prefix) { static void setPrefix(const char *prefix) {
_Prefix = Prefix; _prefix = prefix;
} }
static void SetFile(const char *File) { static void setFile(const char *file) {
_File = File; _file = file;
} }
static void SetLine(int Line) { static void setLine(int line) {
_Line = Line; _line = line;
} }
static void SetAutoNewline(bool AutoNewline) { static void setAutoNewline(bool autoNewline) {
_AutoNewline = AutoNewline; _autoNewline = autoNewline;
} }
static void _CloseLog(); static void closeLog();
private: private:
static Common::WriteStream *_LogFile; static Common::WriteStream *_logFile;
static bool _LineBegin; static bool _lineBegin;
static const char *_Prefix; static const char *_prefix;
static const char *_File; static const char *_file;
static int _Line; static int _line;
static bool _AutoNewline; static bool _autoNewline;
static bool _CreateLog(); static bool createLog();
static int _WriteLog(const char *Message); static int writeLog(const char *message);
static void _FlushLog(); static void flushLog();
}; };
// Auxiliary function that allows to log C functions (needed for Lua). // Auxiliary function that allows to log C functions (needed for Lua).
@ -112,17 +112,17 @@ private:
class BS_Log { class BS_Log {
public: public:
// This version implements all the various methods as empty stubs // This version implements all the various methods as empty stubs
static void Log(const char *Text, ...) {}; static void log(const char *text, ...) {};
static void LogPrefix(const char *Prefix, const char *Format, ...) {}; static void logPrefix(const char *prefix, const char *format, ...) {};
static void LogDecorated(const char *Format, ...) {}; static void logDecorated(const char *format, ...) {};
static void SetPrefix(const char *Prefix) {}; static void setPrefix(const char *prefix) {};
static void SetFile(const char *File) {}; static void setFile(const char *file) {};
static void SetLine(int Line) {}; static void setLine(int line) {};
static void SetAutoNewline(bool AutoNewline) {}; static void setAutoNewline(bool autoNewline) {};
typedef void (*LOG_LISTENER_CALLBACK)(const char *); typedef void (*LOG_LISTENER_CALLBACK)(const char *);
static void RegisterLogListener(LOG_LISTENER_CALLBACK Callback) {}; static void registerLogListener(LOG_LISTENER_CALLBACK callback) {};
}; };
#define BS_Log_C error #define BS_Log_C error

View file

@ -34,97 +34,67 @@
#define BS_LOG_PREFIX "OUTPUTPERSISTENCEBLOCK" #define BS_LOG_PREFIX "OUTPUTPERSISTENCEBLOCK"
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/outputpersistenceblock.h" #include "sword25/kernel/outputpersistenceblock.h"
// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------
namespace { namespace {
const uint INITIAL_BUFFER_SIZE = 1024 * 64; const uint INITIAL_BUFFER_SIZE = 1024 * 64;
} }
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Construction / Destruction
// -----------------------------------------------------------------------------
OutputPersistenceBlock::OutputPersistenceBlock() { OutputPersistenceBlock::OutputPersistenceBlock() {
m_Data.reserve(INITIAL_BUFFER_SIZE); _data.reserve(INITIAL_BUFFER_SIZE);
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(signed int value) {
// Writing writeMarker(SINT_MARKER);
// ----------------------------------------------------------------------------- value = convertEndianessFromSystemToStorage(value);
rawWrite(&value, sizeof(value));
void OutputPersistenceBlock::write(signed int Value) {
WriteMarker(SINT_MARKER);
Value = ConvertEndianessFromSystemToStorage(Value);
RawWrite(&Value, sizeof(Value));
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(uint value) {
writeMarker(UINT_MARKER);
void OutputPersistenceBlock::write(uint Value) { value = convertEndianessFromSystemToStorage(value);
WriteMarker(UINT_MARKER); rawWrite(&value, sizeof(value));
Value = ConvertEndianessFromSystemToStorage(Value);
RawWrite(&Value, sizeof(Value));
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(float value) {
writeMarker(FLOAT_MARKER);
void OutputPersistenceBlock::write(float Value) { value = convertEndianessFromSystemToStorage(value);
WriteMarker(FLOAT_MARKER); rawWrite(&value, sizeof(value));
Value = ConvertEndianessFromSystemToStorage(Value);
RawWrite(&Value, sizeof(Value));
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(bool value) {
writeMarker(BOOL_MARKER);
void OutputPersistenceBlock::write(bool Value) { uint uintBool = value ? 1 : 0;
WriteMarker(BOOL_MARKER); uintBool = convertEndianessFromSystemToStorage(uintBool);
rawWrite(&uintBool, sizeof(uintBool));
uint UIntBool = Value ? 1 : 0;
UIntBool = ConvertEndianessFromSystemToStorage(UIntBool);
RawWrite(&UIntBool, sizeof(UIntBool));
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(const Common::String &string) {
writeMarker(STRING_MARKER);
void OutputPersistenceBlock::write(const Common::String &String) { write(string.size());
WriteMarker(STRING_MARKER); rawWrite(string.c_str(), string.size());
write(String.size());
RawWrite(String.c_str(), String.size());
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::write(const void *bufferPtr, size_t size) {
writeMarker(BLOCK_MARKER);
void OutputPersistenceBlock::write(const void *BufferPtr, size_t Size) { write((int)size);
WriteMarker(BLOCK_MARKER); rawWrite(bufferPtr, size);
write((int) Size);
RawWrite(BufferPtr, Size);
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::writeMarker(byte marker) {
_data.push_back(marker);
void OutputPersistenceBlock::WriteMarker(byte Marker) {
m_Data.push_back(Marker);
} }
// ----------------------------------------------------------------------------- void OutputPersistenceBlock::rawWrite(const void *dataPtr, size_t size) {
if (size > 0) {
void OutputPersistenceBlock::RawWrite(const void *DataPtr, size_t Size) { uint oldSize = _data.size();
if (Size > 0) { _data.resize(oldSize + size);
uint OldSize = m_Data.size(); memcpy(&_data[oldSize], dataPtr, size);
m_Data.resize(OldSize + Size);
memcpy(&m_Data[OldSize], DataPtr, Size);
} }
} }

View file

@ -35,42 +35,34 @@
#ifndef SWORD25_OUTPUTPERSISTENCEBLOCK_H #ifndef SWORD25_OUTPUTPERSISTENCEBLOCK_H
#define SWORD25_OUTPUTPERSISTENCEBLOCK_H #define SWORD25_OUTPUTPERSISTENCEBLOCK_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/persistenceblock.h" #include "sword25/kernel/persistenceblock.h"
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Class declaration
// -----------------------------------------------------------------------------
class OutputPersistenceBlock : public PersistenceBlock { class OutputPersistenceBlock : public PersistenceBlock {
public: public:
OutputPersistenceBlock(); OutputPersistenceBlock();
void write(signed int Value); void write(signed int value);
void write(uint Value); void write(uint value);
void write(float Value); void write(float value);
void write(bool Value); void write(bool value);
void write(const Common::String &String); void write(const Common::String &string);
void write(const void *BufferPtr, size_t Size); void write(const void *bufferPtr, size_t size);
const void *GetData() const { const void *getData() const {
return &m_Data[0]; return &_data[0];
} }
uint GetDataSize() const { uint getDataSize() const {
return m_Data.size(); return _data.size();
} }
private: private:
void WriteMarker(byte Marker); void writeMarker(byte marker);
void RawWrite(const void *DataPtr, size_t Size); void rawWrite(const void *dataPtr, size_t size);
Common::Array<byte> m_Data; Common::Array<byte> _data;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -35,34 +35,26 @@
#ifndef SWORD25_PERSISTENCEBLOCK_H #ifndef SWORD25_PERSISTENCEBLOCK_H
#define SWORD25_PERSISTENCEBLOCK_H #define SWORD25_PERSISTENCEBLOCK_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Class definition
// -----------------------------------------------------------------------------
class PersistenceBlock { class PersistenceBlock {
public: public:
static uint GetSInt32Size() { static uint getSInt32Size() {
return sizeof(signed int) + sizeof(byte); return sizeof(signed int) + sizeof(byte);
} }
static uint GetUInt32Size() { static uint getUInt32Size() {
return sizeof(uint) + sizeof(byte); return sizeof(uint) + sizeof(byte);
} }
static uint GetFloat32Size() { static uint getFloat32Size() {
return sizeof(float) + sizeof(byte); return sizeof(float) + sizeof(byte);
} }
static uint GetBoolSize() { static uint getBoolSize() {
return sizeof(byte) + sizeof(byte); return sizeof(byte) + sizeof(byte);
} }
static uint GetStringSize(const Common::String &String) { static uint getStringSize(const Common::String &string) {
return static_cast<uint>(sizeof(uint) + String.size() + sizeof(byte)); return static_cast<uint>(sizeof(uint) + string.size() + sizeof(byte));
} }
protected: protected:
@ -84,43 +76,41 @@ protected:
// //
template<typename T> template<typename T>
static T ConvertEndianessFromSystemToStorage(T Value) { static T convertEndianessFromSystemToStorage(T value) {
if (IsBigEndian()) ReverseByteOrder(&Value); if (isBigEndian())
return Value; reverseByteOrder(&value);
return value;
} }
template<typename T> template<typename T>
static T ConvertEndianessFromStorageToSystem(T Value) { static T convertEndianessFromStorageToSystem(T value) {
if (IsBigEndian()) ReverseByteOrder(&Value); if (isBigEndian())
return Value; reverseByteOrder(&value);
return value;
} }
private: private:
static bool IsBigEndian() { static bool isBigEndian() {
uint Dummy = 1; uint dummy = 1;
byte *DummyPtr = reinterpret_cast<byte *>(&Dummy); byte *dummyPtr = reinterpret_cast<byte *>(&dummy);
return DummyPtr[0] == 0; return dummyPtr[0] == 0;
} }
template<typename T> template<typename T>
static void Swap(T &One, T &Two) { static void swap(T &one, T &two) {
T Temp = One; T temp = one;
One = Two; one = two;
Two = Temp; two = temp;
} }
static void ReverseByteOrder(void *Ptr) { static void reverseByteOrder(void *ptr) {
// Reverses the byte order of the 32-bit word pointed to by Ptr // Reverses the byte order of the 32-bit word pointed to by Ptr
byte *CharPtr = static_cast<byte *>(Ptr); byte *charPtr = static_cast<byte *>(ptr);
Swap(CharPtr[0], CharPtr[3]); swap(charPtr[0], charPtr[3]);
Swap(CharPtr[1], CharPtr[2]); swap(charPtr[1], charPtr[2]);
} }
}; };
// -----------------------------------------------------------------------------
// Compile time asserts
// -----------------------------------------------------------------------------
#define CTASSERT(ex) typedef char ctassert_type[(ex) ? 1 : -1] #define CTASSERT(ex) typedef char ctassert_type[(ex) ? 1 : -1]
CTASSERT(sizeof(byte) == 1); CTASSERT(sizeof(byte) == 1);
CTASSERT(sizeof(signed int) == 4); CTASSERT(sizeof(signed int) == 4);

View file

@ -32,10 +32,6 @@
* *
*/ */
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/fs.h" #include "common/fs.h"
#include "common/savefile.h" #include "common/savefile.h"
#include "sword25/kernel/kernel.h" #include "sword25/kernel/kernel.h"
@ -52,10 +48,6 @@
#define BS_LOG_PREFIX "PERSISTENCESERVICE" #define BS_LOG_PREFIX "PERSISTENCESERVICE"
// -----------------------------------------------------------------------------
// Constants and utility functions
// -----------------------------------------------------------------------------
namespace Sword25 { namespace Sword25 {
const char *SAVEGAME_EXTENSION = ".b25s"; const char *SAVEGAME_EXTENSION = ".b25s";
const char *SAVEGAME_DIRECTORY = "saves"; const char *SAVEGAME_DIRECTORY = "saves";
@ -64,25 +56,19 @@ const uint SLOT_COUNT = 18;
const uint FILE_COPY_BUFFER_SIZE = 1024 * 10; const uint FILE_COPY_BUFFER_SIZE = 1024 * 10;
const char *VERSIONID = "SCUMMVM1"; const char *VERSIONID = "SCUMMVM1";
// ------------------------------------------------------------------------- Common::String generateSavegameFilename(uint slotID) {
Common::String GenerateSavegameFilename(uint slotID) {
char buffer[10]; char buffer[10];
sprintf(buffer, "%d%s", slotID, SAVEGAME_EXTENSION); sprintf(buffer, "%d%s", slotID, SAVEGAME_EXTENSION);
return Common::String(buffer); return Common::String(buffer);
} }
// ------------------------------------------------------------------------- Common::String generateSavegamePath(uint slotID) {
Common::FSNode folder(PersistenceService::getSavegameDirectory());
Common::String GenerateSavegamePath(uint SlotID) { return folder.getChild(generateSavegameFilename(slotID)).getPath();
Common::FSNode folder(PersistenceService::GetSavegameDirectory());
return folder.getChild(GenerateSavegameFilename(SlotID)).getPath();
} }
// ------------------------------------------------------------------------- Common::String formatTimestamp(TimeDate time) {
Common::String FormatTimestamp(TimeDate Time) {
// In the original BS2.5 engine, this used a local object to show the date/time as as a string. // In the original BS2.5 engine, this used a local object to show the date/time as as a string.
// For now in ScummVM it's being hardcoded to 'dd-MON-yyyy hh:mm:ss' // For now in ScummVM it's being hardcoded to 'dd-MON-yyyy hh:mm:ss'
Common::String monthList[12] = { Common::String monthList[12] = {
@ -90,157 +76,132 @@ Common::String FormatTimestamp(TimeDate Time) {
}; };
char buffer[100]; char buffer[100];
snprintf(buffer, 100, "%.2d-%s-%.4d %.2d:%.2d:%.2d", snprintf(buffer, 100, "%.2d-%s-%.4d %.2d:%.2d:%.2d",
Time.tm_mday, monthList[Time.tm_mon].c_str(), 1900 + Time.tm_year, time.tm_mday, monthList[time.tm_mon].c_str(), 1900 + time.tm_year,
Time.tm_hour, Time.tm_min, Time.tm_sec time.tm_hour, time.tm_min, time.tm_sec
); );
return Common::String(buffer); return Common::String(buffer);
} }
// ------------------------------------------------------------------------- Common::String loadString(Common::InSaveFile *in, uint maxSize = 999) {
Common::String result;
Common::String LoadString(Common::InSaveFile *In, uint MaxSize = 999) { char ch = (char)in->readByte();
Common::String Result;
char ch = (char)In->readByte();
while ((ch != '\0') && (ch != ' ')) { while ((ch != '\0') && (ch != ' ')) {
Result += ch; result += ch;
if (Result.size() >= MaxSize) break; if (result.size() >= maxSize)
ch = (char)In->readByte(); break;
ch = (char)in->readByte();
} }
return Result; return result;
} }
} }
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Private Implementation
// -----------------------------------------------------------------------------
struct SavegameInformation { struct SavegameInformation {
bool IsOccupied; bool isOccupied;
bool IsCompatible; bool isCompatible;
Common::String Description; Common::String description;
Common::String Filename; Common::String filename;
uint GamedataLength; uint gamedataLength;
uint GamedataOffset; uint gamedataOffset;
uint GamedataUncompressedLength; uint gamedataUncompressedLength;
SavegameInformation() { SavegameInformation() {
Clear(); clear();
} }
void Clear() { void clear() {
IsOccupied = false; isOccupied = false;
IsCompatible = false; isCompatible = false;
Description = ""; description = "";
Filename = ""; filename = "";
GamedataLength = 0; gamedataLength = 0;
GamedataOffset = 0; gamedataOffset = 0;
GamedataUncompressedLength = 0; gamedataUncompressedLength = 0;
} }
}; };
struct PersistenceService::Impl { struct PersistenceService::Impl {
SavegameInformation m_SavegameInformations[SLOT_COUNT]; SavegameInformation _savegameInformations[SLOT_COUNT];
// -----------------------------------------------------------------------------
Impl() { Impl() {
ReloadSlots(); reloadSlots();
} }
// ----------------------------------------------------------------------------- void reloadSlots() {
void ReloadSlots() {
// Über alle Spielstanddateien iterieren und deren Infos einlesen. // Über alle Spielstanddateien iterieren und deren Infos einlesen.
for (uint i = 0; i < SLOT_COUNT; ++i) { for (uint i = 0; i < SLOT_COUNT; ++i) {
ReadSlotSavegameInformation(i); readSlotSavegameInformation(i);
} }
} }
void ReadSlotSavegameInformation(uint SlotID) { void readSlotSavegameInformation(uint slotID) {
// Aktuelle Slotinformationen in den Ausgangszustand versetzen, er wird im Folgenden neu gefüllt. // Aktuelle Slotinformationen in den Ausgangszustand versetzen, er wird im Folgenden neu gefüllt.
SavegameInformation &CurSavegameInfo = m_SavegameInformations[SlotID]; SavegameInformation &curSavegameInfo = _savegameInformations[slotID];
CurSavegameInfo.Clear(); curSavegameInfo.clear();
// Den Dateinamen für den Spielstand des Slots generieren. // Den Dateinamen für den Spielstand des Slots generieren.
Common::String Filename = GenerateSavegameFilename(SlotID); Common::String filename = generateSavegameFilename(slotID);
// Try to open the savegame for loading // Try to open the savegame for loading
Common::SaveFileManager *sfm = g_system->getSavefileManager(); Common::SaveFileManager *sfm = g_system->getSavefileManager();
Common::InSaveFile *File = sfm->openForLoading(Filename); Common::InSaveFile *file = sfm->openForLoading(filename);
if (File) { if (file) {
// Read in the header // Read in the header
Common::String StoredMarker = LoadString(File); Common::String storedMarker = loadString(file);
Common::String StoredVersionID = LoadString(File); Common::String storedVersionID = loadString(file);
Common::String gameDataLength = LoadString(File); Common::String gameDataLength = loadString(file);
CurSavegameInfo.GamedataLength = atoi(gameDataLength.c_str()); curSavegameInfo.gamedataLength = atoi(gameDataLength.c_str());
Common::String gamedataUncompressedLength = LoadString(File); Common::String gamedataUncompressedLength = loadString(file);
CurSavegameInfo.GamedataUncompressedLength = atoi(gamedataUncompressedLength.c_str()); curSavegameInfo.gamedataUncompressedLength = atoi(gamedataUncompressedLength.c_str());
// If the header can be read in and is detected to be valid, we will have a valid file // If the header can be read in and is detected to be valid, we will have a valid file
if (StoredMarker == FILE_MARKER) { if (storedMarker == FILE_MARKER) {
// Der Slot wird als belegt markiert. // Der Slot wird als belegt markiert.
CurSavegameInfo.IsOccupied = true; curSavegameInfo.isOccupied = true;
// Speichern, ob der Spielstand kompatibel mit der aktuellen Engine-Version ist. // Speichern, ob der Spielstand kompatibel mit der aktuellen Engine-Version ist.
CurSavegameInfo.IsCompatible = (StoredVersionID == Common::String(VERSIONID)); curSavegameInfo.isCompatible = (storedVersionID == Common::String(VERSIONID));
// Dateinamen des Spielstandes speichern. // Dateinamen des Spielstandes speichern.
CurSavegameInfo.Filename = GenerateSavegameFilename(SlotID); curSavegameInfo.filename = generateSavegameFilename(slotID);
// Die Beschreibung des Spielstandes besteht aus einer textuellen Darstellung des Änderungsdatums der Spielstanddatei. // Die Beschreibung des Spielstandes besteht aus einer textuellen Darstellung des Änderungsdatums der Spielstanddatei.
CurSavegameInfo.Description = FormatTimestamp(FileSystemUtil::GetInstance().GetFileTime(Filename)); curSavegameInfo.description = formatTimestamp(FileSystemUtil::getInstance().getFileTime(filename));
// Den Offset zu den gespeicherten Spieldaten innerhalb der Datei speichern. // Den Offset zu den gespeicherten Spieldaten innerhalb der Datei speichern.
// Dieses entspricht der aktuellen Position, da nach der letzten Headerinformation noch ein Leerzeichen als trenner folgt. // Dieses entspricht der aktuellen Position, da nach der letzten Headerinformation noch ein Leerzeichen als trenner folgt.
CurSavegameInfo.GamedataOffset = static_cast<uint>(File->pos()); curSavegameInfo.gamedataOffset = static_cast<uint>(file->pos());
} }
delete File; delete file;
} }
} }
}; };
// ----------------------------------------------------------------------------- PersistenceService &PersistenceService::getInstance() {
// Construction / Destruction static PersistenceService instance;
// ----------------------------------------------------------------------------- return instance;
PersistenceService &PersistenceService::GetInstance() {
static PersistenceService Instance;
return Instance;
} }
// ----------------------------------------------------------------------------- PersistenceService::PersistenceService() : _impl(new Impl) {
PersistenceService::PersistenceService() : m_impl(new Impl) {
} }
// -----------------------------------------------------------------------------
PersistenceService::~PersistenceService() { PersistenceService::~PersistenceService() {
delete m_impl; delete _impl;
} }
// ----------------------------------------------------------------------------- void PersistenceService::reloadSlots() {
// Implementation _impl->reloadSlots();
// -----------------------------------------------------------------------------
void PersistenceService::ReloadSlots() {
m_impl->ReloadSlots();
} }
// ----------------------------------------------------------------------------- uint PersistenceService::getSlotCount() {
uint PersistenceService::GetSlotCount() {
return SLOT_COUNT; return SLOT_COUNT;
} }
// ----------------------------------------------------------------------------- Common::String PersistenceService::getSavegameDirectory() {
Common::FSNode node(FileSystemUtil::getInstance().getUserdataDirectory());
Common::String PersistenceService::GetSavegameDirectory() {
Common::FSNode node(FileSystemUtil::GetInstance().GetUserdataDirectory());
Common::FSNode childNode = node.getChild(SAVEGAME_DIRECTORY); Common::FSNode childNode = node.getChild(SAVEGAME_DIRECTORY);
// Try and return the path using the savegame subfolder. But if doesn't exist, fall back on the data directory // Try and return the path using the savegame subfolder. But if doesn't exist, fall back on the data directory
@ -250,13 +211,11 @@ Common::String PersistenceService::GetSavegameDirectory() {
return node.getPath(); return node.getPath();
} }
// -----------------------------------------------------------------------------
namespace { namespace {
bool CheckSlotID(uint SlotID) { bool checkslotID(uint slotID) {
// Überprüfen, ob die Slot-ID zulässig ist. // Überprüfen, ob die Slot-ID zulässig ist.
if (SlotID >= SLOT_COUNT) { if (slotID >= SLOT_COUNT) {
BS_LOG_ERRORLN("Tried to access an invalid slot (%d). Only slot ids from 0 to %d are allowed.", SlotID, SLOT_COUNT - 1); BS_LOG_ERRORLN("Tried to access an invalid slot (%d). Only slot ids from 0 to %d are allowed.", slotID, SLOT_COUNT - 1);
return false; return false;
} else { } else {
return true; return true;
@ -264,142 +223,134 @@ bool CheckSlotID(uint SlotID) {
} }
} }
// ----------------------------------------------------------------------------- bool PersistenceService::isSlotOccupied(uint slotID) {
if (!checkslotID(slotID))
bool PersistenceService::IsSlotOccupied(uint SlotID) { return false;
if (!CheckSlotID(SlotID)) return false; return _impl->_savegameInformations[slotID].isOccupied;
return m_impl->m_SavegameInformations[SlotID].IsOccupied;
} }
// ----------------------------------------------------------------------------- bool PersistenceService::isSavegameCompatible(uint slotID) {
if (!checkslotID(slotID))
bool PersistenceService::IsSavegameCompatible(uint SlotID) { return false;
if (!CheckSlotID(SlotID)) return false; return _impl->_savegameInformations[slotID].isCompatible;
return m_impl->m_SavegameInformations[SlotID].IsCompatible;
} }
// ----------------------------------------------------------------------------- Common::String &PersistenceService::getSavegameDescription(uint slotID) {
static Common::String emptyString;
Common::String &PersistenceService::GetSavegameDescription(uint SlotID) { if (!checkslotID(slotID))
static Common::String EmptyString; return emptyString;
if (!CheckSlotID(SlotID)) return EmptyString; return _impl->_savegameInformations[slotID].description;
return m_impl->m_SavegameInformations[SlotID].Description;
} }
// ----------------------------------------------------------------------------- Common::String &PersistenceService::getSavegameFilename(uint slotID) {
static Common::String emptyString;
Common::String &PersistenceService::GetSavegameFilename(uint SlotID) { if (!checkslotID(slotID))
static Common::String EmptyString; return emptyString;
if (!CheckSlotID(SlotID)) return EmptyString; return _impl->_savegameInformations[slotID].filename;
return m_impl->m_SavegameInformations[SlotID].Filename;
} }
// ----------------------------------------------------------------------------- bool PersistenceService::saveGame(uint slotID, const Common::String &screenshotFilename) {
bool PersistenceService::SaveGame(uint SlotID, const Common::String &ScreenshotFilename) {
// Überprüfen, ob die Slot-ID zulässig ist. // Überprüfen, ob die Slot-ID zulässig ist.
if (SlotID >= SLOT_COUNT) { if (slotID >= SLOT_COUNT) {
BS_LOG_ERRORLN("Tried to save to an invalid slot (%d). Only slot ids form 0 to %d are allowed.", SlotID, SLOT_COUNT - 1); BS_LOG_ERRORLN("Tried to save to an invalid slot (%d). Only slot ids form 0 to %d are allowed.", slotID, SLOT_COUNT - 1);
return false; return false;
} }
// Dateinamen erzeugen. // Dateinamen erzeugen.
Common::String Filename = GenerateSavegameFilename(SlotID); Common::String filename = generateSavegameFilename(slotID);
// Sicherstellen, dass das Verzeichnis für die Spielstanddateien existiert. // Sicherstellen, dass das Verzeichnis für die Spielstanddateien existiert.
FileSystemUtil::GetInstance().CreateDirectory(GetSavegameDirectory()); FileSystemUtil::getInstance().createDirectory(getSavegameDirectory());
// Spielstanddatei öffnen und die Headerdaten schreiben. // Spielstanddatei öffnen und die Headerdaten schreiben.
Common::SaveFileManager *sfm = g_system->getSavefileManager(); Common::SaveFileManager *sfm = g_system->getSavefileManager();
Common::OutSaveFile *File = sfm->openForSaving(Filename); Common::OutSaveFile *file = sfm->openForSaving(filename);
File->writeString(FILE_MARKER); file->writeString(FILE_MARKER);
File->writeByte(' '); file->writeByte(' ');
File->writeString(VERSIONID); file->writeString(VERSIONID);
File->writeByte(' '); file->writeByte(' ');
if (File->err()) { if (file->err()) {
error("Unable to write header data to savegame file \"%s\".", Filename.c_str()); error("Unable to write header data to savegame file \"%s\".", filename.c_str());
} }
// Alle notwendigen Module persistieren. // Alle notwendigen Module persistieren.
OutputPersistenceBlock Writer; OutputPersistenceBlock writer;
bool Success = true; bool success = true;
Success &= Kernel::GetInstance()->GetScript()->persist(Writer); success &= Kernel::getInstance()->getScript()->persist(writer);
Success &= RegionRegistry::instance().persist(Writer); success &= RegionRegistry::instance().persist(writer);
Success &= Kernel::GetInstance()->GetGfx()->persist(Writer); success &= Kernel::getInstance()->getGfx()->persist(writer);
Success &= Kernel::GetInstance()->GetSfx()->persist(Writer); success &= Kernel::getInstance()->getSfx()->persist(writer);
Success &= Kernel::GetInstance()->GetInput()->persist(Writer); success &= Kernel::getInstance()->getInput()->persist(writer);
if (!Success) { if (!success) {
error("Unable to persist modules for savegame file \"%s\".", Filename.c_str()); error("Unable to persist modules for savegame file \"%s\".", filename.c_str());
} }
// Daten komprimieren. // Daten komprimieren.
uLongf CompressedLength = Writer.GetDataSize() + (Writer.GetDataSize() + 500) / 1000 + 12; uLongf compressedLength = writer.getDataSize() + (writer.getDataSize() + 500) / 1000 + 12;
Bytef *CompressionBuffer = new Bytef[CompressedLength]; Bytef *compressionBuffer = new Bytef[compressedLength];
if (compress2(&CompressionBuffer[0], &CompressedLength, reinterpret_cast<const Bytef *>(Writer.GetData()), Writer.GetDataSize(), 6) != Z_OK) { if (compress2(&compressionBuffer[0], &compressedLength, reinterpret_cast<const Bytef *>(writer.getData()), writer.getDataSize(), 6) != Z_OK) {
error("Unable to compress savegame data in savegame file \"%s\".", Filename.c_str()); error("Unable to compress savegame data in savegame file \"%s\".", filename.c_str());
} }
// Länge der komprimierten Daten und der unkomprimierten Daten in die Datei schreiben. // Länge der komprimierten Daten und der unkomprimierten Daten in die Datei schreiben.
char sBuffer[10]; char sBuffer[10];
snprintf(sBuffer, 10, "%ld", CompressedLength); snprintf(sBuffer, 10, "%ld", compressedLength);
File->writeString(sBuffer); file->writeString(sBuffer);
File->writeByte(' '); file->writeByte(' ');
snprintf(sBuffer, 10, "%u", Writer.GetDataSize()); snprintf(sBuffer, 10, "%u", writer.getDataSize());
File->writeString(sBuffer); file->writeString(sBuffer);
File->writeByte(' '); file->writeByte(' ');
// Komprimierte Daten in die Datei schreiben. // Komprimierte Daten in die Datei schreiben.
File->write(reinterpret_cast<char *>(&CompressionBuffer[0]), CompressedLength); file->write(reinterpret_cast<char *>(&compressionBuffer[0]), compressedLength);
if (File->err()) { if (file->err()) {
error("Unable to write game data to savegame file \"%s\".", Filename.c_str()); error("Unable to write game data to savegame file \"%s\".", filename.c_str());
} }
// Get the screenshot // Get the screenshot
Common::MemoryReadStream *thumbnail = Kernel::GetInstance()->GetGfx()->getThumbnail(); Common::MemoryReadStream *thumbnail = Kernel::getInstance()->getGfx()->getThumbnail();
if (thumbnail) { if (thumbnail) {
byte *Buffer = new Byte[FILE_COPY_BUFFER_SIZE]; byte *buffer = new Byte[FILE_COPY_BUFFER_SIZE];
while (!thumbnail->eos()) { while (!thumbnail->eos()) {
int bytesRead = thumbnail->read(&Buffer[0], FILE_COPY_BUFFER_SIZE); int bytesRead = thumbnail->read(&buffer[0], FILE_COPY_BUFFER_SIZE);
File->write(&Buffer[0], bytesRead); file->write(&buffer[0], bytesRead);
} }
delete[] Buffer; delete[] buffer;
} else { } else {
BS_LOG_WARNINGLN("The screenshot file \"%s\" does not exist. Savegame is written without a screenshot.", Filename.c_str()); BS_LOG_WARNINGLN("The screenshot file \"%s\" does not exist. Savegame is written without a screenshot.", filename.c_str());
} }
// Savegameinformationen für diesen Slot aktualisieren. // Savegameinformationen für diesen Slot aktualisieren.
m_impl->ReadSlotSavegameInformation(SlotID); _impl->readSlotSavegameInformation(slotID);
File->finalize(); file->finalize();
delete File; delete file;
delete[] CompressionBuffer; delete[] compressionBuffer;
// Erfolg signalisieren. // Erfolg signalisieren.
return true; return true;
} }
// ----------------------------------------------------------------------------- bool PersistenceService::loadGame(uint slotID) {
bool PersistenceService::LoadGame(uint SlotID) {
Common::SaveFileManager *sfm = g_system->getSavefileManager(); Common::SaveFileManager *sfm = g_system->getSavefileManager();
Common::InSaveFile *File; Common::InSaveFile *file;
// Überprüfen, ob die Slot-ID zulässig ist. // Überprüfen, ob die Slot-ID zulässig ist.
if (SlotID >= SLOT_COUNT) { if (slotID >= SLOT_COUNT) {
BS_LOG_ERRORLN("Tried to load from an invalid slot (%d). Only slot ids form 0 to %d are allowed.", SlotID, SLOT_COUNT - 1); BS_LOG_ERRORLN("Tried to load from an invalid slot (%d). Only slot ids form 0 to %d are allowed.", slotID, SLOT_COUNT - 1);
return false; return false;
} }
SavegameInformation &CurSavegameInfo = m_impl->m_SavegameInformations[SlotID]; SavegameInformation &curSavegameInfo = _impl->_savegameInformations[slotID];
// Überprüfen, ob der Slot belegt ist. // Überprüfen, ob der Slot belegt ist.
if (!CurSavegameInfo.IsOccupied) { if (!curSavegameInfo.isOccupied) {
BS_LOG_ERRORLN("Tried to load from an empty slot (%d).", SlotID); BS_LOG_ERRORLN("Tried to load from an empty slot (%d).", slotID);
return false; return false;
} }
@ -407,54 +358,54 @@ bool PersistenceService::LoadGame(uint SlotID) {
// Im Debug-Modus wird dieser Test übersprungen. Für das Testen ist es hinderlich auf die Einhaltung dieser strengen Bedingung zu bestehen, // Im Debug-Modus wird dieser Test übersprungen. Für das Testen ist es hinderlich auf die Einhaltung dieser strengen Bedingung zu bestehen,
// da sich die Versions-ID bei jeder Codeänderung mitändert. // da sich die Versions-ID bei jeder Codeänderung mitändert.
#ifndef DEBUG #ifndef DEBUG
if (!CurSavegameInfo.IsCompatible) { if (!curSavegameInfo.isCompatible) {
BS_LOG_ERRORLN("Tried to load a savegame (%d) that is not compatible with this engine version.", SlotID); BS_LOG_ERRORLN("Tried to load a savegame (%d) that is not compatible with this engine version.", slotID);
return false; return false;
} }
#endif #endif
byte *CompressedDataBuffer = new byte[CurSavegameInfo.GamedataLength]; byte *compressedDataBuffer = new byte[curSavegameInfo.gamedataLength];
byte *UncompressedDataBuffer = new Bytef[CurSavegameInfo.GamedataUncompressedLength]; byte *uncompressedDataBuffer = new Bytef[curSavegameInfo.gamedataUncompressedLength];
File = sfm->openForLoading(GenerateSavegameFilename(SlotID)); file = sfm->openForLoading(generateSavegameFilename(slotID));
File->seek(CurSavegameInfo.GamedataOffset); file->seek(curSavegameInfo.gamedataOffset);
File->read(reinterpret_cast<char *>(&CompressedDataBuffer[0]), CurSavegameInfo.GamedataLength); file->read(reinterpret_cast<char *>(&compressedDataBuffer[0]), curSavegameInfo.gamedataLength);
if (File->err()) { if (file->err()) {
BS_LOG_ERRORLN("Unable to load the gamedata from the savegame file \"%s\".", CurSavegameInfo.Filename.c_str()); BS_LOG_ERRORLN("Unable to load the gamedata from the savegame file \"%s\".", curSavegameInfo.filename.c_str());
delete[] CompressedDataBuffer; delete[] compressedDataBuffer;
delete[] UncompressedDataBuffer; delete[] uncompressedDataBuffer;
return false; return false;
} }
// Spieldaten dekomprimieren. // Spieldaten dekomprimieren.
uLongf UncompressedBufferSize = CurSavegameInfo.GamedataUncompressedLength; uLongf uncompressedBufferSize = curSavegameInfo.gamedataUncompressedLength;
if (uncompress(reinterpret_cast<Bytef *>(&UncompressedDataBuffer[0]), &UncompressedBufferSize, if (uncompress(reinterpret_cast<Bytef *>(&uncompressedDataBuffer[0]), &uncompressedBufferSize,
reinterpret_cast<Bytef *>(&CompressedDataBuffer[0]), CurSavegameInfo.GamedataLength) != Z_OK) { reinterpret_cast<Bytef *>(&compressedDataBuffer[0]), curSavegameInfo.gamedataLength) != Z_OK) {
BS_LOG_ERRORLN("Unable to decompress the gamedata from savegame file \"%s\".", CurSavegameInfo.Filename.c_str()); BS_LOG_ERRORLN("Unable to decompress the gamedata from savegame file \"%s\".", curSavegameInfo.filename.c_str());
delete[] UncompressedDataBuffer; delete[] uncompressedDataBuffer;
delete[] CompressedDataBuffer; delete[] compressedDataBuffer;
delete File; delete file;
return false; return false;
} }
InputPersistenceBlock Reader(&UncompressedDataBuffer[0], CurSavegameInfo.GamedataUncompressedLength); InputPersistenceBlock reader(&uncompressedDataBuffer[0], curSavegameInfo.gamedataUncompressedLength);
// Einzelne Engine-Module depersistieren. // Einzelne Engine-Module depersistieren.
bool Success = true; bool success = true;
Success &= Kernel::GetInstance()->GetScript()->unpersist(Reader); success &= Kernel::getInstance()->getScript()->unpersist(reader);
// Muss unbedingt nach Script passieren. Da sonst die bereits wiederhergestellten Regions per Garbage-Collection gekillt werden. // Muss unbedingt nach Script passieren. Da sonst die bereits wiederhergestellten Regions per Garbage-Collection gekillt werden.
Success &= RegionRegistry::instance().unpersist(Reader); success &= RegionRegistry::instance().unpersist(reader);
Success &= Kernel::GetInstance()->GetGfx()->unpersist(Reader); success &= Kernel::getInstance()->getGfx()->unpersist(reader);
Success &= Kernel::GetInstance()->GetSfx()->unpersist(Reader); success &= Kernel::getInstance()->getSfx()->unpersist(reader);
Success &= Kernel::GetInstance()->GetInput()->unpersist(Reader); success &= Kernel::getInstance()->getInput()->unpersist(reader);
delete[] CompressedDataBuffer; delete[] compressedDataBuffer;
delete[] UncompressedDataBuffer; delete[] uncompressedDataBuffer;
delete File; delete file;
if (!Success) { if (!success) {
BS_LOG_ERRORLN("Unable to unpersist the gamedata from savegame file \"%s\".", CurSavegameInfo.Filename.c_str()); BS_LOG_ERRORLN("Unable to unpersist the gamedata from savegame file \"%s\".", curSavegameInfo.filename.c_str());
return false; return false;
} }

View file

@ -35,18 +35,10 @@
#ifndef SWORD25_PERSISTENCESERVICE_H #ifndef SWORD25_PERSISTENCESERVICE_H
#define SWORD25_PERSISTENCESERVICE_H #define SWORD25_PERSISTENCESERVICE_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
namespace Sword25 { namespace Sword25 {
// -----------------------------------------------------------------------------
// Class declaration
// -----------------------------------------------------------------------------
class PersistenceService { class PersistenceService {
public: public:
PersistenceService(); PersistenceService();
@ -56,27 +48,27 @@ public:
// Singleton Method // Singleton Method
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static PersistenceService &GetInstance(); static PersistenceService &getInstance();
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Interface // Interface
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static uint GetSlotCount(); static uint getSlotCount();
static Common::String GetSavegameDirectory(); static Common::String getSavegameDirectory();
void ReloadSlots(); void reloadSlots();
bool IsSlotOccupied(uint SlotID); bool isSlotOccupied(uint slotID);
bool IsSavegameCompatible(uint SlotID); bool isSavegameCompatible(uint slotID);
Common::String &GetSavegameDescription(uint SlotID); Common::String &getSavegameDescription(uint slotID);
Common::String &GetSavegameFilename(uint SlotID); Common::String &getSavegameFilename(uint slotID);
bool SaveGame(uint SlotID, const Common::String &ScreenshotFilename); bool saveGame(uint slotID, const Common::String &screenshotFilename);
bool LoadGame(uint SlotID); bool loadGame(uint slotID);
private: private:
struct Impl; struct Impl;
Impl *m_impl; Impl *_impl;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -45,20 +45,20 @@ namespace Sword25 {
ResourceManager::~ResourceManager() { ResourceManager::~ResourceManager() {
// Clear all unlocked resources // Clear all unlocked resources
EmptyCache(); emptyCache();
// All remaining resources are not released, so print warnings and release // All remaining resources are not released, so print warnings and release
Common::List<Resource *>::iterator Iter = m_Resources.begin(); Common::List<Resource *>::iterator iter = _resources.begin();
for (; Iter != m_Resources.end(); ++Iter) { for (; iter != _resources.end(); ++iter) {
BS_LOG_WARNINGLN("Resource \"%s\" was not released.", (*Iter)->getFileName().c_str()); BS_LOG_WARNINGLN("Resource \"%s\" was not released.", (*iter)->getFileName().c_str());
// Set the lock count to zero // Set the lock count to zero
while ((*Iter)->GetLockCount() > 0) { while ((*iter)->getLockCount() > 0) {
(*Iter)->release(); (*iter)->release();
}; };
// Delete the resource // Delete the resource
delete(*Iter); delete(*iter);
} }
} }
@ -67,19 +67,19 @@ ResourceManager::~ResourceManager() {
* Note: This method is not optimised for speed and should be used only for debugging purposes * Note: This method is not optimised for speed and should be used only for debugging purposes
* @param Ord Ordinal number of the resource. Must be between 0 and GetResourceCount() - 1. * @param Ord Ordinal number of the resource. Must be between 0 and GetResourceCount() - 1.
*/ */
Resource *ResourceManager::GetResourceByOrdinal(int Ord) const { Resource *ResourceManager::getResourceByOrdinal(int ord) const {
// Überprüfen ob der Index Ord innerhald der Listengrenzen liegt. // Überprüfen ob der Index Ord innerhald der Listengrenzen liegt.
if (Ord < 0 || Ord >= GetResourceCount()) { if (ord < 0 || ord >= getResourceCount()) {
BS_LOG_ERRORLN("Resource ordinal (%d) out of bounds (0 - %d).", Ord, GetResourceCount() - 1); BS_LOG_ERRORLN("Resource ordinal (%d) out of bounds (0 - %d).", ord, getResourceCount() - 1);
return NULL; return NULL;
} }
// Liste durchlaufen und die Resource mit dem gewünschten Index zurückgeben. // Liste durchlaufen und die Resource mit dem gewünschten Index zurückgeben.
int CurOrd = 0; int curOrd = 0;
Common::List<Resource *>::const_iterator Iter = m_Resources.begin(); Common::List<Resource *>::const_iterator iter = _resources.begin();
for (; Iter != m_Resources.end(); ++Iter, ++CurOrd) { for (; iter != _resources.end(); ++iter, ++curOrd) {
if (CurOrd == Ord) if (curOrd == ord)
return (*Iter); return (*iter);
} }
// Die Ausführung sollte nie an diesem Punkt ankommen. // Die Ausführung sollte nie an diesem Punkt ankommen.
@ -92,13 +92,13 @@ Resource *ResourceManager::GetResourceByOrdinal(int Ord) const {
* BS_ResourceService, and thus helps all resource services in the ResourceManager list * BS_ResourceService, and thus helps all resource services in the ResourceManager list
* @param pService Which service * @param pService Which service
*/ */
bool ResourceManager::RegisterResourceService(ResourceService *pService) { bool ResourceManager::registerResourceService(ResourceService *pService) {
if (!pService) { if (!pService) {
BS_LOG_ERRORLN("Can't register NULL resource service."); BS_LOG_ERRORLN("Can't register NULL resource service.");
return false; return false;
} }
m_ResourceServices.push_back(pService); _resourceServices.push_back(pService);
return true; return true;
} }
@ -106,34 +106,36 @@ bool ResourceManager::RegisterResourceService(ResourceService *pService) {
/** /**
* Deletes resources as necessary until the specified memory limit is not being exceeded. * Deletes resources as necessary until the specified memory limit is not being exceeded.
*/ */
void ResourceManager::DeleteResourcesIfNecessary() { void ResourceManager::deleteResourcesIfNecessary() {
// If enough memory is available, or no resources are loaded, then the function can immediately end // If enough memory is available, or no resources are loaded, then the function can immediately end
if (m_KernelPtr->GetUsedMemory() < m_MaxMemoryUsage || m_Resources.empty()) return; if (_kernelPtr->getUsedMemory() < _maxMemoryUsage || _resources.empty())
return;
// Keep deleting resources until the memory usage of the process falls below the set maximum limit. // Keep deleting resources until the memory usage of the process falls below the set maximum limit.
// The list is processed backwards in order to first release those resources who have been // The list is processed backwards in order to first release those resources who have been
// not been accessed for the longest // not been accessed for the longest
Common::List<Resource *>::iterator Iter = m_Resources.end(); Common::List<Resource *>::iterator iter = _resources.end();
do { do {
--Iter; --iter;
// The resource may be released only if it isn't locked // The resource may be released only if it isn't locked
if ((*Iter)->GetLockCount() == 0) Iter = DeleteResource(*Iter); if ((*iter)->getLockCount() == 0)
} while (Iter != m_Resources.begin() && m_KernelPtr->GetUsedMemory() > m_MaxMemoryUsage); iter = deleteResource(*iter);
} while (iter != _resources.begin() && _kernelPtr->getUsedMemory() > _maxMemoryUsage);
} }
/** /**
* Releases all resources that are not locked. * Releases all resources that are not locked.
**/ **/
void ResourceManager::EmptyCache() { void ResourceManager::emptyCache() {
// Scan through the resource list // Scan through the resource list
Common::List<Resource *>::iterator Iter = m_Resources.begin(); Common::List<Resource *>::iterator iter = _resources.begin();
while (Iter != m_Resources.end()) { while (iter != _resources.end()) {
if ((*Iter)->GetLockCount() == 0) { if ((*iter)->getLockCount() == 0) {
// Delete the resource // Delete the resource
Iter = DeleteResource(*Iter); iter = deleteResource(*iter);
} else } else
++Iter; ++iter;
} }
} }
@ -141,29 +143,30 @@ void ResourceManager::EmptyCache() {
* Returns a requested resource. If any error occurs, returns NULL * Returns a requested resource. If any error occurs, returns NULL
* @param FileName Filename of resource * @param FileName Filename of resource
*/ */
Resource *ResourceManager::RequestResource(const Common::String &FileName) { Resource *ResourceManager::requestResource(const Common::String &fileName) {
// Get the absolute path to the file // Get the absolute path to the file
Common::String UniqueFileName = GetUniqueFileName(FileName); Common::String uniqueFileName = getUniqueFileName(fileName);
if (UniqueFileName == "") if (uniqueFileName == "")
return NULL; return NULL;
// Determine whether the resource is already loaded // Determine whether the resource is already loaded
// If the resource is found, it will be placed at the head of the resource list and returned // If the resource is found, it will be placed at the head of the resource list and returned
{ {
Resource *pResource = GetResource(UniqueFileName); Resource *pResource = getResource(uniqueFileName);
if (pResource) { if (pResource) {
MoveToFront(pResource); moveToFront(pResource);
(pResource)->AddReference(); (pResource)->addReference();
return pResource; return pResource;
} }
} }
// The resource was not found, therefore, must not be loaded yet // The resource was not found, therefore, must not be loaded yet
if (m_LogCacheMiss) BS_LOG_WARNINGLN("\"%s\" was not precached.", UniqueFileName.c_str()); if (_logCacheMiss)
BS_LOG_WARNINGLN("\"%s\" was not precached.", uniqueFileName.c_str());
Resource *pResource; Resource *pResource;
if ((pResource = loadResource(UniqueFileName))) { if ((pResource = loadResource(uniqueFileName))) {
pResource->AddReference(); pResource->addReference();
return pResource; return pResource;
} }
@ -176,26 +179,26 @@ Resource *ResourceManager::RequestResource(const Common::String &FileName) {
* @param ForceReload Indicates whether the file should be reloaded if it's already in the cache. * @param ForceReload Indicates whether the file should be reloaded if it's already in the cache.
* This is useful for files that may have changed in the interim * This is useful for files that may have changed in the interim
*/ */
bool ResourceManager::PrecacheResource(const Common::String &FileName, bool ForceReload) { bool ResourceManager::precacheResource(const Common::String &fileName, bool forceReload) {
// Get the absolute path to the file // Get the absolute path to the file
Common::String UniqueFileName = GetUniqueFileName(FileName); Common::String uniqueFileName = getUniqueFileName(fileName);
if (UniqueFileName == "") if (uniqueFileName == "")
return false; return false;
Resource *ResourcePtr = GetResource(UniqueFileName); Resource *resourcePtr = getResource(uniqueFileName);
if (ForceReload && ResourcePtr) { if (forceReload && resourcePtr) {
if (ResourcePtr->GetLockCount()) { if (resourcePtr->getLockCount()) {
BS_LOG_ERRORLN("Could not force precaching of \"%s\". The resource is locked.", FileName.c_str()); BS_LOG_ERRORLN("Could not force precaching of \"%s\". The resource is locked.", fileName.c_str());
return false; return false;
} else { } else {
DeleteResource(ResourcePtr); deleteResource(resourcePtr);
ResourcePtr = 0; resourcePtr = 0;
} }
} }
if (!ResourcePtr && loadResource(UniqueFileName) == NULL) { if (!resourcePtr && loadResource(uniqueFileName) == NULL) {
BS_LOG_ERRORLN("Could not precache \"%s\",", FileName.c_str()); BS_LOG_ERRORLN("Could not precache \"%s\",", fileName.c_str());
return false; return false;
} }
@ -206,13 +209,13 @@ bool ResourceManager::PrecacheResource(const Common::String &FileName, bool Forc
* Moves a resource to the top of the resource list * Moves a resource to the top of the resource list
* @param pResource The resource * @param pResource The resource
*/ */
void ResourceManager::MoveToFront(Resource *pResource) { void ResourceManager::moveToFront(Resource *pResource) {
// Erase the resource from it's current position // Erase the resource from it's current position
m_Resources.erase(pResource->_iterator); _resources.erase(pResource->_iterator);
// Re-add the resource at the front of the list // Re-add the resource at the front of the list
m_Resources.push_front(pResource); _resources.push_front(pResource);
// Reset the resource iterator to the repositioned item // Reset the resource iterator to the repositioned item
pResource->_iterator = m_Resources.begin(); pResource->_iterator = _resources.begin();
} }
/** /**
@ -223,24 +226,24 @@ void ResourceManager::MoveToFront(Resource *pResource) {
*/ */
Resource *ResourceManager::loadResource(const Common::String &fileName) { Resource *ResourceManager::loadResource(const Common::String &fileName) {
// ResourceService finden, der die Resource laden kann. // ResourceService finden, der die Resource laden kann.
for (uint i = 0; i < m_ResourceServices.size(); ++i) { for (uint i = 0; i < _resourceServices.size(); ++i) {
if (m_ResourceServices[i]->canLoadResource(fileName)) { if (_resourceServices[i]->canLoadResource(fileName)) {
// If more memory is desired, memory must be released // If more memory is desired, memory must be released
DeleteResourcesIfNecessary(); deleteResourcesIfNecessary();
// Load the resource // Load the resource
Resource *pResource; Resource *pResource;
if (!(pResource = m_ResourceServices[i]->loadResource(fileName))) { if (!(pResource = _resourceServices[i]->loadResource(fileName))) {
BS_LOG_ERRORLN("Responsible service could not load resource \"%s\".", fileName.c_str()); BS_LOG_ERRORLN("Responsible service could not load resource \"%s\".", fileName.c_str());
return NULL; return NULL;
} }
// Add the resource to the front of the list // Add the resource to the front of the list
m_Resources.push_front(pResource); _resources.push_front(pResource);
pResource->_iterator = m_Resources.begin(); pResource->_iterator = _resources.begin();
// Also store the resource in the hash table for quick lookup // Also store the resource in the hash table for quick lookup
m_ResourceHashTable[pResource->GetFileNameHash() % HASH_TABLE_BUCKETS].push_front(pResource); _resourceHashTable[pResource->getFileNameHash() % HASH_TABLE_BUCKETS].push_front(pResource);
return pResource; return pResource;
} }
@ -254,56 +257,55 @@ Resource *ResourceManager::loadResource(const Common::String &fileName) {
* Returns the full path of a given resource filename. * Returns the full path of a given resource filename.
* It will return an empty string if a path could not be created. * It will return an empty string if a path could not be created.
*/ */
Common::String ResourceManager::GetUniqueFileName(const Common::String &FileName) const { Common::String ResourceManager::getUniqueFileName(const Common::String &fileName) const {
// Get a pointer to the package manager // Get a pointer to the package manager
PackageManager *pPackage = (PackageManager *)m_KernelPtr->GetPackage(); PackageManager *pPackage = (PackageManager *)_kernelPtr->getPackage();
if (!pPackage) { if (!pPackage) {
BS_LOG_ERRORLN("Could not get package manager."); BS_LOG_ERRORLN("Could not get package manager.");
return Common::String(""); return Common::String("");
} }
// Absoluten Pfad der Datei bekommen und somit die Eindeutigkeit des Dateinamens sicherstellen // Absoluten Pfad der Datei bekommen und somit die Eindeutigkeit des Dateinamens sicherstellen
Common::String UniqueFileName = pPackage->getAbsolutePath(FileName); Common::String uniquefileName = pPackage->getAbsolutePath(fileName);
if (UniqueFileName == "") if (uniquefileName == "")
BS_LOG_ERRORLN("Could not create absolute file name for \"%s\".", FileName.c_str()); BS_LOG_ERRORLN("Could not create absolute file name for \"%s\".", fileName.c_str());
return UniqueFileName; return uniquefileName;
} }
/** /**
* Deletes a resource, removes it from the lists, and updates m_UsedMemory * Deletes a resource, removes it from the lists, and updates m_UsedMemory
*/ */
Common::List<Resource *>::iterator ResourceManager::DeleteResource(Resource *pResource) { Common::List<Resource *>::iterator ResourceManager::deleteResource(Resource *pResource) {
// Remove the resource from the hash table // Remove the resource from the hash table
m_ResourceHashTable[pResource->GetFileNameHash() % HASH_TABLE_BUCKETS].remove(pResource); _resourceHashTable[pResource->getFileNameHash() % HASH_TABLE_BUCKETS].remove(pResource);
Resource *pDummy = pResource; Resource *pDummy = pResource;
// Delete the resource from the resource list // Delete the resource from the resource list
Common::List<Resource *>::iterator Result = m_Resources.erase(pResource->_iterator); Common::List<Resource *>::iterator result = _resources.erase(pResource->_iterator);
// Delete the resource // Delete the resource
delete(pDummy); delete(pDummy);
// Return the iterator // Return the iterator
return Result; return result;
} }
/** /**
* Returns a pointer to a loaded resource. If any error occurs, NULL will be returned. * Returns a pointer to a loaded resource. If any error occurs, NULL will be returned.
* @param UniqueFileName The absolute path and filename * @param UniquefileName The absolute path and filename
* Gibt einen Pointer auf die angeforderte Resource zurück, oder NULL, wenn die Resourcen nicht geladen ist. * Gibt einen Pointer auf die angeforderte Resource zurück, oder NULL, wenn die Resourcen nicht geladen ist.
*/ */
Resource *ResourceManager::GetResource(const Common::String &UniqueFileName) const { Resource *ResourceManager::getResource(const Common::String &uniquefileName) const {
// Determine whether the resource is already loaded // Determine whether the resource is already loaded
const Common::List<Resource *>& HashBucket = m_ResourceHashTable[ const Common::List<Resource *>& hashBucket = _resourceHashTable[BS_String::getHash(uniquefileName) % HASH_TABLE_BUCKETS];
BS_String::GetHash(UniqueFileName) % HASH_TABLE_BUCKETS];
{ {
Common::List<Resource *>::const_iterator Iter = HashBucket.begin(); Common::List<Resource *>::const_iterator iter = hashBucket.begin();
for (; Iter != HashBucket.end(); ++Iter) { for (; iter != hashBucket.end(); ++iter) {
// Wenn die Resource gefunden wurde wird sie zurückgegeben. // Wenn die Resource gefunden wurde wird sie zurückgegeben.
if ((*Iter)->getFileName() == UniqueFileName) if ((*iter)->getFileName() == uniquefileName)
return *Iter; return *iter;
} }
} }
@ -314,10 +316,10 @@ Resource *ResourceManager::GetResource(const Common::String &UniqueFileName) con
/** /**
* Writes the names of all currently locked resources to the log file * Writes the names of all currently locked resources to the log file
*/ */
void ResourceManager::DumpLockedResources() { void ResourceManager::dumpLockedResources() {
for (Common::List<Resource *>::iterator Iter = m_Resources.begin(); Iter != m_Resources.end(); ++Iter) { for (Common::List<Resource *>::iterator iter = _resources.begin(); iter != _resources.end(); ++iter) {
if ((*Iter)->GetLockCount() > 0) { if ((*iter)->getLockCount() > 0) {
BS_LOGLN("%s", (*Iter)->getFileName().c_str()); BS_LOGLN("%s", (*iter)->getFileName().c_str());
} }
} }
} }
@ -328,9 +330,9 @@ void ResourceManager::DumpLockedResources() {
* as a guideline, and not as a fixed boundary. It is not guaranteed not to be exceeded; * as a guideline, and not as a fixed boundary. It is not guaranteed not to be exceeded;
* the whole game engine may still use more memory than any amount specified. * the whole game engine may still use more memory than any amount specified.
*/ */
void ResourceManager::SetMaxMemoryUsage(uint MaxMemoryUsage) { void ResourceManager::setMaxMemoryUsage(uint maxMemoryUsage) {
m_MaxMemoryUsage = MaxMemoryUsage; _maxMemoryUsage = maxMemoryUsage;
DeleteResourcesIfNecessary(); deleteResourcesIfNecessary();
} }
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -35,14 +35,12 @@
#ifndef SWORD25_RESOURCEMANAGER_H #ifndef SWORD25_RESOURCEMANAGER_H
#define SWORD25_RESOURCEMANAGER_H #define SWORD25_RESOURCEMANAGER_H
// Includes
#include "common/list.h" #include "common/list.h"
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
namespace Sword25 { namespace Sword25 {
// Class definitions
class ResourceService; class ResourceService;
class Resource; class Resource;
class Kernel; class Kernel;
@ -55,7 +53,7 @@ public:
* Returns a requested resource. If any error occurs, returns NULL * Returns a requested resource. If any error occurs, returns NULL
* @param FileName Filename of resource * @param FileName Filename of resource
*/ */
Resource *RequestResource(const Common::String &FileName); Resource *requestResource(const Common::String &fileName);
/** /**
* Loads a resource into the cache * Loads a resource into the cache
@ -63,13 +61,13 @@ public:
* @param ForceReload Indicates whether the file should be reloaded if it's already in the cache. * @param ForceReload Indicates whether the file should be reloaded if it's already in the cache.
* This is useful for files that may have changed in the interim * This is useful for files that may have changed in the interim
*/ */
bool PrecacheResource(const Common::String &FileName, bool ForceReload = false); bool precacheResource(const Common::String &fileName, bool forceReload = false);
/** /**
* Returns the number of loaded resources * Returns the number of loaded resources
*/ */
int GetResourceCount() const { int getResourceCount() const {
return static_cast<int>(m_Resources.size()); return static_cast<int>(_resources.size());
} }
/** /**
@ -77,25 +75,25 @@ public:
* Note: This method is not optimised for speed and should be used only for debugging purposes * Note: This method is not optimised for speed and should be used only for debugging purposes
* @param Ord Ordinal number of the resource. Must be between 0 and GetResourceCount() - 1. * @param Ord Ordinal number of the resource. Must be between 0 and GetResourceCount() - 1.
*/ */
Resource *GetResourceByOrdinal(int Ord) const; Resource *getResourceByOrdinal(int ord) const;
/** /**
* Registers a RegisterResourceService. This method is the constructor of * Registers a RegisterResourceService. This method is the constructor of
* BS_ResourceService, and thus helps all resource services in the ResourceManager list * BS_ResourceService, and thus helps all resource services in the ResourceManager list
* @param pService Which service * @param pService Which service
*/ */
bool RegisterResourceService(ResourceService *pService); bool registerResourceService(ResourceService *pService);
/** /**
* Releases all resources that are not locked. * Releases all resources that are not locked.
**/ **/
void EmptyCache(); void emptyCache();
/** /**
* Returns the maximum memory the kernel has used * Returns the maximum memory the kernel has used
*/ */
int GetMaxMemoryUsage() const { int getMaxMemoryUsage() const {
return m_MaxMemoryUsage; return _maxMemoryUsage;
} }
/** /**
@ -104,28 +102,28 @@ public:
* as a guideline, and not as a fixed boundary. It is not guaranteed not to be exceeded; * as a guideline, and not as a fixed boundary. It is not guaranteed not to be exceeded;
* the whole game engine may still use more memory than any amount specified. * the whole game engine may still use more memory than any amount specified.
*/ */
void SetMaxMemoryUsage(uint MaxMemoryUsage); void setMaxMemoryUsage(uint maxMemoryUsage);
/** /**
* Specifies whether a warning is written to the log when a cache miss occurs. * Specifies whether a warning is written to the log when a cache miss occurs.
* THe default value is "false". * THe default value is "false".
*/ */
bool IsLogCacheMiss() const { bool isLogCacheMiss() const {
return m_LogCacheMiss; return _logCacheMiss;
} }
/** /**
* Sets whether warnings are written to the log if a cache miss occurs. * Sets whether warnings are written to the log if a cache miss occurs.
* @param Flag If "true", then future warnings will be logged * @param Flag If "true", then future warnings will be logged
*/ */
void SetLogCacheMiss(bool Flag) { void setLogCacheMiss(bool flag) {
m_LogCacheMiss = Flag; _logCacheMiss = flag;
} }
/** /**
* Writes the names of all currently locked resources to the log file * Writes the names of all currently locked resources to the log file
*/ */
void DumpLockedResources(); void dumpLockedResources();
private: private:
/** /**
@ -133,9 +131,9 @@ private:
* Only the BS_Kernel class can generate copies this class. Thus, the constructor is private * Only the BS_Kernel class can generate copies this class. Thus, the constructor is private
*/ */
ResourceManager(Kernel *pKernel) : ResourceManager(Kernel *pKernel) :
m_KernelPtr(pKernel), _kernelPtr(pKernel),
m_MaxMemoryUsage(100000000), _maxMemoryUsage(100000000),
m_LogCacheMiss(false) _logCacheMiss(false)
{} {}
virtual ~ResourceManager(); virtual ~ResourceManager();
@ -147,7 +145,7 @@ private:
* Moves a resource to the top of the resource list * Moves a resource to the top of the resource list
* @param pResource The resource * @param pResource The resource
*/ */
void MoveToFront(Resource *pResource); void moveToFront(Resource *pResource);
/** /**
* Loads a resource and updates the m_UsedMemory total * Loads a resource and updates the m_UsedMemory total
@ -161,31 +159,31 @@ private:
* Returns the full path of a given resource filename. * Returns the full path of a given resource filename.
* It will return an empty string if a path could not be created. * It will return an empty string if a path could not be created.
*/ */
Common::String GetUniqueFileName(const Common::String &FileName) const; Common::String getUniqueFileName(const Common::String &fileName) const;
/** /**
* Deletes a resource, removes it from the lists, and updates m_UsedMemory * Deletes a resource, removes it from the lists, and updates m_UsedMemory
*/ */
Common::List<Resource *>::iterator DeleteResource(Resource *pResource); Common::List<Resource *>::iterator deleteResource(Resource *pResource);
/** /**
* Returns a pointer to a loaded resource. If any error occurs, NULL will be returned. * Returns a pointer to a loaded resource. If any error occurs, NULL will be returned.
* @param UniqueFileName The absolute path and filename * @param UniqueFileName The absolute path and filename
* Gibt einen Pointer auf die angeforderte Resource zurück, oder NULL, wenn die Resourcen nicht geladen ist. * Gibt einen Pointer auf die angeforderte Resource zurück, oder NULL, wenn die Resourcen nicht geladen ist.
*/ */
Resource *GetResource(const Common::String &UniqueFileName) const; Resource *getResource(const Common::String &uniqueFileName) const;
/** /**
* Deletes resources as necessary until the specified memory limit is not being exceeded. * Deletes resources as necessary until the specified memory limit is not being exceeded.
*/ */
void DeleteResourcesIfNecessary(); void deleteResourcesIfNecessary();
Kernel *m_KernelPtr; Kernel *_kernelPtr;
uint m_MaxMemoryUsage; uint _maxMemoryUsage;
Common::Array<ResourceService *> m_ResourceServices; Common::Array<ResourceService *> _resourceServices;
Common::List<Resource *> m_Resources; Common::List<Resource *> _resources;
Common::List<Resource *> m_ResourceHashTable[HASH_TABLE_BUCKETS]; Common::List<Resource *> _resourceHashTable[HASH_TABLE_BUCKETS];
bool m_LogCacheMiss; bool _logCacheMiss;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -44,11 +44,11 @@ namespace Sword25 {
Resource::Resource(const Common::String &fileName, RESOURCE_TYPES type) : Resource::Resource(const Common::String &fileName, RESOURCE_TYPES type) :
_type(type), _type(type),
_refCount(0) { _refCount(0) {
PackageManager *pPM = Kernel::GetInstance()->GetPackage(); PackageManager *pPM = Kernel::getInstance()->getPackage();
BS_ASSERT(pPM); BS_ASSERT(pPM);
_fileName = pPM->getAbsolutePath(fileName); _fileName = pPM->getAbsolutePath(fileName);
_fileNameHash = BS_String::GetHash(fileName); _fileNameHash = BS_String::getHash(fileName);
} }
void Resource::release() { void Resource::release() {

View file

@ -62,7 +62,7 @@ public:
* Prevents the resource from being released. * Prevents the resource from being released.
* @remarks This method allows a resource to be locked multiple times. * @remarks This method allows a resource to be locked multiple times.
**/ **/
void AddReference() { void addReference() {
++_refCount; ++_refCount;
} }
@ -77,7 +77,7 @@ public:
* Returns the current lock count for the resource * Returns the current lock count for the resource
* @return The current lock count * @return The current lock count
**/ **/
int GetLockCount() const { int getLockCount() const {
return _refCount; return _refCount;
} }
@ -91,14 +91,14 @@ public:
/** /**
* Returns the hash of the filename of a resource * Returns the hash of the filename of a resource
*/ */
uint GetFileNameHash() const { uint getFileNameHash() const {
return _fileNameHash; return _fileNameHash;
} }
/** /**
* Returns a resource's type * Returns a resource's type
*/ */
uint GetType() const { uint getType() const {
return _type; return _type;
} }

View file

@ -35,7 +35,6 @@
#ifndef SWORD25_RESOURCESERVICE_H #ifndef SWORD25_RESOURCESERVICE_H
#define SWORD25_RESOURCESERVICE_H #define SWORD25_RESOURCESERVICE_H
// Includes
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/service.h" #include "sword25/kernel/service.h"
#include "sword25/kernel/kernel.h" #include "sword25/kernel/kernel.h"
@ -48,8 +47,8 @@ class Resource;
class ResourceService : public Service { class ResourceService : public Service {
public: public:
ResourceService(Kernel *pKernel) : Service(pKernel) { ResourceService(Kernel *pKernel) : Service(pKernel) {
ResourceManager *pResource = pKernel->GetResourceManager(); ResourceManager *pResource = pKernel->getResourceManager();
pResource->RegisterResourceService(this); pResource->registerResourceService(this);
} }
virtual ~ResourceService() {} virtual ~ResourceService() {}

View file

@ -43,31 +43,31 @@
namespace Sword25 { namespace Sword25 {
bool ScummVMWindow::_ClassRegistered = false; bool ScummVMWindow::_classRegistered = false;
// Constructor / Destructor // Constructor / Destructor
// ------------------------ // ------------------------
ScummVMWindow::ScummVMWindow(int X, int Y, int Width, int Height, bool Visible) { ScummVMWindow::ScummVMWindow(int x, int y, int width, int height, bool visible) {
// Presume that init will fail // Presume that init will fail
_InitSuccess = false; _initSuccess = false;
// We don't support any window creation except at the origin 0,0 // We don't support any window creation except at the origin 0,0
assert(X == 0); assert(x == 0);
assert(Y == 0); assert(y == 0);
if (!_ClassRegistered) { if (!_classRegistered) {
// Nothing here currently // Nothing here currently
_ClassRegistered = true; _classRegistered = true;
} }
// Fenstersichtbarkeit setzen // Fenstersichtbarkeit setzen
SetVisible(Visible); setVisible(visible);
// Indicate success // Indicate success
_InitSuccess = true; _initSuccess = true;
_WindowAlive = true; _windowAlive = true;
_CloseWanted = false; _closeWanted = false;
} }
ScummVMWindow::~ScummVMWindow() { ScummVMWindow::~ScummVMWindow() {
@ -75,86 +75,86 @@ ScummVMWindow::~ScummVMWindow() {
// Get Methods // Get Methods
// ------------ // ------------
int ScummVMWindow::GetX() { int ScummVMWindow::getX() {
return 0; return 0;
} }
int ScummVMWindow::GetY() { int ScummVMWindow::getY() {
return 0; return 0;
} }
int ScummVMWindow::GetClientX() { int ScummVMWindow::getClientX() {
return 0; return 0;
} }
int ScummVMWindow::GetClientY() { int ScummVMWindow::getClientY() {
return 0; return 0;
} }
int ScummVMWindow::GetWidth() { int ScummVMWindow::getWidth() {
return g_system->getWidth(); return g_system->getWidth();
} }
int ScummVMWindow::GetHeight() { int ScummVMWindow::getHeight() {
return g_system->getHeight(); return g_system->getHeight();
} }
Common::String ScummVMWindow::GetTitle() { Common::String ScummVMWindow::getTitle() {
return Common::String(""); return Common::String("");
} }
bool ScummVMWindow::IsVisible() { bool ScummVMWindow::isVisible() {
return true; return true;
} }
bool ScummVMWindow::HasFocus() { bool ScummVMWindow::hasFocus() {
// FIXME: Is there a way to tell if ScummVM has the focus in Windowed mode? // FIXME: Is there a way to tell if ScummVM has the focus in Windowed mode?
return true; return true;
} }
uint ScummVMWindow::GetWindowHandle() { uint ScummVMWindow::getWindowHandle() {
return 0; return 0;
} }
void ScummVMWindow::SetWindowAlive(bool v) { void ScummVMWindow::setWindowAlive(bool v) {
_WindowAlive = v; _windowAlive = v;
} }
// Set Methods // Set Methods
// ------------ // ------------
void ScummVMWindow::SetX(int X) { void ScummVMWindow::setX(int X) {
// No implementation // No implementation
} }
void ScummVMWindow::SetY(int Y) { void ScummVMWindow::setY(int Y) {
// No implementation // No implementation
} }
void ScummVMWindow::SetWidth(int Width) { void ScummVMWindow::setWidth(int width) {
// No implementation // No implementation
} }
void ScummVMWindow::SetHeight(int Height) { void ScummVMWindow::setHeight(int height) {
// No implementation // No implementation
} }
void ScummVMWindow::SetVisible(bool Visible) { void ScummVMWindow::setVisible(bool visible) {
// No implementation // No implementation
} }
void ScummVMWindow::SetTitle(const Common::String &Title) { void ScummVMWindow::setTitle(const Common::String &title) {
// No implementation // No implementation
} }
bool ScummVMWindow::ProcessMessages() { bool ScummVMWindow::processMessages() {
// All messages are handled separately in the input manager. The only thing we // All messages are handled separately in the input manager. The only thing we
// need to do here is to keep returning whether the window/game is still alive // need to do here is to keep returning whether the window/game is still alive
return _WindowAlive; return _windowAlive;
} }
bool ScummVMWindow::WaitForFocus() { bool ScummVMWindow::waitForFocus() {
// No implementation // No implementation
return true; return true;
} }

View file

@ -41,43 +41,41 @@
#ifndef SWORD25_SCUMMVMWINDOW_H #ifndef SWORD25_SCUMMVMWINDOW_H
#define SWORD25_SCUMMVMWINDOW_H #define SWORD25_SCUMMVMWINDOW_H
// Includes
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
#include "sword25/kernel/window.h" #include "sword25/kernel/window.h"
namespace Sword25 { namespace Sword25 {
// Class definition
class ScummVMWindow : public Window { class ScummVMWindow : public Window {
public: public:
ScummVMWindow(int X, int Y, int Width, int Height, bool Visible); ScummVMWindow(int x, int y, int width, int height, bool visible);
virtual ~ScummVMWindow(); virtual ~ScummVMWindow();
bool IsVisible(); bool isVisible();
void SetVisible(bool Visible); void setVisible(bool visible);
int GetX(); int getX();
void SetX(int X); void setX(int x);
int GetY(); int getY();
void SetY(int X); void setY(int x);
int GetClientX(); int getClientX();
int GetClientY(); int getClientY();
int GetWidth(); int getWidth();
void SetWidth(int Width); void setWidth(int width);
int GetHeight(); int getHeight();
void SetHeight(int Height); void setHeight(int height);
Common::String GetTitle(); Common::String getTitle();
void SetWindowAlive(bool v); void setWindowAlive(bool v);
void SetTitle(const Common::String &Title); void setTitle(const Common::String &title);
bool HasFocus(); bool hasFocus();
uint GetWindowHandle(); uint getWindowHandle();
bool WaitForFocus(); bool waitForFocus();
bool ProcessMessages(); bool processMessages();
private: private:
static bool _ClassRegistered; static bool _classRegistered;
bool _WindowAlive; bool _windowAlive;
int _ClientXDelta; int _clientXDelta;
int _ClientYDelta; int _clientYDelta;
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -81,7 +81,6 @@ const BS_ServiceInfo BS_SERVICE_TABLE[] = {
{ "fmv", "oggtheora", OggTheora_CreateObject } { "fmv", "oggtheora", OggTheora_CreateObject }
}; };
} // End of namespace Sword25 } // End of namespace Sword25
#endif #endif

View file

@ -39,71 +39,75 @@
namespace BS_String { namespace BS_String {
inline uint GetHash(const Common::String &Str) { inline uint getHash(const Common::String &str) {
uint Result = 0; uint result = 0;
for (uint i = 0; i < Str.size(); i++) for (uint i = 0; i < str.size(); i++)
Result = ((Result << 5) - Result) + Str[i]; result = ((result << 5) - result) + str[i];
return Result; return result;
} }
inline bool ToInt(const Common::String &Str, int &Result) { inline bool toInt(const Common::String &str, int &result) {
Common::String::const_iterator Iter = Str.begin(); Common::String::const_iterator iter = str.begin();
// Skip whitespaces // Skip whitespaces
while (*Iter && (*Iter == ' ' || *Iter == '\t')) { while (*iter && (*iter == ' ' || *iter == '\t')) {
++Iter; ++iter;
} }
if (Iter == Str.end()) return false; if (iter == str.end())
return false;
// Read sign, if available // Read sign, if available
bool IsNegative = false; bool isNegative = false;
if (*Iter == '-') { if (*iter == '-') {
IsNegative = true; isNegative = true;
++Iter; ++iter;
} else if (*Iter == '+') } else if (*iter == '+')
++Iter; ++iter;
// Skip whitespaces // Skip whitespaces
while (*Iter && (*Iter == ' ' || *Iter == '\t')) { while (*iter && (*iter == ' ' || *iter == '\t')) {
++Iter; ++iter;
} }
if (Iter == Str.end()) return false; if (iter == str.end())
return false;
// Convert string to integer // Convert string to integer
Result = 0; result = 0;
while (Iter != Str.end()) { while (iter != str.end()) {
if (*Iter < '0' || *Iter > '9') { if (*iter < '0' || *iter > '9') {
while (*Iter && (*Iter == ' ' || *Iter == '\t')) { while (*iter && (*iter == ' ' || *iter == '\t')) {
++Iter; ++iter;
} }
if (Iter != Str.end()) return false; if (iter != str.end())
return false;
break; break;
} }
Result = (Result * 10) + (*Iter - '0'); result = (result * 10) + (*iter - '0');
++Iter; ++iter;
} }
if (IsNegative) Result = -Result; if (isNegative)
result = -result;
return true; return true;
} }
inline bool ToBool(const Common::String &Str, bool &Result) { inline bool toBool(const Common::String &str, bool &result) {
if (Str == "true" || Str == "TRUE") { if (str == "true" || str == "TRUE") {
Result = true; result = true;
return true; return true;
} else if (Str == "false" || Str == "FALSE") { } else if (str == "false" || str == "FALSE") {
Result = false; result = false;
return true; return true;
} }
return false; return false;
} }
inline void ToLower(Common::String &Str) { inline void toLower(Common::String &str) {
Str.toLowercase(); str.toLowercase();
} }
} // End of namespace BS_String } // End of namespace BS_String

View file

@ -40,13 +40,13 @@
namespace Sword25 { namespace Sword25 {
// Erstellt ein Fenster des GUI des aktuellen Betriebssystems // Erstellt ein Fenster des GUI des aktuellen Betriebssystems
Window *Window::CreateBSWindow(int X, int Y, int Width, int Height, bool Visible) { Window *Window::createBSWindow(int x, int y, int width, int height, bool visible) {
// Fenster erstellen // Fenster erstellen
Window *pWindow = (Window *) new ScummVMWindow(X, Y, Width, Height, Visible); Window *pWindow = (Window *) new ScummVMWindow(x, y, width, height, visible);
// Falls das Fenster erfolgreich initialisiert wurde, wird ein Pointer auf das Fensterobjekt // Falls das Fenster erfolgreich initialisiert wurde, wird ein Pointer auf das Fensterobjekt
// zurückgegeben // zurückgegeben
if (pWindow->_InitSuccess) if (pWindow->_initSuccess)
return pWindow; return pWindow;
// Ansonsten wird das Fensterobjekt zerstört und NULL zurückgegeben // Ansonsten wird das Fensterobjekt zerstört und NULL zurückgegeben
@ -56,14 +56,14 @@ Window *Window::CreateBSWindow(int X, int Y, int Width, int Height, bool Visible
// Gibt True zurück wenn das Fenster WM_CLOSE empfangen hat - // Gibt True zurück wenn das Fenster WM_CLOSE empfangen hat -
// solange, bis RejectClose() aufgerufen wurde. // solange, bis RejectClose() aufgerufen wurde.
bool Window::CloseWanted() { bool Window::closeWanted() {
bool result = _CloseWanted; bool result = _closeWanted;
_CloseWanted = false; _closeWanted = false;
return result; return result;
} }
void Window::SetCloseWanted(bool Wanted) { void Window::setCloseWanted(bool wanted) {
_CloseWanted = Wanted; _closeWanted = wanted;
} }
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -44,13 +44,10 @@
#ifndef SWORD25_WINDOW_H #ifndef SWORD25_WINDOW_H
#define SWORD25_WINDOW_H #define SWORD25_WINDOW_H
// Includes
#include "sword25/kernel/common.h" #include "sword25/kernel/common.h"
namespace Sword25 { namespace Sword25 {
// Class definitions
/** /**
* A simple window class interface * A simple window class interface
* *
@ -59,8 +56,8 @@ namespace Sword25 {
*/ */
class Window { class Window {
protected: protected:
bool _InitSuccess; bool _initSuccess;
bool _CloseWanted; bool _closeWanted;
public: public:
virtual ~Window() {} virtual ~Window() {}
@ -68,97 +65,97 @@ public:
/** /**
* Returns the visibility of the window. * Returns the visibility of the window.
*/ */
virtual bool IsVisible() = 0; virtual bool isVisible() = 0;
/** /**
* Sets the visibility of the window * Sets the visibility of the window
* @param Visible Specifies whether the window should be visible or hidden * @param Visible Specifies whether the window should be visible or hidden
*/ */
virtual void SetVisible(bool Visible) = 0; virtual void setVisible(bool visible) = 0;
/** /**
* Returns the X position of the window * Returns the X position of the window
*/ */
virtual int GetX() = 0; virtual int getX() = 0;
/** /**
* Sets the X position of the window * Sets the X position of the window
* @paramX The new X position for the window, or -1 for centre aligned * @paramX The new X position for the window, or -1 for centre aligned
*/ */
virtual void SetX(int X) = 0; virtual void setX(int X) = 0;
/** /**
* Gets the Y position of the window * Gets the Y position of the window
*/ */
virtual int GetY() = 0; virtual int getY() = 0;
/** /**
* Sets the Y position of the window * Sets the Y position of the window
* @param Y The new Y position for the window, or -1 for centre aligned * @param Y The new Y position for the window, or -1 for centre aligned
*/ */
virtual void SetY(int X) = 0; virtual void setY(int X) = 0;
/** /**
* Returns the X position of the window's client area * Returns the X position of the window's client area
*/ */
virtual int GetClientX() = 0; virtual int getClientX() = 0;
/** /**
* Returns the Y position of the window's client area * Returns the Y position of the window's client area
*/ */
virtual int GetClientY() = 0; virtual int getClientY() = 0;
/** /**
* Returns the width of the window without the frame * Returns the width of the window without the frame
*/ */
virtual int GetWidth() = 0; virtual int getWidth() = 0;
/** /**
* Sets the width of the window without the frame * Sets the width of the window without the frame
*/ */
virtual void SetWidth(int Width) = 0; virtual void setWidth(int width) = 0;
/** /**
* Gets the height of the window without the frame * Gets the height of the window without the frame
*/ */
virtual int GetHeight() = 0; virtual int getHeight() = 0;
/** /**
* Sets the height of the window without the frame * Sets the height of the window without the frame
*/ */
virtual void SetHeight(int Height) = 0; virtual void setHeight(int height) = 0;
/** /**
* Returns the title of the window * Returns the title of the window
*/ */
virtual Common::String GetTitle() = 0; virtual Common::String getTitle() = 0;
/** /**
* Sets the title of the window * Sets the title of the window
* @param Title The new window title * @param Title The new window title
*/ */
virtual void SetTitle(const Common::String &Title) = 0; virtual void setTitle(const Common::String &title) = 0;
/** /**
* Handle the processing of any pending window messages. This method should be called * Handle the processing of any pending window messages. This method should be called
* during the main loop. * during the main loop.
*/ */
virtual bool ProcessMessages() = 0; virtual bool processMessages() = 0;
/** /**
* Pauses the applicaiton until the window has focus, or has been closed. * Pauses the applicaiton until the window has focus, or has been closed.
* Returns false if the window was closed. * Returns false if the window was closed.
*/ */
virtual bool WaitForFocus() = 0; virtual bool waitForFocus() = 0;
/** /**
* Returns true if the window has focus, false otherwise. * Returns true if the window has focus, false otherwise.
*/ */
virtual bool HasFocus() = 0; virtual bool hasFocus() = 0;
/** /**
* Returns the system handle that represents the window. Note that any use of the handle * Returns the system handle that represents the window. Note that any use of the handle
* will not be portable code. * will not be portable code.
*/ */
virtual uint GetWindowHandle() = 0; virtual uint getWindowHandle() = 0;
virtual void SetWindowAlive(bool v) = 0; virtual void setWindowAlive(bool v) = 0;
/** /**
* Specifies whether the window is wanted to be closed. This is used together with CloseWanted() * Specifies whether the window is wanted to be closed. This is used together with CloseWanted()
* to allow scripts to query when the main window should be closed, or the user is asking it to close * to allow scripts to query when the main window should be closed, or the user is asking it to close
**/ **/
void SetCloseWanted(bool Wanted); void setCloseWanted(bool wanted);
/** /**
* Returns the previous value set in a call to SetCloseWanted. * Returns the previous value set in a call to SetCloseWanted.
* Note that calling this also resets the value back to false, until such time as the SetCloseWanted() * Note that calling this also resets the value back to false, until such time as the SetCloseWanted()
* method is called again. * method is called again.
**/ **/
bool CloseWanted(); bool closeWanted();
/** /**
* Creates a new window instance. Returns a pointer to the window, or NULL if the creation failed. * Creates a new window instance. Returns a pointer to the window, or NULL if the creation failed.
@ -169,7 +166,7 @@ public:
* @param Height The height of the window without the frame * @param Height The height of the window without the frame
* @param Visible Specifies whether window should be visible * @param Visible Specifies whether window should be visible
*/ */
static Window *CreateBSWindow(int X, int Y, int Width, int Height, bool Visible); static Window *createBSWindow(int x, int y, int width, int height, bool visible);
}; };
} // End of namespace Sword25 } // End of namespace Sword25

View file

@ -360,7 +360,7 @@ static int r_setY(lua_State *L) {
} }
static void drawPolygon(const Polygon &polygon, uint color, const Vertex &offset) { static void drawPolygon(const Polygon &polygon, uint color, const Vertex &offset) {
GraphicEngine *pGE = Kernel::GetInstance()->GetGfx(); GraphicEngine *pGE = Kernel::getInstance()->getGfx();
BS_ASSERT(pGE); BS_ASSERT(pGE);
for (int i = 0; i < polygon.vertexCount - 1; i++) for (int i = 0; i < polygon.vertexCount - 1; i++)
@ -470,9 +470,9 @@ static const luaL_reg WALKREGION_METHODS[] = {
}; };
bool Geometry::registerScriptBindings() { bool Geometry::registerScriptBindings() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pScript = pKernel->GetScript(); ScriptEngine *pScript = pKernel->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast< lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast< lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -165,7 +165,7 @@ static void relaxEndPoint(const Vertex &curNodePos,
} }
template<class T> template<class T>
void ReverseArray(Common::Array<T> &arr) { void reverseArray(Common::Array<T> &arr) {
const uint size = arr.size(); const uint size = arr.size();
if (size < 2) if (size < 2)
return; return;
@ -216,7 +216,7 @@ bool WalkRegion::findPath(const Vertex &start, const Vertex &end, BS_Path &path)
// The nodes of the path must be untwisted, as they were extracted in reverse order. // The nodes of the path must be untwisted, as they were extracted in reverse order.
// This step could be saved if the path from end to the beginning was desired // This step could be saved if the path from end to the beginning was desired
ReverseArray<Vertex>(path); reverseArray<Vertex>(path);
return true; return true;
} }

View file

@ -154,7 +154,7 @@ byte *PackageManager::getFile(const Common::String &fileName, uint *fileSizePtr)
// Savegame loading logic // Savegame loading logic
Common::SaveFileManager *sfm = g_system->getSavefileManager(); Common::SaveFileManager *sfm = g_system->getSavefileManager();
Common::InSaveFile *file = sfm->openForLoading( Common::InSaveFile *file = sfm->openForLoading(
FileSystemUtil::GetInstance().GetPathFilename(fileName)); FileSystemUtil::getInstance().getPathFilename(fileName));
if (!file) { if (!file) {
BS_LOG_ERRORLN("Could not load savegame \"%s\".", fileName.c_str()); BS_LOG_ERRORLN("Could not load savegame \"%s\".", fileName.c_str());
return 0; return 0;

View file

@ -42,9 +42,9 @@
namespace Sword25 { namespace Sword25 {
static PackageManager *getPM() { static PackageManager *getPM() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
PackageManager *pPM = pKernel->GetPackage(); PackageManager *pPM = pKernel->getPackage();
BS_ASSERT(pPM); BS_ASSERT(pPM);
return pPM; return pPM;
} }
@ -197,9 +197,9 @@ static const luaL_reg PACKAGE_FUNCTIONS[] = {
}; };
bool PackageManager::registerScriptBindings() { bool PackageManager::registerScriptBindings() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pScript = pKernel->GetScript(); ScriptEngine *pScript = pKernel->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -47,7 +47,7 @@ static int warning(lua_State *L) {
lua_pushstring(L, "WARNING - "); lua_pushstring(L, "WARNING - ");
lua_pushvalue(L, 1); lua_pushvalue(L, 1);
lua_concat(L, 3); lua_concat(L, 3);
BS_Log::Log("%s\n", luaL_checkstring(L, -1)); BS_Log::log("%s\n", luaL_checkstring(L, -1));
lua_pop(L, 1); lua_pop(L, 1);
#ifdef DEBUG #ifdef DEBUG

View file

@ -151,7 +151,7 @@ bool LuaScriptEngine::executeFile(const Common::String &fileName) {
debug(2, "LuaScriptEngine::executeFile(%s)", fileName.c_str()); debug(2, "LuaScriptEngine::executeFile(%s)", fileName.c_str());
// Get a pointer to the package manager // Get a pointer to the package manager
PackageManager *pPackage = Kernel::GetInstance()->GetPackage(); PackageManager *pPackage = Kernel::getInstance()->getPackage();
BS_ASSERT(pPackage); BS_ASSERT(pPackage);
// File read // File read

View file

@ -157,7 +157,7 @@ bool SoundEngine::playSound(const Common::String &fileName, SOUND_TYPES type, fl
} }
uint SoundEngine::playSoundEx(const Common::String &fileName, SOUND_TYPES type, float volume, float pan, bool loop, int loopStart, int loopEnd, uint layer) { uint SoundEngine::playSoundEx(const Common::String &fileName, SOUND_TYPES type, float volume, float pan, bool loop, int loopStart, int loopEnd, uint layer) {
Common::SeekableReadStream *in = Kernel::GetInstance()->GetPackage()->getStream(fileName); Common::SeekableReadStream *in = Kernel::getInstance()->getPackage()->getStream(fileName);
Audio::SeekableAudioStream *stream = Audio::makeVorbisStream(in, DisposeAfterUse::YES); Audio::SeekableAudioStream *stream = Audio::makeVorbisStream(in, DisposeAfterUse::YES);
uint id; uint id;
SndHandle *handle = getHandle(&id); SndHandle *handle = getHandle(&id);

View file

@ -46,9 +46,9 @@
namespace Sword25 { namespace Sword25 {
static int init(lua_State *L) { static int init(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
if (lua_gettop(L) == 0) if (lua_gettop(L) == 0)
@ -62,9 +62,9 @@ static int init(lua_State *L) {
} }
static int update(lua_State *L) { static int update(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->update(); pSfx->update();
@ -73,9 +73,9 @@ static int update(lua_State *L) {
} }
static int setVolume(lua_State *L) { static int setVolume(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->setVolume(static_cast<float>(luaL_checknumber(L, 1)), pSfx->setVolume(static_cast<float>(luaL_checknumber(L, 1)),
@ -85,9 +85,9 @@ static int setVolume(lua_State *L) {
} }
static int getVolume(lua_State *L) { static int getVolume(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
lua_pushnumber(L, pSfx->getVolume(static_cast<SoundEngine::SOUND_TYPES>(static_cast<uint>(luaL_checknumber(L, 1))))); lua_pushnumber(L, pSfx->getVolume(static_cast<SoundEngine::SOUND_TYPES>(static_cast<uint>(luaL_checknumber(L, 1)))));
@ -96,9 +96,9 @@ static int getVolume(lua_State *L) {
} }
static int pauseAll(lua_State *L) { static int pauseAll(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->pauseAll(); pSfx->pauseAll();
@ -107,9 +107,9 @@ static int pauseAll(lua_State *L) {
} }
static int resumeAll(lua_State *L) { static int resumeAll(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->resumeAll(); pSfx->resumeAll();
@ -118,9 +118,9 @@ static int resumeAll(lua_State *L) {
} }
static int pauseLayer(lua_State *L) { static int pauseLayer(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->pauseLayer(static_cast<int>(luaL_checknumber(L, 1))); pSfx->pauseLayer(static_cast<int>(luaL_checknumber(L, 1)));
@ -129,9 +129,9 @@ static int pauseLayer(lua_State *L) {
} }
static int resumeLayer(lua_State *L) { static int resumeLayer(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->resumeLayer(static_cast<int>(luaL_checknumber(L, 1))); pSfx->resumeLayer(static_cast<int>(luaL_checknumber(L, 1)));
@ -176,9 +176,9 @@ static void processPlayParams(lua_State *L, Common::String &fileName, SoundEngin
} }
static int playSound(lua_State *L) { static int playSound(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
Common::String fileName; Common::String fileName;
@ -197,9 +197,9 @@ static int playSound(lua_State *L) {
} }
static int playSoundEx(lua_State *L) { static int playSoundEx(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
Common::String fileName; Common::String fileName;
@ -218,9 +218,9 @@ static int playSoundEx(lua_State *L) {
} }
static int setSoundVolume(lua_State *L) { static int setSoundVolume(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->setSoundVolume(static_cast<uint>(luaL_checknumber(L, 1)), static_cast<float>(luaL_checknumber(L, 2))); pSfx->setSoundVolume(static_cast<uint>(luaL_checknumber(L, 1)), static_cast<float>(luaL_checknumber(L, 2)));
@ -229,9 +229,9 @@ static int setSoundVolume(lua_State *L) {
} }
static int setSoundPanning(lua_State *L) { static int setSoundPanning(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->setSoundPanning(static_cast<uint>(luaL_checknumber(L, 1)), static_cast<float>(luaL_checknumber(L, 2))); pSfx->setSoundPanning(static_cast<uint>(luaL_checknumber(L, 1)), static_cast<float>(luaL_checknumber(L, 2)));
@ -240,9 +240,9 @@ static int setSoundPanning(lua_State *L) {
} }
static int pauseSound(lua_State *L) { static int pauseSound(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->pauseSound(static_cast<uint>(luaL_checknumber(L, 1))); pSfx->pauseSound(static_cast<uint>(luaL_checknumber(L, 1)));
@ -251,9 +251,9 @@ static int pauseSound(lua_State *L) {
} }
static int resumeSound(lua_State *L) { static int resumeSound(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->resumeSound(static_cast<uint>(luaL_checknumber(L, 1))); pSfx->resumeSound(static_cast<uint>(luaL_checknumber(L, 1)));
@ -262,9 +262,9 @@ static int resumeSound(lua_State *L) {
} }
static int stopSound(lua_State *L) { static int stopSound(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
pSfx->stopSound(static_cast<uint>(luaL_checknumber(L, 1))); pSfx->stopSound(static_cast<uint>(luaL_checknumber(L, 1)));
@ -273,9 +273,9 @@ static int stopSound(lua_State *L) {
} }
static int isSoundPaused(lua_State *L) { static int isSoundPaused(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
lua_pushbooleancpp(L, pSfx->isSoundPaused(static_cast<uint>(luaL_checknumber(L, 1)))); lua_pushbooleancpp(L, pSfx->isSoundPaused(static_cast<uint>(luaL_checknumber(L, 1))));
@ -284,9 +284,9 @@ static int isSoundPaused(lua_State *L) {
} }
static int isSoundPlaying(lua_State *L) { static int isSoundPlaying(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
lua_pushbooleancpp(L, pSfx->isSoundPlaying(static_cast<uint>(luaL_checknumber(L, 1)))); lua_pushbooleancpp(L, pSfx->isSoundPlaying(static_cast<uint>(luaL_checknumber(L, 1))));
@ -295,9 +295,9 @@ static int isSoundPlaying(lua_State *L) {
} }
static int getSoundVolume(lua_State *L) { static int getSoundVolume(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
lua_pushnumber(L, pSfx->getSoundVolume(static_cast<uint>(luaL_checknumber(L, 1)))); lua_pushnumber(L, pSfx->getSoundVolume(static_cast<uint>(luaL_checknumber(L, 1))));
@ -306,9 +306,9 @@ static int getSoundVolume(lua_State *L) {
} }
static int getSoundPanning(lua_State *L) { static int getSoundPanning(lua_State *L) {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
SoundEngine *pSfx = pKernel->GetSfx(); SoundEngine *pSfx = pKernel->getSfx();
BS_ASSERT(pSfx); BS_ASSERT(pSfx);
lua_pushnumber(L, pSfx->getSoundPanning(static_cast<uint>(luaL_checknumber(L, 1)))); lua_pushnumber(L, pSfx->getSoundPanning(static_cast<uint>(luaL_checknumber(L, 1))));
@ -349,9 +349,9 @@ static const lua_constant_reg SFX_CONSTANTS[] = {
}; };
bool SoundEngine::registerScriptBindings() { bool SoundEngine::registerScriptBindings() {
Kernel *pKernel = Kernel::GetInstance(); Kernel *pKernel = Kernel::getInstance();
BS_ASSERT(pKernel); BS_ASSERT(pKernel);
ScriptEngine *pScript = pKernel->GetScript(); ScriptEngine *pScript = pKernel->getScript();
BS_ASSERT(pScript); BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject()); lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L); BS_ASSERT(L);

View file

@ -90,13 +90,13 @@ Common::Error Sword25Engine::appStart() {
return Common::kUnsupportedColorMode; return Common::kUnsupportedColorMode;
// Kernel initialization // Kernel initialization
if (!Kernel::GetInstance()->GetInitSuccess()) { if (!Kernel::getInstance()->getInitSuccess()) {
BS_LOG_ERRORLN("Kernel initialization failed."); BS_LOG_ERRORLN("Kernel initialization failed.");
return Common::kUnknownError; return Common::kUnknownError;
} }
// Package-Manager starten, damit die Packfiles geladen werden können. // Package-Manager starten, damit die Packfiles geladen werden können.
PackageManager *packageManagerPtr = static_cast<PackageManager *>(Kernel::GetInstance()->NewService("package", PACKAGE_MANAGER)); PackageManager *packageManagerPtr = static_cast<PackageManager *>(Kernel::getInstance()->newService("package", PACKAGE_MANAGER));
if (!packageManagerPtr) { if (!packageManagerPtr) {
BS_LOG_ERRORLN("PackageManager initialization failed."); BS_LOG_ERRORLN("PackageManager initialization failed.");
return Common::kUnknownError; return Common::kUnknownError;
@ -112,7 +112,7 @@ Common::Error Sword25Engine::appStart() {
} }
// Einen Pointer auf den Skript-Engine holen. // Einen Pointer auf den Skript-Engine holen.
ScriptEngine *scriptPtr = Kernel::GetInstance()->GetScript(); ScriptEngine *scriptPtr = Kernel::getInstance()->getScript();
if (!scriptPtr) { if (!scriptPtr) {
BS_LOG_ERRORLN("Script intialization failed."); BS_LOG_ERRORLN("Script intialization failed.");
return Common::kUnknownError; return Common::kUnknownError;
@ -126,7 +126,7 @@ Common::Error Sword25Engine::appStart() {
bool Sword25Engine::appMain() { bool Sword25Engine::appMain() {
// The main script start. This script loads all the other scripts and starts the actual game. // The main script start. This script loads all the other scripts and starts the actual game.
ScriptEngine *scriptPtr = Kernel::GetInstance()->GetScript(); ScriptEngine *scriptPtr = Kernel::getInstance()->getScript();
BS_ASSERT(scriptPtr); BS_ASSERT(scriptPtr);
scriptPtr->executeFile(DEFAULT_SCRIPT_FILE); scriptPtr->executeFile(DEFAULT_SCRIPT_FILE);
@ -135,20 +135,20 @@ bool Sword25Engine::appMain() {
bool Sword25Engine::appEnd() { bool Sword25Engine::appEnd() {
// The kernel is shutdown, and un-initialises all subsystems // The kernel is shutdown, and un-initialises all subsystems
Kernel::DeleteInstance(); Kernel::deleteInstance();
AnimationTemplateRegistry::destroy(); AnimationTemplateRegistry::destroy();
RenderObjectRegistry::destroy(); RenderObjectRegistry::destroy();
RegionRegistry::destroy(); RegionRegistry::destroy();
// Free the log file if it was used // Free the log file if it was used
BS_Log::_CloseLog(); BS_Log::closeLog();
return true; return true;
} }
bool Sword25Engine::loadPackages() { bool Sword25Engine::loadPackages() {
PackageManager *packageManagerPtr = Kernel::GetInstance()->GetPackage(); PackageManager *packageManagerPtr = Kernel::getInstance()->getPackage();
BS_ASSERT(packageManagerPtr); BS_ASSERT(packageManagerPtr);
// Load the main package // Load the main package