scripts are now more error prone
master
Eduardo Bart 13 years ago
parent e611734396
commit 96e0b1e909

@ -6,7 +6,7 @@ SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}")
# find needed packages # find needed packages
SET(Boost_USE_STATIC_LIBS ON) SET(Boost_USE_STATIC_LIBS ON)
SET(Boost_USE_MULTITHREADED ON) SET(Boost_USE_MULTITHREADED ON)
FIND_PACKAGE(Boost COMPONENTS system regex signals REQUIRED) FIND_PACKAGE(Boost COMPONENTS system signals REQUIRED)
FIND_PACKAGE(OpenGL REQUIRED) FIND_PACKAGE(OpenGL REQUIRED)
FIND_PACKAGE(Lua51 REQUIRED) FIND_PACKAGE(Lua51 REQUIRED)
FIND_PACKAGE(YamlCpp REQUIRED) FIND_PACKAGE(YamlCpp REQUIRED)

@ -9,7 +9,7 @@ end
function MainMenu_enterGameClicked() function MainMenu_enterGameClicked()
enterGameWindow = loadUI("modules/mainmenu/entergamewindow.yml") enterGameWindow = loadUI("modules/mainmenu/entergamewindow.yml")
enterGameWindow:getParent():lock(enterGameWindow) button = enterGameWindow:getChildByID("okButton")
end end
function MainMenu_optionsClicked() function MainMenu_optionsClicked()

@ -54,7 +54,7 @@ bool Configs::load(const std::string& fileName)
m_confsMap[key] = value; m_confsMap[key] = value;
} }
} catch (YAML::Exception& e) { } catch (YAML::Exception& e) {
logError("Malformed config file: %s", e.what()); flogError("ERROR: Malformed config file: %s", e.what());
return false; return false;
} }
@ -102,7 +102,7 @@ const std::string &Configs::getString(const std::string &key) const
{ {
auto it = m_confsMap.find(key); auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) { if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str()); flogWarning("WARNING: Config value %s not found", key.c_str());
static std::string emptystr; static std::string emptystr;
return emptystr; return emptystr;
} }
@ -113,7 +113,7 @@ float Configs::getFloat(const std::string &key) const
{ {
auto it = m_confsMap.find(key); auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) { if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str()); flogWarning("WARNING: Config value %s not found", key.c_str());
return 0; return 0;
} }
return convertType<float, std::string>(it->second); return convertType<float, std::string>(it->second);
@ -123,7 +123,7 @@ bool Configs::getBoolean(const std::string &key) const
{ {
auto it = m_confsMap.find(key); auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) { if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str()); flogWarning("WARNING: Config value %s not found", key.c_str());
return 0; return 0;
} }
return (it->second == "true"); return (it->second == "true");
@ -133,7 +133,7 @@ int Configs::getInteger(const std::string &key) const
{ {
auto it = m_confsMap.find(key); auto it = m_confsMap.find(key);
if(it == m_confsMap.end()) { if(it == m_confsMap.end()) {
logWarning("Config value %s not found", key.c_str()); flogWarning("WARNING: Config value %s not found", key.c_str());
return 0; return 0;
} }
return convertType<int, std::string>(it->second); return convertType<int, std::string>(it->second);

@ -41,12 +41,12 @@ void Dispatcher::poll()
} }
} }
void Dispatcher::scheduleTask(const Callback& callback, int delay) void Dispatcher::scheduleTask(const SimpleCallback& callback, int delay)
{ {
m_taskList.push(new Task(g_engine.getCurrentFrameTicks() + delay, callback)); m_taskList.push(new Task(g_engine.getCurrentFrameTicks() + delay, callback));
} }
void Dispatcher::addTask(const Callback& callback) void Dispatcher::addTask(const SimpleCallback& callback)
{ {
m_taskList.push(new Task(callback)); m_taskList.push(new Task(callback));
} }

@ -29,11 +29,11 @@
class Task { class Task {
public: public:
inline Task(const Callback& _callback) : ticks(0), callback(_callback) { } inline Task(const SimpleCallback& _callback) : ticks(0), callback(_callback) { }
inline Task(int _ticks, const Callback& _callback) : ticks(_ticks), callback(_callback) { } inline Task(int _ticks, const SimpleCallback& _callback) : ticks(_ticks), callback(_callback) { }
inline bool operator<(const Task& other) const { return ticks > other.ticks; } inline bool operator<(const Task& other) const { return ticks > other.ticks; }
int ticks; int ticks;
Callback callback; SimpleCallback callback;
}; };
class lessTask : public std::binary_function<Task*&, Task*&, bool> { class lessTask : public std::binary_function<Task*&, Task*&, bool> {
@ -50,10 +50,10 @@ public:
void poll(); void poll();
/// Add an event /// Add an event
void addTask(const Callback& callback); void addTask(const SimpleCallback& callback);
/// Schedula an event /// Schedula an event
void scheduleTask(const Callback& callback, int delay); void scheduleTask(const SimpleCallback& callback, int delay);
private: private:
std::priority_queue<Task*, std::vector<Task*>, lessTask> m_taskList; std::priority_queue<Task*, std::vector<Task*>, lessTask> m_taskList;

@ -87,7 +87,7 @@ void Engine::run()
frameCount = 0; frameCount = 0;
// update fps text // update fps text
fpsText = format("FPS: %d", fps); fpsText = f("FPS: %d", fps);
fpsTextSize = defaultFont->calculateTextRectSize(fpsText); fpsTextSize = defaultFont->calculateTextRectSize(fpsText);
} }
} }

