Merge with menusorting

This commit is contained in:
Don Honerbrink 2015-06-25 17:10:04 -05:00
commit b22dc3d72c
84 changed files with 2945 additions and 3538 deletions

View File

@ -20,6 +20,13 @@ list.includeMissingItems = true
###############################################################################
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
###############################################################################

View File

@ -4,3 +4,11 @@
# 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
###############################################################################
# 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
###############################################################################

View File

@ -25,77 +25,50 @@ CollectionInfo::CollectionInfo(std::string name,
std::string extensions,
std::string metadataType,
std::string metadataPath)
: Name(name)
, ListPath(listPath)
, Extensions(extensions)
, MetadataType(metadataType)
, MetadataPath(metadataPath)
: name(name)
, listpath(listPath)
, metadataType(metadataType)
, metadataPath_(metadataPath)
, extensions_(extensions)
{
}
CollectionInfo::~CollectionInfo()
{
std::vector<Item *>::iterator it = Items.begin();
std::vector<Item *>::iterator it = items.begin();
while(it != Items.end())
while(it != items.end())
{
delete *it;
Items.erase(it);
it = Items.begin();
items.erase(it);
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::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::istringstream ss(extensions_);
std::string token;
while(std::getline(ss, token, ','))
{
extensions.push_back(token);
extensionlist.push_back(token);
}
}
std::vector<Item *> *CollectionInfo::GetItems()
bool CollectionInfo::itemIsLess(Item *lhs, Item *rhs)
{
return &Items;
return lhs->lowercaseFullTitle() < rhs->lowercaseFullTitle();
}
bool CollectionInfo::ItemIsLess(Item const *lhs, Item const *rhs)
void CollectionInfo::sortItems()
{
return lhs->GetLCFullTitle() < rhs->GetLCFullTitle();
}
void CollectionInfo::SortItems()
{
std::sort(Items.begin(), Items.end(), ItemIsLess);
std::sort(items.begin(), items.end(), itemIsLess);
}

View File

@ -25,23 +25,17 @@ class CollectionInfo
public:
CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath);
virtual ~CollectionInfo();
std::string GetName() const;
std::string GetSettingsPath() const;
std::string GetListPath() const;
std::string GetMetadataType() const;
std::string GetMetadataPath() const;
std::string GetExtensions() const;
std::vector<Item *> *GetItems();
void SortItems();
void GetExtensions(std::vector<std::string> &extensions);
std::string settingsPath() const;
void sortItems();
void extensionList(std::vector<std::string> &extensions);
std::string name;
std::string listpath;
std::string metadataType;
std::vector<Item *> items;
private:
static bool ItemIsLess(Item const *lhs, Item const *rhs);
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>
CollectionInfoBuilder::CollectionInfoBuilder(Configuration &c, MetadataDatabase &mdb)
: Conf(c)
, MetaDB(mdb)
: conf_(c)
, 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;
paths.push_back(collectionPath);
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_front"));
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", "medium_back"));
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", "screentitle"));
paths.push_back(Utils::CombinePath(collectionPath, "medium_artwork", "video"));
paths.push_back(Utils::CombinePath(collectionPath, "roms"));
paths.push_back(Utils::CombinePath(collectionPath, "system_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_front"));
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", "medium_back"));
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", "screentitle"));
paths.push_back(Utils::combinePath(collectionPath, "medium_artwork", "video"));
paths.push_back(Utils::combinePath(collectionPath, "roms"));
paths.push_back(Utils::combinePath(collectionPath, "system_artwork"));
for(std::vector<std::string>::iterator it = paths.begin(); it != paths.end(); it++)
{
@ -89,7 +89,7 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
#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::ofstream includeFile;
@ -99,7 +99,7 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
includeFile << "# by settings.conf will be used" << std::endl;
includeFile.close();
filename = Utils::CombinePath(collectionPath, "exclude.txt");
filename = Utils::combinePath(collectionPath, "exclude.txt");
std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream excludeFile;
excludeFile.open(filename.c_str());
@ -107,31 +107,33 @@ 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;
excludeFile.close();
filename = Utils::CombinePath(collectionPath, "settings.conf");
filename = Utils::combinePath(collectionPath, "settings.conf");
std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream settingsFile;
settingsFile.open(filename.c_str());
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.extensions = zip" << std::endl;
settingsFile << "list.menuSort = yes" << std::endl;
settingsFile << std::endl;
settingsFile << "launcher = mame" << std::endl;
settingsFile << "metadata.type = MAME" << std::endl;
settingsFile << 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.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.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_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.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.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.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.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_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.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.close();
filename = Utils::CombinePath(collectionPath, "menu.xml");
filename = Utils::combinePath(collectionPath, "menu.xml");
std::cout << "Creating file \"" << filename << "\"" << std::endl;
std::ofstream menuFile;
menuFile.open(filename.c_str());
@ -151,7 +153,7 @@ bool CollectionInfoBuilder::CreateCollectionDirectory(std::string name)
return true;
}
CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name)
CollectionInfo *CollectionInfoBuilder::buildCollection(std::string name)
{
std::string listItemsPathKey = "collections." + name + ".list.path";
std::string listFilterKey = "collections." + name + ".list.filter";
@ -168,12 +170,12 @@ CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name)
std::string metadataType = name;
std::string metadataPath;
Conf.GetCollectionAbsolutePath(name, listItemsPath);
(void)Conf.GetProperty(extensionsKey, extensions);
(void)Conf.GetProperty(metadataTypeKey, metadataType);
(void)Conf.GetProperty(metadataPathKey, metadataPath);
conf_.getCollectionAbsolutePath(name, listItemsPath);
(void)conf_.getProperty(extensionsKey, extensions);
(void)conf_.getProperty(metadataTypeKey, metadataType);
(void)conf_.getProperty(metadataPathKey, metadataPath);
if(!Conf.GetProperty(launcherKey, launcherName))
if(!conf_.getProperty(launcherKey, launcherName))
{
std::stringstream ss;
ss << "\""
@ -183,7 +185,7 @@ CollectionInfo *CollectionInfoBuilder::BuildCollection(std::string name)
<< "). Your collection will be viewable, however you will not be able to "
<< "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);
@ -207,7 +209,7 @@ bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::stri
while(std::getline(includeStream, line))
{
line = Utils::FilterComments(line);
line = Utils::filterComments(line);
if(!line.empty() && list.find(line) == list.end())
{
@ -215,11 +217,10 @@ bool CollectionInfoBuilder::ImportBasicList(CollectionInfo * /*info*/, std::stri
line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() );
i->SetFullTitle(line);
i->SetName(line);
i->SetFullTitle(line);
i->SetTitle(line);
i->SetLauncher(launcher);
i->fullTitle = line;
i->name = line;
i->title = line;
i->launcher = launcher;
list[line] = i;
}
@ -232,16 +233,16 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
{
DIR *dp;
struct dirent *dirp;
std::string path = info->GetListPath();
std::string path = info->listpath;
std::map<std::string, Item *> includeFilter;
std::map<std::string, Item *> excludeFilter;
std::string includeFile = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", info->GetName(), "include.txt");
std::string excludeFile = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections", info->GetName(), "exclude.txt");
std::string includeFile = Utils::combinePath(Configuration::absolutePath, "collections", info->name, "include.txt");
std::string excludeFile = Utils::combinePath(Configuration::absolutePath, "collections", info->name, "exclude.txt");
std::string launcher;
bool showMissing = false;
(void)Conf.GetProperty("collections." + info->GetName() + ".launcher", launcher);
(void)Conf.GetProperty("collections." + info->GetName() + ".list.includeMissingItems", showMissing);
(void)conf_.getProperty("collections." + info->name + ".launcher", launcher);
(void)conf_.getProperty("collections." + info->name + ".list.includeMissingItems", showMissing);
ImportBasicList(info, includeFile, launcher, includeFilter);
ImportBasicList(info, excludeFile, launcher, excludeFilter);
@ -249,15 +250,15 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
std::vector<std::string> extensions;
std::vector<std::string>::iterator extensionsIt;
info->GetExtensions(extensions);
info->extensionList(extensions);
Logger::Write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Checking for \"" + includeFile + "\"");
Logger::write(Logger::ZONE_INFO, "CollectionInfoBuilder", "Checking for \"" + includeFile + "\"");
dp = opendir(path.c_str());
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;
}
@ -267,7 +268,7 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
{
if(excludeFilter.find(it->first) == excludeFilter.end())
{
info->GetItems()->push_back(it->second);
info->items.push_back(it->second);
}
}
}
@ -295,11 +296,11 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
if(file.compare(start, comparator.length(), *extensionsIt) == 0)
{
Item *i = new Item();
i->SetName(basename);
i->SetFullTitle(basename);
i->SetTitle(basename);
i->SetLauncher(launcher);
info->GetItems()->push_back(i);
i->name = basename;
i->fullTitle = basename;
i->title = basename;
i->launcher = launcher;
info->items.push_back(i);
}
}
}
@ -325,9 +326,9 @@ bool CollectionInfoBuilder::ImportDirectory(CollectionInfo *info)
excludeFilter.erase(it);
}
MetaDB.InjectMetadata(info);
metaDB_.injectMetadata(info);
info->SortItems();
info->sortItems();
return true;
}

View File

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

View File

@ -20,7 +20,7 @@
#include <algorithm>
Item::Item()
: Leaf(true)
: leaf(true)
{
}
@ -28,142 +28,24 @@ Item::~Item()
{
}
const std::string Item::GetFileName() const
std::string Item::filename()
{
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;
return Utils::getFileName(filepath);
}
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

@ -22,48 +22,20 @@ class Item
public:
Item();
virtual ~Item();
const std::string GetFileName() const;
const std::string& GetFilePath() const;
void SetFilePath(const std::string& filepath);
const std::string& GetLauncher() const;
void SetLauncher(const std::string& launcher);
const std::string& GetManufacturer() const;
void SetManufacturer(const std::string& manufacturer);
const std::string& GetGenre() const;
void SetGenre(const std::string& genre);
const std::string& GetName() const;
void SetName(const std::string& name);
void SetNumberButtons(std::string numberbuttons);
std::string GetNumberButtons() const;
void SetNumberPlayers(std::string numberplayers);
std::string GetNumberPlayers() const;
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;
std::string filename();
std::string lowercaseTitle() ;
std::string lowercaseFullTitle();
std::string name;
std::string launcher;
std::string filepath;
std::string title;
std::string fullTitle;
std::string year;
std::string manufacturer;
std::string genre;
std::string cloneof;
std::string numberPlayers;
std::string numberButtons;
bool leaf;
};

View File

@ -26,9 +26,9 @@
#include <fstream>
#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()
@ -40,15 +40,16 @@ MenuParser::~MenuParser()
}
//todo: clean up this method, too much nesting
bool MenuParser::GetMenuItems(CollectionInfo *collection)
bool MenuParser::buildMenuItems(CollectionInfo *collection, bool sort)
{
bool retVal = false;
//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_node<> * rootNode;
std::vector<Item *> menuItems;
Logger::Write(Logger::ZONE_INFO, "Menu", "Checking if menu exists at \"" + menuFilename + "\"");
Logger::write(Logger::ZONE_INFO, "Menu", "Checking if menu exists at \"" + menuFilename + "\"");
try
{
@ -73,7 +74,7 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
if(!collectionAttribute)
{
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;
}
//todo: too much nesting! Ack!
@ -88,17 +89,16 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
//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);
item->title = title;
item->fullTitle = title;
item->name = collectionAttribute->value();
item->leaf = false;
menuItems.push_back(item);
}
else
{
std::string collectionName = collectionAttribute->value();
Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName);
Logger::write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName);
//todo: unsupported option with this refactor
// need to append the collection
@ -106,8 +106,13 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
}
// todo: sorting should occur within the collection itself, not externally
std::vector<Item *> *items = collection->GetItems();
std::sort( items->begin(), items->end(), VectorSort);
if(sort)
{
// sort the menu if requested
std::sort( menuItems.begin(), menuItems.end(), VectorSort);
}
collection->items.insert(collection->items.begin(), menuItems.begin(), menuItems.end());
retVal = true;
}
@ -116,7 +121,7 @@ bool MenuParser::GetMenuItems(CollectionInfo *collection)
{
std::stringstream ss;
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;

View File

@ -22,6 +22,6 @@ class MenuParser
public:
MenuParser();
virtual ~MenuParser();
bool GetMenuItems(CollectionInfo *cdb);
bool buildMenuItems(CollectionInfo *cdb, bool sort);
};

View File

@ -19,7 +19,7 @@
#include "../Utility/Log.h"
UserInput::UserInput(Configuration &c)
: Config(c)
: config_(c)
{
}
@ -27,7 +27,7 @@ UserInput::~UserInput()
{
}
bool UserInput::Initialize()
bool UserInput::initialize()
{
bool retVal = true;
@ -62,12 +62,12 @@ bool UserInput::Initialize()
return retVal;
}
SDL_Scancode UserInput::GetScancode(KeyCode_E key)
SDL_Scancode UserInput::scancode(KeyCode_E key)
{
SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN;
std::map<KeyCode_E, SDL_Scancode>::iterator it = KeyMap.find(key);
std::map<KeyCode_E, SDL_Scancode>::iterator it = keyMap_.find(key);
if(it != KeyMap.end())
if(it != keyMap_.end())
{
scancode = it->second;
}
@ -76,13 +76,13 @@ SDL_Scancode UserInput::GetScancode(KeyCode_E key)
}
UserInput::KeyCode_E UserInput::GetKeycode(SDL_Scancode scancode)
UserInput::KeyCode_E UserInput::keycode(SDL_Scancode scancode)
{
KeyCode_E keycode = KeyCodeNull;
std::map<SDL_Scancode, KeyCode_E>::iterator it = ReverseKeyMap.find(scancode);
std::map<SDL_Scancode, KeyCode_E>::iterator it = reverseKeyMap_.find(scancode);
if(it != ReverseKeyMap.end())
if(it != reverseKeyMap_.end())
{
keycode = it->second;
}
@ -90,9 +90,9 @@ UserInput::KeyCode_E UserInput::GetKeycode(SDL_Scancode scancode)
return keycode;
}
void UserInput::ResetKeyStates()
void UserInput::resetKeyStates()
{
for(std::map<KeyCode_E, bool>::iterator it = KeyState.begin(); it != KeyState.end(); it++)
for(std::map<KeyCode_E, bool>::iterator it = keyState_.begin(); it != keyState_.end(); it++)
{
it->second = false;
}
@ -106,9 +106,9 @@ bool UserInput::MapKey(std::string keyDescription, KeyCode_E key)
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, "Configuration", "Missing property " + configKey);
return false;
}
@ -116,31 +116,31 @@ bool UserInput::MapKey(std::string keyDescription, KeyCode_E key)
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_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs");
return false;
}
KeyMap[key] = scanCode;
ReverseKeyMap[scanCode] = key;
KeyState[key] = false;
keyMap_[key] = scanCode;
reverseKeyMap_[scanCode] = key;
keyState_[key] = false;
return true;
}
bool UserInput::SetKeyState(SDL_Scancode code, bool state)
bool UserInput::keystate(SDL_Scancode code, bool state)
{
KeyCode_E key = GetKeycode(code);
KeyCode_E key = keycode(code);
if(key == KeyCodeNull) { return false; }
if(KeyState.find(key) == KeyState.end()) { return false; }
if(keyState_.find(key) == keyState_.end()) { return false; }
KeyState[key] = state;
keyState_[key] = state;
return true;
}
bool UserInput::GetKeyState(KeyCode_E key)
bool UserInput::keystate(KeyCode_E key)
{
if(KeyState.find(key) == KeyState.end()) { return false; }
return KeyState[key];
if(keyState_.find(key) == keyState_.end()) { return false; }
return keyState_[key];
}

View File

@ -43,21 +43,21 @@ public:
UserInput(Configuration &c);
virtual ~UserInput();
bool Initialize();
SDL_Scancode GetScancode(KeyCode_E key);
KeyCode_E GetKeycode(SDL_Scancode scancode);
bool SetKeyState(SDL_Scancode code, bool state);
bool GetKeyState(KeyCode_E key);
bool KeyStateChanged();
void ResetKeyStates();
bool initialize();
SDL_Scancode scancode(KeyCode_E key);
KeyCode_E keycode(SDL_Scancode scancode);
bool keystate(SDL_Scancode code, bool state);
bool keystate(KeyCode_E key);
bool keyStateChanged();
void resetKeyStates();
private:
bool MapKey(std::string keyDescription, KeyCode_E key);
std::map<KeyCode_E, SDL_Scancode> KeyMap;
std::map<SDL_Scancode, KeyCode_E> ReverseKeyMap;
std::map<KeyCode_E, bool> KeyState;
Configuration &Config;
const Uint8 *SDLKeys;
std::map<KeyCode_E, SDL_Scancode> keyMap_;
std::map<SDL_Scancode, KeyCode_E> reverseKeyMap_;
std::map<KeyCode_E, bool> keyState_;
Configuration &config_;
const Uint8 *sdlkeys_;
};

View File

