Merge with develop

This commit is contained in:
Don Honerbrink
2015-08-03 10:44:47 -05:00
101 changed files with 3827 additions and 3742 deletions

View File

@@ -8,4 +8,5 @@ Documentation/Artifacts/*
Documentation/Manual/_build/* Documentation/Manual/_build/*
Configuration/Configuration/bin/** Configuration/Configuration/bin/**
Configuration/Configuration/obj/** Configuration/Configuration/obj/**
Artifacts/**

View File

@@ -20,6 +20,13 @@ list.includeMissingItems = true
############################################################################### ###############################################################################
list.extensions = zip list.extensions = zip
###############################################################################
# If a menu.xml file exists, it will display the menu alphabetically. To
# not auto-sort the menu items alphabetically, set the following to false.
# This does not apply to how your ROMs are sorted.
###############################################################################
list.menuSort = true
############################################################################### ###############################################################################
# The executable to run when an item in a collection item is selected # The executable to run when an item in a collection item is selected
############################################################################### ###############################################################################

View File

@@ -0,0 +1,2 @@
Sega Genesis
Arcade

View File

@@ -1,4 +0,0 @@
<menu>
<item collection="Sega Genesis"/>
<item collection="Arcade"/>
</menu>

View File

@@ -4,3 +4,11 @@
# See Menu.xml to configure the menu # See Menu.xml to configure the menu
############################################################################### ###############################################################################
###############################################################################
# If a menu.xml file exists, it will display the menu alphabetically. To
# not auto-sort the menu items alphabetically, set the following to false.
# This does not apply to how your ROMs are sorted.
###############################################################################
list.menuSort = true

View File

@@ -21,6 +21,13 @@ list.includeMissingItems = true
############################################################################### ###############################################################################
list.extensions = zip list.extensions = zip
###############################################################################
# If a menu.xml file exists, it will display the menu alphabetically. To
# not auto-sort the menu items alphabetically, set the following to false.
# This does not apply to how your ROMs are sorted.
###############################################################################
list.menuSort = true
############################################################################### ###############################################################################
# The executable to run when an item in a collection item is selected # The executable to run when an item in a collection item is selected
############################################################################### ###############################################################################

View File

@@ -11,8 +11,56 @@ back = Escape
quit = Q quit = Q
# See below for a list of key codes that can be used for configuring the controls: ##############################################################################
# MOUSE CODES
###################### ######################################################
# Code # Description
###################### ######################################################
# mouseButtonLeft Left mouse click
# mouseButtonMiddle Middle mouse click
# mouseButtonRight Right mouse click
# mouseButtonX1 ?
# mouseButtonX2 ?
##############################################################################
# JOYSTICK/GAMEPAD CODES
###################### ######################################################
# Code # Description
###################### ######################################################
# X is joypad number (0 is first joystick/gamepad)
# joyXHatYLeftUp Y=hat number (0 is the first dpad) (example joy0Hat0Up)
# joyXHatYLeft
# joyXHatYLeftDown
# joyXHatYUp
# joyXHatYDown
# joyXHatYRightUp
# joyXHatYRight
# joyXHatYRightDown
# joyXButtonY Y is button number (0 is first button)
# Example: joy1button7 -> second joystick, 8th button
# Open up the gamepad control panel in windows or use
# "jstest" in linux
#
# joyXAxis0+ First POV stick, first axis positive direction
# (axis 0 is usually x)
# joyXAxis0- First POV stick, first axis positive direction
# (axis 0 is usually x)
# joyXAxis1+ First POV stick, second axis positive direction
# (axis 0 is usually y)
#joyXAxis1- First POV stick, second axis positive direction
# (axis 0 is usually y)
#
# joyXAxis2+ Second POV stick, first axis positive direction
# (axis 2 is usually x)
# joyXAxis2- Second POV stick, first axis positive direction
# (axis 2 is usually x)
# joyXAxis3+ Second POV stick, second axis positive direction
# (axis 3 is usually y)
# joyXAxis3- Second POV stick, second axis positive direction
# (axis 3 is usually y)
##############################################################################
# KEYBOARD CODES
###################### ###################################################### ###################### ######################################################
# Code # Description # Code # Description
###################### ###################################################### ###################### ######################################################

View File

@@ -12,8 +12,8 @@
# Display # Display
####################################### #######################################
fullscreen = no fullscreen = no
horizontal = stretch # or enter in the screen pixel width (i.e 1024) horizontal = 400 # or enter in the screen pixel width (i.e 1024)
vertical = stretch # or enter in the screen pixel width (i.e 768) vertical = 300 # or enter in the screen pixel width (i.e 768)
layout = Default 16x9 layout = Default 16x9
hideMouse = yes hideMouse = yes
showParenthesis = yes showParenthesis = yes

View File

@@ -92,6 +92,12 @@ set(RETROFE_HEADERS
"${RETROFE_DIR}/Source/Collection/Item.h" "${RETROFE_DIR}/Source/Collection/Item.h"
"${RETROFE_DIR}/Source/Collection/MenuParser.h" "${RETROFE_DIR}/Source/Collection/MenuParser.h"
"${RETROFE_DIR}/Source/Control/UserInput.h" "${RETROFE_DIR}/Source/Control/UserInput.h"
"${RETROFE_DIR}/Source/Control/InputHandler.h"
"${RETROFE_DIR}/Source/Control/JoyAxisHandler.h"
"${RETROFE_DIR}/Source/Control/JoyButtonHandler.h"
"${RETROFE_DIR}/Source/Control/JoyHatHandler.h"
"${RETROFE_DIR}/Source/Control/KeyboardHandler.h"
"${RETROFE_DIR}/Source/Control/MouseButtonHandler.h"
"${RETROFE_DIR}/Source/Database/Configuration.h" "${RETROFE_DIR}/Source/Database/Configuration.h"
"${RETROFE_DIR}/Source/Database/DB.h" "${RETROFE_DIR}/Source/Database/DB.h"
"${RETROFE_DIR}/Source/Database/MetadataDatabase.h" "${RETROFE_DIR}/Source/Database/MetadataDatabase.h"
@@ -137,6 +143,11 @@ set(RETROFE_SOURCES
"${RETROFE_DIR}/Source/Collection/Item.cpp" "${RETROFE_DIR}/Source/Collection/Item.cpp"
"${RETROFE_DIR}/Source/Collection/MenuParser.cpp" "${RETROFE_DIR}/Source/Collection/MenuParser.cpp"
"${RETROFE_DIR}/Source/Control/UserInput.cpp" "${RETROFE_DIR}/Source/Control/UserInput.cpp"
"${RETROFE_DIR}/Source/Control/JoyAxisHandler.cpp"
"${RETROFE_DIR}/Source/Control/JoyButtonHandler.cpp"
"${RETROFE_DIR}/Source/Control/JoyHatHandler.cpp"
"${RETROFE_DIR}/Source/Control/KeyboardHandler.cpp"
"${RETROFE_DIR}/Source/Control/MouseButtonHandler.cpp"
"${RETROFE_DIR}/Source/Database/Configuration.cpp" "${RETROFE_DIR}/Source/Database/Configuration.cpp"
"${RETROFE_DIR}/Source/Database/DB.cpp" "${RETROFE_DIR}/Source/Database/DB.cpp"
"${RETROFE_DIR}/Source/Database/MetadataDatabase.cpp" "${RETROFE_DIR}/Source/Database/MetadataDatabase.cpp"

View File

@@ -25,77 +25,75 @@ CollectionInfo::CollectionInfo(std::string name,
std::string extensions, std::string extensions,
std::string metadataType, std::string metadataType,
std::string metadataPath) std::string metadataPath)
: Name(name) : name(name)
, ListPath(listPath) , listpath(listPath)
, Extensions(extensions) , metadataType(metadataType)
, MetadataType(metadataType) , menusort(true)
, MetadataPath(metadataPath) , metadataPath_(metadataPath)
, extensions_(extensions)
{ {
} }
CollectionInfo::~CollectionInfo() CollectionInfo::~CollectionInfo()
{ {
std::vector<Item *>::iterator it = Items.begin(); // remove items from the subcollections so their destructors do not
// delete the items since the parent collection will delete them.
std::vector<CollectionInfo *>::iterator subit;
for (subit != subcollections_.begin(); subit != subcollections_.end(); subit++)
{
CollectionInfo *info = *subit;
info->items.clear();
}
while(it != Items.end())
std::vector<Item *>::iterator it = items.begin();
while(it != items.end())
{ {
delete *it; delete *it;
Items.erase(it); items.erase(it);
it = Items.begin(); it = items.begin();
} }
} }
std::string CollectionInfo::GetName() const std::string CollectionInfo::settingsPath() const
{ {
return Name; return Utils::combinePath(Configuration::absolutePath, "collections", name);
} }
std::string CollectionInfo::GetSettingsPath() const
{
return Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", GetName());
}
std::string CollectionInfo::GetListPath() const void CollectionInfo::extensionList(std::vector<std::string> &extensionlist)
{ {
return ListPath; std::istringstream ss(extensions_);
}
std::string CollectionInfo::GetMetadataType() const
{
return MetadataType;
}
std::string CollectionInfo::GetMetadataPath() const
{
return MetadataPath;
}
std::string CollectionInfo::GetExtensions() const
{
return Extensions;
}
void CollectionInfo::GetExtensions(std::vector<std::string> &extensions)
{
std::istringstream ss(Extensions);
std::string token; std::string token;
while(std::getline(ss, token, ',')) while(std::getline(ss, token, ','))
{ {
extensions.push_back(token); extensionlist.push_back(token);
} }
} }
std::vector<Item *> *CollectionInfo::GetItems()
void CollectionInfo::addSubcollection(CollectionInfo *newinfo)
{ {
return &Items; subcollections_.push_back(newinfo);
items.insert(items.begin(), newinfo->items.begin(), newinfo->items.end());
} }
bool CollectionInfo::ItemIsLess(Item const *lhs, Item const *rhs) bool CollectionInfo::hasSubcollections()
{ {
return lhs->GetLCFullTitle() < rhs->GetLCFullTitle(); return (subcollections_.size() > 0);
} }
void CollectionInfo::SortItems() bool CollectionInfo::itemIsLess(Item *lhs, Item *rhs)
{ {
std::sort(Items.begin(), Items.end(), ItemIsLess); if(lhs->leaf && !rhs->leaf) return true;
if(!lhs->leaf && rhs->leaf) return false;
if(!lhs->collectionInfo->menusort && lhs->leaf && rhs->leaf) return false;
return lhs->lowercaseFullTitle() < rhs->lowercaseFullTitle();
}
void CollectionInfo::sortItems()
{
std::sort(items.begin(), items.end(), itemIsLess);
} }

View File

@@ -25,23 +25,21 @@ class CollectionInfo
public: public:
CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath); CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath);
virtual ~CollectionInfo(); virtual ~CollectionInfo();
std::string GetName() const; std::string settingsPath() const;
std::string GetSettingsPath() const; void sortItems();
std::string GetListPath() const; void addSubcollection(CollectionInfo *info);
std::string GetMetadataType() const; bool hasSubcollections();
std::string GetMetadataPath() const; void extensionList(std::vector<std::string> &extensions);
std::string GetExtensions() const; std::string name;
std::vector<Item *> *GetItems(); std::string listpath;
void SortItems(); std::string metadataType;
void GetExtensions(std::vector<std::string> &extensions); std::string launcher;
std::vector<Item *> items;
bool menusort;
private: private:
static bool ItemIsLess(Item const *lhs, Item const *rhs); std::vector<CollectionInfo *> subcollections_;
std::string metadataPath_;
std::string extensions_;
static bool itemIsLess(Item *lhs, Item *rhs);
std::string Name;
std::string ListPath;
std::string Extensions;
std::string MetadataType;
std::string MetadataPath;
std::vector<Item *> Items;
}; };

View File

@@ -36,8 +36,8 @@
#include <algorithm> #include <algorithm>
CollectionInfoBuilder::CollectionInfoBuilder(Configuration &c, MetadataDatabase &mdb) CollectionInfoBuilder::CollectionInfoBuilder(Configuration &c, MetadataDatabase &mdb)
: Conf(c) : conf_(c)
, MetaDB(mdb) , metaDB_(mdb)
{ {
} }
@@ -45,24 +45,24 @@ CollectionInfoBuilder::~CollectionInfoBuilder()
{ {
} }
bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name) bool CollectionInfoBuilder::createCollectionDirectory(std::string name)
{ {
std::string collectionPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", name); std::string collectionPath = Utils::combinePath(Configuration::absolutePath, "collections", name);
std::vector<std::string> paths; std::vector<std::string> paths;
paths.push_back(collectionPath); paths.push_back(collectionPath);
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "artwork_back")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "artwork_back"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "artwork_front")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "artwork_front"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "bezel")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "bezel"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "logo")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "logo"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "medium_back")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "medium_back"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "medium_front")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "medium_front"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "screenshot")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "screenshot"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "screentitle")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "screentitle"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "video")); paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "video"));
paths.push_back(Utils::CombinePath(collectionPath, "roms")); paths.push_back(Utils::combinePath(collectionPath, "roms"));
paths.push_back(Utils::CombinePath(collectionPath, "system_artwork")); paths.push_back(Utils::combinePath(collectionPath, "system_artwork"));
for(std::vector<std::string>::iterator it = paths.begin(); it != paths.end(); it++) for(std::vector<std::string>::iterator it = paths.begin(); it != paths.end(); it++)
{ {
@@ -89,7 +89,7 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
#endif #endif
} }
std::string filename = Utils::CombinePath(collectionPath, "include.txt"); std::string filename = Utils::combinePath(collectionPath, "include.txt");
std::cout << "Creating file \"" << filename << "\"" << std::endl; std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream includeFile; std::ofstream includeFile;
@@ -99,7 +99,7 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
includeFile << "# by settings.conf will be used" << std::endl; includeFile << "# by settings.conf will be used" << std::endl;
includeFile.close(); includeFile.close();
filename = Utils::CombinePath(collectionPath, "exclude.txt"); filename = Utils::combinePath(collectionPath, "exclude.txt");
std::cout << "Creating file \"" << filename << "\"" << std::endl; std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream excludeFile; std::ofstream excludeFile;
excludeFile.open(filename.c_str()); excludeFile.open(filename.c_str());
@@ -107,51 +107,46 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
includeFile << "# Add a list of files to hide on the menu (one filename per line, without the extension)." << std::endl; includeFile << "# Add a list of files to hide on the menu (one filename per line, without the extension)." << std::endl;
excludeFile.close(); excludeFile.close();
filename = Utils::CombinePath(collectionPath, "settings.conf"); filename = Utils::combinePath(collectionPath, "settings.conf");
std::cout << "Creating file \"" << filename << "\"" << std::endl; std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream settingsFile; std::ofstream settingsFile;
settingsFile.open(filename.c_str()); settingsFile.open(filename.c_str());
settingsFile << "# Uncomment and edit the following line to use a different ROM path." << std::endl; settingsFile << "# Uncomment and edit the following line to use a different ROM path." << std::endl;
settingsFile << "#list.path = " << Utils::CombinePath("%BASE_ITEM_PATH%", "%ITEM_COLLECTION_NAME%", "roms") << std::endl; settingsFile << "#list.path = " << Utils::combinePath("%BASE_ITEM_PATH%", "%ITEM_COLLECTION_NAME%", "roms") << std::endl;
settingsFile << "list.includeMissingItems = false" << std::endl; settingsFile << "list.includeMissingItems = false" << std::endl;
settingsFile << "list.extensions = zip" << std::endl; settingsFile << "list.extensions = zip" << std::endl;
settingsFile << "list.menuSort = yes" << std::endl;
settingsFile << std::endl;
settingsFile << "launcher = mame" << std::endl; settingsFile << "launcher = mame" << std::endl;
settingsFile << "metadata.type = MAME" << std::endl; settingsFile << "metadata.type = MAME" << std::endl;
settingsFile << std::endl; settingsFile << std::endl;
settingsFile << "#media.screenshot = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screenshot") << std::endl; settingsFile << "#media.screenshot = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screenshot") << std::endl;
settingsFile << "#media.screentitle = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screentitle") << std::endl; settingsFile << "#media.screentitle = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screentitle") << std::endl;
settingsFile << "#media.artwork_back = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "artwork_back") << std::endl; settingsFile << "#media.artwork_back = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "artwork_back") << std::endl;
settingsFile << "#media.artwork_front = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "artwork_front") << std::endl; settingsFile << "#media.artwork_front = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "artwork_front") << std::endl;
settingsFile << "#media.logo = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "logo") << std::endl; settingsFile << "#media.logo = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "logo") << std::endl;
settingsFile << "#media.medium_back = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "medium_back") << std::endl; settingsFile << "#media.medium_back = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "medium_back") << std::endl;
settingsFile << "#media.medium_front = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "medium_front") << std::endl; settingsFile << "#media.medium_front = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "medium_front") << std::endl;
settingsFile << "#media.screenshot = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screenshot") << std::endl; settingsFile << "#media.screenshot = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screenshot") << std::endl;
settingsFile << "#media.screentitle = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screentitle") << std::endl; settingsFile << "#media.screentitle = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "screentitle") << std::endl;
settingsFile << "#media.video = " << Utils::CombinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "video") << std::endl; settingsFile << "#media.video = " << Utils::combinePath("%BASE_MEDIA_PATH%", "%ITEM_COLLECTION_NAME%", "medium_artwork", "video") << std::endl;
settingsFile.close(); settingsFile.close();
filename = Utils::CombinePath(collectionPath, "menu.xml"); filename = Utils::combinePath(collectionPath, "menu.txt");
std::cout << "Creating file \"" << filename << "\"" << std::endl; std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream menuFile; std::ofstream menuFile;
menuFile.open(filename.c_str()); menuFile.open(filename.c_str());
menuFile << "<menu>" << std::endl;
menuFile << std::endl;
menuFile << "<!-- uncomment this line and edit the example below to have a submenu" << std::endl;
menuFile << std::endl;
menuFile << " <item collection=\"Some collection name\"/>" << std::endl;
menuFile << " <item collection=\"Arcade\"/>" << std::endl;
menuFile << std::endl;
menuFile << "uncomment this line and edit the example above to have a submenu -->" << std::endl;
menuFile << std::endl;
menuFile << "</menu>" << std::endl;
menuFile.close(); menuFile.close();
return true; return true;
} }
CollectionInfo *CollectionInfoBuilder::buildCollection(std::string name)
{
return buildCollection(name, "");
}
CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name) CollectionInfo *CollectionInfoBuilder::buildCollection(std::string name, std::string mergedCollectionName)
{ {
std::string listItemsPathKey = "collections." + name + ".list.path"; std::string listItemsPathKey = "collections." + name + ".list.path";
std::string listFilterKey = "collections." + name + ".list.filter"; std::string listFilterKey = "collections." + name + ".list.filter";
@@ -167,13 +162,14 @@ CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name)
std::string extensions; std::string extensions;
std::string metadataType = name; std::string metadataType = name;
std::string metadataPath; std::string metadataPath;
conf_.getCollectionAbsolutePath(name, listItemsPath);
Conf.GetCollectionAbsolutePath(name, listItemsPath); (void)conf_.getProperty(extensionsKey, extensions);
(void)Conf.GetProperty(extensionsKey, extensions); (void)conf_.getProperty(metadataTypeKey, metadataType);
(void)Conf.GetProperty(metadataTypeKey, metadataType); (void)conf_.getProperty(metadataPathKey, metadataPath);
(void)Conf.GetProperty(metadataPathKey, metadataPath);
if(!Conf.GetProperty(launcherKey, launcherName)) if(!conf_.getProperty(launcherKey, launcherName))
{ {
std::stringstream ss; std::stringstream ss;
ss << "\"" ss << "\""
@@ -183,18 +179,20 @@ CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name)
<< "). Your collection will be viewable, however you will not be able to " << "). Your collection will be viewable, however you will not be able to "
<< "launch any of the items in your collection."; << "launch any of the items in your collection.";
Logger::Write(Logger::ZONE_NOTICE, "Collections", ss.str()); Logger::write(Logger::ZONE_NOTICE, "Collections", ss.str());
} }
CollectionInfo *collection = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath); CollectionInfo *collection = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath);
ImportDirectory(collection); (void)conf_.getProperty("collections." + collection->name + ".launcher", collection->launcher);
ImportDirectory(collection, mergedCollectionName);
return collection; return collection;
} }
bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::string file, std::string launcher, std::map<std::string, Item *> &list) bool CollectionInfoBuilder::ImportBasicList(CollectionInfo *info, std::string file, std::map<std::string, Item *> &list)
{ {
std::ifstream includeStream(file.c_str()); std::ifstream includeStream(file.c_str());
@@ -207,7 +205,7 @@ bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::stri
while(std::getline(includeStream, line)) while(std::getline(includeStream, line))
{ {
line = Utils::FilterComments(line); line = Utils::filterComments(line);
if(!line.empty() && list.find(line) == list.end()) if(!line.empty() && list.find(line) == list.end())
{ {
@@ -215,11 +213,10 @@ bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::stri
line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() );
i->SetFullTitle(line); i->fullTitle = line;
i->SetName(line); i->name = line;
i->SetFullTitle(line); i->title = line;
i->SetTitle(line); i->collectionInfo = info;
i->SetLauncher(launcher);
list[line] = i; list[line] = i;
} }
@@ -228,36 +225,54 @@ bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::stri
return true; return true;
} }
bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info) bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info, std::string mergedCollectionName)
{ {
DIR *dp; DIR *dp;
struct dirent *dirp; struct dirent *dirp;
std::string path = info->GetListPath(); std::string path = info->listpath;
std::map<std::string, Item *> includeFilter; std::map<std::string, Item *> includeFilter;
std::map<std::string, Item *> excludeFilter; std::map<std::string, Item *> excludeFilter;
std::string includeFile = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", info->GetName(), "include.txt"); std::string includeFile = Utils::combinePath(Configuration::absolutePath, "collections", info->name, "include.txt");
std::string excludeFile = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", info->GetName(), "exclude.txt"); std::string excludeFile = Utils::combinePath(Configuration::absolutePath, "collections", info->name, "exclude.txt");
std::string launcher; std::string launcher;
bool showMissing = false; bool showMissing = false;
(void)Conf.GetProperty("collections." + info->GetName() + ".launcher", launcher); if(mergedCollectionName != "")
(void)Conf.GetProperty("collections." + info->GetName() + ".list.includeMissingItems", showMissing); {
std::string mergedFile = Utils::combinePath(Configuration::absolutePath, "collections", mergedCollectionName, info->name + ".sub");
Logger::write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Checking for \"" + mergedFile + "\"");
(void)conf_.getProperty("collections." + mergedCollectionName + ".list.includeMissingItems", showMissing);
ImportBasicList(info, mergedFile, includeFilter);
ImportBasicList(info, includeFile, launcher, includeFilter); }
ImportBasicList(info, excludeFile, launcher, excludeFilter); else
{
(void)conf_.getProperty("collections." + info->name + ".list.includeMissingItems", showMissing);
}
// If no merged file exists, or it is empty, attempt to use the include and exclude from the subcollection
// If this not a merged collection, the size will be 0 anyways and the code below will still execute
if(includeFilter.size() == 0)
{
Logger::write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Checking for \"" + includeFile + "\"");
ImportBasicList(info, includeFile, includeFilter);
ImportBasicList(info, excludeFile, excludeFilter);
}
std::vector<std::string> extensions; std::vector<std::string> extensions;
std::vector<std::string>::iterator extensionsIt; std::vector<std::string>::iterator extensionsIt;
info->GetExtensions(extensions); info->extensionList(extensions);
Logger::Write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Checking for \"" + includeFile + "\"");
dp = opendir(path.c_str()); dp = opendir(path.c_str());
Logger::write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Scanning directory \"" + path + "\"");
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Could not read directory \"" + path + "\". Ignore if this is a menu."); Logger::write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Could not read directory \"" + path + "\". Ignore if this is a menu.");
return false; return false;
} }
@@ -267,7 +282,7 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
{ {
if(excludeFilter.find(it->first) == excludeFilter.end()) if(excludeFilter.find(it->first) == excludeFilter.end())
{ {
info->GetItems()->push_back(it->second); info->items.push_back(it->second);
} }
} }
} }
@@ -295,11 +310,12 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
if(file.compare(start, comparator.length(), *extensionsIt) == 0) if(file.compare(start, comparator.length(), *extensionsIt) == 0)
{ {
Item *i = new Item(); Item *i = new Item();
i->SetName(basename); i->name = basename;
i->SetFullTitle(basename); i->fullTitle = basename;
i->SetTitle(basename); i->title = basename;
i->SetLauncher(launcher); i->collectionInfo = info;
info->GetItems()->push_back(i);
info->items.push_back(i);
} }
} }
} }
@@ -325,9 +341,7 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
excludeFilter.erase(it); excludeFilter.erase(it);
} }
MetaDB.InjectMetadata(info); metaDB_.injectMetadata(info);
info->SortItems();
return true; return true;
} }

View File

@@ -29,12 +29,13 @@ class CollectionInfoBuilder
public: public:
CollectionInfoBuilder(Configuration &c, MetadataDatabase &mdb); CollectionInfoBuilder(Configuration &c, MetadataDatabase &mdb);
virtual ~CollectionInfoBuilder(); virtual ~CollectionInfoBuilder();
CollectionInfo *BuildCollection(std::string collectionName); CollectionInfo *buildCollection(std::string collectionName);
static bool CreateCollectionDirectory(std::string collectionName); CollectionInfo *buildCollection(std::string collectionName, std::string mergedCollectionName);
static bool createCollectionDirectory(std::string collectionName);
private: private:
Configuration &Conf; Configuration &conf_;
MetadataDatabase &MetaDB; MetadataDatabase &metaDB_;
bool ImportBasicList(CollectionInfo *info, std::string file, std::string launcher, std::map<std::string, Item *> &list); bool ImportBasicList(CollectionInfo *info, std::string file, std::map<std::string, Item *> &list);
bool ImportDirectory(CollectionInfo *info); bool ImportDirectory(CollectionInfo *info, std::string mergedCollectionName);
}; };

View File

@@ -20,7 +20,8 @@
#include <algorithm> #include <algorithm>
Item::Item() Item::Item()
: Leaf(true) : collectionInfo(NULL)
, leaf(true)
{ {
} }
@@ -28,142 +29,24 @@ Item::~Item()
{ {
} }
const std::string Item::GetFileName() const std::string Item::filename()
{ {
return Utils::GetFileName(FilePath); return Utils::getFileName(filepath);
}
const std::string& Item::GetFilePath() const
{
return FilePath;
}
void Item::SetFilePath(const std::string& filepath)
{
FilePath = filepath;
}
const std::string& Item::GetLauncher() const
{
return Launcher;
}
void Item::SetLauncher(const std::string& launcher)
{
Launcher = launcher;
}
const std::string& Item::GetManufacturer() const
{
return Manufacturer;
}
void Item::SetManufacturer(const std::string& manufacturer)
{
Manufacturer = manufacturer;
}
const std::string& Item::GetGenre() const
{
return Genre;
}
void Item::SetGenre(const std::string& genre)
{
Genre = genre;
}
const std::string& Item::GetName() const
{
return Name;
}
void Item::SetName(const std::string& name)
{
Name = name;
}
std::string Item::GetNumberButtons() const
{
return NumberButtons;
} }
void Item::SetNumberButtons(std::string numberbuttons)
std::string Item::lowercaseTitle()
{ {
NumberButtons = numberbuttons; std::string lcstr = title;
std::transform(lcstr.begin(), lcstr.end(), lcstr.begin(), ::tolower);
return lcstr;
} }
std::string Item::GetNumberPlayers() const std::string Item::lowercaseFullTitle()
{ {
return NumberPlayers; std::string lcstr = fullTitle;
std::transform(lcstr.begin(), lcstr.end(), lcstr.begin(), ::tolower);
return lcstr;
} }
void Item::SetNumberPlayers(std::string numberplayers)
{
NumberPlayers = numberplayers;
}
const std::string& Item::GetTitle() const
{
return Title;
}
const std::string& Item::GetLCTitle() const
{
return LCTitle;
}
const std::string& Item::GetLCFullTitle() const
{
return LCFullTitle;
}
void Item::SetTitle(const std::string& title)
{
Title = title;
LCTitle = Title;
std::transform(LCTitle.begin(), LCTitle.end(), LCTitle.begin(), ::tolower);
}
const std::string& Item::GetYear() const
{
return Year;
}
void Item::SetYear(const std::string& year)
{
Year = year;
}
bool Item::IsLeaf() const
{
return Leaf;
}
void Item::SetIsLeaf(bool leaf)
{
Leaf = leaf;
}
const std::string& Item::GetFullTitle() const
{
return FullTitle;
}
void Item::SetFullTitle(const std::string& fulltitle)
{
FullTitle = fulltitle;
LCFullTitle = fulltitle;
std::transform(LCFullTitle.begin(), LCFullTitle.end(), LCFullTitle.begin(), ::tolower);
}
const std::string& Item::GetCloneOf() const
{
return CloneOf;
}
void Item::SetCloneOf(const std::string& cloneOf)
{
CloneOf = cloneOf;
}

View File

@@ -16,54 +16,27 @@
#pragma once #pragma once
#include <string> #include <string>
#include "CollectionInfo.h"
class Item class Item
{ {
public: public:
Item(); Item();
virtual ~Item(); virtual ~Item();
const std::string GetFileName() const; std::string filename();
const std::string& GetFilePath() const; std::string lowercaseTitle() ;
void SetFilePath(const std::string& filepath); std::string lowercaseFullTitle();
const std::string& GetLauncher() const; std::string name;
void SetLauncher(const std::string& launcher); std::string filepath;
const std::string& GetManufacturer() const; std::string title;
void SetManufacturer(const std::string& manufacturer); std::string fullTitle;
const std::string& GetGenre() const; std::string year;
void SetGenre(const std::string& genre); std::string manufacturer;
const std::string& GetName() const; std::string genre;
void SetName(const std::string& name); std::string cloneof;
void SetNumberButtons(std::string numberbuttons); std::string numberPlayers;
std::string GetNumberButtons() const; std::string numberButtons;
void SetNumberPlayers(std::string numberplayers); CollectionInfo *collectionInfo;
std::string GetNumberPlayers() const; bool leaf;
const std::string& GetTitle() const;
const std::string& GetLCTitle() const;
void SetTitle(const std::string& title);
const std::string& GetYear() const;
void SetYear(const std::string& year);
bool IsLeaf() const;
void SetIsLeaf(bool leaf);
const std::string& GetFullTitle() const;
const std::string& GetLCFullTitle() const;
void SetFullTitle(const std::string& fulltitle);
const std::string& GetCloneOf() const;
void SetCloneOf(const std::string& cloneOf);
private:
std::string Launcher;
std::string FilePath;
std::string Name;
std::string Title;
std::string LCTitle;
std::string FullTitle;
std::string LCFullTitle;
std::string Year;
std::string Manufacturer;
std::string Genre;
std::string CloneOf;
std::string NumberPlayers;
std::string NumberButtons;
bool Leaf;
}; };

View File

@@ -16,6 +16,7 @@
#include "MenuParser.h" #include "MenuParser.h"
#include "CollectionInfo.h" #include "CollectionInfo.h"
#include "CollectionInfoBuilder.h"
#include "Item.h" #include "Item.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
#include "../Utility/Utils.h" #include "../Utility/Utils.h"
@@ -26,9 +27,9 @@
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
bool VectorSort(const Item *d1, const Item *d2) bool VectorSort(Item *d1, Item *d2)
{ {
return d1->GetLCTitle() < d2->GetLCTitle(); return d1->lowercaseTitle() < d2->lowercaseTitle();
} }
MenuParser::MenuParser() MenuParser::MenuParser()
@@ -39,16 +40,67 @@ MenuParser::~MenuParser()
{ {
} }
//todo: clean up this method, too much nesting bool MenuParser::buildMenuItems(CollectionInfo *collection, bool sort)
bool MenuParser::GetMenuItems(CollectionInfo *collection) {
if(!buildTextMenu(collection, sort))
{
return buildLegacyXmlMenu(collection, sort);
}
return true;
}
bool MenuParser::buildTextMenu(CollectionInfo *collection, bool sort)
{
std::string file = Utils::combinePath(Configuration::absolutePath, "collections", collection->name, "menu.txt");
std::ifstream includeStream(file.c_str());
std::vector<Item *> menuItems;
if (!includeStream.good())
{
Logger::write(Logger::ZONE_INFO, "Menu", "File does not exist: \"" + file + "\"");
return false;
}
Logger::write(Logger::ZONE_INFO, "Menu", "Found: \"" + file + "\"");
std::string line;
while(std::getline(includeStream, line))
{
line = Utils::filterComments(line);
if(!line.empty())
{
std::string title = line;
Item *item = new Item();
item->title = title;
item->fullTitle = title;
item->name = title;
item->leaf = false;
item->collectionInfo = collection;
menuItems.push_back(item);
}
}
collection->menusort = sort;
collection->items.insert(collection->items.begin(), menuItems.begin(), menuItems.end());
collection->sortItems();
return true;
}
bool MenuParser::buildLegacyXmlMenu(CollectionInfo *collection, bool sort)
{ {
bool retVal = false; bool retVal = false;
//todo: magic string //todo: magic string
std::string menuFilename = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", collection->GetName(), "menu.xml"); std::string menuFilename = Utils::combinePath(Configuration::absolutePath, "collections", collection->name, "menu.xml");
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
rapidxml::xml_node<> * rootNode; rapidxml::xml_node<> * rootNode;
std::vector<Item *> menuItems;
Logger::Write(Logger::ZONE_INFO, "Menu", "Checking if menu exists at \"" + menuFilename + "\"");
try try
{ {
@@ -57,6 +109,8 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
// gracefully exit if there is no menu file for the pa // gracefully exit if there is no menu file for the pa
if(file.good()) if(file.good())
{ {
Logger::write(Logger::ZONE_INFO, "Menu", "Found: \"" + menuFilename + "\"");
Logger::write(Logger::ZONE_INFO, "Menu", "Using legacy menu.xml file. Consider using the new menu.txt format");
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
buffer.push_back('\0'); buffer.push_back('\0');
@@ -68,46 +122,28 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling()) for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling())
{ {
rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection"); rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection");
rapidxml::xml_attribute<> *importAttribute = itemNode->first_attribute("import");
if(!collectionAttribute) if(!collectionAttribute)
{ {
retVal = false; retVal = false;
Logger::Write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute"); Logger::write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute");
break; break;
} }
//todo: too much nesting! Ack! //todo, check for empty string
std::string import; std::string title = collectionAttribute->value();
if(importAttribute) Item *item = new Item();
{ item->title = title;
import = importAttribute->value(); item->fullTitle = title;
} item->name = collectionAttribute->value();
item->leaf = false;
item->collectionInfo = collection;
if(import != "true") menuItems.push_back(item);
{
//todo, check for empty string
std::string title = collectionAttribute->value();
Item *item = new Item();
item->SetTitle(title);
item->SetFullTitle(title);
item->SetName(collectionAttribute->value());
item->SetIsLeaf(false);
collection->GetItems()->push_back(item);
}
else
{
std::string collectionName = collectionAttribute->value();
Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName);
//todo: unsupported option with this refactor
// need to append the collection
}
} }
// todo: sorting should occur within the collection itself, not externally collection->menusort = sort;
std::vector<Item *> *items = collection->GetItems(); collection->items.insert(collection->items.begin(), menuItems.begin(), menuItems.end());
std::sort( items->begin(), items->end(), VectorSort);
retVal = true; retVal = true;
} }
@@ -116,9 +152,8 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what(); ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what();
Logger::Write(Logger::ZONE_ERROR, "Menu", ss.str()); Logger::write(Logger::ZONE_ERROR, "Menu", ss.str());
} }
return retVal; return retVal;
} }

View File

@@ -15,6 +15,7 @@
*/ */
#pragma once #pragma once
#include "CollectionInfoBuilder.h"
class CollectionInfo; class CollectionInfo;
class MenuParser class MenuParser
@@ -22,6 +23,10 @@ class MenuParser
public: public:
MenuParser(); MenuParser();
virtual ~MenuParser(); virtual ~MenuParser();
bool GetMenuItems(CollectionInfo *cdb); bool buildMenuItems(CollectionInfo *cdb, bool sort);
private:
bool buildTextMenu(CollectionInfo *collection, bool sort);
bool buildLegacyXmlMenu(CollectionInfo *collection, bool sort);
}; };

View File

@@ -0,0 +1,12 @@
#pragma once
#include <SDL2/SDL.h>
class InputHandler
{
public:
virtual bool update(SDL_Event &e) = 0;
virtual bool pressed() = 0;
virtual void reset() = 0;
};

View File

@@ -0,0 +1,29 @@
#include "JoyAxisHandler.h"
JoyAxisHandler::JoyAxisHandler(SDL_JoystickID joyid, Uint8 axis, Sint16 min, Sint16 max)
: joyid_(joyid)
, axis_(axis)
, min_(min)
, max_(max)
, pressed_(false)
{
}
void JoyAxisHandler::reset()
{
pressed_= false;
}
bool JoyAxisHandler::update(SDL_Event &e)
{
if(e.type != SDL_JOYAXISMOTION || e.jaxis.which != joyid_ || e.jaxis.axis != axis_) return false;
pressed_ = (min_ <= e.jaxis.value && e.jaxis.value <= max_);
return true;
}
bool JoyAxisHandler::pressed()
{
return pressed_;
}

View File

@@ -0,0 +1,21 @@
#pragma once
#include "InputHandler.h"
class JoyAxisHandler : public InputHandler
{
public:
JoyAxisHandler(SDL_JoystickID joyid, Uint8 axis, Sint16 min, Sint16 max);
bool update(SDL_Event &e);
bool pressed();
void reset();
private:
SDL_JoystickID joyid_;
Uint8 axis_;
Sint16 min_;
Sint16 max_;
bool pressed_;
};

View File

@@ -0,0 +1,32 @@
#include "JoyButtonHandler.h"
JoyButtonHandler::JoyButtonHandler(SDL_JoystickID joynum, Uint8 button)
: joynum_(joynum)
, button_(button)
, pressed_(false)
{
}
void JoyButtonHandler::reset()
{
pressed_= false;
}
bool JoyButtonHandler::update(SDL_Event &e)
{
if(e.type != SDL_JOYBUTTONUP && e.type != SDL_JOYBUTTONDOWN) return false;
if(e.jbutton.which == joynum_ && e.jbutton.button == button_)
{
pressed_ = (e.type == SDL_JOYBUTTONDOWN) ? true : false;
return true;
}
return false;
}
bool JoyButtonHandler::pressed()
{
return pressed_;
}

View File

@@ -0,0 +1,18 @@
#pragma once
#include "InputHandler.h"
class JoyButtonHandler : public InputHandler
{
public:
JoyButtonHandler(SDL_JoystickID joynum, Uint8 button);
bool update(SDL_Event &e);
bool pressed();
void reset();
private:
SDL_JoystickID joynum_;
Uint8 button_;
bool pressed_;
};

View File

@@ -0,0 +1,28 @@
#include "JoyHatHandler.h"
JoyHatHandler::JoyHatHandler(SDL_JoystickID joynum, Uint8 hatnum, Uint8 direction)
: joynum_(joynum)
, hatnum_(hatnum)
, direction_(direction)
, pressed_(false)
{
}
void JoyHatHandler::reset()
{
pressed_= false;
}
bool JoyHatHandler::update(SDL_Event &e)
{
if(e.type != SDL_JOYHATMOTION || e.jhat.which != joynum_ || e.jhat.hat != hatnum_) return false;
pressed_ = (e.jhat.value == direction_);
return true;
}
bool JoyHatHandler::pressed()
{
return pressed_;
}

View File

@@ -0,0 +1,19 @@
#pragma once
#include "InputHandler.h"
class JoyHatHandler : public InputHandler
{
public:
JoyHatHandler(SDL_JoystickID joynum, Uint8 hatnum, Uint8 direction);
bool update(SDL_Event &e);
bool pressed();
void reset();
private:
SDL_JoystickID joynum_;
Uint8 hatnum_;
Uint8 direction_;
bool pressed_;
};

View File

@@ -0,0 +1,31 @@
#include "KeyboardHandler.h"
KeyboardHandler::KeyboardHandler(SDL_Scancode s)
: scancode_(s)
, pressed_(false)
{
}
void KeyboardHandler::reset()
{
pressed_= false;
}
bool KeyboardHandler::update(SDL_Event &e)
{
if(e.type != SDL_KEYUP && e.type != SDL_KEYDOWN) return false;
if(e.key.keysym.scancode == scancode_)
{
pressed_ = (e.type == SDL_KEYDOWN);
return true;
}
return false;
}
bool KeyboardHandler::pressed()
{
return pressed_;
}

View File

@@ -0,0 +1,17 @@
#pragma once
#include "InputHandler.h"
class KeyboardHandler : public InputHandler
{
public:
KeyboardHandler(SDL_Scancode scancode);
bool update(SDL_Event &e);
bool pressed();
void reset();
private:
SDL_Scancode scancode_;
bool pressed_;
};

View File

@@ -0,0 +1,31 @@
#include "MouseButtonHandler.h"
MouseButtonHandler::MouseButtonHandler(Uint8 button)
: button_(button)
, pressed_(false)
{
}
void MouseButtonHandler::reset()
{
pressed_= false;
}
bool MouseButtonHandler::update(SDL_Event &e)
{
if(e.type != SDL_MOUSEBUTTONUP && e.type != SDL_MOUSEBUTTONDOWN) return false;
if(e.button.button == button_)
{
pressed_ = (e.type == SDL_MOUSEBUTTONDOWN) ? true : false;
return true;
}
return false;
}
bool MouseButtonHandler::pressed()
{
return pressed_;
}

View File

@@ -0,0 +1,17 @@
#pragma once
#include "InputHandler.h"
class MouseButtonHandler : public InputHandler
{
public:
MouseButtonHandler(Uint8 button);
bool update(SDL_Event &e);
bool pressed();
void reset();
private:
Uint8 button_;
bool pressed_;
};

View File

@@ -17,17 +17,35 @@
#include "UserInput.h" #include "UserInput.h"
#include "../Database/Configuration.h" #include "../Database/Configuration.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
#include "../Utility/Utils.h"
#include "JoyAxisHandler.h"
#include "JoyButtonHandler.h"
#include "JoyHatHandler.h"
#include "KeyboardHandler.h"
#include "MouseButtonHandler.h"
UserInput::UserInput(Configuration &c) UserInput::UserInput(Configuration &c)
: Config(c) : config_(c)
{ {
for(unsigned int i = 0; i < KeyCodeMax; ++i)
{
keyHandlers_[i] = NULL;
lastKeyState_[i] = false;
}
} }
UserInput::~UserInput() UserInput::~UserInput()
{ {
for(std::vector<SDL_Joystick *>::iterator it = joysticks_.begin(); it != joysticks_.end(); it++)
{
if(*it)
{
SDL_JoystickClose(*it);
}
}
} }
bool UserInput::Initialize() bool UserInput::initialize()
{ {
bool retVal = true; bool retVal = true;
@@ -59,46 +77,15 @@ bool UserInput::Initialize()
// retVal = MapKey("admin", KeyCodeAdminMode) && retVal; // retVal = MapKey("admin", KeyCodeAdminMode) && retVal;
// retVal = MapKey("remove", KeyCodeHideItem) && retVal; // retVal = MapKey("remove", KeyCodeHideItem) && retVal;
for(int i = 0; i < SDL_NumJoysticks(); ++i)
{
joysticks_.push_back(SDL_JoystickOpen(i));
}
return retVal; return retVal;
} }
SDL_Scancode UserInput::GetScancode(KeyCode_E key)
{
SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN;
std::map<KeyCode_E, SDL_Scancode>::iterator it = KeyMap.find(key);
if(it != KeyMap.end())
{
scancode = it->second;
}
return scancode;
}
UserInput::KeyCode_E UserInput::GetKeycode(SDL_Scancode scancode)
{
KeyCode_E keycode = KeyCodeNull;
std::map<SDL_Scancode, KeyCode_E>::iterator it = ReverseKeyMap.find(scancode);
if(it != ReverseKeyMap.end())
{
keycode = it->second;
}
return keycode;
}
void UserInput::ResetKeyStates()
{
for(std::map<KeyCode_E, bool>::iterator it = KeyState.begin(); it != KeyState.end(); it++)
{
it->second = false;
}
}
bool UserInput::MapKey(std::string keyDescription, KeyCode_E key) bool UserInput::MapKey(std::string keyDescription, KeyCode_E key)
{ {
SDL_Scancode scanCode; SDL_Scancode scanCode;
@@ -106,42 +93,151 @@ bool UserInput::MapKey(std::string keyDescription, KeyCode_E key)
std::string configKey = "controls." + keyDescription; std::string configKey = "controls." + keyDescription;
if(!Config.GetProperty(configKey, description)) if(!config_.getProperty(configKey, description))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property " + configKey); Logger::write(Logger::ZONE_ERROR, "Input", "Missing property " + configKey);
return false; return false;
} }
scanCode = SDL_GetScancodeFromName(description.c_str()); scanCode = SDL_GetScancodeFromName(description.c_str());
if(scanCode == SDL_SCANCODE_UNKNOWN) if(scanCode != SDL_SCANCODE_UNKNOWN)
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs"); Logger::write(Logger::ZONE_INFO, "Input", "Binding key " + configKey);
return false; keyHandlers_[key] = new KeyboardHandler(scanCode);
return true;
} }
description = Utils::toLower(description);
KeyMap[key] = scanCode; if(description.find("mouse") == 0)
ReverseKeyMap[scanCode] = key; {
KeyState[key] = false; std::string mousedesc = Utils::replace(Utils::toLower(description), "mouse", "");
return true; if(mousedesc.find("button") == 0)
{
int button = 0;
std::stringstream ss;
mousedesc = Utils::replace(mousedesc, "button", "");
if(mousedesc == "left") button = SDL_BUTTON_LEFT;
else if(mousedesc == "middle") button = SDL_BUTTON_MIDDLE;
else if(mousedesc == "right") button = SDL_BUTTON_RIGHT;
else if(mousedesc == "x1") button = SDL_BUTTON_X1;
else if(mousedesc == "x2") button = SDL_BUTTON_X2;
keyHandlers_[key] = new MouseButtonHandler(button);
Logger::write(Logger::ZONE_INFO, "Input", "Binding mouse button " + ss.str() );
return true;
}
}
else if(description.find("joy") == 0)
{
std::string joydesc = Utils::replace(Utils::toLower(description), "joy", "");
std::stringstream ssjoy;
ssjoy << joydesc.at(0);
int joynum;
ssjoy >> joynum;
joydesc = joydesc.erase(0, 1);
if(joydesc.find("button") == 0)
{
unsigned int button;
std::stringstream ss;
ss << Utils::replace(joydesc, "button", "");
ss >> button;
keyHandlers_[key] = new JoyButtonHandler(joynum, button);
Logger::write(Logger::ZONE_INFO, "Input", "Binding joypad button " + ss.str() );
return true;
}
else if(joydesc.find("hat") == 0)
{
Uint8 hat;
joydesc = Utils::replace(joydesc, "hat", "");
std::stringstream sshat;
sshat << joydesc.at(0);
int hatnum;
sshat >> hatnum;
joydesc = joydesc.erase(0, 1);
if(joydesc == "leftup") hat = SDL_HAT_LEFTUP;
else if(joydesc == "left") hat = SDL_HAT_LEFT;
else if(joydesc == "leftdown") hat = SDL_HAT_LEFTDOWN;
else if(joydesc == "up") hat = SDL_HAT_UP;
//else if(joydesc == "centered") hat = SDL_HAT_CENTERED;
else if(joydesc == "down") hat = SDL_HAT_DOWN;
else if(joydesc == "rightup") hat = SDL_HAT_RIGHTUP;
else if(joydesc == "right") hat = SDL_HAT_RIGHT;
else if(joydesc == "rightdown") hat = SDL_HAT_RIGHTDOWN;
keyHandlers_[key] = new JoyHatHandler(joynum, hatnum, hat);
Logger::write(Logger::ZONE_INFO, "Input", "Binding joypad hat " + joydesc );
return true;
}
else if(joydesc.find("axis") == 0)
{
// string is now axis0+
unsigned int axis;
Sint16 min;
Sint16 max;
joydesc = Utils::replace(joydesc, "axis", "");
// string is now 0+
if(joydesc.find("-") != std::string::npos)
{
min = -32768;
max = -1000;
joydesc = Utils::replace(joydesc, "-", "");
}
else if(joydesc.find("+") != std::string::npos)
{
min = 1000;
max = 32767;
joydesc = Utils::replace(joydesc, "+", "");
}
// string is now just the axis number
std::stringstream ss;
ss << joydesc;
ss >> axis;
Logger::write(Logger::ZONE_INFO, "Input", "Binding joypad axis " + ss.str() );
keyHandlers_[key] = new JoyAxisHandler(joynum, axis, min, max);
return true;
}
}
Logger::write(Logger::ZONE_ERROR, "Input", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs");
return false;
} }
bool UserInput::SetKeyState(SDL_Scancode code, bool state) void UserInput::resetStates()
{ {
KeyCode_E key = GetKeycode(code); for(unsigned int i = 0; i < KeyCodeMax; ++i)
{
if(key == KeyCodeNull) { return false; } if(keyHandlers_[i])
if(KeyState.find(key) == KeyState.end()) { return false; } {
keyHandlers_[i]->reset();
KeyState[key] = state; }
return true; }
} }
bool UserInput::GetKeyState(KeyCode_E key) bool UserInput::update(SDL_Event &e)
{ {
if(KeyState.find(key) == KeyState.end()) { return false; } bool updated = false;
return KeyState[key]; for(unsigned int i = 0; i < KeyCodeMax; ++i)
{
InputHandler *h = keyHandlers_[i];
if(h)
{
if(h->update(e)) updated = true;
lastKeyState_[i] = h->pressed();
}
}
return updated;
} }
bool UserInput::keystate(KeyCode_E code)
{
return lastKeyState_[code];
}

View File

@@ -14,11 +14,14 @@
* along with RetroFE. If not, see <http://www.gnu.org/licenses/>. * along with RetroFE. If not, see <http://www.gnu.org/licenses/>.
*/ */
#pragma once #pragma once
#include <map>
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include <SDL2/SDL_joystick.h>
#include <map>
#include <string> #include <string>
#include <vector>
class Configuration; class Configuration;
class InputHandler;
class UserInput class UserInput
{ {
@@ -38,26 +41,22 @@ public:
KeyCodeLetterUp, KeyCodeLetterUp,
KeyCodeAdminMode, KeyCodeAdminMode,
KeyCodeHideItem, KeyCodeHideItem,
KeyCodeQuit KeyCodeQuit,
KeyCodeMax
}; };
UserInput(Configuration &c); UserInput(Configuration &c);
virtual ~UserInput(); virtual ~UserInput();
bool Initialize(); bool initialize();
SDL_Scancode GetScancode(KeyCode_E key); void resetStates();
KeyCode_E GetKeycode(SDL_Scancode scancode); bool update(SDL_Event &e);
bool SetKeyState(SDL_Scancode code, bool state); bool keystate(KeyCode_E);
bool GetKeyState(KeyCode_E key);
bool KeyStateChanged();
void ResetKeyStates();
private: private:
bool MapKey(std::string keyDescription, KeyCode_E key); bool MapKey(std::string keyDescription, KeyCode_E key);
std::map<KeyCode_E, SDL_Scancode> KeyMap; Configuration &config_;
std::map<SDL_Scancode, KeyCode_E> ReverseKeyMap; std::vector<SDL_Joystick *> joysticks_;
std::map<KeyCode_E, bool> KeyState; InputHandler *keyHandlers_[KeyCodeMax];
Configuration &Config; bool lastKeyState_[KeyCodeMax];
const Uint8 *SDLKeys;
}; };

View File

@@ -28,10 +28,9 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
std::string Configuration::AbsolutePath; std::string Configuration::absolutePath;
Configuration::Configuration() Configuration::Configuration()
: Verbose(false)
{ {
} }
@@ -39,14 +38,14 @@ Configuration::~Configuration()
{ {
} }
void Configuration::Initialize() void Configuration::initialize()
{ {
const char *environment = std::getenv("RETROFE_PATH"); const char *environment = std::getenv("RETROFE_PATH");
std::string environmentStr; std::string environmentStr;
if (environment != NULL) if (environment != NULL)
{ {
environmentStr = environment; environmentStr = environment;
Configuration::SetAbsolutePath(environment); absolutePath = environment;
} }
else else
{ {
@@ -55,44 +54,39 @@ void Configuration::Initialize()
CHAR exe[MAX_PATH]; CHAR exe[MAX_PATH];
GetModuleFileName(hModule, exe, MAX_PATH); GetModuleFileName(hModule, exe, MAX_PATH);
std::string sPath(exe); std::string sPath(exe);
sPath = Utils::GetDirectory(sPath); sPath = Utils::getDirectory(sPath);
sPath = Utils::GetParentDirectory(sPath); sPath = Utils::getParentDirectory(sPath);
#else #else
char exepath[1024]; char exepath[1024];
sprintf(exepath, "/proc/%d/exe", getpid()); sprintf(exepath, "/proc/%d/exe", getpid());
readlink(exepath, exepath, sizeof(exepath)); readlink(exepath, exepath, sizeof(exepath));
std::string sPath(exepath); std::string sPath(exepath);
sPath = Utils::GetDirectory(sPath); sPath = Utils::getDirectory(sPath);
#endif #endif
Configuration::SetAbsolutePath(sPath); absolutePath = sPath;
} }
} }
void Configuration::SetCurrentCollection(std::string collection) bool Configuration::import(std::string keyPrefix, std::string file)
{ {
CurrentCollection = collection; return import("", keyPrefix, file);
} }
std::string Configuration::GetCurrentCollection() bool Configuration::import(std::string collection, std::string keyPrefix, std::string file)
{
return CurrentCollection;
}
bool Configuration::Import(std::string keyPrefix, std::string file)
{ {
bool retVal = true; bool retVal = true;
int lineCount = 0; int lineCount = 0;
std::string line; std::string line;
Logger::Write(Logger::ZONE_INFO, "Configuration", "Importing \"" + file + "\""); Logger::write(Logger::ZONE_INFO, "Configuration", "Importing \"" + file + "\"");
std::ifstream ifs(file.c_str()); std::ifstream ifs(file.c_str());
if (!ifs.is_open()) if (!ifs.is_open())
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file + "\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file + "\"");
return false; return false;
} }
@@ -100,7 +94,7 @@ bool Configuration::Import(std::string keyPrefix, std::string file)
while (std::getline (ifs, line)) while (std::getline (ifs, line))
{ {
lineCount++; lineCount++;
retVal = retVal && ParseLine(keyPrefix, line, lineCount); retVal = retVal && parseLine(collection, keyPrefix, line, lineCount);
} }
ifs.close(); ifs.close();
@@ -108,7 +102,8 @@ bool Configuration::Import(std::string keyPrefix, std::string file)
return retVal; return retVal;
} }
bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineCount)
bool Configuration::parseLine(std::string collection, std::string keyPrefix, std::string line, int lineCount)
{ {
bool retVal = false; bool retVal = false;
std::string key; std::string key;
@@ -117,7 +112,7 @@ bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineC
std::string delimiter = "="; std::string delimiter = "=";
// strip out any comments // strip out any comments
line = Utils::FilterComments(line); line = Utils::filterComments(line);
if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos)) if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos))
{ {
@@ -133,32 +128,33 @@ bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineC
key = keyPrefix + line.substr(0, position); key = keyPrefix + line.substr(0, position);
key = TrimEnds(key); key = trimEnds(key);
value = line.substr(position + delimiter.length(), line.length()); value = line.substr(position + delimiter.length(), line.length());
value = TrimEnds(value); value = trimEnds(value);
value = Utils::replace(value, "%ITEM_COLLECTION_NAME%", collection);
Properties.insert(PropertiesPair(key, value)); properties_.insert(PropertiesPair(key, value));
std::stringstream ss; std::stringstream ss;
ss << "Dump: " << "\"" << key << "\" = \"" << value << "\""; ss << "Dump: " << "\"" << key << "\" = \"" << value << "\"";
Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str()); Logger::write(Logger::ZONE_INFO, "Configuration", ss.str());
retVal = true; retVal = true;
} }
else else
{ {
std::stringstream ss; std::stringstream ss;
ss << "Missing an assignment operator (=) on line " << lineCount; ss << "Missing an assignment operator (=) on line " << lineCount;
Logger::Write(Logger::ZONE_ERROR, "Configuration", ss.str()); Logger::write(Logger::ZONE_ERROR, "Configuration", ss.str());
} }
return retVal; return retVal;
} }
std::string Configuration::TrimEnds(std::string str) std::string Configuration::trimEnds(std::string str)
{ {
// strip off any initial tabs or spaces // strip off any initial tabs or spaces
size_t trimStart = str.find_first_not_of(" \t"); size_t trimStart = str.find_first_not_of(" \t");
@@ -173,46 +169,39 @@ std::string Configuration::TrimEnds(std::string str)
return str; return str;
} }
bool Configuration::GetRawProperty(std::string key, std::string &value) bool Configuration::getRawProperty(std::string key, std::string &value)
{ {
bool retVal = false; bool retVal = false;
if(Properties.find(key) != Properties.end()) if(properties_.find(key) != properties_.end())
{ {
value = Properties[key]; value = properties_[key];
retVal = true; retVal = true;
} }
else if(Verbose)
{
Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key);
}
return retVal; return retVal;
} }
bool Configuration::GetProperty(std::string key, std::string &value) bool Configuration::getProperty(std::string key, std::string &value)
{ {
bool retVal = GetRawProperty(key, value); bool retVal = getRawProperty(key, value);
std::string baseMediaPath = GetAbsolutePath(); std::string baseMediaPath = absolutePath;
std::string baseItemPath = GetAbsolutePath(); std::string baseItemPath = absolutePath;
std::string collectionName;
GetRawProperty("baseMediaPath", baseMediaPath); getRawProperty("baseMediaPath", baseMediaPath);
GetRawProperty("baseItemPath", baseItemPath); getRawProperty("baseItemPath", baseItemPath);
collectionName = GetCurrentCollection();
value = Utils::Replace(value, "%BASE_MEDIA_PATH%", baseMediaPath); value = Utils::replace(value, "%BASE_MEDIA_PATH%", baseMediaPath);
value = Utils::Replace(value, "%BASE_ITEM_PATH%", baseItemPath); value = Utils::replace(value, "%BASE_ITEM_PATH%", baseItemPath);
value = Utils::Replace(value, "%ITEM_COLLECTION_NAME%", collectionName);
return retVal; return retVal;
} }
bool Configuration::GetProperty(std::string key, int &value) bool Configuration::getProperty(std::string key, int &value)
{ {
std::string strValue; std::string strValue;
bool retVal = GetProperty(key, strValue); bool retVal = getProperty(key, strValue);
if(retVal) if(retVal)
{ {
@@ -224,11 +213,11 @@ bool Configuration::GetProperty(std::string key, int &value)
return retVal; return retVal;
} }
bool Configuration::GetProperty(std::string key, bool &value) bool Configuration::getProperty(std::string key, bool &value)
{ {
std::string strValue; std::string strValue;
bool retVal = GetProperty(key, strValue); bool retVal = getProperty(key, strValue);
if(retVal) if(retVal)
{ {
@@ -245,21 +234,21 @@ bool Configuration::GetProperty(std::string key, bool &value)
return retVal; return retVal;
} }
void Configuration::SetProperty(std::string key, std::string value) void Configuration::setProperty(std::string key, std::string value)
{ {
Properties[key] = value; properties_[key] = value;
} }
bool Configuration::PropertyExists(std::string key) bool Configuration::propertyExists(std::string key)
{ {
return (Properties.find(key) != Properties.end()); return (properties_.find(key) != properties_.end());
} }
bool Configuration::PropertyPrefixExists(std::string key) bool Configuration::propertyPrefixExists(std::string key)
{ {
PropertiesType::iterator it; PropertiesType::iterator it;
for(it = Properties.begin(); it != Properties.end(); ++it) for(it = properties_.begin(); it != properties_.end(); ++it)
{ {
std::string search = key + "."; std::string search = key + ".";
if(it->first.compare(0, search.length(), search) == 0) if(it->first.compare(0, search.length(), search) == 0)
@@ -271,16 +260,16 @@ bool Configuration::PropertyPrefixExists(std::string key)
return false; return false;
} }
void Configuration::GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children) void Configuration::childKeyCrumbs(std::string parent, std::vector<std::string> &children)
{ {
PropertiesType::iterator it; PropertiesType::iterator it;
for(it = Properties.begin(); it != Properties.end(); ++it) for(it = properties_.begin(); it != properties_.end(); ++it)
{ {
std::string search = parent + "."; std::string search = parent + ".";
if(it->first.compare(0, search.length(), search) == 0) if(it->first.compare(0, search.length(), search) == 0)
{ {
std::string crumb = Utils::Replace(it->first, search, ""); std::string crumb = Utils::replace(it->first, search, "");
std::size_t end = crumb.find_first_of("."); std::size_t end = crumb.find_first_of(".");
@@ -297,7 +286,7 @@ void Configuration::GetChildKeyCrumbs(std::string parent, std::vector<std::strin
} }
} }
std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string path) std::string Configuration::convertToAbsolutePath(std::string prefix, std::string path)
{ {
char first = ' '; char first = ' ';
char second = ' '; char second = ' ';
@@ -312,128 +301,98 @@ std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string
} }
// check to see if it is already an absolute path // check to see if it is already an absolute path
if((first != Utils::PathSeparator) && if((first != Utils::pathSeparator) &&
//(first != '.') && //(first != '.') &&
(second != ':')) (second != ':'))
{ {
path = Utils::CombinePath(prefix, path); path = Utils::combinePath(prefix, path);
} }
return path; return path;
} }
bool Configuration::GetPropertyAbsolutePath(std::string key, std::string &value) bool Configuration::getPropertyAbsolutePath(std::string key, std::string &value)
{ {
bool retVal = GetProperty(key, value); bool retVal = getProperty(key, value);
if(retVal) if(retVal)
{ {
value = ConvertToAbsolutePath(GetAbsolutePath(), value); value = convertToAbsolutePath(absolutePath, value);
} }
return retVal; return retVal;
} }
void Configuration::GetMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, std::string &value) void Configuration::getMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, std::string &value)
{ {
return GetMediaPropertyAbsolutePath(collectionName, mediaType, false, value); return getMediaPropertyAbsolutePath(collectionName, mediaType, false, value);
} }
void Configuration::GetMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, bool system, std::string &value) void Configuration::getMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, bool system, std::string &value)
{ {
std::string key = "collections." + collectionName + ".media." + mediaType; std::string key = "collections." + collectionName + ".media." + mediaType;
// use user-overridden setting if it exists // use user-overridden setting if it exists
if(GetPropertyAbsolutePath(key, value)) if(getPropertyAbsolutePath(key, value))
{ {
return; return;
} }
// use user-overridden base media path if it was specified // use user-overridden base media path if it was specified
std::string baseMediaPath; std::string baseMediaPath;
if(!GetPropertyAbsolutePath("baseMediaPath", baseMediaPath)) if(!getPropertyAbsolutePath("baseMediaPath", baseMediaPath))
{ {
// base media path was not specified, assume media files are in the collection // base media path was not specified, assume media files are in the collection
baseMediaPath = Utils::CombinePath(GetAbsolutePath(), "collections"); baseMediaPath = Utils::combinePath(absolutePath, "collections");
} }
if(mediaType == "manufacturer") if(mediaType == "manufacturer")
{ {
value = Utils::CombinePath(baseMediaPath, "_manufacturer"); value = Utils::combinePath(baseMediaPath, "_manufacturer");
} }
else if(mediaType == "genre") else if(mediaType == "genre")
{ {
value = Utils::CombinePath(baseMediaPath, "_genre"); value = Utils::combinePath(baseMediaPath, "_genre");
} }
else if(mediaType == "year") else if(mediaType == "year")
{ {
value = Utils::CombinePath(baseMediaPath, "_year"); value = Utils::combinePath(baseMediaPath, "_year");
} }
else if(mediaType == "number_players") else if(mediaType == "number_players")
{ {
value = Utils::CombinePath(baseMediaPath, "_number_players"); value = Utils::combinePath(baseMediaPath, "_number_players");
} }
else if(mediaType == "number_buttons") else if(mediaType == "number_buttons")
{ {
value = Utils::CombinePath(baseMediaPath, "_number_buttons"); value = Utils::combinePath(baseMediaPath, "_number_buttons");
} }
else if(system) else if(system)
{ {
value = Utils::CombinePath(baseMediaPath, collectionName, "system_artwork"); value = Utils::combinePath(baseMediaPath, collectionName, "system_artwork");
} }
else else
{ {
value = Utils::CombinePath(baseMediaPath, collectionName, "medium_artwork", mediaType); value = Utils::combinePath(baseMediaPath, collectionName, "medium_artwork", mediaType);
} }
} }
void Configuration::GetCollectionAbsolutePath(std::string collectionName, std::string &value) void Configuration::getCollectionAbsolutePath(std::string collectionName, std::string &value)
{ {
std::string key = "collections." + collectionName + ".list.path"; std::string key = "collections." + collectionName + ".list.path";
if(GetPropertyAbsolutePath(key, value)) if(getPropertyAbsolutePath(key, value))
{ {
return; return;
} }
std::string baseItemPath; std::string baseItemPath;
if(GetPropertyAbsolutePath("baseItemPath", baseItemPath)) if(getPropertyAbsolutePath("baseItemPath", baseItemPath))
{ {
value = Utils::CombinePath(baseItemPath, collectionName); value = Utils::combinePath(baseItemPath, collectionName);
return; return;
} }
value = Utils::CombinePath(GetAbsolutePath(), "collections", collectionName, "roms"); value = Utils::combinePath(absolutePath, "collections", collectionName, "roms");
} }
void Configuration::SetAbsolutePath(std::string absolutePath)
{
AbsolutePath = absolutePath;
}
std::string Configuration::GetAbsolutePath()
{
return AbsolutePath;
}
bool Configuration::IsVerbose() const
{
return Verbose;
}
void Configuration::SetVerbose(bool verbose)
{
this->Verbose = verbose;
}
void Configuration::SetStatus(std::string status)
{
Status = status;
}
std::string Configuration::GetStatus()
{
return Status;
}

View File

@@ -24,41 +24,31 @@ class Configuration
public: public:
Configuration(); Configuration();
virtual ~Configuration(); virtual ~Configuration();
static void Initialize(); static void initialize();
static void SetAbsolutePath(std::string absolutePath); static std::string convertToAbsolutePath(std::string prefix, std::string path);
static std::string GetAbsolutePath();
static std::string ConvertToAbsolutePath(std::string prefix, std::string path);
void SetStatus(std::string status);
std::string GetStatus();
// gets the global configuration // gets the global configuration
bool Import(std::string keyPrefix, std::string file); bool import(std::string keyPrefix, std::string file);
void SetCurrentCollection(std::string collection); bool import(std::string collection, std::string keyPrefix, std::string file);
std::string GetCurrentCollection(); bool getProperty(std::string key, std::string &value);
bool GetProperty(std::string key, std::string &value); bool getProperty(std::string key, int &value);
bool GetProperty(std::string key, int &value); bool getProperty(std::string key, bool &value);
bool GetProperty(std::string key, bool &value); void childKeyCrumbs(std::string parent, std::vector<std::string> &children);
void GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children); void setProperty(std::string key, std::string value);
void SetProperty(std::string key, std::string value); bool propertyExists(std::string key);
bool PropertyExists(std::string key); bool propertyPrefixExists(std::string key);
bool PropertyPrefixExists(std::string key); bool getPropertyAbsolutePath(std::string key, std::string &value);
bool GetPropertyAbsolutePath(std::string key, std::string &value); void getMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, std::string &value);
void GetMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, std::string &value); void getMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, bool system, std::string &value);
void GetMediaPropertyAbsolutePath(std::string collectionName, std::string mediaType, bool system, std::string &value); void getCollectionAbsolutePath(std::string collectionName, std::string &value);
void GetCollectionAbsolutePath(std::string collectionName, std::string &value); static std::string absolutePath;
bool IsVerbose() const;
void SetVerbose(bool verbose);
private: private:
bool GetRawProperty(std::string key, std::string &value); bool getRawProperty(std::string key, std::string &value);
bool ParseLine(std::string keyPrefix, std::string line, int lineCount); bool parseLine(std::string collection, std::string keyPrefix, std::string line, int lineCount);
std::string TrimEnds(std::string str); std::string trimEnds(std::string str);
typedef std::map<std::string, std::string> PropertiesType; typedef std::map<std::string, std::string> PropertiesType;
typedef std::pair<std::string, std::string> PropertiesPair; typedef std::pair<std::string, std::string> PropertiesPair;
bool Verbose;
static std::string AbsolutePath; PropertiesType properties_;
std::string CurrentCollection;
PropertiesType Properties;
std::string Status;
}; };

View File

@@ -20,29 +20,29 @@
#include <fstream> #include <fstream>
DB::DB(std::string dbFile) DB::DB(std::string dbFile)
: Path(dbFile) : handle(NULL)
, Handle(NULL) , path_(dbFile)
{ {
} }
DB::~DB() DB::~DB()
{ {
DeInitialize(); deInitialize();
} }
bool DB::Initialize() bool DB::initialize()
{ {
bool retVal = false; bool retVal = false;
if(sqlite3_open(Path.c_str(), &Handle) != 0) if(sqlite3_open(path_.c_str(), &handle) != 0)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Cannot open database: \"" << Path << "\"" << sqlite3_errmsg(Handle); ss << "Cannot open database: \"" << path_ << "\"" << sqlite3_errmsg(handle);
Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); Logger::write(Logger::ZONE_ERROR, "Database", ss.str());
} }
else else
{ {
Logger::Write(Logger::ZONE_INFO, "Database", "Opened database \"" + Path + "\""); Logger::write(Logger::ZONE_INFO, "Database", "Opened database \"" + path_ + "\"");
retVal = true; retVal = true;
} }
@@ -50,12 +50,12 @@ bool DB::Initialize()
} }
void DB::DeInitialize() void DB::deInitialize()
{ {
if(Handle != NULL) if(handle != NULL)
{ {
sqlite3_close(Handle); sqlite3_close(handle);
Handle = NULL; handle = NULL;
} }
} }

View File

@@ -21,16 +21,12 @@ class DB
{ {
public: public:
DB(std::string dbFile); DB(std::string dbFile);
bool Initialize(); bool initialize();
void DeInitialize(); void deInitialize();
virtual ~DB(); virtual ~DB();
sqlite3 *GetHandle() sqlite3 *handle;
{
return Handle;
}
private: private:
std::string Path; std::string path_;
sqlite3 *Handle;
}; };

View File

@@ -20,5 +20,5 @@ class Metadata
{ {
public: public:
virtual ~Metadata() {} virtual ~Metadata() {}
virtual bool Import(std::string file, std::string collectionName) = 0; virtual bool import(std::string file, std::string collectionName) = 0;
}; };

View File

@@ -34,8 +34,8 @@
#include <exception> #include <exception>
MetadataDatabase::MetadataDatabase(DB &db, Configuration &c) MetadataDatabase::MetadataDatabase(DB &db, Configuration &c)
: Config(c) : config_(c)
, DBInstance(db) , db_(db)
{ {
} }
@@ -44,13 +44,13 @@ MetadataDatabase::~MetadataDatabase()
{ {
} }
bool MetadataDatabase::ResetDatabase() bool MetadataDatabase::resetDatabase()
{ {
int rc; int rc;
char *error = NULL; char *error = NULL;
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
Logger::Write(Logger::ZONE_INFO, "Metadata", "Erasing"); Logger::write(Logger::ZONE_INFO, "Metadata", "Erasing");
std::string sql; std::string sql;
sql.append("DROP TABLE IF EXISTS Meta;"); sql.append("DROP TABLE IF EXISTS Meta;");
@@ -61,18 +61,18 @@ bool MetadataDatabase::ResetDatabase()
{ {
std::stringstream ss; std::stringstream ss;
ss << "Unable to create Metadata table. Error: " << error; ss << "Unable to create Metadata table. Error: " << error;
Logger::Write(Logger::ZONE_ERROR, "Metadata", ss.str()); Logger::write(Logger::ZONE_ERROR, "Metadata", ss.str());
return false; return false;
} }
return Initialize(); return initialize();
} }
bool MetadataDatabase::Initialize() bool MetadataDatabase::initialize()
{ {
int rc; int rc;
char *error = NULL; char *error = NULL;
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
std::string sql; std::string sql;
sql.append("CREATE TABLE IF NOT EXISTS Meta("); sql.append("CREATE TABLE IF NOT EXISTS Meta(");
@@ -93,31 +93,31 @@ bool MetadataDatabase::Initialize()
{ {
std::stringstream ss; std::stringstream ss;
ss << "Unable to create Metadata table. Error: " << error; ss << "Unable to create Metadata table. Error: " << error;
Logger::Write(Logger::ZONE_ERROR, "Metadata", ss.str()); Logger::write(Logger::ZONE_ERROR, "Metadata", ss.str());
return false; return false;
} }
if(NeedsRefresh()) if(needsRefresh())
{ {
ImportDirectory(); importDirectory();
} }
return true; return true;
} }
bool MetadataDatabase::ImportDirectory() bool MetadataDatabase::importDirectory()
{ {
DIR *dp; DIR *dp;
struct dirent *dirp; struct dirent *dirp;
std::string hyperListPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "meta", "hyperlist"); std::string hyperListPath = Utils::combinePath(Configuration::absolutePath, "meta", "hyperlist");
std::string mameListPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "meta", "mamelist"); std::string mameListPath = Utils::combinePath(Configuration::absolutePath, "meta", "mamelist");
dp = opendir(hyperListPath.c_str()); dp = opendir(hyperListPath.c_str());
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_INFO, "MetadataDatabase", "Could not read directory \"" + hyperListPath + "\""); Logger::write(Logger::ZONE_INFO, "MetadataDatabase", "Could not read directory \"" + hyperListPath + "\"");
} }
else else
{ {
@@ -135,9 +135,9 @@ bool MetadataDatabase::ImportDirectory()
if(extension == ".xml") if(extension == ".xml")
{ {
std::string importFile = Utils::CombinePath(hyperListPath, std::string(dirp->d_name)); std::string importFile = Utils::combinePath(hyperListPath, std::string(dirp->d_name));
Logger::Write(Logger::ZONE_INFO, "Metadata", "Importing hyperlist: " + importFile); Logger::write(Logger::ZONE_INFO, "Metadata", "Importing hyperlist: " + importFile);
ImportHyperList(importFile, collectionName); importHyperlist(importFile, collectionName);
} }
} }
} }
@@ -149,7 +149,7 @@ bool MetadataDatabase::ImportDirectory()
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_ERROR, "CollectionInfoBuilder", "Could not read directory \"" + mameListPath + "\""); Logger::write(Logger::ZONE_ERROR, "CollectionInfoBuilder", "Could not read directory \"" + mameListPath + "\"");
} }
else else
{ {
@@ -167,10 +167,10 @@ bool MetadataDatabase::ImportDirectory()
if(extension == ".xml") if(extension == ".xml")
{ {
std::string importFile = Utils::CombinePath(mameListPath, std::string(dirp->d_name)); std::string importFile = Utils::combinePath(mameListPath, std::string(dirp->d_name));
Logger::Write(Logger::ZONE_INFO, "Metadata", "Importing mamelist: " + importFile); Logger::write(Logger::ZONE_INFO, "Metadata", "Importing mamelist: " + importFile);
Config.SetStatus("Scraping data from " + importFile); config_.setProperty("status", "Scraping data from " + importFile);
ImportMameList(importFile, collectionName); importMamelist(importFile, collectionName);
} }
} }
} }
@@ -181,26 +181,26 @@ bool MetadataDatabase::ImportDirectory()
return true; return true;
} }
void MetadataDatabase::InjectMetadata(CollectionInfo *collection) void MetadataDatabase::injectMetadata(CollectionInfo *collection)
{ {
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
int rc; int rc;
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
bool showParenthesis = true; bool showParenthesis = true;
bool showSquareBrackets = true; bool showSquareBrackets = true;
(void)Config.GetProperty("showParenthesis", showParenthesis); (void)config_.getProperty("showParenthesis", showParenthesis);
(void)Config.GetProperty("showSquareBrackets", showSquareBrackets); (void)config_.getProperty("showSquareBrackets", showSquareBrackets);
// items into a hash to make it easily searchable // items into a hash to make it easily searchable
std::vector<Item *> *items = collection->GetItems(); std::vector<Item *> *items = &collection->items;
std::map<std::string, Item *> itemMap; std::map<std::string, Item *> itemMap;
for(std::vector<Item *>::iterator it = items->begin(); it != items->end(); it++) for(std::vector<Item *>::iterator it = items->begin(); it != items->end(); it++)
{ {
itemMap[(*it)->GetName()] = *it; itemMap[(*it)->name] = *it;
} }
//todo: program crashes if this query fails //todo: program crashes if this query fails
@@ -209,7 +209,7 @@ void MetadataDatabase::InjectMetadata(CollectionInfo *collection)
"FROM Meta WHERE collectionName=? ORDER BY title ASC;", "FROM Meta WHERE collectionName=? ORDER BY title ASC;",
-1, &stmt, 0); -1, &stmt, 0);
sqlite3_bind_text(stmt, 1, collection->GetMetadataType().c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 1, collection->metadataType.c_str(), -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt); rc = sqlite3_step(stmt);
@@ -265,22 +265,22 @@ void MetadataDatabase::InjectMetadata(CollectionInfo *collection)
if(it != itemMap.end()) if(it != itemMap.end())
{ {
Item *item = it->second; Item *item = it->second;
item->SetTitle(title); item->title = title;
item->SetFullTitle(fullTitle); item->fullTitle = fullTitle;
item->SetYear(year); item->year = year;
item->SetManufacturer(manufacturer); item->manufacturer = manufacturer;
item->SetGenre(genre); item->genre = genre;
item->SetNumberPlayers(numberPlayers); item->numberPlayers = numberPlayers;
item->SetNumberButtons(numberButtons); item->numberButtons = numberButtons;
item->SetCloneOf(cloneOf); item->cloneof = cloneOf;
} }
rc = sqlite3_step(stmt); rc = sqlite3_step(stmt);
} }
} }
bool MetadataDatabase::NeedsRefresh() bool MetadataDatabase::needsRefresh()
{ {
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
sqlite3_prepare_v2(handle, sqlite3_prepare_v2(handle,
@@ -301,11 +301,11 @@ bool MetadataDatabase::NeedsRefresh()
} }
} }
bool MetadataDatabase::ImportHyperList(std::string hyperlistFile, std::string collectionName) bool MetadataDatabase::importHyperlist(std::string hyperlistFile, std::string collectionName)
{ {
char *error = NULL; char *error = NULL;
Config.SetStatus("Scraping data from \"" + hyperlistFile + "\""); config_.setProperty("status", "Scraping data from \"" + hyperlistFile + "\"");
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
std::ifstream file(hyperlistFile.c_str()); std::ifstream file(hyperlistFile.c_str());
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
@@ -320,10 +320,10 @@ bool MetadataDatabase::ImportHyperList(std::string hyperlistFile, std::string co
if(!root) if(!root)
{ {
Logger::Write(Logger::ZONE_ERROR, "Metadata", "Does not appear to be a HyperList file (missing <menu> tag)"); Logger::write(Logger::ZONE_ERROR, "Metadata", "Does not appear to be a HyperList file (missing <menu> tag)");
return false; return false;
} }
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error);
for(rapidxml::xml_node<> *game = root->first_node("game"); game; game = game->next_sibling("game")) for(rapidxml::xml_node<> *game = root->first_node("game"); game; game = game->next_sibling("game"))
{ {
@@ -366,7 +366,7 @@ bool MetadataDatabase::ImportHyperList(std::string hyperlistFile, std::string co
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
} }
} }
Config.SetStatus("Saving data from \"" + hyperlistFile + "\" to database"); config_.setProperty("status", "Saving data from \"" + hyperlistFile + "\" to database");
sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error);
return true; return true;
@@ -378,28 +378,28 @@ bool MetadataDatabase::ImportHyperList(std::string hyperlistFile, std::string co
std::stringstream ss; std::stringstream ss;
ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what();
Logger::Write(Logger::ZONE_ERROR, "Metadata", ss.str()); Logger::write(Logger::ZONE_ERROR, "Metadata", ss.str());
} }
catch(std::exception &e) catch(std::exception &e)
{ {
std::string what = e.what(); std::string what = e.what();
Logger::Write(Logger::ZONE_ERROR, "Metadata", "Could not parse hyperlist file. Reason: " + what); Logger::write(Logger::ZONE_ERROR, "Metadata", "Could not parse hyperlist file. Reason: " + what);
} }
return false; return false;
} }
bool MetadataDatabase::ImportMameList(std::string filename, std::string collectionName) bool MetadataDatabase::importMamelist(std::string filename, std::string collectionName)
{ {
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
rapidxml::xml_node<> * rootNode; rapidxml::xml_node<> * rootNode;
char *error = NULL; char *error = NULL;
sqlite3 *handle = DBInstance.GetHandle(); sqlite3 *handle = db_.handle;
Config.SetStatus("Scraping data from \"" + filename + "\" (this will take a while)"); config_.setProperty("status", "Scraping data from \"" + filename + "\" (this will take a while)");
Logger::Write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\" (this will take a while)"); Logger::write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\" (this will take a while)");
std::ifstream file(filename.c_str()); std::ifstream file(filename.c_str());
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
@@ -412,7 +412,7 @@ bool MetadataDatabase::ImportMameList(std::string filename, std::string collecti
if(!rootNode) if(!rootNode)
{ {
Logger::Write(Logger::ZONE_ERROR, "Metadata", "Does not appear to be a MameList file (missing <mame> tag)"); Logger::write(Logger::ZONE_ERROR, "Metadata", "Does not appear to be a MameList file (missing <mame> tag)");
return false; return false;
} }
@@ -478,7 +478,7 @@ bool MetadataDatabase::ImportMameList(std::string filename, std::string collecti
} }
} }
Config.SetStatus("Saving data from \"" + filename + "\" to database"); config_.setProperty("status", "Saving data from \"" + filename + "\" to database");
sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error);
return true; return true;

View File

@@ -29,16 +29,16 @@ class MetadataDatabase
public: public:
MetadataDatabase(DB &db, Configuration &c); MetadataDatabase(DB &db, Configuration &c);
virtual ~MetadataDatabase(); virtual ~MetadataDatabase();
bool Initialize(); bool initialize();
bool ResetDatabase(); bool resetDatabase();
void InjectMetadata(CollectionInfo *collection); void injectMetadata(CollectionInfo *collection);
bool ImportHyperList(std::string hyperlistFile, std::string collectionName); bool importHyperlist(std::string hyperlistFile, std::string collectionName);
bool ImportMameList(std::string filename, std::string collectionName); bool importMamelist(std::string filename, std::string collectionName);
private: private:
bool ImportDirectory(); bool importDirectory();
bool NeedsRefresh(); bool needsRefresh();
Configuration &Config; Configuration &config_;
DB &DBInstance; DB &db_;
}; };

View File

@@ -19,45 +19,41 @@
#include <cstdlib> #include <cstdlib>
AttractMode::AttractMode() AttractMode::AttractMode()
: IsActive(false) : idleTime(0)
, ElapsedTime(0) , isActive_(false)
, ActiveTime(0) , elapsedTime_(0)
, IdleTime(0) , activeTime_(0)
{ {
} }
void AttractMode::SetIdleTime(float time) void AttractMode::reset()
{ {
IdleTime = time; elapsedTime_ = 0;
} isActive_ = false;
void AttractMode::Reset() activeTime_ = 0;
{
ElapsedTime = 0;
IsActive = false;
ActiveTime = 0;
} }
void AttractMode::Update(float dt, Page &page) void AttractMode::update(float dt, Page &page)
{ {
ElapsedTime += dt; elapsedTime_ += dt;
// enable attract mode when idling for the expected time. Disable if idle time is set to 0. // enable attract mode when idling for the expected time. Disable if idle time is set to 0.
if(!IsActive && ElapsedTime > IdleTime && IdleTime > 0) if(!isActive_ && elapsedTime_ > idleTime && idleTime > 0)
{ {
IsActive = true; isActive_ = true;
ElapsedTime = 0; elapsedTime_ = 0;
ActiveTime = ((float)((1000+rand()) % 5000)) / 1000; activeTime_ = ((float)((1000+rand()) % 5000)) / 1000;
} }
if(IsActive) if(isActive_)
{ {
page.SetScrolling(Page::ScrollDirectionForward); page.setScrolling(Page::ScrollDirectionForward);
if(ElapsedTime > ActiveTime) if(elapsedTime_ > activeTime_)
{ {
ElapsedTime = 0; elapsedTime_ = 0;
IsActive = false; isActive_ = false;
page.SetScrolling(Page::ScrollDirectionIdle); page.setScrolling(Page::ScrollDirectionIdle);
} }
} }
} }

View File

@@ -21,14 +21,13 @@ class AttractMode
{ {
public: public:
AttractMode(); AttractMode();
void SetIdleTime(float time); void reset();
void Reset(); void update(float dt, Page &page);
void Update(float dt, Page &page); float idleTime;
private: private:
bool IsActive; bool isActive_;
float ElapsedTime; float elapsedTime_;
float ActiveTime; float activeTime_;
float IdleTime;
}; };

View File

@@ -31,109 +31,109 @@
#endif #endif
Launcher::Launcher(RetroFE &p, Configuration &c) Launcher::Launcher(RetroFE &p, Configuration &c)
: Config(c) : config_(c)
, RetroFEInst(p) , retrofe_(p)
{ {
} }
bool Launcher::Run(std::string collection, Item *collectionItem) bool Launcher::run(std::string collection, Item *collectionItem)
{ {
std::string launcherName = collectionItem->GetLauncher(); std::string launcherName = collectionItem->collectionInfo->launcher;
std::string executablePath; std::string executablePath;
std::string selectedItemsDirectory; std::string selectedItemsDirectory;
std::string selectedItemsPath; std::string selectedItemsPath;
std::string currentDirectory; std::string currentDirectory;
std::string extensions; std::string extensionstr;
std::string matchedExtension; std::string matchedExtension;
std::string args; std::string args;
if(!GetLauncherExecutable(executablePath, currentDirectory, launcherName)) if(!launcherExecutable(executablePath, currentDirectory, launcherName))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")"); Logger::write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")");
return false; return false;
} }
if(!GetExtensions(extensions, collection)) if(!extensions(extensionstr, collection))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\""); Logger::write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\"");
return false; return false;
} }
if(!GetCollectionDirectory(selectedItemsDirectory, collection)) if(!collectionDirectory(selectedItemsDirectory, collection))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\""); Logger::write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\"");
return false; return false;
} }
if(!GetLauncherArgs(args, launcherName)) if(!launcherArgs(args, launcherName))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName); Logger::write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName);
return false; return false;
} }
if(!FindFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->GetName(), extensions)) if(!findFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->name, extensionstr))
{ {
// FindFile() prints out diagnostic messages for us, no need to print anything here // FindFile() prints out diagnostic messages for us, no need to print anything here
return false; return false;
} }
args = ReplaceVariables(args, args = replaceVariables(args,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->name,
collectionItem->GetFileName(), collectionItem->filename(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
executablePath = ReplaceVariables(executablePath, executablePath = replaceVariables(executablePath,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->name,
collectionItem->GetFileName(), collectionItem->filename(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
currentDirectory = ReplaceVariables(currentDirectory, currentDirectory = replaceVariables(currentDirectory,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->name,
collectionItem->GetFileName(), collectionItem->filename(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
if(!ExecuteCommand(executablePath, args, currentDirectory)) if(!execute(executablePath, args, currentDirectory))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to launch."); Logger::write(Logger::ZONE_ERROR, "Launcher", "Failed to launch.");
return false; return false;
} }
return true; return true;
} }
std::string Launcher::ReplaceVariables(std::string str, std::string Launcher::replaceVariables(std::string str,
std::string itemFilePath, std::string itemFilePath,
std::string itemName, std::string itemName,
std::string itemFilename, std::string itemFilename,
std::string itemDirectory, std::string itemDirectory,
std::string itemCollectionName) std::string itemCollectionName)
{ {
str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath); str = Utils::replace(str, "%ITEM_FILEPATH%", itemFilePath);
str = Utils::Replace(str, "%ITEM_NAME%", itemName); str = Utils::replace(str, "%ITEM_NAME%", itemName);
str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename); str = Utils::replace(str, "%ITEM_FILENAME%", itemFilename);
str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory); str = Utils::replace(str, "%ITEM_DIRECTORY%", itemDirectory);
str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName); str = Utils::replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName);
str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath()); str = Utils::replace(str, "%RETROFE_PATH%", Configuration::absolutePath);
#ifdef WIN32 #ifdef WIN32
str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Utils::CombinePath(Configuration::GetAbsolutePath(), "RetroFE.exe")); str = Utils::replace(str, "%RETROFE_EXEC_PATH%", Utils::combinePath(Configuration::absolutePath, "RetroFE.exe"));
#else #else
str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Utils::CombinePath(Configuration::GetAbsolutePath(), "RetroFE")); str = Utils::replace(str, "%RETROFE_EXEC_PATH%", Utils::combinePath(Configuration::absolutePath, "RetroFE"));
#endif #endif
return str; return str;
} }
bool Launcher::ExecuteCommand(std::string executable, std::string args, std::string currentDirectory) bool Launcher::execute(std::string executable, std::string args, std::string currentDirectory)
{ {
bool retVal = false; bool retVal = false;
std::string executionString = "\"" + executable + "\" " + args; std::string executionString = "\"" + executable + "\" " + args;
Logger::Write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString); Logger::write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString);
Logger::Write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory); Logger::write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory);
//todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface) //todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface)
RetroFEInst.LaunchEnter(); retrofe_.launchEnter();
#ifdef WIN32 #ifdef WIN32
STARTUPINFO startupInfo; STARTUPINFO startupInfo;
@@ -153,7 +153,7 @@ bool Launcher::ExecuteCommand(std::string executable, std::string args, std::str
if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, currDir, &startupInfo, &processInfo)) if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, currDir, &startupInfo, &processInfo))
#else #else
const std::size_t last_slash_idx = executable.rfind(Utils::PathSeparator); const std::size_t last_slash_idx = executable.rfind(Utils::pathSeparator);
if (last_slash_idx != std::string::npos) if (last_slash_idx != std::string::npos)
{ {
std::string applicationName = executable.substr(last_slash_idx + 1); std::string applicationName = executable.substr(last_slash_idx + 1);
@@ -162,7 +162,7 @@ bool Launcher::ExecuteCommand(std::string executable, std::string args, std::str
if(system(executionString.c_str()) != 0) if(system(executionString.c_str()) != 0)
#endif #endif
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable); Logger::write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable);
} }
else else
@@ -183,18 +183,18 @@ bool Launcher::ExecuteCommand(std::string executable, std::string args, std::str
retVal = true; retVal = true;
} }
Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed"); Logger::write(Logger::ZONE_INFO, "Launcher", "Completed");
RetroFEInst.LaunchExit(); retrofe_.launchExit();
return retVal; return retVal;
} }
bool Launcher::GetLauncherName(std::string &launcherName, std::string collection) bool Launcher::launcherName(std::string &launcherName, std::string collection)
{ {
std::string launcherKey = "collections." + collection + ".launcher"; std::string launcherKey = "collections." + collection + ".launcher";
// find the launcher for the particular item // find the launcher for the particular item
if(!Config.GetProperty(launcherKey, launcherName)) if(!config_.getProperty(launcherKey, launcherName))
{ {
std::stringstream ss; std::stringstream ss;
@@ -204,7 +204,7 @@ bool Launcher::GetLauncherName(std::string &launcherName, std::string collection
<< launcherKey << launcherKey
<< "\")"; << "\")";
Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); Logger::write(Logger::ZONE_ERROR, "Launcher", ss.str());
return false; return false;
} }
@@ -216,71 +216,72 @@ bool Launcher::GetLauncherName(std::string &launcherName, std::string collection
<< launcherName << launcherName
<< "\""; << "\"";
Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str()); Logger::write(Logger::ZONE_DEBUG, "Launcher", ss.str());
return true; return true;
} }
bool Launcher::GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName) bool Launcher::launcherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName)
{ {
std::string executableKey = "launchers." + launcherName + ".executable"; std::string executableKey = "launchers." + launcherName + ".executable";
if(!Config.GetProperty(executableKey, executable)) if(!config_.getProperty(executableKey, executable))
{ {
return false; return false;
} }
std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory"; std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory";
currentDirectory = Utils::GetDirectory(executable); currentDirectory = Utils::getDirectory(executable);
Config.GetProperty(currentDirectoryKey, currentDirectory); config_.getProperty(currentDirectoryKey, currentDirectory);
return true; return true;
} }
bool Launcher::GetLauncherArgs(std::string &args, std::string launcherName) bool Launcher::launcherArgs(std::string &args, std::string launcherName)
{ {
std::string argsKey = "launchers." + launcherName + ".arguments"; std::string argsKey = "launchers." + launcherName + ".arguments";
if(!Config.GetProperty(argsKey, args)) if(!config_.getProperty(argsKey, args))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey); Logger::write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey);
return false; return false;
} }
return true; return true;
} }
bool Launcher::GetExtensions(std::string &extensions, std::string collection) bool Launcher::extensions(std::string &extensions, std::string collection)
{ {
std::string extensionsKey = "collections." + collection + ".list.extensions"; std::string extensionsKey = "collections." + collection + ".list.extensions";
if(!Config.GetProperty(extensionsKey, extensions)) if(!config_.getProperty(extensionsKey, extensions))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey); Logger::write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey);
return false; return false;
} }
extensions = Utils::Replace(extensions, " ", ""); extensions = Utils::replace(extensions, " ", "");
extensions = Utils::Replace(extensions, ".", ""); extensions = Utils::replace(extensions, ".", "");
return true; return true;
} }
bool Launcher::GetCollectionDirectory(std::string &directory, std::string collection) bool Launcher::collectionDirectory(std::string &directory, std::string collection)
{ {
std::string itemsPathValue; std::string itemsPathValue;
std::string mergedCollectionName;
// find the items path folder (i.e. ROM path) // find the items path folder (i.e. ROM path)
Config.GetCollectionAbsolutePath(collection, itemsPathValue); config_.getCollectionAbsolutePath(collection, itemsPathValue);
directory += itemsPathValue + Utils::PathSeparator; directory += itemsPathValue + Utils::pathSeparator;
return true; return true;
} }
bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions) bool Launcher::findFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions)
{ {
std::string extension; std::string extension;
bool fileFound = false; bool fileFound = false;
@@ -301,7 +302,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
fileFound = true; fileFound = true;
Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str()); Logger::write(Logger::ZONE_INFO, "Launcher", ss.str());
foundFilePath = selectedItemsPath; foundFilePath = selectedItemsPath;
foundFilename = extension; foundFilename = extension;
@@ -313,7 +314,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
ss << "Checking to see if \"" ss << "Checking to see if \""
<< selectedItemsPath << "\" exists [No]"; << selectedItemsPath << "\" exists [No]";
Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str()); Logger::write(Logger::ZONE_WARNING, "Launcher", ss.str());
} }
f.close(); f.close();
@@ -328,7 +329,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
<< filenameWithoutExtension << "\" in folder \"" << filenameWithoutExtension << "\" in folder \""
<< directory; << directory;
Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); Logger::write(Logger::ZONE_ERROR, "Launcher", ss.str());
} }

View File

@@ -25,28 +25,28 @@ class Launcher
{ {
public: public:
Launcher(RetroFE &p, Configuration &c); Launcher(RetroFE &p, Configuration &c);
bool Run(std::string collection, Item *collectionItem); bool run(std::string collection, Item *collectionItem);
private: private:
std::string ReplaceString( std::string replaceString(
std::string subject, std::string subject,
const std::string &search, const std::string &search,
const std::string &replace); const std::string &replace);
bool GetLauncherName(std::string &launcherName, std::string collection); bool launcherName(std::string &launcherName, std::string collection);
bool GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName); bool launcherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName);
bool GetLauncherArgs(std::string &args, std::string launcherName); bool launcherArgs(std::string &args, std::string launcherName);
bool GetExtensions(std::string &extensions, std::string launcherName); bool extensions(std::string &extensions, std::string launcherName);
bool GetCollectionDirectory(std::string &directory, std::string collection); bool collectionDirectory(std::string &directory, std::string collection);
bool ExecuteCommand(std::string executable, std::string arguments, std::string currentDirectory); bool execute(std::string executable, std::string arguments, std::string currentDirectory);
bool FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions); bool findFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions);
std::string ReplaceVariables(std::string str, std::string replaceVariables(std::string str,
std::string itemFilePath, std::string itemFilePath,
std::string itemName, std::string itemName,
std::string itemFilename, std::string itemFilename,
std::string itemDirectory, std::string itemDirectory,
std::string itemCollectionName); std::string itemCollectionName);
Configuration &Config; Configuration &config_;
RetroFE &RetroFEInst; RetroFE &retrofe_;
}; };

View File

@@ -23,7 +23,7 @@ Animation::Animation()
Animation::Animation(Animation &copy) Animation::Animation(Animation &copy)
{ {
for(std::vector<TweenSet *>::iterator it = copy.AnimationVector.begin(); it != copy.AnimationVector.end(); it++) for(std::vector<TweenSet *>::iterator it = copy.animationVector_.begin(); it != copy.animationVector_.end(); it++)
{ {
Push(new TweenSet(**it)); Push(new TweenSet(**it));
} }
@@ -35,34 +35,34 @@ Animation::~Animation()
void Animation::Push(TweenSet *set) void Animation::Push(TweenSet *set)
{ {
AnimationVector.push_back(set); animationVector_.push_back(set);
} }
void Animation::Clear() void Animation::Clear()
{ {
std::vector<TweenSet *>::iterator it = AnimationVector.begin(); std::vector<TweenSet *>::iterator it = animationVector_.begin();
while(it != AnimationVector.end()) while(it != animationVector_.end())
{ {
delete *it; delete *it;
AnimationVector.erase(it); animationVector_.erase(it);
it = AnimationVector.begin(); it = animationVector_.begin();
} }
AnimationVector.clear(); animationVector_.clear();
} }
std::vector<TweenSet *> *Animation::GetTweenSets() std::vector<TweenSet *> *Animation::tweenSets()
{ {
return &AnimationVector; return &animationVector_;
} }
TweenSet *Animation::GetTweenSet(unsigned int index) TweenSet *Animation::tweenSet(unsigned int index)
{ {
return AnimationVector[index]; return animationVector_[index];
} }
unsigned int Animation::GetSize() unsigned int Animation::size()
{ {
return AnimationVector.size(); return animationVector_.size();
} }

View File

@@ -28,9 +28,9 @@ public:
~Animation(); ~Animation();
void Push(TweenSet *set); void Push(TweenSet *set);
void Clear(); void Clear();
std::vector<TweenSet *> *GetTweenSets(); std::vector<TweenSet *> *tweenSets();
TweenSet *GetTweenSet(unsigned int index); TweenSet *tweenSet(unsigned int index);
unsigned int GetSize(); unsigned int size();
private: private:
std::vector<TweenSet *> AnimationVector; std::vector<TweenSet *> animationVector_;
}; };

View File

@@ -25,55 +25,55 @@ AnimationEvents::AnimationEvents()
AnimationEvents::AnimationEvents(AnimationEvents &copy) AnimationEvents::AnimationEvents(AnimationEvents &copy)
{ {
for(std::map<std::string, std::map<int , Animation *> >::iterator it = copy.AnimationMap.begin(); it != copy.AnimationMap.end(); it++) for(std::map<std::string, std::map<int , Animation *> >::iterator it = copy.animationMap_.begin(); it != copy.animationMap_.end(); it++)
{ {
for(std::map<int, Animation *>::iterator it2 = (it->second).begin(); it2 != (it->second).end(); it2++) for(std::map<int, Animation *>::iterator it2 = (it->second).begin(); it2 != (it->second).end(); it2++)
{ {
Animation *t = new Animation(*it2->second); Animation *t = new Animation(*it2->second);
AnimationMap[it->first][it2->first] = t; animationMap_[it->first][it2->first] = t;
} }
} }
} }
AnimationEvents::~AnimationEvents() AnimationEvents::~AnimationEvents()
{ {
Clear(); clear();
} }
Animation *AnimationEvents::GetAnimation(std::string tween) Animation *AnimationEvents::getAnimation(std::string tween)
{ {
return GetAnimation(tween, -1); return getAnimation(tween, -1);
} }
Animation *AnimationEvents::GetAnimation(std::string tween, int index) Animation *AnimationEvents::getAnimation(std::string tween, int index)
{ {
if(AnimationMap.find(tween) == AnimationMap.end()) if(animationMap_.find(tween) == animationMap_.end())
{ {
AnimationMap[tween][-1] = new Animation(); animationMap_[tween][-1] = new Animation();
} }
if(AnimationMap[tween].find(index) == AnimationMap[tween].end()) if(animationMap_[tween].find(index) == animationMap_[tween].end())
{ {
index = -1; index = -1;
if(AnimationMap[tween].find(index) == AnimationMap[tween].end()) if(animationMap_[tween].find(index) == animationMap_[tween].end())
{ {
AnimationMap[tween][index] = new Animation(); animationMap_[tween][index] = new Animation();
} }
} }
return AnimationMap[tween][index]; return animationMap_[tween][index];
} }
void AnimationEvents::SetAnimation(std::string tween, int index, Animation *animation) void AnimationEvents::setAnimation(std::string tween, int index, Animation *animation)
{ {
AnimationMap[tween][index] = animation; animationMap_[tween][index] = animation;
} }
void AnimationEvents::Clear() void AnimationEvents::clear()
{ {
std::map<std::string, std::map<int, Animation *> >::iterator it = AnimationMap.begin(); std::map<std::string, std::map<int, Animation *> >::iterator it = animationMap_.begin();
while(it != AnimationMap.end()) while(it != animationMap_.end())
{ {
std::map<int, Animation *>::iterator it2 = (it->second).begin(); std::map<int, Animation *>::iterator it2 = (it->second).begin();
while(it2 != (it->second).end()) while(it2 != (it->second).end())
@@ -83,11 +83,11 @@ void AnimationEvents::Clear()
} }
(it->second).clear(); (it->second).clear();
AnimationMap.erase(it); animationMap_.erase(it);
it = AnimationMap.begin(); it = animationMap_.begin();
} }
AnimationMap.clear(); animationMap_.clear();
} }

View File

@@ -28,11 +28,11 @@ public:
AnimationEvents(AnimationEvents &copy); AnimationEvents(AnimationEvents &copy);
~AnimationEvents(); ~AnimationEvents();
Animation *GetAnimation(std::string tween); Animation *getAnimation(std::string tween);
Animation *GetAnimation(std::string tween, int index); Animation *getAnimation(std::string tween, int index);
void SetAnimation(std::string tween, int index, Animation *animation); void setAnimation(std::string tween, int index, Animation *animation);
void Clear(); void clear();
private: private:
std::map<std::string, std::map<int, Animation *> > AnimationMap; std::map<std::string, std::map<int, Animation *> > animationMap_;
}; };

View File

@@ -19,49 +19,44 @@
#include <math.h> #include <math.h>
#include <string> #include <string>
std::map<std::string, TweenAlgorithm> Tween::TweenTypeMap; std::map<std::string, TweenAlgorithm> Tween::tweenTypeMap_;
std::map<std::string, TweenProperty> Tween::TweenPropertyMap; std::map<std::string, TweenProperty> Tween::tweenPropertyMap_;
Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration) Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration)
: Property(property) : property(property)
, Type(type) , duration(duration)
, Start(start) , type(type)
, End(end) , start(start)
, Duration(duration) , end(end)
{ {
} }
TweenProperty Tween::GetProperty() const
{
return Property;
}
bool Tween::getTweenProperty(std::string name, TweenProperty &property)
bool Tween::GetTweenProperty(std::string name, TweenProperty &property)
{ {
bool retVal = false; bool retVal = false;
if(TweenPropertyMap.size() == 0) if(tweenPropertyMap_.size() == 0)
{ {
TweenPropertyMap["x"] = TWEEN_PROPERTY_X; tweenPropertyMap_["x"] = TWEEN_PROPERTY_X;
TweenPropertyMap["y"] = TWEEN_PROPERTY_Y; tweenPropertyMap_["y"] = TWEEN_PROPERTY_Y;
TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE; tweenPropertyMap_["angle"] = TWEEN_PROPERTY_ANGLE;
TweenPropertyMap["alpha"] = TWEEN_PROPERTY_ALPHA; tweenPropertyMap_["alpha"] = TWEEN_PROPERTY_ALPHA;
TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH; tweenPropertyMap_["width"] = TWEEN_PROPERTY_WIDTH;
TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT; tweenPropertyMap_["height"] = TWEEN_PROPERTY_HEIGHT;
TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN; tweenPropertyMap_["xorigin"] = TWEEN_PROPERTY_X_ORIGIN;
TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN; tweenPropertyMap_["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN;
TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET; tweenPropertyMap_["xoffset"] = TWEEN_PROPERTY_X_OFFSET;
TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET; tweenPropertyMap_["yoffset"] = TWEEN_PROPERTY_Y_OFFSET;
TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE; tweenPropertyMap_["fontSize"] = TWEEN_PROPERTY_FONT_SIZE;
TweenPropertyMap["backgroundalpha"] = TWEEN_PROPERTY_BACKGROUND_ALPHA; tweenPropertyMap_["backgroundalpha"] = TWEEN_PROPERTY_BACKGROUND_ALPHA;
} }
std::transform(name.begin(), name.end(), name.begin(), ::tolower); std::transform(name.begin(), name.end(), name.begin(), ::tolower);
if(TweenPropertyMap.find(name) != TweenPropertyMap.end()) if(tweenPropertyMap_.find(name) != tweenPropertyMap_.end())
{ {
property = TweenPropertyMap[name]; property = tweenPropertyMap_[name];
retVal = true; retVal = true;
} }
@@ -69,54 +64,54 @@ bool Tween::GetTweenProperty(std::string name, TweenProperty &property)
} }
TweenAlgorithm Tween::GetTweenType(std::string name) TweenAlgorithm Tween::getTweenType(std::string name)
{ {
if(TweenTypeMap.size() == 0) if(tweenTypeMap_.size() == 0)
{ {
TweenTypeMap["easeinquadratic"] = EASE_IN_QUADRATIC; tweenTypeMap_["easeInquadratic"] = EASE_IN_QUADRATIC;
TweenTypeMap["easeoutquadratic"] = EASE_OUT_QUADRATIC; tweenTypeMap_["easeOutquadratic"] = EASE_OUT_QUADRATIC;
TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC; tweenTypeMap_["easeInoutquadratic"] = EASE_INOUT_QUADRATIC;
TweenTypeMap["easeincubic"] = EASE_IN_CUBIC; tweenTypeMap_["easeIncubic"] = EASE_IN_CUBIC;
TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC; tweenTypeMap_["easeOutcubic"] = EASE_OUT_CUBIC;
TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC; tweenTypeMap_["easeInoutcubic"] = EASE_INOUT_CUBIC;
TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC; tweenTypeMap_["easeInquartic"] = EASE_IN_QUARTIC;
TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC; tweenTypeMap_["easeOutquartic"] = EASE_OUT_QUARTIC;
TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC; tweenTypeMap_["easeInoutquartic"] = EASE_INOUT_QUARTIC;
TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC; tweenTypeMap_["easeInquintic"] = EASE_IN_QUINTIC;
TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC; tweenTypeMap_["easeOutquintic"] = EASE_OUT_QUINTIC;
TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC; tweenTypeMap_["easeInoutquintic"] = EASE_INOUT_QUINTIC;
TweenTypeMap["easeinsine"] = EASE_IN_SINE; tweenTypeMap_["easeInsine"] = EASE_IN_SINE;
TweenTypeMap["easeoutsine"] = EASE_OUT_SINE; tweenTypeMap_["easeOutsine"] = EASE_OUT_SINE;
TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE; tweenTypeMap_["easeInoutsine"] = EASE_INOUT_SINE;
TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL; tweenTypeMap_["easeInexponential"] = EASE_IN_EXPONENTIAL;
TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL; tweenTypeMap_["easeOutexponential"] = EASE_OUT_EXPONENTIAL;
TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL; tweenTypeMap_["easeInoutexponential"] = EASE_INOUT_EXPONENTIAL;
TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR; tweenTypeMap_["easeIncircular"] = EASE_IN_CIRCULAR;
TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR; tweenTypeMap_["easeOutcircular"] = EASE_OUT_CIRCULAR;
TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR; tweenTypeMap_["easeInoutcircular"] = EASE_INOUT_CIRCULAR;
TweenTypeMap["linear"] = LINEAR; tweenTypeMap_["linear"] = LINEAR;
} }
std::transform(name.begin(), name.end(), name.begin(), ::tolower); std::transform(name.begin(), name.end(), name.begin(), ::tolower);
if(TweenTypeMap.find(name) != TweenTypeMap.end()) if(tweenTypeMap_.find(name) != tweenTypeMap_.end())
{ {
return TweenTypeMap[name]; return tweenTypeMap_[name];
} }
else else
{ {
return TweenTypeMap["linear"]; return tweenTypeMap_["linear"];
} }
} }
float Tween::Animate(double elapsedTime) float Tween::animate(double elapsedTime)
{ {
return AnimateSingle(Type, Start, End, Duration, elapsedTime); return animateSingle(type, start, end, duration, elapsedTime);
} }
//todo: SDL likes floats, consider having casting being performed elsewhere //todo: SDL likes floats, consider having casting being performed elsewhere
float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime) float Tween::animateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime)
{ {
double a = start; double a = start;
double b = end - start; double b = end - start;
@@ -125,92 +120,92 @@ float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double
switch(type) switch(type)
{ {
case EASE_IN_QUADRATIC: case EASE_IN_QUADRATIC:
result = EaseInQuadratic(elapsedTime, duration, a, b); result = easeInQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUADRATIC: case EASE_OUT_QUADRATIC:
result = EaseOutQuadratic(elapsedTime, duration, a, b); result = easeOutQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUADRATIC: case EASE_INOUT_QUADRATIC:
result = EaseInOutQuadratic(elapsedTime, duration, a, b); result = easeInOutQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_CUBIC: case EASE_IN_CUBIC:
result = EaseInCubic(elapsedTime, duration, a, b); result = easeInCubic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_CUBIC: case EASE_OUT_CUBIC:
result = EaseOutCubic(elapsedTime, duration, a, b); result = easeOutCubic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_CUBIC: case EASE_INOUT_CUBIC:
result = EaseInOutCubic(elapsedTime, duration, a, b); result = easeInOutCubic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_QUARTIC: case EASE_IN_QUARTIC:
result = EaseInQuartic(elapsedTime, duration, a, b); result = easeInQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUARTIC: case EASE_OUT_QUARTIC:
result = EaseOutQuartic(elapsedTime, duration, a, b); result = easeOutQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUARTIC: case EASE_INOUT_QUARTIC:
result = EaseInOutQuartic(elapsedTime, duration, a, b); result = easeInOutQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_QUINTIC: case EASE_IN_QUINTIC:
result = EaseInQuintic(elapsedTime, duration, a, b); result = easeInQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUINTIC: case EASE_OUT_QUINTIC:
result = EaseOutQuintic(elapsedTime, duration, a, b); result = easeOutQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUINTIC: case EASE_INOUT_QUINTIC:
result = EaseInOutQuintic(elapsedTime, duration, a, b); result = easeInOutQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_SINE: case EASE_IN_SINE:
result = EaseInSine(elapsedTime, duration, a, b); result = easeInSine(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_SINE: case EASE_OUT_SINE:
result = EaseOutSine(elapsedTime, duration, a, b); result = easeOutSine(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_SINE: case EASE_INOUT_SINE:
result = EaseInOutSine(elapsedTime, duration, a, b); result = easeInOutSine(elapsedTime, duration, a, b);
break; break;
case EASE_IN_EXPONENTIAL: case EASE_IN_EXPONENTIAL:
result = EaseInExponential(elapsedTime, duration, a, b); result = easeInExponential(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_EXPONENTIAL: case EASE_OUT_EXPONENTIAL:
result = EaseOutExponential(elapsedTime, duration, a, b); result = easeOutExponential(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_EXPONENTIAL: case EASE_INOUT_EXPONENTIAL:
result = EaseInOutExponential(elapsedTime, duration, a, b); result = easeInOutExponential(elapsedTime, duration, a, b);
break; break;
case EASE_IN_CIRCULAR: case EASE_IN_CIRCULAR:
result = EaseInCircular(elapsedTime, duration, a, b); result = easeInCircular(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_CIRCULAR: case EASE_OUT_CIRCULAR:
result = EaseOutCircular(elapsedTime, duration, a, b); result = easeOutCircular(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_CIRCULAR: case EASE_INOUT_CIRCULAR:
result = EaseInOutCircular(elapsedTime, duration, a, b); result = easeInOutCircular(elapsedTime, duration, a, b);
break; break;
case LINEAR: case LINEAR:
default: default:
result = Linear(elapsedTime, duration, a, b); result = linear(elapsedTime, duration, a, b);
break; break;
} }
@@ -218,27 +213,27 @@ float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double
} }
double Tween::Linear(double t, double d, double b, double c) double Tween::linear(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
return c*t/d + b; return c*t/d + b;
}; };
double Tween::EaseInQuadratic(double t, double d, double b, double c) double Tween::easeInQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t + b; return c*t*t + b;
}; };
double Tween::EaseOutQuadratic(double t, double d, double b, double c) double Tween::easeOutQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return -c * t*(t-2) + b; return -c * t*(t-2) + b;
}; };
double Tween::EaseInOutQuadratic(double t, double d, double b, double c) double Tween::easeInOutQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
@@ -247,14 +242,14 @@ double Tween::EaseInOutQuadratic(double t, double d, double b, double c)
return -c/2 * (t*(t-2) - 1) + b; return -c/2 * (t*(t-2) - 1) + b;
}; };
double Tween::EaseInCubic(double t, double d, double b, double c) double Tween::easeInCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t*t + b; return c*t*t*t + b;
}; };
double Tween::EaseOutCubic(double t, double d, double b, double c) double Tween::easeOutCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
@@ -262,7 +257,7 @@ double Tween::EaseOutCubic(double t, double d, double b, double c)
return c*(t*t*t + 1) + b; return c*(t*t*t + 1) + b;
}; };
double Tween::EaseInOutCubic(double t, double d, double b, double c) double Tween::easeInOutCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
@@ -271,14 +266,14 @@ double Tween::EaseInOutCubic(double t, double d, double b, double c)
return c/2*(t*t*t + 2) + b; return c/2*(t*t*t + 2) + b;
}; };
double Tween::EaseInQuartic(double t, double d, double b, double c) double Tween::easeInQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t*t*t + b; return c*t*t*t*t + b;
}; };
double Tween::EaseOutQuartic(double t, double d, double b, double c) double Tween::easeOutQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
@@ -286,7 +281,7 @@ double Tween::EaseOutQuartic(double t, double d, double b, double c)
return -c * (t*t*t*t - 1) + b; return -c * (t*t*t*t - 1) + b;
}; };
double Tween::EaseInOutQuartic(double t, double d, double b, double c) double Tween::easeInOutQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
@@ -295,7 +290,7 @@ double Tween::EaseInOutQuartic(double t, double d, double b, double c)
return -c/2 * (t*t*t*t - 2) + b; return -c/2 * (t*t*t*t - 2) + b;
}; };
double Tween::EaseInQuintic(double t, double d, double b, double c) double Tween::easeInQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
@@ -303,7 +298,7 @@ double Tween::EaseInQuintic(double t, double d, double b, double c)
}; };
double Tween::EaseOutQuintic(double t, double d, double b, double c) double Tween::easeOutQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
@@ -311,7 +306,7 @@ double Tween::EaseOutQuintic(double t, double d, double b, double c)
return c*(t*t*t*t*t + 1) + b; return c*(t*t*t*t*t + 1) + b;
}; };
double Tween::EaseInOutQuintic(double t, double d, double b, double c) double Tween::easeInOutQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
@@ -320,32 +315,32 @@ double Tween::EaseInOutQuintic(double t, double d, double b, double c)
return c/2*(t*t*t*t*t + 2) + b; return c/2*(t*t*t*t*t + 2) + b;
}; };
double Tween::EaseInSine(double t, double d, double b, double c) double Tween::easeInSine(double t, double d, double b, double c)
{ {
return -c * cos(t/d * (M_PI/2)) + c + b; return -c * cos(t/d * (M_PI/2)) + c + b;
}; };
double Tween::EaseOutSine(double t, double d, double b, double c) double Tween::easeOutSine(double t, double d, double b, double c)
{ {
return c * sin(t/d * (M_PI/2)) + b; return c * sin(t/d * (M_PI/2)) + b;
}; };
double Tween::EaseInOutSine(double t, double d, double b, double c) double Tween::easeInOutSine(double t, double d, double b, double c)
{ {
return -c/2 * (cos( M_PI*t/d) - 1) + b; return -c/2 * (cos( M_PI*t/d) - 1) + b;
}; };
double Tween::EaseInExponential(double t, double d, double b, double c) double Tween::easeInExponential(double t, double d, double b, double c)
{ {
return c * pow( 2, 10 * (t/d - 1) ) + b; return c * pow( 2, 10 * (t/d - 1) ) + b;
}; };
double Tween::EaseOutExponential(double t, double d, double b, double c) double Tween::easeOutExponential(double t, double d, double b, double c)
{ {
return c * ( - pow( 2, -10 * t/d ) + 1 ) + b; return c * ( - pow( 2, -10 * t/d ) + 1 ) + b;
}; };
double Tween::EaseInOutExponential(double t, double d, double b, double c) double Tween::easeInOutExponential(double t, double d, double b, double c)
{ {
t /= d/2; t /= d/2;
if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b; if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b;
@@ -353,31 +348,24 @@ double Tween::EaseInOutExponential(double t, double d, double b, double c)
return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b; return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b;
}; };
double Tween::EaseInCircular(double t, double d, double b, double c) double Tween::easeInCircular(double t, double d, double b, double c)
{ {
t /= d; t /= d;
return -c * (sqrt(1 - t*t) - 1) + b; return -c * (sqrt(1 - t*t) - 1) + b;
}; };
double Tween::EaseOutCircular(double t, double d, double b, double c) double Tween::easeOutCircular(double t, double d, double b, double c)
{ {
t /= d; t /= d;
t--; t--;
return c * sqrt(1 - t*t) + b; return c * sqrt(1 - t*t) + b;
}; };
double Tween::EaseInOutCircular(double t, double d, double b, double c) double Tween::easeInOutCircular(double t, double d, double b, double c)
{ {
t /= d/2; t /= d/2;
if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b; if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b;
t -= 2; t -= 2;
return c/2 * (sqrt(1 - t*t) + 1) + b; return c/2 * (sqrt(1 - t*t) + 1) + b;
} }
;
//todo: sdl requires floats, should the casting be done at this layer?
float Tween::GetDuration() const
{
return static_cast<float>(Duration);
}

View File

@@ -26,42 +26,40 @@ class Tween
public: public:
Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration); Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration);
float Animate(double elapsedTime); float animate(double elapsedTime);
static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime); static float animateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime);
static TweenAlgorithm GetTweenType(std::string name); static TweenAlgorithm getTweenType(std::string name);
static bool GetTweenProperty(std::string name, TweenProperty &property); static bool getTweenProperty(std::string name, TweenProperty &property);
TweenProperty GetProperty() const; TweenProperty property;
float GetDuration() const; double duration;
private: private:
static double EaseInQuadratic(double elapsedTime, double duration, double b, double c); static double easeInQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuadratic(double elapsedTime, double duration, double b, double c); static double easeOutQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuadratic(double elapsedTime, double duration, double b, double c); static double easeInOutQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseInCubic(double elapsedTime, double duration, double b, double c); static double easeInCubic(double elapsedTime, double duration, double b, double c);
static double EaseOutCubic(double elapsedTime, double duration, double b, double c); static double easeOutCubic(double elapsedTime, double duration, double b, double c);
static double EaseInOutCubic(double elapsedTime, double duration, double b, double c); static double easeInOutCubic(double elapsedTime, double duration, double b, double c);
static double EaseInQuartic(double elapsedTime, double duration, double b, double c); static double easeInQuartic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuartic(double elapsedTime, double duration, double b, double c); static double easeOutQuartic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuartic(double elapsedTime, double duration, double b, double c); static double easeInOutQuartic(double elapsedTime, double duration, double b, double c);
static double EaseInQuintic(double elapsedTime, double duration, double b, double c); static double easeInQuintic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuintic(double elapsedTime, double duration, double b, double c); static double easeOutQuintic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuintic(double elapsedTime, double duration, double b, double c); static double easeInOutQuintic(double elapsedTime, double duration, double b, double c);
static double EaseInSine(double elapsedTime, double duration, double b, double c); static double easeInSine(double elapsedTime, double duration, double b, double c);
static double EaseOutSine(double elapsedTime, double duration, double b, double c); static double easeOutSine(double elapsedTime, double duration, double b, double c);
static double EaseInOutSine(double elapsedTime, double duration, double b, double c); static double easeInOutSine(double elapsedTime, double duration, double b, double c);
static double EaseInExponential(double elapsedTime, double duration, double b, double c); static double easeInExponential(double elapsedTime, double duration, double b, double c);
static double EaseOutExponential(double elapsedTime, double duration, double b, double c); static double easeOutExponential(double elapsedTime, double duration, double b, double c);
static double EaseInOutExponential(double elapsedTime, double duration, double b, double c); static double easeInOutExponential(double elapsedTime, double duration, double b, double c);
static double EaseInCircular(double elapsedTime, double duration, double b, double c); static double easeInCircular(double elapsedTime, double duration, double b, double c);
static double EaseOutCircular(double elapsedTime, double duration, double b, double c); static double easeOutCircular(double elapsedTime, double duration, double b, double c);
static double EaseInOutCircular(double elapsedTime, double duration, double b, double c); static double easeInOutCircular(double elapsedTime, double duration, double b, double c);
static double Linear(double elapsedTime, double duration, double b, double c); static double linear(double elapsedTime, double duration, double b, double c);
static std::map<std::string, TweenAlgorithm> TweenTypeMap; static std::map<std::string, TweenAlgorithm> tweenTypeMap_;
static std::map<std::string, TweenProperty> TweenPropertyMap; static std::map<std::string, TweenProperty> tweenPropertyMap_;
TweenProperty Property; TweenAlgorithm type;
TweenAlgorithm Type; double start;
double Start; double end;
double End;
double Duration;
}; };

View File

@@ -21,45 +21,45 @@ TweenSet::TweenSet()
TweenSet::TweenSet(TweenSet &copy) TweenSet::TweenSet(TweenSet &copy)
{ {
for(std::vector<Tween *>::iterator it = copy.Set.begin(); it != copy.Set.end(); it++) for(std::vector<Tween *>::iterator it = copy.set_.begin(); it != copy.set_.end(); it++)
{ {
Tween *t = new Tween(**it); Tween *t = new Tween(**it);
Set.push_back(t); set_.push_back(t);
} }
} }
TweenSet::~TweenSet() TweenSet::~TweenSet()
{ {
Clear(); clear();
} }
void TweenSet::Push(Tween *tween) void TweenSet::push(Tween *tween)
{ {
Set.push_back(tween); set_.push_back(tween);
} }
void TweenSet::Clear() void TweenSet::clear()
{ {
std::vector<Tween *>::iterator it = Set.begin(); std::vector<Tween *>::iterator it = set_.begin();
while(it != Set.end()) while(it != set_.end())
{ {
delete *it; delete *it;
Set.erase(it); set_.erase(it);
it = Set.begin(); it = set_.begin();
} }
} }
std::vector<Tween *> *TweenSet::GetTweens() std::vector<Tween *> *TweenSet::tweens()
{ {
return &Set; return &set_;
} }
Tween *TweenSet::GetTween(unsigned int index) Tween *TweenSet::getTween(unsigned int index)
{ {
return Set[index]; return set_[index];
} }
unsigned int TweenSet::GetSize() unsigned int TweenSet::size()
{ {
return Set.size(); return set_.size();
} }

View File

@@ -24,12 +24,12 @@ public:
TweenSet(); TweenSet();
TweenSet(TweenSet &copy); TweenSet(TweenSet &copy);
~TweenSet(); ~TweenSet();
void Push(Tween * tween); void push(Tween * tween);
void Clear(); void clear();
std::vector<Tween *> *GetTweens(); std::vector<Tween *> *tweens();
Tween *GetTween(unsigned int index); Tween *getTween(unsigned int index);
unsigned int GetSize(); unsigned int size();
private: private:
std::vector<Tween *> Set; std::vector<Tween *> set_;
}; };

View File

@@ -21,26 +21,26 @@
Component::Component() Component::Component()
{ {
Tweens = NULL; tweens_ = NULL;
SelectedItem = NULL; selectedItem_ = NULL;
NewItemSelectedSinceEnter = false; newItemSelectedSinceEnter = false;
BackgroundTexture = NULL; backgroundTexture_ = NULL;
FreeGraphicsMemory(); freeGraphicsMemory();
} }
Component::Component(const Component &copy) Component::Component(const Component &copy)
{ {
Tweens = NULL; tweens_ = NULL;
SelectedItem = NULL; selectedItem_ = NULL;
NewItemSelectedSinceEnter = false; newItemSelectedSinceEnter = false;
BackgroundTexture = NULL; backgroundTexture_ = NULL;
FreeGraphicsMemory(); freeGraphicsMemory();
if(copy.Tweens) if(copy.tweens_)
{ {
AnimationEvents *tweens = new AnimationEvents(*copy.Tweens); AnimationEvents *tweens = new AnimationEvents(*copy.tweens_);
SetTweens(tweens); setTweens(tweens);
} }
@@ -48,249 +48,214 @@ Component::Component(const Component &copy)
Component::~Component() Component::~Component()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
} }
void Component::FreeGraphicsMemory() void Component::freeGraphicsMemory()
{ {
CurrentAnimationState = HIDDEN; currentAnimationState = HIDDEN;
EnterRequested = false; enterRequested = false;
ExitRequested = false; exitRequested = false;
MenuEnterRequested = false; menuEnterRequested = false;
MenuEnterIndex = -1; menuEnterIndex = -1;
MenuScrollRequested = false; menuScrollRequested = false;
MenuExitRequested = false; menuExitRequested = false;
MenuExitIndex = -1; menuExitIndex = -1;
NewItemSelected = false; newItemSelected = false;
HighlightExitComplete = false; highlightExitComplete = false;
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentTweenIndex = 0; currentTweenIndex_ = 0;
CurrentTweenComplete = false; currentTweenComplete_ = false;
ElapsedTweenTime = 0; elapsedTweenTime_ = 0;
ScrollActive = false; scrollActive = false;
if(BackgroundTexture) if(backgroundTexture_)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
SDL_DestroyTexture(BackgroundTexture); SDL_DestroyTexture(backgroundTexture_);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
BackgroundTexture = NULL; backgroundTexture_ = NULL;
} }
} }
void Component::AllocateGraphicsMemory() void Component::allocateGraphicsMemory()
{ {
if(!BackgroundTexture) if(!backgroundTexture_)
{ {
// make a 4x4 pixel wide surface to be stretched during rendering, make it a white background so we can use // make a 4x4 pixel wide surface to be stretched during rendering, make it a white background so we can use
// color later // color later
SDL_Surface *surface = SDL_CreateRGBSurface(0, 4, 4, 32, 0, 0, 0, 0); SDL_Surface *surface = SDL_CreateRGBSurface(0, 4, 4, 32, 0, 0, 0, 0);
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
BackgroundTexture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), surface); backgroundTexture_ = SDL_CreateTextureFromSurface(SDL::getRenderer(), surface);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
SDL_FreeSurface(surface); SDL_FreeSurface(surface);
SDL_SetTextureBlendMode(BackgroundTexture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(backgroundTexture_, SDL_BLENDMODE_BLEND);
} }
} }
Item *Component::GetSelectedItem() Item *Component::getSelectedItem()
{ {
return SelectedItem; return selectedItem_;
} }
void Component::TriggerEnterEvent() void Component::triggerEnterEvent()
{ {
EnterRequested = true; enterRequested = true;
} }
void Component::TriggerExitEvent() void Component::triggerExitEvent()
{ {
ExitRequested = true; exitRequested = true;
} }
void Component::TriggerMenuEnterEvent(int menuIndex) void Component::triggerMenuEnterEvent(int menuIndex)
{ {
MenuEnterRequested = true; menuEnterRequested = true;
MenuEnterIndex = menuIndex; menuEnterIndex = menuIndex;
} }
void Component::TriggerMenuScrollEvent() void Component::triggerMenuScrollEvent()
{ {
MenuScrollRequested = true; menuScrollRequested = true;
} }
void Component::TriggerMenuExitEvent(int menuIndex) void Component::triggerMenuExitEvent(int menuIndex)
{ {
MenuExitRequested = true; menuExitRequested = true;
MenuExitIndex = menuIndex; menuExitIndex = menuIndex;
} }
void Component::TriggerHighlightEvent(Item *selectedItem) void Component::triggerHighlightEvent(Item *selectedItem)
{ {
NewItemSelected = true; newItemSelected = true;
this->SelectedItem = selectedItem; this->selectedItem_ = selectedItem;
} }
bool Component::IsIdle() bool Component::isIdle()
{ {
return (CurrentAnimationState == IDLE); return (currentAnimationState == IDLE);
} }
bool Component::IsHidden() bool Component::isHidden()
{ {
return (CurrentAnimationState == HIDDEN); return (currentAnimationState == HIDDEN);
} }
bool Component::IsWaiting() bool Component::isWaiting()
{ {
return (CurrentAnimationState == HIGHLIGHT_WAIT); return (currentAnimationState == HIGHLIGHT_WAIT);
} }
bool Component::IsMenuScrolling() bool Component::isMenuScrolling()
{ {
return (CurrentAnimationState == MENU_ENTER || CurrentAnimationState == MENU_SCROLL || CurrentAnimationState == MENU_EXIT || MenuScrollRequested); return (currentAnimationState == MENU_ENTER || currentAnimationState == MENU_SCROLL || currentAnimationState == MENU_EXIT || menuScrollRequested);
}
void Component::setTweens(AnimationEvents *set)
{
tweens_ = set;
forceIdle();
}
void Component::forceIdle()
{
currentAnimationState = IDLE;
currentTweenIndex_ = 0;
currentTweenComplete_ = false;
elapsedTweenTime_ = 0;
currentTweens_ = NULL;
} }
std::string Component::GetCollectionName() void Component::update(float dt)
{ {
return CollectionName; elapsedTweenTime_ += dt;
} highlightExitComplete = false;
if(isHidden() || isWaiting() || (isIdle() && exitRequested))
void Component::SetCollectionName(std::string collectionName)
{
CollectionName = collectionName;
}
AnimationEvents *Component::GetTweens()
{
return Tweens;
}
void Component::SetTweens(AnimationEvents *set)
{
Tweens = set;
ForceIdle();
}
void Component::ForceIdle()
{
CurrentAnimationState = IDLE;
CurrentTweenIndex = 0;
CurrentTweenComplete = false;
ElapsedTweenTime = 0;
CurrentTweens = NULL;
}
ViewInfo *Component::GetBaseViewInfo()
{
return &BaseViewInfo;
}
void Component::UpdateBaseViewInfo(ViewInfo &info)
{
BaseViewInfo = info;
}
bool Component::IsScrollActive() const
{
return ScrollActive;
}
void Component::SetScrollActive(bool scrollActive)
{
ScrollActive = scrollActive;
}
void Component::Update(float dt)
{
ElapsedTweenTime += dt;
HighlightExitComplete = false;
if(IsHidden() || IsWaiting() || (IsIdle() && ExitRequested))
{ {
CurrentTweenComplete = true; currentTweenComplete_ = true;
} }
if(CurrentTweenComplete) if(currentTweenComplete_)
{ {
CurrentTweens = NULL; currentTweens_ = NULL;
// There was no request to override our state path. Continue on as normal. // There was no request to override our state path. Continue on as normal.
std::stringstream ss; std::stringstream ss;
switch(CurrentAnimationState) switch(currentAnimationState)
{ {
case MENU_ENTER: case MENU_ENTER:
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = IDLE; currentAnimationState = IDLE;
break; break;
case MENU_SCROLL: case MENU_SCROLL:
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = IDLE; currentAnimationState = IDLE;
break; break;
case MENU_EXIT: case MENU_EXIT:
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = IDLE; currentAnimationState = IDLE;
break; break;
case ENTER: case ENTER:
CurrentTweens = Tweens->GetAnimation("enter", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("enter", menuEnterIndex);
CurrentAnimationState = HIGHLIGHT_ENTER; currentAnimationState = HIGHLIGHT_ENTER;
break; break;
case EXIT: case EXIT:
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = HIDDEN; currentAnimationState = HIDDEN;
break; break;
case HIGHLIGHT_ENTER: case HIGHLIGHT_ENTER:
CurrentTweens = Tweens->GetAnimation("idle", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("idle", menuEnterIndex);
CurrentAnimationState = IDLE; currentAnimationState = IDLE;
break; break;
case IDLE: case IDLE:
// prevent us from automatically jumping to the exit tween upon enter // prevent us from automatically jumping to the exit tween upon enter
if(EnterRequested) if(enterRequested)
{ {
EnterRequested = false; enterRequested = false;
NewItemSelected = false; newItemSelected = false;
} }
else if(MenuExitRequested && (!MenuEnterRequested || MenuExitRequested <= MenuEnterRequested)) else if(menuExitRequested && (!menuEnterRequested || menuExitRequested <= menuEnterRequested))
{ {
CurrentTweens = Tweens->GetAnimation("menuExit", MenuExitIndex); currentTweens_ = tweens_->getAnimation("menuExit", menuExitIndex);
CurrentAnimationState = MENU_EXIT; currentAnimationState = MENU_EXIT;
MenuExitRequested = false; menuExitRequested = false;
} }
else if(MenuEnterRequested && (!MenuExitRequested || MenuExitRequested > MenuEnterRequested)) else if(menuEnterRequested && (!menuExitRequested || menuExitRequested > menuEnterRequested))
{ {
CurrentTweens = Tweens->GetAnimation("menuEnter", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("menuEnter", menuEnterIndex);
CurrentAnimationState = MENU_ENTER; currentAnimationState = MENU_ENTER;
MenuEnterRequested = false; menuEnterRequested = false;
} }
else if(MenuScrollRequested) else if(menuScrollRequested)
{ {
MenuScrollRequested = false; menuScrollRequested = false;
CurrentTweens = Tweens->GetAnimation("menuScroll", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("menuScroll", menuEnterIndex);
CurrentAnimationState = MENU_SCROLL; currentAnimationState = MENU_SCROLL;
} }
else if(IsScrollActive() || NewItemSelected || ExitRequested) else if(scrollActive || newItemSelected || exitRequested)
{ {
CurrentTweens = Tweens->GetAnimation("highlightExit", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("highlightExit", menuEnterIndex);
CurrentAnimationState = HIGHLIGHT_EXIT; currentAnimationState = HIGHLIGHT_EXIT;
} }
else else
{ {
CurrentTweens = Tweens->GetAnimation("idle", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("idle", menuEnterIndex);
CurrentAnimationState = IDLE; currentAnimationState = IDLE;
} }
break; break;
@@ -299,195 +264,194 @@ void Component::Update(float dt)
// intentionally break down // intentionally break down
case HIGHLIGHT_WAIT: case HIGHLIGHT_WAIT:
if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_WAIT)) if(exitRequested && (currentAnimationState == HIGHLIGHT_WAIT))
{ {
CurrentTweens = Tweens->GetAnimation("highlightExit", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("highlightExit", menuEnterIndex);
CurrentAnimationState = HIGHLIGHT_EXIT; currentAnimationState = HIGHLIGHT_EXIT;
} }
else if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_EXIT)) else if(exitRequested && (currentAnimationState == HIGHLIGHT_EXIT))
{ {
CurrentTweens = Tweens->GetAnimation("exit", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("exit", menuEnterIndex);
CurrentAnimationState = EXIT; currentAnimationState = EXIT;
ExitRequested = false; exitRequested = false;
} }
else if(IsScrollActive()) else if(scrollActive)
{ {
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT; currentAnimationState = HIGHLIGHT_WAIT;
} }
else if(NewItemSelected) else if(newItemSelected)
{ {
CurrentTweens = Tweens->GetAnimation("highlightEnter", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("highlightEnter", menuEnterIndex);
CurrentAnimationState = HIGHLIGHT_ENTER; currentAnimationState = HIGHLIGHT_ENTER;
HighlightExitComplete = true; highlightExitComplete = true;
NewItemSelected = false; newItemSelected = false;
} }
else else
{ {
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT; currentAnimationState = HIGHLIGHT_WAIT;
} }
break; break;
case HIDDEN: case HIDDEN:
if(EnterRequested || ExitRequested) if(enterRequested || exitRequested)
{ {
CurrentTweens = Tweens->GetAnimation("enter", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("enter", menuEnterIndex);
CurrentAnimationState = ENTER; currentAnimationState = ENTER;
} }
else if(MenuExitRequested && (!MenuEnterRequested || MenuExitRequested <= MenuEnterRequested)) else if(menuExitRequested && (!menuEnterRequested || menuExitRequested <= menuEnterRequested))
{ {
CurrentTweens = Tweens->GetAnimation("menuExit", MenuExitIndex); currentTweens_ = tweens_->getAnimation("menuExit", menuExitIndex);
CurrentAnimationState = MENU_EXIT; currentAnimationState = MENU_EXIT;
MenuExitRequested = false; menuExitRequested = false;
} }
else if(MenuEnterRequested && (!MenuExitRequested || MenuExitRequested > MenuEnterRequested)) else if(menuEnterRequested && (!menuExitRequested || menuExitRequested > menuEnterRequested))
{ {
CurrentTweens = Tweens->GetAnimation("menuEnter", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("menuEnter", menuEnterIndex);
CurrentAnimationState = MENU_ENTER; currentAnimationState = MENU_ENTER;
MenuEnterRequested = false; menuEnterRequested = false;
} }
else if(MenuScrollRequested) else if(menuScrollRequested)
{ {
MenuScrollRequested = false; menuScrollRequested = false;
CurrentTweens = Tweens->GetAnimation("menuScroll", MenuEnterIndex); currentTweens_ = tweens_->getAnimation("menuScroll", menuEnterIndex);
CurrentAnimationState = MENU_SCROLL; currentAnimationState = MENU_SCROLL;
} }
else else
{ {
CurrentTweens = NULL; currentTweens_ = NULL;
CurrentAnimationState = HIDDEN; currentAnimationState = HIDDEN;
} }
} }
CurrentTweenIndex = 0; currentTweenIndex_ = 0;
CurrentTweenComplete = false; currentTweenComplete_ = false;
ElapsedTweenTime = 0; elapsedTweenTime_ = 0;
} }
CurrentTweenComplete = Animate(IsIdle()); currentTweenComplete_ = animate(isIdle());
} }
void Component::Draw() void Component::draw()
{ {
if(BackgroundTexture) if(backgroundTexture_)
{ {
ViewInfo *info = GetBaseViewInfo();
SDL_Rect rect; SDL_Rect rect;
rect.h = static_cast<int>(info->GetHeight()); rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
rect.w = static_cast<int>(info->GetWidth()); rect.w = static_cast<int>(baseViewInfo.ScaledWidth());
rect.x = static_cast<int>(info->GetXRelativeToOrigin()); rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin()); rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
SDL_SetTextureColorMod(BackgroundTexture, SDL_SetTextureColorMod(backgroundTexture_,
static_cast<char>(info->GetBackgroundRed()*255), static_cast<char>(baseViewInfo.BackgroundRed*255),
static_cast<char>(info->GetBackgroundGreen()*255), static_cast<char>(baseViewInfo.BackgroundGreen*255),
static_cast<char>(info->GetBackgroundBlue()*255)); static_cast<char>(baseViewInfo.BackgroundBlue*255));
SDL::RenderCopy(BackgroundTexture, static_cast<char>(info->GetBackgroundAlpha()*255), NULL, &rect, info->GetAngle()); SDL::renderCopy(backgroundTexture_, static_cast<char>(baseViewInfo.BackgroundAlpha*255), NULL, &rect, baseViewInfo.Angle);
} }
} }
bool Component::Animate(bool loop) bool Component::animate(bool loop)
{ {
bool completeDone = false; bool completeDone = false;
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->GetSize()) if(!currentTweens_ || currentTweenIndex_ >= currentTweens_->size())
{ {
completeDone = true; completeDone = true;
} }
else if(CurrentTweens) else if(currentTweens_)
{ {
bool currentDone = true; bool currentDone = true;
TweenSet *tweens = CurrentTweens->GetTweenSet(CurrentTweenIndex); TweenSet *tweens = currentTweens_->tweenSet(currentTweenIndex_);
for(unsigned int i = 0; i < tweens->GetSize(); i++) for(unsigned int i = 0; i < tweens->size(); i++)
{ {
Tween *tween = tweens->GetTweens()->at(i); Tween *tween = tweens->tweens()->at(i);
float elapsedTime = ElapsedTweenTime; double elapsedTime = elapsedTweenTime_;
//todo: too many levels of nesting //todo: too many levels of nesting
if(elapsedTime < tween->GetDuration()) if(elapsedTime < tween->duration)
{ {
currentDone = false; currentDone = false;
} }
else else
{ {
elapsedTime = tween->GetDuration(); elapsedTime = static_cast<float>(tween->duration);
} }
float value = tween->Animate(elapsedTime); float value = tween->animate(elapsedTime);
switch(tween->GetProperty()) switch(tween->property)
{ {
case TWEEN_PROPERTY_X: case TWEEN_PROPERTY_X:
GetBaseViewInfo()->SetX(value); baseViewInfo.X = value;
break; break;
case TWEEN_PROPERTY_Y: case TWEEN_PROPERTY_Y:
GetBaseViewInfo()->SetY(value); baseViewInfo.Y = value;
break; break;
case TWEEN_PROPERTY_HEIGHT: case TWEEN_PROPERTY_HEIGHT:
GetBaseViewInfo()->SetHeight(value); baseViewInfo.Height = value;
break; break;
case TWEEN_PROPERTY_WIDTH: case TWEEN_PROPERTY_WIDTH:
GetBaseViewInfo()->SetWidth(value); baseViewInfo.Width = value;
break; break;
case TWEEN_PROPERTY_ANGLE: case TWEEN_PROPERTY_ANGLE:
GetBaseViewInfo()->SetAngle(value); baseViewInfo.Angle = value;
break; break;
case TWEEN_PROPERTY_ALPHA: case TWEEN_PROPERTY_ALPHA:
GetBaseViewInfo()->SetAlpha(value); baseViewInfo.Alpha = value;
break; break;
case TWEEN_PROPERTY_X_ORIGIN: case TWEEN_PROPERTY_X_ORIGIN:
GetBaseViewInfo()->SetXOrigin(value); baseViewInfo.XOrigin = value;
break; break;
case TWEEN_PROPERTY_Y_ORIGIN: case TWEEN_PROPERTY_Y_ORIGIN:
GetBaseViewInfo()->SetYOrigin(value); baseViewInfo.YOrigin = value;
break; break;
case TWEEN_PROPERTY_X_OFFSET: case TWEEN_PROPERTY_X_OFFSET:
GetBaseViewInfo()->SetXOffset(value); baseViewInfo.XOffset = value;
break; break;
case TWEEN_PROPERTY_Y_OFFSET: case TWEEN_PROPERTY_Y_OFFSET:
GetBaseViewInfo()->SetYOffset(value); baseViewInfo.YOffset = value;
break; break;
case TWEEN_PROPERTY_FONT_SIZE: case TWEEN_PROPERTY_FONT_SIZE:
GetBaseViewInfo()->SetFontSize(value); baseViewInfo.FontSize = value;
break; break;
case TWEEN_PROPERTY_BACKGROUND_ALPHA: case TWEEN_PROPERTY_BACKGROUND_ALPHA:
GetBaseViewInfo()->SetBackgroundAlpha(value); baseViewInfo.BackgroundAlpha = value;
break; break;
} }
} }
if(currentDone) if(currentDone)
{ {
CurrentTweenIndex++; currentTweenIndex_++;
ElapsedTweenTime = 0; elapsedTweenTime_ = 0;
} }
} }
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->GetTweenSets()->size()) if(!currentTweens_ || currentTweenIndex_ >= currentTweens_->tweenSets()->size())
{ {
if(loop) if(loop)
{ {
CurrentTweenIndex = 0; currentTweenIndex_ = 0;
} }
completeDone = true; completeDone = true;
} }

View File

@@ -30,35 +30,31 @@ public:
Component(); Component();
Component(const Component &copy); Component(const Component &copy);
virtual ~Component(); virtual ~Component();
virtual void FreeGraphicsMemory(); virtual void freeGraphicsMemory();
virtual void AllocateGraphicsMemory(); virtual void allocateGraphicsMemory();
virtual void LaunchEnter() {} virtual void launchEnter() {}
virtual void LaunchExit() {} virtual void launchExit() {}
void TriggerEnterEvent(); void triggerEnterEvent();
void TriggerExitEvent(); void triggerExitEvent();
void TriggerMenuEnterEvent(int menuIndex = -1); void triggerMenuEnterEvent(int menuIndex = -1);
void TriggerMenuExitEvent(int menuIndex = -1); void triggerMenuExitEvent(int menuIndex = -1);
void TriggerMenuScrollEvent(); void triggerMenuScrollEvent();
void TriggerHighlightEvent(Item *selectedItem); void triggerHighlightEvent(Item *selectedItem);
bool IsIdle(); bool isIdle();
bool IsHidden(); bool isHidden();
bool IsWaiting(); bool isWaiting();
bool IsMenuScrolling(); bool isMenuScrolling();
std::string GetCollectionName();
void SetCollectionName(std::string collectionName);
virtual void Update(float dt); virtual void update(float dt);
virtual void Draw(); virtual void draw();
AnimationEvents *GetTweens(); void setTweens(AnimationEvents *set);
void SetTweens(AnimationEvents *set); void forceIdle();
void ForceIdle(); ViewInfo baseViewInfo;
ViewInfo *GetBaseViewInfo(); std::string collectionName;
void UpdateBaseViewInfo(ViewInfo &info); bool scrollActive;
bool IsScrollActive() const;
void SetScrollActive(bool scrollActive);
protected: protected:
Item *GetSelectedItem(); Item *getSelectedItem();
enum AnimationState enum AnimationState
{ {
IDLE, IDLE,
@@ -73,31 +69,28 @@ protected:
HIDDEN HIDDEN
}; };
AnimationState CurrentAnimationState; AnimationState currentAnimationState;
bool EnterRequested; bool enterRequested;
bool ExitRequested; bool exitRequested;
bool MenuEnterRequested; bool menuEnterRequested;
int MenuEnterIndex; int menuEnterIndex;
bool MenuScrollRequested; bool menuScrollRequested;
bool MenuExitRequested; bool menuExitRequested;
int MenuExitIndex; int menuExitIndex;
bool NewItemSelected; bool newItemSelected;
bool HighlightExitComplete; bool highlightExitComplete;
bool NewItemSelectedSinceEnter; bool newItemSelectedSinceEnter;
private: private:
bool Animate(bool loop); bool animate(bool loop);
bool IsTweenSequencingComplete(); bool tweenSequencingComplete();
AnimationEvents *Tweens; AnimationEvents *tweens_;
Animation *CurrentTweens; Animation *currentTweens_;
Item *SelectedItem; Item *selectedItem_;
SDL_Texture *BackgroundTexture; SDL_Texture *backgroundTexture_;
unsigned int CurrentTweenIndex; unsigned int currentTweenIndex_;
bool CurrentTweenComplete; bool currentTweenComplete_;
std::string CollectionName; float elapsedTweenTime_;
ViewInfo BaseViewInfo;
float ElapsedTweenTime;
bool ScrollActive;
}; };

View File

@@ -20,25 +20,25 @@
Container::Container() Container::Container()
{ {
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
Container::~Container() Container::~Container()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
} }
void Container::FreeGraphicsMemory() void Container::freeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
} }
void Container::AllocateGraphicsMemory() void Container::allocateGraphicsMemory()
{ {
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
} }
void Container::Draw() void Container::draw()
{ {
Component::Draw(); Component::draw();
} }

View File

@@ -24,7 +24,7 @@ class Container : public Component
public: public:
Container(); Container();
virtual ~Container(); virtual ~Container();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void Draw(); void draw();
}; };

View File

@@ -20,70 +20,69 @@
#include <SDL2/SDL_image.h> #include <SDL2/SDL_image.h>
Image::Image(std::string file, float scaleX, float scaleY) Image::Image(std::string file, float scaleX, float scaleY)
: Texture(NULL) : texture_(NULL)
, File(file) , file_(file)
, ScaleX(scaleX) , scaleX_(scaleX)
, ScaleY(scaleY) , scaleY_(scaleY)
{ {
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
Image::~Image() Image::~Image()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
} }
void Image::FreeGraphicsMemory() void Image::freeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
if (Texture != NULL) if (texture_ != NULL)
{ {
SDL_DestroyTexture(Texture); SDL_DestroyTexture(texture_);
Texture = NULL; texture_ = NULL;
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
void Image::AllocateGraphicsMemory() void Image::allocateGraphicsMemory()
{ {
int width; int width;
int height; int height;
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
if(!Texture) if(!texture_)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str()); texture_ = IMG_LoadTexture(SDL::getRenderer(), file_.c_str());
if (Texture != NULL) if (texture_ != NULL)
{ {
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
SDL_QueryTexture(Texture, NULL, NULL, &width, &height); SDL_QueryTexture(texture_, NULL, NULL, &width, &height);
GetBaseViewInfo()->SetImageWidth(width * ScaleX); baseViewInfo.ImageWidth = width * scaleX_;
GetBaseViewInfo()->SetImageHeight(height * ScaleY); baseViewInfo.ImageHeight = height * scaleY_;
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
} }
void Image::Draw() void Image::draw()
{ {
Component::Draw(); Component::draw();
if(Texture) if(texture_)
{ {
ViewInfo *info = GetBaseViewInfo();
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(info->GetXRelativeToOrigin()); rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin()); rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight()); rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
rect.w = static_cast<int>(info->GetWidth()); rect.w = static_cast<int>(baseViewInfo.ScaledWidth());
SDL::RenderCopy(Texture, static_cast<char>((info->GetAlpha() * 255)), NULL, &rect, info->GetAngle()); SDL::renderCopy(texture_, static_cast<char>((baseViewInfo.Alpha * 255)), NULL, &rect, baseViewInfo.Angle);
} }
} }

View File

@@ -24,13 +24,13 @@ class Image : public Component
public: public:
Image(std::string file, float scaleX, float scaleY); Image(std::string file, float scaleX, float scaleY);
virtual ~Image(); virtual ~Image();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void Draw(); void draw();
protected: protected:
SDL_Texture *Texture; SDL_Texture *texture_;
std::string File; std::string file_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
}; };

View File

@@ -30,10 +30,10 @@ Image * ImageBuilder::CreateImage(std::string path, std::string name, float scal
extensions.push_back("jpeg"); extensions.push_back("jpeg");
extensions.push_back("JPEG"); extensions.push_back("JPEG");
std::string prefix = Utils::CombinePath(path, name); std::string prefix = Utils::combinePath(path, name);
std::string file; std::string file;
if(Utils::FindMatchingFile(prefix, extensions, file)) if(Utils::findMatchingFile(prefix, extensions, file))
{ {
image = new Image(file, scaleX, scaleY); image = new Image(file, scaleX, scaleY);
} }

View File

@@ -29,252 +29,340 @@
#include <iostream> #include <iostream>
ReloadableMedia::ReloadableMedia(Configuration &config, bool systemMode, std::string type, bool isVideo, Font *font, float scaleX, float scaleY) ReloadableMedia::ReloadableMedia(Configuration &config, bool systemMode, std::string type, bool isVideo, Font *font, float scaleX, float scaleY)
: Config(config) : config_(config)
, SystemMode(systemMode) , systemMode_(systemMode)
, LoadedComponent(NULL) , loadedComponent_(NULL)
, ReloadRequested(false) , reloadRequested_(false)
, FirstLoad(true) , firstLoad_(true)
, VideoInst(NULL) , videoInst_(NULL)
, IsVideo(isVideo) , isVideo_(isVideo)
, FontInst(font) , FfntInst_(font)
, TextFallback(false) , textFallback_(false)
, Type(type) , type_(type)
, ScaleX(scaleX) , scaleX_(scaleX)
, ScaleY(scaleY) , scaleY_(scaleY)
{ {
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
ReloadableMedia::~ReloadableMedia() ReloadableMedia::~ReloadableMedia()
{ {
if (LoadedComponent != NULL) if (loadedComponent_ != NULL)
{ {
delete LoadedComponent; delete loadedComponent_;
} }
} }
void ReloadableMedia::EnableTextFallback(bool value) void ReloadableMedia::enableTextFallback_(bool value)
{ {
TextFallback = value; textFallback_ = value;
} }
void ReloadableMedia::Update(float dt) void ReloadableMedia::update(float dt)
{ {
if(NewItemSelected) if(newItemSelected)
{ {
if(!SystemMode || (SystemMode && CurrentCollection != Config.GetCurrentCollection())) std::string collection;
config_.getProperty("currentCollection", collection);
if(!systemMode_ || (systemMode_ && currentCollection_ != collection))
{ {
ReloadRequested = true; reloadRequested_ = true;
} }
} }
// wait for the right moment to reload the image // wait for the right moment to reload the image
if (ReloadRequested && (HighlightExitComplete || FirstLoad)) if (reloadRequested_ && (highlightExitComplete || firstLoad_))
{ {
ReloadTexture(); reloadTexture();
ReloadRequested = false; reloadRequested_ = false;
FirstLoad = false; firstLoad_ = false;
} }
if(LoadedComponent) if(loadedComponent_)
{ {
// video needs to run a frame to start getting size info // video needs to run a frame to start getting size info
if(GetBaseViewInfo()->GetImageHeight() == 0 && GetBaseViewInfo()->GetImageWidth() == 0) if(baseViewInfo.ImageHeight == 0 && baseViewInfo.ImageWidth == 0)
{ {
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
} }
LoadedComponent->Update(dt); loadedComponent_->update(dt);
} }
// needs to be ran at the end to prevent the NewItemSelected flag from being detected // needs to be ran at the end to prevent the NewItemSelected flag from being detected
Component::Update(dt); Component::update(dt);
} }
void ReloadableMedia::AllocateGraphicsMemory() void ReloadableMedia::allocateGraphicsMemory()
{ {
FirstLoad = true; firstLoad_ = true;
if(LoadedComponent) if(loadedComponent_)
{ {
LoadedComponent->AllocateGraphicsMemory(); loadedComponent_->allocateGraphicsMemory();
} }
// NOTICE! needs to be done last to prevent flags from being missed // NOTICE! needs to be done last to prevent flags from being missed
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
} }
void ReloadableMedia::LaunchEnter() void ReloadableMedia::launchEnter()
{ {
if(LoadedComponent) if(loadedComponent_)
{ {
LoadedComponent->LaunchEnter(); loadedComponent_->launchEnter();
} }
} }
void ReloadableMedia::LaunchExit() void ReloadableMedia::launchExit()
{ {
if(LoadedComponent) if(loadedComponent_)
{ {
LoadedComponent->LaunchExit(); loadedComponent_->launchExit();
} }
} }
void ReloadableMedia::FreeGraphicsMemory() void ReloadableMedia::freeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
if(LoadedComponent) if(loadedComponent_)
{ {
LoadedComponent->FreeGraphicsMemory(); loadedComponent_->freeGraphicsMemory();
} }
} }
void ReloadableMedia::ReloadTexture()
{
bool found = false;
if(LoadedComponent)
void ReloadableMedia::reloadTexture()
{
if(loadedComponent_)
{ {
delete LoadedComponent; delete loadedComponent_;
LoadedComponent = NULL; loadedComponent_ = NULL;
} }
Item *selectedItem = GetSelectedItem(); Item *selectedItem = getSelectedItem();
if(!selectedItem) return;
CurrentCollection = Config.GetCurrentCollection(); config_.getProperty("currentCollection", currentCollection_);
if (selectedItem != NULL) // build clone list
std::vector<std::string> names;
names.push_back(selectedItem->name);
names.push_back(selectedItem->fullTitle);
if(selectedItem->cloneof.length() > 0)
{ {
std::vector<std::string> names; names.push_back(selectedItem->cloneof);
}
names.push_back(selectedItem->GetName()); if(isVideo_)
names.push_back(selectedItem->GetFullTitle()); {
for(unsigned int n = 0; n < names.size() && !loadedComponent_; ++n)
if(selectedItem->GetCloneOf().length() > 0)
{ {
names.push_back(selectedItem->GetCloneOf()); std::string basename = names[n];
} if(systemMode_)
for(unsigned int n = 0; n < names.size() && !found; ++n)
{
if(IsVideo)
{ {
VideoBuilder videoBuild;
std::string videoPath;
if(SystemMode) // check the master collection for the system artifact
loadedComponent_ = findComponent(collectionName, "video", "video", true);
// check the collection for the system artifact
if(!loadedComponent_)
{ {
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), "video", true, videoPath); loadedComponent_ = findComponent(selectedItem->collectionInfo->name, "video", "video", true);
LoadedComponent = videoBuild.CreateVideo(videoPath, "video", ScaleX, ScaleY);
}
else
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), "video", false, videoPath);
LoadedComponent = videoBuild.CreateVideo(videoPath, names[n], ScaleX, ScaleY);
} }
if(!LoadedComponent && !SystemMode) }
else
{
// are we looking at a leaf or a submenu
if (selectedItem->leaf) // item is a leaf
{ {
Config.GetMediaPropertyAbsolutePath(names[n], Type, true, videoPath);
LoadedComponent = videoBuild.CreateVideo(videoPath, "video", ScaleX, ScaleY); // check the master collection for the artifact
loadedComponent_ = findComponent(collectionName, "video", basename, false);
// check the collection for the artifact
if(!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->collectionInfo->name, "video", basename, false);
}
} }
else // item is a submenu
if(LoadedComponent)
{ {
LoadedComponent->AllocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
found = true;
}
}
std::string imageBasename = names[n]; // check the master collection for the artifact
loadedComponent_ = findComponent(collectionName, "video", basename, false);
std::string typeLC = Utils::ToLower(Type); // check the collection for the artifact
if(!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->collectionInfo->name, "video", basename, false);
}
if(typeLC == "numberButtons") // check the submenu collection for the system artifact
{ if (!loadedComponent_)
imageBasename = selectedItem->GetNumberButtons(); {
} loadedComponent_ = findComponent(selectedItem->name, "video", "video", true);
else if(typeLC == "numberPlayers") }
{
imageBasename = selectedItem->GetNumberPlayers();
}
else if(typeLC == "year")
{
imageBasename = selectedItem->GetYear();
}
else if(typeLC == "title")
{
imageBasename = selectedItem->GetTitle();
}
else if(typeLC == "manufacturer")
{
imageBasename = selectedItem->GetManufacturer();
}
else if(typeLC == "genre")
{
imageBasename = selectedItem->GetGenre();
}
Utils::ReplaceSlashesWithUnderscores(imageBasename);
if(!LoadedComponent)
{
std::string imagePath;
ImageBuilder imageBuild;
if(SystemMode)
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), Type, true, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, Type, ScaleX, ScaleY);
}
else
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), Type, false, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, imageBasename, ScaleX, ScaleY);
}
if(!LoadedComponent && !SystemMode)
{
Config.GetMediaPropertyAbsolutePath(imageBasename, Type, true, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, Type, ScaleX, ScaleY);
}
if (LoadedComponent != NULL)
{
LoadedComponent->AllocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
} }
} }
if(!LoadedComponent && TextFallback) if(loadedComponent_)
{ {
LoadedComponent = new Text(imageBasename, FontInst, ScaleX, ScaleY); loadedComponent_->allocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
} }
} }
} }
}
void ReloadableMedia::Draw() // check for images if video could not be found (and was specified)
{ for(unsigned int n = 0; n < names.size() && !loadedComponent_; ++n)
ViewInfo *info = GetBaseViewInfo();
Component::Draw();
if(LoadedComponent)
{ {
info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); std::string basename = names[n];
info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
LoadedComponent->UpdateBaseViewInfo(*info); std::string typeLC = Utils::toLower(type_);
LoadedComponent->Draw();
if(typeLC == "numberButtons")
{
basename = selectedItem->numberButtons;
}
else if(typeLC == "numberPlayers")
{
basename = selectedItem->numberPlayers;
}
else if(typeLC == "year")
{
basename = selectedItem->year;
}
else if(typeLC == "title")
{
basename = selectedItem->title;
}
else if(typeLC == "manufacturer")
{
basename = selectedItem->manufacturer;
}
else if(typeLC == "genre")
{
basename = selectedItem->genre;
}
Utils::replaceSlashesWithUnderscores(basename);
if(systemMode_)
{
// check the master collection for the system artifact
loadedComponent_ = findComponent(collectionName, type_, type_, true);
// check collection for the system artifact
if(!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->collectionInfo->name, type_, type_, true);
}
}
else
{
// are we looking at a leaf or a submenu
if (selectedItem->leaf) // item is a leaf
{
// check the master collection for the artifact
loadedComponent_ = findComponent(collectionName, type_, basename, false);
// check the collection for the artifact
if(!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->collectionInfo->name, type_, basename, false);
}
}
else // item is a submenu
{
// check the master collection for the artifact
loadedComponent_ = findComponent(collectionName, type_, basename, false);
// check the collection for the artifact
if(!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->collectionInfo->name, type_, basename, false);
}
// check the submenu collection for the system artifact
if (!loadedComponent_)
{
loadedComponent_ = findComponent(selectedItem->name, type_, type_, true);
}
}
}
if (loadedComponent_ != NULL)
{
loadedComponent_->allocateGraphicsMemory();
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
}
}
// if image and artwork was not specified, fall back to displaying text
if(!loadedComponent_ && textFallback_)
{
loadedComponent_ = new Text(selectedItem->fullTitle, FfntInst_, scaleX_, scaleY_);
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
}
}
Component *ReloadableMedia::findComponent(std::string collection, std::string type, std::string basename, bool systemMode)
{
std::string imagePath;
Component *component = NULL;
VideoBuilder videoBuild;
ImageBuilder imageBuild;
// check the system folder
config_.getMediaPropertyAbsolutePath(collection, type, systemMode, imagePath);
if(type == "video")
{
component = videoBuild.createVideo(imagePath, basename, scaleX_, scaleY_);
}
else
{
component = imageBuild.CreateImage(imagePath, basename, scaleX_, scaleY_);
}
return component;
}
void ReloadableMedia::draw()
{
Component::draw();
if(loadedComponent_)
{
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
loadedComponent_->baseViewInfo = baseViewInfo;
loadedComponent_->draw();
} }
} }

View File

@@ -29,27 +29,29 @@ class ReloadableMedia : public Component
public: public:
ReloadableMedia(Configuration &config, bool systemMode, std::string type, bool isVideo, Font *font, float scaleX, float scaleY); ReloadableMedia(Configuration &config, bool systemMode, std::string type, bool isVideo, Font *font, float scaleX, float scaleY);
virtual ~ReloadableMedia(); virtual ~ReloadableMedia();
void Update(float dt); void update(float dt);
void Draw(); void draw();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void LaunchEnter(); void launchEnter();
void LaunchExit(); void launchExit();
void EnableTextFallback(bool value); Component *findComponent(std::string collection, std::string type, std::string basename, bool systemMode);
void enableTextFallback_(bool value);
private: private:
void ReloadTexture(); void reloadTexture();
Configuration &Config; Configuration &config_;
bool SystemMode; bool systemMode_;
Component *LoadedComponent; Component *loadedComponent_;
bool ReloadRequested; bool reloadRequested_;
bool FirstLoad; bool firstLoad_;
IVideo *VideoInst; IVideo *videoInst_;
bool IsVideo; bool isVideo_;
Font *FontInst; Font *FfntInst_;
bool TextFallback; bool textFallback_;
std::string Type; std::string type_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
std::string CurrentCollection; std::string currentCollection_;
}; };

View File

@@ -24,152 +24,150 @@
#include <iostream> #include <iostream>
ReloadableText::ReloadableText(std::string type, Font *font, std::string layoutKey, float scaleX, float scaleY) ReloadableText::ReloadableText(std::string type, Font *font, std::string layoutKey, float scaleX, float scaleY)
: ImageInst(NULL) : imageInst_(NULL)
, LayoutKey(layoutKey) , layoutKey_(layoutKey)
, ReloadRequested(false) , reloadRequested_(false)
, FirstLoad(true) , firstLoad_(true)
, FontInst(font) , fontInst_(font)
, ScaleX(scaleX) , scaleX_(scaleX)
, ScaleY(scaleY) , scaleY_(scaleY)
{ {
Type = TextTypeUnknown; type_ = TextTypeUnknown;
if(type == "numberButtons") if(type == "numberButtons")
{ {
Type = TextTypeNumberButtons; type_ = TextTypeNumberButtons;
} }
else if(type == "numberPlayers") else if(type == "numberPlayers")
{ {
Type = TextTypeNumberPlayers; type_ = TextTypeNumberPlayers;
} }
else if(type == "year") else if(type == "year")
{ {
Type = TextTypeYear; type_ = TextTypeYear;
} }
else if(type == "title") else if(type == "title")
{ {
Type = TextTypeTitle; type_ = TextTypeTitle;
} }
else if(type == "manufacturer") else if(type == "manufacturer")
{ {
Type = TextTypeManufacturer; type_ = TextTypeManufacturer;
} }
else if(type == "genre") else if(type == "genre")
{ {
Type = TextTypeGenre; type_ = TextTypeGenre;
} }
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
ReloadableText::~ReloadableText() ReloadableText::~ReloadableText()
{ {
if (ImageInst != NULL) if (imageInst_ != NULL)
{ {
delete ImageInst; delete imageInst_;
} }
} }
void ReloadableText::Update(float dt) void ReloadableText::update(float dt)
{ {
if(NewItemSelected) if(newItemSelected)
{ {
ReloadRequested = true; reloadRequested_ = true;
} }
// wait for the right moment to reload the image // wait for the right moment to reload the image
if (ReloadRequested && (HighlightExitComplete || FirstLoad)) if (reloadRequested_ && (highlightExitComplete || firstLoad_))
{ {
ReloadTexture(); ReloadTexture();
ReloadRequested = false; reloadRequested_ = false;
FirstLoad = false; firstLoad_ = false;
} }
// needs to be ran at the end to prevent the NewItemSelected flag from being detected // needs to be ran at the end to prevent the NewItemSelected flag from being detected
Component::Update(dt); Component::update(dt);
} }
void ReloadableText::AllocateGraphicsMemory() void ReloadableText::allocateGraphicsMemory()
{ {
FirstLoad = true; firstLoad_ = true;
ReloadTexture(); ReloadTexture();
// NOTICE! needs to be done last to prevent flags from being missed // NOTICE! needs to be done last to prevent flags from being missed
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
} }
void ReloadableText::LaunchEnter() void ReloadableText::launchEnter()
{ {
} }
void ReloadableText::LaunchExit() void ReloadableText::launchExit()
{ {
} }
void ReloadableText::FreeGraphicsMemory() void ReloadableText::freeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
if (ImageInst != NULL) if (imageInst_ != NULL)
{ {
delete ImageInst; delete imageInst_;
ImageInst = NULL; imageInst_ = NULL;
} }
} }
void ReloadableText::ReloadTexture() void ReloadableText::ReloadTexture()
{ {
if (ImageInst != NULL) if (imageInst_ != NULL)
{ {
delete ImageInst; delete imageInst_;
ImageInst = NULL; imageInst_ = NULL;
} }
Item *selectedItem = GetSelectedItem(); Item *selectedItem = getSelectedItem();
if (selectedItem != NULL) if (selectedItem != NULL)
{ {
std::stringstream ss; std::stringstream ss;
std::string text; std::string text;
switch(Type) switch(type_)
{ {
case TextTypeNumberButtons: case TextTypeNumberButtons:
ss << selectedItem->GetNumberButtons(); ss << selectedItem->numberButtons;
break; break;
case TextTypeNumberPlayers: case TextTypeNumberPlayers:
ss << selectedItem->GetNumberPlayers(); ss << selectedItem->numberPlayers;
break; break;
case TextTypeYear: case TextTypeYear:
ss << selectedItem->GetYear(); ss << selectedItem->year;
break; break;
case TextTypeTitle: case TextTypeTitle:
ss << selectedItem->GetTitle(); ss << selectedItem->title;
break; break;
case TextTypeManufacturer: case TextTypeManufacturer:
ss << selectedItem->GetManufacturer(); ss << selectedItem->manufacturer;
break; break;
case TextTypeGenre: case TextTypeGenre:
ss << selectedItem->GetGenre(); ss << selectedItem->genre;
break; break;
default: default:
break; break;
} }
ImageInst = new Text(ss.str(), FontInst, ScaleX, ScaleY); imageInst_ = new Text(ss.str(), fontInst_, scaleX_, scaleY_);
} }
} }
void ReloadableText::Draw() void ReloadableText::draw()
{ {
ViewInfo *info = GetBaseViewInfo(); if(imageInst_)
if(ImageInst)
{ {
ImageInst->UpdateBaseViewInfo(*info); imageInst_->baseViewInfo = baseViewInfo;
ImageInst->Draw(); imageInst_->draw();
} }
} }

View File

@@ -26,12 +26,12 @@ class ReloadableText : public Component
public: public:
ReloadableText(std::string type, Font *font, std::string layoutKey, float scaleX, float scaleY); ReloadableText(std::string type, Font *font, std::string layoutKey, float scaleX, float scaleY);
virtual ~ReloadableText(); virtual ~ReloadableText();
void Update(float dt); void update(float dt);
void Draw(); void draw();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void LaunchEnter(); void launchEnter();
void LaunchExit(); void launchExit();
private: private:
enum TextType enum TextType
@@ -47,13 +47,13 @@ private:
void ReloadTexture(); void ReloadTexture();
Text *ImageInst; Text *imageInst_;
TextType Type; TextType type_;
std::string LayoutKey; std::string layoutKey_;
bool ReloadRequested; bool reloadRequested_;
bool FirstLoad; bool firstLoad_;
Font *FontInst; Font *fontInst_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -52,46 +52,45 @@ public:
ScrollingList(const ScrollingList &copy); ScrollingList(const ScrollingList &copy);
virtual ~ScrollingList(); virtual ~ScrollingList();
void TriggerMenuEnterEvent(); void triggerMenuEnterEvent();
void TriggerMenuExitEvent(); void triggerMenuExitEvent();
bool AllocateTexture(ComponentItemBinding *s); bool allocateTexture(ComponentItemBinding *s);
void DeallocateTexture(ComponentItemBinding *s); void deallocateTexture(ComponentItemBinding *s);
void SetItems(std::vector<ComponentItemBinding *> *spriteList); void setItems(std::vector<ComponentItemBinding *> *spriteList);
void DestroyItems(); void destroyItems();
void SetPoints(std::vector<ViewInfo *> *scrollPoints, std::vector<AnimationEvents *> *tweenPoints); void setPoints(std::vector<ViewInfo *> *scrollPoints, std::vector<AnimationEvents *> *tweenPoints);
void SetScrollDirection(ScrollDirection direction); void setScrollDirection(ScrollDirection direction);
void SetScrollOrientation(bool horizontal); void pageUp();
bool IsHorizontalScroll(); void pageDown();
void PageUp(); void letterUp();
void PageDown(); void letterDown();
void LetterUp(); bool isIdle();
void LetterDown(); unsigned int getScrollOffsetIndex();
bool IsIdle(); void setScrollOffsetIndex(unsigned int index);
unsigned int GetScrollOffsetIndex(); void setSelectedIndex(int selectedIndex);
void SetScrollOffsetIndex(unsigned int index); ComponentItemBinding *getSelectedCollectionItemSprite();
void SetSelectedIndex(int selectedIndex); ComponentItemBinding *getPendingCollectionItemSprite();
ComponentItemBinding *GetSelectedCollectionItemSprite(); ComponentItemBinding *getPendingSelectedCollectionItemSprite();
ComponentItemBinding *GetPendingCollectionItemSprite(); void addComponentForNotifications(MenuNotifierInterface *c);
ComponentItemBinding *GetPendingSelectedCollectionItemSprite(); void removeComponentForNotifications(MenuNotifierInterface *c);
void AddComponentForNotifications(MenuNotifierInterface *c); std::vector<ComponentItemBinding *> *getCollectionItemSprites();
void RemoveComponentForNotifications(MenuNotifierInterface *c); void removeSelectedItem();
std::vector<ComponentItemBinding *> *GetCollectionItemSprites(); void freeGraphicsMemory();
void RemoveSelectedItem(); void update(float dt);
void FreeGraphicsMemory(); void draw();
void Update(float dt); void draw(unsigned int layer);
void Draw(); void setScrollAcceleration(float value);
void Draw(unsigned int layer); void setStartScrollTime(float value);
void SetScrollAcceleration(float value); bool horizontalScroll;
void SetStartScrollTime(float value);
private: private:
void Click(double nextScrollTime); void click(double nextScrollTime);
void DeallocateSpritePoints(); void deallocateSpritePoints();
void AllocateSpritePoints(); void allocateSpritePoints();
void UpdateSprite(unsigned int spriteIndex, unsigned int pointIndex, bool newScroll, float dt, double nextScrollTime); void updateSprite(unsigned int spriteIndex, unsigned int pointIndex, bool newScroll, float dt, double nextScrollTime);
unsigned int GetNextTween(unsigned int currentIndex, std::vector<ViewInfo *> *list); unsigned int getNextTween(unsigned int currentIndex, std::vector<ViewInfo *> *list);
void ResetTweens(Component *c, AnimationEvents *sets, ViewInfo *currentViewInfo, ViewInfo *nextViewInfo, double scrollTime); void resetTweens(Component *c, AnimationEvents *sets, ViewInfo *currentViewInfo, ViewInfo *nextViewInfo, double scrollTime);
enum ScrollState enum ScrollState
{ {
@@ -101,38 +100,37 @@ private:
ScrollStateIdle ScrollStateIdle
}; };
std::vector<ComponentItemBinding *> *SpriteList; std::vector<ComponentItemBinding *> *spriteList_;
std::vector<ViewInfo *> *ScrollPoints; std::vector<ViewInfo *> *scrollPoints_;
std::vector<AnimationEvents *> *TweenPoints; std::vector<AnimationEvents *> *tweenPoints_;
std::vector<MenuNotifierInterface *> NotificationComponents; std::vector<MenuNotifierInterface *> notificationComponents_;
float TweenEnterTime; float tweenEnterTime_;
bool Focus; bool focus_;
unsigned int FirstSpriteIndex; unsigned int firstSpriteIndex_;
unsigned int SelectedSpriteListIndex; unsigned int selectedSpriteListIndex_;
bool ScrollStopRequested; bool scrollStopRequested_;
bool NotifyAllRequested; bool notifyAllRequested_;
ScrollDirection CurrentScrollDirection; ScrollDirection currentScrollDirection_;
ScrollDirection RequestedScrollDirection; ScrollDirection requestedScrollDirection_;
ScrollState CurrentScrollState; ScrollState currentScrollState_;
float ScrollAcceleration; float scrollAcceleration_;
float StartScrollTime; float startScrollTime_;
float ScrollPeriod; float scrollPeriod_;
int CircularIncrement(unsigned int index, unsigned int offset, std::vector<ComponentItemBinding *> *list); int circularIncrement(unsigned int index, unsigned int offset, std::vector<ComponentItemBinding *> *list);
void CircularIncrement(unsigned &index, std::vector<ComponentItemBinding *> *list); void circularIncrement(unsigned &index, std::vector<ComponentItemBinding *> *list);
void CircularDecrement(unsigned &index, std::vector<ComponentItemBinding *> *list); void circularDecrement(unsigned &index, std::vector<ComponentItemBinding *> *list);
void CircularIncrement(unsigned &index, std::vector<ViewInfo *> *list); void circularIncrement(unsigned &index, std::vector<ViewInfo *> *list);
void CircularDecrement(unsigned &index, std::vector<ViewInfo *> *list); void circularDecrement(unsigned &index, std::vector<ViewInfo *> *list);
void UpdateOffset(float dt); void updateOffset(float dt);
std::string Collection; std::string collection_;
Configuration &Config; Configuration &config_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
Font *FontInst; Font *fontInst_;
std::string LayoutKey; std::string layoutKey_;
std::string ImageType; std::string imageType_;
bool HorizontalScroll;
}; };

View File

@@ -21,114 +21,113 @@
#include <sstream> #include <sstream>
Text::Text(std::string text, Font *font, float scaleX, float scaleY) Text::Text(std::string text, Font *font, float scaleX, float scaleY)
: TextData(text) : textData_(text)
, FontInst(font) , fontInst_(font)
, ScaleX(scaleX) , scaleX_(scaleX)
, ScaleY(scaleY) , scaleY_(scaleY)
{ {
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
Text::~Text() Text::~Text()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
} }
void Text::FreeGraphicsMemory() void Text::freeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
} }
void Text::AllocateGraphicsMemory() void Text::allocateGraphicsMemory()
{ {
//todo: make the font blend color a parameter that is passed in //todo: make the font blend color a parameter that is passed in
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
} }
void Text::SetText(std::string text) void Text::setText(std::string text)
{ {
TextData = text; textData_ = text;
} }
void Text::Draw() void Text::draw()
{ {
Component::Draw(); Component::draw();
SDL_Texture *t = FontInst->GetTexture(); SDL_Texture *t = fontInst_->getTexture();
ViewInfo *info = GetBaseViewInfo();
float imageHeight = 0; float imageHeight = 0;
float imageWidth = 0; float imageWidth = 0;
// determine image width // determine image width
for(unsigned int i = 0; i < TextData.size(); ++i) for(unsigned int i = 0; i < textData_.size(); ++i)
{ {
Font::GlyphInfo glyph; Font::GlyphInfo glyph;
if(FontInst->GetRect(TextData[i], glyph)) if(fontInst_->getRect(textData_[i], glyph))
{ {
if(glyph.MinX < 0) if(glyph.minX < 0)
{ {
imageWidth += glyph.MinX; imageWidth += glyph.minX;
} }
imageWidth += glyph.Advance; imageWidth += glyph.advance;
} }
} }
imageHeight = (float)FontInst->GetHeight(); imageHeight = (float)fontInst_->getHeight();
float scale = (float)info->GetFontSize() / (float)imageHeight; float scale = (float)baseViewInfo.FontSize / (float)imageHeight;
float oldWidth = info->GetRawWidth(); float oldWidth = baseViewInfo.Width;
float oldHeight = info->GetRawHeight(); float oldHeight = baseViewInfo.Height;
float oldImageWidth = info->GetImageHeight(); float oldImageWidth = baseViewInfo.ImageHeight;
float oldImageHeight = info->GetImageWidth(); float oldImageHeight = baseViewInfo.ImageWidth;
info->SetWidth(imageWidth*scale); baseViewInfo.Width = imageWidth*scale;
info->SetHeight(info->GetFontSize()); baseViewInfo.Height = baseViewInfo.FontSize;
info->SetImageWidth(imageWidth); baseViewInfo.ImageWidth = imageWidth;
info->SetImageHeight(imageHeight); baseViewInfo.ImageHeight = imageHeight;
float xOrigin = info->GetXRelativeToOrigin(); float xOrigin = baseViewInfo.XRelativeToOrigin();
float yOrigin = info->GetYRelativeToOrigin(); float yOrigin = baseViewInfo.YRelativeToOrigin();
info->SetWidth(oldWidth); baseViewInfo.Width = oldWidth;
info->SetHeight(oldHeight); baseViewInfo.Height = oldHeight;
info->SetImageWidth(oldImageWidth); baseViewInfo.ImageWidth = oldImageWidth;
info->SetImageHeight(oldImageHeight); baseViewInfo.ImageHeight = oldImageHeight;
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(xOrigin); rect.x = static_cast<int>(xOrigin);
for(unsigned int i = 0; i < TextData.size(); ++i) for(unsigned int i = 0; i < textData_.size(); ++i)
{ {
Font::GlyphInfo glyph; Font::GlyphInfo glyph;
if(FontInst->GetRect(TextData[i], glyph) && glyph.Rect.h > 0) if(fontInst_->getRect(textData_[i], glyph) && glyph.rect.h > 0)
{ {
SDL_Rect charRect = glyph.Rect; SDL_Rect charRect = glyph.rect;
float h = static_cast<float>(charRect.h * scale); float h = static_cast<float>(charRect.h * scale);
float w = static_cast<float>(charRect.w * scale); float w = static_cast<float>(charRect.w * scale);
rect.h = static_cast<int>(h); rect.h = static_cast<int>(h);
rect.w = static_cast<int>(w); rect.w = static_cast<int>(w);
rect.y = static_cast<int>(yOrigin); rect.y = static_cast<int>(yOrigin);
if(glyph.MinX < 0) if(glyph.minX < 0)
{ {
rect.x += static_cast<int>((float)(glyph.MinX) * scale); rect.x += static_cast<int>((float)(glyph.minX) * scale);
} }
if(FontInst->GetAscent() < glyph.MaxY) if(fontInst_->getAscent() < glyph.maxY)
{ {
rect.y += static_cast<int>((FontInst->GetAscent() - glyph.MaxY)*scale); rect.y += static_cast<int>((fontInst_->getAscent() - glyph.maxY)*scale);
} }
SDL::RenderCopy(t, static_cast<char>(info->GetAlpha() * 255), &charRect, &rect, info->GetAngle()); SDL::renderCopy(t, static_cast<char>(baseViewInfo.Alpha * 255), &charRect, &rect, baseViewInfo.Angle);
rect.x += static_cast<int>(glyph.Advance * scale); rect.x += static_cast<int>(glyph.advance * scale);
if((static_cast<float>(rect.x) - xOrigin) > info->GetMaxWidth()) if((static_cast<float>(rect.x) - xOrigin) > baseViewInfo.MaxWidth)
{ {
break; break;
} }

View File

@@ -27,15 +27,15 @@ class Text : public Component
public: public:
//todo: should have a Font flass that references fontcache, pass that in as an argument //todo: should have a Font flass that references fontcache, pass that in as an argument
Text(std::string text, Font *font, float scaleX, float scaleY); Text(std::string text, Font *font, float scaleX, float scaleY);
void SetText(std::string text);
virtual ~Text(); virtual ~Text();
void AllocateGraphicsMemory(); void setText(std::string text);
void FreeGraphicsMemory(); void allocateGraphicsMemory();
void Draw(); void freeGraphicsMemory();
void draw();
private: private:
std::string TextData; std::string textData_;
Font *FontInst; Font *fontInst_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
}; };

View File

@@ -21,7 +21,7 @@
#include <fstream> #include <fstream>
VideoComponent * VideoBuilder::CreateVideo(std::string path, std::string name, float scaleX, float scaleY) VideoComponent * VideoBuilder::createVideo(std::string path, std::string name, float scaleX, float scaleY)
{ {
VideoComponent *component = NULL; VideoComponent *component = NULL;
std::vector<std::string> extensions; std::vector<std::string> extensions;
@@ -31,12 +31,12 @@ VideoComponent * VideoBuilder::CreateVideo(std::string path, std::string name, f
extensions.push_back("avi"); extensions.push_back("avi");
extensions.push_back("AVI"); extensions.push_back("AVI");
std::string prefix = Utils::CombinePath(path, name); std::string prefix = Utils::combinePath(path, name);
std::string file; std::string file;
if(Utils::FindMatchingFile(prefix, extensions, file)) if(Utils::findMatchingFile(prefix, extensions, file))
{ {
IVideo *video = Factory.CreateVideo(); IVideo *video = factory_.createVideo();
if(video) if(video)
{ {

View File

@@ -23,8 +23,8 @@
class VideoBuilder class VideoBuilder
{ {
public: public:
VideoComponent * CreateVideo(std::string path, std::string name, float scaleX, float scaleY); VideoComponent * createVideo(std::string path, std::string name, float scaleX, float scaleY);
private: private:
VideoFactory Factory; VideoFactory factory_;
}; };

View File

@@ -21,85 +21,84 @@
#include "../../SDL.h" #include "../../SDL.h"
VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY) VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY)
: VideoFile(videoFile) : videoFile_(videoFile)
, VideoInst(videoInst) , videoInst_(videoInst)
, ScaleX(scaleX) , scaleX_(scaleX)
, ScaleY(scaleY) , scaleY_(scaleY)
, IsPlaying(false) , isPlaying_(false)
{ {
// AllocateGraphicsMemory(); // AllocateGraphicsMemory();
} }
VideoComponent::~VideoComponent() VideoComponent::~VideoComponent()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
if(VideoInst) if(videoInst_)
{ {
VideoInst->Stop(); videoInst_->stop();
} }
} }
void VideoComponent::Update(float dt) void VideoComponent::update(float dt)
{ {
if(IsPlaying) if(isPlaying_)
{ {
VideoInst->Update(dt); videoInst_->update(dt);
// video needs to run a frame to start getting size info // video needs to run a frame to start getting size info
if(GetBaseViewInfo()->GetImageHeight() == 0 && GetBaseViewInfo()->GetImageWidth() == 0) if(baseViewInfo.ImageHeight == 0 && baseViewInfo.ImageWidth == 0)
{ {
GetBaseViewInfo()->SetImageHeight(static_cast<float>(VideoInst->GetHeight())); baseViewInfo.ImageHeight = static_cast<float>(videoInst_->getHeight());
GetBaseViewInfo()->SetImageWidth(static_cast<float>(VideoInst->GetWidth())); baseViewInfo.ImageWidth = static_cast<float>(videoInst_->getWidth());
} }
} }
Component::Update(dt); Component::update(dt);
} }
void VideoComponent::AllocateGraphicsMemory() void VideoComponent::allocateGraphicsMemory()
{ {
Component::AllocateGraphicsMemory(); Component::allocateGraphicsMemory();
if(!IsPlaying) if(!isPlaying_)
{ {
IsPlaying = VideoInst->Play(VideoFile); isPlaying_ = videoInst_->play(videoFile_);
} }
} }
void VideoComponent::FreeGraphicsMemory() void VideoComponent::freeGraphicsMemory()
{ {
VideoInst->Stop(); videoInst_->stop();
IsPlaying = false; isPlaying_ = false;
Component::FreeGraphicsMemory(); Component::freeGraphicsMemory();
} }
void VideoComponent::LaunchEnter() void VideoComponent::launchEnter()
{ {
FreeGraphicsMemory(); freeGraphicsMemory();
} }
void VideoComponent::LaunchExit() void VideoComponent::launchExit()
{ {
AllocateGraphicsMemory(); allocateGraphicsMemory();
} }
void VideoComponent::Draw() void VideoComponent::draw()
{ {
ViewInfo *info = GetBaseViewInfo();
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(info->GetXRelativeToOrigin()); rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin()); rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight()); rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
rect.w = static_cast<int>(info->GetWidth()); rect.w = static_cast<int>(baseViewInfo.ScaledWidth());
VideoInst->Draw(); videoInst_->draw();
SDL_Texture *texture = VideoInst->GetTexture(); SDL_Texture *texture = videoInst_->getTexture();
if(texture) if(texture)
{ {
SDL::RenderCopy(texture, static_cast<int>(info->GetAlpha() * 255), NULL, &rect, static_cast<int>(info->GetAngle())); SDL::renderCopy(texture, static_cast<int>(baseViewInfo.Alpha * 255), NULL, &rect, static_cast<int>(baseViewInfo.Angle));
} }
} }

View File

@@ -26,18 +26,18 @@ class VideoComponent : public Component
public: public:
VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY); VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY);
virtual ~VideoComponent(); virtual ~VideoComponent();
void Update(float dt); void update(float dt);
void Draw(); void draw();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void LaunchEnter(); void launchEnter();
void LaunchExit(); void launchExit();
private: private:
std::string VideoFile; std::string videoFile_;
std::string Name; std::string name_;
IVideo *VideoInst; IVideo *videoInst_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
bool IsPlaying; bool isPlaying_;
}; };

View File

@@ -16,14 +16,14 @@
#include "ComponentItemBinding.h" #include "ComponentItemBinding.h"
ComponentItemBinding::ComponentItemBinding( Component *c, Item *item) ComponentItemBinding::ComponentItemBinding( Component *c, Item *item)
: CollectionComponent(c) : component(c)
, CollectionItem(item) , item(item)
{ {
} }
ComponentItemBinding::ComponentItemBinding(Item *item) ComponentItemBinding::ComponentItemBinding(Item *item)
: CollectionComponent(NULL) : component(NULL)
, CollectionItem(item) , item(item)
{ {
} }
@@ -31,17 +31,3 @@ ComponentItemBinding::~ComponentItemBinding()
{ {
} }
Item* ComponentItemBinding::GetCollectionItem() const
{
return CollectionItem;
}
void ComponentItemBinding::SetComponent(Component *c)
{
CollectionComponent = c;
}
Component* ComponentItemBinding::GetComponent() const
{
return CollectionComponent;
}

View File

@@ -24,13 +24,7 @@ public:
ComponentItemBinding(Component *c, Item *item); ComponentItemBinding(Component *c, Item *item);
ComponentItemBinding(Item *item); ComponentItemBinding(Item *item);
virtual ~ComponentItemBinding(); virtual ~ComponentItemBinding();
Item* GetCollectionItem() const;
void SetComponent(Component *c); Component *component;
Component* GetComponent() const; Item *item;
private:
Component *CollectionComponent;
Item *CollectionItem;
}; };

View File

@@ -26,7 +26,7 @@ ComponentItemBindingBuilder::~ComponentItemBindingBuilder()
{ {
} }
std::vector<ComponentItemBinding *> *ComponentItemBindingBuilder::BuildCollectionItems(std::vector<Item *> *infoList) std::vector<ComponentItemBinding *> *ComponentItemBindingBuilder::buildCollectionItems(std::vector<Item *> *infoList)
{ {
std::vector<ComponentItemBinding *> *sprites = new std::vector<ComponentItemBinding *>(); std::vector<ComponentItemBinding *> *sprites = new std::vector<ComponentItemBinding *>();
std::vector<Item *>::iterator it; std::vector<Item *>::iterator it;

View File

@@ -26,5 +26,5 @@ class ComponentItemBindingBuilder
public: public:
ComponentItemBindingBuilder(); ComponentItemBindingBuilder();
virtual ~ComponentItemBindingBuilder(); virtual ~ComponentItemBindingBuilder();
static std::vector<ComponentItemBinding *> *BuildCollectionItems(std::vector<Item *> *infoList); static std::vector<ComponentItemBinding *> *buildCollectionItems(std::vector<Item *> *infoList);
}; };

View File

@@ -22,29 +22,37 @@
#include <cstring> #include <cstring>
Font::Font() Font::Font()
: Texture(NULL) : texture(NULL)
{ {
} }
Font::~Font() Font::~Font()
{ {
DeInitialize(); deInitialize();
} }
SDL_Texture *Font::GetTexture() SDL_Texture *Font::getTexture()
{ {
return Texture; return texture;
} }
bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph) int Font::getHeight()
{ {
std::map<unsigned int, GlyphInfoBuild *>::iterator it = Atlas.find(charCode); return height;
}
int Font::getAscent()
{
return ascent;
}
bool Font::getRect(unsigned int charCode, GlyphInfo &glyph)
{
std::map<unsigned int, GlyphInfoBuild *>::iterator it = atlas.find(charCode);
if(it != Atlas.end()) if(it != atlas.end())
{ {
GlyphInfoBuild *info = it->second; GlyphInfoBuild *info = it->second;
glyph = info->Glyph; glyph = info->glyph;
return true; return true;
} }
@@ -52,7 +60,7 @@ bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph)
return false; return false;
} }
bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color) bool Font::initialize(std::string fontPath, int fontSize, SDL_Color color)
{ {
TTF_Font *font = TTF_OpenFont(fontPath.c_str(), fontSize); TTF_Font *font = TTF_OpenFont(fontPath.c_str(), fontSize);
@@ -60,7 +68,7 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Could not open font: " << TTF_GetError(); ss << "Could not open font: " << TTF_GetError();
Logger::Write(Logger::ZONE_ERROR, "FontCache", ss.str()); Logger::write(Logger::ZONE_ERROR, "FontCache", ss.str());
return false; return false;
} }
@@ -68,8 +76,8 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
int y = 0; int y = 0;
int atlasHeight = 0; int atlasHeight = 0;
int atlasWidth = 0; int atlasWidth = 0;
Height = TTF_FontHeight(font); height = TTF_FontHeight(font);
Ascent = TTF_FontAscent(font); ascent = TTF_FontAscent(font);
for(unsigned short int i = 32; i < 128; ++i) for(unsigned short int i = 32; i < 128; ++i)
{ {
@@ -77,10 +85,13 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
memset(info, 0, sizeof(GlyphInfoBuild)); memset(info, 0, sizeof(GlyphInfoBuild));
color.a = 255; color.a = 255;
info->Surface = TTF_RenderGlyph_Blended(font, i, color); info->surface = TTF_RenderGlyph_Blended(font, i, color);
TTF_GlyphMetrics(font, i, &info->Glyph.MinX, &info->Glyph.MaxX, &info->Glyph.MinY, &info->Glyph.MaxY, &info->Glyph.Advance); TTF_GlyphMetrics(font, i,
&info->glyph.minX, &info->glyph.maxX,
&info->glyph.minY, &info->glyph.maxY,
&info->glyph.advance);
if(x + info->Surface->w >= 1024) if(x + info->surface->w >= 1024)
{ {
atlasHeight += y; atlasHeight += y;
atlasWidth = (atlasWidth >= x) ? atlasWidth : x; atlasWidth = (atlasWidth >= x) ? atlasWidth : x;
@@ -88,14 +99,14 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
y = 0; y = 0;
} }
info->Glyph.Rect.w = info->Surface->w; info->glyph.rect.w = info->surface->w;
info->Glyph.Rect.h = info->Surface->h; info->glyph.rect.h = info->surface->h;
info->Glyph.Rect.x = x; info->glyph.rect.x = x;
info->Glyph.Rect.y = atlasHeight; info->glyph.rect.y = atlasHeight;
Atlas[i] = info; atlas[i] = info;
x += info->Glyph.Rect.w; x += info->glyph.rect.w;
y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h; y = (y > info->glyph.rect.h) ? y : info->glyph.rect.h;
/* /*
std::stringstream ss; std::stringstream ss;
ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h; ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h;
@@ -124,19 +135,19 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 32, rmask, gmask, bmask, amask); SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 32, rmask, gmask, bmask, amask);
std::map<unsigned int, GlyphInfoBuild *>::iterator it; std::map<unsigned int, GlyphInfoBuild *>::iterator it;
for(it = Atlas.begin(); it != Atlas.end(); it++) for(it = atlas.begin(); it != atlas.end(); it++)
{ {
GlyphInfoBuild *info = it->second; GlyphInfoBuild *info = it->second;
SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect); SDL_BlitSurface(info->surface, NULL, atlasSurface, &info->glyph.rect);
SDL_FreeSurface(info->Surface); SDL_FreeSurface(info->surface);
info->Surface = NULL; info->surface = NULL;
} }
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface); texture = SDL_CreateTextureFromSurface(SDL::getRenderer(), atlasSurface);
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_ADD); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_ADD);
SDL_FreeSurface(atlasSurface); SDL_FreeSurface(atlasSurface);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
TTF_CloseFont(font); TTF_CloseFont(font);
@@ -145,32 +156,24 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
void Font::DeInitialize() void Font::deInitialize()
{ {
if(Texture) if(texture)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
SDL_DestroyTexture(Texture); SDL_DestroyTexture(texture);
Texture = NULL; texture = NULL;
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = Atlas.begin(); std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = atlas.begin();
while(atlasIt != Atlas.end()) while(atlasIt != atlas.end())
{ {
delete atlasIt->second; delete atlasIt->second;
Atlas.erase(atlasIt); atlas.erase(atlasIt);
atlasIt = Atlas.begin(); atlasIt = atlas.begin();
} }
} }
int Font::GetHeight()
{
return Height;
}
int Font::GetAscent()
{
return Ascent;
}

View File

@@ -24,32 +24,32 @@ class Font
public: public:
struct GlyphInfo struct GlyphInfo
{ {
int MinX; int minX;
int MaxX; int maxX;
int MinY; int minY;
int MaxY; int maxY;
int Advance; int advance;
SDL_Rect Rect; SDL_Rect rect;
}; };
Font(); Font();
virtual ~Font(); virtual ~Font();
bool Initialize(std::string fontPath, int fontSize, SDL_Color color); bool initialize(std::string fontPath, int fontSize, SDL_Color color);
void DeInitialize(); void deInitialize();
SDL_Texture *GetTexture(); SDL_Texture *getTexture();
bool GetRect(unsigned int charCode, GlyphInfo &glyph); bool getRect(unsigned int charCode, GlyphInfo &glyph);
int GetHeight(); int getHeight();
int GetAscent(); int getAscent();
private: private:
struct GlyphInfoBuild struct GlyphInfoBuild
{ {
Font::GlyphInfo Glyph; Font::GlyphInfo glyph;
SDL_Surface *Surface; SDL_Surface *surface;
}; };
int Height; SDL_Texture *texture;
int Ascent; int height;
std::map<unsigned int, GlyphInfoBuild *> Atlas; int ascent;
SDL_Texture *Texture; std::map<unsigned int, GlyphInfoBuild *> atlas;
}; };

View File

@@ -28,37 +28,37 @@ FontCache::FontCache()
FontCache::~FontCache() FontCache::~FontCache()
{ {
DeInitialize(); deInitialize();
} }
void FontCache::DeInitialize() void FontCache::deInitialize()
{ {
std::map<std::string, Font *>::iterator it = FontFaceMap.begin(); std::map<std::string, Font *>::iterator it = fontFaceMap_.begin();
while(it != FontFaceMap.end()) while(it != fontFaceMap_.end())
{ {
delete it->second; delete it->second;
FontFaceMap.erase(it); fontFaceMap_.erase(it);
it = FontFaceMap.begin(); it = fontFaceMap_.begin();
} }
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
TTF_Quit(); TTF_Quit();
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
void FontCache::Initialize() void FontCache::initialize()
{ {
//todo: make bool //todo: make bool
TTF_Init(); TTF_Init();
} }
Font *FontCache::GetFont(std::string fontPath, int fontSize, SDL_Color color) Font *FontCache::getFont(std::string fontPath, int fontSize, SDL_Color color)
{ {
Font *t = NULL; Font *t = NULL;
std::map<std::string, Font *>::iterator it = FontFaceMap.find(BuildFontKey(fontPath, fontSize, color)); std::map<std::string, Font *>::iterator it = fontFaceMap_.find(buildFontKey(fontPath, fontSize, color));
if(it != FontFaceMap.end()) if(it != fontFaceMap_.end())
{ {
t = it->second; t = it->second;
} }
@@ -66,7 +66,7 @@ Font *FontCache::GetFont(std::string fontPath, int fontSize, SDL_Color color)
return t; return t;
} }
std::string FontCache::BuildFontKey(std::string font, int fontSize, SDL_Color color) std::string FontCache::buildFontKey(std::string font, int fontSize, SDL_Color color)
{ {
std::stringstream ss; std::stringstream ss;
ss << font << "_SIZE=" << fontSize << " RGB=" << color.r << "." << color.g << "." << color.b; ss << font << "_SIZE=" << fontSize << " RGB=" << color.r << "." << color.g << "." << color.b;
@@ -74,16 +74,16 @@ std::string FontCache::BuildFontKey(std::string font, int fontSize, SDL_Color co
return ss.str(); return ss.str();
} }
bool FontCache::LoadFont(std::string fontPath, int fontSize, SDL_Color color) bool FontCache::loadFont(std::string fontPath, int fontSize, SDL_Color color)
{ {
std::string key = BuildFontKey(fontPath, fontSize, color); std::string key = buildFontKey(fontPath, fontSize, color);
std::map<std::string, Font *>::iterator it = FontFaceMap.find(key); std::map<std::string, Font *>::iterator it = fontFaceMap_.find(key);
if(it == FontFaceMap.end()) if(it == fontFaceMap_.end())
{ {
Font *f = new Font(); Font *f = new Font();
f->Initialize(fontPath, fontSize, color); f->initialize(fontPath, fontSize, color);
FontFaceMap[key] = f; fontFaceMap_[key] = f;
} }
return true; return true;

View File

@@ -22,16 +22,16 @@
class FontCache class FontCache
{ {
public: public:
void Initialize();
void DeInitialize();
FontCache(); FontCache();
bool LoadFont(std::string font, int fontSize, SDL_Color color); void initialize();
Font *GetFont(std::string font, int fontSize, SDL_Color color); void deInitialize();
bool loadFont(std::string font, int fontSize, SDL_Color color);
Font *getFont(std::string font, int fontSize, SDL_Color color);
virtual ~FontCache(); virtual ~FontCache();
private: private:
std::map<std::string, Font *> FontFaceMap; std::map<std::string, Font *> fontFaceMap_;
std::string BuildFontKey(std::string font, int fontSize, SDL_Color color); std::string buildFontKey(std::string font, int fontSize, SDL_Color color);
}; };

View File

@@ -21,6 +21,6 @@ class MenuNotifierInterface
{ {
public: public:
virtual ~MenuNotifierInterface() {} virtual ~MenuNotifierInterface() {}
virtual void OnNewItemSelected(Item *) = 0; virtual void onNewItemSelected(Item *) = 0;
}; };

View File

@@ -26,32 +26,32 @@
#include <sstream> #include <sstream>
Page::Page(Configuration &config) Page::Page(Configuration &config)
: Config(config) : config_(config)
, ActiveMenu(NULL) , activeMenu_(NULL)
, MenuDepth(0) , menuDepth_(0)
, Items(NULL) , items_(NULL)
, ScrollActive(false) , scrollActive_(false)
, SelectedItem(NULL) , selectedItem_(NULL)
, TextStatusComponent(NULL) , textStatusComponent_(NULL)
, SelectedItemChanged(false) , selectedItemChanged_(false)
, LoadSoundChunk(NULL) , loadSoundChunk_(NULL)
, UnloadSoundChunk(NULL) , unloadSoundChunk_(NULL)
, HighlightSoundChunk(NULL) , highlightSoundChunk_(NULL)
, SelectSoundChunk(NULL) , selectSoundChunk_(NULL)
, MinShowTime(0) , minShowTime_(0)
{ {
} }
Page::~Page() Page::~Page()
{ {
MenuVector_T::iterator it = Menus.begin(); MenuVector_T::iterator it = menus_.begin();
while(it != Menus.end()) while(it != menus_.end())
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->RemoveComponentForNotifications(this); menu->removeComponentForNotifications(this);
Menus.erase(it); menus_.erase(it);
delete menu; delete menu;
it = Menus.begin(); it = menus_.begin();
} }
for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i) for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i)
@@ -65,85 +65,85 @@ Page::~Page()
} }
if(LoadSoundChunk) if(loadSoundChunk_)
{ {
delete LoadSoundChunk; delete loadSoundChunk_;
LoadSoundChunk = NULL; loadSoundChunk_ = NULL;
} }
if(UnloadSoundChunk) if(unloadSoundChunk_)
{ {
delete UnloadSoundChunk; delete unloadSoundChunk_;
UnloadSoundChunk = NULL; unloadSoundChunk_ = NULL;
} }
if(HighlightSoundChunk) if(highlightSoundChunk_)
{ {
delete HighlightSoundChunk; delete highlightSoundChunk_;
HighlightSoundChunk = NULL; highlightSoundChunk_ = NULL;
} }
if(SelectSoundChunk) if(selectSoundChunk_)
{ {
delete SelectSoundChunk; delete selectSoundChunk_;
SelectSoundChunk = NULL; selectSoundChunk_ = NULL;
} }
} }
bool Page::IsMenusFull() bool Page::isMenusFull()
{ {
return (MenuDepth > Menus.size()); return (menuDepth_ > menus_.size());
} }
void Page::SetLoadSound(Sound *chunk) void Page::setLoadSound(Sound *chunk)
{ {
LoadSoundChunk = chunk; loadSoundChunk_ = chunk;
} }
void Page::SetUnloadSound(Sound *chunk) void Page::setUnloadSound(Sound *chunk)
{ {
UnloadSoundChunk = chunk; unloadSoundChunk_ = chunk;
} }
void Page::SetHighlightSound(Sound *chunk) void Page::setHighlightSound(Sound *chunk)
{ {
HighlightSoundChunk = chunk; highlightSoundChunk_ = chunk;
} }
void Page::SetSelectSound(Sound *chunk) void Page::setSelectSound(Sound *chunk)
{ {
SelectSoundChunk = chunk; selectSoundChunk_ = chunk;
} }
void Page::OnNewItemSelected(Item *item) void Page::onNewItemSelected(Item *item)
{ {
SelectedItem = item; selectedItem_ = item;
SelectedItemChanged = true; selectedItemChanged_ = true;
} }
void Page::PushMenu(ScrollingList *s) void Page::pushMenu(ScrollingList *s)
{ {
Menus.push_back(s); menus_.push_back(s);
if(s) if(s)
{ {
s->AddComponentForNotifications(this); s->addComponentForNotifications(this);
} }
} }
unsigned int Page::GetMenuDepth() unsigned int Page::getMenuDepth()
{ {
return MenuDepth; return menuDepth_;
} }
void Page::SetStatusTextComponent(Text *t) void Page::setStatusTextComponent(Text *t)
{ {
TextStatusComponent = t; textStatusComponent_ = t;
} }
bool Page::AddComponent(Component *c) bool Page::addComponent(Component *c)
{ {
bool retVal = false; bool retVal = false;
unsigned int layer = c->GetBaseViewInfo()->GetLayer(); unsigned int layer = c->baseViewInfo.Layer;
if(layer < NUM_LAYERS) if(layer < NUM_LAYERS)
@@ -156,21 +156,21 @@ bool Page::AddComponent(Component *c)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Component layer too large Layer: " << layer; ss << "Component layer too large Layer: " << layer;
Logger::Write(Logger::ZONE_ERROR, "Page", ss.str()); Logger::write(Logger::ZONE_ERROR, "Page", ss.str());
} }
return retVal; return retVal;
} }
bool Page::IsMenuIdle() bool Page::isMenuIdle()
{ {
bool idle = true; bool idle = true;
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
if(!menu->IsIdle()) if(!menu->isIdle())
{ {
idle = false; idle = false;
break; break;
@@ -179,15 +179,15 @@ bool Page::IsMenuIdle()
return idle; return idle;
} }
bool Page::IsIdle() bool Page::isIdle()
{ {
bool idle = IsMenuIdle(); bool idle = isMenuIdle();
for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i) for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it)
{ {
idle = (*it)->IsIdle(); idle = (*it)->isIdle();
} }
} }
@@ -195,15 +195,15 @@ bool Page::IsIdle()
} }
bool Page::IsHidden() bool Page::isHidden()
{ {
bool hidden = true; bool hidden = true;
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
if(!menu->IsHidden()) if(!menu->isHidden())
{ {
hidden = false; hidden = false;
break; break;
@@ -215,70 +215,70 @@ bool Page::IsHidden()
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it)
{ {
hidden = (*it)->IsHidden(); hidden = (*it)->isHidden();
} }
} }
return hidden; return hidden;
} }
void Page::Start() void Page::start()
{ {
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->TriggerEnterEvent(); menu->triggerEnterEvent();
} }
if(LoadSoundChunk) if(loadSoundChunk_)
{ {
LoadSoundChunk->Play(); loadSoundChunk_->play();
} }
StartComponents(); startComponents();
} }
void Page::StartComponents() void Page::startComponents()
{ {
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerEnterEvent(); (*it)->triggerEnterEvent();
} }
} }
} }
void Page::Stop() void Page::stop()
{ {
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->TriggerExitEvent(); menu->triggerExitEvent();
} }
if(UnloadSoundChunk) if(unloadSoundChunk_)
{ {
UnloadSoundChunk->Play(); unloadSoundChunk_->play();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerExitEvent(); (*it)->triggerExitEvent();
} }
} }
} }
Item *Page::GetSelectedItem() Item *Page::getSelectedItem()
{ {
return SelectedItem; return selectedItem_;
} }
void Page::RemoveSelectedItem() void Page::removeSelectedItem()
{ {
/* /*
//todo: change method to RemoveItem() and pass in SelectedItem //todo: change method to RemoveItem() and pass in SelectedItem
@@ -287,177 +287,177 @@ void Page::RemoveSelectedItem()
Menu->RemoveSelectedItem(); Menu->RemoveSelectedItem();
} }
*/ */
SelectedItem = NULL; selectedItem_ = NULL;
} }
void Page::SetScrollOffsetIndex(unsigned int i) void Page::setScrollOffsetIndex(unsigned int i)
{ {
if(!ActiveMenu) return; if(!activeMenu_) return;
ActiveMenu->SetScrollOffsetIndex(i); activeMenu_->setScrollOffsetIndex(i);
} }
unsigned int Page::GetScrollOffsetIndex() unsigned int Page::getScrollOffsetIndex()
{ {
if(!ActiveMenu) return -1; if(!activeMenu_) return -1;
return ActiveMenu->GetScrollOffsetIndex(); return activeMenu_->getScrollOffsetIndex();
} }
void Page::SetMinShowTime(float value) void Page::setMinShowTime(float value)
{ {
MinShowTime = value; minShowTime_ = value;
} }
float Page::GetMinShowTime() float Page::getMinShowTime()
{ {
return MinShowTime; return minShowTime_;
} }
void Page::Highlight() void Page::highlight()
{ {
Item *item = SelectedItem; Item *item = selectedItem_;
if(item) if(item)
{ {
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->TriggerHighlightEvent(item); activeMenu_->triggerHighlightEvent(item);
ActiveMenu->SetScrollActive(ScrollActive); activeMenu_->scrollActive = scrollActive_;
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerHighlightEvent(item); (*it)->triggerHighlightEvent(item);
(*it)->SetScrollActive(ScrollActive); (*it)->scrollActive = scrollActive_;
} }
} }
} }
} }
void Page::SetScrolling(ScrollDirection direction) void Page::setScrolling(ScrollDirection direction)
{ {
ScrollingList::ScrollDirection menuDirection; ScrollingList::ScrollDirection menuDirection;
bool prevScrollActive = ScrollActive; bool prevScrollActive = scrollActive_;
switch(direction) switch(direction)
{ {
case ScrollDirectionForward: case ScrollDirectionForward:
menuDirection = ScrollingList::ScrollDirectionForward; menuDirection = ScrollingList::ScrollDirectionForward;
ScrollActive = true; scrollActive_ = true;
break; break;
case ScrollDirectionBack: case ScrollDirectionBack:
menuDirection = ScrollingList::ScrollDirectionBack; menuDirection = ScrollingList::ScrollDirectionBack;
ScrollActive = true; scrollActive_ = true;
break; break;
case ScrollDirectionIdle: case ScrollDirectionIdle:
default: default:
menuDirection = ScrollingList::ScrollDirectionIdle; menuDirection = ScrollingList::ScrollDirectionIdle;
ScrollActive = false; scrollActive_ = false;
break; break;
} }
if(!prevScrollActive && ScrollActive && HighlightSoundChunk) if(!prevScrollActive && scrollActive_ && highlightSoundChunk_)
{ {
HighlightSoundChunk->Play(); highlightSoundChunk_->play();
} }
ActiveMenu->SetScrollDirection(menuDirection); activeMenu_->setScrollDirection(menuDirection);
} }
bool Page::IsHorizontalScroll() bool Page::isHorizontalScroll()
{ {
if(!ActiveMenu) { return false; } if(!activeMenu_) { return false; }
return ActiveMenu->IsHorizontalScroll(); return activeMenu_->horizontalScroll;
} }
void Page::PageScroll(ScrollDirection direction) void Page::pageScroll(ScrollDirection direction)
{ {
if(ActiveMenu) if(activeMenu_)
{ {
if(direction == ScrollDirectionForward) if(direction == ScrollDirectionForward)
{ {
ActiveMenu->PageDown(); activeMenu_->pageDown();
} }
if(direction == ScrollDirectionBack) if(direction == ScrollDirectionBack)
{ {
ActiveMenu->PageUp(); activeMenu_->pageUp();
} }
} }
} }
void Page::LetterScroll(ScrollDirection direction) void Page::letterScroll(ScrollDirection direction)
{ {
if(ActiveMenu) if(activeMenu_)
{ {
if(direction == ScrollDirectionForward) if(direction == ScrollDirectionForward)
{ {
ActiveMenu->LetterDown(); activeMenu_->letterDown();
} }
if(direction == ScrollDirectionBack) if(direction == ScrollDirectionBack)
{ {
ActiveMenu->LetterUp(); activeMenu_->letterUp();
} }
} }
} }
bool Page::PushCollection(CollectionInfo *collection) bool Page::pushCollection(CollectionInfo *collection)
{ {
Collections.push_back(collection); collections_.push_back(collection);
std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::BuildCollectionItems(collection->GetItems()); std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::buildCollectionItems(&collection->items);
int menuExitIndex = -1; int menuExitIndex = -1;
int menuEnterIndex = -1; int menuEnterIndex = -1;
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->TriggerMenuExitEvent(); activeMenu_->triggerMenuExitEvent();
} }
if(MenuDepth > 0) if(menuDepth_ > 0)
{ {
menuExitIndex = MenuDepth - 1; menuExitIndex = menuDepth_ - 1;
} }
if(Menus.size() >= MenuDepth && ActiveMenu) if(menus_.size() >= menuDepth_ && activeMenu_)
{ {
ScrollingList *newList = new ScrollingList(*ActiveMenu); ScrollingList *newList = new ScrollingList(*activeMenu_);
newList->ForceIdle(); newList->forceIdle();
PushMenu(newList); pushMenu(newList);
} }
ActiveMenu = Menus[MenuDepth]; activeMenu_ = menus_[menuDepth_];
ActiveMenu->SetCollectionName(collection->GetName()); activeMenu_->collectionName = collection->name;
ActiveMenu->DestroyItems(); activeMenu_->destroyItems();
ActiveMenu->SetItems(sprites); activeMenu_->setItems(sprites);
ActiveMenu->TriggerMenuEnterEvent(); activeMenu_->triggerMenuEnterEvent();
if(MenuDepth < Menus.size()) if(menuDepth_ < menus_.size())
{ {
menuEnterIndex = MenuDepth; menuEnterIndex = menuDepth_;
MenuDepth++; menuDepth_++;
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->SetCollectionName(collection->GetName()); (*it)->collectionName = collection->name;
if(menuEnterIndex >= 0) if(menuEnterIndex >= 0)
{ {
(*it)->TriggerMenuEnterEvent(menuEnterIndex); (*it)->triggerMenuEnterEvent(menuEnterIndex);
} }
if(menuExitIndex >= 0) if(menuExitIndex >= 0)
{ {
(*it)->TriggerMenuExitEvent(menuExitIndex); (*it)->triggerMenuExitEvent(menuExitIndex);
} }
} }
} }
@@ -465,51 +465,51 @@ bool Page::PushCollection(CollectionInfo *collection)
return true; return true;
} }
bool Page::PopCollection() bool Page::popCollection()
{ {
int menuExitIndex = -1; int menuExitIndex = -1;
int menuEnterIndex = -1; int menuEnterIndex = -1;
CollectionInfo *collection = NULL; CollectionInfo *collection = NULL;
if(MenuDepth <= 1) if(menuDepth_ <= 1)
{ {
return false; return false;
} }
if(Collections.size() <= 1) if(collections_.size() <= 1)
{ {
return false; return false;
} }
Collections.pop_back(); collections_.pop_back();
collection = Collections.back(); collection = collections_.back();
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->TriggerMenuExitEvent(); activeMenu_->triggerMenuExitEvent();
} }
MenuDepth--; menuDepth_--;
menuExitIndex = MenuDepth; menuExitIndex = menuDepth_;
menuEnterIndex = menuExitIndex - 1; menuEnterIndex = menuExitIndex - 1;
ActiveMenu = Menus[MenuDepth - 1]; activeMenu_ = menus_[menuDepth_ - 1];
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->TriggerMenuEnterEvent(); activeMenu_->triggerMenuEnterEvent();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->SetCollectionName(collection->GetName()); (*it)->collectionName = collection->name;
if(menuEnterIndex >= 0) if(menuEnterIndex >= 0)
{ {
(*it)->TriggerMenuEnterEvent(menuEnterIndex); (*it)->triggerMenuEnterEvent(menuEnterIndex);
} }
if(menuExitIndex >= 0) if(menuExitIndex >= 0)
{ {
(*it)->TriggerMenuExitEvent(menuExitIndex); (*it)->triggerMenuExitEvent(menuExitIndex);
} }
} }
} }
@@ -518,141 +518,143 @@ bool Page::PopCollection()
} }
void Page::Update(float dt) void Page::update(float dt)
{ {
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->Update(dt); menu->update(dt);
} }
if(SelectedItemChanged && !ScrollActive) if(selectedItemChanged_ && !scrollActive_)
{ {
Highlight(); highlight();
SelectedItemChanged = false; selectedItemChanged_ = false;
} }
if(TextStatusComponent) if(textStatusComponent_)
{ {
TextStatusComponent->SetText(Config.GetStatus()); std::string status;
config_.setProperty("status", status);
textStatusComponent_->setText(status);
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->Update(dt); (*it)->update(dt);
} }
} }
} }
void Page::Draw() void Page::draw()
{ {
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->Draw(); (*it)->draw();
} }
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->Draw(i); menu->draw(i);
} }
} }
} }
std::string Page::GetCollectionName() std::string Page::getCollectionName()
{ {
CollectionInfo *info = Collections.back(); CollectionInfo *info = collections_.back();
if(info) if(info)
{ {
return info->GetName(); return info->name;
} }
return ""; return "";
} }
void Page::FreeGraphicsMemory() void Page::freeGraphicsMemory()
{ {
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->FreeGraphicsMemory(); menu->freeGraphicsMemory();
} }
if(LoadSoundChunk) LoadSoundChunk->Free(); if(loadSoundChunk_) loadSoundChunk_->free();
if(UnloadSoundChunk) UnloadSoundChunk->Free(); if(unloadSoundChunk_) unloadSoundChunk_->free();
if(HighlightSoundChunk) HighlightSoundChunk->Free(); if(highlightSoundChunk_) highlightSoundChunk_->free();
if(SelectSoundChunk) SelectSoundChunk->Free(); if(selectSoundChunk_) selectSoundChunk_->free();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->FreeGraphicsMemory(); (*it)->freeGraphicsMemory();
} }
} }
} }
void Page::AllocateGraphicsMemory() void Page::allocateGraphicsMemory()
{ {
Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory"); Logger::write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory");
for(MenuVector_T::iterator it = Menus.begin(); it != Menus.end(); it++) for(MenuVector_T::iterator it = menus_.begin(); it != menus_.end(); it++)
{ {
ScrollingList *menu = *it; ScrollingList *menu = *it;
menu->AllocateGraphicsMemory(); menu->allocateGraphicsMemory();
} }
if(LoadSoundChunk) LoadSoundChunk->Allocate(); if(loadSoundChunk_) loadSoundChunk_->allocate();
if(UnloadSoundChunk) UnloadSoundChunk->Allocate(); if(unloadSoundChunk_) unloadSoundChunk_->allocate();
if(HighlightSoundChunk) HighlightSoundChunk->Allocate(); if(highlightSoundChunk_) highlightSoundChunk_->allocate();
if(SelectSoundChunk) SelectSoundChunk->Allocate(); if(selectSoundChunk_) selectSoundChunk_->allocate();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->AllocateGraphicsMemory(); (*it)->allocateGraphicsMemory();
} }
} }
Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete"); Logger::write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete");
} }
void Page::LaunchEnter() void Page::launchEnter()
{ {
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->LaunchEnter(); activeMenu_->launchEnter();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->LaunchEnter(); (*it)->launchEnter();
} }
} }
} }
void Page::LaunchExit() void Page::launchExit()
{ {
if(ActiveMenu) if(activeMenu_)
{ {
ActiveMenu->LaunchExit(); activeMenu_->launchExit();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->LaunchExit(); (*it)->launchExit();
} }
} }
} }

View File

@@ -43,68 +43,68 @@ public:
Page(Configuration &c); Page(Configuration &c);
virtual ~Page(); virtual ~Page();
virtual void OnNewItemSelected(Item *); virtual void onNewItemSelected(Item *);
bool PushCollection(CollectionInfo *collection); bool pushCollection(CollectionInfo *collection);
bool PopCollection(); bool popCollection();
void PushMenu(ScrollingList *s); void pushMenu(ScrollingList *s);
bool IsMenusFull(); bool isMenusFull();
void SetLoadSound(Sound *chunk); void setLoadSound(Sound *chunk);
void SetUnloadSound(Sound *chunk); void setUnloadSound(Sound *chunk);
void SetHighlightSound(Sound *chunk); void setHighlightSound(Sound *chunk);
void SetSelectSound(Sound *chunk); void setSelectSound(Sound *chunk);
bool AddComponent(Component *c); bool addComponent(Component *c);
void PageScroll(ScrollDirection direction); void pageScroll(ScrollDirection direction);
void LetterScroll(ScrollDirection direction); void letterScroll(ScrollDirection direction);
void Start(); void start();
void StartComponents(); void startComponents();
void Stop(); void stop();
void SetScrolling(ScrollDirection direction); void setScrolling(ScrollDirection direction);
bool IsHorizontalScroll(); bool isHorizontalScroll();
unsigned int GetMenuDepth(); unsigned int getMenuDepth();
Item *GetSelectedItem(); Item *getSelectedItem();
void RemoveSelectedItem(); void removeSelectedItem();
void SetScrollOffsetIndex(unsigned int i); void setScrollOffsetIndex(unsigned int i);
unsigned int GetScrollOffsetIndex(); unsigned int getScrollOffsetIndex();
bool IsIdle(); bool isIdle();
bool IsMenuIdle(); bool isMenuIdle();
bool IsHidden(); bool isHidden();
void SetStatusTextComponent(Text *t); void setStatusTextComponent(Text *t);
void Update(float dt); void update(float dt);
void Draw(); void draw();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void LaunchEnter(); void launchEnter();
void LaunchExit(); void launchExit();
std::string GetCollectionName(); std::string getCollectionName();
void SetMinShowTime(float value); void setMinShowTime(float value);
float GetMinShowTime(); float getMinShowTime();
private: private:
void Highlight(); void highlight();
std::string CollectionName; std::string collectionName_;
Configuration &Config; Configuration &config_;
typedef std::vector<ScrollingList *> MenuVector_T; typedef std::vector<ScrollingList *> MenuVector_T;
typedef std::vector<CollectionInfo *> CollectionInfo_T; typedef std::vector<CollectionInfo *> CollectionInfo_T;
ScrollingList *ActiveMenu; ScrollingList *activeMenu_;
unsigned int MenuDepth; unsigned int menuDepth_;
MenuVector_T Menus; MenuVector_T menus_;
CollectionInfo_T Collections; CollectionInfo_T collections_;
static const unsigned int NUM_LAYERS = 8; static const unsigned int NUM_LAYERS = 8;
std::vector<Component *> LayerComponents[NUM_LAYERS]; std::vector<Component *> LayerComponents[NUM_LAYERS];
std::vector<Item *> *Items; std::vector<Item *> *items_;
bool ScrollActive; bool scrollActive_;
Item *SelectedItem; Item *selectedItem_;
Text *TextStatusComponent; Text *textStatusComponent_;
bool SelectedItemChanged; bool selectedItemChanged_;
Sound *LoadSoundChunk; Sound *loadSoundChunk_;
Sound *UnloadSoundChunk; Sound *unloadSoundChunk_;
Sound *HighlightSoundChunk; Sound *highlightSoundChunk_;
Sound *SelectSoundChunk; Sound *selectSoundChunk_;
float MinShowTime; float minShowTime_;
float ElapsedTime; float elapsedTime_;
}; };

View File

@@ -48,39 +48,39 @@ static const int MENU_CENTER = -4;
//todo: this file is starting to become a god class of building. Consider splitting into sub-builders //todo: this file is starting to become a god class of building. Consider splitting into sub-builders
PageBuilder::PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc) PageBuilder::PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc)
: LayoutKey(layoutKey) : layoutKey(layoutKey)
, LayoutPage(layoutPage) , layoutPage(layoutPage)
, Config(c) , config_(c)
, ScaleX(1) , scaleX_(1)
, ScaleY(1) , scaleY_(1)
, ScreenHeight(0) , screenHeight_(0)
, ScreenWidth(0) , screenWidth_(0)
, FontSize(24) , fontSize_(24)
, FC(fc) , fontCache_(fc)
{ {
ScreenWidth = SDL::GetWindowWidth(); screenWidth_ = SDL::getWindowWidth();
ScreenHeight = SDL::GetWindowHeight(); screenHeight_ = SDL::getWindowHeight();
FontColor.a = 255; fontColor_.a = 255;
FontColor.r = 0; fontColor_.r = 0;
FontColor.g = 0; fontColor_.g = 0;
FontColor.b = 0; fontColor_.b = 0;
} }
PageBuilder::~PageBuilder() PageBuilder::~PageBuilder()
{ {
} }
Page *PageBuilder::BuildPage() Page *PageBuilder::buildPage()
{ {
Page *page = NULL; Page *page = NULL;
std::string layoutFile; std::string layoutFile;
std::string layoutName = LayoutKey; std::string layoutName = layoutKey;
LayoutPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "layouts", layoutName); layoutPath = Utils::combinePath(Configuration::absolutePath, "layouts", layoutName);
layoutFile = Utils::CombinePath(LayoutPath, LayoutPage + ".xml"); layoutFile = Utils::combinePath(layoutPath, layoutPage + ".xml");
Logger::Write(Logger::ZONE_INFO, "Layout", "Initializing " + layoutFile); Logger::write(Logger::ZONE_INFO, "Layout", "Initializing " + layoutFile);
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
std::ifstream file(layoutFile.c_str()); std::ifstream file(layoutFile.c_str());
@@ -88,7 +88,7 @@ Page *PageBuilder::BuildPage()
if(!file.good()) if(!file.good())
{ {
Logger::Write(Logger::ZONE_INFO, "Layout", "could not find layout file: " + layoutFile); Logger::write(Logger::ZONE_INFO, "Layout", "could not find layout file: " + layoutFile);
return NULL; return NULL;
} }
@@ -103,7 +103,7 @@ Page *PageBuilder::BuildPage()
if(!root) if(!root)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing <layout> tag"); Logger::write(Logger::ZONE_ERROR, "Layout", "Missing <layout> tag");
return NULL; return NULL;
} }
else else
@@ -119,13 +119,13 @@ Page *PageBuilder::BuildPage()
int layoutWidth; int layoutWidth;
if(!layoutWidthXml || !layoutHeightXml) if(!layoutWidthXml || !layoutHeightXml)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "<layout> tag must specify a width and height"); Logger::write(Logger::ZONE_ERROR, "Layout", "<layout> tag must specify a width and height");
return NULL; return NULL;
} }
if(fontXml) if(fontXml)
{ {
FontName = Config.ConvertToAbsolutePath( fontName_ = config_.convertToAbsolutePath(
Utils::CombinePath(Config.GetAbsolutePath(), "layouts", LayoutKey, ""), Utils::combinePath(config_.absolutePath, "layouts", layoutKey, ""),
fontXml->value()); fontXml->value());
} }
@@ -136,39 +136,39 @@ Page *PageBuilder::BuildPage()
ss << std::hex << fontColorXml->value(); ss << std::hex << fontColorXml->value();
ss >> intColor; ss >> intColor;
FontColor.b = intColor & 0xFF; fontColor_.b = intColor & 0xFF;
intColor >>= 8; intColor >>= 8;
FontColor.g = intColor & 0xFF; fontColor_.g = intColor & 0xFF;
intColor >>= 8; intColor >>= 8;
FontColor.r = intColor & 0xFF; fontColor_.r = intColor & 0xFF;
} }
if(fontSizeXml) if(fontSizeXml)
{ {
FontSize = Utils::ConvertInt(fontSizeXml->value()); fontSize_ = Utils::convertInt(fontSizeXml->value());
} }
layoutWidth = Utils::ConvertInt(layoutWidthXml->value()); layoutWidth = Utils::convertInt(layoutWidthXml->value());
layoutHeight = Utils::ConvertInt(layoutHeightXml->value()); layoutHeight = Utils::convertInt(layoutHeightXml->value());
if(layoutWidth == 0 || layoutHeight == 0) if(layoutWidth == 0 || layoutHeight == 0)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Layout width and height cannot be set to 0"); Logger::write(Logger::ZONE_ERROR, "Layout", "Layout width and height cannot be set to 0");
return NULL; return NULL;
} }
ScaleX = (float)ScreenWidth / (float)layoutWidth; scaleX_ = (float)screenWidth_ / (float)layoutWidth;
ScaleY = (float)ScreenHeight / (float)layoutHeight; scaleY_ = (float)screenHeight_ / (float)layoutHeight;
std::stringstream ss; std::stringstream ss;
ss << layoutWidth << "x" << layoutHeight << " (scale " << ScaleX << "x" << ScaleY << ")"; ss << layoutWidth << "x" << layoutHeight << " (scale " << scaleX_ << "x" << scaleY_ << ")";
Logger::Write(Logger::ZONE_INFO, "Layout", "Layout resolution " + ss.str()); Logger::write(Logger::ZONE_INFO, "Layout", "Layout resolution " + ss.str());
page = new Page(Config); page = new Page(config_);
if(minShowTimeXml) if(minShowTimeXml)
{ {
page->SetMinShowTime(Utils::ConvertFloat(minShowTimeXml->value())); page->setMinShowTime(Utils::convertFloat(minShowTimeXml->value()));
} }
// load sounds // load sounds
@@ -176,10 +176,10 @@ Page *PageBuilder::BuildPage()
{ {
xml_attribute<> *src = sound->first_attribute("src"); xml_attribute<> *src = sound->first_attribute("src");
xml_attribute<> *type = sound->first_attribute("type"); xml_attribute<> *type = sound->first_attribute("type");
std::string file = Configuration::ConvertToAbsolutePath(LayoutPath, src->value()); std::string file = Configuration::convertToAbsolutePath(layoutPath, src->value());
if(!type) if(!type)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute");
} }
else else
{ {
@@ -188,28 +188,28 @@ Page *PageBuilder::BuildPage()
if(!soundType.compare("load")) if(!soundType.compare("load"))
{ {
page->SetLoadSound(sound); page->setLoadSound(sound);
} }
else if(!soundType.compare("unload")) else if(!soundType.compare("unload"))
{ {
page->SetUnloadSound(sound); page->setUnloadSound(sound);
} }
else if(!soundType.compare("highlight")) else if(!soundType.compare("highlight"))
{ {
page->SetHighlightSound(sound); page->setHighlightSound(sound);
} }
else if(!soundType.compare("select")) else if(!soundType.compare("select"))
{ {
page->SetSelectSound(sound); page->setSelectSound(sound);
} }
else else
{ {
Logger::Write(Logger::ZONE_WARNING, "Layout", "Unsupported sound effect type \"" + soundType + "\""); Logger::write(Logger::ZONE_WARNING, "Layout", "Unsupported sound effect type \"" + soundType + "\"");
} }
} }
} }
if(!BuildComponents(root, page)) if(!buildComponents(root, page))
{ {
delete page; delete page;
page = NULL; page = NULL;
@@ -225,21 +225,21 @@ Page *PageBuilder::BuildPage()
std::stringstream ss; std::stringstream ss;
ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what();
Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); Logger::write(Logger::ZONE_ERROR, "Layout", ss.str());
} }
catch(std::exception &e) catch(std::exception &e)
{ {
std::string what = e.what(); std::string what = e.what();
Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what); Logger::write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what);
} }
if(page) if(page)
{ {
Logger::Write(Logger::ZONE_INFO, "Layout", "Initialized"); Logger::write(Logger::ZONE_INFO, "Layout", "Initialized");
} }
else else
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not initialize layout (see previous messages for reason)"); Logger::write(Logger::ZONE_ERROR, "Layout", "Could not initialize layout (see previous messages for reason)");
} }
return page; return page;
@@ -247,7 +247,7 @@ Page *PageBuilder::BuildPage()
float PageBuilder::GetHorizontalAlignment(xml_attribute<> *attribute, float valueIfNull) float PageBuilder::getHorizontalAlignment(xml_attribute<> *attribute, float valueIfNull)
{ {
float value; float value;
std::string str; std::string str;
@@ -266,22 +266,22 @@ float PageBuilder::GetHorizontalAlignment(xml_attribute<> *attribute, float valu
} }
else if(!str.compare("center")) else if(!str.compare("center"))
{ {
value = static_cast<float>(ScreenWidth) / 2; value = static_cast<float>(screenWidth_) / 2;
} }
else if(!str.compare("right") || !str.compare("stretch")) else if(!str.compare("right") || !str.compare("stretch"))
{ {
value = static_cast<float>(ScreenWidth); value = static_cast<float>(screenWidth_);
} }
else else
{ {
value = Utils::ConvertFloat(str) * ScaleX; value = Utils::convertFloat(str) * scaleX_;
} }
} }
return value; return value;
} }
float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueIfNull) float PageBuilder::getVerticalAlignment(xml_attribute<> *attribute, float valueIfNull)
{ {
float value; float value;
std::string str; std::string str;
@@ -299,15 +299,15 @@ float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueI
} }
else if(!str.compare("center")) else if(!str.compare("center"))
{ {
value = static_cast<float>(ScreenHeight / 2); value = static_cast<float>(screenHeight_ / 2);
} }
else if(!str.compare("bottom") || !str.compare("stretch")) else if(!str.compare("bottom") || !str.compare("stretch"))
{ {
value = static_cast<float>(ScreenHeight); value = static_cast<float>(screenHeight_);
} }
else else
{ {
value = Utils::ConvertFloat(str) * ScaleY; value = Utils::convertFloat(str) * scaleY_;
} }
} }
return value; return value;
@@ -316,21 +316,20 @@ float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueI
bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page) bool PageBuilder::buildComponents(xml_node<> *layout, Page *page)
{ {
for(xml_node<> *componentXml = layout->first_node("menu"); componentXml; componentXml = componentXml->next_sibling("menu")) for(xml_node<> *componentXml = layout->first_node("menu"); componentXml; componentXml = componentXml->next_sibling("menu"))
{ {
ScrollingList *scrollingList = BuildMenu(componentXml); ScrollingList *scrollingList = buildMenu(componentXml);
page->PushMenu(scrollingList); page->pushMenu(scrollingList);
} }
for(xml_node<> *componentXml = layout->first_node("container"); componentXml; componentXml = componentXml->next_sibling("container")) for(xml_node<> *componentXml = layout->first_node("container"); componentXml; componentXml = componentXml->next_sibling("container"))
{ {
Container *c = new Container(); Container *c = new Container();
ViewInfo *v = c->GetBaseViewInfo(); buildViewInfo(componentXml, c->baseViewInfo);
BuildViewInfo(componentXml, v); loadTweens(c, componentXml);
LoadTweens(c, componentXml); page->addComponent(c);
page->AddComponent(c);
} }
@@ -340,18 +339,17 @@ bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page)
if (!src) if (!src)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); Logger::write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file");
} }
else else
{ {
std::string imagePath; std::string imagePath;
imagePath = Utils::CombinePath(Configuration::ConvertToAbsolutePath(LayoutPath, imagePath), std::string(src->value())); imagePath = Utils::combinePath(Configuration::convertToAbsolutePath(layoutPath, imagePath), std::string(src->value()));
Image *c = new Image(imagePath, ScaleX, ScaleY); Image *c = new Image(imagePath, scaleX_, scaleY_);
ViewInfo *v = c->GetBaseViewInfo(); buildViewInfo(componentXml, c->baseViewInfo);
BuildViewInfo(componentXml, v); loadTweens(c, componentXml);
LoadTweens(c, componentXml); page->addComponent(c);
page->AddComponent(c);
} }
} }
@@ -362,43 +360,41 @@ bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page)
if (!value) if (!value)
{ {
Logger::Write(Logger::ZONE_WARNING, "Layout", "Text component in layout does not specify a value"); Logger::write(Logger::ZONE_WARNING, "Layout", "Text component in layout does not specify a value");
} }
else else
{ {
Font *font = AddFont(componentXml, NULL); Font *font = addFont(componentXml, NULL);
Text *c = new Text(value->value(), font, ScaleX, ScaleY); Text *c = new Text(value->value(), font, scaleX_, scaleY_);
ViewInfo *v = c->GetBaseViewInfo();
BuildViewInfo(componentXml, v); buildViewInfo(componentXml, c->baseViewInfo);
LoadTweens(c, componentXml); loadTweens(c, componentXml);
page->AddComponent(c); page->addComponent(c);
} }
} }
for(xml_node<> *componentXml = layout->first_node("statusText"); componentXml; componentXml = componentXml->next_sibling("statusText")) for(xml_node<> *componentXml = layout->first_node("statusText"); componentXml; componentXml = componentXml->next_sibling("statusText"))
{ {
Font *font = AddFont(componentXml, NULL); Font *font = addFont(componentXml, NULL);
Text *c = new Text("", font, ScaleX, ScaleY); Text *c = new Text("", font, scaleX_, scaleY_);
ViewInfo *v = c->GetBaseViewInfo();
BuildViewInfo(componentXml, v); buildViewInfo(componentXml, c->baseViewInfo);
LoadTweens(c, componentXml); loadTweens(c, componentXml);
page->AddComponent(c); page->addComponent(c);
page->SetStatusTextComponent(c); page->setStatusTextComponent(c);
} }
LoadReloadableImages(layout, "reloadableImage", page); loadReloadableImages(layout, "reloadableImage", page);
LoadReloadableImages(layout, "reloadableVideo", page); loadReloadableImages(layout, "reloadableVideo", page);
LoadReloadableImages(layout, "reloadableText", page); loadReloadableImages(layout, "reloadableText", page);
return true; return true;
} }
void PageBuilder::LoadReloadableImages(xml_node<> *layout, std::string tagName, Page *page) void PageBuilder::loadReloadableImages(xml_node<> *layout, std::string tagName, Page *page)
{ {
for(xml_node<> *componentXml = layout->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str())) for(xml_node<> *componentXml = layout->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str()))
@@ -417,11 +413,11 @@ void PageBuilder::LoadReloadableImages(xml_node<> *layout, std::string tagName,
if(!type && tagName == "reloadableVideo") if(!type && tagName == "reloadableVideo")
{ {
Logger::Write(Logger::ZONE_WARNING, "Layout", "<reloadableImage> component in layout does not specify an imageType for when the video does not exist"); Logger::write(Logger::ZONE_WARNING, "Layout", "<reloadableImage> component in layout does not specify an imageType for when the video does not exist");
} }
if(!type && (tagName == "reloadableImage" || tagName == "reloadableText")) if(!type && (tagName == "reloadableImage" || tagName == "reloadableText"))
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); Logger::write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file");
} }
@@ -441,36 +437,36 @@ void PageBuilder::LoadReloadableImages(xml_node<> *layout, std::string tagName,
{ {
if(type) if(type)
{ {
Font *font = AddFont(componentXml, NULL); Font *font = addFont(componentXml, NULL);
c = new ReloadableText(type->value(), font, LayoutKey, ScaleX, ScaleY); c = new ReloadableText(type->value(), font, layoutKey, scaleX_, scaleY_);
} }
} }
else else
{ {
Font *font = AddFont(componentXml, NULL); Font *font = addFont(componentXml, NULL);
c = new ReloadableMedia(Config, systemMode, type->value(), (tagName == "reloadableVideo"), font, ScaleX, ScaleY); c = new ReloadableMedia(config_, systemMode, type->value(), (tagName == "reloadableVideo"), font, scaleX_, scaleY_);
xml_attribute<> *textFallback = componentXml->first_attribute("textFallback"); xml_attribute<> *textFallback = componentXml->first_attribute("textFallback");
if(textFallback && Utils::ToLower(textFallback->value()) == "true") if(textFallback && Utils::toLower(textFallback->value()) == "true")
{ {
static_cast<ReloadableMedia *>(c)->EnableTextFallback(true); static_cast<ReloadableMedia *>(c)->enableTextFallback_(true);
} }
else else
{ {
static_cast<ReloadableMedia *>(c)->EnableTextFallback(false); static_cast<ReloadableMedia *>(c)->enableTextFallback_(false);
} }
} }
if(c) if(c)
{ {
LoadTweens(c, componentXml); loadTweens(c, componentXml);
page->AddComponent(c); page->addComponent(c);
} }
} }
} }
Font *PageBuilder::AddFont(xml_node<> *component, xml_node<> *defaults) Font *PageBuilder::addFont(xml_node<> *component, xml_node<> *defaults)
{ {
xml_attribute<> *fontXml = component->first_attribute("font"); xml_attribute<> *fontXml = component->first_attribute("font");
xml_attribute<> *fontColorXml = component->first_attribute("fontColor"); xml_attribute<> *fontColorXml = component->first_attribute("fontColor");
@@ -496,17 +492,17 @@ Font *PageBuilder::AddFont(xml_node<> *component, xml_node<> *defaults)
// use layout defaults unless overridden // use layout defaults unless overridden
std::string fontName = FontName; std::string fontName = fontName_;
SDL_Color fontColor = FontColor; SDL_Color fontColor = fontColor_;
int fontSize = FontSize; int fontSize = fontSize_;
if(fontXml) if(fontXml)
{ {
fontName = Config.ConvertToAbsolutePath( fontName = config_.convertToAbsolutePath(
Utils::CombinePath(Config.GetAbsolutePath(), "layouts", LayoutKey,""), Utils::combinePath(config_.absolutePath, "layouts", layoutKey,""),
fontXml->value()); fontXml->value());
Logger::Write(Logger::ZONE_DEBUG, "Layout", "loading font " + fontName ); Logger::write(Logger::ZONE_DEBUG, "Layout", "loading font " + fontName );
} }
if(fontColorXml) if(fontColorXml)
{ {
@@ -524,53 +520,51 @@ Font *PageBuilder::AddFont(xml_node<> *component, xml_node<> *defaults)
if(fontSizeXml) if(fontSizeXml)
{ {
fontSize = Utils::ConvertInt(fontSizeXml->value()); fontSize = Utils::convertInt(fontSizeXml->value());
} }
FC->LoadFont(fontName, fontSize, fontColor); fontCache_->loadFont(fontName, fontSize, fontColor);
return FC->GetFont(fontName, fontSize, fontColor); return fontCache_->getFont(fontName, fontSize, fontColor);
} }
void PageBuilder::LoadTweens(Component *c, xml_node<> *componentXml) void PageBuilder::loadTweens(Component *c, xml_node<> *componentXml)
{ {
ViewInfo *v = c->GetBaseViewInfo(); buildViewInfo(componentXml, c->baseViewInfo);
BuildViewInfo(componentXml, v); c->setTweens(createTweenInstance(componentXml));
c->SetTweens(CreateTweenInstance(componentXml));
} }
AnimationEvents *PageBuilder::CreateTweenInstance(xml_node<> *componentXml) AnimationEvents *PageBuilder::createTweenInstance(xml_node<> *componentXml)
{ {
AnimationEvents *tweens = new AnimationEvents(); AnimationEvents *tweens = new AnimationEvents();
BuildTweenSet(tweens, componentXml, "onEnter", "enter"); buildTweenSet(tweens, componentXml, "onEnter", "enter");
BuildTweenSet(tweens, componentXml, "onExit", "exit"); buildTweenSet(tweens, componentXml, "onExit", "exit");
BuildTweenSet(tweens, componentXml, "onIdle", "idle"); buildTweenSet(tweens, componentXml, "onIdle", "idle");
BuildTweenSet(tweens, componentXml, "onHighlightEnter", "highlightEnter"); buildTweenSet(tweens, componentXml, "onHighlightEnter", "highlightEnter");
BuildTweenSet(tweens, componentXml, "onHighlightExit", "highlightExit"); buildTweenSet(tweens, componentXml, "onHighlightExit", "highlightExit");
BuildTweenSet(tweens, componentXml, "onMenuEnter", "menuEnter"); buildTweenSet(tweens, componentXml, "onMenuEnter", "menuEnter");
BuildTweenSet(tweens, componentXml, "onMenuExit", "menuExit"); buildTweenSet(tweens, componentXml, "onMenuExit", "menuExit");
return tweens; return tweens;
} }
void PageBuilder::BuildTweenSet(AnimationEvents *tweens, xml_node<> *componentXml, std::string tagName, std::string tweenName) void PageBuilder::buildTweenSet(AnimationEvents *tweens, xml_node<> *componentXml, std::string tagName, std::string tweenName)
{ {
for(componentXml = componentXml->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str())) for(componentXml = componentXml->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str()))
{ {
xml_attribute<> *indexXml = componentXml->first_attribute("menuIndex"); xml_attribute<> *indexXml = componentXml->first_attribute("menuIndex");
int index = (indexXml) ? Utils::ConvertInt(indexXml->value()) : -1; int index = (indexXml) ? Utils::convertInt(indexXml->value()) : -1;
Animation *animation = new Animation(); Animation *animation = new Animation();
GetTweenSet(componentXml, animation); getTweenSet(componentXml, animation);
tweens->SetAnimation(tweenName, index, animation); tweens->setAnimation(tweenName, index, animation);
} }
} }
ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml) ScrollingList * PageBuilder::buildMenu(xml_node<> *menuXml)
{ {
ScrollingList *menu = NULL; ScrollingList *menu = NULL;
std::string menuType = "vertical"; std::string menuType = "vertical";
@@ -591,7 +585,7 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
// ensure <menu> has an <itemDefaults> tag // ensure <menu> has an <itemDefaults> tag
if(!itemDefaults) if(!itemDefaults)
{ {
Logger::Write(Logger::ZONE_WARNING, "Layout", "Menu tag is missing <itemDefaults> tag."); Logger::write(Logger::ZONE_WARNING, "Layout", "Menu tag is missing <itemDefaults> tag.");
} }
if(imageTypeXml) if(imageTypeXml)
@@ -600,18 +594,18 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
} }
// on default, text will be rendered to the menu. Preload it into cache. // on default, text will be rendered to the menu. Preload it into cache.
Font *font = AddFont(itemDefaults, NULL); Font *font = addFont(itemDefaults, NULL);
menu = new ScrollingList(Config, ScaleX, ScaleY, font, LayoutKey, imageType); menu = new ScrollingList(config_, scaleX_, scaleY_, font, layoutKey, imageType);
if(scrollTimeXml) if(scrollTimeXml)
{ {
menu->SetStartScrollTime(Utils::ConvertFloat(scrollTimeXml->value())); menu->setStartScrollTime(Utils::convertFloat(scrollTimeXml->value()));
} }
if(scrollAccelerationXml) if(scrollAccelerationXml)
{ {
menu->SetScrollAcceleration(Utils::ConvertFloat(scrollAccelerationXml->value())); menu->setScrollAcceleration(Utils::convertFloat(scrollAccelerationXml->value()));
} }
if(scrollOrientationXml) if(scrollOrientationXml)
@@ -619,29 +613,28 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
std::string scrollOrientation = scrollOrientationXml->value(); std::string scrollOrientation = scrollOrientationXml->value();
if(scrollOrientation == "horizontal") if(scrollOrientation == "horizontal")
{ {
menu->SetScrollOrientation(true); menu->horizontalScroll = true;
} }
} }
ViewInfo *v = menu->GetBaseViewInfo(); buildViewInfo(menuXml, menu->baseViewInfo);
BuildViewInfo(menuXml, v);
if(menuType == "custom") if(menuType == "custom")
{ {
BuildCustomMenu(menu, menuXml, itemDefaults); buildCustomMenu(menu, menuXml, itemDefaults);
} }
else else
{ {
BuildVerticalMenu(menu, menuXml, itemDefaults); buildVerticalMenu(menu, menuXml, itemDefaults);
} }
LoadTweens(menu, menuXml); loadTweens(menu, menuXml);
return menu; return menu;
} }
void PageBuilder::BuildCustomMenu(ScrollingList *menu, xml_node<> *menuXml, xml_node<> *itemDefaults) void PageBuilder::buildCustomMenu(ScrollingList *menu, xml_node<> *menuXml, xml_node<> *itemDefaults)
{ {
std::vector<ViewInfo *> *points = new std::vector<ViewInfo *>(); std::vector<ViewInfo *> *points = new std::vector<ViewInfo *>();
std::vector<AnimationEvents *> *tweenPoints = new std::vector<AnimationEvents *>(); std::vector<AnimationEvents *> *tweenPoints = new std::vector<AnimationEvents *>();
@@ -651,24 +644,24 @@ void PageBuilder::BuildCustomMenu(ScrollingList *menu, xml_node<> *menuXml, xml_
for(xml_node<> *componentXml = menuXml->first_node("item"); componentXml; componentXml = componentXml->next_sibling("item")) for(xml_node<> *componentXml = menuXml->first_node("item"); componentXml; componentXml = componentXml->next_sibling("item"))
{ {
ViewInfo *viewInfo = new ViewInfo(); ViewInfo *viewInfo = new ViewInfo();
BuildViewInfo(componentXml, viewInfo, itemDefaults); buildViewInfo(componentXml, *viewInfo, itemDefaults);
points->push_back(viewInfo); points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(componentXml)); tweenPoints->push_back(createTweenInstance(componentXml));
xml_attribute<> *selected = componentXml->first_attribute("selected"); xml_attribute<> *selected = componentXml->first_attribute("selected");
if(selected) if(selected)
{ {
menu->SetSelectedIndex(i); menu->setSelectedIndex(i);
} }
i++; i++;
} }
menu->SetPoints(points, tweenPoints); menu->setPoints(points, tweenPoints);
} }
void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xml_node<> *itemDefaults) void PageBuilder::buildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xml_node<> *itemDefaults)
{ {
std::vector<ViewInfo *> *points = new std::vector<ViewInfo *>(); std::vector<ViewInfo *> *points = new std::vector<ViewInfo *>();
std::vector<AnimationEvents *> *tweenPoints = new std::vector<AnimationEvents *>(); std::vector<AnimationEvents *> *tweenPoints = new std::vector<AnimationEvents *>();
@@ -685,7 +678,7 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
if(xmlIndex) if(xmlIndex)
{ {
int itemIndex = ParseMenuPosition(xmlIndex->value()); int itemIndex = parseMenuPosition(xmlIndex->value());
overrideItems[itemIndex] = componentXml; overrideItems[itemIndex] = componentXml;
// check to see if the item specified is the selected index // check to see if the item specified is the selected index
@@ -708,10 +701,10 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
if(overrideItems.find(MENU_START) != overrideItems.end()) if(overrideItems.find(MENU_START) != overrideItems.end())
{ {
xml_node<> *component = overrideItems[MENU_START]; xml_node<> *component = overrideItems[MENU_START];
ViewInfo *viewInfo = CreateMenuItemInfo(component, itemDefaults, menu->GetBaseViewInfo()->GetY() + height); ViewInfo *viewInfo = createMenuItemInfo(component, itemDefaults, menu->baseViewInfo.Y + height);
points->push_back(viewInfo); points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(component)); tweenPoints->push_back(createTweenInstance(component));
height += viewInfo->GetHeight(); height += viewInfo->Height;
// increment the selected index to account for the new "invisible" menu item // increment the selected index to account for the new "invisible" menu item
selectedIndex++; selectedIndex++;
@@ -728,12 +721,12 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
} }
// calculate the total height of our menu items if we can load any additional items // calculate the total height of our menu items if we can load any additional items
BuildViewInfo(component, viewInfo, itemDefaults); buildViewInfo(component, *viewInfo, itemDefaults);
xml_attribute<> *itemSpacingXml = component->first_attribute("spacing"); xml_attribute<> *itemSpacingXml = component->first_attribute("spacing");
int itemSpacing = itemSpacingXml ? Utils::ConvertInt(itemSpacingXml->value()) : 0; int itemSpacing = itemSpacingXml ? Utils::convertInt(itemSpacingXml->value()) : 0;
float nextHeight = height + viewInfo->GetHeight() + itemSpacing; float nextHeight = height + viewInfo->Height + itemSpacing;
if(nextHeight >= menu->GetBaseViewInfo()->GetHeight()) if(nextHeight >= menu->baseViewInfo.Height)
{ {
end = true; end = true;
} }
@@ -743,15 +736,15 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
{ {
component = overrideItems[MENU_LAST]; component = overrideItems[MENU_LAST];
BuildViewInfo(component, viewInfo, itemDefaults); buildViewInfo(component, *viewInfo, itemDefaults);
xml_attribute<> *itemSpacingXml = component->first_attribute("spacing"); xml_attribute<> *itemSpacingXml = component->first_attribute("spacing");
int itemSpacing = itemSpacingXml ? Utils::ConvertInt(itemSpacingXml->value()) : 0; int itemSpacing = itemSpacingXml ? Utils::convertInt(itemSpacingXml->value()) : 0;
nextHeight = height + viewInfo->GetHeight() + itemSpacing; nextHeight = height + viewInfo->Height + itemSpacing;
} }
viewInfo->SetY(menu->GetBaseViewInfo()->GetY() + (float)height); viewInfo->Y = menu->baseViewInfo.Y + (float)height;
points->push_back(viewInfo); points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(component)); tweenPoints->push_back(createTweenInstance(component));
index++; index++;
height = nextHeight; height = nextHeight;
} }
@@ -760,9 +753,9 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
if(overrideItems.find(MENU_END) != overrideItems.end()) if(overrideItems.find(MENU_END) != overrideItems.end())
{ {
xml_node<> *component = overrideItems[MENU_END]; xml_node<> *component = overrideItems[MENU_END];
ViewInfo *viewInfo = CreateMenuItemInfo(component, itemDefaults, menu->GetBaseViewInfo()->GetY() + height); ViewInfo *viewInfo = createMenuItemInfo(component, itemDefaults, menu->baseViewInfo.Y + height);
points->push_back(viewInfo); points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(component)); tweenPoints->push_back(createTweenInstance(component));
} }
if(selectedIndex >= ((int)points->size())) if(selectedIndex >= ((int)points->size()))
@@ -774,25 +767,25 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
<< " although there are only " << points->size() << " although there are only " << points->size()
<< " menu points that can be displayed"; << " menu points that can be displayed";
Logger::Write(Logger::ZONE_ERROR, "Layout", "Design error! \"duration\" attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Design error! \"duration\" attribute");
selectedIndex = 0; selectedIndex = 0;
} }
menu->SetSelectedIndex(selectedIndex); menu->setSelectedIndex(selectedIndex);
menu->SetPoints(points, tweenPoints); menu->setPoints(points, tweenPoints);
} }
ViewInfo *PageBuilder::CreateMenuItemInfo(xml_node<> *component, xml_node<> *defaults, float y) ViewInfo *PageBuilder::createMenuItemInfo(xml_node<> *component, xml_node<> *defaults, float y)
{ {
ViewInfo *viewInfo = new ViewInfo(); ViewInfo *viewInfo = new ViewInfo();
BuildViewInfo(component, viewInfo, defaults); buildViewInfo(component, *viewInfo, defaults);
viewInfo->SetY(y); viewInfo->Y = y;
return viewInfo; return viewInfo;
} }
int PageBuilder::ParseMenuPosition(std::string strIndex) int PageBuilder::parseMenuPosition(std::string strIndex)
{ {
int index = MENU_FIRST; int index = MENU_FIRST;
@@ -814,12 +807,12 @@ int PageBuilder::ParseMenuPosition(std::string strIndex)
} }
else else
{ {
index = Utils::ConvertInt(strIndex); index = Utils::convertInt(strIndex);
} }
return index; return index;
} }
xml_attribute<> *PageBuilder::FindAttribute(xml_node<> *componentXml, std::string attribute, xml_node<> *defaultXml = NULL) xml_attribute<> *PageBuilder::findAttribute(xml_node<> *componentXml, std::string attribute, xml_node<> *defaultXml = NULL)
{ {
xml_attribute<> *attributeXml = componentXml->first_attribute(attribute.c_str()); xml_attribute<> *attributeXml = componentXml->first_attribute(attribute.c_str());
@@ -831,58 +824,58 @@ xml_attribute<> *PageBuilder::FindAttribute(xml_node<> *componentXml, std::strin
return attributeXml; return attributeXml;
} }
void PageBuilder::BuildViewInfo(xml_node<> *componentXml, ViewInfo *info, xml_node<> *defaultXml) void PageBuilder::buildViewInfo(xml_node<> *componentXml, ViewInfo &info, xml_node<> *defaultXml)
{ {
xml_attribute<> *x = FindAttribute(componentXml, "x", defaultXml); xml_attribute<> *x = findAttribute(componentXml, "x", defaultXml);
xml_attribute<> *y = FindAttribute(componentXml, "y", defaultXml); xml_attribute<> *y = findAttribute(componentXml, "y", defaultXml);
xml_attribute<> *xOffset = FindAttribute(componentXml, "xOffset", defaultXml); xml_attribute<> *xOffset = findAttribute(componentXml, "xOffset", defaultXml);
xml_attribute<> *yOffset = FindAttribute(componentXml, "yOffset", defaultXml); xml_attribute<> *yOffset = findAttribute(componentXml, "yOffset", defaultXml);
xml_attribute<> *xOrigin = FindAttribute(componentXml, "xOrigin", defaultXml); xml_attribute<> *xOrigin = findAttribute(componentXml, "xOrigin", defaultXml);
xml_attribute<> *yOrigin = FindAttribute(componentXml, "yOrigin", defaultXml); xml_attribute<> *yOrigin = findAttribute(componentXml, "yOrigin", defaultXml);
xml_attribute<> *height = FindAttribute(componentXml, "height", defaultXml); xml_attribute<> *height = findAttribute(componentXml, "height", defaultXml);
xml_attribute<> *width = FindAttribute(componentXml, "width", defaultXml); xml_attribute<> *width = findAttribute(componentXml, "width", defaultXml);
xml_attribute<> *fontSize = FindAttribute(componentXml, "fontSize", defaultXml); xml_attribute<> *fontSize = findAttribute(componentXml, "fontSize", defaultXml);
xml_attribute<> *minHeight = FindAttribute(componentXml, "minHeight", defaultXml); xml_attribute<> *minHeight = findAttribute(componentXml, "minHeight", defaultXml);
xml_attribute<> *minWidth = FindAttribute(componentXml, "minWidth", defaultXml); xml_attribute<> *minWidth = findAttribute(componentXml, "minWidth", defaultXml);
xml_attribute<> *maxHeight = FindAttribute(componentXml, "maxHeight", defaultXml); xml_attribute<> *maxHeight = findAttribute(componentXml, "maxHeight", defaultXml);
xml_attribute<> *maxWidth = FindAttribute(componentXml, "maxWidth", defaultXml); xml_attribute<> *maxWidth = findAttribute(componentXml, "maxWidth", defaultXml);
xml_attribute<> *alpha = FindAttribute(componentXml, "alpha", defaultXml); xml_attribute<> *alpha = findAttribute(componentXml, "alpha", defaultXml);
xml_attribute<> *angle = FindAttribute(componentXml, "angle", defaultXml); xml_attribute<> *angle = findAttribute(componentXml, "angle", defaultXml);
xml_attribute<> *layer = FindAttribute(componentXml, "layer", defaultXml); xml_attribute<> *layer = findAttribute(componentXml, "layer", defaultXml);
xml_attribute<> *backgroundColor = FindAttribute(componentXml, "backgroundColor", defaultXml); xml_attribute<> *backgroundColor = findAttribute(componentXml, "backgroundColor", defaultXml);
xml_attribute<> *backgroundAlpha = FindAttribute(componentXml, "backgroundAlpha", defaultXml); xml_attribute<> *backgroundAlpha = findAttribute(componentXml, "backgroundAlpha", defaultXml);
info->SetX(GetHorizontalAlignment(x, 0)); info.X = getHorizontalAlignment(x, 0);
info->SetY(GetVerticalAlignment(y, 0)); info.Y = getVerticalAlignment(y, 0);
info->SetXOffset( GetHorizontalAlignment(xOffset, 0)); info.XOffset = getHorizontalAlignment(xOffset, 0);
info->SetYOffset( GetVerticalAlignment(yOffset, 0)); info.YOffset = getVerticalAlignment(yOffset, 0);
float xOriginRelative = GetHorizontalAlignment(xOrigin, 0); float xOriginRelative = getHorizontalAlignment(xOrigin, 0);
float yOriginRelative = GetVerticalAlignment(yOrigin, 0); float yOriginRelative = getVerticalAlignment(yOrigin, 0);
// the origins need to be saved as a percent since the heights and widths can be scaled // the origins need to be saved as a percent since the heights and widths can be scaled
info->SetXOrigin(xOriginRelative / ScreenWidth); info.XOrigin = xOriginRelative / screenWidth_;
info->SetYOrigin(yOriginRelative / ScreenHeight); info.YOrigin = yOriginRelative / screenHeight_;
if(!height && !width) if(!height && !width)
{ {
info->SetHeight(-1); info.Height = -1;
info->SetWidth(-1); info.Width = -1;
} }
else else
{ {
info->SetHeight(GetVerticalAlignment(height, -1)); info.Height = getVerticalAlignment(height, -1);
info->SetWidth(GetHorizontalAlignment(width, -1)); info.Width = getHorizontalAlignment(width, -1);
} }
info->SetFontSize(GetVerticalAlignment(fontSize, -1)); info.FontSize = getVerticalAlignment(fontSize, -1);
info->SetMinHeight(GetVerticalAlignment(minHeight, 0)); info.MinHeight = getVerticalAlignment(minHeight, 0);
info->SetMinWidth(GetHorizontalAlignment(minWidth, 0)); info.MinWidth = getHorizontalAlignment(minWidth, 0);
info->SetMaxHeight(GetVerticalAlignment(maxHeight, FLT_MAX)); info.MaxHeight = getVerticalAlignment(maxHeight, FLT_MAX);
info->SetMaxWidth(GetVerticalAlignment(maxWidth, FLT_MAX)); info.MaxWidth = getVerticalAlignment(maxWidth, FLT_MAX);
info->SetAlpha( alpha ? Utils::ConvertFloat(alpha->value()) : 1); info.Alpha = alpha ? Utils::convertFloat(alpha->value()) : 1.f;
info->SetAngle( angle ? Utils::ConvertFloat(angle->value()) : 0); info.Angle = angle ? Utils::convertFloat(angle->value()) : 0.f;
info->SetLayer( layer ? Utils::ConvertInt(layer->value()) : 0); info.Layer = layer ? Utils::convertInt(layer->value()) : 0;
if(backgroundColor) if(backgroundColor)
{ {
@@ -893,37 +886,37 @@ void PageBuilder::BuildViewInfo(xml_node<> *componentXml, ViewInfo *info, xml_no
int green = (num / 0x100) % 0x100; int green = (num / 0x100) % 0x100;
int blue = num % 0x100; int blue = num % 0x100;
info->SetBackgroundRed(static_cast<float>(red)/255); info.BackgroundRed = static_cast<float>(red/255);
info->SetBackgroundGreen(static_cast<float>(green)/255); info.BackgroundGreen = static_cast<float>(green/255);
info->SetBackgroundBlue(static_cast<float>(blue)/255); info.BackgroundBlue = static_cast<float>(blue/255);
} }
if(backgroundAlpha) if(backgroundAlpha)
{ {
info->SetBackgroundAlpha( backgroundAlpha ? Utils::ConvertFloat(backgroundAlpha->value()) : 1); info.BackgroundAlpha = backgroundAlpha ? Utils::convertFloat(backgroundAlpha->value()) : 1.f;
} }
} }
void PageBuilder::GetTweenSet(xml_node<> *node, Animation *animation) void PageBuilder::getTweenSet(xml_node<> *node, Animation *animation)
{ {
if(node) if(node)
{ {
for(xml_node<> *set = node->first_node("set"); set; set = set->next_sibling("set")) for(xml_node<> *set = node->first_node("set"); set; set = set->next_sibling("set"))
{ {
TweenSet *ts = new TweenSet(); TweenSet *ts = new TweenSet();
GetAnimationEvents(set, *ts); getAnimationEvents(set, *ts);
animation->Push(ts); animation->Push(ts);
} }
} }
} }
void PageBuilder::GetAnimationEvents(xml_node<> *node, TweenSet &tweens) void PageBuilder::getAnimationEvents(xml_node<> *node, TweenSet &tweens)
{ {
xml_attribute<> *durationXml = node->first_attribute("duration"); xml_attribute<> *durationXml = node->first_attribute("duration");
if(!durationXml) if(!durationXml)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Animation set tag missing \"duration\" attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Animation set tag missing \"duration\" attribute");
} }
else else
{ {
@@ -936,60 +929,60 @@ void PageBuilder::GetAnimationEvents(xml_node<> *node, TweenSet &tweens)
if(!type) if(!type)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"type\" attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"type\" attribute");
} }
else if(!from) else if(!from)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"from\" attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"from\" attribute");
} }
else if(!to) else if(!to)
{ {
Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute"); Logger::write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute");
} }
else else
{ {
float fromValue = Utils::ConvertFloat(from->value()); float fromValue = Utils::convertFloat(from->value());
float toValue = Utils::ConvertFloat(to->value()); float toValue = Utils::convertFloat(to->value());
float durationValue = Utils::ConvertFloat(durationXml->value()); float durationValue = Utils::convertFloat(durationXml->value());
TweenAlgorithm algorithm = LINEAR; TweenAlgorithm algorithm = LINEAR;
TweenProperty property; TweenProperty property;
if(algorithmXml) if(algorithmXml)
{ {
algorithm = Tween::GetTweenType(algorithmXml->value()); algorithm = Tween::getTweenType(algorithmXml->value());
} }
if(Tween::GetTweenProperty(type->value(), property)) if(Tween::getTweenProperty(type->value(), property))
{ {
switch(property) switch(property)
{ {
case TWEEN_PROPERTY_WIDTH: case TWEEN_PROPERTY_WIDTH:
case TWEEN_PROPERTY_X: case TWEEN_PROPERTY_X:
case TWEEN_PROPERTY_X_OFFSET: case TWEEN_PROPERTY_X_OFFSET:
fromValue = GetHorizontalAlignment(from, 0); fromValue = getHorizontalAlignment(from, 0);
toValue = GetHorizontalAlignment(to, 0); toValue = getHorizontalAlignment(to, 0);
break; break;
// x origin gets translated to a percent // x origin gets translated to a percent
case TWEEN_PROPERTY_X_ORIGIN: case TWEEN_PROPERTY_X_ORIGIN:
fromValue = GetHorizontalAlignment(from, 0) / ScreenWidth; fromValue = getHorizontalAlignment(from, 0) / screenWidth_;
toValue = GetHorizontalAlignment(to, 0) / ScreenWidth; toValue = getHorizontalAlignment(to, 0) / screenWidth_;
break; break;
case TWEEN_PROPERTY_HEIGHT: case TWEEN_PROPERTY_HEIGHT:
case TWEEN_PROPERTY_Y: case TWEEN_PROPERTY_Y:
case TWEEN_PROPERTY_Y_OFFSET: case TWEEN_PROPERTY_Y_OFFSET:
case TWEEN_PROPERTY_FONT_SIZE: case TWEEN_PROPERTY_FONT_SIZE:
fromValue = GetVerticalAlignment(from, 0); fromValue = getVerticalAlignment(from, 0);
toValue = GetVerticalAlignment(to, 0); toValue = getVerticalAlignment(to, 0);
break; break;
// y origin gets translated to a percent // y origin gets translated to a percent
case TWEEN_PROPERTY_Y_ORIGIN: case TWEEN_PROPERTY_Y_ORIGIN:
fromValue = GetVerticalAlignment(from, 0) / ScreenHeight; fromValue = getVerticalAlignment(from, 0) / screenHeight_;
toValue = GetVerticalAlignment(to, 0) / ScreenHeight; toValue = getVerticalAlignment(to, 0) / screenHeight_;
break; break;
default: default:
@@ -997,13 +990,13 @@ void PageBuilder::GetAnimationEvents(xml_node<> *node, TweenSet &tweens)
} }
Tween *t = new Tween(property, algorithm, fromValue, toValue, durationValue); Tween *t = new Tween(property, algorithm, fromValue, toValue, durationValue);
tweens.Push(t); tweens.push(t);
} }
else else
{ {
std::stringstream ss; std::stringstream ss;
ss << "Unsupported tween type attribute \"" << type->value() << "\""; ss << "Unsupported tween type attribute \"" << type->value() << "\"";
Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); Logger::write(Logger::ZONE_ERROR, "Layout", ss.str());
} }
} }
} }

View File

@@ -33,37 +33,37 @@ class PageBuilder
public: public:
PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc); PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc);
virtual ~PageBuilder(); virtual ~PageBuilder();
Page *BuildPage(); Page *buildPage();
private: private:
std::string LayoutKey; std::string layoutKey;
std::string LayoutPage; std::string layoutPage;
std::string LayoutPath; std::string layoutPath;
Configuration &Config; Configuration &config_;
float ScaleX; float scaleX_;
float ScaleY; float scaleY_;
int ScreenHeight; int screenHeight_;
int ScreenWidth; int screenWidth_;
SDL_Color FontColor; SDL_Color fontColor_;
std::string FontName; std::string fontName_;
int FontSize; int fontSize_;
FontCache *FC; FontCache *fontCache_;
Font *AddFont(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults); Font *addFont(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults);
void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page); void loadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page);
float GetVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); float getVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull);
float GetHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); float getHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull);
void BuildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo *info, rapidxml::xml_node<> *defaultXml = NULL); void buildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo &info, rapidxml::xml_node<> *defaultXml = NULL);
bool BuildComponents(rapidxml::xml_node<> *layout, Page *page); bool buildComponents(rapidxml::xml_node<> *layout, Page *page);
void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml); void loadTweens(Component *c, rapidxml::xml_node<> *componentXml);
AnimationEvents *CreateTweenInstance(rapidxml::xml_node<> *componentXml); AnimationEvents *createTweenInstance(rapidxml::xml_node<> *componentXml);
void BuildTweenSet(AnimationEvents *tweens, rapidxml::xml_node<> *componentXml, std::string tagName, std::string tweenName); void buildTweenSet(AnimationEvents *tweens, rapidxml::xml_node<> *componentXml, std::string tagName, std::string tweenName);
ScrollingList * BuildMenu(rapidxml::xml_node<> *menuXml); ScrollingList * buildMenu(rapidxml::xml_node<> *menuXml);
void BuildCustomMenu(ScrollingList *menu, rapidxml::xml_node<> *menuXml, rapidxml::xml_node<> *itemDefaults); void buildCustomMenu(ScrollingList *menu, rapidxml::xml_node<> *menuXml, rapidxml::xml_node<> *itemDefaults);
void BuildVerticalMenu(ScrollingList *menu, rapidxml::xml_node<> *menuXml, rapidxml::xml_node<> *itemDefaults); void buildVerticalMenu(ScrollingList *menu, rapidxml::xml_node<> *menuXml, rapidxml::xml_node<> *itemDefaults);
int ParseMenuPosition(std::string strIndex); int parseMenuPosition(std::string strIndex);
rapidxml::xml_attribute<> *FindAttribute(rapidxml::xml_node<> *componentXml, std::string attribute, rapidxml::xml_node<> *defaultXml); rapidxml::xml_attribute<> *findAttribute(rapidxml::xml_node<> *componentXml, std::string attribute, rapidxml::xml_node<> *defaultXml);
void GetTweenSet(rapidxml::xml_node<> *node, Animation *animation); void getTweenSet(rapidxml::xml_node<> *node, Animation *animation);
void GetAnimationEvents(rapidxml::xml_node<> *node, TweenSet &tweens); void getAnimationEvents(rapidxml::xml_node<> *node, TweenSet &tweens);
ViewInfo * CreateMenuItemInfo(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults, float y); ViewInfo * createMenuItemInfo(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults, float y);
}; };

View File

@@ -50,20 +50,20 @@ ViewInfo::~ViewInfo()
{ {
} }
float ViewInfo::GetXRelativeToOrigin() const float ViewInfo::XRelativeToOrigin() const
{ {
return X + XOffset - XOrigin*GetWidth(); return X + XOffset - XOrigin*ScaledWidth();
} }
float ViewInfo::GetYRelativeToOrigin() const float ViewInfo::YRelativeToOrigin() const
{ {
return Y + YOffset - YOrigin*GetHeight(); return Y + YOffset - YOrigin*ScaledHeight();
} }
float ViewInfo::GetHeight() const float ViewInfo::ScaledHeight() const
{ {
float height = GetAbsoluteHeight(); float height = AbsoluteHeight();
float width = GetAbsoluteWidth(); float width = AbsoluteWidth();
if (height < MinHeight || width < MinWidth) if (height < MinHeight || width < MinWidth)
{ {
@@ -105,10 +105,10 @@ float ViewInfo::GetHeight() const
return height; return height;
} }
float ViewInfo::GetWidth() const float ViewInfo::ScaledWidth() const
{ {
float height = GetAbsoluteHeight(); float height = AbsoluteHeight();
float width = GetAbsoluteWidth(); float width = AbsoluteWidth();
if (height < MinHeight || width < MinWidth) if (height < MinHeight || width < MinWidth)
{ {
@@ -150,7 +150,7 @@ float ViewInfo::GetWidth() const
return width; return width;
} }
float ViewInfo::GetAbsoluteHeight() const float ViewInfo::AbsoluteHeight() const
{ {
if(Height == -1 && Width == -1) if(Height == -1 && Width == -1)
{ {
@@ -165,7 +165,7 @@ float ViewInfo::GetAbsoluteHeight() const
return Height; return Height;
} }
float ViewInfo::GetAbsoluteWidth() const float ViewInfo::AbsoluteWidth() const
{ {
if(Height == -1 && Width == -1) if(Height == -1 && Width == -1)
{ {
@@ -179,245 +179,3 @@ float ViewInfo::GetAbsoluteWidth() const
return Width; return Width;
} }
float ViewInfo::GetXOffset() const
{
return XOffset;
}
float ViewInfo::GetXOrigin() const
{
return XOrigin;
}
float ViewInfo::GetYOffset() const
{
return YOffset;
}
float ViewInfo::GetYOrigin() const
{
return YOrigin;
}
float ViewInfo::GetAngle() const
{
return Angle;
}
void ViewInfo::SetAngle(float angle)
{
Angle = angle;
}
float ViewInfo::GetImageHeight() const
{
return ImageHeight;
}
void ViewInfo::SetImageHeight(float imageheight)
{
ImageHeight = imageheight;
}
float ViewInfo::GetImageWidth() const
{
return ImageWidth;
}
void ViewInfo::SetImageWidth(float imagewidth)
{
ImageWidth = imagewidth;
}
unsigned int ViewInfo::GetLayer() const
{
return Layer;
}
void ViewInfo::SetLayer(unsigned int layer)
{
Layer = layer;
}
float ViewInfo::GetMaxHeight() const
{
return MaxHeight;
}
void ViewInfo::SetMaxHeight(float maxheight)
{
MaxHeight = maxheight;
}
float ViewInfo::GetMaxWidth() const
{
return MaxWidth;
}
void ViewInfo::SetMaxWidth(float maxwidth)
{
MaxWidth = maxwidth;
}
float ViewInfo::GetMinHeight() const
{
return MinHeight;
}
void ViewInfo::SetMinHeight(float minheight)
{
MinHeight = minheight;
}
float ViewInfo::GetMinWidth() const
{
return MinWidth;
}
void ViewInfo::SetMinWidth(float minwidth)
{
MinWidth = minwidth;
}
float ViewInfo::GetAlpha() const
{
return Alpha;
}
void ViewInfo::SetAlpha(float alpha)
{
Alpha = alpha;
}
float ViewInfo::GetX() const
{
return X;
}
void ViewInfo::SetX(float x)
{
X = x;
}
void ViewInfo::SetXOffset(float offset)
{
XOffset = offset;
}
void ViewInfo::SetXOrigin(float origin)
{
XOrigin = origin;
}
float ViewInfo::GetY() const
{
return Y;
}
void ViewInfo::SetY(float y)
{
Y = y;
}
void ViewInfo::SetYOffset(float offset)
{
YOffset = offset;
}
void ViewInfo::SetYOrigin(float origin)
{
YOrigin = origin;
}
float ViewInfo::GetRawYOrigin()
{
return YOrigin;
}
float ViewInfo::GetRawXOrigin()
{
return XOrigin;
}
float ViewInfo::GetRawWidth()
{
return Width;
}
float ViewInfo::GetRawHeight()
{
return Height;
}
void ViewInfo::SetHeight(float height)
{
Height = height;
}
void ViewInfo::SetWidth(float width)
{
Width = width;
}
float ViewInfo::GetFontSize() const
{
if(FontSize == -1)
{
return GetHeight();
}
else
{
return FontSize;
}
}
void ViewInfo::SetFontSize(float fontSize)
{
FontSize = fontSize;
}
float ViewInfo::GetBackgroundRed()
{
return BackgroundRed;
}
void ViewInfo::SetBackgroundRed(float value)
{
BackgroundRed = value;
}
float ViewInfo::GetBackgroundGreen()
{
return BackgroundGreen;
}
void ViewInfo::SetBackgroundGreen(float value)
{
BackgroundGreen = value;
}
float ViewInfo::GetBackgroundBlue()
{
return BackgroundBlue;
}
void ViewInfo::SetBackgroundBlue(float value)
{
BackgroundBlue = value;
}
float ViewInfo::GetBackgroundAlpha()
{
return BackgroundAlpha;
}
void ViewInfo::SetBackgroundAlpha(float value)
{
BackgroundAlpha = value;
}

View File

@@ -26,60 +26,11 @@ public:
ViewInfo(); ViewInfo();
virtual ~ViewInfo(); virtual ~ViewInfo();
float GetXRelativeToOrigin() const; float XRelativeToOrigin() const;
float GetYRelativeToOrigin() const; float YRelativeToOrigin() const;
float GetHeight() const; float ScaledHeight() const;
float GetWidth() const; float ScaledWidth() const;
float GetAngle() const;
void SetAngle(float angle);
float GetImageHeight() const;
void SetImageHeight(float imageheight);
float GetImageWidth() const;
void SetImageWidth(float imagewidth);
unsigned int GetLayer() const;
void SetLayer(unsigned int layer);
float GetMaxHeight() const;
void SetMaxHeight(float maxheight);
float GetMaxWidth() const;
void SetMaxWidth(float maxwidth);
float GetMinHeight() const;
void SetMinHeight(float minheight);
float GetMinWidth() const;
void SetMinWidth(float minwidth);
float GetAlpha() const;
void SetAlpha(float alpha);
float GetX() const;
void SetX(float x);
float GetXOffset() const;
void SetXOffset(float offset);
float GetXOrigin() const;
void SetXOrigin(float origin);
float GetY() const;
void SetY(float y);
float GetYOffset() const;
void SetYOffset(float offset);
float GetYOrigin() const;
void SetYOrigin(float origin);
float GetRawYOrigin();
float GetRawXOrigin();
float GetRawWidth();
float GetRawHeight();
float GetBackgroundRed();
void SetBackgroundRed(float value);
float GetBackgroundGreen();
void SetBackgroundGreen(float value);
float GetBackgroundBlue();
void SetBackgroundBlue(float value);
float GetBackgroundAlpha();
void SetBackgroundAlpha(float value);
void SetHeight(float height);
void SetWidth(float width);
float GetFontSize() const;
void SetFontSize(float fontSize);
static const int AlignCenter = -1; static const int AlignCenter = -1;
static const int AlignLeft = -2; static const int AlignLeft = -2;
@@ -87,9 +38,6 @@ public:
static const int AlignRight = -4; static const int AlignRight = -4;
static const int AlignBottom = -5; static const int AlignBottom = -5;
private:
float GetAbsoluteHeight() const;
float GetAbsoluteWidth() const;
float X; float X;
float Y; float Y;
float XOrigin; float XOrigin;
@@ -114,4 +62,8 @@ private:
float BackgroundGreen; float BackgroundGreen;
float BackgroundBlue; float BackgroundBlue;
float BackgroundAlpha; float BackgroundAlpha;
private:
float AbsoluteHeight() const;
float AbsoluteWidth() const;
}; };

View File

@@ -30,7 +30,7 @@ static bool StartLogging();
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
Configuration::Initialize(); Configuration::initialize();
Configuration config; Configuration config;
@@ -47,7 +47,7 @@ int main(int argc, char **argv)
if(param == "-createcollection") if(param == "-createcollection")
{ {
CollectionInfoBuilder::CreateCollectionDirectory(value); CollectionInfoBuilder::createCollectionDirectory(value);
} }
return 0; return 0;
@@ -61,34 +61,34 @@ int main(int argc, char **argv)
RetroFE p(config); RetroFE p(config);
p.Run(); p.run();
p.DeInitialize(); p.deInitialize();
Logger::DeInitialize(); Logger::deInitialize();
return 0; return 0;
} }
bool ImportConfiguration(Configuration *c) bool ImportConfiguration(Configuration *c)
{ {
std::string configPath = Configuration::GetAbsolutePath(); std::string configPath = Configuration::absolutePath;
std::string launchersPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "launchers"); std::string launchersPath = Utils::combinePath(Configuration::absolutePath, "launchers");
std::string collectionsPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections"); std::string collectionsPath = Utils::combinePath(Configuration::absolutePath, "collections");
DIR *dp; DIR *dp;
struct dirent *dirp; struct dirent *dirp;
std::string settingsConfPath = Utils::CombinePath(configPath, "settings.conf"); std::string settingsConfPath = Utils::combinePath(configPath, "settings.conf");
if(!c->Import("", settingsConfPath)) if(!c->import("", settingsConfPath))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsConfPath + "\""); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsConfPath + "\"");
return false; return false;
} }
std::string controlsConfPath = Utils::CombinePath(configPath, "controls.conf"); std::string controlsConfPath = Utils::combinePath(configPath, "controls.conf");
if(!c->Import("controls", controlsConfPath)) if(!c->import("controls", controlsConfPath))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + controlsConfPath + "\""); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + controlsConfPath + "\"");
return false; return false;
} }
@@ -96,7 +96,7 @@ bool ImportConfiguration(Configuration *c)
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_NOTICE, "RetroFE", "Could not read directory \"" + launchersPath + "\""); Logger::write(Logger::ZONE_NOTICE, "RetroFE", "Could not read directory \"" + launchersPath + "\"");
return false; return false;
} }
@@ -113,11 +113,11 @@ bool ImportConfiguration(Configuration *c)
{ {
std::string prefix = "launchers." + basename; std::string prefix = "launchers." + basename;
std::string importFile = Utils::CombinePath(launchersPath, std::string(dirp->d_name)); std::string importFile = Utils::combinePath(launchersPath, std::string(dirp->d_name));
if(!c->Import(prefix, importFile)) if(!c->import(prefix, importFile))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\""); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\"");
closedir(dp); closedir(dp);
return false; return false;
} }
@@ -131,22 +131,22 @@ bool ImportConfiguration(Configuration *c)
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\""); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\"");
return false; return false;
} }
while((dirp = readdir(dp)) != NULL) while((dirp = readdir(dp)) != NULL)
{ {
std::string dirName = (dirp->d_name); std::string collection = (dirp->d_name);
if (dirp->d_type == DT_DIR && dirName != "." && dirName != ".." && dirName.length() > 0 && dirName[0] != '_') if (dirp->d_type == DT_DIR && collection != "." && collection != ".." && collection.length() > 0 && collection[0] != '_')
{ {
std::string prefix = "collections." + std::string(dirp->d_name); std::string prefix = "collections." + collection;
std::string settingsFile = Utils::CombinePath(collectionsPath, std::string(dirp->d_name), "settings.conf"); std::string settingsFile = Utils::combinePath(collectionsPath, collection, "settings.conf");
if(!c->Import(prefix, settingsFile)) if(!c->import(collection, prefix, settingsFile))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\""); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\"");
closedir(dp); closedir(dp);
return false; return false;
} }
@@ -155,30 +155,30 @@ bool ImportConfiguration(Configuration *c)
closedir(dp); closedir(dp);
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration"); Logger::write(Logger::ZONE_INFO, "RetroFE", "Imported configuration");
return true; return true;
} }
bool StartLogging() bool StartLogging()
{ {
std::string logFile = Utils::CombinePath(Configuration::GetAbsolutePath(), "log.txt"); std::string logFile = Utils::combinePath(Configuration::absolutePath, "log.txt");
if(!Logger::Initialize(logFile)) if(!Logger::initialize(logFile))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing"); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing");
return false; return false;
} }
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting"); Logger::write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::getString() + " starting");
#ifdef WIN32 #ifdef WIN32
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows"); Logger::write(Logger::ZONE_INFO, "RetroFE", "OS: Windows");
#else #else
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux"); Logger::write(Logger::ZONE_INFO, "RetroFE", "OS: Linux");
#endif #endif
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath()); Logger::write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::absolutePath);
return true; return true;
} }

View File

@@ -32,6 +32,15 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include <sstream> #include <sstream>
#include <dirent.h>
#ifdef __linux
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <cstring>
#endif
#ifdef WIN32 #ifdef WIN32
#include <Windows.h> #include <Windows.h>
#include <SDL2/SDL_syswm.h> #include <SDL2/SDL_syswm.h>
@@ -39,176 +48,180 @@
#endif #endif
RetroFE::RetroFE(Configuration &c) RetroFE::RetroFE(Configuration &c)
: Initialized(false) : initialized(false)
, InitializeError(false) , initializeError(false)
, InitializeThread(NULL) , initializeThread(NULL)
, Config(c) , config_(c)
, Db(NULL) , db_(NULL)
, MetaDb(NULL) , metadb_(NULL)
, Input(Config) , input_(config_)
, CurrentPage(NULL) , currentPage_(NULL)
, KeyInputDisable(0) , keyInputDisable_(0)
, CurrentTime(0) , currentTime_(0)
, lastLaunchReturnTime_(0)
, keyLastTime_(0)
, keyDelayTime_(.3f)
{ {
} }
RetroFE::~RetroFE() RetroFE::~RetroFE()
{ {
DeInitialize(); deInitialize();
} }
void RetroFE::Render() void RetroFE::render()
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF); SDL_SetRenderDrawColor(SDL::getRenderer(), 0x0, 0x0, 0x00, 0xFF);
SDL_RenderClear(SDL::GetRenderer()); SDL_RenderClear(SDL::getRenderer());
if(CurrentPage) if(currentPage_)
{ {
CurrentPage->Draw(); currentPage_->draw();
} }
SDL_RenderPresent(SDL::GetRenderer()); SDL_RenderPresent(SDL::getRenderer());
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
int RetroFE::Initialize(void *context) int RetroFE::initialize(void *context)
{ {
RetroFE *instance = static_cast<RetroFE *>(context); RetroFE *instance = static_cast<RetroFE *>(context);
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Initializing"); Logger::write(Logger::ZONE_INFO, "RetroFE", "Initializing");
if(!instance->Input.Initialize()) if(!instance->input_.initialize())
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize user controls"); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize user controls");
instance->InitializeError = true; instance->initializeError = true;
return -1; return -1;
} }
instance->Db = new DB(Utils::CombinePath(Configuration::GetAbsolutePath(), "meta.db")); instance->db_ = new DB(Utils::combinePath(Configuration::absolutePath, "meta.db"));
if(!instance->Db->Initialize()) if(!instance->db_->initialize())
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize database"); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize database");
instance->InitializeError = true; instance->initializeError = true;
return -1; return -1;
} }
instance->MetaDb = new MetadataDatabase(*(instance->Db), instance->Config); instance->metadb_ = new MetadataDatabase(*(instance->db_), instance->config_);
if(!instance->MetaDb->Initialize()) if(!instance->metadb_->initialize())
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize meta database"); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize meta database");
instance->InitializeError = true; instance->initializeError = true;
return -1; return -1;
} }
instance->Initialized = true; instance->initialized = true;
return 0; return 0;
} }
void RetroFE::LaunchEnter() void RetroFE::launchEnter()
{ {
if(CurrentPage) if(currentPage_)
{ {
CurrentPage->LaunchEnter(); currentPage_->launchEnter();
} }
SDL_SetWindowGrab(SDL::GetWindow(), SDL_FALSE); SDL_SetWindowGrab(SDL::getWindow(), SDL_FALSE);
} }
void RetroFE::LaunchExit() void RetroFE::launchExit()
{ {
SDL_RestoreWindow(SDL::GetWindow()); SDL_RestoreWindow(SDL::getWindow());
SDL_RaiseWindow(SDL::GetWindow()); SDL_RaiseWindow(SDL::getWindow());
SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE); SDL_SetWindowGrab(SDL::getWindow(), SDL_TRUE);
Input.ResetKeyStates(); input_.resetStates();
Attract.Reset(); attract_.reset();
CurrentTime = static_cast<float>(SDL_GetTicks()) / 1000; currentTime_ = static_cast<float>(SDL_GetTicks()) / 1000;
if(CurrentPage) if(currentPage_)
{ {
CurrentPage->LaunchExit(); currentPage_->launchExit();
} }
lastLaunchReturnTime_ = currentTime_;
} }
void RetroFE::FreeGraphicsMemory() void RetroFE::freeGraphicsMemory()
{ {
if(CurrentPage) if(currentPage_)
{ {
CurrentPage->FreeGraphicsMemory(); currentPage_->freeGraphicsMemory();
} }
FC.DeInitialize(); fontcache_.deInitialize();
SDL::DeInitialize(); SDL::deInitialize();
} }
void RetroFE::AllocateGraphicsMemory() void RetroFE::allocateGraphicsMemory()
{ {
SDL::Initialize(Config); SDL::initialize(config_);
FC.Initialize(); fontcache_.initialize();
if(CurrentPage) if(currentPage_)
{ {
CurrentPage->AllocateGraphicsMemory(); currentPage_->allocateGraphicsMemory();
CurrentPage->Start(); currentPage_->start();
} }
} }
bool RetroFE::DeInitialize() bool RetroFE::deInitialize()
{ {
bool retVal = true; bool retVal = true;
FreeGraphicsMemory(); freeGraphicsMemory();
if(CurrentPage) if(currentPage_)
{ {
delete CurrentPage; delete currentPage_;
CurrentPage = NULL; currentPage_ = NULL;
} }
if(MetaDb) if(metadb_)
{ {
delete MetaDb; delete metadb_;
MetaDb = NULL; metadb_ = NULL;
} }
if(Db) if(db_)
{ {
delete Db; delete db_;
Db = NULL; db_ = NULL;
} }
Initialized = false; initialized = false;
//todo: handle video deallocation //todo: handle video deallocation
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Exiting"); Logger::write(Logger::ZONE_INFO, "RetroFE", "Exiting");
return retVal; return retVal;
} }
void RetroFE::Run() void RetroFE::run()
{ {
if(!SDL::Initialize(Config)) return; if(!SDL::initialize(config_)) return;
FC.Initialize(); fontcache_.initialize();
float preloadTime = 0; float preloadTime = 0;
bool videoEnable = true; bool videoEnable = true;
int videoLoop = 0; int videoLoop = 0;
Config.GetProperty("videoEnable", videoEnable); config_.getProperty("videoEnable", videoEnable);
Config.GetProperty("videoLoop", videoLoop); config_.getProperty("videoLoop", videoLoop);
VideoFactory::SetEnabled(videoEnable); VideoFactory::setEnabled(videoEnable);
VideoFactory::SetNumLoops(videoLoop); VideoFactory::setNumLoops(videoLoop);
VideoFactory::CreateVideo(); // pre-initialize the gstreamer engine VideoFactory::createVideo(); // pre-initialize the gstreamer engine
InitializeThread = SDL_CreateThread(Initialize, "RetroFEInit", (void *)this); initializeThread = SDL_CreateThread(initialize, "RetroFEInit", (void *)this);
if(!InitializeThread) if(!initializeThread)
{ {
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Could not initialize RetroFE"); Logger::write(Logger::ZONE_INFO, "RetroFE", "Could not initialize RetroFE");
return; return;
} }
@@ -217,72 +230,84 @@ void RetroFE::Run()
bool running = true; bool running = true;
RETROFE_STATE state = RETROFE_NEW; RETROFE_STATE state = RETROFE_NEW;
Config.GetProperty("attractModeTime", attractModeTime); config_.getProperty("attractModeTime", attractModeTime);
Config.GetProperty("firstCollection", firstCollection); config_.getProperty("firstCollection", firstCollection);
Attract.SetIdleTime(static_cast<float>(attractModeTime)); attract_.idleTime = static_cast<float>(attractModeTime);
int initializeStatus = 0; int initializeStatus = 0;
// load the initial splash screen, unload it once it is complete // load the initial splash screen, unload it once it is complete
CurrentPage = LoadSplashPage(); currentPage_ = loadSplashPage();
bool splashMode = true; bool splashMode = true;
Launcher l(*this, Config); Launcher l(*this, config_);
preloadTime = static_cast<float>(SDL_GetTicks()) / 1000; preloadTime = static_cast<float>(SDL_GetTicks()) / 1000;
while (running) while (running)
{ {
float lastTime = 0; float lastTime = 0;
float deltaTime = 0; float deltaTime = 0;
SDL_Event e;
if(!CurrentPage) if (SDL_PollEvent(&e))
{ {
Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page"); if(input_.update(e))
{
attract_.reset();
}
}
if(!currentPage_)
{
Logger::write(Logger::ZONE_WARNING, "RetroFE", "Could not load page");
running = false; running = false;
break; break;
} }
// todo: This could be transformed to use the state design pattern.
switch(state) switch(state)
{ {
case RETROFE_IDLE: case RETROFE_IDLE:
if(CurrentPage && !splashMode) if(currentPage_ && !splashMode)
{ {
state = ProcessUserInput(CurrentPage);
} // account for when returning from a menu and the previous key was still "stuck"
else if(lastLaunchReturnTime_ == 0 || (currentTime_ - lastLaunchReturnTime_ > .3))
{ {
// read and discard SDL input to prevent windows from balking at us state = processUserInput(currentPage_);
SDL_Event e; lastLaunchReturnTime_ = 0;
(void)SDL_PollEvent(&e); }
} }
if((Initialized || InitializeError) && splashMode && CurrentPage->GetMinShowTime() <= (CurrentTime - preloadTime)) if((initialized || initializeError) && splashMode && currentPage_->getMinShowTime() <= (currentTime_ - preloadTime))
{ {
SDL_WaitThread(InitializeThread, &initializeStatus); SDL_WaitThread(initializeThread, &initializeStatus);
if(InitializeError) if(initializeError)
{ {
state = RETROFE_QUIT_REQUEST; state = RETROFE_QUIT_REQUEST;
break; break;
} }
// delete the splash screen and use the standard menu // delete the splash screen and use the standard menu
delete CurrentPage; delete currentPage_;
CurrentPage = LoadPage(); currentPage_ = loadPage();
splashMode = false; splashMode = false;
if(CurrentPage) if(currentPage_)
{ {
std::string firstCollection = "Main"; std::string firstCollection = "Main";
Config.GetProperty("firstCollection", firstCollection); bool menuSort = true;
CurrentPage->Start(); config_.getProperty("firstCollection", firstCollection);
Config.SetCurrentCollection(firstCollection); config_.getProperty("collections." + firstCollection + ".list.menuSort", menuSort);
CollectionInfo *info = GetCollection(firstCollection);
currentPage_->start();
config_.setProperty("currentCollection", firstCollection);
CollectionInfo *info = getCollection(firstCollection);
MenuParser mp; MenuParser mp;
mp.GetMenuItems(info);
CurrentPage->PushCollection(info); mp.buildMenuItems(info, menuSort);
currentPage_->pushCollection(info);
} }
else else
{ {
@@ -294,41 +319,42 @@ void RetroFE::Run()
break; break;
case RETROFE_NEXT_PAGE_REQUEST: case RETROFE_NEXT_PAGE_REQUEST:
if(CurrentPage->IsIdle()) if(currentPage_->isIdle())
{ {
state = RETROFE_NEW; state = RETROFE_NEW;
} }
break; break;
case RETROFE_LAUNCH_REQUEST: case RETROFE_LAUNCH_REQUEST:
NextPageItem = CurrentPage->GetSelectedItem(); nextPageItem_ = currentPage_->getSelectedItem();
l.Run(CurrentPage->GetCollectionName(), NextPageItem); l.run(nextPageItem_->collectionInfo->name, nextPageItem_);
state = RETROFE_IDLE; state = RETROFE_IDLE;
break; break;
case RETROFE_BACK_REQUEST: case RETROFE_BACK_REQUEST:
LastMenuOffsets[CurrentPage->GetCollectionName()] = CurrentPage->GetScrollOffsetIndex();
CurrentPage->PopCollection(); lastMenuOffsets_[currentPage_->getCollectionName()] = currentPage_->getScrollOffsetIndex();
Config.SetCurrentCollection(CurrentPage->GetCollectionName()); currentPage_->popCollection();
config_.setProperty("currentCollection", currentPage_->getCollectionName());
state = RETROFE_NEW; state = RETROFE_NEW;
break; break;
case RETROFE_NEW: case RETROFE_NEW:
if(CurrentPage->IsIdle()) if(currentPage_->isIdle())
{ {
state = RETROFE_IDLE; state = RETROFE_IDLE;
} }
break; break;
case RETROFE_QUIT_REQUEST: case RETROFE_QUIT_REQUEST:
CurrentPage->Stop(); currentPage_->stop();
state = RETROFE_QUIT; state = RETROFE_QUIT;
break; break;
case RETROFE_QUIT: case RETROFE_QUIT:
if(CurrentPage->IsHidden()) if(currentPage_->isHidden())
{ {
running = false; running = false;
} }
@@ -339,42 +365,42 @@ void RetroFE::Run()
// the logic below could be done in a helper method // the logic below could be done in a helper method
if(running) if(running)
{ {
lastTime = CurrentTime; lastTime = currentTime_;
CurrentTime = static_cast<float>(SDL_GetTicks()) / 1000; currentTime_ = static_cast<float>(SDL_GetTicks()) / 1000;
if (CurrentTime < lastTime) if (currentTime_ < lastTime)
{ {
CurrentTime = lastTime; currentTime_ = lastTime;
} }
deltaTime = CurrentTime - lastTime; deltaTime = currentTime_ - lastTime;
double sleepTime = 1000.0/60.0 - deltaTime*1000; double sleepTime = 1000.0/60.0 - deltaTime*1000;
if(sleepTime > 0) if(sleepTime > 0)
{ {
SDL_Delay(static_cast<unsigned int>(sleepTime)); SDL_Delay(static_cast<unsigned int>(sleepTime));
} }
if(CurrentPage) if(currentPage_)
{ {
Attract.Update(deltaTime, *CurrentPage); attract_.update(deltaTime, *currentPage_);
CurrentPage->Update(deltaTime); currentPage_->update(deltaTime);
} }
Render(); render();
} }
} }
} }
bool RetroFE::Back(bool &exit) bool RetroFE::back(bool &exit)
{ {
bool canGoBack = false; bool canGoBack = false;
bool exitOnBack = false; bool exitOnBack = false;
Config.GetProperty("exitOnFirstPageBack", exitOnBack); config_.getProperty("exitOnFirstPageBack", exitOnBack);
exit = false; exit = false;
if(CurrentPage->GetMenuDepth() <= 1) if(currentPage_->getMenuDepth() <= 1)
{ {
exit = exitOnBack; exit = exitOnBack;
} }
@@ -387,173 +413,212 @@ bool RetroFE::Back(bool &exit)
} }
RetroFE::RETROFE_STATE RetroFE::ProcessUserInput(Page *page) RetroFE::RETROFE_STATE RetroFE::processUserInput(Page *page)
{ {
SDL_Event e;
bool exit = false; bool exit = false;
RETROFE_STATE state = RETROFE_IDLE; RETROFE_STATE state = RETROFE_IDLE;
if (SDL_PollEvent(&e) == 0) return state;
bool rememberMenu = false; bool rememberMenu = false;
Config.GetProperty("rememberMenu", rememberMenu); config_.getProperty("rememberMenu", rememberMenu);
if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) if(page->isHorizontalScroll())
{ {
SDL_Scancode scancode = SDL_GetScancodeFromKey(e.key.keysym.sym); if (input_.keystate(UserInput::KeyCodeLeft))
Input.SetKeyState(scancode, (e.type == SDL_KEYDOWN) ? true : false);
Attract.Reset();
if(page->IsHorizontalScroll())
{ {
if (Input.GetKeyState(UserInput::KeyCodeLeft)) page->setScrolling(Page::ScrollDirectionBack);
}
if (input_.keystate(UserInput::KeyCodeRight))
{
page->setScrolling(Page::ScrollDirectionForward);
}
}
else
{
if (input_.keystate(UserInput::KeyCodeUp))
{
page->setScrolling(Page::ScrollDirectionBack);
}
if (input_.keystate(UserInput::KeyCodeDown))
{
page->setScrolling(Page::ScrollDirectionForward);
}
}
if (!input_.keystate(UserInput::KeyCodePageUp) &&
!input_.keystate(UserInput::KeyCodePageDown) &&
!input_.keystate(UserInput::KeyCodeLetterUp) &&
!input_.keystate(UserInput::KeyCodeLetterDown))
{
keyLastTime_ = 0;
keyDelayTime_= 0.3f;
}
else if((currentTime_ - keyLastTime_) > keyDelayTime_ || keyLastTime_ == 0)
{
keyLastTime_ = currentTime_;
keyDelayTime_-= .05f;
if(keyDelayTime_< 0.1f) keyDelayTime_= 0.1f;
if (input_.keystate(UserInput::KeyCodePageUp))
{
page->pageScroll(Page::ScrollDirectionBack);
}
if (input_.keystate(UserInput::KeyCodePageDown))
{
page->pageScroll(Page::ScrollDirectionForward);
}
if (input_.keystate(UserInput::KeyCodeLetterUp))
{
page->letterScroll(Page::ScrollDirectionBack);
}
if (input_.keystate(UserInput::KeyCodeLetterDown))
{
page->letterScroll(Page::ScrollDirectionForward);
}
}
if (input_.keystate(UserInput::KeyCodeAdminMode))
{
//todo: add admin mode support
}
if (input_.keystate(UserInput::KeyCodeSelect) && page->isMenuIdle())
{
nextPageItem_ = page->getSelectedItem();
if(nextPageItem_)
{
if(nextPageItem_->leaf)
{ {
page->SetScrolling(Page::ScrollDirectionBack); state = RETROFE_LAUNCH_REQUEST;
} }
if (Input.GetKeyState(UserInput::KeyCodeRight)) else
{ {
page->SetScrolling(Page::ScrollDirectionForward); bool menuSort = true;
} config_.setProperty("currentCollection", nextPageItem_->name);
} config_.getProperty("collections." + nextPageItem_->name + ".list.menuSort", menuSort);
else
{
if (Input.GetKeyState(UserInput::KeyCodeUp))
{
page->SetScrolling(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodeDown))
{
page->SetScrolling(Page::ScrollDirectionForward);
}
}
if (Input.GetKeyState(UserInput::KeyCodePageUp))
{
page->PageScroll(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodePageDown))
{
page->PageScroll(Page::ScrollDirectionForward);
}
if (Input.GetKeyState(UserInput::KeyCodeLetterUp))
{
page->LetterScroll(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodeLetterDown))
{
page->LetterScroll(Page::ScrollDirectionForward);
}
if (Input.GetKeyState(UserInput::KeyCodeAdminMode)) CollectionInfo *info = getCollection(nextPageItem_->name);
{
//todo: add admin mode support
}
if (Input.GetKeyState(UserInput::KeyCodeSelect) && page->IsMenuIdle())
{
NextPageItem = page->GetSelectedItem();
if(NextPageItem) MenuParser mp;
{ mp.buildMenuItems(info, menuSort);
if(NextPageItem->IsLeaf()) page->pushCollection(info);
if(rememberMenu && lastMenuOffsets_.find(nextPageItem_->name) != lastMenuOffsets_.end())
{ {
state = RETROFE_LAUNCH_REQUEST; page->setScrollOffsetIndex(lastMenuOffsets_[nextPageItem_->name]);
}
else
{
Config.SetCurrentCollection(NextPageItem->GetName());
CollectionInfo *info = GetCollection(NextPageItem->GetName());
MenuParser mp;
mp.GetMenuItems(info);
page->PushCollection(info);
if(rememberMenu && LastMenuOffsets.find(NextPageItem->GetName()) != LastMenuOffsets.end())
{
page->SetScrollOffsetIndex(LastMenuOffsets[NextPageItem->GetName()]);
}
state = RETROFE_NEXT_PAGE_REQUEST;
} }
state = RETROFE_NEXT_PAGE_REQUEST;
} }
} }
}
if (Input.GetKeyState(UserInput::KeyCodeBack) && page->IsMenuIdle()) if (input_.keystate(UserInput::KeyCodeBack) && page->isMenuIdle())
{
if(back(exit) || exit)
{ {
if(Back(exit) || exit) state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST;
{
state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST;
}
} }
}
if (Input.GetKeyState(UserInput::KeyCodeQuit)) if (input_.keystate(UserInput::KeyCodeQuit))
{ {
state = RETROFE_QUIT_REQUEST; state = RETROFE_QUIT_REQUEST;
} }
if(!Input.GetKeyState(UserInput::KeyCodeUp) && if(!input_.keystate(UserInput::KeyCodeUp) &&
!Input.GetKeyState(UserInput::KeyCodeLeft) && !input_.keystate(UserInput::KeyCodeLeft) &&
!Input.GetKeyState(UserInput::KeyCodeDown) && !input_.keystate(UserInput::KeyCodeDown) &&
!Input.GetKeyState(UserInput::KeyCodeRight) && !input_.keystate(UserInput::KeyCodeRight) &&
!Input.GetKeyState(UserInput::KeyCodePageUp) && !input_.keystate(UserInput::KeyCodePageUp) &&
!Input.GetKeyState(UserInput::KeyCodePageDown)) !input_.keystate(UserInput::KeyCodePageDown))
{ {
page->SetScrolling(Page::ScrollDirectionIdle); page->setScrolling(Page::ScrollDirectionIdle);
}
} }
return state; return state;
} }
Page *RetroFE::LoadPage() Page *RetroFE::loadPage()
{ {
std::string layoutName; std::string layoutName;
Config.GetProperty("layout", layoutName); config_.getProperty("layout", layoutName);
PageBuilder pb(layoutName, "layout", Config, &FC); PageBuilder pb(layoutName, "layout", config_, &fontcache_);
Page *page = pb.BuildPage(); Page *page = pb.buildPage();
if(!page) if(!page)
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not create page"); Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not create page");
} }
else else
{ {
page->Start(); page->start();
} }
return page; return page;
} }
Page *RetroFE::LoadSplashPage() Page *RetroFE::loadSplashPage()
{ {
std::string layoutName; std::string layoutName;
Config.GetProperty("layout", layoutName); config_.getProperty("layout", layoutName);
PageBuilder pb(layoutName, "splash", Config, &FC); PageBuilder pb(layoutName, "splash", config_, &fontcache_);
Page * page = pb.BuildPage(); Page * page = pb.buildPage();
page->Start(); page->start();
return page; return page;
} }
CollectionInfo *RetroFE::GetCollection(std::string collectionName) CollectionInfo *RetroFE::getCollection(std::string collectionName)
{ {
// the page will deallocate this once its done // the page will deallocate this once its done
CollectionInfoBuilder cib(Config, *MetaDb); CollectionInfoBuilder cib(config_, *metadb_);
CollectionInfo *collection = cib.BuildCollection(collectionName); CollectionInfo *collection = cib.buildCollection(collectionName);
DIR *dp;
struct dirent *dirp;
std::string path = Utils::combinePath(Configuration::absolutePath, "collections", collectionName);
dp = opendir(path.c_str());
while((dirp = readdir(dp)) != NULL)
{
std::string file = dirp->d_name;
size_t position = file.find_last_of(".");
std::string basename = (std::string::npos == position)? file : file.substr(0, position);
std::string comparator = ".sub";
int start = file.length() - comparator.length();
if(start >= 0)
{
if(file.compare(start, comparator.length(), comparator) == 0)
{
Logger::write(Logger::ZONE_INFO, "RetroFE", "Loading subcollection into menu: " + basename);
CollectionInfo *subcollection = cib.buildCollection(basename, collectionName);
collection->addSubcollection(subcollection);
}
}
}
collection->sortItems();
return collection; return collection;
} }
std::string RetroFE::GetLayout(std::string collectionName) std::string RetroFE::getLayout(std::string collectionName)
{ {
std::string layoutKeyName = "collections." + collectionName + ".layout"; std::string layoutKeyName = "collections." + collectionName + ".layout";
std::string layoutName = "Default 16x9"; std::string layoutName = "Default 16x9";
if(!Config.GetProperty(layoutKeyName, layoutName)) if(!config_.getProperty(layoutKeyName, layoutName))
{ {
Config.GetProperty("layout", layoutName); config_.getProperty("layout", layoutName);
} }
return layoutName; return layoutName;

View File

@@ -37,17 +37,17 @@ class RetroFE
public: public:
RetroFE(Configuration &c); RetroFE(Configuration &c);
virtual ~RetroFE(); virtual ~RetroFE();
bool DeInitialize(); bool deInitialize();
void Run(); void run();
void FreeGraphicsMemory(); void freeGraphicsMemory();
void AllocateGraphicsMemory(); void allocateGraphicsMemory();
void LaunchEnter(); void launchEnter();
void LaunchExit(); void launchExit();
private: private:
volatile bool Initialized; volatile bool initialized;
volatile bool InitializeError; volatile bool initializeError;
SDL_Thread *InitializeThread; SDL_Thread *initializeThread;
static int Initialize(void *context); static int initialize(void *context);
enum RETROFE_STATE enum RETROFE_STATE
{ {
@@ -60,25 +60,28 @@ private:
RETROFE_QUIT, RETROFE_QUIT,
}; };
void Render(); void render();
bool Back(bool &exit); bool back(bool &exit);
void Quit(); void quit();
Page *LoadPage(); Page *loadPage();
Page *LoadSplashPage(); Page *loadSplashPage();
RETROFE_STATE ProcessUserInput(Page *page); RETROFE_STATE processUserInput(Page *page);
void Update(float dt, bool scrollActive); void update(float dt, bool scrollActive);
std::string GetLayout(std::string collectionName); std::string getLayout(std::string collectionName);
CollectionInfo *GetCollection(std::string collectionName); CollectionInfo *getCollection(std::string collectionName);
Configuration &Config; Configuration &config_;
DB *Db; DB *db_;
MetadataDatabase *MetaDb; MetadataDatabase *metadb_;
UserInput Input; UserInput input_;
Page *CurrentPage; Page *currentPage_;
float KeyInputDisable; float keyInputDisable_;
float CurrentTime; float currentTime_;
Item *NextPageItem; float lastLaunchReturnTime_;
FontCache FC; float keyLastTime_;
AttractMode Attract; float keyDelayTime_;
std::map<std::string, unsigned int> LastMenuOffsets; Item *nextPageItem_;
FontCache fontcache_;
AttractMode attract_;
std::map<std::string, unsigned int> lastMenuOffsets_;
}; };

View File

@@ -19,17 +19,17 @@
#include "Utility/Log.h" #include "Utility/Log.h"
#include <SDL2/SDL_mixer.h> #include <SDL2/SDL_mixer.h>
SDL_Window *SDL::Window = NULL; SDL_Window *SDL::window_ = NULL;
SDL_Renderer *SDL::Renderer = NULL; SDL_Renderer *SDL::renderer_ = NULL;
SDL_mutex *SDL::Mutex = NULL; SDL_mutex *SDL::mutex_ = NULL;
int SDL::DisplayWidth = 0; int SDL::displayWidth_ = 0;
int SDL::DisplayHeight = 0; int SDL::displayHeight_ = 0;
int SDL::WindowWidth = 0; int SDL::windowWidth_ = 0;
int SDL::WindowHeight = 0; int SDL::windowHeight_ = 0;
bool SDL::Fullscreen = false; bool SDL::fullscreen_ = false;
bool SDL::Initialize(Configuration &config) bool SDL::initialize(Configuration &config)
{ {
bool retVal = true; bool retVal = true;
std::string hString; std::string hString;
@@ -41,15 +41,15 @@ bool SDL::Initialize(Configuration &config)
int audioBuffers = 4096; int audioBuffers = 4096;
bool hideMouse; bool hideMouse;
Logger::Write(Logger::ZONE_INFO, "SDL", "Initializing"); Logger::write(Logger::ZONE_INFO, "SDL", "Initializing");
if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0) if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0)
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error); Logger::write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error);
retVal = false; retVal = false;
} }
if(retVal && config.GetProperty("hideMouse", hideMouse)) if(retVal && config.getProperty("hideMouse", hideMouse))
{ {
if(hideMouse) if(hideMouse)
{ {
@@ -70,16 +70,16 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode; SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0) if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{ {
DisplayWidth = mode.w; displayWidth_ = mode.w;
DisplayHeight = mode.h; displayHeight_ = mode.h;
break; break;
} }
} }
if(!config.GetProperty("horizontal", hString)) if(!config.getProperty("horizontal", hString))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\"");
retVal = false; retVal = false;
} }
else if(hString == "stretch") else if(hString == "stretch")
@@ -90,22 +90,22 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode; SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0) if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{ {
WindowWidth = mode.w; windowWidth_ = mode.w;
break; break;
} }
} }
} }
else if(!config.GetProperty("horizontal", WindowWidth)) else if(!config.getProperty("horizontal", windowWidth_))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\"");
} }
} }
if(retVal) if(retVal)
{ {
if(!config.GetProperty("vertical", vString)) if(!config.getProperty("vertical", vString))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\"");
retVal = false; retVal = false;
} }
else if(vString == "stretch") else if(vString == "stretch")
@@ -116,24 +116,24 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode; SDL_DisplayMode mode;
if(SDL_GetDesktopDisplayMode(i, &mode) == 0) if(SDL_GetDesktopDisplayMode(i, &mode) == 0)
{ {
WindowHeight = mode.h; windowHeight_ = mode.h;
break; break;
} }
} }
} }
else if(!config.GetProperty("vertical", WindowHeight)) else if(!config.getProperty("vertical", windowHeight_))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\"");
} }
} }
if(retVal && !config.GetProperty("fullscreen", Fullscreen)) if(retVal && !config.getProperty("fullscreen", fullscreen_))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\""); Logger::write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\"");
retVal = false; retVal = false;
} }
if (retVal && Fullscreen) if (retVal && fullscreen_)
{ {
#ifdef WIN32 #ifdef WIN32
windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
@@ -144,55 +144,55 @@ bool SDL::Initialize(Configuration &config)
if(retVal) if(retVal)
{ {
std::string fullscreenStr = Fullscreen ? "yes" : "no"; std::string fullscreenStr = fullscreen_ ? "yes" : "no";
std::stringstream ss; std::stringstream ss;
ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: " ss << "Creating "<< windowWidth_ << "x" << windowHeight_ << " window (fullscreen: "
<< fullscreenStr << ")"; << fullscreenStr << ")";
Logger::Write(Logger::ZONE_INFO, "SDL", ss.str()); Logger::write(Logger::ZONE_INFO, "SDL", ss.str());
Window = SDL_CreateWindow("RetroFE", window_ = SDL_CreateWindow("RetroFE",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
WindowWidth, windowWidth_,
WindowHeight, windowHeight_,
windowFlags); windowFlags);
if (Window == NULL) if (window_ == NULL)
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error); Logger::write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error);
retVal = false; retVal = false;
} }
} }
if(retVal) if(retVal)
{ {
Renderer = SDL_CreateRenderer(Window, renderer_ = SDL_CreateRenderer(window_,
-1, -1,
SDL_RENDERER_ACCELERATED); SDL_RENDERER_ACCELERATED);
if (Renderer == NULL) if (renderer_ == NULL)
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error); Logger::write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error);
retVal = false; retVal = false;
} }
} }
if(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1") != SDL_TRUE) if(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1") != SDL_TRUE)
{ {
Logger::Write(Logger::ZONE_ERROR, "SDL", "Improve scale quality. Continuing with low-quality settings."); Logger::write(Logger::ZONE_ERROR, "SDL", "Improve scale quality. Continuing with low-quality settings.");
} }
if(retVal) if(retVal)
{ {
Mutex = SDL_CreateMutex(); mutex_ = SDL_CreateMutex();
if (Mutex == NULL) if (mutex_ == NULL)
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error); Logger::write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error);
retVal = false; retVal = false;
} }
} }
@@ -201,36 +201,36 @@ bool SDL::Initialize(Configuration &config)
if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1) if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1)
{ {
std::string error = Mix_GetError(); std::string error = Mix_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Audio initialize failed: " + error); Logger::write(Logger::ZONE_ERROR, "SDL", "Audio initialize failed: " + error);
retVal = false; retVal = false;
} }
return retVal; return retVal;
} }
bool SDL::DeInitialize() bool SDL::deInitialize()
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_INFO, "SDL", "DeInitializing"); Logger::write(Logger::ZONE_INFO, "SDL", "DeInitializing");
Mix_CloseAudio(); Mix_CloseAudio();
Mix_Quit(); Mix_Quit();
if(Mutex) if(mutex_)
{ {
SDL_DestroyMutex(Mutex); SDL_DestroyMutex(mutex_);
Mutex = NULL; mutex_ = NULL;
} }
if(Renderer) if(renderer_)
{ {
SDL_DestroyRenderer(Renderer); SDL_DestroyRenderer(renderer_);
Renderer = NULL; renderer_ = NULL;
} }
if(Window) if(window_)
{ {
SDL_DestroyWindow(Window); SDL_DestroyWindow(window_);
Window = NULL; window_ = NULL;
} }
SDL_ShowCursor(SDL_TRUE); SDL_ShowCursor(SDL_TRUE);
@@ -240,31 +240,31 @@ bool SDL::DeInitialize()
return true; return true;
} }
SDL_Renderer* SDL::GetRenderer() SDL_Renderer* SDL::getRenderer()
{ {
return Renderer; return renderer_;
} }
SDL_mutex* SDL::GetMutex() SDL_mutex* SDL::getMutex()
{ {
return Mutex; return mutex_;
} }
SDL_Window* SDL::GetWindow() SDL_Window* SDL::getWindow()
{ {
return Window; return window_;
} }
bool SDL::RenderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, SDL_Rect *dest, double angle) bool SDL::renderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, SDL_Rect *dest, double angle)
{ {
SDL_Rect rotateRect; SDL_Rect rotateRect;
rotateRect.w = dest->w; rotateRect.w = dest->w;
rotateRect.h = dest->h; rotateRect.h = dest->h;
if(Fullscreen) if(fullscreen_)
{ {
rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2; rotateRect.x = dest->x + (displayWidth_ - windowWidth_)/2;
rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2; rotateRect.y = dest->y + (displayHeight_ - windowHeight_)/2;
} }
else else
{ {
@@ -273,7 +273,7 @@ bool SDL::RenderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, S
} }
SDL_SetTextureAlphaMod(texture, alpha); SDL_SetTextureAlphaMod(texture, alpha);
SDL_RenderCopyEx(GetRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE); SDL_RenderCopyEx(getRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE);
return true; return true;
} }

View File

@@ -22,32 +22,32 @@ class Configuration;
class SDL class SDL
{ {
public: public:
static bool Initialize(Configuration &config); static bool initialize(Configuration &config);
static bool DeInitialize(); static bool deInitialize();
static SDL_Renderer *GetRenderer(); static SDL_Renderer *getRenderer();
static SDL_mutex *GetMutex(); static SDL_mutex *getMutex();
static SDL_Window *GetWindow(); static SDL_Window *getWindow();
static bool RenderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, SDL_Rect *dest, double angle); static bool renderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, SDL_Rect *dest, double angle);
static int GetWindowWidth() static int getWindowWidth()
{ {
return WindowWidth; return windowWidth_;
} }
static int GetWindowHeight() static int getWindowHeight()
{ {
return WindowHeight; return windowHeight_;
} }
static bool IsFullscreen() static bool isFullscreen()
{ {
return Fullscreen; return fullscreen_;
} }
private: private:
static SDL_Window *Window; static SDL_Window *window_;
static SDL_Renderer *Renderer; static SDL_Renderer *renderer_;
static SDL_mutex *Mutex; static SDL_mutex *mutex_;
static int DisplayWidth; static int displayWidth_;
static int DisplayHeight; static int displayHeight_;
static int WindowWidth; static int windowWidth_;
static int WindowHeight; static int windowHeight_;
static bool Fullscreen; static bool fullscreen_;
}; };

View File

@@ -19,49 +19,49 @@
#include "../Utility/Log.h" #include "../Utility/Log.h"
Sound::Sound(std::string file) Sound::Sound(std::string file)
: File(file) : file_(file)
, Chunk(NULL) , chunk_(NULL)
{ {
if(!Allocate()) if(!allocate())
{ {
Logger::Write(Logger::ZONE_ERROR, "Sound", "Cannot load " + File); Logger::write(Logger::ZONE_ERROR, "Sound", "Cannot load " + file_);
} }
} }
Sound::~Sound() Sound::~Sound()
{ {
if(Chunk) if(chunk_)
{ {
Mix_FreeChunk(Chunk); Mix_FreeChunk(chunk_);
Chunk = NULL; chunk_ = NULL;
} }
} }
void Sound::Play() void Sound::play()
{ {
if(Chunk) if(chunk_)
{ {
(void)Mix_PlayChannel(-1, Chunk, 0); (void)Mix_PlayChannel(-1, chunk_, 0);
} }
} }
bool Sound::Free() bool Sound::free()
{ {
if(Chunk) if(chunk_)
{ {
Mix_FreeChunk(Chunk); Mix_FreeChunk(chunk_);
Chunk = NULL; chunk_ = NULL;
} }
return true; return true;
} }
bool Sound::Allocate() bool Sound::allocate()
{ {
if(!Chunk) if(!chunk_)
{ {
Chunk = Mix_LoadWAV(File.c_str()); chunk_ = Mix_LoadWAV(file_.c_str());
} }
return (Chunk != NULL); return (chunk_ != NULL);
} }

View File

@@ -22,10 +22,10 @@ class Sound
public: public:
Sound(std::string file); Sound(std::string file);
virtual ~Sound(); virtual ~Sound();
void Play(); void play();
bool Allocate(); bool allocate();
bool Free(); bool free();
private: private:
std::string File; std::string file_;
Mix_Chunk *Chunk; Mix_Chunk *chunk_;
}; };

View File

@@ -19,34 +19,34 @@
#include <sstream> #include <sstream>
#include <ctime> #include <ctime>
std::ofstream Logger::WriteFileStream; std::ofstream Logger::writeFileStream_;
std::streambuf *Logger::CerrStream = NULL; std::streambuf *Logger::cerrStream_ = NULL;
std::streambuf *Logger::CoutStream = NULL; std::streambuf *Logger::coutStream_ = NULL;
bool Logger::Initialize(std::string file) bool Logger::initialize(std::string file)
{ {
WriteFileStream.open(file.c_str()); writeFileStream_.open(file.c_str());
CerrStream = std::cerr.rdbuf(WriteFileStream.rdbuf()); cerrStream_ = std::cerr.rdbuf(writeFileStream_.rdbuf());
CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf()); coutStream_ = std::cout.rdbuf(writeFileStream_.rdbuf());
return WriteFileStream.is_open(); return writeFileStream_.is_open();
} }
void Logger::DeInitialize() void Logger::deInitialize()
{ {
if(WriteFileStream.is_open()) if(writeFileStream_.is_open())
{ {
WriteFileStream.close(); writeFileStream_.close();
} }
std::cerr.rdbuf(CerrStream); std::cerr.rdbuf(cerrStream_);
std::cout.rdbuf(CoutStream); std::cout.rdbuf(coutStream_);
} }
void Logger::Write(Zone zone, std::string component, std::string message) void Logger::write(Zone zone, std::string component, std::string message)
{ {
std::string zoneStr; std::string zoneStr;

View File

@@ -33,12 +33,12 @@ public:
ZONE_ERROR ZONE_ERROR
}; };
static bool Initialize(std::string file); static bool initialize(std::string file);
static void Write(Zone zone, std::string component, std::string message); static void write(Zone zone, std::string component, std::string message);
static void DeInitialize(); static void deInitialize();
private: private:
static std::streambuf *CerrStream; static std::streambuf *cerrStream_;
static std::streambuf *CoutStream; static std::streambuf *coutStream_;
static std::ofstream WriteFileStream; static std::ofstream writeFileStream_;
}; };

View File

@@ -33,7 +33,7 @@ Utils::~Utils()
{ {
} }
std::string Utils::ToLower(std::string str) std::string Utils::toLower(std::string str)
{ {
for(unsigned int i=0; i < str.length(); ++i) for(unsigned int i=0; i < str.length(); ++i)
{ {
@@ -44,7 +44,7 @@ std::string Utils::ToLower(std::string str)
return str; return str;
} }
std::string Utils::UppercaseFirst(std::string str) std::string Utils::uppercaseFirst(std::string str)
{ {
if(str.length() > 0) if(str.length() > 0)
{ {
@@ -54,7 +54,7 @@ std::string Utils::UppercaseFirst(std::string str)
return str; return str;
} }
std::string Utils::FilterComments(std::string line) std::string Utils::filterComments(std::string line)
{ {
size_t position; size_t position;
@@ -69,7 +69,7 @@ std::string Utils::FilterComments(std::string line)
return line; return line;
} }
std::string Utils::CombinePath(std::list<std::string> &paths) std::string Utils::combinePath(std::list<std::string> &paths)
{ {
std::list<std::string>::iterator it = paths.begin(); std::list<std::string>::iterator it = paths.begin();
std::string path; std::string path;
@@ -83,7 +83,7 @@ std::string Utils::CombinePath(std::list<std::string> &paths)
while(it != paths.end()) while(it != paths.end())
{ {
path += Utils::PathSeparator; path += Utils::pathSeparator;
path += *it; path += *it;
it++; it++;
} }
@@ -91,33 +91,33 @@ std::string Utils::CombinePath(std::list<std::string> &paths)
return path; return path;
} }
std::string Utils::CombinePath(std::string path1, std::string path2) std::string Utils::combinePath(std::string path1, std::string path2)
{ {
std::list<std::string> paths; std::list<std::string> paths;
paths.push_back(path1); paths.push_back(path1);
paths.push_back(path2); paths.push_back(path2);
return CombinePath(paths); return combinePath(paths);
} }
std::string Utils::CombinePath(std::string path1, std::string path2, std::string path3) std::string Utils::combinePath(std::string path1, std::string path2, std::string path3)
{ {
std::list<std::string> paths; std::list<std::string> paths;
paths.push_back(path1); paths.push_back(path1);
paths.push_back(path2); paths.push_back(path2);
paths.push_back(path3); paths.push_back(path3);
return CombinePath(paths); return combinePath(paths);
} }
std::string Utils::CombinePath(std::string path1, std::string path2, std::string path3, std::string path4) std::string Utils::combinePath(std::string path1, std::string path2, std::string path3, std::string path4)
{ {
std::list<std::string> paths; std::list<std::string> paths;
paths.push_back(path1); paths.push_back(path1);
paths.push_back(path2); paths.push_back(path2);
paths.push_back(path3); paths.push_back(path3);
paths.push_back(path4); paths.push_back(path4);
return CombinePath(paths); return combinePath(paths);
} }
std::string Utils::CombinePath(std::string path1, std::string path2, std::string path3, std::string path4, std::string path5) std::string Utils::combinePath(std::string path1, std::string path2, std::string path3, std::string path4, std::string path5)
{ {
std::list<std::string> paths; std::list<std::string> paths;
paths.push_back(path1); paths.push_back(path1);
@@ -125,16 +125,16 @@ std::string Utils::CombinePath(std::string path1, std::string path2, std::string
paths.push_back(path3); paths.push_back(path3);
paths.push_back(path4); paths.push_back(path4);
paths.push_back(path5); paths.push_back(path5);
return CombinePath(paths); return combinePath(paths);
} }
bool Utils::FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file) bool Utils::findMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file)
{ {
for(unsigned int i = 0; i < extensions.size(); ++i) for(unsigned int i = 0; i < extensions.size(); ++i)
{ {
std::string temp = prefix + "." + extensions[i]; std::string temp = prefix + "." + extensions[i];
temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp); temp = Configuration::convertToAbsolutePath(Configuration::absolutePath, temp);
std::ifstream f(temp.c_str()); std::ifstream f(temp.c_str());
@@ -149,7 +149,7 @@ bool Utils::FindMatchingFile(std::string prefix, std::vector<std::string> &exten
} }
std::string Utils::Replace( std::string Utils::replace(
std::string subject, std::string subject,
const std::string& search, const std::string& search,
const std::string& replace) const std::string& replace)
@@ -164,7 +164,7 @@ std::string Utils::Replace(
} }
float Utils::ConvertFloat(std::string content) float Utils::convertFloat(std::string content)
{ {
float retVal = 0; float retVal = 0;
std::stringstream ss; std::stringstream ss;
@@ -174,7 +174,7 @@ float Utils::ConvertFloat(std::string content)
return retVal; return retVal;
} }
int Utils::ConvertInt(std::string content) int Utils::convertInt(std::string content)
{ {
int retVal = 0; int retVal = 0;
std::stringstream ss; std::stringstream ss;
@@ -184,19 +184,19 @@ int Utils::ConvertInt(std::string content)
return retVal; return retVal;
} }
void Utils::ReplaceSlashesWithUnderscores(std::string &content) void Utils::replaceSlashesWithUnderscores(std::string &content)
{ {
std::replace(content.begin(), content.end(), '\\', '_'); std::replace(content.begin(), content.end(), '\\', '_');
std::replace(content.begin(), content.end(), '/', '_'); std::replace(content.begin(), content.end(), '/', '_');
} }
std::string Utils::GetDirectory(std::string filePath) std::string Utils::getDirectory(std::string filePath)
{ {
std::string directory = filePath; std::string directory = filePath;
const size_t last_slash_idx = filePath.rfind(PathSeparator); const size_t last_slash_idx = filePath.rfind(pathSeparator);
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
{ {
directory = filePath.substr(0, last_slash_idx); directory = filePath.substr(0, last_slash_idx);
@@ -205,13 +205,13 @@ std::string Utils::GetDirectory(std::string filePath)
return directory; return directory;
} }
std::string Utils::GetParentDirectory(std::string directory) std::string Utils::getParentDirectory(std::string directory)
{ {
size_t last_slash_idx = directory.find_last_of(PathSeparator); size_t last_slash_idx = directory.find_last_of(pathSeparator);
if(directory.length() - 1 == last_slash_idx) if(directory.length() - 1 == last_slash_idx)
{ {
directory = directory.erase(last_slash_idx, directory.length()-1); directory = directory.erase(last_slash_idx, directory.length()-1);
last_slash_idx = directory.find_last_of(PathSeparator); last_slash_idx = directory.find_last_of(pathSeparator);
} }
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
@@ -223,12 +223,12 @@ std::string Utils::GetParentDirectory(std::string directory)
} }
std::string Utils::GetFileName(std::string filePath) std::string Utils::getFileName(std::string filePath)
{ {
std::string filename = filePath; std::string filename = filePath;
const size_t last_slash_idx = filePath.rfind(PathSeparator); const size_t last_slash_idx = filePath.rfind(pathSeparator);
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
{ {
filename = filePath.erase(0, last_slash_idx+1); filename = filePath.erase(0, last_slash_idx+1);

View File

@@ -21,31 +21,31 @@
class Utils class Utils
{ {
public: public:
static std::string Replace(std::string subject, const std::string& search, static std::string replace(std::string subject, const std::string& search,
const std::string& replace); const std::string& replace);
static float ConvertFloat(std::string content); static float convertFloat(std::string content);
static int ConvertInt(std::string content); static int convertInt(std::string content);
static void ReplaceSlashesWithUnderscores(std::string &content); static void replaceSlashesWithUnderscores(std::string &content);
static std::string GetDirectory(std::string filePath); static std::string getDirectory(std::string filePath);
static std::string GetParentDirectory(std::string filePath); static std::string getParentDirectory(std::string filePath);
static std::string GetFileName(std::string filePath); static std::string getFileName(std::string filePath);
static bool FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file); static bool findMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file);
static std::string ToLower(std::string str); static std::string toLower(std::string str);
static std::string UppercaseFirst(std::string str); static std::string uppercaseFirst(std::string str);
static std::string FilterComments(std::string line); static std::string filterComments(std::string line);
//todo: there has to be a better way to do this //todo: there has to be a better way to do this
static std::string CombinePath(std::list<std::string> &paths); static std::string combinePath(std::list<std::string> &paths);
static std::string CombinePath(std::string path1, std::string path2); static std::string combinePath(std::string path1, std::string path2);
static std::string CombinePath(std::string path1, std::string path2, std::string path3); static std::string combinePath(std::string path1, std::string path2, std::string path3);
static std::string CombinePath(std::string path1, std::string path2, std::string path3, std::string path4); static std::string combinePath(std::string path1, std::string path2, std::string path3, std::string path4);
static std::string CombinePath(std::string path1, std::string path2, std::string path3, std::string path4, std::string path5); static std::string combinePath(std::string path1, std::string path2, std::string path3, std::string path4, std::string path5);
#ifdef WIN32 #ifdef WIN32
static const char PathSeparator = '\\'; static const char pathSeparator = '\\';
#else #else
static const char PathSeparator = '/'; static const char pathSeparator = '/';
#endif #endif
private: private:

View File

@@ -33,7 +33,7 @@
#define RETROFE_VERSION_BETA #define RETROFE_VERSION_BETA
#endif #endif
std::string Version::GetString() std::string Version::getString()
{ {
std::stringstream version; std::stringstream version;
version << RETROFE_VERSION_MAJOR; version << RETROFE_VERSION_MAJOR;

View File

@@ -20,5 +20,5 @@
class Version class Version
{ {
public: public:
static std::string GetString(); static std::string getString();
}; };

View File

@@ -29,113 +29,113 @@
#include <sys/types.h> #include <sys/types.h>
#include <gst/app/gstappsink.h> #include <gst/app/gstappsink.h>
bool GStreamerVideo::Initialized = false; bool GStreamerVideo::initialized_ = false;
//todo: this started out as sandbox code. This class needs to be refactored //todo: this started out as sandbox code. This class needs to be refactored
// MUST match video size // MUST match video size
gboolean GStreamerVideo::BusCallback(GstBus * /* bus */, GstMessage * /* msg */, gpointer /* data */) gboolean GStreamerVideo::busCallback(GstBus * /* bus */, GstMessage * /* msg */, gpointer /* data */)
{ {
// this callback only needs to be defined so we can loop the video once it completes // this callback only needs to be defined so we can loop the video once it completes
return TRUE; return TRUE;
} }
GStreamerVideo::GStreamerVideo() GStreamerVideo::GStreamerVideo()
: Playbin(NULL) : playbin_(NULL)
, VideoBin(NULL) , videoBin_(NULL)
, VideoSink(NULL) , videoSink_(NULL)
, VideoConvert(NULL) , videoConvert_(NULL)
, VideoConvertCaps(NULL) , videoConvertCaps_(NULL)
, VideoBus(NULL) , videoBus_(NULL)
, Texture(NULL) , texture_(NULL)
, Height(0) , height_(0)
, Width(0) , width_(0)
, VideoBuffer(NULL) , videoBuffer_(NULL)
, VideoBufferSize(0) , videoBufferSize_(0)
, MaxVideoBufferSize(0) , maxVideoBufferSize_(0)
, FrameReady(false) , frameReady_(false)
, IsPlaying(false) , isPlaying_(false)
, PlayCount(0) , playCount_(0)
, NumLoops(0) , numLoops_(0)
{ {
} }
GStreamerVideo::~GStreamerVideo() GStreamerVideo::~GStreamerVideo()
{ {
Stop(); stop();
if(VideoBuffer) if(videoBuffer_)
{ {
delete[] VideoBuffer; delete[] videoBuffer_;
VideoBuffer = NULL; videoBuffer_ = NULL;
VideoBufferSize = 0; videoBufferSize_ = 0;
MaxVideoBufferSize = 0; maxVideoBufferSize_ = 0;
} }
SDL_DestroyTexture(Texture); SDL_DestroyTexture(texture_);
Texture = NULL; texture_ = NULL;
FreeElements(); freeElements();
} }
void GStreamerVideo::SetNumLoops(int n) void GStreamerVideo::setNumLoops(int n)
{ {
NumLoops = n; numLoops_ = n;
} }
SDL_Texture *GStreamerVideo::GetTexture() const SDL_Texture *GStreamerVideo::getTexture() const
{ {
return Texture; return texture_;
} }
void GStreamerVideo::ProcessNewBuffer (GstElement * /* fakesink */, GstBuffer *buf, GstPad *new_pad, gpointer userdata) void GStreamerVideo::processNewBuffer (GstElement * /* fakesink */, GstBuffer *buf, GstPad *new_pad, gpointer userdata)
{ {
GStreamerVideo *video = (GStreamerVideo *)userdata; GStreamerVideo *video = (GStreamerVideo *)userdata;
GstMapInfo map; GstMapInfo map;
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
if (!video->FrameReady && video && video->IsPlaying && gst_buffer_map (buf, &map, GST_MAP_READ)) if (!video->frameReady_ && video && video->isPlaying_ && gst_buffer_map (buf, &map, GST_MAP_READ))
{ {
if(!video->Width || !video->Height) if(!video->width_ || !video->height_)
{ {
GstCaps *caps = gst_pad_get_current_caps (new_pad); GstCaps *caps = gst_pad_get_current_caps (new_pad);
GstStructure *s = gst_caps_get_structure(caps, 0); GstStructure *s = gst_caps_get_structure(caps, 0);
gst_structure_get_int(s, "width", &video->Width); gst_structure_get_int(s, "width", &video->width_);
gst_structure_get_int(s, "height", &video->Height); gst_structure_get_int(s, "height", &video->height_);
} }
if(video->Height && video->Width) if(video->height_ && video->width_)
{ {
// keep the largest video buffer allocated to avoid the penalty of reallocating and deallocating // keep the largest video buffer allocated to avoid the penalty of reallocating and deallocating
if(!video->VideoBuffer || video->MaxVideoBufferSize < map.size) if(!video->videoBuffer_ || video->maxVideoBufferSize_ < map.size)
{ {
if(video->VideoBuffer) if(video->videoBuffer_)
{ {
delete[] video->VideoBuffer; delete[] video->videoBuffer_;
} }
video->VideoBuffer = new char[map.size]; video->videoBuffer_ = new char[map.size];
video->MaxVideoBufferSize = map.size; video->maxVideoBufferSize_ = map.size;
} }
video->VideoBufferSize = map.size; video->videoBufferSize_ = map.size;
memcpy(video->VideoBuffer, map.data, map.size); memcpy(video->videoBuffer_, map.data, map.size);
gst_buffer_unmap(buf, &map); gst_buffer_unmap(buf, &map);
video->FrameReady = true; video->frameReady_ = true;
} }
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
} }
bool GStreamerVideo::Initialize() bool GStreamerVideo::initialize()
{ {
if(Initialized) if(initialized_)
{ {
return true; return true;
} }
std::string path = Utils::CombinePath(Configuration::GetAbsolutePath(), "Core"); std::string path = Utils::combinePath(Configuration::absolutePath, "Core");
gst_init(NULL, NULL); gst_init(NULL, NULL);
#ifdef WIN32 #ifdef WIN32
@@ -143,63 +143,63 @@ bool GStreamerVideo::Initialize()
gst_registry_scan_path(registry, path.c_str()); gst_registry_scan_path(registry, path.c_str());
#endif #endif
Initialized = true; initialized_ = true;
return true; return true;
} }
bool GStreamerVideo::DeInitialize() bool GStreamerVideo::deInitialize()
{ {
gst_deinit(); gst_deinit();
Initialized = false; initialized_ = false;
return true; return true;
} }
bool GStreamerVideo::Stop() bool GStreamerVideo::stop()
{ {
if(!Initialized) if(!initialized_)
{ {
return false; return false;
} }
if(VideoSink) if(videoSink_)
{ {
g_object_set(G_OBJECT(VideoSink), "signal-handoffs", FALSE, NULL); g_object_set(G_OBJECT(videoSink_), "signal-handoffs", FALSE, NULL);
} }
if(Playbin) if(playbin_)
{ {
(void)gst_element_set_state(Playbin, GST_STATE_NULL); (void)gst_element_set_state(playbin_, GST_STATE_NULL);
} }
if(Texture) if(texture_)
{ {
SDL_DestroyTexture(Texture); SDL_DestroyTexture(texture_);
Texture = NULL; texture_ = NULL;
} }
// FreeElements(); // FreeElements();
IsPlaying = false; isPlaying_ = false;
Height = 0; height_ = 0;
Width = 0; width_ = 0;
FrameReady = false; frameReady_ = false;
return true; return true;
} }
bool GStreamerVideo::Play(std::string file) bool GStreamerVideo::play(std::string file)
{ {
PlayCount = 0; playCount_ = 0;
if(!Initialized) if(!initialized_)
{ {
return false; return false;
} }
CurrentFile = file; currentFile_ = file;
const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL); const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL);
if(!uriFile) if(!uriFile)
@@ -208,91 +208,91 @@ bool GStreamerVideo::Play(std::string file)
} }
else else
{ {
Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file); Configuration::convertToAbsolutePath(Configuration::absolutePath, file);
file = uriFile; file = uriFile;
if(!Playbin) if(!playbin_)
{ {
Playbin = gst_element_factory_make("playbin", "player"); playbin_ = gst_element_factory_make("playbin", "player");
VideoBin = gst_bin_new("SinkBin"); videoBin_ = gst_bin_new("SinkBin");
VideoSink = gst_element_factory_make("fakesink", "video_sink"); videoSink_ = gst_element_factory_make("fakesink", "video_sink");
VideoConvert = gst_element_factory_make("capsfilter", "video_convert"); videoConvert_ = gst_element_factory_make("capsfilter", "video_convert");
VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2"); videoConvertCaps_ = gst_caps_from_string("video/x-raw,format=(string)YUY2");
Height = 0; height_ = 0;
Width = 0; width_ = 0;
if(!Playbin) if(!playbin_)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create playbin");
FreeElements(); freeElements();
return false; return false;
} }
if(!VideoSink) if(!videoSink_)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video sink");
FreeElements(); freeElements();
return false; return false;
} }
if(!VideoConvert) if(!videoConvert_)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video converter");
FreeElements(); freeElements();
return false; return false;
} }
if(!VideoConvertCaps) if(!videoConvertCaps_)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video caps");
FreeElements(); freeElements();
return false; return false;
} }
gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL); gst_bin_add_many(GST_BIN(videoBin_), videoConvert_, videoSink_, NULL);
gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps); gst_element_link_filtered(videoConvert_, videoSink_, videoConvertCaps_);
GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink"); GstPad *videoConvertSinkPad = gst_element_get_static_pad(videoConvert_, "sink");
if(!videoConvertSinkPad) if(!videoConvertSinkPad)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad");
FreeElements(); freeElements();
return false; return false;
} }
g_object_set(G_OBJECT(VideoSink), "sync", TRUE, "qos", FALSE, NULL); g_object_set(G_OBJECT(videoSink_), "sync", TRUE, "qos", FALSE, NULL);
GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad); GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad);
if(!videoSinkPad) if(!videoSinkPad)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad"); Logger::write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad");
FreeElements(); freeElements();
gst_object_unref(videoConvertSinkPad); gst_object_unref(videoConvertSinkPad);
videoConvertSinkPad = NULL; videoConvertSinkPad = NULL;
return false; return false;
} }
gst_element_add_pad(VideoBin, videoSinkPad); gst_element_add_pad(videoBin_, videoSinkPad);
gst_object_unref(videoConvertSinkPad); gst_object_unref(videoConvertSinkPad);
videoConvertSinkPad = NULL; videoConvertSinkPad = NULL;
} }
g_object_set(G_OBJECT(Playbin), "uri", file.c_str(), "video-sink", VideoBin, NULL); g_object_set(G_OBJECT(playbin_), "uri", file.c_str(), "video-sink", videoBin_, NULL);
IsPlaying = true; isPlaying_ = true;
g_object_set(G_OBJECT(VideoSink), "signal-handoffs", TRUE, NULL); g_object_set(G_OBJECT(videoSink_), "signal-handoffs", TRUE, NULL);
g_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this); g_signal_connect(videoSink_, "handoff", G_CALLBACK(processNewBuffer), this);
VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin)); videoBus_ = gst_pipeline_get_bus(GST_PIPELINE(playbin_));
gst_bus_add_watch(VideoBus, &BusCallback, this); gst_bus_add_watch(videoBus_, &busCallback, this);
/* Start playing */ /* Start playing */
GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(Playbin), GST_STATE_PLAYING); GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(playbin_), GST_STATE_PLAYING);
if (playState != GST_STATE_CHANGE_ASYNC) if (playState != GST_STATE_CHANGE_ASYNC)
{ {
IsPlaying = false; isPlaying_ = false;
std::stringstream ss; std::stringstream ss;
ss << "Unable to set the pipeline to the playing state: "; ss << "Unable to set the pipeline to the playing state: ";
ss << playState; ss << playState;
Logger::Write(Logger::ZONE_ERROR, "Video", ss.str()); Logger::write(Logger::ZONE_ERROR, "Video", ss.str());
FreeElements(); freeElements();
return false; return false;
} }
} }
@@ -300,88 +300,88 @@ bool GStreamerVideo::Play(std::string file)
return true; return true;
} }
void GStreamerVideo::FreeElements() void GStreamerVideo::freeElements()
{ {
if(VideoBin) if(videoBin_)
{ {
gst_object_unref(VideoBin); gst_object_unref(videoBin_);
VideoBin = NULL; videoBin_ = NULL;
} }
if(VideoSink) if(videoSink_)
{ {
gst_object_unref(VideoSink); gst_object_unref(videoSink_);
VideoSink = NULL; videoSink_ = NULL;
} }
if(VideoConvert) if(videoConvert_)
{ {
gst_object_unref(VideoConvert); gst_object_unref(videoConvert_);
VideoConvert = NULL; videoConvert_ = NULL;
} }
if(VideoConvertCaps) if(videoConvertCaps_)
{ {
gst_object_unref(VideoConvertCaps); gst_object_unref(videoConvertCaps_);
VideoConvertCaps = NULL; videoConvertCaps_ = NULL;
} }
if(Playbin) if(playbin_)
{ {
gst_object_unref(Playbin); gst_object_unref(playbin_);
Playbin = NULL; playbin_ = NULL;
} }
} }
int GStreamerVideo::GetHeight() int GStreamerVideo::getHeight()
{ {
return static_cast<int>(Height); return static_cast<int>(height_);
} }
int GStreamerVideo::GetWidth() int GStreamerVideo::getWidth()
{ {
return static_cast<int>(Width); return static_cast<int>(width_);
} }
void GStreamerVideo::Draw() void GStreamerVideo::draw()
{ {
FrameReady = false; frameReady_ = false;
} }
void GStreamerVideo::Update(float /* dt */) void GStreamerVideo::update(float /* dt */)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::getMutex());
if(!Texture && Width != 0 && Height != 0) if(!texture_ && width_ != 0 && height_ != 0)
{ {
Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2, texture_ = SDL_CreateTexture(SDL::getRenderer(), SDL_PIXELFORMAT_YUY2,
SDL_TEXTUREACCESS_STREAMING, Width, Height); SDL_TEXTUREACCESS_STREAMING, width_, height_);
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
} }
if(VideoBuffer && FrameReady && Texture && Width && Height) if(videoBuffer_ && frameReady_ && texture_ && width_ && height_)
{ {
//todo: change to width of cap //todo: change to width of cap
void *pixels; void *pixels;
int pitch; int pitch;
SDL_LockTexture(Texture, NULL, &pixels, &pitch); SDL_LockTexture(texture_, NULL, &pixels, &pitch);
memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number memcpy(pixels, videoBuffer_, width_*height_*2); //todo: magic number
SDL_UnlockTexture(Texture); SDL_UnlockTexture(texture_);
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::getMutex());
if(VideoBus) if(videoBus_)
{ {
GstMessage *msg = gst_bus_pop(VideoBus); GstMessage *msg = gst_bus_pop(videoBus_);
if(msg) if(msg)
{ {
if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS) if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS)
{ {
PlayCount++; playCount_++;
//todo: nesting hazard //todo: nesting hazard
// if number of loops is 0, set to infinite (todo: this is misleading, rename variable) // if number of loops is 0, set to infinite (todo: this is misleading, rename variable)
if(!NumLoops || NumLoops > PlayCount) if(!numLoops_ || numLoops_ > playCount_)
{ {
gst_element_seek(Playbin, gst_element_seek(playbin_,
1.0, 1.0,
GST_FORMAT_TIME, GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH, GST_SEEK_FLAG_FLUSH,

View File

@@ -29,38 +29,38 @@ class GStreamerVideo : public IVideo
public: public:
GStreamerVideo(); GStreamerVideo();
~GStreamerVideo(); ~GStreamerVideo();
bool Initialize(); bool initialize();
bool Play(std::string file); bool play(std::string file);
bool Stop(); bool stop();
bool DeInitialize(); bool deInitialize();
SDL_Texture *GetTexture() const; SDL_Texture *getTexture() const;
void Update(float dt); void update(float dt);
void Draw(); void draw();
void SetNumLoops(int n); void setNumLoops(int n);
void FreeElements(); void freeElements();
int GetHeight(); int getHeight();
int GetWidth(); int getWidth();
private: private:
static void ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data); static void processNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data);
static gboolean BusCallback(GstBus *bus, GstMessage *msg, gpointer data); static gboolean busCallback(GstBus *bus, GstMessage *msg, gpointer data);
GstElement *Playbin; GstElement *playbin_;
GstElement *VideoBin; GstElement *videoBin_;
GstElement *VideoSink; GstElement *videoSink_;
GstElement *VideoConvert; GstElement *videoConvert_;
GstCaps *VideoConvertCaps; GstCaps *videoConvertCaps_;
GstBus *VideoBus; GstBus *videoBus_;
SDL_Texture* Texture; SDL_Texture* texture_;
gint Height; gint height_;
gint Width; gint width_;
char *VideoBuffer; char *videoBuffer_;
gsize VideoBufferSize; gsize videoBufferSize_;
gsize MaxVideoBufferSize; gsize maxVideoBufferSize_;
bool FrameReady; bool frameReady_;
bool IsPlaying; bool isPlaying_;
static bool Initialized; static bool initialized_;
int PlayCount; int playCount_;
std::string CurrentFile; std::string currentFile_;
int NumLoops; int numLoops_;
}; };

View File

@@ -22,13 +22,13 @@ class IVideo
{ {
public: public:
virtual ~IVideo() {} virtual ~IVideo() {}
virtual bool Initialize() = 0; virtual bool initialize() = 0;
virtual bool Play(std::string file) = 0; virtual bool play(std::string file) = 0;
virtual bool Stop() = 0; virtual bool stop() = 0;
virtual bool DeInitialize() = 0; virtual bool deInitialize() = 0;
virtual SDL_Texture *GetTexture() const = 0; virtual SDL_Texture *getTexture() const = 0;
virtual void Update(float dt) = 0; virtual void update(float dt) = 0;
virtual void Draw() = 0; virtual void draw() = 0;
virtual int GetHeight() = 0; virtual int getHeight() = 0;
virtual int GetWidth() = 0; virtual int getWidth() = 0;
}; };

View File

@@ -18,29 +18,29 @@
#include "IVideo.h" #include "IVideo.h"
#include "GStreamerVideo.h" #include "GStreamerVideo.h"
bool VideoFactory::Enabled = true; bool VideoFactory::enabled_ = true;
int VideoFactory::NumLoops = 0; int VideoFactory::numLoops_ = 0;
IVideo *VideoFactory::Instance = NULL; IVideo *VideoFactory::instance_ = NULL;
IVideo *VideoFactory::CreateVideo() IVideo *VideoFactory::createVideo()
{ {
if(Enabled && !Instance) if(enabled_ && !instance_)
{ {
Instance = new GStreamerVideo(); instance_ = new GStreamerVideo();
Instance->Initialize(); instance_->initialize();
((GStreamerVideo *)(Instance))->SetNumLoops(NumLoops); ((GStreamerVideo *)(instance_))->setNumLoops(numLoops_);
} }
return Instance; return instance_;
} }
void VideoFactory::SetEnabled(bool enabled) void VideoFactory::setEnabled(bool enabled)
{ {
Enabled = enabled; enabled_ = enabled;
} }
void VideoFactory::SetNumLoops(int numLoops) void VideoFactory::setNumLoops(int numLoops)
{ {
NumLoops = numLoops; numLoops_ = numLoops;
} }

Some files were not shown because too many files have changed in this diff Show More