@ -63,7 +63,7 @@ public:
/// Return the current ticks on this frame /// Return the current ticks on this frame
int getCurrentFrameTicks() const { return m_lastFrameTicks; } int getCurrentFrameTicks() const { return m_lastFrameTicks; }
void setOnClose(Callback onCloseCallback) { m_onCloseCallback = onCloseCallback; } void setOnClose(SimpleCallback onCloseCallback) { m_onCloseCallback = onCloseCallback; }
private: private:
bool m_stopping; bool m_stopping;
@ -72,7 +72,7 @@ private:
int m_lastFrameTicks; int m_lastFrameTicks;
Callback m_onCloseCallback; SimpleCallback m_onCloseCallback;
}; };
extern Engine g_engine; extern Engine g_engine;

@ -44,14 +44,14 @@ bool Resources::setWriteDir(const std::string& path)
bool ret = (bool)PHYSFS_setWriteDir(path.c_str()); bool ret = (bool)PHYSFS_setWriteDir(path.c_str());
if(!ret) if(!ret)
logError("Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str()); flogError("ERROR: Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str());
return ret; return ret;
} }
bool Resources::addToSearchPath(const std::string& path, bool insertInFront /*= true*/) bool Resources::addToSearchPath(const std::string& path, bool insertInFront /*= true*/)
{ {
if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1)) { if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1)) {
logError("Error while adding \"%s\" to resources search path: %s", path.c_str(), PHYSFS_getLastError()); flogError("ERROR: Error while adding \"%s\" to resources search path: %s", path.c_str() % PHYSFS_getLastError());
return false; return false;
} }
return true; return true;
@ -66,7 +66,7 @@ uchar *Resources::loadFile(const std::string& fileName, uint *fileSize)
{ {
PHYSFS_file *file = PHYSFS_openRead(fileName.c_str()); PHYSFS_file *file = PHYSFS_openRead(fileName.c_str());
if(!file) { if(!file) {
logError("Failed to load file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError()); flogError("ERROR: Failed to load file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError());
*fileSize = 0; *fileSize = 0;
return NULL; return NULL;
} }
@ -95,7 +95,7 @@ bool Resources::saveFile(const std::string &fileName, const uchar *data, uint si
{ {
PHYSFS_file *file = PHYSFS_openWrite(fileName.c_str()); PHYSFS_file *file = PHYSFS_openWrite(fileName.c_str());
if(!file) { if(!file) {
logError("Failed to save file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError()); flogError("ERROR: Failed to save file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError());
return false; return false;
} }

@ -68,7 +68,7 @@ bool Font::load(const std::string& file)
{ {
std::string fileContents = g_resources.loadTextFile(file); std::string fileContents = g_resources.loadTextFile(file);
if(!fileContents.size()) { if(!fileContents.size()) {
logError("Coult not load font file \"%s", file.c_str()); flogError("ERROR: Coult not load font file \"%s", file.c_str());
return false; return false;
} }
@ -96,7 +96,7 @@ bool Font::load(const std::string& file)
// load texture // load texture
m_texture = g_textures.get("fonts/" + textureName); m_texture = g_textures.get("fonts/" + textureName);
if(!m_texture) { if(!m_texture) {
logError("Failed to load image for font file \"%s\"", file.c_str()); flogError("ERROR: Failed to load image for font file \"%s\"", file.c_str());
return false; return false;
} }
@ -123,7 +123,7 @@ bool Font::load(const std::string& file)
m_glyphHeight); m_glyphHeight);
} }
} catch (YAML::Exception& e) { } catch (YAML::Exception& e) {
logError("Malformed font file \"%s\":\n %s", file.c_str(), e.what()); flogError("ERROR: Malformed font file \"%s\":\n %s", file.c_str() % e.what());
return false; return false;
} }

@ -47,7 +47,7 @@ void Fonts::init(const std::string& defaultFontName)
} }
if(!m_defaultFont) if(!m_defaultFont)
logFatal("Could not load the default font \"%s\"\n", defaultFontName.c_str()); flogFatal("FATAL ERROR: Could not load the default font \"%s\"\n", defaultFontName.c_str());
} }
Font* Fonts::get(const std::string& fontName) Font* Fonts::get(const std::string& fontName)
@ -58,6 +58,6 @@ Font* Fonts::get(const std::string& fontName)
return (*it).get(); return (*it).get();
} }
logError("Font \"%s\" not found, returing the default one", fontName.c_str()); flogError("ERROR: Font \"%s\" not found, returing the default one", fontName.c_str());
return m_defaultFont.get(); return m_defaultFont.get();
} }

@ -43,8 +43,8 @@ void Graphics::init()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
logInfo("GPU %s", (const char*)glGetString(GL_RENDERER)); flogInfo("GPU %s", (const char*)glGetString(GL_RENDERER));
logInfo("OpenGL %s", (const char*)glGetString(GL_VERSION)); flogInfo("OpenGL %s", (const char*)glGetString(GL_VERSION));
} }
void Graphics::terminate() void Graphics::terminate()

@ -46,18 +46,18 @@ TexturePtr Textures::get(const std::string& textureFile)
if(!texture) { if(!texture) {
// currently only png textures are supported // currently only png textures are supported
if(!boost::ends_with(textureFile, ".png")) if(!boost::ends_with(textureFile, ".png"))
logFatal("Unable to load texture %s, file format no supported.", textureFile.c_str()); flogFatal("FATAL ERROR: Unable to load texture %s, file format no supported.", textureFile.c_str());
// load texture file data // load texture file data
uint fileSize; uint fileSize;
uchar *textureFileData = g_resources.loadFile(textureFile, &fileSize); uchar *textureFileData = g_resources.loadFile(textureFile, &fileSize);
if(!textureFileData) if(!textureFileData)
logFatal("Unable to load texture %s, file could not be read.", textureFile.c_str()); flogFatal("FATAL ERROR: Unable to load texture %s, file could not be read.", textureFile.c_str());
// load the texture // load the texture
texture = TexturePtr(TextureLoader::loadPNG(textureFileData)); texture = TexturePtr(TextureLoader::loadPNG(textureFileData));
if(!texture) if(!texture)
logFatal("Unable to load texture %s", textureFile.c_str()); flogFatal("FATAL ERROR: Unable to load texture %s", textureFile.c_str());
delete[] textureFileData; delete[] textureFileData;
} }