@ -28,10 +28,9 @@
#include <unistd.h>
#endif
std::string Configuration::AbsolutePath;
std::string Configuration::absolutePath;
Configuration::Configuration()
: Verbose(false)
{
}
@ -39,14 +38,14 @@ Configuration::~Configuration()
{
}
void Configuration::Initialize()
void Configuration::initialize()
{
const char *environment = std::getenv("RETROFE_PATH");
std::string environmentStr;
if (environment != NULL)
{
environmentStr = environment;
Configuration::SetAbsolutePath(environment);
absolutePath = environment;
}
else
{
@ -55,44 +54,34 @@ void Configuration::Initialize()
CHAR exe[MAX_PATH];
GetModuleFileName(hModule, exe, MAX_PATH);
std::string sPath(exe);
sPath = Utils::GetDirectory(sPath);
sPath = Utils::getDirectory(sPath);
sPath = Utils::GetParentDirectory(sPath);
#else
char exepath[1024];
sprintf(exepath, "/proc/%d/exe", getpid());
readlink(exepath, exepath, sizeof(exepath));
std::string sPath(exepath);
sPath = Utils::GetDirectory(sPath);
sPath = Utils::getDirectory(sPath);
#endif
Configuration::SetAbsolutePath(sPath);
absolutePath = sPath;
}
}
void Configuration::SetCurrentCollection(std::string collection)
{
CurrentCollection = collection;
}
std::string Configuration::GetCurrentCollection()
{
return CurrentCollection;
}
bool Configuration::Import(std::string keyPrefix, std::string file)
bool Configuration::import(std::string keyPrefix, std::string file)
{
bool retVal = true;
int lineCount = 0;
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());
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;
}
@ -100,7 +89,7 @@ bool Configuration::Import(std::string keyPrefix, std::string file)
while (std::getline (ifs, line))
{
lineCount++;
retVal = retVal && ParseLine(keyPrefix, line, lineCount);
retVal = retVal && parseLine(keyPrefix, line, lineCount);
}
ifs.close();
@ -108,7 +97,7 @@ bool Configuration::Import(std::string keyPrefix, std::string file)
return retVal;
}
bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineCount)
bool Configuration::parseLine(std::string keyPrefix, std::string line, int lineCount)
{
bool retVal = false;
std::string key;
@ -117,7 +106,7 @@ bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineC
std::string delimiter = "=";
// 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))
{
@ -133,32 +122,32 @@ bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineC
key = keyPrefix + line.substr(0, position);
key = TrimEnds(key);
key = trimEnds(key);
value = line.substr(position + delimiter.length(), line.length());
value = TrimEnds(value);
value = trimEnds(value);
Properties.insert(PropertiesPair(key, value));
properties_.insert(PropertiesPair(key, value));
std::stringstream ss;
ss << "Dump: " << "\"" << key << "\" = \"" << value << "\"";
Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str());
Logger::write(Logger::ZONE_INFO, "Configuration", ss.str());
retVal = true;
}
else
{
std::stringstream ss;
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;
}
std::string Configuration::TrimEnds(std::string str)
std::string Configuration::trimEnds(std::string str)
{
// strip off any initial tabs or spaces
size_t trimStart = str.find_first_not_of(" \t");
@ -173,46 +162,42 @@ std::string Configuration::TrimEnds(std::string str)
return str;
}
bool Configuration::GetRawProperty(std::string key, std::string &value)
bool Configuration::getRawProperty(std::string key, std::string &value)
{
bool retVal = false;
if(Properties.find(key) != Properties.end())
if(properties_.find(key) != properties_.end())
{
value = Properties[key];
value = properties_[key];
retVal = true;
}
else if(Verbose)
{
Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key);
}
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 baseItemPath = GetAbsolutePath();
std::string baseMediaPath = absolutePath;
std::string baseItemPath = absolutePath;
std::string collectionName;
GetRawProperty("baseMediaPath", baseMediaPath);
GetRawProperty("baseItemPath", baseItemPath);
collectionName = GetCurrentCollection();
getRawProperty("currentCollection", collectionName);
getRawProperty("baseMediaPath", baseMediaPath);
getRawProperty("baseItemPath", baseItemPath);
value = Utils::Replace(value, "%BASE_MEDIA_PATH%", baseMediaPath);
value = Utils::Replace(value, "%BASE_ITEM_PATH%", baseItemPath);
value = Utils::Replace(value, "%ITEM_COLLECTION_NAME%", collectionName);
value = Utils::replace(value, "%BASE_MEDIA_PATH%", baseMediaPath);
value = Utils::replace(value, "%BASE_ITEM_PATH%", baseItemPath);
value = Utils::replace(value, "%ITEM_COLLECTION_NAME%", collectionName);
return retVal;
}
bool Configuration::GetProperty(std::string key, int &value)
bool Configuration::getProperty(std::string key, int &value)
{
std::string strValue;
bool retVal = GetProperty(key, strValue);
bool retVal = getProperty(key, strValue);
if(retVal)
{
@ -224,11 +209,11 @@ bool Configuration::GetProperty(std::string key, int &value)
return retVal;
}
bool Configuration::GetProperty(std::string key, bool &value)
bool Configuration::getProperty(std::string key, bool &value)
{
std::string strValue;
bool retVal = GetProperty(key, strValue);
bool retVal = getProperty(key, strValue);
if(retVal)
{
@ -245,21 +230,21 @@ bool Configuration::GetProperty(std::string key, bool &value)
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;
for(it = Properties.begin(); it != Properties.end(); ++it)
for(it = properties_.begin(); it != properties_.end(); ++it)
{
std::string search = key + ".";
if(it->first.compare(0, search.length(), search) == 0)
@ -271,16 +256,16 @@ bool Configuration::PropertyPrefixExists(std::string key)
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;
for(it = Properties.begin(); it != Properties.end(); ++it)
for(it = properties_.begin(); it != properties_.end(); ++it)
{
std::string search = parent + ".";
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(".");
@ -297,7 +282,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 second = ' ';
@ -312,128 +297,98 @@ std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string
}
// check to see if it is already an absolute path
if((first != Utils::PathSeparator) &&
if((first != Utils::pathSeparator) &&
//(first != '.') &&
(second != ':'))
{
path = Utils::CombinePath(prefix, path);
path = Utils::combinePath(prefix, 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)
{
value = ConvertToAbsolutePath(GetAbsolutePath(), value);
value = convertToAbsolutePath(absolutePath, value);
}
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;
// use user-overridden setting if it exists
if(GetPropertyAbsolutePath(key, value))
if(getPropertyAbsolutePath(key, value))
{
return;
}
// use user-overridden base media path if it was specified
std::string baseMediaPath;
if(!GetPropertyAbsolutePath("baseMediaPath", baseMediaPath))
if(!getPropertyAbsolutePath("baseMediaPath", baseMediaPath))
{
// 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")
{
value = Utils::CombinePath(baseMediaPath, "_manufacturer");
value = Utils::combinePath(baseMediaPath, "_manufacturer");
}
else if(mediaType == "genre")
{
value = Utils::CombinePath(baseMediaPath, "_genre");
value = Utils::combinePath(baseMediaPath, "_genre");
}
else if(mediaType == "year")
{
value = Utils::CombinePath(baseMediaPath, "_year");
value = Utils::combinePath(baseMediaPath, "_year");
}
else if(mediaType == "number_players")
{
value = Utils::CombinePath(baseMediaPath, "_number_players");
value = Utils::combinePath(baseMediaPath, "_number_players");
}
else if(mediaType == "number_buttons")
{
value = Utils::CombinePath(baseMediaPath, "_number_buttons");
value = Utils::combinePath(baseMediaPath, "_number_buttons");
}
else if(system)
{
value = Utils::CombinePath(baseMediaPath, collectionName, "system_artwork");
value = Utils::combinePath(baseMediaPath, collectionName, "system_artwork");
}
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";
if(GetPropertyAbsolutePath(key, value))
if(getPropertyAbsolutePath(key, value))
{
return;
}
std::string baseItemPath;
if(GetPropertyAbsolutePath("baseItemPath", baseItemPath))
if(getPropertyAbsolutePath("baseItemPath", baseItemPath))
{
value = Utils::CombinePath(baseItemPath, collectionName);
value = Utils::combinePath(baseItemPath, collectionName);
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,30 @@ class Configuration
public:
Configuration();
virtual ~Configuration();
static void Initialize();
static void SetAbsolutePath(std::string absolutePath);
static std::string GetAbsolutePath();
static std::string ConvertToAbsolutePath(std::string prefix, std::string path);
void SetStatus(std::string status);
std::string GetStatus();
static void initialize();
static std::string convertToAbsolutePath(std::string prefix, std::string path);
// gets the global configuration
bool Import(std::string keyPrefix, std::string file);
void SetCurrentCollection(std::string collection);
std::string GetCurrentCollection();
bool GetProperty(std::string key, std::string &value);
bool GetProperty(std::string key, int &value);
bool GetProperty(std::string key, bool &value);
void GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children);
void SetProperty(std::string key, std::string value);
bool PropertyExists(std::string key);
bool PropertyPrefixExists(std::string key);
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, bool system, std::string &value);
void GetCollectionAbsolutePath(std::string collectionName, std::string &value);
bool IsVerbose() const;
void SetVerbose(bool verbose);
bool import(std::string keyPrefix, std::string file);
bool getProperty(std::string key, std::string &value);
bool getProperty(std::string key, int &value);
bool getProperty(std::string key, bool &value);
void childKeyCrumbs(std::string parent, std::vector<std::string> &children);
void setProperty(std::string key, std::string value);
bool propertyExists(std::string key);
bool propertyPrefixExists(std::string key);
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, bool system, std::string &value);
void getCollectionAbsolutePath(std::string collectionName, std::string &value);
static std::string absolutePath;
private:
bool GetRawProperty(std::string key, std::string &value);
bool ParseLine(std::string keyPrefix, std::string line, int lineCount);
std::string TrimEnds(std::string str);
bool getRawProperty(std::string key, std::string &value);
bool parseLine(std::string keyPrefix, std::string line, int lineCount);
std::string trimEnds(std::string str);
typedef std::map<std::string, std::string> PropertiesType;
typedef std::pair<std::string, std::string> PropertiesPair;
bool Verbose;
static std::string AbsolutePath;
std::string CurrentCollection;
PropertiesType Properties;
std::string Status;
PropertiesType properties_;
};

View File

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

View File

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

View File

@ -20,5 +20,5 @@ class Metadata
{
public:
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>
MetadataDatabase::MetadataDatabase(DB &db, Configuration &c)
: Config(c)
, DBInstance(db)
: config_(c)
, db_(db)
{
}
@ -44,13 +44,13 @@ MetadataDatabase::~MetadataDatabase()
{
}
bool MetadataDatabase::ResetDatabase()
bool MetadataDatabase::resetDatabase()
{
int rc;
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;
sql.append("DROP TABLE IF EXISTS Meta;");
@ -61,18 +61,18 @@ bool MetadataDatabase::ResetDatabase()
{
std::stringstream ss;
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 Initialize();
return initialize();
}
bool MetadataDatabase::Initialize()
bool MetadataDatabase::initialize()
{
int rc;
char *error = NULL;
sqlite3 *handle = DBInstance.GetHandle();
sqlite3 *handle = db_.handle;
std::string sql;
sql.append("CREATE TABLE IF NOT EXISTS Meta(");
@ -93,31 +93,31 @@ bool MetadataDatabase::Initialize()
{
std::stringstream ss;
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;
}
if(NeedsRefresh())
if(needsRefresh())
{
ImportDirectory();
importDirectory();
}
return true;
}
bool MetadataDatabase::ImportDirectory()
bool MetadataDatabase::importDirectory()
{
DIR *dp;
struct dirent *dirp;
std::string hyperListPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "meta", "hyperlist");
std::string mameListPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "meta", "mamelist");
std::string hyperListPath = Utils::combinePath(Configuration::absolutePath, "meta", "hyperlist");
std::string mameListPath = Utils::combinePath(Configuration::absolutePath, "meta", "mamelist");
dp = opendir(hyperListPath.c_str());
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
{
@ -135,9 +135,9 @@ bool MetadataDatabase::ImportDirectory()
if(extension == ".xml")
{
std::string importFile = Utils::CombinePath(hyperListPath, std::string(dirp->d_name));
Logger::Write(Logger::ZONE_INFO, "Metadata", "Importing hyperlist: " + importFile);
ImportHyperList(importFile, collectionName);
std::string importFile = Utils::combinePath(hyperListPath, std::string(dirp->d_name));
Logger::write(Logger::ZONE_INFO, "Metadata", "Importing hyperlist: " + importFile);
importHyperlist(importFile, collectionName);
}
}
}
@ -149,7 +149,7 @@ bool MetadataDatabase::ImportDirectory()
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
{
@ -167,10 +167,10 @@ bool MetadataDatabase::ImportDirectory()
if(extension == ".xml")
{
std::string importFile = Utils::CombinePath(mameListPath, std::string(dirp->d_name));
Logger::Write(Logger::ZONE_INFO, "Metadata", "Importing mamelist: " + importFile);
Config.SetStatus("Scraping data from " + importFile);
ImportMameList(importFile, collectionName);
std::string importFile = Utils::combinePath(mameListPath, std::string(dirp->d_name));
Logger::write(Logger::ZONE_INFO, "Metadata", "Importing mamelist: " + importFile);
config_.setProperty("status", "Scraping data from " + importFile);
importMamelist(importFile, collectionName);
}
}
}
@ -181,26 +181,26 @@ bool MetadataDatabase::ImportDirectory()
return true;
}
void MetadataDatabase::InjectMetadata(CollectionInfo *collection)
void MetadataDatabase::injectMetadata(CollectionInfo *collection)
{
sqlite3 *handle = DBInstance.GetHandle();
sqlite3 *handle = db_.handle;
int rc;
sqlite3_stmt *stmt;
bool showParenthesis = true;
bool showSquareBrackets = true;
(void)Config.GetProperty("showParenthesis", showParenthesis);
(void)Config.GetProperty("showSquareBrackets", showSquareBrackets);
(void)config_.getProperty("showParenthesis", showParenthesis);
(void)config_.getProperty("showSquareBrackets", showSquareBrackets);
// 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;
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
@ -209,7 +209,7 @@ void MetadataDatabase::InjectMetadata(CollectionInfo *collection)
"FROM Meta WHERE collectionName=? ORDER BY title ASC;",
-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);
@ -265,22 +265,22 @@ void MetadataDatabase::InjectMetadata(CollectionInfo *collection)
if(it != itemMap.end())
{
Item *item = it->second;
item->SetTitle(title);
item->SetFullTitle(fullTitle);
item->SetYear(year);
item->SetManufacturer(manufacturer);
item->SetGenre(genre);
item->SetNumberPlayers(numberPlayers);
item->SetNumberButtons(numberButtons);
item->SetCloneOf(cloneOf);
item->title = title;
item->fullTitle = fullTitle;
item->year = year;
item->manufacturer = manufacturer;
item->genre = genre;
item->numberPlayers = numberPlayers;
item->numberButtons = numberButtons;
item->cloneof = cloneOf;
}
rc = sqlite3_step(stmt);
}
}
bool MetadataDatabase::NeedsRefresh()
bool MetadataDatabase::needsRefresh()
{
sqlite3 *handle = DBInstance.GetHandle();
sqlite3 *handle = db_.handle;
sqlite3_stmt *stmt;
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;
Config.SetStatus("Scraping data from \"" + hyperlistFile + "\"");
config_.setProperty("status", "Scraping data from \"" + hyperlistFile + "\"");
rapidxml::xml_document<> doc;
std::ifstream file(hyperlistFile.c_str());
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)
{
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;
}
sqlite3 *handle = DBInstance.GetHandle();
sqlite3 *handle = db_.handle;
sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error);
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);
}
}
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);
return true;
@ -378,28 +378,28 @@ bool MetadataDatabase::ImportHyperList(std::string hyperlistFile, std::string co
std::stringstream ss;
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)
{
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;
}
bool MetadataDatabase::ImportMameList(std::string filename, std::string collectionName)
bool MetadataDatabase::importMamelist(std::string filename, std::string collectionName)
{
rapidxml::xml_document<> doc;
rapidxml::xml_node<> * rootNode;
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::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)
{
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;
}
@ -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);
return true;

View File

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

View File

@ -19,45 +19,41 @@
#include <cstdlib>
AttractMode::AttractMode()
: IsActive(false)
, ElapsedTime(0)
, ActiveTime(0)
, IdleTime(0)
: idleTime(0)
, isActive_(false)
, elapsedTime_(0)
, activeTime_(0)
{
}
void AttractMode::SetIdleTime(float time)
void AttractMode::reset()
{
IdleTime = time;
}
void AttractMode::Reset()
{
ElapsedTime = 0;
IsActive = false;
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.
if(!IsActive && ElapsedTime > IdleTime && IdleTime > 0)
if(!isActive_ && elapsedTime_ > idleTime && idleTime > 0)
{
IsActive = true;
ElapsedTime = 0;
ActiveTime = ((float)((1000+rand()) % 5000)) / 1000;
isActive_ = true;
elapsedTime_ = 0;
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;
IsActive = false;
page.SetScrolling(Page::ScrollDirectionIdle);
elapsedTime_ = 0;
isActive_ = false;
page.setScrolling(Page::ScrollDirectionIdle);
}
}
}
}

View File

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

View File

@ -31,109 +31,109 @@
#endif
Launcher::Launcher(RetroFE &p, Configuration &c)
: Config(c)
, RetroFEInst(p)
: config_(c)
, 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->launcher;
std::string executablePath;
std::string selectedItemsDirectory;
std::string selectedItemsPath;
std::string currentDirectory;
std::string extensions;
std::string extensionstr;
std::string matchedExtension;
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;
}
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;
}
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;
}
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;
}
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
return false;
}
args = ReplaceVariables(args,
args = replaceVariables(args,
selectedItemsPath,
collectionItem->GetName(),
collectionItem->GetFileName(),
collectionItem->name,
collectionItem->filename(),
selectedItemsDirectory,
collection);
executablePath = ReplaceVariables(executablePath,
executablePath = replaceVariables(executablePath,
selectedItemsPath,
collectionItem->GetName(),
collectionItem->GetFileName(),
collectionItem->name,
collectionItem->filename(),
selectedItemsDirectory,
collection);
currentDirectory = ReplaceVariables(currentDirectory,
currentDirectory = replaceVariables(currentDirectory,
selectedItemsPath,
collectionItem->GetName(),
collectionItem->GetFileName(),
collectionItem->name,
collectionItem->filename(),
selectedItemsDirectory,
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 true;
}
std::string Launcher::ReplaceVariables(std::string str,
std::string Launcher::replaceVariables(std::string str,
std::string itemFilePath,
std::string itemName,
std::string itemFilename,
std::string itemDirectory,
std::string itemCollectionName)
{
str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath);
str = Utils::Replace(str, "%ITEM_NAME%", itemName);
str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename);
str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory);
str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName);
str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath());
str = Utils::replace(str, "%ITEM_FILEPATH%", itemFilePath);
str = Utils::replace(str, "%ITEM_NAME%", itemName);
str = Utils::replace(str, "%ITEM_FILENAME%", itemFilename);
str = Utils::replace(str, "%ITEM_DIRECTORY%", itemDirectory);
str = Utils::replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName);
str = Utils::replace(str, "%RETROFE_PATH%", Configuration::absolutePath);
#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
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
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;
std::string executionString = "\"" + executable + "\" " + args;
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", "Attempting to launch: " + executionString);
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)
RetroFEInst.LaunchEnter();
retrofe_.launchEnter();
#ifdef WIN32
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))
#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)
{
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)
#endif
{
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable);
Logger::write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable);
}
else
@ -183,18 +183,18 @@ bool Launcher::ExecuteCommand(std::string executable, std::string args, std::str
retVal = true;
}
Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed");
RetroFEInst.LaunchExit();
Logger::write(Logger::ZONE_INFO, "Launcher", "Completed");
retrofe_.launchExit();
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";
// find the launcher for the particular item
if(!Config.GetProperty(launcherKey, launcherName))
if(!config_.getProperty(launcherKey, launcherName))
{
std::stringstream ss;
@ -204,7 +204,7 @@ bool Launcher::GetLauncherName(std::string &launcherName, std::string collection
<< launcherKey
<< "\")";
Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str());
Logger::write(Logger::ZONE_ERROR, "Launcher", ss.str());
return false;
}
@ -216,71 +216,71 @@ bool Launcher::GetLauncherName(std::string &launcherName, std::string collection
<< launcherName
<< "\"";
Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str());
Logger::write(Logger::ZONE_DEBUG, "Launcher", ss.str());
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";
if(!Config.GetProperty(executableKey, executable))
if(!config_.getProperty(executableKey, executable))
{
return false;
}
std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory";
currentDirectory = Utils::GetDirectory(executable);
currentDirectory = Utils::getDirectory(executable);
Config.GetProperty(currentDirectoryKey, currentDirectory);
config_.getProperty(currentDirectoryKey, currentDirectory);
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";
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 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";
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;
}
extensions = Utils::Replace(extensions, " ", "");
extensions = Utils::Replace(extensions, ".", "");
extensions = Utils::replace(extensions, " ", "");
extensions = Utils::replace(extensions, ".", "");
return true;
}
bool Launcher::GetCollectionDirectory(std::string &directory, std::string collection)
bool Launcher::collectionDirectory(std::string &directory, std::string collection)
{
std::string itemsPathValue;
// find the items path folder (i.e. ROM path)
Config.GetCollectionAbsolutePath(collection, itemsPathValue);
directory += itemsPathValue + Utils::PathSeparator;
config_.getCollectionAbsolutePath(collection, itemsPathValue);
directory += itemsPathValue + Utils::pathSeparator;
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;
bool fileFound = false;
@ -301,7 +301,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
fileFound = true;
Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str());
Logger::write(Logger::ZONE_INFO, "Launcher", ss.str());
foundFilePath = selectedItemsPath;
foundFilename = extension;
@ -313,7 +313,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
ss << "Checking to see if \""
<< selectedItemsPath << "\" exists [No]";
Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str());
Logger::write(Logger::ZONE_WARNING, "Launcher", ss.str());
}
f.close();
@ -328,7 +328,7 @@ bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename,
<< filenameWithoutExtension << "\" in folder \""
<< 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:
Launcher(RetroFE &p, Configuration &c);
bool Run(std::string collection, Item *collectionItem);
bool run(std::string collection, Item *collectionItem);
private:
std::string ReplaceString(
std::string replaceString(
std::string subject,
const std::string &search,
const std::string &replace);
bool GetLauncherName(std::string &launcherName, std::string collection);
bool GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName);
bool GetLauncherArgs(std::string &args, std::string launcherName);
bool GetExtensions(std::string &extensions, std::string launcherName);
bool GetCollectionDirectory(std::string &directory, std::string collection);
bool ExecuteCommand(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);
std::string ReplaceVariables(std::string str,
bool launcherName(std::string &launcherName, std::string collection);
bool launcherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName);
bool launcherArgs(std::string &args, std::string launcherName);
bool extensions(std::string &extensions, std::string launcherName);
bool collectionDirectory(std::string &directory, std::string collection);
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);
std::string replaceVariables(std::string str,
std::string itemFilePath,
std::string itemName,
std::string itemFilename,
std::string itemDirectory,
std::string itemCollectionName);
Configuration &Config;
RetroFE &RetroFEInst;
Configuration &config_;
RetroFE &retrofe_;
};

View File

@ -23,7 +23,7 @@ Animation::Animation()
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));
}
@ -35,34 +35,34 @@ Animation::~Animation()
void Animation::Push(TweenSet *set)
{
AnimationVector.push_back(set);
animationVector_.push_back(set);
}
void Animation::Clear()
{
std::vector<TweenSet *>::iterator it = AnimationVector.begin();
while(it != AnimationVector.end())
std::vector<TweenSet *>::iterator it = animationVector_.begin();
while(it != animationVector_.end())
{
delete *it;
AnimationVector.erase(it);
it = AnimationVector.begin();
animationVector_.erase(it);
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();
void Push(TweenSet *set);
void Clear();
std::vector<TweenSet *> *GetTweenSets();
TweenSet *GetTweenSet(unsigned int index);
unsigned int GetSize();
std::vector<TweenSet *> *tweenSets();
TweenSet *tweenSet(unsigned int index);
unsigned int size();
private:
std::vector<TweenSet *> AnimationVector;
std::vector<TweenSet *> animationVector_;
};

View File

@ -25,55 +25,55 @@ AnimationEvents::AnimationEvents()
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++)
{
Animation *t = new Animation(*it2->second);
AnimationMap[it->first][it2->first] = t;
animationMap_[it->first][it2->first] = t;
}
}
}
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;
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();
while(it != AnimationMap.end())
std::map<std::string, std::map<int, Animation *> >::iterator it = animationMap_.begin();
while(it != animationMap_.end())
{
std::map<int, Animation *>::iterator it2 = (it->second).begin();
while(it2 != (it->second).end())
@ -83,11 +83,11 @@ void AnimationEvents::Clear()
}
(it->second).clear();
AnimationMap.erase(it);
it = AnimationMap.begin();
animationMap_.erase(it);
it = animationMap_.begin();
}
AnimationMap.clear();
animationMap_.clear();
}

View File

@ -28,11 +28,11 @@ public:
AnimationEvents(AnimationEvents &copy);
~AnimationEvents();
Animation *GetAnimation(std::string tween);
Animation *GetAnimation(std::string tween, int index);
void SetAnimation(std::string tween, int index, Animation *animation);
void Clear();
Animation *getAnimation(std::string tween);
Animation *getAnimation(std::string tween, int index);
void setAnimation(std::string tween, int index, Animation *animation);
void clear();
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 <string>
std::map<std::string, TweenAlgorithm> Tween::TweenTypeMap;
std::map<std::string, TweenProperty> Tween::TweenPropertyMap;
std::map<std::string, TweenAlgorithm> Tween::tweenTypeMap_;
std::map<std::string, TweenProperty> Tween::tweenPropertyMap_;
Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration)
: Property(property)
, Type(type)
, Start(start)
, End(end)
, Duration(duration)
: property(property)
, duration(duration)
, type(type)
, start(start)
, 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;
if(TweenPropertyMap.size() == 0)
if(tweenPropertyMap_.size() == 0)
{
TweenPropertyMap["x"] = TWEEN_PROPERTY_X;
TweenPropertyMap["y"] = TWEEN_PROPERTY_Y;
TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE;
TweenPropertyMap["alpha"] = TWEEN_PROPERTY_ALPHA;
TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH;
TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT;
TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN;
TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN;
TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET;
TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET;
TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE;
TweenPropertyMap["backgroundalpha"] = TWEEN_PROPERTY_BACKGROUND_ALPHA;
tweenPropertyMap_["x"] = TWEEN_PROPERTY_X;
tweenPropertyMap_["y"] = TWEEN_PROPERTY_Y;
tweenPropertyMap_["angle"] = TWEEN_PROPERTY_ANGLE;
tweenPropertyMap_["alpha"] = TWEEN_PROPERTY_ALPHA;
tweenPropertyMap_["width"] = TWEEN_PROPERTY_WIDTH;
tweenPropertyMap_["height"] = TWEEN_PROPERTY_HEIGHT;
tweenPropertyMap_["xorigin"] = TWEEN_PROPERTY_X_ORIGIN;
tweenPropertyMap_["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN;
tweenPropertyMap_["xoffset"] = TWEEN_PROPERTY_X_OFFSET;
tweenPropertyMap_["yoffset"] = TWEEN_PROPERTY_Y_OFFSET;
tweenPropertyMap_["fontSize"] = TWEEN_PROPERTY_FONT_SIZE;
tweenPropertyMap_["backgroundalpha"] = TWEEN_PROPERTY_BACKGROUND_ALPHA;
}
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;
}
@ -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["easeoutquadratic"] = EASE_OUT_QUADRATIC;
TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC;
TweenTypeMap["easeincubic"] = EASE_IN_CUBIC;
TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC;
TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC;
TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC;
TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC;
TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC;
TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC;
TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC;
TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC;
TweenTypeMap["easeinsine"] = EASE_IN_SINE;
TweenTypeMap["easeoutsine"] = EASE_OUT_SINE;
TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE;
TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL;
TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL;
TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL;
TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR;
TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR;
TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR;
TweenTypeMap["linear"] = LINEAR;
tweenTypeMap_["easeInquadratic"] = EASE_IN_QUADRATIC;
tweenTypeMap_["easeOutquadratic"] = EASE_OUT_QUADRATIC;
tweenTypeMap_["easeInoutquadratic"] = EASE_INOUT_QUADRATIC;
tweenTypeMap_["easeIncubic"] = EASE_IN_CUBIC;
tweenTypeMap_["easeOutcubic"] = EASE_OUT_CUBIC;
tweenTypeMap_["easeInoutcubic"] = EASE_INOUT_CUBIC;
tweenTypeMap_["easeInquartic"] = EASE_IN_QUARTIC;
tweenTypeMap_["easeOutquartic"] = EASE_OUT_QUARTIC;
tweenTypeMap_["easeInoutquartic"] = EASE_INOUT_QUARTIC;
tweenTypeMap_["easeInquintic"] = EASE_IN_QUINTIC;
tweenTypeMap_["easeOutquintic"] = EASE_OUT_QUINTIC;
tweenTypeMap_["easeInoutquintic"] = EASE_INOUT_QUINTIC;
tweenTypeMap_["easeInsine"] = EASE_IN_SINE;
tweenTypeMap_["easeOutsine"] = EASE_OUT_SINE;
tweenTypeMap_["easeInoutsine"] = EASE_INOUT_SINE;
tweenTypeMap_["easeInexponential"] = EASE_IN_EXPONENTIAL;
tweenTypeMap_["easeOutexponential"] = EASE_OUT_EXPONENTIAL;
tweenTypeMap_["easeInoutexponential"] = EASE_INOUT_EXPONENTIAL;
tweenTypeMap_["easeIncircular"] = EASE_IN_CIRCULAR;
tweenTypeMap_["easeOutcircular"] = EASE_OUT_CIRCULAR;
tweenTypeMap_["easeInoutcircular"] = EASE_INOUT_CIRCULAR;
tweenTypeMap_["linear"] = LINEAR;
}
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
{
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
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 b = end - start;
@ -125,92 +120,92 @@ float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double
switch(type)
{
case EASE_IN_QUADRATIC:
result = EaseInQuadratic(elapsedTime, duration, a, b);
result = easeInQuadratic(elapsedTime, duration, a, b);
break;
case EASE_OUT_QUADRATIC:
result = EaseOutQuadratic(elapsedTime, duration, a, b);
result = easeOutQuadratic(elapsedTime, duration, a, b);
break;
case EASE_INOUT_QUADRATIC:
result = EaseInOutQuadratic(elapsedTime, duration, a, b);
result = easeInOutQuadratic(elapsedTime, duration, a, b);
break;
case EASE_IN_CUBIC:
result = EaseInCubic(elapsedTime, duration, a, b);
result = easeInCubic(elapsedTime, duration, a, b);
break;
case EASE_OUT_CUBIC:
result = EaseOutCubic(elapsedTime, duration, a, b);
result = easeOutCubic(elapsedTime, duration, a, b);
break;
case EASE_INOUT_CUBIC:
result = EaseInOutCubic(elapsedTime, duration, a, b);
result = easeInOutCubic(elapsedTime, duration, a, b);
break;
case EASE_IN_QUARTIC:
result = EaseInQuartic(elapsedTime, duration, a, b);
result = easeInQuartic(elapsedTime, duration, a, b);
break;
case EASE_OUT_QUARTIC:
result = EaseOutQuartic(elapsedTime, duration, a, b);
result = easeOutQuartic(elapsedTime, duration, a, b);
break;
case EASE_INOUT_QUARTIC:
result = EaseInOutQuartic(elapsedTime, duration, a, b);
result = easeInOutQuartic(elapsedTime, duration, a, b);
break;
case EASE_IN_QUINTIC:
result = EaseInQuintic(elapsedTime, duration, a, b);
result = easeInQuintic(elapsedTime, duration, a, b);
break;
case EASE_OUT_QUINTIC:
result = EaseOutQuintic(elapsedTime, duration, a, b);
result = easeOutQuintic(elapsedTime, duration, a, b);
break;
case EASE_INOUT_QUINTIC:
result = EaseInOutQuintic(elapsedTime, duration, a, b);
result = easeInOutQuintic(elapsedTime, duration, a, b);
break;
case EASE_IN_SINE:
result = EaseInSine(elapsedTime, duration, a, b);
result = easeInSine(elapsedTime, duration, a, b);
break;
case EASE_OUT_SINE:
result = EaseOutSine(elapsedTime, duration, a, b);
result = easeOutSine(elapsedTime, duration, a, b);
break;
case EASE_INOUT_SINE:
result = EaseInOutSine(elapsedTime, duration, a, b);
result = easeInOutSine(elapsedTime, duration, a, b);
break;
case EASE_IN_EXPONENTIAL:
result = EaseInExponential(elapsedTime, duration, a, b);
result = easeInExponential(elapsedTime, duration, a, b);
break;
case EASE_OUT_EXPONENTIAL:
result = EaseOutExponential(elapsedTime, duration, a, b);
result = easeOutExponential(elapsedTime, duration, a, b);
break;
case EASE_INOUT_EXPONENTIAL:
result = EaseInOutExponential(elapsedTime, duration, a, b);
result = easeInOutExponential(elapsedTime, duration, a, b);
break;
case EASE_IN_CIRCULAR:
result = EaseInCircular(elapsedTime, duration, a, b);
result = easeInCircular(elapsedTime, duration, a, b);
break;
case EASE_OUT_CIRCULAR:
result = EaseOutCircular(elapsedTime, duration, a, b);
result = easeOutCircular(elapsedTime, duration, a, b);
break;
case EASE_INOUT_CIRCULAR:
result = EaseInOutCircular(elapsedTime, duration, a, b);
result = easeInOutCircular(elapsedTime, duration, a, b);
break;
case LINEAR:
default:
result = Linear(elapsedTime, duration, a, b);
result = linear(elapsedTime, duration, a, b);
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;
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;
t /= d;
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;
t /= d;
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;
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;
};
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;
t /= d;
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;
t /= d;
@ -262,7 +257,7 @@ double Tween::EaseOutCubic(double t, double d, double b, double c)
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;
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;
};
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;
t /= d;
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;
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;
};
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;
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;
};
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;
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;
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;
};
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;
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;
};
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;
};
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;
};
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;
};
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;
};
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;
};
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;
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;
};
double Tween::EaseInCircular(double t, double d, double b, double c)
double Tween::easeInCircular(double t, double d, double b, double c)
{
t /= d;
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--;
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;
if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b;
t -= 2;
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:
Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration);
float Animate(double elapsedTime);
static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime);
static TweenAlgorithm GetTweenType(std::string name);
static bool GetTweenProperty(std::string name, TweenProperty &property);
TweenProperty GetProperty() const;
float GetDuration() const;
float animate(double elapsedTime);
static float animateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime);
static TweenAlgorithm getTweenType(std::string name);
static bool getTweenProperty(std::string name, TweenProperty &property);
TweenProperty property;
double duration;
private:
static double EaseInQuadratic(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 EaseInCubic(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 EaseInQuartic(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 EaseInQuintic(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 EaseInSine(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 EaseInExponential(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 EaseInCircular(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 Linear(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 easeInOutQuadratic(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 easeInOutCubic(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 easeInOutQuartic(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 easeInOutQuintic(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 easeInOutSine(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 easeInOutExponential(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 easeInOutCircular(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, TweenProperty> TweenPropertyMap;
TweenProperty Property;
TweenAlgorithm Type;
double Start;
double End;
double Duration;
static std::map<std::string, TweenAlgorithm> tweenTypeMap_;
static std::map<std::string, TweenProperty> tweenPropertyMap_;
TweenAlgorithm type;
double start;
double end;
};

View File

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

View File

@ -21,26 +21,26 @@
Component::Component()
{
Tweens = NULL;
SelectedItem = NULL;
NewItemSelectedSinceEnter = false;
BackgroundTexture = NULL;
FreeGraphicsMemory();
tweens_ = NULL;
selectedItem_ = NULL;
newItemSelectedSinceEnter = false;
backgroundTexture_ = NULL;
freeGraphicsMemory();
}
Component::Component(const Component &copy)
{
Tweens = NULL;
SelectedItem = NULL;
NewItemSelectedSinceEnter = false;
BackgroundTexture = NULL;
FreeGraphicsMemory();
tweens_ = NULL;
selectedItem_ = NULL;
newItemSelectedSinceEnter = false;
backgroundTexture_ = NULL;
freeGraphicsMemory();
if(copy.Tweens)
if(copy.tweens_)
{
AnimationEvents *tweens = new AnimationEvents(*copy.Tweens);
SetTweens(tweens);
AnimationEvents *tweens = new AnimationEvents(*copy.tweens_);
setTweens(tweens);
}
@ -48,249 +48,214 @@ Component::Component(const Component &copy)
Component::~Component()
{
FreeGraphicsMemory();
freeGraphicsMemory();
}
void Component::FreeGraphicsMemory()
void Component::freeGraphicsMemory()
{
CurrentAnimationState = HIDDEN;
EnterRequested = false;
ExitRequested = false;
MenuEnterRequested = false;
MenuEnterIndex = -1;
MenuScrollRequested = false;
MenuExitRequested = false;
MenuExitIndex = -1;
currentAnimationState = HIDDEN;
enterRequested = false;
exitRequested = false;
menuEnterRequested = false;
menuEnterIndex = -1;
menuScrollRequested = false;
menuExitRequested = false;
menuExitIndex = -1;
NewItemSelected = false;
HighlightExitComplete = false;
CurrentTweens = NULL;
CurrentTweenIndex = 0;
CurrentTweenComplete = false;
ElapsedTweenTime = 0;
ScrollActive = false;
newItemSelected = false;
highlightExitComplete = false;
currentTweens_ = NULL;
currentTweenIndex_ = 0;
currentTweenComplete_ = false;
elapsedTweenTime_ = 0;
scrollActive = false;
if(BackgroundTexture)
if(backgroundTexture_)
{
SDL_LockMutex(SDL::GetMutex());
SDL_DestroyTexture(BackgroundTexture);
SDL_UnlockMutex(SDL::GetMutex());
SDL_LockMutex(SDL::getMutex());
SDL_DestroyTexture(backgroundTexture_);
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
// color later
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_LockMutex(SDL::GetMutex());
BackgroundTexture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), surface);
SDL_UnlockMutex(SDL::GetMutex());
SDL_LockMutex(SDL::getMutex());
backgroundTexture_ = SDL_CreateTextureFromSurface(SDL::getRenderer(), surface);
SDL_UnlockMutex(SDL::getMutex());
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;
MenuEnterIndex = menuIndex;
menuEnterRequested = true;
menuEnterIndex = menuIndex;
}
void Component::TriggerMenuScrollEvent()
void Component::triggerMenuScrollEvent()
{
MenuScrollRequested = true;
menuScrollRequested = true;
}
void Component::TriggerMenuExitEvent(int menuIndex)
void Component::triggerMenuExitEvent(int menuIndex)
{
MenuExitRequested = true;
MenuExitIndex = menuIndex;
menuExitRequested = true;
menuExitIndex = menuIndex;
}
void Component::TriggerHighlightEvent(Item *selectedItem)
void Component::triggerHighlightEvent(Item *selectedItem)
{
NewItemSelected = true;
this->SelectedItem = selectedItem;
newItemSelected = true;
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;
}
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))
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.
std::stringstream ss;
switch(CurrentAnimationState)
switch(currentAnimationState)
{
case MENU_ENTER:
CurrentTweens = NULL;
CurrentAnimationState = IDLE;
currentTweens_ = NULL;
currentAnimationState = IDLE;
break;
case MENU_SCROLL:
CurrentTweens = NULL;
CurrentAnimationState = IDLE;
currentTweens_ = NULL;
currentAnimationState = IDLE;
break;
case MENU_EXIT:
CurrentTweens = NULL;
CurrentAnimationState = IDLE;
currentTweens_ = NULL;
currentAnimationState = IDLE;
break;
case ENTER:
CurrentTweens = Tweens->GetAnimation("enter", MenuEnterIndex);
CurrentAnimationState = HIGHLIGHT_ENTER;
currentTweens_ = tweens_->getAnimation("enter", menuEnterIndex);
currentAnimationState = HIGHLIGHT_ENTER;
break;
case EXIT:
CurrentTweens = NULL;
CurrentAnimationState = HIDDEN;
currentTweens_ = NULL;
currentAnimationState = HIDDEN;
break;
case HIGHLIGHT_ENTER:
CurrentTweens = Tweens->GetAnimation("idle", MenuEnterIndex);
CurrentAnimationState = IDLE;
currentTweens_ = tweens_->getAnimation("idle", menuEnterIndex);
currentAnimationState = IDLE;
break;
case IDLE:
// prevent us from automatically jumping to the exit tween upon enter
if(EnterRequested)
if(enterRequested)
{
EnterRequested = false;
NewItemSelected = false;
enterRequested = false;
newItemSelected = false;
}
else if(MenuExitRequested && (!MenuEnterRequested || MenuExitRequested <= MenuEnterRequested))
else if(menuExitRequested && (!menuEnterRequested || menuExitRequested <= menuEnterRequested))
{
CurrentTweens = Tweens->GetAnimation("menuExit", MenuExitIndex);
CurrentAnimationState = MENU_EXIT;
MenuExitRequested = false;
currentTweens_ = tweens_->getAnimation("menuExit", menuExitIndex);
currentAnimationState = MENU_EXIT;
menuExitRequested = false;
}
else if(MenuEnterRequested && (!MenuExitRequested || MenuExitRequested > MenuEnterRequested))
else if(menuEnterRequested && (!menuExitRequested || menuExitRequested > menuEnterRequested))
{
CurrentTweens = Tweens->GetAnimation("menuEnter", MenuEnterIndex);
CurrentAnimationState = MENU_ENTER;
MenuEnterRequested = false;
currentTweens_ = tweens_->getAnimation("menuEnter", menuEnterIndex);
currentAnimationState = MENU_ENTER;
menuEnterRequested = false;
}
else if(MenuScrollRequested)
else if(menuScrollRequested)
{
MenuScrollRequested = false;
CurrentTweens = Tweens->GetAnimation("menuScroll", MenuEnterIndex);
CurrentAnimationState = MENU_SCROLL;
menuScrollRequested = false;
currentTweens_ = tweens_->getAnimation("menuScroll", menuEnterIndex);
currentAnimationState = MENU_SCROLL;
}
else if(IsScrollActive() || NewItemSelected || ExitRequested)
else if(scrollActive || newItemSelected || exitRequested)
{
CurrentTweens = Tweens->GetAnimation("highlightExit", MenuEnterIndex);
CurrentAnimationState = HIGHLIGHT_EXIT;
currentTweens_ = tweens_->getAnimation("highlightExit", menuEnterIndex);
currentAnimationState = HIGHLIGHT_EXIT;
}
else
{
CurrentTweens = Tweens->GetAnimation("idle", MenuEnterIndex);
CurrentAnimationState = IDLE;
currentTweens_ = tweens_->getAnimation("idle", menuEnterIndex);
currentAnimationState = IDLE;
}
break;
@ -299,195 +264,194 @@ void Component::Update(float dt)
// intentionally break down
case HIGHLIGHT_WAIT:
if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_WAIT))
if(exitRequested && (currentAnimationState == HIGHLIGHT_WAIT))
{
CurrentTweens = Tweens->GetAnimation("highlightExit", MenuEnterIndex);
CurrentAnimationState = HIGHLIGHT_EXIT;
currentTweens_ = tweens_->getAnimation("highlightExit", menuEnterIndex);
currentAnimationState = HIGHLIGHT_EXIT;
}
else if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_EXIT))
else if(exitRequested && (currentAnimationState == HIGHLIGHT_EXIT))
{
CurrentTweens = Tweens->GetAnimation("exit", MenuEnterIndex);
CurrentAnimationState = EXIT;
ExitRequested = false;
currentTweens_ = tweens_->getAnimation("exit", menuEnterIndex);
currentAnimationState = EXIT;
exitRequested = false;
}
else if(IsScrollActive())
else if(scrollActive)
{
CurrentTweens = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT;
currentTweens_ = NULL;
currentAnimationState = HIGHLIGHT_WAIT;
}
else if(NewItemSelected)
else if(newItemSelected)
{
CurrentTweens = Tweens->GetAnimation("highlightEnter", MenuEnterIndex);
CurrentAnimationState = HIGHLIGHT_ENTER;
HighlightExitComplete = true;
NewItemSelected = false;
currentTweens_ = tweens_->getAnimation("highlightEnter", menuEnterIndex);
currentAnimationState = HIGHLIGHT_ENTER;
highlightExitComplete = true;
newItemSelected = false;
}
else
{
CurrentTweens = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT;
currentTweens_ = NULL;
currentAnimationState = HIGHLIGHT_WAIT;
}
break;
case HIDDEN:
if(EnterRequested || ExitRequested)
if(enterRequested || exitRequested)
{
CurrentTweens = Tweens->GetAnimation("enter", MenuEnterIndex);
CurrentAnimationState = ENTER;
currentTweens_ = tweens_->getAnimation("enter", menuEnterIndex);
currentAnimationState = ENTER;
}
else if(MenuExitRequested && (!MenuEnterRequested || MenuExitRequested <= MenuEnterRequested))
else if(menuExitRequested && (!menuEnterRequested || menuExitRequested <= menuEnterRequested))
{
CurrentTweens = Tweens->GetAnimation("menuExit", MenuExitIndex);
CurrentAnimationState = MENU_EXIT;
MenuExitRequested = false;
currentTweens_ = tweens_->getAnimation("menuExit", menuExitIndex);
currentAnimationState = MENU_EXIT;
menuExitRequested = false;
}
else if(MenuEnterRequested && (!MenuExitRequested || MenuExitRequested > MenuEnterRequested))
else if(menuEnterRequested && (!menuExitRequested || menuExitRequested > menuEnterRequested))
{
CurrentTweens = Tweens->GetAnimation("menuEnter", MenuEnterIndex);
CurrentAnimationState = MENU_ENTER;
MenuEnterRequested = false;
currentTweens_ = tweens_->getAnimation("menuEnter", menuEnterIndex);
currentAnimationState = MENU_ENTER;
menuEnterRequested = false;
}
else if(MenuScrollRequested)
else if(menuScrollRequested)
{
MenuScrollRequested = false;
CurrentTweens = Tweens->GetAnimation("menuScroll", MenuEnterIndex);
CurrentAnimationState = MENU_SCROLL;
menuScrollRequested = false;
currentTweens_ = tweens_->getAnimation("menuScroll", menuEnterIndex);
currentAnimationState = MENU_SCROLL;
}
else
{
CurrentTweens = NULL;
CurrentAnimationState = HIDDEN;
currentTweens_ = NULL;
currentAnimationState = HIDDEN;
}
}
CurrentTweenIndex = 0;
CurrentTweenComplete = false;
currentTweenIndex_ = 0;
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;
rect.h = static_cast<int>(info->GetHeight());
rect.w = static_cast<int>(info->GetWidth());
rect.x = static_cast<int>(info->GetXRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin());
rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
rect.w = static_cast<int>(baseViewInfo.ScaledWidth());
rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
SDL_SetTextureColorMod(BackgroundTexture,
static_cast<char>(info->GetBackgroundRed()*255),
static_cast<char>(info->GetBackgroundGreen()*255),
static_cast<char>(info->GetBackgroundBlue()*255));
SDL_SetTextureColorMod(backgroundTexture_,
static_cast<char>(baseViewInfo.BackgroundRed*255),
static_cast<char>(baseViewInfo.BackgroundGreen*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;
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->GetSize())
if(!currentTweens_ || currentTweenIndex_ >= currentTweens_->size())
{
completeDone = true;
}
else if(CurrentTweens)
else if(currentTweens_)
{
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);
float elapsedTime = ElapsedTweenTime;
Tween *tween = tweens->tweens()->at(i);
float elapsedTime = elapsedTweenTime_;
//todo: too many levels of nesting
if(elapsedTime < tween->GetDuration())
if(elapsedTime < tween->duration)
{
currentDone = false;
}
else
{
elapsedTime = tween->GetDuration();
elapsedTime = tween->duration;
}
float value = tween->Animate(elapsedTime);
float value = tween->animate(elapsedTime);
switch(tween->GetProperty())
switch(tween->property)
{
case TWEEN_PROPERTY_X:
GetBaseViewInfo()->SetX(value);
baseViewInfo.X = value;
break;
case TWEEN_PROPERTY_Y:
GetBaseViewInfo()->SetY(value);
baseViewInfo.Y = value;
break;
case TWEEN_PROPERTY_HEIGHT:
GetBaseViewInfo()->SetHeight(value);
baseViewInfo.Height = value;
break;
case TWEEN_PROPERTY_WIDTH:
GetBaseViewInfo()->SetWidth(value);
baseViewInfo.Width = value;
break;
case TWEEN_PROPERTY_ANGLE:
GetBaseViewInfo()->SetAngle(value);
baseViewInfo.Angle = value;
break;
case TWEEN_PROPERTY_ALPHA:
GetBaseViewInfo()->SetAlpha(value);
baseViewInfo.Alpha = value;
break;
case TWEEN_PROPERTY_X_ORIGIN:
GetBaseViewInfo()->SetXOrigin(value);
baseViewInfo.XOrigin = value;
break;
case TWEEN_PROPERTY_Y_ORIGIN:
GetBaseViewInfo()->SetYOrigin(value);
baseViewInfo.YOrigin = value;
break;
case TWEEN_PROPERTY_X_OFFSET:
GetBaseViewInfo()->SetXOffset(value);
baseViewInfo.XOffset = value;
break;
case TWEEN_PROPERTY_Y_OFFSET:
GetBaseViewInfo()->SetYOffset(value);
baseViewInfo.YOffset = value;
break;
case TWEEN_PROPERTY_FONT_SIZE:
GetBaseViewInfo()->SetFontSize(value);
baseViewInfo.FontSize = value;
break;
case TWEEN_PROPERTY_BACKGROUND_ALPHA:
GetBaseViewInfo()->SetBackgroundAlpha(value);
baseViewInfo.BackgroundAlpha = value;
break;
}
}
if(currentDone)
{
CurrentTweenIndex++;
ElapsedTweenTime = 0;
currentTweenIndex_++;
elapsedTweenTime_ = 0;
}
}
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->GetTweenSets()->size())
if(!currentTweens_ || currentTweenIndex_ >= currentTweens_->tweenSets()->size())
{
if(loop)
{
CurrentTweenIndex = 0;
currentTweenIndex_ = 0;
}
completeDone = true;
}

View File

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

View File

@ -20,25 +20,25 @@
Container::Container()
{
AllocateGraphicsMemory();
allocateGraphicsMemory();
}
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:
Container();
virtual ~Container();
void FreeGraphicsMemory();
void AllocateGraphicsMemory();
void Draw();
void freeGraphicsMemory();
void allocateGraphicsMemory();
void draw();
};

View File

@ -20,70 +20,69 @@
#include <SDL2/SDL_image.h>
Image::Image(std::string file, float scaleX, float scaleY)
: Texture(NULL)
, File(file)
, ScaleX(scaleX)
, ScaleY(scaleY)
: texture_(NULL)
, file_(file)
, scaleX_(scaleX)
, scaleY_(scaleY)
{
AllocateGraphicsMemory();
allocateGraphicsMemory();
}
Image::~Image()
{
FreeGraphicsMemory();
freeGraphicsMemory();
}
void Image::FreeGraphicsMemory()
void Image::freeGraphicsMemory()
{
Component::FreeGraphicsMemory();
Component::freeGraphicsMemory();
SDL_LockMutex(SDL::GetMutex());
if (Texture != NULL)
SDL_LockMutex(SDL::getMutex());
if (texture_ != NULL)
{
SDL_DestroyTexture(Texture);
Texture = NULL;
SDL_DestroyTexture(texture_);
texture_ = NULL;
}
SDL_UnlockMutex(SDL::GetMutex());
SDL_UnlockMutex(SDL::getMutex());
}
void Image::AllocateGraphicsMemory()
void Image::allocateGraphicsMemory()
{
int width;
int height;
Component::AllocateGraphicsMemory();
Component::allocateGraphicsMemory();
if(!Texture)
if(!texture_)
{
SDL_LockMutex(SDL::GetMutex());
Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str());
SDL_LockMutex(SDL::getMutex());
texture_ = IMG_LoadTexture(SDL::getRenderer(), file_.c_str());
if (Texture != NULL)
if (texture_ != NULL)
{
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND);
SDL_QueryTexture(Texture, NULL, NULL, &width, &height);
GetBaseViewInfo()->SetImageWidth(width * ScaleX);
GetBaseViewInfo()->SetImageHeight(height * ScaleY);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
SDL_QueryTexture(texture_, NULL, NULL, &width, &height);
baseViewInfo.ImageWidth = width * scaleX_;
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;
rect.x = static_cast<int>(info->GetXRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight());
rect.w = static_cast<int>(info->GetWidth());
rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
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:
Image(std::string file, float scaleX, float scaleY);
virtual ~Image();
void FreeGraphicsMemory();
void AllocateGraphicsMemory();
void Draw();
void freeGraphicsMemory();
void allocateGraphicsMemory();
void draw();
protected:
SDL_Texture *Texture;
std::string File;
float ScaleX;
float ScaleY;
SDL_Texture *texture_;
std::string file_;
float scaleX_;
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");
std::string prefix = Utils::CombinePath(path, name);
std::string prefix = Utils::combinePath(path, name);
std::string file;
if(Utils::FindMatchingFile(prefix, extensions, file))
if(Utils::findMatchingFile(prefix, extensions, file))
{
image = new Image(file, scaleX, scaleY);
}

View File

@ -29,252 +29,253 @@
#include <iostream>
ReloadableMedia::ReloadableMedia(Configuration &config, bool systemMode, std::string type, bool isVideo, Font *font, float scaleX, float scaleY)
: Config(config)
, SystemMode(systemMode)
, LoadedComponent(NULL)
, ReloadRequested(false)
, FirstLoad(true)
, VideoInst(NULL)
, IsVideo(isVideo)
, FontInst(font)
, TextFallback(false)
, Type(type)
, ScaleX(scaleX)
, ScaleY(scaleY)
: config_(config)
, systemMode_(systemMode)
, loadedComponent_(NULL)
, reloadRequested_(false)
, firstLoad_(true)
, videoInst_(NULL)
, isVideo_(isVideo)
, FfntInst_(font)
, textFallback_(false)
, type_(type)
, scaleX_(scaleX)
, scaleY_(scaleY)
{
AllocateGraphicsMemory();
allocateGraphicsMemory();
}
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
if (ReloadRequested && (HighlightExitComplete || FirstLoad))
if (reloadRequested_ && (highlightExitComplete || firstLoad_))
{
ReloadTexture();
ReloadRequested = false;
FirstLoad = false;
reloadTexture();
reloadRequested_ = false;
firstLoad_ = false;
}
if(LoadedComponent)
if(loadedComponent_)
{
// 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());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
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
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
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()
void ReloadableMedia::reloadTexture()
{
bool found = false;
if(LoadedComponent)
if(loadedComponent_)
{
delete LoadedComponent;
LoadedComponent = NULL;
delete loadedComponent_;
loadedComponent_ = NULL;
}
Item *selectedItem = GetSelectedItem();
Item *selectedItem = getSelectedItem();
CurrentCollection = Config.GetCurrentCollection();
config_.getProperty("currentCollection", currentCollection_);
if (selectedItem != NULL)
{
std::vector<std::string> names;
names.push_back(selectedItem->GetName());
names.push_back(selectedItem->GetFullTitle());
names.push_back(selectedItem->name);
names.push_back(selectedItem->fullTitle);
if(selectedItem->GetCloneOf().length() > 0)
if(selectedItem->cloneof.length() > 0)
{
names.push_back(selectedItem->GetCloneOf());
names.push_back(selectedItem->cloneof);
}
for(unsigned int n = 0; n < names.size() && !found; ++n)
{
if(IsVideo)
if(isVideo_)
{
VideoBuilder videoBuild;
std::string videoPath;
if(SystemMode)
if(systemMode_)
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), "video", true, videoPath);
LoadedComponent = videoBuild.CreateVideo(videoPath, "video", ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(collectionName, "video", true, videoPath);
loadedComponent_ = videoBuild.createVideo(videoPath, "video", scaleX_, scaleY_);
}
else
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), "video", false, videoPath);
LoadedComponent = videoBuild.CreateVideo(videoPath, names[n], ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(collectionName, "video", false, videoPath);
loadedComponent_ = videoBuild.createVideo(videoPath, names[n], scaleX_, scaleY_);
}
if(!LoadedComponent && !SystemMode)
if(!loadedComponent_ && !systemMode_)
{
Config.GetMediaPropertyAbsolutePath(names[n], Type, true, videoPath);
LoadedComponent = videoBuild.CreateVideo(videoPath, "video", ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(names[n], type_, true, videoPath);
loadedComponent_ = videoBuild.createVideo(videoPath, "video", scaleX_, scaleY_);
}
if(LoadedComponent)
if(loadedComponent_)
{
LoadedComponent->AllocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
loadedComponent_->allocateGraphicsMemory();
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
found = true;
}
}
std::string imageBasename = names[n];
std::string typeLC = Utils::ToLower(Type);
std::string typeLC = Utils::toLower(type_);
if(typeLC == "numberButtons")
{
imageBasename = selectedItem->GetNumberButtons();
imageBasename = selectedItem->numberButtons;
}
else if(typeLC == "numberPlayers")
{
imageBasename = selectedItem->GetNumberPlayers();
imageBasename = selectedItem->numberPlayers;
}
else if(typeLC == "year")
{
imageBasename = selectedItem->GetYear();
imageBasename = selectedItem->year;
}
else if(typeLC == "title")
{
imageBasename = selectedItem->GetTitle();
imageBasename = selectedItem->title;
}
else if(typeLC == "manufacturer")
{
imageBasename = selectedItem->GetManufacturer();
imageBasename = selectedItem->manufacturer;
}
else if(typeLC == "genre")
{
imageBasename = selectedItem->GetGenre();
imageBasename = selectedItem->genre;
}
Utils::ReplaceSlashesWithUnderscores(imageBasename);
Utils::replaceSlashesWithUnderscores(imageBasename);
if(!LoadedComponent)
if(!loadedComponent_)
{
std::string imagePath;
ImageBuilder imageBuild;
if(SystemMode)
if(systemMode_)
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), Type, true, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, Type, ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(collectionName, type_, true, imagePath);
loadedComponent_ = imageBuild.CreateImage(imagePath, type_, scaleX_, scaleY_);
}
else
{
Config.GetMediaPropertyAbsolutePath(GetCollectionName(), Type, false, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, imageBasename, ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(collectionName, type_, false, imagePath);
loadedComponent_ = imageBuild.CreateImage(imagePath, imageBasename, scaleX_, scaleY_);
}
if(!LoadedComponent && !SystemMode)
if(!loadedComponent_ && !systemMode_)
{
Config.GetMediaPropertyAbsolutePath(imageBasename, Type, true, imagePath);
LoadedComponent = imageBuild.CreateImage(imagePath, Type, ScaleX, ScaleY);
config_.getMediaPropertyAbsolutePath(imageBasename, type_, true, imagePath);
loadedComponent_ = imageBuild.CreateImage(imagePath, type_, scaleX_, scaleY_);
}
if (LoadedComponent != NULL)
if (loadedComponent_ != NULL)
{
LoadedComponent->AllocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
loadedComponent_->allocateGraphicsMemory();
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
}
}
if(!LoadedComponent && TextFallback)
if(!loadedComponent_ && textFallback_)
{
LoadedComponent = new Text(imageBasename, FontInst, ScaleX, ScaleY);
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
loadedComponent_ = new Text(imageBasename, FfntInst_, scaleX_, scaleY_);
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
}
}
}
}
void ReloadableMedia::Draw()
void ReloadableMedia::draw()
{
ViewInfo *info = GetBaseViewInfo();
Component::draw();
Component::Draw();
if(LoadedComponent)
if(loadedComponent_)
{
info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
LoadedComponent->UpdateBaseViewInfo(*info);
LoadedComponent->Draw();
baseViewInfo.ImageHeight = loadedComponent_->baseViewInfo.ImageHeight;
baseViewInfo.ImageWidth = loadedComponent_->baseViewInfo.ImageWidth;
loadedComponent_->baseViewInfo = baseViewInfo;
loadedComponent_->draw();
}
}

View File

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

View File

@ -24,152 +24,150 @@
#include <iostream>
ReloadableText::ReloadableText(std::string type, Font *font, std::string layoutKey, float scaleX, float scaleY)
: ImageInst(NULL)
, LayoutKey(layoutKey)
, ReloadRequested(false)
, FirstLoad(true)
, FontInst(font)
, ScaleX(scaleX)
, ScaleY(scaleY)
: imageInst_(NULL)
, layoutKey_(layoutKey)
, reloadRequested_(false)
, firstLoad_(true)
, fontInst_(font)
, scaleX_(scaleX)
, scaleY_(scaleY)
{
Type = TextTypeUnknown;
type_ = TextTypeUnknown;
if(type == "numberButtons")
{
Type = TextTypeNumberButtons;
type_ = TextTypeNumberButtons;
}
else if(type == "numberPlayers")
{
Type = TextTypeNumberPlayers;
type_ = TextTypeNumberPlayers;
}
else if(type == "year")
{
Type = TextTypeYear;
type_ = TextTypeYear;
}
else if(type == "title")
{
Type = TextTypeTitle;
type_ = TextTypeTitle;
}
else if(type == "manufacturer")
{
Type = TextTypeManufacturer;
type_ = TextTypeManufacturer;
}
else if(type == "genre")
{
Type = TextTypeGenre;
type_ = TextTypeGenre;
}
AllocateGraphicsMemory();
allocateGraphicsMemory();
}
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
if (ReloadRequested && (HighlightExitComplete || FirstLoad))
if (reloadRequested_ && (highlightExitComplete || firstLoad_))
{
ReloadTexture();
ReloadRequested = false;
FirstLoad = false;
reloadRequested_ = false;
firstLoad_ = false;
}
// 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();
// 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;
ImageInst = NULL;
delete imageInst_;
imageInst_ = NULL;
}
}
void ReloadableText::ReloadTexture()
{
if (ImageInst != NULL)
if (imageInst_ != NULL)
{
delete ImageInst;
ImageInst = NULL;
delete imageInst_;
imageInst_ = NULL;
}
Item *selectedItem = GetSelectedItem();
Item *selectedItem = getSelectedItem();
if (selectedItem != NULL)
{
std::stringstream ss;
std::string text;
switch(Type)
switch(type_)
{
case TextTypeNumberButtons:
ss << selectedItem->GetNumberButtons();
ss << selectedItem->numberButtons;
break;
case TextTypeNumberPlayers:
ss << selectedItem->GetNumberPlayers();
ss << selectedItem->numberPlayers;
break;
case TextTypeYear:
ss << selectedItem->GetYear();
ss << selectedItem->year;
break;
case TextTypeTitle:
ss << selectedItem->GetTitle();
ss << selectedItem->title;
break;
case TextTypeManufacturer:
ss << selectedItem->GetManufacturer();
ss << selectedItem->manufacturer;
break;
case TextTypeGenre:
ss << selectedItem->GetGenre();
ss << selectedItem->genre;
break;
default:
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->Draw();
imageInst_->baseViewInfo = baseViewInfo;
imageInst_->draw();
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -21,114 +21,113 @@
#include <sstream>
Text::Text(std::string text, Font *font, float scaleX, float scaleY)
: TextData(text)
, FontInst(font)
, ScaleX(scaleX)
, ScaleY(scaleY)
: textData_(text)
, fontInst_(font)
, scaleX_(scaleX)
, scaleY_(scaleY)
{
AllocateGraphicsMemory();
allocateGraphicsMemory();
}
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
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 imageWidth = 0;
// determine image width
for(unsigned int i = 0; i < TextData.size(); ++i)
for(unsigned int i = 0; i < textData_.size(); ++i)
{
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();
float scale = (float)info->GetFontSize() / (float)imageHeight;
imageHeight = (float)fontInst_->getHeight();
float scale = (float)baseViewInfo.FontSize / (float)imageHeight;
float oldWidth = info->GetRawWidth();
float oldHeight = info->GetRawHeight();
float oldImageWidth = info->GetImageHeight();
float oldImageHeight = info->GetImageWidth();
float oldWidth = baseViewInfo.Width;
float oldHeight = baseViewInfo.Height;
float oldImageWidth = baseViewInfo.ImageHeight;
float oldImageHeight = baseViewInfo.ImageWidth;
info->SetWidth(imageWidth*scale);
info->SetHeight(info->GetFontSize());
info->SetImageWidth(imageWidth);
info->SetImageHeight(imageHeight);
baseViewInfo.Width = imageWidth*scale;
baseViewInfo.Height = baseViewInfo.FontSize;
baseViewInfo.ImageWidth = imageWidth;
baseViewInfo.ImageHeight = imageHeight;
float xOrigin = info->GetXRelativeToOrigin();
float yOrigin = info->GetYRelativeToOrigin();
float xOrigin = baseViewInfo.XRelativeToOrigin();
float yOrigin = baseViewInfo.YRelativeToOrigin();
info->SetWidth(oldWidth);
info->SetHeight(oldHeight);
info->SetImageWidth(oldImageWidth);
info->SetImageHeight(oldImageHeight);
baseViewInfo.Width = oldWidth;
baseViewInfo.Height = oldHeight;
baseViewInfo.ImageWidth = oldImageWidth;
baseViewInfo.ImageHeight = oldImageHeight;
SDL_Rect rect;
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;
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 w = static_cast<float>(charRect.w * scale);
rect.h = static_cast<int>(h);
rect.w = static_cast<int>(w);
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;
}

View File

@ -27,15 +27,15 @@ class Text : public Component
public:
//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);
void SetText(std::string text);
virtual ~Text();
void AllocateGraphicsMemory();
void FreeGraphicsMemory();
void Draw();
void setText(std::string text);
void allocateGraphicsMemory();
void freeGraphicsMemory();
void draw();
private:
std::string TextData;
Font *FontInst;
float ScaleX;
float ScaleY;
std::string textData_;
Font *fontInst_;
float scaleX_;
float scaleY_;
};

View File

@ -21,7 +21,7 @@
#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;
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");
std::string prefix = Utils::CombinePath(path, name);
std::string prefix = Utils::combinePath(path, name);
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)
{

View File

@ -23,8 +23,8 @@
class VideoBuilder
{
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:
VideoFactory Factory;
VideoFactory factory_;
};

View File

@ -21,85 +21,84 @@
#include "../../SDL.h"
VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY)
: VideoFile(videoFile)
, VideoInst(videoInst)
, ScaleX(scaleX)
, ScaleY(scaleY)
, IsPlaying(false)
: videoFile_(videoFile)
, videoInst_(videoInst)
, scaleX_(scaleX)
, scaleY_(scaleY)
, isPlaying_(false)
{
// AllocateGraphicsMemory();
}
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
if(GetBaseViewInfo()->GetImageHeight() == 0 && GetBaseViewInfo()->GetImageWidth() == 0)
if(baseViewInfo.ImageHeight == 0 && baseViewInfo.ImageWidth == 0)
{
GetBaseViewInfo()->SetImageHeight(static_cast<float>(VideoInst->GetHeight()));
GetBaseViewInfo()->SetImageWidth(static_cast<float>(VideoInst->GetWidth()));
baseViewInfo.ImageHeight = static_cast<float>(videoInst_->getHeight());
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();
IsPlaying = false;
videoInst_->stop();
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;
rect.x = static_cast<int>(info->GetXRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight());
rect.w = static_cast<int>(info->GetWidth());
rect.x = static_cast<int>(baseViewInfo.XRelativeToOrigin());
rect.y = static_cast<int>(baseViewInfo.YRelativeToOrigin());
rect.h = static_cast<int>(baseViewInfo.ScaledHeight());
rect.w = static_cast<int>(baseViewInfo.ScaledWidth());
VideoInst->Draw();
SDL_Texture *texture = VideoInst->GetTexture();
videoInst_->draw();
SDL_Texture *texture = videoInst_->getTexture();
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:
VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY);
virtual ~VideoComponent();
void Update(float dt);
void Draw();
void FreeGraphicsMemory();
void AllocateGraphicsMemory();
void LaunchEnter();
void LaunchExit();
void update(float dt);
void draw();
void freeGraphicsMemory();
void allocateGraphicsMemory();
void launchEnter();
void launchExit();
private:
std::string VideoFile;
std::string Name;
IVideo *VideoInst;
float ScaleX;
float ScaleY;
bool IsPlaying;
std::string videoFile_;
std::string name_;
IVideo *videoInst_;
float scaleX_;
float scaleY_;
bool isPlaying_;
};

View File

@ -16,14 +16,14 @@
#include "ComponentItemBinding.h"
ComponentItemBinding::ComponentItemBinding( Component *c, Item *item)
: CollectionComponent(c)
, CollectionItem(item)
: component(c)
, item(item)
{
}
ComponentItemBinding::ComponentItemBinding(Item *item)
: CollectionComponent(NULL)
, CollectionItem(item)
: component(NULL)
, 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(Item *item);
virtual ~ComponentItemBinding();
Item* GetCollectionItem() const;
void SetComponent(Component *c);
Component* GetComponent() const;
private:
Component *CollectionComponent;
Item *CollectionItem;
Component *component;
Item *item;
};

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<Item *>::iterator it;