@ -40,7 +40,7 @@ void Connection::poll()
ioService.reset(); ioService.reset();
} }
void Connection::connect(const std::string& host, uint16 port, const Callback& callback) void Connection::connect(const std::string& host, uint16 port, const SimpleCallback& callback)
{ {
m_connectCallback = callback; m_connectCallback = callback;
m_connectionState = CONNECTION_STATE_RESOLVING; m_connectionState = CONNECTION_STATE_RESOLVING;

@ -37,7 +37,7 @@ public:
static void poll(); static void poll();
void connect(const std::string& host, uint16 port, const Callback& callback); void connect(const std::string& host, uint16 port, const SimpleCallback& callback);
void setErrorCallback(const ErrorCallback& errorCallback) { m_errorCallback = errorCallback; } void setErrorCallback(const ErrorCallback& errorCallback) { m_errorCallback = errorCallback; }
void onTimeout(const boost::system::error_code& error); void onTimeout(const boost::system::error_code& error);
@ -53,7 +53,7 @@ public:
private: private:
ErrorCallback m_errorCallback; ErrorCallback m_errorCallback;
Callback m_connectCallback; SimpleCallback m_connectCallback;
ConnectionState_t m_connectionState; ConnectionState_t m_connectionState;
boost::asio::deadline_timer m_timer; boost::asio::deadline_timer m_timer;

@ -30,14 +30,14 @@ Protocol::Protocol() :
m_connection->setErrorCallback(boost::bind(&Protocol::onError, this, _1)); m_connection->setErrorCallback(boost::bind(&Protocol::onError, this, _1));
} }
void Protocol::connect(const std::string& host, uint16 port, const Callback& callback) void Protocol::connect(const std::string& host, uint16 port, const SimpleCallback& callback)
{ {
m_connection->connect(host, port, callback); m_connection->connect(host, port, callback);
} }
void Protocol::onError(const boost::system::error_code& error) void Protocol::onError(const boost::system::error_code& error)
{ {
logError(error.message().c_str()); flogError("PROTOCOL ERROR: ", error.message());
// invalid hostname // invalid hostname
// connection timeouted // connection timeouted

@ -32,7 +32,7 @@ class Protocol
public: public:
Protocol(); Protocol();
void connect(const std::string& host, uint16 port, const Callback& callback); void connect(const std::string& host, uint16 port, const SimpleCallback& callback);
virtual void onError(const boost::system::error_code& error); virtual void onError(const boost::system::error_code& error);

@ -211,7 +211,7 @@ void Platform::init(const char *appName)
wc.lpszClassName = win32.appName.c_str(); // Set The Class Name wc.lpszClassName = win32.appName.c_str(); // Set The Class Name
if(!RegisterClassA(&wc)) if(!RegisterClassA(&wc))
logFatal("Failed to register the window class."); logFatal("FATAL ERROR: Failed to register the window class.");
// force first tick // force first tick
Platform::getTicks(); Platform::getTicks();
@ -226,7 +226,7 @@ void Platform::terminate()
if(win32.instance) { if(win32.instance) {
if(!UnregisterClassA(win32.appName.c_str(), win32.instance)) if(!UnregisterClassA(win32.appName.c_str(), win32.instance))
logError("Unregister class failed."); logError("ERROR: Unregister class failed.");
win32.instance = NULL; win32.instance = NULL;
} }
@ -286,7 +286,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
if(!win32.window) { if(!win32.window) {
terminate(); terminate();
logFatal("Window creation error."); logFatal("FATAL ERROR: Window creation error.");
return false; return false;
} }
@ -315,31 +315,31 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
if(!(win32.hdc = GetDC(win32.window))) { if(!(win32.hdc = GetDC(win32.window))) {
terminate(); terminate();
logFatal("Can't Create A GL Device Context."); logFatal("FATAL ERROR: Can't Create A GL Device Context.");
return false; return false;
} }
if(!(pixelFormat = ChoosePixelFormat(win32.hdc, &pfd))) { if(!(pixelFormat = ChoosePixelFormat(win32.hdc, &pfd))) {
terminate(); terminate();
logFatal("Can't Find A Suitable PixelFormat."); logFatal("FATAL ERROR: Can't Find A Suitable PixelFormat.");
return false; return false;
} }
if(!SetPixelFormat(win32.hdc, pixelFormat, &pfd)) { if(!SetPixelFormat(win32.hdc, pixelFormat, &pfd)) {
terminate(); terminate();
logFatal("Can't Set The PixelFormat."); logFatal("FATAL ERROR: Can't Set The PixelFormat.");
return false; return false;
} }
if(!(win32.hrc = wglCreateContext(win32.hdc))) { if(!(win32.hrc = wglCreateContext(win32.hdc))) {
terminate(); terminate();
logFatal("Can't Create A GL Rendering Context."); logFatal("FATAL ERROR: Can't Create A GL Rendering Context.");
return false; return false;
} }
if(!wglMakeCurrent(win32.hdc, win32.hrc)) { if(!wglMakeCurrent(win32.hdc, win32.hrc)) {
terminate(); terminate();
logFatal("Can't Activate The GL Rendering Context."); logFatal("FATAL ERROR: Can't Activate The GL Rendering Context.");
return false; return false;
} }
@ -350,24 +350,24 @@ void Platform::destroyWindow()
{ {
if(win32.hrc) { if(win32.hrc) {
if(!wglMakeCurrent(NULL, NULL)) if(!wglMakeCurrent(NULL, NULL))
logError("Release Of DC And RC Failed."); logError("ERROR: Release Of DC And RC Failed.");
if(!wglDeleteContext(win32.hrc)) if(!wglDeleteContext(win32.hrc))
logError("Release Rendering Context Failed."); logError("ERROR: Release Rendering Context Failed.");
win32.hrc = NULL; win32.hrc = NULL;
} }
if(win32.hdc) { if(win32.hdc) {
if(!ReleaseDC(win32.window, win32.hdc)) if(!ReleaseDC(win32.window, win32.hdc))
logError("Release Device Context Failed."); logError("ERROR: Release Device Context Failed.");
win32.hdc = NULL; win32.hdc = NULL;
} }
if(win32.window) { if(win32.window) {
if(!DestroyWindow(win32.window)) if(!DestroyWindow(win32.window))
logError("Destroy window failed."); logError("ERROR: Destroy window failed.");
win32.window = NULL; win32.window = NULL;
} }
@ -502,7 +502,7 @@ std::string Platform::getAppUserDir()
std::stringstream sdir; std::stringstream sdir;
sdir << PHYSFS_getUserDir() << "/." << win32.appName << "/"; sdir << PHYSFS_getUserDir() << "/." << win32.appName << "/";
if((mkdir(sdir.str().c_str()) != 0) && (errno != EEXIST)) if((mkdir(sdir.str().c_str()) != 0) && (errno != EEXIST))
logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); logError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
return sdir.str(); return sdir.str();
} }

@ -234,18 +234,18 @@ void Platform::init(const char *appName)
// open display // open display
x11.display = XOpenDisplay(0); x11.display = XOpenDisplay(0);
if(!x11.display) if(!x11.display)
logFatal("Failed to open X display"); logFatal("FATAL ERROR: Failed to open X display");
// check if GLX is supported on this display // check if GLX is supported on this display
if(!glXQueryExtension(x11.display, 0, 0)) if(!glXQueryExtension(x11.display, 0, 0))
logFatal("GLX not supported"); logFatal("FATAL ERROR: GLX not supported");
// retrieve GLX version // retrieve GLX version
int glxMajor; int glxMajor;
int glxMinor; int glxMinor;
if(!glXQueryVersion(x11.display, &glxMajor, &glxMinor)) if(!glXQueryVersion(x11.display, &glxMajor, &glxMinor))
logFatal("Unable to query GLX version"); logFatal("FATAL ERROR: Unable to query GLX version");
logInfo("GLX version %d.%d", glxMajor, glxMinor); flogInfo("GLX version %d.%d", glxMajor % glxMinor);
// clipboard related atoms // clipboard related atoms
x11.atomClipboard = XInternAtom(x11.display, "CLIPBOARD", False); x11.atomClipboard = XInternAtom(x11.display, "CLIPBOARD", False);
@ -497,12 +497,12 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
// choose OpenGL, RGBA, double buffered, visual // choose OpenGL, RGBA, double buffered, visual
x11.visual = glXChooseVisual(x11.display, DefaultScreen(x11.display), attrList); x11.visual = glXChooseVisual(x11.display, DefaultScreen(x11.display), attrList);
if(!x11.visual) if(!x11.visual)
logFatal("RGBA/Double buffered visual not supported"); logFatal("FATAL ERROR: RGBA/Double buffered visual not supported");
// create GLX context // create GLX context
x11.glxContext = glXCreateContext(x11.display, x11.visual, 0, GL_TRUE); x11.glxContext = glXCreateContext(x11.display, x11.visual, 0, GL_TRUE);
if(!x11.glxContext) if(!x11.glxContext)
logFatal("Unable to create GLX context"); logFatal("FATAL ERROR: Unable to create GLX context");
// color map // color map
x11.colormap = XCreateColormap(x11.display, x11.colormap = XCreateColormap(x11.display,
@ -535,7 +535,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
&wa); &wa);
if(!x11.window) if(!x11.window)
logFatal("Unable to create X window"); logFatal("FATAL ERROR: Unable to create X window");
// create input context (to have better key input handling) // create input context (to have better key input handling)
if(XSupportsLocale()) { if(XSupportsLocale()) {
@ -547,11 +547,11 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i
XIMPreeditNothing | XIMStatusNothing, XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, x11.window, NULL); XNClientWindow, x11.window, NULL);
if(!x11.xic) if(!x11.xic)
logError("Unable to create the input context"); logError("ERROR: Unable to create the input context");
} else } else
logError("Failed to open an input method"); logError("ERROR: Failed to open an input method");
} else } else
logError("X11 does not support the current locale"); logError("ERROR: X11 does not support the current locale");
if(!x11.xic) if(!x11.xic)
logWarning("Input of special keys maybe messed up because we couldn't create an input context"); logWarning("Input of special keys maybe messed up because we couldn't create an input context");
@ -836,6 +836,6 @@ std::string Platform::getAppUserDir()
std::stringstream sdir; std::stringstream sdir;
sdir << PHYSFS_getUserDir() << "/." << x11.appName << "/"; sdir << PHYSFS_getUserDir() << "/." << x11.appName << "/";
if((mkdir(sdir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) && (errno != EEXIST)) if((mkdir(sdir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) && (errno != EEXIST))
logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); flogError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str());
return sdir.str(); return sdir.str();
} }