View File

@ -26,5 +26,5 @@ class ComponentItemBindingBuilder
public:
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>
Font::Font()
: Texture(NULL)
: texture(NULL)
{
}
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;
glyph = info->Glyph;
glyph = info->glyph;
return true;
}
@ -52,7 +60,7 @@ bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph)
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);
@ -60,7 +68,7 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
{
std::stringstream ss;
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;
}
@ -68,8 +76,8 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
int y = 0;
int atlasHeight = 0;
int atlasWidth = 0;
Height = TTF_FontHeight(font);
Ascent = TTF_FontAscent(font);
height = TTF_FontHeight(font);
ascent = TTF_FontAscent(font);
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));
color.a = 255;
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);
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);
if(x + info->Surface->w >= 1024)
if(x + info->surface->w >= 1024)
{
atlasHeight += y;
atlasWidth = (atlasWidth >= x) ? atlasWidth : x;
@ -88,14 +99,14 @@ bool Font::Initialize(std::string fontPath, int fontSize, SDL_Color color)
y = 0;
}
info->Glyph.Rect.w = info->Surface->w;
info->Glyph.Rect.h = info->Surface->h;
info->Glyph.Rect.x = x;
info->Glyph.Rect.y = atlasHeight;
Atlas[i] = info;
info->glyph.rect.w = info->surface->w;
info->glyph.rect.h = info->surface->h;
info->glyph.rect.x = x;
info->glyph.rect.y = atlasHeight;
atlas[i] = info;
x += info->Glyph.Rect.w;
y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h;
x += info->glyph.rect.w;
y = (y > info->glyph.rect.h) ? y : info->glyph.rect.h;
/*
std::stringstream ss;
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);
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;
SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect);
SDL_FreeSurface(info->Surface);
info->Surface = NULL;
SDL_BlitSurface(info->surface, NULL, atlasSurface, &info->glyph.rect);
SDL_FreeSurface(info->surface);
info->surface = NULL;
}
SDL_LockMutex(SDL::GetMutex());
SDL_LockMutex(SDL::getMutex());
Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface);
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_ADD);
texture = SDL_CreateTextureFromSurface(SDL::getRenderer(), atlasSurface);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_ADD);
SDL_FreeSurface(atlasSurface);
SDL_UnlockMutex(SDL::GetMutex());
SDL_UnlockMutex(SDL::getMutex());
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_DestroyTexture(Texture);
Texture = NULL;
SDL_UnlockMutex(SDL::GetMutex());
SDL_LockMutex(SDL::getMutex());
SDL_DestroyTexture(texture);
texture = NULL;
SDL_UnlockMutex(SDL::getMutex());
}
std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = Atlas.begin();
while(atlasIt != Atlas.end())
std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = atlas.begin();
while(atlasIt != atlas.end())
{
delete atlasIt->second;
Atlas.erase(atlasIt);
atlasIt = Atlas.begin();
atlas.erase(atlasIt);
atlasIt = atlas.begin();
}
}
int Font::GetHeight()
{
return Height;
}
int Font::GetAscent()
{
return Ascent;
}

View File

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

View File

@ -28,37 +28,37 @@ FontCache::FontCache()
FontCache::~FontCache()
{
DeInitialize();
deInitialize();
}
void FontCache::DeInitialize()
void FontCache::deInitialize()
{
std::map<std::string, Font *>::iterator it = FontFaceMap.begin();
while(it != FontFaceMap.end())
std::map<std::string, Font *>::iterator it = fontFaceMap_.begin();
while(it != fontFaceMap_.end())
{
delete it->second;
FontFaceMap.erase(it);
it = FontFaceMap.begin();
fontFaceMap_.erase(it);
it = fontFaceMap_.begin();
}
SDL_LockMutex(SDL::GetMutex());
SDL_LockMutex(SDL::getMutex());
TTF_Quit();
SDL_UnlockMutex(SDL::GetMutex());
SDL_UnlockMutex(SDL::getMutex());
}
void FontCache::Initialize()
void FontCache::initialize()
{
//todo: make bool
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;
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;
}
@ -66,7 +66,7 @@ Font *FontCache::GetFont(std::string fontPath, int fontSize, SDL_Color color)
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;
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();
}
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::map<std::string, Font *>::iterator it = FontFaceMap.find(key);
std::string key = buildFontKey(fontPath, fontSize, color);
std::map<std::string, Font *>::iterator it = fontFaceMap_.find(key);
if(it == FontFaceMap.end())
if(it == fontFaceMap_.end())
{
Font *f = new Font();
f->Initialize(fontPath, fontSize, color);
FontFaceMap[key] = f;
f->initialize(fontPath, fontSize, color);
fontFaceMap_[key] = f;
}
return true;

View File

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

View File

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

View File

@ -26,32 +26,32 @@
#include <sstream>
Page::Page(Configuration &config)
: Config(config)
, ActiveMenu(NULL)
, MenuDepth(0)
, Items(NULL)
, ScrollActive(false)
, SelectedItem(NULL)
, TextStatusComponent(NULL)
, SelectedItemChanged(false)
, LoadSoundChunk(NULL)
, UnloadSoundChunk(NULL)
, HighlightSoundChunk(NULL)
, SelectSoundChunk(NULL)
, MinShowTime(0)
: config_(config)
, activeMenu_(NULL)
, menuDepth_(0)
, items_(NULL)
, scrollActive_(false)
, selectedItem_(NULL)
, textStatusComponent_(NULL)
, selectedItemChanged_(false)
, loadSoundChunk_(NULL)
, unloadSoundChunk_(NULL)
, highlightSoundChunk_(NULL)
, selectSoundChunk_(NULL)
, minShowTime_(0)
{
}
Page::~Page()
{
MenuVector_T::iterator it = Menus.begin();
while(it != Menus.end())
MenuVector_T::iterator it = menus_.begin();
while(it != menus_.end())
{
ScrollingList *menu = *it;
menu->RemoveComponentForNotifications(this);
Menus.erase(it);
menu->removeComponentForNotifications(this);
menus_.erase(it);
delete menu;
it = Menus.begin();
it = menus_.begin();
}
for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i)
@ -65,85 +65,85 @@ Page::~Page()
}
if(LoadSoundChunk)
if(loadSoundChunk_)
{
delete LoadSoundChunk;
LoadSoundChunk = NULL;
delete loadSoundChunk_;
loadSoundChunk_ = NULL;
}
if(UnloadSoundChunk)
if(unloadSoundChunk_)
{
delete UnloadSoundChunk;
UnloadSoundChunk = NULL;
delete unloadSoundChunk_;
unloadSoundChunk_ = NULL;
}
if(HighlightSoundChunk)
if(highlightSoundChunk_)
{
delete HighlightSoundChunk;
HighlightSoundChunk = NULL;
delete highlightSoundChunk_;
highlightSoundChunk_ = NULL;
}
if(SelectSoundChunk)
if(selectSoundChunk_)
{
delete SelectSoundChunk;
SelectSoundChunk = NULL;
delete selectSoundChunk_;
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;
SelectedItemChanged = true;
selectedItem_ = item;
selectedItemChanged_ = true;
}
void Page::PushMenu(ScrollingList *s)
void Page::pushMenu(ScrollingList *s)
{
Menus.push_back(s);
menus_.push_back(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;
unsigned int layer = c->GetBaseViewInfo()->GetLayer();
unsigned int layer = c->baseViewInfo.Layer;
if(layer < NUM_LAYERS)
@ -156,21 +156,21 @@ bool Page::AddComponent(Component *c)
{
std::stringstream ss;
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;
}
bool Page::IsMenuIdle()
bool Page::isMenuIdle()
{
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;
if(!menu->IsIdle())
if(!menu->isIdle())
{
idle = false;
break;
@ -179,15 +179,15 @@ bool Page::IsMenuIdle()
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(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;
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;
if(!menu->IsHidden())
if(!menu->isHidden())
{
hidden = false;
break;
@ -215,70 +215,70 @@ bool Page::IsHidden()
{
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it)
{
hidden = (*it)->IsHidden();
hidden = (*it)->isHidden();
}
}
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;
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(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;
menu->TriggerExitEvent();
menu->triggerExitEvent();
}
if(UnloadSoundChunk)
if(unloadSoundChunk_)
{
UnloadSoundChunk->Play();
unloadSoundChunk_->play();
}
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
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
@ -287,177 +287,177 @@ void Page::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(ActiveMenu)
if(activeMenu_)
{
ActiveMenu->TriggerHighlightEvent(item);
ActiveMenu->SetScrollActive(ScrollActive);
activeMenu_->triggerHighlightEvent(item);
activeMenu_->scrollActive = scrollActive_;
}
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{
(*it)->TriggerHighlightEvent(item);
(*it)->SetScrollActive(ScrollActive);
(*it)->triggerHighlightEvent(item);
(*it)->scrollActive = scrollActive_;
}
}
}
}
void Page::SetScrolling(ScrollDirection direction)
void Page::setScrolling(ScrollDirection direction)
{
ScrollingList::ScrollDirection menuDirection;
bool prevScrollActive = ScrollActive;
bool prevScrollActive = scrollActive_;
switch(direction)
{
case ScrollDirectionForward:
menuDirection = ScrollingList::ScrollDirectionForward;
ScrollActive = true;
scrollActive_ = true;
break;
case ScrollDirectionBack:
menuDirection = ScrollingList::ScrollDirectionBack;
ScrollActive = true;
scrollActive_ = true;
break;
case ScrollDirectionIdle:
default:
menuDirection = ScrollingList::ScrollDirectionIdle;
ScrollActive = false;
scrollActive_ = false;
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)
{
ActiveMenu->PageDown();
activeMenu_->pageDown();
}
if(direction == ScrollDirectionBack)
{
ActiveMenu->PageUp();
activeMenu_->pageUp();
}
}
}
void Page::LetterScroll(ScrollDirection direction)
void Page::letterScroll(ScrollDirection direction)
{
if(ActiveMenu)
if(activeMenu_)
{
if(direction == ScrollDirectionForward)
{
ActiveMenu->LetterDown();
activeMenu_->letterDown();
}
if(direction == ScrollDirectionBack)
{
ActiveMenu->LetterUp();
activeMenu_->letterUp();
}
}
}
bool Page::PushCollection(CollectionInfo *collection)
bool Page::pushCollection(CollectionInfo *collection)
{
Collections.push_back(collection);
std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::BuildCollectionItems(collection->GetItems());
collections_.push_back(collection);
std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::buildCollectionItems(&collection->items);
int menuExitIndex = -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);
newList->ForceIdle();
PushMenu(newList);
ScrollingList *newList = new ScrollingList(*activeMenu_);
newList->forceIdle();
pushMenu(newList);
}
ActiveMenu = Menus[MenuDepth];
ActiveMenu->SetCollectionName(collection->GetName());
ActiveMenu->DestroyItems();
ActiveMenu->SetItems(sprites);
ActiveMenu->TriggerMenuEnterEvent();
activeMenu_ = menus_[menuDepth_];
activeMenu_->collectionName = collection->name;
activeMenu_->destroyItems();
activeMenu_->setItems(sprites);
activeMenu_->triggerMenuEnterEvent();
if(MenuDepth < Menus.size())
if(menuDepth_ < menus_.size())
{
menuEnterIndex = MenuDepth;
MenuDepth++;
menuEnterIndex = menuDepth_;
menuDepth_++;
}
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
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)
{
(*it)->TriggerMenuEnterEvent(menuEnterIndex);
(*it)->triggerMenuEnterEvent(menuEnterIndex);
}
if(menuExitIndex >= 0)
{
(*it)->TriggerMenuExitEvent(menuExitIndex);
(*it)->triggerMenuExitEvent(menuExitIndex);
}
}
}
@ -465,51 +465,51 @@ bool Page::PushCollection(CollectionInfo *collection)
return true;
}
bool Page::PopCollection()
bool Page::popCollection()
{
int menuExitIndex = -1;
int menuEnterIndex = -1;
CollectionInfo *collection = NULL;
if(MenuDepth <= 1)
if(menuDepth_ <= 1)
{
return false;
}
if(Collections.size() <= 1)
if(collections_.size() <= 1)
{
return false;
}
Collections.pop_back();
collection = Collections.back();
collections_.pop_back();
collection = collections_.back();
if(ActiveMenu)
if(activeMenu_)
{
ActiveMenu->TriggerMenuExitEvent();
activeMenu_->triggerMenuExitEvent();
}
MenuDepth--;
menuExitIndex = MenuDepth;
menuDepth_--;
menuExitIndex = menuDepth_;
menuEnterIndex = menuExitIndex - 1;
ActiveMenu = Menus[MenuDepth - 1];
if(ActiveMenu)
activeMenu_ = menus_[menuDepth_ - 1];
if(activeMenu_)
{
ActiveMenu->TriggerMenuEnterEvent();
activeMenu_->triggerMenuEnterEvent();
}
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
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)
{
(*it)->TriggerMenuEnterEvent(menuEnterIndex);
(*it)->triggerMenuEnterEvent(menuEnterIndex);
}
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;
menu->Update(dt);
menu->update(dt);
}
if(SelectedItemChanged && !ScrollActive)
if(selectedItemChanged_ && !scrollActive_)
{
Highlight();
SelectedItemChanged = false;
highlight();
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(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(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;
menu->Draw(i);
menu->draw(i);
}
}
}
std::string Page::GetCollectionName()
std::string Page::getCollectionName()
{
CollectionInfo *info = Collections.back();
CollectionInfo *info = collections_.back();
if(info)
{
return info->GetName();
return info->name;
}
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;
menu->FreeGraphicsMemory();
menu->freeGraphicsMemory();
}
if(LoadSoundChunk) LoadSoundChunk->Free();
if(UnloadSoundChunk) UnloadSoundChunk->Free();
if(HighlightSoundChunk) HighlightSoundChunk->Free();
if(SelectSoundChunk) SelectSoundChunk->Free();
if(loadSoundChunk_) loadSoundChunk_->free();
if(unloadSoundChunk_) unloadSoundChunk_->free();
if(highlightSoundChunk_) highlightSoundChunk_->free();
if(selectSoundChunk_) selectSoundChunk_->free();
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
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;
menu->AllocateGraphicsMemory();
menu->allocateGraphicsMemory();
}
if(LoadSoundChunk) LoadSoundChunk->Allocate();
if(UnloadSoundChunk) UnloadSoundChunk->Allocate();
if(HighlightSoundChunk) HighlightSoundChunk->Allocate();
if(SelectSoundChunk) SelectSoundChunk->Allocate();
if(loadSoundChunk_) loadSoundChunk_->allocate();
if(unloadSoundChunk_) unloadSoundChunk_->allocate();
if(highlightSoundChunk_) highlightSoundChunk_->allocate();
if(selectSoundChunk_) selectSoundChunk_->allocate();
for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{
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(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(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);
virtual ~Page();
virtual void OnNewItemSelected(Item *);
bool PushCollection(CollectionInfo *collection);
bool PopCollection();
void PushMenu(ScrollingList *s);
bool IsMenusFull();
void SetLoadSound(Sound *chunk);
void SetUnloadSound(Sound *chunk);
void SetHighlightSound(Sound *chunk);
void SetSelectSound(Sound *chunk);
bool AddComponent(Component *c);
void PageScroll(ScrollDirection direction);
void LetterScroll(ScrollDirection direction);
void Start();
void StartComponents();
void Stop();
void SetScrolling(ScrollDirection direction);
bool IsHorizontalScroll();
unsigned int GetMenuDepth();
Item *GetSelectedItem();
void RemoveSelectedItem();
void SetScrollOffsetIndex(unsigned int i);
unsigned int GetScrollOffsetIndex();
bool IsIdle();
bool IsMenuIdle();
bool IsHidden();
void SetStatusTextComponent(Text *t);
void Update(float dt);
void Draw();
void FreeGraphicsMemory();
void AllocateGraphicsMemory();
void LaunchEnter();
void LaunchExit();
std::string GetCollectionName();
void SetMinShowTime(float value);
float GetMinShowTime();
virtual void onNewItemSelected(Item *);
bool pushCollection(CollectionInfo *collection);
bool popCollection();
void pushMenu(ScrollingList *s);
bool isMenusFull();
void setLoadSound(Sound *chunk);
void setUnloadSound(Sound *chunk);
void setHighlightSound(Sound *chunk);
void setSelectSound(Sound *chunk);
bool addComponent(Component *c);
void pageScroll(ScrollDirection direction);
void letterScroll(ScrollDirection direction);
void start();
void startComponents();
void stop();
void setScrolling(ScrollDirection direction);
bool isHorizontalScroll();
unsigned int getMenuDepth();
Item *getSelectedItem();
void removeSelectedItem();
void setScrollOffsetIndex(unsigned int i);
unsigned int getScrollOffsetIndex();
bool isIdle();
bool isMenuIdle();
bool isHidden();
void setStatusTextComponent(Text *t);
void update(float dt);
void draw();
void freeGraphicsMemory();
void allocateGraphicsMemory();
void launchEnter();
void launchExit();
std::string getCollectionName();
void setMinShowTime(float value);
float getMinShowTime();
private:
void Highlight();
std::string CollectionName;
Configuration &Config;
void highlight();
std::string collectionName_;
Configuration &config_;
typedef std::vector<ScrollingList *> MenuVector_T;
typedef std::vector<CollectionInfo *> CollectionInfo_T;
ScrollingList *ActiveMenu;
unsigned int MenuDepth;
MenuVector_T Menus;
CollectionInfo_T Collections;
ScrollingList *activeMenu_;
unsigned int menuDepth_;
MenuVector_T menus_;
CollectionInfo_T collections_;
static const unsigned int NUM_LAYERS = 8;
std::vector<Component *> LayerComponents[NUM_LAYERS];
std::vector<Item *> *Items;
bool ScrollActive;
std::vector<Item *> *items_;
bool scrollActive_;
Item *SelectedItem;
Text *TextStatusComponent;
bool SelectedItemChanged;
Sound *LoadSoundChunk;
Sound *UnloadSoundChunk;
Sound *HighlightSoundChunk;
Sound *SelectSoundChunk;
float MinShowTime;
float ElapsedTime;
Item *selectedItem_;
Text *textStatusComponent_;
bool selectedItemChanged_;
Sound *loadSoundChunk_;
Sound *unloadSoundChunk_;
Sound *highlightSoundChunk_;
Sound *selectSoundChunk_;
float minShowTime_;
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
PageBuilder::PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc)
: LayoutKey(layoutKey)
, LayoutPage(layoutPage)
, Config(c)
, ScaleX(1)
, ScaleY(1)
, ScreenHeight(0)
, ScreenWidth(0)
, FontSize(24)
, FC(fc)
: layoutKey(layoutKey)
, layoutPage(layoutPage)
, config_(c)
, scaleX_(1)
, scaleY_(1)
, screenHeight_(0)
, screenWidth_(0)
, fontSize_(24)
, fontCache_(fc)
{
ScreenWidth = SDL::GetWindowWidth();
ScreenHeight = SDL::GetWindowHeight();
FontColor.a = 255;
FontColor.r = 0;
FontColor.g = 0;
FontColor.b = 0;
screenWidth_ = SDL::getWindowWidth();
screenHeight_ = SDL::getWindowHeight();
fontColor_.a = 255;
fontColor_.r = 0;
fontColor_.g = 0;
fontColor_.b = 0;
}
PageBuilder::~PageBuilder()
{
}
Page *PageBuilder::BuildPage()
Page *PageBuilder::buildPage()
{
Page *page = NULL;
std::string layoutFile;
std::string layoutName = LayoutKey;
std::string layoutName = layoutKey;
LayoutPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "layouts", layoutName);
layoutFile = Utils::CombinePath(LayoutPath, LayoutPage + ".xml");
layoutPath = Utils::combinePath(Configuration::absolutePath, "layouts", layoutName);
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;
std::ifstream file(layoutFile.c_str());
@ -88,7 +88,7 @@ Page *PageBuilder::BuildPage()
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;
}
@ -103,7 +103,7 @@ Page *PageBuilder::BuildPage()
if(!root)
{
Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing <layout> tag");
Logger::write(Logger::ZONE_ERROR, "Layout", "Missing <layout> tag");
return NULL;
}
else
@ -119,13 +119,13 @@ Page *PageBuilder::BuildPage()
int layoutWidth;
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;
}
if(fontXml)
{
FontName = Config.ConvertToAbsolutePath(
Utils::CombinePath(Config.GetAbsolutePath(), "layouts", LayoutKey, ""),
fontName_ = config_.convertToAbsolutePath(
Utils::combinePath(config_.absolutePath, "layouts", layoutKey, ""),
fontXml->value());
}
@ -136,39 +136,39 @@ Page *PageBuilder::BuildPage()
ss << std::hex << fontColorXml->value();
ss >> intColor;
FontColor.b = intColor & 0xFF;
fontColor_.b = intColor & 0xFF;
intColor >>= 8;
FontColor.g = intColor & 0xFF;
fontColor_.g = intColor & 0xFF;
intColor >>= 8;
FontColor.r = intColor & 0xFF;
fontColor_.r = intColor & 0xFF;
}
if(fontSizeXml)
{
FontSize = Utils::ConvertInt(fontSizeXml->value());
fontSize_ = Utils::convertInt(fontSizeXml->value());
}
layoutWidth = Utils::ConvertInt(layoutWidthXml->value());
layoutHeight = Utils::ConvertInt(layoutHeightXml->value());
layoutWidth = Utils::convertInt(layoutWidthXml->value());
layoutHeight = Utils::convertInt(layoutHeightXml->value());
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;
}
ScaleX = (float)ScreenWidth / (float)layoutWidth;
ScaleY = (float)ScreenHeight / (float)layoutHeight;
scaleX_ = (float)screenWidth_ / (float)layoutWidth;
scaleY_ = (float)screenHeight_ / (float)layoutHeight;
std::stringstream ss;
ss << layoutWidth << "x" << layoutHeight << " (scale " << ScaleX << "x" << ScaleY << ")";
Logger::Write(Logger::ZONE_INFO, "Layout", "Layout resolution " + ss.str());
ss << layoutWidth << "x" << layoutHeight << " (scale " << scaleX_ << "x" << scaleY_ << ")";
Logger::write(Logger::ZONE_INFO, "Layout", "Layout resolution " + ss.str());
page = new Page(Config);
page = new Page(config_);
if(minShowTimeXml)
{
page->SetMinShowTime(Utils::ConvertFloat(minShowTimeXml->value()));
page->setMinShowTime(Utils::convertFloat(minShowTimeXml->value()));
}
// load sounds
@ -176,10 +176,10 @@ Page *PageBuilder::BuildPage()
{
xml_attribute<> *src = sound->first_attribute("src");
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)
{
Logger::Write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute");
Logger::write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute");
}
else
{
@ -188,28 +188,28 @@ Page *PageBuilder::BuildPage()
if(!soundType.compare("load"))
{
page->SetLoadSound(sound);
page->setLoadSound(sound);
}
else if(!soundType.compare("unload"))
{
page->SetUnloadSound(sound);
page->setUnloadSound(sound);
}
else if(!soundType.compare("highlight"))
{
page->SetHighlightSound(sound);
page->setHighlightSound(sound);
}
else if(!soundType.compare("select"))
{
page->SetSelectSound(sound);
page->setSelectSound(sound);
}
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;
page = NULL;
@ -225,21 +225,21 @@ Page *PageBuilder::BuildPage()
std::stringstream ss;
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)
{
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)
{
Logger::Write(Logger::ZONE_INFO, "Layout", "Initialized");
Logger::write(Logger::ZONE_INFO, "Layout", "Initialized");
}
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;
@ -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;
std::string str;
@ -266,22 +266,22 @@ float PageBuilder::GetHorizontalAlignment(xml_attribute<> *attribute, float valu
}
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"))
{
value = static_cast<float>(ScreenWidth);
value = static_cast<float>(screenWidth_);
}
else
{
value = Utils::ConvertFloat(str) * ScaleX;
value = Utils::convertFloat(str) * scaleX_;
}
}
return value;
}
float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueIfNull)
float PageBuilder::getVerticalAlignment(xml_attribute<> *attribute, float valueIfNull)
{
float value;
std::string str;
@ -299,15 +299,15 @@ float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueI
}
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"))
{
value = static_cast<float>(ScreenHeight);
value = static_cast<float>(screenHeight_);
}
else
{
value = Utils::ConvertFloat(str) * ScaleY;
value = Utils::convertFloat(str) * scaleY_;
}
}
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"))
{
ScrollingList *scrollingList = BuildMenu(componentXml);
page->PushMenu(scrollingList);
ScrollingList *scrollingList = buildMenu(componentXml);
page->pushMenu(scrollingList);
}
for(xml_node<> *componentXml = layout->first_node("container"); componentXml; componentXml = componentXml->next_sibling("container"))
{
Container *c = new Container();
ViewInfo *v = c->GetBaseViewInfo();
BuildViewInfo(componentXml, v);
LoadTweens(c, componentXml);
page->AddComponent(c);
buildViewInfo(componentXml, c->baseViewInfo);
loadTweens(c, componentXml);
page->addComponent(c);
}
@ -340,18 +339,17 @@ bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page)
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
{
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);
ViewInfo *v = c->GetBaseViewInfo();
BuildViewInfo(componentXml, v);
LoadTweens(c, componentXml);
page->AddComponent(c);
Image *c = new Image(imagePath, scaleX_, scaleY_);
buildViewInfo(componentXml, c->baseViewInfo);
loadTweens(c, componentXml);
page->addComponent(c);
}
}
@ -362,43 +360,41 @@ bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page)
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
{
Font *font = AddFont(componentXml, NULL);
Text *c = new Text(value->value(), font, ScaleX, ScaleY);
ViewInfo *v = c->GetBaseViewInfo();
Font *font = addFont(componentXml, NULL);
Text *c = new Text(value->value(), font, scaleX_, scaleY_);
BuildViewInfo(componentXml, v);
buildViewInfo(componentXml, c->baseViewInfo);
LoadTweens(c, componentXml);
page->AddComponent(c);
loadTweens(c, componentXml);
page->addComponent(c);
}
}
for(xml_node<> *componentXml = layout->first_node("statusText"); componentXml; componentXml = componentXml->next_sibling("statusText"))
{
Font *font = AddFont(componentXml, NULL);
Text *c = new Text("", font, ScaleX, ScaleY);
ViewInfo *v = c->GetBaseViewInfo();
Font *font = addFont(componentXml, NULL);
Text *c = new Text("", font, scaleX_, scaleY_);
BuildViewInfo(componentXml, v);
buildViewInfo(componentXml, c->baseViewInfo);
LoadTweens(c, componentXml);
page->AddComponent(c);
page->SetStatusTextComponent(c);
loadTweens(c, componentXml);
page->addComponent(c);
page->setStatusTextComponent(c);
}
LoadReloadableImages(layout, "reloadableImage", page);
LoadReloadableImages(layout, "reloadableVideo", page);
LoadReloadableImages(layout, "reloadableText", page);
loadReloadableImages(layout, "reloadableImage", page);
loadReloadableImages(layout, "reloadableVideo", page);
loadReloadableImages(layout, "reloadableText", page);
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()))
@ -417,11 +413,11 @@ void PageBuilder::LoadReloadableImages(xml_node<> *layout, std::string tagName,
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"))
{
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)
{
Font *font = AddFont(componentXml, NULL);
c = new ReloadableText(type->value(), font, LayoutKey, ScaleX, ScaleY);
Font *font = addFont(componentXml, NULL);
c = new ReloadableText(type->value(), font, layoutKey, scaleX_, scaleY_);
}
}
else
{
Font *font = AddFont(componentXml, NULL);
c = new ReloadableMedia(Config, systemMode, type->value(), (tagName == "reloadableVideo"), font, ScaleX, ScaleY);
Font *font = addFont(componentXml, NULL);
c = new ReloadableMedia(config_, systemMode, type->value(), (tagName == "reloadableVideo"), font, scaleX_, scaleY_);
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
{
static_cast<ReloadableMedia *>(c)->EnableTextFallback(false);
static_cast<ReloadableMedia *>(c)->enableTextFallback_(false);
}
}
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<> *fontColorXml = component->first_attribute("fontColor");
@ -496,17 +492,17 @@ Font *PageBuilder::AddFont(xml_node<> *component, xml_node<> *defaults)
// use layout defaults unless overridden
std::string fontName = FontName;
SDL_Color fontColor = FontColor;
int fontSize = FontSize;
std::string fontName = fontName_;
SDL_Color fontColor = fontColor_;
int fontSize = fontSize_;
if(fontXml)
{
fontName = Config.ConvertToAbsolutePath(
Utils::CombinePath(Config.GetAbsolutePath(), "layouts", LayoutKey,""),
fontName = config_.convertToAbsolutePath(
Utils::combinePath(config_.absolutePath, "layouts", layoutKey,""),
fontXml->value());
Logger::Write(Logger::ZONE_DEBUG, "Layout", "loading font " + fontName );
Logger::write(Logger::ZONE_DEBUG, "Layout", "loading font " + fontName );
}
if(fontColorXml)
{
@ -524,53 +520,51 @@ Font *PageBuilder::AddFont(xml_node<> *component, xml_node<> *defaults)
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();
BuildTweenSet(tweens, componentXml, "onEnter", "enter");
BuildTweenSet(tweens, componentXml, "onExit", "exit");
BuildTweenSet(tweens, componentXml, "onIdle", "idle");
BuildTweenSet(tweens, componentXml, "onHighlightEnter", "highlightEnter");
BuildTweenSet(tweens, componentXml, "onHighlightExit", "highlightExit");
BuildTweenSet(tweens, componentXml, "onMenuEnter", "menuEnter");
BuildTweenSet(tweens, componentXml, "onMenuExit", "menuExit");
buildTweenSet(tweens, componentXml, "onEnter", "enter");
buildTweenSet(tweens, componentXml, "onExit", "exit");
buildTweenSet(tweens, componentXml, "onIdle", "idle");
buildTweenSet(tweens, componentXml, "onHighlightEnter", "highlightEnter");
buildTweenSet(tweens, componentXml, "onHighlightExit", "highlightExit");
buildTweenSet(tweens, componentXml, "onMenuEnter", "menuEnter");
buildTweenSet(tweens, componentXml, "onMenuExit", "menuExit");
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()))
{
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();
GetTweenSet(componentXml, animation);
tweens->SetAnimation(tweenName, index, animation);
getTweenSet(componentXml, animation);
tweens->setAnimation(tweenName, index, animation);
}
}
ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
ScrollingList * PageBuilder::buildMenu(xml_node<> *menuXml)
{
ScrollingList *menu = NULL;
std::string menuType = "vertical";
@ -591,7 +585,7 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
// ensure <menu> has an <itemDefaults> tag
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)
@ -600,18 +594,18 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
}
// 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)
{
menu->SetStartScrollTime(Utils::ConvertFloat(scrollTimeXml->value()));
menu->setStartScrollTime(Utils::convertFloat(scrollTimeXml->value()));
}
if(scrollAccelerationXml)
{
menu->SetScrollAcceleration(Utils::ConvertFloat(scrollAccelerationXml->value()));
menu->setScrollAcceleration(Utils::convertFloat(scrollAccelerationXml->value()));
}
if(scrollOrientationXml)
@ -619,29 +613,28 @@ ScrollingList * PageBuilder::BuildMenu(xml_node<> *menuXml)
std::string scrollOrientation = scrollOrientationXml->value();
if(scrollOrientation == "horizontal")
{
menu->SetScrollOrientation(true);
menu->horizontalScroll = true;
}
}
ViewInfo *v = menu->GetBaseViewInfo();
BuildViewInfo(menuXml, v);
buildViewInfo(menuXml, menu->baseViewInfo);
if(menuType == "custom")
{
BuildCustomMenu(menu, menuXml, itemDefaults);
buildCustomMenu(menu, menuXml, itemDefaults);
}
else
{
BuildVerticalMenu(menu, menuXml, itemDefaults);
buildVerticalMenu(menu, menuXml, itemDefaults);
}
LoadTweens(menu, menuXml);
loadTweens(menu, menuXml);
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<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"))
{
ViewInfo *viewInfo = new ViewInfo();
BuildViewInfo(componentXml, viewInfo, itemDefaults);
buildViewInfo(componentXml, *viewInfo, itemDefaults);
points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(componentXml));
tweenPoints->push_back(createTweenInstance(componentXml));
xml_attribute<> *selected = componentXml->first_attribute("selected");
if(selected)
{
menu->SetSelectedIndex(i);
menu->setSelectedIndex(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<AnimationEvents *> *tweenPoints = new std::vector<AnimationEvents *>();
@ -685,7 +678,7 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
if(xmlIndex)
{
int itemIndex = ParseMenuPosition(xmlIndex->value());
int itemIndex = parseMenuPosition(xmlIndex->value());
overrideItems[itemIndex] = componentXml;
// 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())
{
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);
tweenPoints->push_back(CreateTweenInstance(component));
height += viewInfo->GetHeight();
tweenPoints->push_back(createTweenInstance(component));
height += viewInfo->Height;
// increment the selected index to account for the new "invisible" menu item
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
BuildViewInfo(component, viewInfo, itemDefaults);
buildViewInfo(component, *viewInfo, itemDefaults);
xml_attribute<> *itemSpacingXml = component->first_attribute("spacing");
int itemSpacing = itemSpacingXml ? Utils::ConvertInt(itemSpacingXml->value()) : 0;
float nextHeight = height + viewInfo->GetHeight() + itemSpacing;
int itemSpacing = itemSpacingXml ? Utils::convertInt(itemSpacingXml->value()) : 0;
float nextHeight = height + viewInfo->Height + itemSpacing;
if(nextHeight >= menu->GetBaseViewInfo()->GetHeight())
if(nextHeight >= menu->baseViewInfo.Height)
{
end = true;
}
@ -743,15 +736,15 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
{
component = overrideItems[MENU_LAST];
BuildViewInfo(component, viewInfo, itemDefaults);
buildViewInfo(component, *viewInfo, itemDefaults);
xml_attribute<> *itemSpacingXml = component->first_attribute("spacing");
int itemSpacing = itemSpacingXml ? Utils::ConvertInt(itemSpacingXml->value()) : 0;
nextHeight = height + viewInfo->GetHeight() + itemSpacing;
int itemSpacing = itemSpacingXml ? Utils::convertInt(itemSpacingXml->value()) : 0;
nextHeight = height + viewInfo->Height + itemSpacing;
}
viewInfo->SetY(menu->GetBaseViewInfo()->GetY() + (float)height);
viewInfo->Y = menu->baseViewInfo.Y + (float)height;
points->push_back(viewInfo);
tweenPoints->push_back(CreateTweenInstance(component));
tweenPoints->push_back(createTweenInstance(component));
index++;
height = nextHeight;
}
@ -760,9 +753,9 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
if(overrideItems.find(MENU_END) != overrideItems.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);
tweenPoints->push_back(CreateTweenInstance(component));
tweenPoints->push_back(createTweenInstance(component));
}
if(selectedIndex >= ((int)points->size()))
@ -774,25 +767,25 @@ void PageBuilder::BuildVerticalMenu(ScrollingList *menu, xml_node<> *menuXml, xm
<< " although there are only " << points->size()
<< " 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;
}
menu->SetSelectedIndex(selectedIndex);
menu->SetPoints(points, tweenPoints);
menu->setSelectedIndex(selectedIndex);
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();
BuildViewInfo(component, viewInfo, defaults);
viewInfo->SetY(y);
buildViewInfo(component, *viewInfo, defaults);
viewInfo->Y = y;
return viewInfo;
}
int PageBuilder::ParseMenuPosition(std::string strIndex)
int PageBuilder::parseMenuPosition(std::string strIndex)
{
int index = MENU_FIRST;
@ -814,12 +807,12 @@ int PageBuilder::ParseMenuPosition(std::string strIndex)
}
else
{
index = Utils::ConvertInt(strIndex);
index = Utils::convertInt(strIndex);
}
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());
@ -831,58 +824,58 @@ xml_attribute<> *PageBuilder::FindAttribute(xml_node<> *componentXml, std::strin
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<> *y = FindAttribute(componentXml, "y", defaultXml);
xml_attribute<> *xOffset = FindAttribute(componentXml, "xOffset", defaultXml);
xml_attribute<> *yOffset = FindAttribute(componentXml, "yOffset", defaultXml);
xml_attribute<> *xOrigin = FindAttribute(componentXml, "xOrigin", defaultXml);
xml_attribute<> *yOrigin = FindAttribute(componentXml, "yOrigin", defaultXml);
xml_attribute<> *height = FindAttribute(componentXml, "height", defaultXml);
xml_attribute<> *width = FindAttribute(componentXml, "width", defaultXml);
xml_attribute<> *fontSize = FindAttribute(componentXml, "fontSize", defaultXml);
xml_attribute<> *minHeight = FindAttribute(componentXml, "minHeight", defaultXml);
xml_attribute<> *minWidth = FindAttribute(componentXml, "minWidth", defaultXml);
xml_attribute<> *maxHeight = FindAttribute(componentXml, "maxHeight", defaultXml);
xml_attribute<> *maxWidth = FindAttribute(componentXml, "maxWidth", defaultXml);
xml_attribute<> *alpha = FindAttribute(componentXml, "alpha", defaultXml);
xml_attribute<> *angle = FindAttribute(componentXml, "angle", defaultXml);
xml_attribute<> *layer = FindAttribute(componentXml, "layer", defaultXml);
xml_attribute<> *backgroundColor = FindAttribute(componentXml, "backgroundColor", defaultXml);
xml_attribute<> *backgroundAlpha = FindAttribute(componentXml, "backgroundAlpha", defaultXml);
xml_attribute<> *x = findAttribute(componentXml, "x", defaultXml);
xml_attribute<> *y = findAttribute(componentXml, "y", defaultXml);
xml_attribute<> *xOffset = findAttribute(componentXml, "xOffset", defaultXml);
xml_attribute<> *yOffset = findAttribute(componentXml, "yOffset", defaultXml);
xml_attribute<> *xOrigin = findAttribute(componentXml, "xOrigin", defaultXml);
xml_attribute<> *yOrigin = findAttribute(componentXml, "yOrigin", defaultXml);
xml_attribute<> *height = findAttribute(componentXml, "height", defaultXml);
xml_attribute<> *width = findAttribute(componentXml, "width", defaultXml);
xml_attribute<> *fontSize = findAttribute(componentXml, "fontSize", defaultXml);
xml_attribute<> *minHeight = findAttribute(componentXml, "minHeight", defaultXml);
xml_attribute<> *minWidth = findAttribute(componentXml, "minWidth", defaultXml);
xml_attribute<> *maxHeight = findAttribute(componentXml, "maxHeight", defaultXml);
xml_attribute<> *maxWidth = findAttribute(componentXml, "maxWidth", defaultXml);
xml_attribute<> *alpha = findAttribute(componentXml, "alpha", defaultXml);
xml_attribute<> *angle = findAttribute(componentXml, "angle", defaultXml);
xml_attribute<> *layer = findAttribute(componentXml, "layer", defaultXml);
xml_attribute<> *backgroundColor = findAttribute(componentXml, "backgroundColor", defaultXml);
xml_attribute<> *backgroundAlpha = findAttribute(componentXml, "backgroundAlpha", defaultXml);
info->SetX(GetHorizontalAlignment(x, 0));
info->SetY(GetVerticalAlignment(y, 0));
info.X = getHorizontalAlignment(x, 0);
info.Y = getVerticalAlignment(y, 0);
info->SetXOffset( GetHorizontalAlignment(xOffset, 0));
info->SetYOffset( GetVerticalAlignment(yOffset, 0));
float xOriginRelative = GetHorizontalAlignment(xOrigin, 0);
float yOriginRelative = GetVerticalAlignment(yOrigin, 0);
info.XOffset = getHorizontalAlignment(xOffset, 0);
info.YOffset = getVerticalAlignment(yOffset, 0);
float xOriginRelative = getHorizontalAlignment(xOrigin, 0);
float yOriginRelative = getVerticalAlignment(yOrigin, 0);
// the origins need to be saved as a percent since the heights and widths can be scaled
info->SetXOrigin(xOriginRelative / ScreenWidth);
info->SetYOrigin(yOriginRelative / ScreenHeight);
info.XOrigin = xOriginRelative / screenWidth_;
info.YOrigin = yOriginRelative / screenHeight_;
if(!height && !width)
{
info->SetHeight(-1);
info->SetWidth(-1);
info.Height = -1;
info.Width = -1;
}
else
{
info->SetHeight(GetVerticalAlignment(height, -1));
info->SetWidth(GetHorizontalAlignment(width, -1));
info.Height = getVerticalAlignment(height, -1);
info.Width = getHorizontalAlignment(width, -1);
}
info->SetFontSize(GetVerticalAlignment(fontSize, -1));
info->SetMinHeight(GetVerticalAlignment(minHeight, 0));
info->SetMinWidth(GetHorizontalAlignment(minWidth, 0));
info->SetMaxHeight(GetVerticalAlignment(maxHeight, FLT_MAX));
info->SetMaxWidth(GetVerticalAlignment(maxWidth, FLT_MAX));
info->SetAlpha( alpha ? Utils::ConvertFloat(alpha->value()) : 1);
info->SetAngle( angle ? Utils::ConvertFloat(angle->value()) : 0);
info->SetLayer( layer ? Utils::ConvertInt(layer->value()) : 0);
info.FontSize = getVerticalAlignment(fontSize, -1);
info.MinHeight = getVerticalAlignment(minHeight, 0);
info.MinWidth = getHorizontalAlignment(minWidth, 0);
info.MaxHeight = getVerticalAlignment(maxHeight, FLT_MAX);
info.MaxWidth = getVerticalAlignment(maxWidth, FLT_MAX);
info.Alpha = alpha ? Utils::convertFloat(alpha->value()) : 1.f;
info.Angle = angle ? Utils::convertFloat(angle->value()) : 0.f;
info.Layer = layer ? Utils::convertInt(layer->value()) : 0;
if(backgroundColor)
{
@ -893,37 +886,37 @@ void PageBuilder::BuildViewInfo(xml_node<> *componentXml, ViewInfo *info, xml_no
int green = (num / 0x100) % 0x100;
int blue = num % 0x100;
info->SetBackgroundRed(static_cast<float>(red)/255);
info->SetBackgroundGreen(static_cast<float>(green)/255);
info->SetBackgroundBlue(static_cast<float>(blue)/255);
info.BackgroundRed = static_cast<float>(red/255);
info.BackgroundGreen = static_cast<float>(green/255);
info.BackgroundBlue = static_cast<float>(blue/255);
}
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)
{
for(xml_node<> *set = node->first_node("set"); set; set = set->next_sibling("set"))
{
TweenSet *ts = new TweenSet();
GetAnimationEvents(set, *ts);
getAnimationEvents(set, *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");
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
{
@ -936,60 +929,60 @@ void PageBuilder::GetAnimationEvents(xml_node<> *node, TweenSet &tweens)
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)
{
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)
{
Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute");
Logger::write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute");
}
else
{
float fromValue = Utils::ConvertFloat(from->value());
float toValue = Utils::ConvertFloat(to->value());
float durationValue = Utils::ConvertFloat(durationXml->value());
float fromValue = Utils::convertFloat(from->value());
float toValue = Utils::convertFloat(to->value());
float durationValue = Utils::convertFloat(durationXml->value());
TweenAlgorithm algorithm = LINEAR;
TweenProperty property;
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)
{
case TWEEN_PROPERTY_WIDTH:
case TWEEN_PROPERTY_X:
case TWEEN_PROPERTY_X_OFFSET:
fromValue = GetHorizontalAlignment(from, 0);
toValue = GetHorizontalAlignment(to, 0);
fromValue = getHorizontalAlignment(from, 0);
toValue = getHorizontalAlignment(to, 0);
break;
// x origin gets translated to a percent
case TWEEN_PROPERTY_X_ORIGIN:
fromValue = GetHorizontalAlignment(from, 0) / ScreenWidth;
toValue = GetHorizontalAlignment(to, 0) / ScreenWidth;
fromValue = getHorizontalAlignment(from, 0) / screenWidth_;
toValue = getHorizontalAlignment(to, 0) / screenWidth_;
break;
case TWEEN_PROPERTY_HEIGHT:
case TWEEN_PROPERTY_Y:
case TWEEN_PROPERTY_Y_OFFSET:
case TWEEN_PROPERTY_FONT_SIZE:
fromValue = GetVerticalAlignment(from, 0);
toValue = GetVerticalAlignment(to, 0);
fromValue = getVerticalAlignment(from, 0);
toValue = getVerticalAlignment(to, 0);
break;
// y origin gets translated to a percent
case TWEEN_PROPERTY_Y_ORIGIN:
fromValue = GetVerticalAlignment(from, 0) / ScreenHeight;
toValue = GetVerticalAlignment(to, 0) / ScreenHeight;
fromValue = getVerticalAlignment(from, 0) / screenHeight_;
toValue = getVerticalAlignment(to, 0) / screenHeight_;
break;
default:
@ -997,13 +990,13 @@ void PageBuilder::GetAnimationEvents(xml_node<> *node, TweenSet &tweens)
}
Tween *t = new Tween(property, algorithm, fromValue, toValue, durationValue);
tweens.Push(t);
tweens.push(t);
}
else
{
std::stringstream ss;
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:
PageBuilder(std::string layoutKey, std::string layoutPage, Configuration &c, FontCache *fc);
virtual ~PageBuilder();
Page *BuildPage();
Page *buildPage();
private:
std::string LayoutKey;
std::string LayoutPage;
std::string LayoutPath;
Configuration &Config;
float ScaleX;
float ScaleY;
int ScreenHeight;
int ScreenWidth;
SDL_Color FontColor;
std::string FontName;
int FontSize;
FontCache *FC;
std::string layoutKey;
std::string layoutPage;
std::string layoutPath;
Configuration &config_;
float scaleX_;
float scaleY_;
int screenHeight_;
int screenWidth_;
SDL_Color fontColor_;
std::string fontName_;
int fontSize_;
FontCache *fontCache_;
Font *AddFont(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults);
void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page);
float GetVerticalAlignment(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);
bool BuildComponents(rapidxml::xml_node<> *layout, Page *page);
void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml);
AnimationEvents *CreateTweenInstance(rapidxml::xml_node<> *componentXml);
void BuildTweenSet(AnimationEvents *tweens, rapidxml::xml_node<> *componentXml, std::string tagName, std::string tweenName);
ScrollingList * BuildMenu(rapidxml::xml_node<> *menuXml);
void BuildCustomMenu(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);
rapidxml::xml_attribute<> *FindAttribute(rapidxml::xml_node<> *componentXml, std::string attribute, rapidxml::xml_node<> *defaultXml);
void GetTweenSet(rapidxml::xml_node<> *node, Animation *animation);
void GetAnimationEvents(rapidxml::xml_node<> *node, TweenSet &tweens);
ViewInfo * CreateMenuItemInfo(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults, float y);
Font *addFont(rapidxml::xml_node<> *component, rapidxml::xml_node<> *defaults);
void loadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page);
float getVerticalAlignment(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);
bool buildComponents(rapidxml::xml_node<> *layout, Page *page);
void loadTweens(Component *c, rapidxml::xml_node<> *componentXml);
AnimationEvents *createTweenInstance(rapidxml::xml_node<> *componentXml);
void buildTweenSet(AnimationEvents *tweens, rapidxml::xml_node<> *componentXml, std::string tagName, std::string tweenName);
ScrollingList * buildMenu(rapidxml::xml_node<> *menuXml);
void buildCustomMenu(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);
rapidxml::xml_attribute<> *findAttribute(rapidxml::xml_node<> *componentXml, std::string attribute, rapidxml::xml_node<> *defaultXml);
void getTweenSet(rapidxml::xml_node<> *node, Animation *animation);
void getAnimationEvents(rapidxml::xml_node<> *node, TweenSet &tweens);
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 width = GetAbsoluteWidth();
float height = AbsoluteHeight();
float width = AbsoluteWidth();
if (height < MinHeight || width < MinWidth)
{
@ -105,10 +105,10 @@ float ViewInfo::GetHeight() const
return height;
}
float ViewInfo::GetWidth() const
float ViewInfo::ScaledWidth() const
{
float height = GetAbsoluteHeight();
float width = GetAbsoluteWidth();
float height = AbsoluteHeight();
float width = AbsoluteWidth();
if (height < MinHeight || width < MinWidth)
{
@ -150,7 +150,7 @@ float ViewInfo::GetWidth() const
return width;
}
float ViewInfo::GetAbsoluteHeight() const
float ViewInfo::AbsoluteHeight() const
{
if(Height == -1 && Width == -1)
{
@ -165,7 +165,7 @@ float ViewInfo::GetAbsoluteHeight() const
return Height;
}
float ViewInfo::GetAbsoluteWidth() const
float ViewInfo::AbsoluteWidth() const
{
if(Height == -1 && Width == -1)
{
@ -179,245 +179,3 @@ float ViewInfo::GetAbsoluteWidth() const
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();
virtual ~ViewInfo();
float GetXRelativeToOrigin() const;
float GetYRelativeToOrigin() const;
float XRelativeToOrigin() const;
float YRelativeToOrigin() const;
float GetHeight() const;
float GetWidth() 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);
float ScaledHeight() const;
float ScaledWidth() const;
static const int AlignCenter = -1;
static const int AlignLeft = -2;
@ -87,9 +38,6 @@ public:
static const int AlignRight = -4;
static const int AlignBottom = -5;
private:
float GetAbsoluteHeight() const;
float GetAbsoluteWidth() const;
float X;
float Y;
float XOrigin;
@ -114,4 +62,8 @@ private:
float BackgroundGreen;
float BackgroundBlue;
float BackgroundAlpha;
private:
float AbsoluteHeight() const;
float AbsoluteWidth() const;
};

View File

@ -30,7 +30,7 @@ static bool StartLogging();
int main(int argc, char **argv)
{
Configuration::Initialize();
Configuration::initialize();
Configuration config;
@ -47,7 +47,7 @@ int main(int argc, char **argv)
if(param == "-createcollection")
{
CollectionInfoBuilder::CreateCollectionDirectory(value);
CollectionInfoBuilder::createCollectionDirectory(value);
}
return 0;
@ -61,34 +61,34 @@ int main(int argc, char **argv)
RetroFE p(config);
p.Run();
p.run();
p.DeInitialize();
p.deInitialize();
Logger::DeInitialize();
Logger::deInitialize();
return 0;
}
bool ImportConfiguration(Configuration *c)
{
std::string configPath = Configuration::GetAbsolutePath();
std::string launchersPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "launchers");
std::string collectionsPath = Utils::CombinePath(Configuration::GetAbsolutePath(), "collections");
std::string configPath = Configuration::absolutePath;
std::string launchersPath = Utils::combinePath(Configuration::absolutePath, "launchers");
std::string collectionsPath = Utils::combinePath(Configuration::absolutePath, "collections");
DIR *dp;
struct dirent *dirp;
std::string settingsConfPath = Utils::CombinePath(configPath, "settings.conf");
if(!c->Import("", settingsConfPath))
std::string settingsConfPath = Utils::combinePath(configPath, "settings.conf");
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;
}
std::string controlsConfPath = Utils::CombinePath(configPath, "controls.conf");
if(!c->Import("controls", controlsConfPath))
std::string controlsConfPath = Utils::combinePath(configPath, "controls.conf");
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;
}
@ -96,7 +96,7 @@ bool ImportConfiguration(Configuration *c)
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;
}
@ -113,11 +113,11 @@ bool ImportConfiguration(Configuration *c)
{
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);
return false;
}
@ -131,7 +131,7 @@ bool ImportConfiguration(Configuration *c)
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;
}
@ -142,11 +142,11 @@ bool ImportConfiguration(Configuration *c)
{
std::string prefix = "collections." + std::string(dirp->d_name);
std::string settingsFile = Utils::CombinePath(collectionsPath, std::string(dirp->d_name), "settings.conf");
std::string settingsFile = Utils::combinePath(collectionsPath, std::string(dirp->d_name), "settings.conf");
if(!c->Import(prefix, settingsFile))
if(!c->import(prefix, settingsFile))
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\"");
Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\"");
closedir(dp);
return false;
}
@ -155,30 +155,30 @@ bool ImportConfiguration(Configuration *c)
closedir(dp);
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration");
Logger::write(Logger::ZONE_INFO, "RetroFE", "Imported configuration");
return true;
}
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;
}
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting");
Logger::write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::getString() + " starting");
#ifdef WIN32
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows");
Logger::write(Logger::ZONE_INFO, "RetroFE", "OS: Windows");
#else
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux");
Logger::write(Logger::ZONE_INFO, "RetroFE", "OS: Linux");
#endif
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath());
Logger::write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::absolutePath);
return true;
}

View File

@ -39,176 +39,176 @@
#endif
RetroFE::RetroFE(Configuration &c)
: Initialized(false)
, InitializeError(false)
, InitializeThread(NULL)
, Config(c)
, Db(NULL)
, MetaDb(NULL)
, Input(Config)
, CurrentPage(NULL)
, KeyInputDisable(0)
, CurrentTime(0)
: initialized(false)
, initializeError(false)
, initializeThread(NULL)
, config_(c)
, db_(NULL)
, metadb_(NULL)
, input_(config_)
, currentPage_(NULL)
, keyInputDisable_(0)
, currentTime_(0)
{
}
RetroFE::~RetroFE()
{
DeInitialize();
deInitialize();
}
void RetroFE::Render()
void RetroFE::render()
{
SDL_LockMutex(SDL::GetMutex());
SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF);
SDL_RenderClear(SDL::GetRenderer());
SDL_LockMutex(SDL::getMutex());
SDL_SetRenderDrawColor(SDL::getRenderer(), 0x0, 0x0, 0x00, 0xFF);
SDL_RenderClear(SDL::getRenderer());
if(CurrentPage)
if(currentPage_)
{
CurrentPage->Draw();
currentPage_->draw();
}
SDL_RenderPresent(SDL::GetRenderer());
SDL_UnlockMutex(SDL::GetMutex());
SDL_RenderPresent(SDL::getRenderer());
SDL_UnlockMutex(SDL::getMutex());
}
int RetroFE::Initialize(void *context)
int RetroFE::initialize(void *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");
instance->InitializeError = true;
Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize user controls");
instance->initializeError = true;
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");
instance->InitializeError = true;
Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize database");
instance->initializeError = true;
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");
instance->InitializeError = true;
Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not initialize meta database");
instance->initializeError = true;
return -1;
}
instance->Initialized = true;
instance->initialized = true;
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_RaiseWindow(SDL::GetWindow());
SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE);
Input.ResetKeyStates();
Attract.Reset();
SDL_RestoreWindow(SDL::getWindow());
SDL_RaiseWindow(SDL::getWindow());
SDL_SetWindowGrab(SDL::getWindow(), SDL_TRUE);
input_.resetKeyStates();
attract_.reset();
CurrentTime = static_cast<float>(SDL_GetTicks()) / 1000;
if(CurrentPage)
currentTime_ = static_cast<float>(SDL_GetTicks()) / 1000;
if(currentPage_)
{
CurrentPage->LaunchExit();
currentPage_->launchExit();
}
}
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->Start();
currentPage_->allocateGraphicsMemory();
currentPage_->start();
}
}
bool RetroFE::DeInitialize()
bool RetroFE::deInitialize()
{
bool retVal = true;
FreeGraphicsMemory();
freeGraphicsMemory();
if(CurrentPage)
if(currentPage_)
{
delete CurrentPage;
CurrentPage = NULL;
delete currentPage_;
currentPage_ = NULL;
}
if(MetaDb)
if(metadb_)
{
delete MetaDb;
MetaDb = NULL;
delete metadb_;
metadb_ = NULL;
}
if(Db)
if(db_)
{
delete Db;
Db = NULL;
delete db_;
db_ = NULL;
}
Initialized = false;
initialized = false;
//todo: handle video deallocation
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Exiting");
Logger::write(Logger::ZONE_INFO, "RetroFE", "Exiting");
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;
bool videoEnable = true;
int videoLoop = 0;
Config.GetProperty("videoEnable", videoEnable);
Config.GetProperty("videoLoop", videoLoop);
config_.getProperty("videoEnable", videoEnable);
config_.getProperty("videoLoop", videoLoop);
VideoFactory::SetEnabled(videoEnable);
VideoFactory::SetNumLoops(videoLoop);
VideoFactory::CreateVideo(); // pre-initialize the gstreamer engine
VideoFactory::setEnabled(videoEnable);
VideoFactory::setNumLoops(videoLoop);
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;
}
@ -217,18 +217,18 @@ void RetroFE::Run()
bool running = true;
RETROFE_STATE state = RETROFE_NEW;
Config.GetProperty("attractModeTime", attractModeTime);
Config.GetProperty("firstCollection", firstCollection);
config_.getProperty("attractModeTime", attractModeTime);
config_.getProperty("firstCollection", firstCollection);
Attract.SetIdleTime(static_cast<float>(attractModeTime));
attract_.idleTime = static_cast<float>(attractModeTime);
int initializeStatus = 0;
// load the initial splash screen, unload it once it is complete
CurrentPage = LoadSplashPage();
currentPage_ = loadSplashPage();
bool splashMode = true;
Launcher l(*this, Config);
Launcher l(*this, config_);
preloadTime = static_cast<float>(SDL_GetTicks()) / 1000;
while (running)
@ -236,9 +236,9 @@ void RetroFE::Run()
float lastTime = 0;
float deltaTime = 0;
if(!CurrentPage)
if(!currentPage_)
{
Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page");
Logger::write(Logger::ZONE_WARNING, "RetroFE", "Could not load page");
running = false;
break;
}
@ -246,9 +246,9 @@ void RetroFE::Run()
switch(state)
{
case RETROFE_IDLE:
if(CurrentPage && !splashMode)
if(currentPage_ && !splashMode)
{
state = ProcessUserInput(CurrentPage);
state = processUserInput(currentPage_);
}
else
{
@ -257,32 +257,35 @@ void RetroFE::Run()
(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;
break;
}
// delete the splash screen and use the standard menu
delete CurrentPage;
delete currentPage_;
CurrentPage = LoadPage();
currentPage_ = loadPage();
splashMode = false;
if(CurrentPage)
if(currentPage_)
{
std::string firstCollection = "Main";
Config.GetProperty("firstCollection", firstCollection);
bool menuSort = true;
CurrentPage->Start();
Config.SetCurrentCollection(firstCollection);
CollectionInfo *info = GetCollection(firstCollection);
config_.getProperty("firstCollection", firstCollection);
config_.getProperty("collections." + firstCollection + ".list.menuSort", menuSort);
currentPage_->start();
config_.setProperty("currentCollection", firstCollection);
CollectionInfo *info = getCollection(firstCollection);
MenuParser mp;
mp.GetMenuItems(info);
CurrentPage->PushCollection(info);
mp.buildMenuItems(info, menuSort);
currentPage_->pushCollection(info);
}
else
{
@ -294,41 +297,42 @@ void RetroFE::Run()
break;
case RETROFE_NEXT_PAGE_REQUEST:
if(CurrentPage->IsIdle())
if(currentPage_->isIdle())
{
state = RETROFE_NEW;
}
break;
case RETROFE_LAUNCH_REQUEST:
NextPageItem = CurrentPage->GetSelectedItem();
l.Run(CurrentPage->GetCollectionName(), NextPageItem);
nextPageItem_ = currentPage_->getSelectedItem();
l.run(currentPage_->getCollectionName(), nextPageItem_);
state = RETROFE_IDLE;
break;
case RETROFE_BACK_REQUEST:
LastMenuOffsets[CurrentPage->GetCollectionName()] = CurrentPage->GetScrollOffsetIndex();
CurrentPage->PopCollection();
Config.SetCurrentCollection(CurrentPage->GetCollectionName());
lastMenuOffsets_[currentPage_->getCollectionName()] = currentPage_->getScrollOffsetIndex();
currentPage_->popCollection();
config_.setProperty("currentCollection", currentPage_->getCollectionName());
state = RETROFE_NEW;
break;
case RETROFE_NEW:
if(CurrentPage->IsIdle())
if(currentPage_->isIdle())
{
state = RETROFE_IDLE;
}
break;
case RETROFE_QUIT_REQUEST:
CurrentPage->Stop();
currentPage_->stop();
state = RETROFE_QUIT;
break;
case RETROFE_QUIT:
if(CurrentPage->IsHidden())
if(currentPage_->isHidden())
{
running = false;
}
@ -339,42 +343,42 @@ void RetroFE::Run()
// the logic below could be done in a helper method
if(running)
{
lastTime = CurrentTime;
CurrentTime = static_cast<float>(SDL_GetTicks()) / 1000;
lastTime = currentTime_;
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;
if(sleepTime > 0)
{
SDL_Delay(static_cast<unsigned int>(sleepTime));
}
if(CurrentPage)
if(currentPage_)
{
Attract.Update(deltaTime, *CurrentPage);
CurrentPage->Update(deltaTime);
attract_.update(deltaTime, *currentPage_);
currentPage_->update(deltaTime);
}
Render();
render();
}
}
}
bool RetroFE::Back(bool &exit)
bool RetroFE::back(bool &exit)
{
bool canGoBack = false;
bool exitOnBack = false;
Config.GetProperty("exitOnFirstPageBack", exitOnBack);
config_.getProperty("exitOnFirstPageBack", exitOnBack);
exit = false;
if(CurrentPage->GetMenuDepth() <= 1)
if(currentPage_->getMenuDepth() <= 1)
{
exit = exitOnBack;
}
@ -387,87 +391,90 @@ 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;
RETROFE_STATE state = RETROFE_IDLE;
if (SDL_PollEvent(&e) == 0) return state;
bool rememberMenu = false;
Config.GetProperty("rememberMenu", rememberMenu);
config_.getProperty("rememberMenu", rememberMenu);
if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)
{
SDL_Scancode scancode = SDL_GetScancodeFromKey(e.key.keysym.sym);
Input.SetKeyState(scancode, (e.type == SDL_KEYDOWN) ? true : false);
input_.keystate(scancode, (e.type == SDL_KEYDOWN) ? true : false);
Attract.Reset();
attract_.reset();
if(page->IsHorizontalScroll())
if(page->isHorizontalScroll())
{
if (Input.GetKeyState(UserInput::KeyCodeLeft))
if (input_.keystate(UserInput::KeyCodeLeft))
{
page->SetScrolling(Page::ScrollDirectionBack);
page->setScrolling(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodeRight))
if (input_.keystate(UserInput::KeyCodeRight))
{
page->SetScrolling(Page::ScrollDirectionForward);
page->setScrolling(Page::ScrollDirectionForward);
}
}
else
{
if (Input.GetKeyState(UserInput::KeyCodeUp))
if (input_.keystate(UserInput::KeyCodeUp))
{
page->SetScrolling(Page::ScrollDirectionBack);
page->setScrolling(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodeDown))
if (input_.keystate(UserInput::KeyCodeDown))
{
page->SetScrolling(Page::ScrollDirectionForward);
page->setScrolling(Page::ScrollDirectionForward);
}
}
if (Input.GetKeyState(UserInput::KeyCodePageUp))
if (input_.keystate(UserInput::KeyCodePageUp))
{
page->PageScroll(Page::ScrollDirectionBack);
page->pageScroll(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodePageDown))
if (input_.keystate(UserInput::KeyCodePageDown))
{
page->PageScroll(Page::ScrollDirectionForward);
page->pageScroll(Page::ScrollDirectionForward);
}
if (Input.GetKeyState(UserInput::KeyCodeLetterUp))
if (input_.keystate(UserInput::KeyCodeLetterUp))
{
page->LetterScroll(Page::ScrollDirectionBack);
page->letterScroll(Page::ScrollDirectionBack);
}
if (Input.GetKeyState(UserInput::KeyCodeLetterDown))
if (input_.keystate(UserInput::KeyCodeLetterDown))
{
page->LetterScroll(Page::ScrollDirectionForward);
page->letterScroll(Page::ScrollDirectionForward);
}
if (Input.GetKeyState(UserInput::KeyCodeAdminMode))
if (input_.keystate(UserInput::KeyCodeAdminMode))
{
//todo: add admin mode support
}
if (Input.GetKeyState(UserInput::KeyCodeSelect) && page->IsMenuIdle())
if (input_.keystate(UserInput::KeyCodeSelect) && page->isMenuIdle())
{
NextPageItem = page->GetSelectedItem();
nextPageItem_ = page->getSelectedItem();
if(NextPageItem)
if(nextPageItem_)
{
if(NextPageItem->IsLeaf())
if(nextPageItem_->leaf)
{
state = RETROFE_LAUNCH_REQUEST;
}
else
{
Config.SetCurrentCollection(NextPageItem->GetName());
CollectionInfo *info = GetCollection(NextPageItem->GetName());
bool menuSort = true;
config_.setProperty("currentCollection", nextPageItem_->name);
config_.getProperty("collections." + nextPageItem_->name + ".list.menuSort", menuSort);
CollectionInfo *info = getCollection(nextPageItem_->name);
MenuParser mp;
mp.GetMenuItems(info);
page->PushCollection(info);
mp.buildMenuItems(info, menuSort);
page->pushCollection(info);
if(rememberMenu && LastMenuOffsets.find(NextPageItem->GetName()) != LastMenuOffsets.end())
if(rememberMenu && lastMenuOffsets_.find(nextPageItem_->name) != lastMenuOffsets_.end())
{
page->SetScrollOffsetIndex(LastMenuOffsets[NextPageItem->GetName()]);
page->setScrollOffsetIndex(lastMenuOffsets_[nextPageItem_->name]);
}
state = RETROFE_NEXT_PAGE_REQUEST;
@ -475,85 +482,85 @@ RetroFE::RETROFE_STATE RetroFE::ProcessUserInput(Page *page)
}
}
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;
}
}
if (Input.GetKeyState(UserInput::KeyCodeQuit))
if (input_.keystate(UserInput::KeyCodeQuit))
{
state = RETROFE_QUIT_REQUEST;
}
if(!Input.GetKeyState(UserInput::KeyCodeUp) &&
!Input.GetKeyState(UserInput::KeyCodeLeft) &&
!Input.GetKeyState(UserInput::KeyCodeDown) &&
!Input.GetKeyState(UserInput::KeyCodeRight) &&
!Input.GetKeyState(UserInput::KeyCodePageUp) &&
!Input.GetKeyState(UserInput::KeyCodePageDown))
if(!input_.keystate(UserInput::KeyCodeUp) &&
!input_.keystate(UserInput::KeyCodeLeft) &&
!input_.keystate(UserInput::KeyCodeDown) &&
!input_.keystate(UserInput::KeyCodeRight) &&
!input_.keystate(UserInput::KeyCodePageUp) &&
!input_.keystate(UserInput::KeyCodePageDown))
{
page->SetScrolling(Page::ScrollDirectionIdle);
page->setScrolling(Page::ScrollDirectionIdle);
}
}
return state;
}
Page *RetroFE::LoadPage()
Page *RetroFE::loadPage()
{
std::string layoutName;
Config.GetProperty("layout", layoutName);
config_.getProperty("layout", layoutName);
PageBuilder pb(layoutName, "layout", Config, &FC);
Page *page = pb.BuildPage();
PageBuilder pb(layoutName, "layout", config_, &fontcache_);
Page *page = pb.buildPage();
if(!page)
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not create page");
Logger::write(Logger::ZONE_ERROR, "RetroFE", "Could not create page");
}
else
{
page->Start();
page->start();
}
return page;
}
Page *RetroFE::LoadSplashPage()
Page *RetroFE::loadSplashPage()
{
std::string layoutName;
Config.GetProperty("layout", layoutName);
config_.getProperty("layout", layoutName);
PageBuilder pb(layoutName, "splash", Config, &FC);
Page * page = pb.BuildPage();
page->Start();
PageBuilder pb(layoutName, "splash", config_, &fontcache_);
Page * page = pb.buildPage();
page->start();
return page;
}
CollectionInfo *RetroFE::GetCollection(std::string collectionName)
CollectionInfo *RetroFE::getCollection(std::string collectionName)
{
// the page will deallocate this once its done
CollectionInfoBuilder cib(Config, *MetaDb);
CollectionInfo *collection = cib.BuildCollection(collectionName);
CollectionInfoBuilder cib(config_, *metadb_);
CollectionInfo *collection = cib.buildCollection(collectionName);
return collection;
}
std::string RetroFE::GetLayout(std::string collectionName)
std::string RetroFE::getLayout(std::string collectionName)
{
std::string layoutKeyName = "collections." + collectionName + ".layout";
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;

View File

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

View File

@ -19,17 +19,17 @@
#include "Utility/Log.h"
#include <SDL2/SDL_mixer.h>
SDL_Window *SDL::Window = NULL;
SDL_Renderer *SDL::Renderer = NULL;
SDL_mutex *SDL::Mutex = NULL;
int SDL::DisplayWidth = 0;
int SDL::DisplayHeight = 0;
int SDL::WindowWidth = 0;
int SDL::WindowHeight = 0;
bool SDL::Fullscreen = false;
SDL_Window *SDL::window_ = NULL;
SDL_Renderer *SDL::renderer_ = NULL;
SDL_mutex *SDL::mutex_ = NULL;
int SDL::displayWidth_ = 0;
int SDL::displayHeight_ = 0;
int SDL::windowWidth_ = 0;
int SDL::windowHeight_ = 0;
bool SDL::fullscreen_ = false;
bool SDL::Initialize(Configuration &config)
bool SDL::initialize(Configuration &config)
{
bool retVal = true;
std::string hString;
@ -41,15 +41,15 @@ bool SDL::Initialize(Configuration &config)
int audioBuffers = 4096;
bool hideMouse;
Logger::Write(Logger::ZONE_INFO, "SDL", "Initializing");
Logger::write(Logger::ZONE_INFO, "SDL", "Initializing");
if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
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;
}
if(retVal && config.GetProperty("hideMouse", hideMouse))
if(retVal && config.getProperty("hideMouse", hideMouse))
{
if(hideMouse)
{
@ -70,16 +70,16 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{
DisplayWidth = mode.w;
DisplayHeight = mode.h;
displayWidth_ = mode.w;
displayHeight_ = mode.h;
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;
}
else if(hString == "stretch")
@ -90,22 +90,22 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{
WindowWidth = mode.w;
windowWidth_ = mode.w;
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(!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;
}
else if(vString == "stretch")
@ -116,24 +116,24 @@ bool SDL::Initialize(Configuration &config)
SDL_DisplayMode mode;
if(SDL_GetDesktopDisplayMode(i, &mode) == 0)
{
WindowHeight = mode.h;
windowHeight_ = mode.h;
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;
}
if (retVal && Fullscreen)
if (retVal && fullscreen_)
{
#ifdef WIN32
windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
@ -144,55 +144,55 @@ bool SDL::Initialize(Configuration &config)
if(retVal)
{
std::string fullscreenStr = Fullscreen ? "yes" : "no";
std::string fullscreenStr = fullscreen_ ? "yes" : "no";
std::stringstream ss;
ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: "
ss << "Creating "<< windowWidth_ << "x" << windowHeight_ << " window (fullscreen: "
<< 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,
WindowWidth,
WindowHeight,
windowWidth_,
windowHeight_,
windowFlags);
if (Window == NULL)
if (window_ == NULL)
{
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;
}
}
if(retVal)
{
Renderer = SDL_CreateRenderer(Window,
renderer_ = SDL_CreateRenderer(window_,
-1,
SDL_RENDERER_ACCELERATED);
if (Renderer == NULL)
if (renderer_ == NULL)
{
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;
}
}
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)
{
Mutex = SDL_CreateMutex();
mutex_ = SDL_CreateMutex();
if (Mutex == NULL)
if (mutex_ == NULL)
{
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;
}
}
@ -201,36 +201,36 @@ bool SDL::Initialize(Configuration &config)
if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1)
{
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;
}
return retVal;
}
bool SDL::DeInitialize()
bool SDL::deInitialize()
{
std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_INFO, "SDL", "DeInitializing");
Logger::write(Logger::ZONE_INFO, "SDL", "DeInitializing");
Mix_CloseAudio();
Mix_Quit();
if(Mutex)
if(mutex_)
{
SDL_DestroyMutex(Mutex);
Mutex = NULL;
SDL_DestroyMutex(mutex_);
mutex_ = NULL;
}
if(Renderer)
if(renderer_)
{
SDL_DestroyRenderer(Renderer);
Renderer = NULL;
SDL_DestroyRenderer(renderer_);
renderer_ = NULL;
}
if(Window)
if(window_)
{
SDL_DestroyWindow(Window);
Window = NULL;
SDL_DestroyWindow(window_);
window_ = NULL;
}
SDL_ShowCursor(SDL_TRUE);
@ -240,31 +240,31 @@ bool SDL::DeInitialize()
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;
rotateRect.w = dest->w;
rotateRect.h = dest->h;
if(Fullscreen)
if(fullscreen_)
{
rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2;
rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2;
rotateRect.x = dest->x + (displayWidth_ - windowWidth_)/2;
rotateRect.y = dest->y + (displayHeight_ - windowHeight_)/2;
}
else
{
@ -273,7 +273,7 @@ bool SDL::RenderCopy(SDL_Texture *texture, unsigned char alpha, SDL_Rect *src, S
}
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;
}

View File

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

View File

@ -19,49 +19,49 @@
#include "../Utility/Log.h"
Sound::Sound(std::string file)
: File(file)
, Chunk(NULL)
: file_(file)
, 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()
{
if(Chunk)
if(chunk_)
{
Mix_FreeChunk(Chunk);
Chunk = NULL;
Mix_FreeChunk(chunk_);
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);
Chunk = NULL;
Mix_FreeChunk(chunk_);
chunk_ = NULL;
}
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:
Sound(std::string file);
virtual ~Sound();
void Play();
bool Allocate();
bool Free();
void play();
bool allocate();
bool free();
private:
std::string File;
Mix_Chunk *Chunk;
std::string file_;
Mix_Chunk *chunk_;
};

View File

@ -19,34 +19,34 @@
#include <sstream>
#include <ctime>
std::ofstream Logger::WriteFileStream;
std::streambuf *Logger::CerrStream = NULL;
std::streambuf *Logger::CoutStream = NULL;
std::ofstream Logger::writeFileStream_;
std::streambuf *Logger::cerrStream_ = 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());
CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf());
cerrStream_ = std::cerr.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::cout.rdbuf(CoutStream);
std::cerr.rdbuf(cerrStream_);
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;

View File

@ -33,12 +33,12 @@ public:
ZONE_ERROR
};
static bool Initialize(std::string file);
static void Write(Zone zone, std::string component, std::string message);
static void DeInitialize();
static bool initialize(std::string file);
static void write(Zone zone, std::string component, std::string message);
static void deInitialize();
private:
static std::streambuf *CerrStream;
static std::streambuf *CoutStream;
static std::ofstream WriteFileStream;
static std::streambuf *cerrStream_;
static std::streambuf *coutStream_;
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)
{
@ -44,7 +44,7 @@ std::string Utils::ToLower(std::string str)
return str;
}
std::string Utils::UppercaseFirst(std::string str)
std::string Utils::uppercaseFirst(std::string str)
{
if(str.length() > 0)
{
@ -54,7 +54,7 @@ std::string Utils::UppercaseFirst(std::string str)
return str;
}
std::string Utils::FilterComments(std::string line)
std::string Utils::filterComments(std::string line)
{
size_t position;
@ -69,7 +69,7 @@ std::string Utils::FilterComments(std::string 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::string path;
@ -83,7 +83,7 @@ std::string Utils::CombinePath(std::list<std::string> &paths)
while(it != paths.end())
{
path += Utils::PathSeparator;
path += Utils::pathSeparator;
path += *it;
it++;
}
@ -91,33 +91,33 @@ std::string Utils::CombinePath(std::list<std::string> &paths)
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;
paths.push_back(path1);
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;
paths.push_back(path1);
paths.push_back(path2);
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;
paths.push_back(path1);
paths.push_back(path2);
paths.push_back(path3);
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;
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(path4);
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)
{
std::string temp = prefix + "." + extensions[i];
temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp);
temp = Configuration::convertToAbsolutePath(Configuration::absolutePath, temp);
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,
const std::string& search,
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;
std::stringstream ss;
@ -174,7 +174,7 @@ float Utils::ConvertFloat(std::string content)
return retVal;
}
int Utils::ConvertInt(std::string content)
int Utils::convertInt(std::string content)
{
int retVal = 0;
std::stringstream ss;
@ -184,19 +184,19 @@ int Utils::ConvertInt(std::string content)
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::string Utils::GetDirectory(std::string filePath)
std::string Utils::getDirectory(std::string 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)
{
directory = filePath.substr(0, last_slash_idx);
@ -205,13 +205,13 @@ std::string Utils::GetDirectory(std::string filePath)
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)
{
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)
@ -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;
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)
{
filename = filePath.erase(0, last_slash_idx+1);

View File

@ -21,31 +21,31 @@
class Utils
{
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);
static float ConvertFloat(std::string content);
static int ConvertInt(std::string content);
static void ReplaceSlashesWithUnderscores(std::string &content);
static std::string GetDirectory(std::string filePath);
static std::string GetParentDirectory(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 std::string ToLower(std::string str);
static std::string UppercaseFirst(std::string str);
static std::string FilterComments(std::string line);
static float convertFloat(std::string content);
static int convertInt(std::string content);
static void replaceSlashesWithUnderscores(std::string &content);
static std::string getDirectory(std::string filePath);
static std::string getParentDirectory(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 std::string toLower(std::string str);
static std::string uppercaseFirst(std::string str);
static std::string filterComments(std::string line);
//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::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, 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::list<std::string> &paths);
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, std::string path4);
static std::string combinePath(std::string path1, std::string path2, std::string path3, std::string path4, std::string path5);
#ifdef WIN32
static const char PathSeparator = '\\';
static const char pathSeparator = '\\';
#else
static const char PathSeparator = '/';
static const char pathSeparator = '/';
#endif
private:

View File

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

View File

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

View File

@ -29,113 +29,113 @@
#include <sys/types.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
// 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
return TRUE;
}
GStreamerVideo::GStreamerVideo()
: Playbin(NULL)
, VideoBin(NULL)
, VideoSink(NULL)
, VideoConvert(NULL)
, VideoConvertCaps(NULL)
, VideoBus(NULL)
, Texture(NULL)
, Height(0)
, Width(0)
, VideoBuffer(NULL)
, VideoBufferSize(0)
, MaxVideoBufferSize(0)
, FrameReady(false)
, IsPlaying(false)
, PlayCount(0)
, NumLoops(0)
: playbin_(NULL)
, videoBin_(NULL)
, videoSink_(NULL)
, videoConvert_(NULL)
, videoConvertCaps_(NULL)
, videoBus_(NULL)
, texture_(NULL)
, height_(0)
, width_(0)
, videoBuffer_(NULL)
, videoBufferSize_(0)
, maxVideoBufferSize_(0)
, frameReady_(false)
, isPlaying_(false)
, playCount_(0)
, numLoops_(0)
{
}
GStreamerVideo::~GStreamerVideo()
{
Stop();
stop();
if(VideoBuffer)
if(videoBuffer_)
{
delete[] VideoBuffer;
VideoBuffer = NULL;
VideoBufferSize = 0;
MaxVideoBufferSize = 0;
delete[] videoBuffer_;
videoBuffer_ = NULL;
videoBufferSize_ = 0;
maxVideoBufferSize_ = 0;
}
SDL_DestroyTexture(Texture);
Texture = NULL;
SDL_DestroyTexture(texture_);
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;
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);
GstStructure *s = gst_caps_get_structure(caps, 0);
gst_structure_get_int(s, "width", &video->Width);
gst_structure_get_int(s, "height", &video->Height);
gst_structure_get_int(s, "width", &video->width_);
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
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->MaxVideoBufferSize = map.size;
video->videoBuffer_ = new char[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);
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;
}
std::string path = Utils::CombinePath(Configuration::GetAbsolutePath(), "Core");
std::string path = Utils::combinePath(Configuration::absolutePath, "Core");
gst_init(NULL, NULL);
#ifdef WIN32
@ -143,63 +143,63 @@ bool GStreamerVideo::Initialize()
gst_registry_scan_path(registry, path.c_str());
#endif
Initialized = true;
initialized_ = true;
return true;
}
bool GStreamerVideo::DeInitialize()
bool GStreamerVideo::deInitialize()
{
gst_deinit();
Initialized = false;
initialized_ = false;
return true;
}
bool GStreamerVideo::Stop()
bool GStreamerVideo::stop()
{
if(!Initialized)
if(!initialized_)
{
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);
Texture = NULL;
SDL_DestroyTexture(texture_);
texture_ = NULL;
}
// FreeElements();
IsPlaying = false;
Height = 0;
Width = 0;
FrameReady = false;
isPlaying_ = false;
height_ = 0;
width_ = 0;
frameReady_ = false;
return true;
}
bool GStreamerVideo::Play(std::string file)
bool GStreamerVideo::play(std::string file)
{
PlayCount = 0;
playCount_ = 0;
if(!Initialized)
if(!initialized_)
{
return false;
}
CurrentFile = file;
currentFile_ = file;
const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL);
if(!uriFile)
@ -208,91 +208,91 @@ bool GStreamerVideo::Play(std::string file)
}
else
{
Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file);
Configuration::convertToAbsolutePath(Configuration::absolutePath, file);
file = uriFile;
if(!Playbin)
if(!playbin_)
{
Playbin = gst_element_factory_make("playbin", "player");
VideoBin = gst_bin_new("SinkBin");
VideoSink = gst_element_factory_make("fakesink", "video_sink");
VideoConvert = gst_element_factory_make("capsfilter", "video_convert");
VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2");
Height = 0;
Width = 0;
if(!Playbin)
playbin_ = gst_element_factory_make("playbin", "player");
videoBin_ = gst_bin_new("SinkBin");
videoSink_ = gst_element_factory_make("fakesink", "video_sink");
videoConvert_ = gst_element_factory_make("capsfilter", "video_convert");
videoConvertCaps_ = gst_caps_from_string("video/x-raw,format=(string)YUY2");
height_ = 0;
width_ = 0;
if(!playbin_)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create playbin");
freeElements();
return false;
}
if(!VideoSink)
if(!videoSink_)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video sink");
freeElements();
return false;
}
if(!VideoConvert)
if(!videoConvert_)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video converter");
freeElements();
return false;
}
if(!VideoConvertCaps)
if(!videoConvertCaps_)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not create video caps");
freeElements();
return false;
}
gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL);
gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps);
GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink");
gst_bin_add_many(GST_BIN(videoBin_), videoConvert_, videoSink_, NULL);
gst_element_link_filtered(videoConvert_, videoSink_, videoConvertCaps_);
GstPad *videoConvertSinkPad = gst_element_get_static_pad(videoConvert_, "sink");
if(!videoConvertSinkPad)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad");
freeElements();
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);
if(!videoSinkPad)
{
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad");
FreeElements();
Logger::write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad");
freeElements();
gst_object_unref(videoConvertSinkPad);
videoConvertSinkPad = NULL;
return false;
}
gst_element_add_pad(VideoBin, videoSinkPad);
gst_element_add_pad(videoBin_, videoSinkPad);
gst_object_unref(videoConvertSinkPad);
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_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this);
g_object_set(G_OBJECT(videoSink_), "signal-handoffs", TRUE, NULL);
g_signal_connect(videoSink_, "handoff", G_CALLBACK(processNewBuffer), this);
VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin));
gst_bus_add_watch(VideoBus, &BusCallback, this);
videoBus_ = gst_pipeline_get_bus(GST_PIPELINE(playbin_));
gst_bus_add_watch(videoBus_, &busCallback, this);
/* 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)
{
IsPlaying = false;
isPlaying_ = false;
std::stringstream ss;
ss << "Unable to set the pipeline to the playing state: ";
ss << playState;
Logger::Write(Logger::ZONE_ERROR, "Video", ss.str());
FreeElements();
Logger::write(Logger::ZONE_ERROR, "Video", ss.str());
freeElements();
return false;
}
}
@ -300,88 +300,88 @@ bool GStreamerVideo::Play(std::string file)
return true;
}
void GStreamerVideo::FreeElements()
void GStreamerVideo::freeElements()
{
if(VideoBin)
if(videoBin_)
{
gst_object_unref(VideoBin);
VideoBin = NULL;
gst_object_unref(videoBin_);
videoBin_ = NULL;
}
if(VideoSink)
if(videoSink_)
{
gst_object_unref(VideoSink);
VideoSink = NULL;
gst_object_unref(videoSink_);
videoSink_ = NULL;
}
if(VideoConvert)
if(videoConvert_)
{
gst_object_unref(VideoConvert);
VideoConvert = NULL;
gst_object_unref(videoConvert_);
videoConvert_ = NULL;
}
if(VideoConvertCaps)
if(videoConvertCaps_)
{
gst_object_unref(VideoConvertCaps);
VideoConvertCaps = NULL;
gst_object_unref(videoConvertCaps_);
videoConvertCaps_ = NULL;
}
if(Playbin)
if(playbin_)
{
gst_object_unref(Playbin);
Playbin = NULL;
gst_object_unref(playbin_);
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());
if(!Texture && Width != 0 && Height != 0)
SDL_LockMutex(SDL::getMutex());
if(!texture_ && width_ != 0 && height_ != 0)
{
Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2,
SDL_TEXTUREACCESS_STREAMING, Width, Height);
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND);
texture_ = SDL_CreateTexture(SDL::getRenderer(), SDL_PIXELFORMAT_YUY2,
SDL_TEXTUREACCESS_STREAMING, width_, height_);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
}
if(VideoBuffer && FrameReady && Texture && Width && Height)
if(videoBuffer_ && frameReady_ && texture_ && width_ && height_)
{
//todo: change to width of cap
void *pixels;
int pitch;
SDL_LockTexture(Texture, NULL, &pixels, &pitch);
memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number
SDL_UnlockTexture(Texture);
SDL_LockTexture(texture_, NULL, &pixels, &pitch);
memcpy(pixels, videoBuffer_, width_*height_*2); //todo: magic number
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(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS)
{
PlayCount++;
playCount_++;
//todo: nesting hazard
// 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,
GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH,

View File

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

View File

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

View File

@ -18,29 +18,29 @@
#include "IVideo.h"
#include "GStreamerVideo.h"
bool VideoFactory::Enabled = true;
int VideoFactory::NumLoops = 0;
IVideo *VideoFactory::Instance = NULL;
bool VideoFactory::enabled_ = true;
int VideoFactory::numLoops_ = 0;
IVideo *VideoFactory::instance_ = NULL;
IVideo *VideoFactory::CreateVideo()
IVideo *VideoFactory::createVideo()
{
if(Enabled && !Instance)
if(enabled_ && !instance_)
{
Instance = new GStreamerVideo();
Instance->Initialize();
((GStreamerVideo *)(Instance))->SetNumLoops(NumLoops);
instance_ = new GStreamerVideo();
instance_->initialize();
((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;
}

View File

@ -20,12 +20,12 @@ class IVideo;
class VideoFactory
{
public:
static IVideo *CreateVideo();
static void SetEnabled(bool enabled);
static void SetNumLoops(int numLoops);
static IVideo *createVideo();
static void setEnabled(bool enabled);
static void setNumLoops(int numLoops);
private:
static bool Enabled;
static int NumLoops;
static IVideo *Instance;
static bool enabled_;
static int numLoops_;
static IVideo *instance_;
};