@ -62,7 +62,6 @@ typedef int8_t int8;
// boost utilities // boost utilities
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <boost/bind.hpp> #include <boost/bind.hpp>
#include <boost/function.hpp> #include <boost/function.hpp>
@ -72,7 +71,7 @@ typedef int8_t int8;
#include <boost/signals.hpp> #include <boost/signals.hpp>
#define foreach BOOST_FOREACH #define foreach BOOST_FOREACH
typedef boost::function<void()> Callback; typedef boost::function<void()> SimpleCallback;
// yaml // yaml
#include <yaml-cpp/yaml.h> #include <yaml-cpp/yaml.h>

@ -61,12 +61,19 @@ int LuaScript::lua_loadUI()
{ {
UIContainerPtr parent; UIContainerPtr parent;
if(getStackSize() > 1) { if(getStackSize() > 1) {
parent = boost::static_pointer_cast<UIContainer>(popClassInstance()); parent = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
} else { } else {
parent = UIContainer::getRootContainer(); parent = UIContainer::getRootContainer();
} }
std::string uiFile = popString(); std::string uiFile = popString();
UIElementPtr element = UILoader::loadFile(uiFile.c_str(), parent);
UIElementPtr element;
if(parent)
element = UILoader::loadFile(uiFile.c_str(), parent);
else
reportErrorWithTraceback("invalid parent container");
pushClassInstance(element); pushClassInstance(element);
return 1; return 1;
} }
@ -78,7 +85,6 @@ int LuaScript::lua_getUIRootContainer()
return 1; return 1;
} }
int LuaScript::lua_setOnApplicationClose() int LuaScript::lua_setOnApplicationClose()
{ {
int funcRef = popFunction(); int funcRef = popFunction();
@ -91,7 +97,7 @@ int LuaScript::lua_setOnApplicationClose()
int LuaScript::lua_UIElement_destroy() int LuaScript::lua_UIElement_destroy()
{ {
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance()); UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
if(element) if(element)
element->destroy(); element->destroy();
else else
@ -101,7 +107,7 @@ int LuaScript::lua_UIElement_destroy()
int LuaScript::lua_UIElement_getParent() int LuaScript::lua_UIElement_getParent()
{ {
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance()); UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
if(element) if(element)
pushClassInstance(element->getParent()); pushClassInstance(element->getParent());
else else
@ -111,13 +117,13 @@ int LuaScript::lua_UIElement_getParent()
int LuaScript::lua_UIButton_setOnClick() int LuaScript::lua_UIButton_setOnClick()
{ {
lua_insert(L, -2); moveTop(-2);
UIButtonPtr button = boost::static_pointer_cast<UIButton>(popClassInstance()); UIButtonPtr button = boost::dynamic_pointer_cast<UIButton>(popClassInstance());
if(button) { if(button) {
int funcRef = popFunction(); int funcRef = popFunction();
button->setOnClick([this, funcRef](UIButtonPtr button) { button->setOnClick([this, funcRef](UIButtonPtr button) {
pushFunction(funcRef); pushFunction(funcRef);
setSelf(button); setLocal(button, "self");
callFunction(); callFunction();
}); });
} else { } else {
@ -129,7 +135,7 @@ int LuaScript::lua_UIButton_setOnClick()
int LuaScript::lua_UIContainer_getChildByID() int LuaScript::lua_UIContainer_getChildByID()
{ {
std::string id = popString(); std::string id = popString();
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance()); UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(container) if(container)
pushClassInstance(container->getChildById(id)); pushClassInstance(container->getChildById(id));
else else
@ -139,9 +145,14 @@ int LuaScript::lua_UIContainer_getChildByID()
int LuaScript::lua_UIContainer_lock() int LuaScript::lua_UIContainer_lock()
{ {
UIElementPtr element = boost::static_pointer_cast<UIElement>(popClassInstance()); UIElementPtr element = boost::dynamic_pointer_cast<UIElement>(popClassInstance());
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance()); UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(container && element) { if(!element) {
reportFuncErrorWithTraceback("invalid lock element");
return 1;
}
if(container) {
container->lockElement(element); container->lockElement(element);
} }
return 1; return 1;
@ -149,7 +160,7 @@ int LuaScript::lua_UIContainer_lock()
int LuaScript::lua_UIContainer_unlock() int LuaScript::lua_UIContainer_unlock()
{ {
UIContainerPtr container = boost::static_pointer_cast<UIContainer>(popClassInstance()); UIContainerPtr container = boost::dynamic_pointer_cast<UIContainer>(popClassInstance());
if(container) { if(container) {
container->unlockElement(); container->unlockElement();
} }

@ -32,7 +32,7 @@ LuaScript::LuaScript()
{ {
L = luaL_newstate(); L = luaL_newstate();
if(!L) if(!L)
logFatal("could not create lua context"); logFatal("FATAL ERROR: could not create lua context");
// load lua standard libraries // load lua standard libraries
luaL_openlibs(L); luaL_openlibs(L);
@ -64,7 +64,7 @@ void LuaScript::loadAllModules()
bool LuaScript::loadFile(const std::string& fileName) bool LuaScript::loadFile(const std::string& fileName)
{ {
if(!g_resources.fileExists(fileName)) { if(!g_resources.fileExists(fileName)) {
logError("script file '%s' doesn't exist", fileName.c_str()); flogError("ERROR: script file '%s' doesn't exist", fileName.c_str());
return false; return false;
} }
std::string fileContents = g_resources.loadTextFile(fileName); std::string fileContents = g_resources.loadTextFile(fileName);
@ -114,11 +114,18 @@ int LuaScript::loadBufferAsFunction(const std::string& text, const std::string&
void LuaScript::reportError(const std::string& errorDesc, const char *funcName) void LuaScript::reportError(const std::string& errorDesc, const char *funcName)
{ {
std::stringstream ss; std::stringstream ss;
ss << "LUA script error"; ss << "LUA Script ERROR: ";
if(funcName) if(funcName)
ss << " in " << funcName << "()"; ss << " in " << funcName << "(): ";
ss << ": " << errorDesc << std::endl; ss << errorDesc << std::endl;
logError(ss.str().c_str()); logError(ss.str());
}
void LuaScript::reportErrorWithTraceback(const std::string& errorDesc, const char* funcName)
{
pushString(errorDesc);
luaErrorHandler(L);
reportError(popString(), funcName);
} }
int LuaScript::getStackSize() int LuaScript::getStackSize()
@ -126,6 +133,11 @@ int LuaScript::getStackSize()
return lua_gettop(L); return lua_gettop(L);
} }
void LuaScript::moveTop(int index)
{
lua_insert(L, index);
}
void LuaScript::pop(int n) void LuaScript::pop(int n)
{ {
lua_pop(L, n); lua_pop(L, n);
@ -141,15 +153,15 @@ bool LuaScript::popBoolean()
int32_t LuaScript::popInteger() int32_t LuaScript::popInteger()
{ {
double d = lua_tonumber(L, -1); double d = lua_tonumber(L, -1);
pop(1); pop();
return (int)d; return (int)d;
} }
std::string LuaScript::popString() std::string LuaScript::popString()
{ {
size_t len; std::string str;
const char *cstr = lua_tolstring(L, -1, &len); if(lua_isstring(L, -1))
std::string str(cstr, len); str = lua_tostring(L, -1);
pop(); pop();
return str; return str;
} }
@ -181,8 +193,10 @@ void LuaScript::pushUserdata(void* ptr)
void LuaScript::pushClassInstance(const ScriptablePtr& object) void LuaScript::pushClassInstance(const ScriptablePtr& object)
{ {
if(object && object->getScriptableName()) { if(object) {
// create weak_ptr to the scriptable object stored as userdata
new(lua_newuserdata(L, sizeof(ScriptableWeakPtr))) ScriptableWeakPtr(object); new(lua_newuserdata(L, sizeof(ScriptableWeakPtr))) ScriptableWeakPtr(object);
// set object metatable
lua_getfield(L, LUA_REGISTRYINDEX, (std::string(object->getScriptableName()) + "_mt").c_str()); lua_getfield(L, LUA_REGISTRYINDEX, (std::string(object->getScriptableName()) + "_mt").c_str());
lua_setmetatable(L, -2); lua_setmetatable(L, -2);
} else { } else {
@ -192,18 +206,14 @@ void LuaScript::pushClassInstance(const ScriptablePtr& object)
ScriptablePtr LuaScript::popClassInstance() ScriptablePtr LuaScript::popClassInstance()
{ {
if(!lua_isuserdata(L, -1)) { ScriptablePtr object;
reportError(format("couldn't pop a class instance, top objet is not a valid type (%s)", luaL_typename(L, -1))); if(lua_isuserdata(L, -1)) { // instances are store as userdata
lua_pop(L, 1); object = ((ScriptableWeakPtr *)lua_touserdata(L, -1))->lock();
return ScriptablePtr(); if(!object)
} reportErrorWithTraceback("attempt to retrive class instance from a object that is already expired");
} else if(!lua_isnil(L, -1)) // we accept nil values
ScriptableWeakPtr *objectRef = (ScriptableWeakPtr *)lua_touserdata(L, -1); reportErrorWithTraceback("couldn't retrive class instance, the value is not a scriptable type");
lua_pop(L, 1); lua_pop(L, 1);
ScriptablePtr object = objectRef->lock();
if(!object)
reportError(format("attempt to retrive class instance from a object that is already expired"));
return object; return object;
} }
@ -240,11 +250,11 @@ void LuaScript::callFunction(int numArgs)
reportError("stack size changed!"); reportError("stack size changed!");
} }
void LuaScript::setSelf(const ScriptablePtr& scriptable, int envIndex) void LuaScript::setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex)
{ {
lua_getfenv(L, envIndex); lua_getfenv(L, envIndex);
pushClassInstance(scriptable); pushClassInstance(scriptable);
lua_setfield(L, -2, "self"); lua_setfield(L, -2, varName);
lua_pop(L, 1); lua_pop(L, 1);
} }
@ -382,24 +392,36 @@ int LuaScript::luaCompareClassInstances(lua_State* L)
int LuaScript::luaFunctionCallback(lua_State* L) int LuaScript::luaFunctionCallback(lua_State* L)
{ {
// look for function id
int id = lua_tonumber(L, lua_upvalueindex(1)); int id = lua_tonumber(L, lua_upvalueindex(1));
// call the function
return (g_lua.*(g_lua.m_functions[id]))(); return (g_lua.*(g_lua.m_functions[id]))();
} }
int LuaScript::luaErrorHandler(lua_State *L) int LuaScript::luaErrorHandler(lua_State *L)
{ {
// push debug
lua_getfield(L, LUA_GLOBALSINDEX, "debug"); lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if(!lua_istable(L, -1)) { if(!lua_istable(L, -1)) {
lua_pop(L, 1); lua_pop(L, 1);
return 1; return 1;
} }
// push debug.traceback
lua_getfield(L, -1, "traceback"); lua_getfield(L, -1, "traceback");
if(!lua_isfunction(L, -1)) { if(!lua_isfunction(L, -1)) {
lua_pop(L, 2); lua_pop(L, 2);
return 1; return 1;
} }
lua_pushvalue(L, 1); // remove debug
lua_remove(L, -2);
// push additional error message
lua_pushvalue(L, -2);
// push level
lua_pushinteger(L, 2); lua_pushinteger(L, 2);
// call debug.traceback
lua_call(L, 2, 1); lua_call(L, 2, 1);
// remove additional error message
lua_remove(L, -2);
// return, the complete error message is on the stack
return 1; return 1;
} }

@ -30,6 +30,7 @@
#include <lua.hpp> #include <lua.hpp>
#define reportFuncError(a) reportError(a, __FUNCTION__) #define reportFuncError(a) reportError(a, __FUNCTION__)
#define reportFuncErrorWithTraceback(a) reportErrorWithTraceback(a, __FUNCTION__)
class LuaScript class LuaScript
{ {
@ -42,8 +43,10 @@ public:
bool loadBuffer(const std::string& text, const std::string& what = "luaBuffer"); bool loadBuffer(const std::string& text, const std::string& what = "luaBuffer");
int loadBufferAsFunction(const std::string& text, const std::string& what = "luaBuffer"); int loadBufferAsFunction(const std::string& text, const std::string& what = "luaBuffer");
void reportError(const std::string& errorDesc, const char *funcName = NULL); void reportError(const std::string& errorDesc, const char *funcName = NULL);
void reportErrorWithTraceback(const std::string& errorDesc, const char *funcName = NULL);
int getStackSize(); int getStackSize();
void moveTop(int index);
void pushNil(); void pushNil();
void pushBoolean(bool b); void pushBoolean(bool b);
@ -61,7 +64,7 @@ public:
void releaseFunction(int functionRef); void releaseFunction(int functionRef);
void callFunction(int numArgs = 0); void callFunction(int numArgs = 0);
void setSelf(const ScriptablePtr& scriptable, int envIndex = -1); void setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex = -1);
void pushClassInstance(const ScriptablePtr& object); void pushClassInstance(const ScriptablePtr& object);
ScriptablePtr popClassInstance(); ScriptablePtr popClassInstance();

@ -47,7 +47,7 @@ int AnchorLine::getPos() const
return 0; return 0;
} }
} }
logError("anchor line of an element has expired, your UI is missconfigured"); logError("ERROR: anchor line of an element has expired, your UI is missconfigured");
return 0; return 0;
} }
@ -74,7 +74,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine)
{ {
// we can never anchor with itself // we can never anchor with itself
if(anchorLine.getRelativeElement() == asUILayout()) { if(anchorLine.getRelativeElement() == asUILayout()) {
logError("anchoring with itself is not possible"); logError("ERROR: anchoring with itself is not possible");
return false; return false;
} }
@ -82,7 +82,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine)
// this only happens in missconfigurations // this only happens in missconfigurations
for(auto it = m_anchoredElements.begin(); it != m_anchoredElements.end(); ++it) { for(auto it = m_anchoredElements.begin(); it != m_anchoredElements.end(); ++it) {
if((*it).lock() == anchorLine.getRelativeElement()) { if((*it).lock() == anchorLine.getRelativeElement()) {
logError("anchoring elements with each other is not possible"); logError("ERROR: anchoring elements with each other is not possible");
return false; return false;
} }
} }

@ -67,7 +67,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p
{ {
std::string fileContents = g_resources.loadTextFile(file); std::string fileContents = g_resources.loadTextFile(file);
if(!fileContents.size()) { if(!fileContents.size()) {
logError("Could not load ui file \"%s", file.c_str()); flogError("ERROR: Could not load ui file \"%s", file.c_str());
return UIElementPtr(); return UIElementPtr();
} }
@ -101,7 +101,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p
return element; return element;
} catch (YAML::Exception& e) { } catch (YAML::Exception& e) {
logError("Failed to load ui file \"%s\":\n %s", file.c_str(), e.what()); flogError("ERROR: Failed to load ui file \"%s\":\n %s", file.c_str() % e.what());
} }
return UIElementPtr(); return UIElementPtr();

@ -38,7 +38,7 @@ void UISkins::load(const std::string& skinsFile)
{ {
std::string fileContents = g_resources.loadTextFile(skinsFile); std::string fileContents = g_resources.loadTextFile(skinsFile);
if(!fileContents.size()) if(!fileContents.size())
logFatal("Could not load skin file \"%s", skinsFile.c_str()); flogFatal("FATAL ERROR: Could not load skin file \"%s", skinsFile.c_str());
std::istringstream fin(fileContents); std::istringstream fin(fileContents);
@ -126,7 +126,7 @@ void UISkins::load(const std::string& skinsFile)
} }
} }
} catch (YAML::Exception& e) { } catch (YAML::Exception& e) {
logFatal("Malformed skin file \"%s\":\n %s", skinsFile.c_str(), e.what()); flogFatal("FATAL ERROR: Malformed skin file \"%s\":\n %s", skinsFile.c_str() % e.what());
} }
} }
@ -143,6 +143,6 @@ UIElementSkinPtr UISkins::getElementSkin(UI::EElementType elementType, const std
if(elementType == skin->getElementType() && name == skin->getName()) if(elementType == skin->getElementType() && name == skin->getName())
return skin; return skin;
} }
logWarning("Element skin '%s' not found", name.c_str()); flogWarning("Element skin '%s' not found", name.c_str());
return UIElementSkinPtr(); return UIElementSkinPtr();
} }

@ -26,17 +26,10 @@
#include <iostream> #include <iostream>
#include <cstdlib> #include <cstdlib>
#include <stdarg.h>
void Logger::_log(int level, const char *trace, const char *format, ...) void Logger::log(int level, const std::string& text, const char *trace)
{ {
va_list args;
std::string strace; std::string strace;
va_start(args, format);
std::string text = vformat(format, args);
va_end(args);
if(trace) { if(trace) {
strace = trace; strace = trace;
strace = strace.substr(0, strace.find_first_of('(')); strace = strace.substr(0, strace.find_first_of('('));
@ -54,8 +47,6 @@ void Logger::_log(int level, const char *trace, const char *format, ...)
if(!strace.empty()) if(!strace.empty())
std::cout << "[" << strace << "] "; std::cout << "[" << strace << "] ";
static char const *prefixes[] = { "FATAL ERROR: ", "ERROR: ", "WARNING: ", "", "", "" };
std::cout << prefixes[level];
std::cout << text; std::cout << text;
#ifdef linux #ifdef linux
@ -68,3 +59,4 @@ void Logger::_log(int level, const char *trace, const char *format, ...)
if(level == LFATAL) if(level == LFATAL)
exit(-1); exit(-1);
} }

@ -26,33 +26,39 @@
#define LOGGER_H #define LOGGER_H
#include <sstream> #include <sstream>
#include <boost/format.hpp>
namespace Logger { class Logger {
public:
enum ELogLevel {
LFATAL = 0,
LERROR,
LWARNING,
LINFO,
LDEBUG
};
enum ELogLevel { static void log(int level, const std::string& text = "", const char *trace = NULL);
LFATAL = 0,
LERROR,
LWARNING,
LINFO,
LDEBUG
}; };
void _log(int level, const char *trace, const char *format, ...); #define logFatal(a) Logger::log(Logger::LFATAL, a)
#define logError(a) Logger::log(Logger::LERROR, a)
} #define logWarning(a) Logger::log(Logger::LWARNING, a)
#define logDebug(a) Logger::log(Logger::LDEBUG, a)
#define logInfo(a) Logger::log(Logger::LINFO, a)
#define logFatal(...) Logger::_log(Logger::LFATAL, NULL, __VA_ARGS__) #define flogFatal(a,b) Logger::log(Logger::LFATAL, (boost::format(a) % b).str())
#define logError(...) Logger::_log(Logger::LERROR, NULL, __VA_ARGS__) #define flogError(a,b) Logger::log(Logger::LERROR, (boost::format(a) % b).str())
#define logWarning(...) Logger::_log(Logger::LWARNING, NULL, __VA_ARGS__) #define flogWarning(a,b) Logger::log(Logger::LWARNING, (boost::format(a) % b).str())
#define logDebug(...) Logger::_log(Logger::LDEBUG, NULL, __VA_ARGS__) #define flogDebug(a,b) Logger::log(Logger::LDEBUG, (boost::format(a) % b).str())
#define logInfo(...) Logger::_log(Logger::LINFO, NULL, __VA_ARGS__) #define flogInfo(a,b) Logger::log(Logger::LINFO, (boost::format(a) % b).str())
#define logTrace() Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, "") #define logTrace() Logger::log(Logger::LDEBUG, "", __PRETTY_FUNCTION__)
#define logTraceFatal(...) Logger::_log(Logger::LFATAL, __PRETTY_FUNCTION__, __VA_ARGS__) #define logTraceFatal(a) Logger::log(Logger::LFATAL, a, __PRETTY_FUNCTION__)
#define logTraceError(...) Logger::_log(Logger::LERROR, __PRETTY_FUNCTION__, __VA_ARGS__) #define logTraceError(a) Logger::log(Logger::LERROR, a, __PRETTY_FUNCTION__)
#define logTraceWarning(...) Logger::_log(Logger::LWARNING, __PRETTY_FUNCTION__, __VA_ARGS__) #define logTraceWarning(a) Logger::log(Logger::LWARNING, a, __PRETTY_FUNCTION__)
#define logTraceDebug(...) Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, __VA_ARGS__) #define logTraceDebug(a) Logger::log(Logger::LDEBUG, a, __PRETTY_FUNCTION__)
#define logTraceInfo(...) Logger::_log(Logger::LINFO, __PRETTY_FUNCTION__, __VA_ARGS__) #define logTraceInfo(a) Logger::log(Logger::LINFO, a, __PRETTY_FUNCTION__)
struct Dump { struct Dump {
public: public:
@ -65,4 +71,4 @@ private:
#define dump Dump() #define dump Dump()
#endif #endif // LOGGER_H

@ -23,30 +23,3 @@
#include <util/util.h> #include <util/util.h>
#include <cstdio> #include <cstdio>
std::string vformat(const char *format, va_list args)
{
if(!format)
return "";
int result = -1, length = 256;
char *buffer = 0;
while(result == -1) {
if(buffer)
delete [] buffer;
buffer = new char [length + 1];
result = vsnprintf(buffer, length, format, args);
length *= 2;
}
std::string s(buffer);
delete [] buffer;
return s;
}
std::string format(const char *format, ...)
{
va_list args;
va_start(args, format);
std::string s = vformat(format, args);
va_end(args);
return s;
}

@ -26,14 +26,11 @@
#define UTIL_H #define UTIL_H
#include <util/logger.h> #include <util/logger.h>
#include <stdarg.h>
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
/// Formatting like printf for std::string, va_list input version /// Easy/fast writting formater
std::string vformat(const char *format, va_list args); #define f(a, b) (boost::format(a) % b).str()
/// Formatting like printf for std::string
std::string format(const char *format, ...);
/// Convert any data type through boost::lexical_cast /// Convert any data type through boost::lexical_cast
template<class R, class T> template<class R, class T>
@ -43,9 +40,9 @@ R convertType(T t)
try { try {
ret = boost::lexical_cast<R>(t); ret = boost::lexical_cast<R>(t);
} catch(boost::bad_lexical_cast bad) { } catch(boost::bad_lexical_cast bad) {
logError("Error converting type: %s", bad.what()); flogError("Error converting type: %s", bad.what());
} }
return ret; return ret;
} }
#endif #endif // UTIL_H

@ -121,7 +121,7 @@ int main(int argc, const char *argv[])
g_lua.loadAllModules(); g_lua.loadAllModules();
if(!UIContainer::getRootContainer()->getChildCount()) if(!UIContainer::getRootContainer()->getChildCount())
logFatal("no ui loaded at all, no reason to continue running"); logFatal("FATAL ERROR: no ui loaded at all, no reason to continue running");
Platform::showWindow(); Platform::showWindow();
//Platform::hideMouseCursor(); //Platform::hideMouseCursor();

Loading…
Cancel
Save