Setting code formatting standard to allman.

This commit is contained in:
emb
2015-01-01 14:08:42 -06:00
parent 174ea4f4f9
commit 6410139f87
76 changed files with 5352 additions and 5314 deletions

View File

@@ -1,20 +1,20 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "CollectionInfo.h" #include "CollectionInfo.h"
#include "../Database/Configuration.h" #include "../Database/Configuration.h"
#include <sstream> #include <sstream>
CollectionInfo::CollectionInfo(std::string name, CollectionInfo::CollectionInfo(std::string name,
std::string listPath, std::string listPath,
std::string extensions, std::string extensions,
std::string metadataType, std::string metadataType,
std::string metadataPath) std::string metadataPath)
: Name(name) : Name(name)
, ListPath(listPath) , ListPath(listPath)
, Extensions(extensions) , Extensions(extensions)
, MetadataType(metadataType) , MetadataType(metadataType)
, MetadataPath(metadataPath) , MetadataPath(metadataPath)
{ {
} }
@@ -24,43 +24,43 @@ CollectionInfo::~CollectionInfo()
std::string CollectionInfo::GetName() const std::string CollectionInfo::GetName() const
{ {
return Name; return Name;
} }
std::string CollectionInfo::GetSettingsPath() const std::string CollectionInfo::GetSettingsPath() const
{ {
return Configuration::GetAbsolutePath() + "/Collections/" + GetName(); return Configuration::GetAbsolutePath() + "/Collections/" + GetName();
} }
std::string CollectionInfo::GetListPath() const std::string CollectionInfo::GetListPath() const
{ {
return ListPath; return ListPath;
} }
std::string CollectionInfo::GetMetadataType() const std::string CollectionInfo::GetMetadataType() const
{ {
return MetadataType; return MetadataType;
} }
std::string CollectionInfo::GetMetadataPath() const std::string CollectionInfo::GetMetadataPath() const
{ {
return MetadataPath; return MetadataPath;
} }
std::string CollectionInfo::GetExtensions() const std::string CollectionInfo::GetExtensions() const
{ {
return Extensions; return Extensions;
} }
void CollectionInfo::GetExtensions(std::vector<std::string> &extensions) void CollectionInfo::GetExtensions(std::vector<std::string> &extensions)
{ {
std::istringstream ss(Extensions); std::istringstream ss(Extensions);
std::string token; std::string token;
while(std::getline(ss, token, ',')) while(std::getline(ss, token, ','))
{ {
extensions.push_back(token); extensions.push_back(token);
} }
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -9,20 +9,20 @@
class CollectionInfo class CollectionInfo
{ {
public: public:
CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath); CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath);
virtual ~CollectionInfo(); virtual ~CollectionInfo();
std::string GetName() const; std::string GetName() const;
std::string GetSettingsPath() const; std::string GetSettingsPath() const;
std::string GetListPath() const; std::string GetListPath() const;
std::string GetMetadataType() const; std::string GetMetadataType() const;
std::string GetMetadataPath() const; std::string GetMetadataPath() const;
std::string GetExtensions() const; std::string GetExtensions() const;
void GetExtensions(std::vector<std::string> &extensions); void GetExtensions(std::vector<std::string> &extensions);
private: private:
std::string Name; std::string Name;
std::string ListPath; std::string ListPath;
std::string Extensions; std::string Extensions;
std::string MetadataType; std::string MetadataType;
std::string MetadataPath; std::string MetadataPath;
}; };

View File

@@ -6,121 +6,121 @@
#include <vector> #include <vector>
CollectionInfoBuilder::CollectionInfoBuilder(Configuration *c) CollectionInfoBuilder::CollectionInfoBuilder(Configuration *c)
: Conf(c) : Conf(c)
{ {
} }
CollectionInfoBuilder::~CollectionInfoBuilder() CollectionInfoBuilder::~CollectionInfoBuilder()
{ {
std::map<std::string, CollectionInfo *>::iterator it = InfoMap.begin(); std::map<std::string, CollectionInfo *>::iterator it = InfoMap.begin();
for(it == InfoMap.begin(); it != InfoMap.end(); ++it) for(it == InfoMap.begin(); it != InfoMap.end(); ++it)
{ {
delete it->second; delete it->second;
} }
InfoMap.clear(); InfoMap.clear();
} }
bool CollectionInfoBuilder::LoadAllCollections() bool CollectionInfoBuilder::LoadAllCollections()
{ {
std::vector<std::string> collections; std::vector<std::string> collections;
Conf->GetChildKeyCrumbs("collections", collections); Conf->GetChildKeyCrumbs("collections", collections);
if(collections.size() == 0) if(collections.size() == 0)
{ {
Logger::Write(Logger::ZONE_ERROR, "Collections", "No collections were found. Please configure Settings.conf"); Logger::Write(Logger::ZONE_ERROR, "Collections", "No collections were found. Please configure Settings.conf");
return false; return false;
} }
bool retVal = true; bool retVal = true;
std::vector<std::string>::iterator it; std::vector<std::string>::iterator it;
for(it = collections.begin(); it != collections.end(); ++it) for(it = collections.begin(); it != collections.end(); ++it)
{ {
// todo: There is nothing that should really stop us from creating a collection // todo: There is nothing that should really stop us from creating a collection
// in the main folder. I just need to find some time to look at the impacts if // in the main folder. I just need to find some time to look at the impacts if
// I remove this conditional check. // I remove this conditional check.
if(*it != "Main") if(*it != "Main")
{ {
if(ImportCollection(*it)) if(ImportCollection(*it))
{ {
Logger::Write(Logger::ZONE_INFO, "Collections", "Adding collection " + *it); Logger::Write(Logger::ZONE_INFO, "Collections", "Adding collection " + *it);
} }
else else
{ {
// Continue processing the rest of the collections if an error occurs during import. // Continue processing the rest of the collections if an error occurs during import.
// ImportCollection() will print out an error to the log file. // ImportCollection() will print out an error to the log file.
retVal = false; retVal = false;
} }
} }
} }
return retVal; return retVal;
} }
void CollectionInfoBuilder::GetCollections(std::vector<CollectionInfo *> &collections) void CollectionInfoBuilder::GetCollections(std::vector<CollectionInfo *> &collections)
{ {
std::map<std::string, CollectionInfo *>::iterator InfoMapIt; std::map<std::string, CollectionInfo *>::iterator InfoMapIt;
for(InfoMapIt = InfoMap.begin(); InfoMapIt != InfoMap.end(); ++InfoMapIt) for(InfoMapIt = InfoMap.begin(); InfoMapIt != InfoMap.end(); ++InfoMapIt)
{ {
collections.push_back(InfoMapIt->second); collections.push_back(InfoMapIt->second);
} }
} }
bool CollectionInfoBuilder::ImportCollection(std::string name) bool CollectionInfoBuilder::ImportCollection(std::string name)
{ {
// create a new instance if one does not exist // create a new instance if one does not exist
if(InfoMap.find(name) != InfoMap.end()) if(InfoMap.find(name) != InfoMap.end())
{ {
return true; return true;
} }
std::string listItemsPathKey = "collections." + name + ".list.path"; std::string listItemsPathKey = "collections." + name + ".list.path";
std::string listFilterKey = "collections." + name + ".list.filter"; std::string listFilterKey = "collections." + name + ".list.filter";
std::string extensionsKey = "collections." + name + ".list.extensions"; std::string extensionsKey = "collections." + name + ".list.extensions";
std::string launcherKey = "collections." + name + ".launcher"; std::string launcherKey = "collections." + name + ".launcher";
//todo: metadata is not fully not implemented //todo: metadata is not fully not implemented
std::string metadataTypeKey = "collections." + name + ".metadata.type"; std::string metadataTypeKey = "collections." + name + ".metadata.type";
std::string metadataPathKey = "collections." + name + ".metadata.path"; std::string metadataPathKey = "collections." + name + ".metadata.path";
std::string listItemsPath; std::string listItemsPath;
std::string launcherName; std::string launcherName;
std::string extensions; std::string extensions;
std::string metadataType; std::string metadataType;
std::string metadataPath; std::string metadataPath;
if(!Conf->GetPropertyAbsolutePath(listItemsPathKey, listItemsPath)) if(!Conf->GetPropertyAbsolutePath(listItemsPathKey, listItemsPath))
{ {
Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + listItemsPathKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + listItemsPathKey + "\" does not exist. Assuming \"" + name + "\" is a menu");
return false; return false;
} }
if(!Conf->GetProperty(extensionsKey, extensions)) if(!Conf->GetProperty(extensionsKey, extensions))
{ {
Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + extensionsKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + extensionsKey + "\" does not exist. Assuming \"" + name + "\" is a menu");
return false; return false;
} }
(void)Conf->GetProperty(metadataTypeKey, metadataType); (void)Conf->GetProperty(metadataTypeKey, metadataType);
(void)Conf->GetProperty(metadataPathKey, metadataPath); (void)Conf->GetProperty(metadataPathKey, metadataPath);
if(!Conf->GetProperty(launcherKey, launcherName)) if(!Conf->GetProperty(launcherKey, launcherName))
{ {
std::stringstream ss; std::stringstream ss;
ss << "Warning: launcher property \"" ss << "Warning: launcher property \""
<< launcherKey << launcherKey
<< "\" points to a launcher that is not configured (launchers." << "\" points to a launcher that is not configured (launchers."
<< launcherName << launcherName
<< "). Your collection will be viewable, however you will not be able to " << "). Your collection will be viewable, however you will not be able to "
<< "launch any of the items in your collection."; << "launch any of the items in your collection.";
Logger::Write(Logger::ZONE_WARNING, "Collections", ss.str()); Logger::Write(Logger::ZONE_WARNING, "Collections", ss.str());
} }
InfoMap[name] = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath); InfoMap[name] = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath);
return (InfoMap[name] != NULL); return (InfoMap[name] != NULL);
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -13,13 +13,13 @@ class CollectionInfo;
class CollectionInfoBuilder class CollectionInfoBuilder
{ {
public: public:
CollectionInfoBuilder(Configuration *c); CollectionInfoBuilder(Configuration *c);
virtual ~CollectionInfoBuilder(); virtual ~CollectionInfoBuilder();
bool LoadAllCollections(); bool LoadAllCollections();
void GetCollections(std::vector<CollectionInfo *> &keys); void GetCollections(std::vector<CollectionInfo *> &keys);
private: private:
bool ImportCollection(std::string name); bool ImportCollection(std::string name);
std::map<std::string, CollectionInfo *> InfoMap; std::map<std::string, CollectionInfo *> InfoMap;
Configuration *Conf; Configuration *Conf;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "Item.h" #include "Item.h"
#include "../Utility/Utils.h" #include "../Utility/Utils.h"
@@ -7,9 +7,9 @@
#include <algorithm> #include <algorithm>
Item::Item() Item::Item()
: NumberPlayers(0) : NumberPlayers(0)
, NumberButtons(0) , NumberButtons(0)
, Leaf(true) , Leaf(true)
{ {
} }
@@ -19,142 +19,148 @@ Item::~Item()
const std::string Item::GetFileName() const const std::string Item::GetFileName() const
{ {
return Utils::GetFileName(FilePath); return Utils::GetFileName(FilePath);
} }
const std::string& Item::GetFilePath() const const std::string& Item::GetFilePath() const
{ {
return FilePath; return FilePath;
} }
void Item::SetFilePath(const std::string& filepath) void Item::SetFilePath(const std::string& filepath)
{ {
FilePath = filepath; FilePath = filepath;
} }
const std::string& Item::GetLauncher() const const std::string& Item::GetLauncher() const
{ {
return Launcher; return Launcher;
} }
void Item::SetLauncher(const std::string& launcher) void Item::SetLauncher(const std::string& launcher)
{ {
Launcher = launcher; Launcher = launcher;
} }
const std::string& Item::GetManufacturer() const const std::string& Item::GetManufacturer() const
{ {
return Manufacturer; return Manufacturer;
} }
void Item::SetManufacturer(const std::string& manufacturer) void Item::SetManufacturer(const std::string& manufacturer)
{ {
Manufacturer = manufacturer; Manufacturer = manufacturer;
} }
const std::string& Item::GetName() const const std::string& Item::GetName() const
{ {
return Name; return Name;
} }
void Item::SetName(const std::string& name) void Item::SetName(const std::string& name)
{ {
Name = name; Name = name;
} }
int Item::GetNumberButtons() const int Item::GetNumberButtons() const
{ {
return NumberButtons; return NumberButtons;
} }
std::string Item::GetNumberButtonsString() std::string Item::GetNumberButtonsString()
{ {
std::stringstream ss; std::stringstream ss;
ss << NumberButtons; ss << NumberButtons;
return ss.str(); return ss.str();
} }
void Item::SetNumberButtons(int numberbuttons) void Item::SetNumberButtons(int numberbuttons)
{ {
NumberButtons = numberbuttons; NumberButtons = numberbuttons;
} }
int Item::GetNumberPlayers() const int Item::GetNumberPlayers() const
{ {
return NumberPlayers; return NumberPlayers;
} }
std::string Item::GetNumberPlayersString() std::string Item::GetNumberPlayersString()
{ {
std::stringstream ss; std::stringstream ss;
ss << NumberButtons; ss << NumberButtons;
return ss.str(); return ss.str();
} }
void Item::SetNumberPlayers(int numberplayers) void Item::SetNumberPlayers(int numberplayers)
{ {
NumberPlayers = numberplayers; NumberPlayers = numberplayers;
} }
const std::string& Item::GetTitle() const const std::string& Item::GetTitle() const
{ {
return Title; return Title;
} }
const std::string& Item::GetLCTitle() const const std::string& Item::GetLCTitle() const
{ {
return LCTitle; return LCTitle;
} }
void Item::SetTitle(const std::string& title) void Item::SetTitle(const std::string& title)
{ {
Title = title; Title = title;
LCTitle = Title; LCTitle = Title;
std::transform(LCTitle.begin(), LCTitle.end(), LCTitle.begin(), ::tolower); std::transform(LCTitle.begin(), LCTitle.end(), LCTitle.begin(), ::tolower);
} }
const std::string& Item::GetYear() const const std::string& Item::GetYear() const
{ {
return Year; return Year;
} }
void Item::SetYear(const std::string& year) void Item::SetYear(const std::string& year)
{ {
Year = year; Year = year;
} }
bool Item::IsLeaf() const bool Item::IsLeaf() const
{ {
return Leaf; return Leaf;
} }
void Item::SetIsLeaf(bool leaf) void Item::SetIsLeaf(bool leaf)
{ {
Leaf = leaf; Leaf = leaf;
} }
const std::string& Item::GetFullTitle() const const std::string& Item::GetFullTitle() const
{ {
return FullTitle; return FullTitle;
} }
void Item::SetFullTitle(const std::string& fulltitle) void Item::SetFullTitle(const std::string& fulltitle)
{ {
FullTitle = fulltitle; FullTitle = fulltitle;
} }
const std::string& Item::GetCloneOf() const const std::string& Item::GetCloneOf() const
{ {
return CloneOf; return CloneOf;
} }
void Item::SetCloneOf(const std::string& cloneOf) void Item::SetCloneOf(const std::string& cloneOf)
{ {
CloneOf = cloneOf; CloneOf = cloneOf;
} }
bool Item::operator<(const Item &rhs) { return LCTitle < rhs.LCTitle; } bool Item::operator<(const Item &rhs)
bool Item::operator>(const Item &rhs) { return LCTitle > rhs.LCTitle; } {
return LCTitle < rhs.LCTitle;
}
bool Item::operator>(const Item &rhs)
{
return LCTitle > rhs.LCTitle;
}

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -8,49 +8,49 @@
class Item class Item
{ {
public: public:
Item(); Item();
virtual ~Item(); virtual ~Item();
const std::string GetFileName() const; const std::string GetFileName() const;
const std::string& GetFilePath() const; const std::string& GetFilePath() const;
void SetFilePath(const std::string& filepath); void SetFilePath(const std::string& filepath);
const std::string& GetLauncher() const; const std::string& GetLauncher() const;
void SetLauncher(const std::string& launcher); void SetLauncher(const std::string& launcher);
const std::string& GetManufacturer() const; const std::string& GetManufacturer() const;
void SetManufacturer(const std::string& manufacturer); void SetManufacturer(const std::string& manufacturer);
const std::string& GetName() const; const std::string& GetName() const;
void SetName(const std::string& name); void SetName(const std::string& name);
int GetNumberButtons() const; int GetNumberButtons() const;
std::string GetNumberButtonsString(); std::string GetNumberButtonsString();
void SetNumberButtons(int numberbuttons); void SetNumberButtons(int numberbuttons);
void SetNumberPlayers(int numberplayers); void SetNumberPlayers(int numberplayers);
int GetNumberPlayers() const; int GetNumberPlayers() const;
std::string GetNumberPlayersString(); std::string GetNumberPlayersString();
const std::string& GetTitle() const; const std::string& GetTitle() const;
const std::string& GetLCTitle() const; const std::string& GetLCTitle() const;
void SetTitle(const std::string& title); void SetTitle(const std::string& title);
const std::string& GetYear() const; const std::string& GetYear() const;
void SetYear(const std::string& year); void SetYear(const std::string& year);
bool IsLeaf() const; bool IsLeaf() const;
void SetIsLeaf(bool leaf); void SetIsLeaf(bool leaf);
const std::string& GetFullTitle() const; const std::string& GetFullTitle() const;
void SetFullTitle(const std::string& fulltitle); void SetFullTitle(const std::string& fulltitle);
const std::string& GetCloneOf() const; const std::string& GetCloneOf() const;
void SetCloneOf(const std::string& cloneOf); void SetCloneOf(const std::string& cloneOf);
bool operator<(const Item& rhs); bool operator<(const Item& rhs);
bool operator>(const Item& rhs); bool operator>(const Item& rhs);
private: private:
std::string Launcher; std::string Launcher;
std::string FilePath; std::string FilePath;
std::string Name; std::string Name;
std::string Title; std::string Title;
std::string LCTitle; std::string LCTitle;
std::string FullTitle; std::string FullTitle;
std::string Year; std::string Year;
std::string Manufacturer; std::string Manufacturer;
std::string CloneOf; std::string CloneOf;
int NumberPlayers; int NumberPlayers;
int NumberButtons; int NumberButtons;
bool Leaf; bool Leaf;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "MenuParser.h" #include "MenuParser.h"
#include "Item.h" #include "Item.h"
@@ -14,7 +14,7 @@
bool VectorSort(const Item *d1, const Item *d2) bool VectorSort(const Item *d1, const Item *d2)
{ {
return d1->GetLCTitle() < d2->GetLCTitle(); return d1->GetLCTitle() < d2->GetLCTitle();
} }
MenuParser::MenuParser() MenuParser::MenuParser()
@@ -28,81 +28,81 @@ MenuParser::~MenuParser()
//todo: clean up this method, too much nesting //todo: clean up this method, too much nesting
bool MenuParser::GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector<Item *> &items) bool MenuParser::GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector<Item *> &items)
{ {
bool retVal = false; bool retVal = false;
//todo: magic string //todo: magic string
std::string menuFilename = Configuration::GetAbsolutePath() + "/Collections/" + collectionName + "/Menu.xml"; std::string menuFilename = Configuration::GetAbsolutePath() + "/Collections/" + collectionName + "/Menu.xml";
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
rapidxml::xml_node<> * rootNode; rapidxml::xml_node<> * rootNode;
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 try
{ {
std::ifstream file(menuFilename.c_str()); std::ifstream file(menuFilename.c_str());
// gracefully exit if there is no menu file for the pa // gracefully exit if there is no menu file for the pa
if(file.good()) if(file.good())
{ {
Logger::Write(Logger::ZONE_INFO, "Menu", "Found menu"); Logger::Write(Logger::ZONE_INFO, "Menu", "Found menu");
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
buffer.push_back('\0'); buffer.push_back('\0');
doc.parse<0>(&buffer[0]); doc.parse<0>(&buffer[0]);
rootNode = doc.first_node("menu"); rootNode = doc.first_node("menu");
for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling()) for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling())
{
rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection");
rapidxml::xml_attribute<> *importAttribute = itemNode->first_attribute("import");
if(!collectionAttribute)
{ {
retVal = false; rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection");
Logger::Write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute"); rapidxml::xml_attribute<> *importAttribute = itemNode->first_attribute("import");
break;
if(!collectionAttribute)
{
retVal = false;
Logger::Write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute");
break;
}
else
{
//todo: too much nesting! Ack!
std::string import;
if(importAttribute)
{
import = importAttribute->value();
}
if(import != "true")
{
//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);
items.push_back(item);
}
else
{
std::string collectionName = collectionAttribute->value();
Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName);
cdb->GetCollection(collectionAttribute->value(), items);
}
}
} }
else
{
//todo: too much nesting! Ack!
std::string import;
if(importAttribute)
{
import = importAttribute->value();
}
if(import != "true")
{
//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);
items.push_back(item);
}
else
{
std::string collectionName = collectionAttribute->value();
Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName);
cdb->GetCollection(collectionAttribute->value(), items);
}
}
}
std::sort( items.begin(), items.end(), VectorSort); std::sort( items.begin(), items.end(), VectorSort);
retVal = true; retVal = true;
} }
} }
catch(std::ifstream::failure &e) catch(std::ifstream::failure &e)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what(); ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what();
Logger::Write(Logger::ZONE_ERROR, "Menu", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Menu", ss.str());
} }
return retVal; return retVal;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include "Item.h" #include "Item.h"
@@ -10,8 +10,8 @@ class CollectionDatabase;
class MenuParser class MenuParser
{ {
public: public:
MenuParser(); MenuParser();
virtual ~MenuParser(); virtual ~MenuParser();
bool GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector<Item *> &items); bool GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector<Item *> &items);
}; };

View File

@@ -1,12 +1,12 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "UserInput.h" #include "UserInput.h"
#include "../Database/Configuration.h" #include "../Database/Configuration.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
UserInput::UserInput(Configuration *c) UserInput::UserInput(Configuration *c)
: Config(c) : Config(c)
{ {
} }
@@ -16,63 +16,63 @@ UserInput::~UserInput()
bool UserInput::Initialize() bool UserInput::Initialize()
{ {
bool retVal = true; bool retVal = true;
retVal = MapKey("nextItem", KeyCodeNextItem) && retVal; retVal = MapKey("nextItem", KeyCodeNextItem) && retVal;
retVal = MapKey("previousItem", KeyCodePreviousItem) && retVal; retVal = MapKey("previousItem", KeyCodePreviousItem) && retVal;
retVal = MapKey("pageDown", KeyCodePageDown) && retVal; retVal = MapKey("pageDown", KeyCodePageDown) && retVal;
retVal = MapKey("pageUp", KeyCodePageUp) && retVal; retVal = MapKey("pageUp", KeyCodePageUp) && retVal;
retVal = MapKey("select", KeyCodeSelect) && retVal; retVal = MapKey("select", KeyCodeSelect) && retVal;
retVal = MapKey("back", KeyCodeBack) && retVal; retVal = MapKey("back", KeyCodeBack) && retVal;
retVal = MapKey("quit", KeyCodeQuit) && retVal; retVal = MapKey("quit", KeyCodeQuit) && retVal;
// these features will need to be implemented at a later time // these features will need to be implemented at a later time
// retVal = MapKey("admin", KeyCodeAdminMode) && retVal; // retVal = MapKey("admin", KeyCodeAdminMode) && retVal;
// retVal = MapKey("remove", KeyCodeHideItem) && retVal; // retVal = MapKey("remove", KeyCodeHideItem) && retVal;
return retVal; return retVal;
} }
SDL_Scancode UserInput::GetScancode(KeyCode_E key) SDL_Scancode UserInput::GetScancode(KeyCode_E key)
{ {
SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; 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; scancode = it->second;
} }
return scancode; return scancode;
} }
bool UserInput::MapKey(std::string keyDescription, KeyCode_E key) bool UserInput::MapKey(std::string keyDescription, KeyCode_E key)
{ {
bool retVal = false; bool retVal = false;
SDL_Scancode scanCode; SDL_Scancode scanCode;
std::string description; std::string description;
std::string configKey = "controls." + keyDescription; std::string configKey = "controls." + keyDescription;
if(!Config->GetProperty(configKey, description)) if(!Config->GetProperty(configKey, description))
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property " + configKey); Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property " + configKey);
} }
else else
{ {
scanCode = SDL_GetScancodeFromName(description.c_str()); scanCode = SDL_GetScancodeFromName(description.c_str());
if(scanCode == SDL_SCANCODE_UNKNOWN) if(scanCode == SDL_SCANCODE_UNKNOWN)
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs"); Logger::Write(Logger::ZONE_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs");
} }
else else
{ {
KeyMap[key] = scanCode; KeyMap[key] = scanCode;
retVal = true; retVal = true;
} }
} }
return retVal; return retVal;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include <map> #include <map>
@@ -11,28 +11,28 @@ class Configuration;
class UserInput class UserInput
{ {
public: public:
enum KeyCode_E enum KeyCode_E
{ {
KeyCodeNextItem, KeyCodeNextItem,
KeyCodePreviousItem, KeyCodePreviousItem,
KeyCodeSelect, KeyCodeSelect,
KeyCodeBack, KeyCodeBack,
KeyCodePageDown, KeyCodePageDown,
KeyCodePageUp, KeyCodePageUp,
KeyCodeAdminMode, KeyCodeAdminMode,
KeyCodeHideItem, KeyCodeHideItem,
KeyCodeQuit KeyCodeQuit
}; };
UserInput(Configuration *c); UserInput(Configuration *c);
virtual ~UserInput(); virtual ~UserInput();
bool Initialize(); bool Initialize();
SDL_Scancode GetScancode(KeyCode_E key); SDL_Scancode GetScancode(KeyCode_E key);
private: private:
bool MapKey(std::string keyDescription, KeyCode_E key); bool MapKey(std::string keyDescription, KeyCode_E key);
std::map<KeyCode_E, SDL_Scancode> KeyMap; std::map<KeyCode_E, SDL_Scancode> KeyMap;
Configuration *Config; Configuration *Config;
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -15,30 +15,30 @@ class Item;
class CollectionDatabase class CollectionDatabase
{ {
public: public:
CollectionDatabase(DB *db, Configuration *c); CollectionDatabase(DB *db, Configuration *c);
virtual ~CollectionDatabase(); virtual ~CollectionDatabase();
bool Initialize(); bool Initialize();
bool Import(); bool Import();
bool ResetDatabase(); bool ResetDatabase();
bool GetCollection(std::string collectionName, std::vector<Item *> &list); bool GetCollection(std::string collectionName, std::vector<Item *> &list);
bool SetHidden(std::string collectionName, Item *item, bool hidden); bool SetHidden(std::string collectionName, Item *item, bool hidden);
private: private:
unsigned long CalculateCollectionCrc32(CollectionInfo *info); unsigned long CalculateCollectionCrc32(CollectionInfo *info);
bool CollectionChanged(CollectionInfo *info, unsigned long crc32); bool CollectionChanged(CollectionInfo *info, unsigned long crc32);
unsigned long CrcFile(std::string file, unsigned long crc); unsigned long CrcFile(std::string file, unsigned long crc);
// bool ImportMetadata(CollectionInfo *info); // bool ImportMetadata(CollectionInfo *info);
bool ImportDirectory(CollectionInfo *info, unsigned long crc32); bool ImportDirectory(CollectionInfo *info, unsigned long crc32);
bool ImportBasicList(CollectionInfo *info, bool ImportBasicList(CollectionInfo *info,
std::string file, std::string file,
std::map<std::string, Item *> &list); std::map<std::string, Item *> &list);
bool ImportHyperList(CollectionInfo *info, bool ImportHyperList(CollectionInfo *info,
std::string file, std::string file,
std::map<std::string, Item *> &list); std::map<std::string, Item *> &list);
std::map<std::string, Item *> *ImportHyperList(CollectionInfo *info); std::map<std::string, Item *> *ImportHyperList(CollectionInfo *info);
Configuration *Config; Configuration *Config;
DB *DBInstance; DB *DBInstance;
}; };

View File

@@ -19,7 +19,7 @@
std::string Configuration::AbsolutePath; std::string Configuration::AbsolutePath;
Configuration::Configuration() Configuration::Configuration()
: Verbose(false) : Verbose(false)
{ {
} }
@@ -27,307 +27,307 @@ Configuration::~Configuration()
{ {
} }
void Configuration::Initialize() void Configuration::Initialize()
{ {
const char *environment = std::getenv("RETROFE_PATH"); const char *environment = std::getenv("RETROFE_PATH");
std::string environmentStr; std::string environmentStr;
if (environment != NULL) if (environment != NULL)
{ {
environmentStr = environment; environmentStr = environment;
Configuration::SetAbsolutePath(environment); Configuration::SetAbsolutePath(environment);
} }
else else
{ {
#ifdef WIN32 #ifdef WIN32
HMODULE hModule = GetModuleHandle(NULL); HMODULE hModule = GetModuleHandle(NULL);
CHAR exe[MAX_PATH]; CHAR exe[MAX_PATH];
GetModuleFileName(hModule, exe, MAX_PATH); GetModuleFileName(hModule, exe, MAX_PATH);
std::string sPath(exe); std::string sPath(exe);
sPath = Utils::GetDirectory(sPath); sPath = Utils::GetDirectory(sPath);
sPath = Utils::GetParentDirectory(sPath); sPath = Utils::GetParentDirectory(sPath);
#else #else
char exepath[1024]; char exepath[1024];
sprintf(exepath, "/proc/%d/exe", getpid()); sprintf(exepath, "/proc/%d/exe", getpid());
readlink(exepath, exepath, sizeof(exepath)); readlink(exepath, exepath, sizeof(exepath));
std::string sPath(exepath); std::string sPath(exepath);
sPath = Utils::GetDirectory(sPath); sPath = Utils::GetDirectory(sPath);
#endif #endif
Configuration::SetAbsolutePath(sPath); Configuration::SetAbsolutePath(sPath);
} }
} }
bool Configuration::Import(std::string keyPrefix, std::string file) bool Configuration::Import(std::string keyPrefix, std::string file)
{ {
bool retVal = true; bool retVal = true;
int lineCount = 0; int lineCount = 0;
std::string line; std::string line;
Logger::Write(Logger::ZONE_INFO, "Configuration", "Importing " + file); Logger::Write(Logger::ZONE_INFO, "Configuration", "Importing " + file);
std::ifstream ifs(file.c_str()); std::ifstream ifs(file.c_str());
if (!ifs.is_open()) if (!ifs.is_open())
{ {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file); Logger::Write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file);
return false; return false;
} }
while (std::getline (ifs, line)) while (std::getline (ifs, line))
{ {
lineCount++; lineCount++;
retVal = retVal && ParseLine(keyPrefix, line, lineCount); retVal = retVal && ParseLine(keyPrefix, line, lineCount);
} }
ifs.close(); ifs.close();
return retVal; 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; bool retVal = false;
std::string key; std::string key;
std::string value; std::string value;
size_t position; size_t position;
std::string delimiter = "="; std::string delimiter = "=";
// strip out any comments // strip out any comments
if((position = line.find("#")) != std::string::npos) if((position = line.find("#")) != std::string::npos)
{ {
line = line.substr(0, position); line = line.substr(0, position);
} }
// unix only wants \n. Windows uses \r\n. Strip off the \r for unix. // unix only wants \n. Windows uses \r\n. Strip off the \r for unix.
line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() );
if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos)) if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos))
{ {
retVal = true; retVal = true;
} }
// all configuration fields must have an assignment operator // all configuration fields must have an assignment operator
else if((position = line.find(delimiter)) != std::string::npos) else if((position = line.find(delimiter)) != std::string::npos)
{ {
if(keyPrefix.size() != 0) if(keyPrefix.size() != 0)
{ {
keyPrefix += "."; keyPrefix += ".";
} }
key = keyPrefix + line.substr(0, position); key = keyPrefix + line.substr(0, position);
key = TrimEnds(key); key = TrimEnds(key);
value = line.substr(position + delimiter.length(), line.length()); value = line.substr(position + delimiter.length(), line.length());
value = TrimEnds(value); value = TrimEnds(value);
Properties.insert(PropertiesPair(key, value)); Properties.insert(PropertiesPair(key, value));
std::stringstream ss; std::stringstream ss;
ss << "Dump: " << "\"" << key << "\" = \"" << value << "\""; ss << "Dump: " << "\"" << key << "\" = \"" << value << "\"";
Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str()); Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str());
retVal = true; retVal = true;
} }
else else
{ {
std::stringstream ss; std::stringstream ss;
ss << "Missing an assignment operator (=) on line " << lineCount; ss << "Missing an assignment operator (=) on line " << lineCount;
Logger::Write(Logger::ZONE_ERROR, "Configuration", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Configuration", ss.str());
} }
return retVal; return retVal;
} }
std::string Configuration::TrimEnds(std::string str) std::string Configuration::TrimEnds(std::string str)
{ {
// strip off any initial tabs or spaces // strip off any initial tabs or spaces
size_t trimStart = str.find_first_not_of(" \t"); size_t trimStart = str.find_first_not_of(" \t");
if(trimStart != std::string::npos) if(trimStart != std::string::npos)
{ {
size_t trimEnd = str.find_last_not_of(" \t"); size_t trimEnd = str.find_last_not_of(" \t");
str = str.substr(trimStart, trimEnd - trimStart + 1); str = str.substr(trimStart, trimEnd - trimStart + 1);
} }
return str; return str;
} }
bool Configuration::GetProperty(std::string key, std::string &value) bool Configuration::GetProperty(std::string key, std::string &value)
{ {
bool retVal = false; bool retVal = false;
if(Properties.find(key) != Properties.end()) if(Properties.find(key) != Properties.end())
{ {
value = Properties[key]; value = Properties[key];
retVal = true; retVal = true;
} }
else if(Verbose) else if(Verbose)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key); Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key);
} }
return retVal; return retVal;
} }
bool Configuration::GetProperty(std::string key, int &value) bool Configuration::GetProperty(std::string key, int &value)
{ {
std::string strValue; std::string strValue;
bool retVal = GetProperty(key, strValue); bool retVal = GetProperty(key, strValue);
if(retVal) if(retVal)
{ {
std::stringstream ss; std::stringstream ss;
ss << strValue; ss << strValue;
ss >> value; ss >> value;
} }
return retVal; return retVal;
} }
bool Configuration::GetProperty(std::string key, bool &value) bool Configuration::GetProperty(std::string key, bool &value)
{ {
std::string strValue; std::string strValue;
bool retVal = GetProperty(key, strValue); bool retVal = GetProperty(key, strValue);
if(retVal) if(retVal)
{ {
std::stringstream ss; std::stringstream ss;
ss << strValue; ss << strValue;
for(unsigned int i=0; i < strValue.length(); ++i) for(unsigned int i=0; i < strValue.length(); ++i)
{ {
std::locale loc; std::locale loc;
strValue[i] = std::tolower(strValue[i], loc); strValue[i] = std::tolower(strValue[i], loc);
} }
if(!strValue.compare("yes") || !strValue.compare("true")) if(!strValue.compare("yes") || !strValue.compare("true"))
{ {
value = true; value = true;
} }
else else
{ {
value = false; value = false;
} }
} }
return retVal; return retVal;
} }
void Configuration::SetProperty(std::string key, std::string value) void Configuration::SetProperty(std::string key, std::string value)
{ {
Properties[key] = value; Properties[key] = value;
} }
bool Configuration::PropertyExists(std::string key) bool Configuration::PropertyExists(std::string key)
{ {
return (Properties.find(key) != Properties.end()); return (Properties.find(key) != Properties.end());
} }
bool Configuration::PropertyPrefixExists(std::string key) bool Configuration::PropertyPrefixExists(std::string key)
{ {
PropertiesType::iterator it; PropertiesType::iterator it;
for(it = Properties.begin(); it != Properties.end(); ++it) for(it = Properties.begin(); it != Properties.end(); ++it)
{ {
std::string search = key + "."; std::string search = key + ".";
if(it->first.compare(0, search.length(), search) == 0) if(it->first.compare(0, search.length(), search) == 0)
{ {
return true; return true;
} }
} }
return false; return false;
} }
void Configuration::GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children) void Configuration::GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children)
{ {
PropertiesType::iterator it; PropertiesType::iterator it;
for(it = Properties.begin(); it != Properties.end(); ++it) for(it = Properties.begin(); it != Properties.end(); ++it)
{ {
std::string search = parent + "."; std::string search = parent + ".";
if(it->first.compare(0, search.length(), search) == 0) if(it->first.compare(0, search.length(), search) == 0)
{ {
std::string crumb = Utils::Replace(it->first, search, ""); std::string crumb = Utils::Replace(it->first, search, "");
std::size_t end = crumb.find_first_of("."); std::size_t end = crumb.find_first_of(".");
if(end != std::string::npos) if(end != std::string::npos)
{ {
crumb = crumb.substr(0, end); crumb = crumb.substr(0, end);
} }
if(std::find(children.begin(), children.end(), crumb) == children.end()) if(std::find(children.begin(), children.end(), crumb) == children.end())
{ {
children.push_back(crumb); children.push_back(crumb);
} }
} }
} }
} }
std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string path) std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string path)
{ {
char first = ' '; char first = ' ';
char second = ' '; char second = ' ';
if(path.length() >= 0) if(path.length() >= 0)
{ {
first = path.c_str()[0]; first = path.c_str()[0];
} }
if(path.length() >= 1) if(path.length() >= 1)
{ {
second = path.c_str()[1]; second = path.c_str()[1];
} }
// check to see if it is already an absolute path // check to see if it is already an absolute path
if((first != '/') && if((first != '/') &&
(first != '\\') && (first != '\\') &&
//(first != '.') && //(first != '.') &&
(second != ':')) (second != ':'))
{ {
path = prefix + "/" + path; path = prefix + "/" + path;
} }
return path; return path;
} }
bool Configuration::GetPropertyAbsolutePath(std::string key, std::string &value) bool Configuration::GetPropertyAbsolutePath(std::string key, std::string &value)
{ {
bool retVal = GetProperty(key, value); bool retVal = GetProperty(key, value);
if(retVal) if(retVal)
{ {
value = ConvertToAbsolutePath(GetAbsolutePath(), value); value = ConvertToAbsolutePath(GetAbsolutePath(), value);
} }
return retVal; return retVal;
} }
void Configuration::SetAbsolutePath(std::string absolutePath) void Configuration::SetAbsolutePath(std::string absolutePath)
{ {
AbsolutePath = absolutePath; AbsolutePath = absolutePath;
} }
std::string Configuration::GetAbsolutePath() std::string Configuration::GetAbsolutePath()
{ {
return AbsolutePath; return AbsolutePath;
} }
bool Configuration::IsVerbose() const bool Configuration::IsVerbose() const
{ {
return Verbose; return Verbose;
} }
void Configuration::SetVerbose(bool verbose) void Configuration::SetVerbose(bool verbose)
{ {
this->Verbose = verbose; this->Verbose = verbose;
} }

View File

@@ -10,35 +10,35 @@
class Configuration class Configuration
{ {
public: public:
Configuration(); Configuration();
virtual ~Configuration(); virtual ~Configuration();
static void Initialize(); static void Initialize();
static void SetAbsolutePath(std::string absolutePath); static void SetAbsolutePath(std::string absolutePath);
static std::string GetAbsolutePath(); static std::string GetAbsolutePath();
static std::string ConvertToAbsolutePath(std::string prefix, std::string path); static std::string ConvertToAbsolutePath(std::string prefix, std::string path);
// gets the global configuration // gets the global configuration
bool Import(std::string keyPrefix, std::string file); bool Import(std::string keyPrefix, std::string file);
bool GetProperty(std::string key, std::string &value); bool GetProperty(std::string key, std::string &value);
bool GetProperty(std::string key, int &value); bool GetProperty(std::string key, int &value);
bool GetProperty(std::string key, bool &value); bool GetProperty(std::string key, bool &value);
void GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children); void GetChildKeyCrumbs(std::string parent, std::vector<std::string> &children);
void SetProperty(std::string key, std::string value); void SetProperty(std::string key, std::string value);
bool PropertyExists(std::string key); bool PropertyExists(std::string key);
bool PropertyPrefixExists(std::string key); bool PropertyPrefixExists(std::string key);
bool GetPropertyAbsolutePath(std::string key, std::string &value); bool GetPropertyAbsolutePath(std::string key, std::string &value);
bool IsVerbose() const; bool IsVerbose() const;
void SetVerbose(bool verbose); void SetVerbose(bool verbose);
bool IsRequiredPropertiesSet(); bool IsRequiredPropertiesSet();
private: private:
bool ParseLine(std::string keyPrefix, std::string line, int lineCount); bool ParseLine(std::string keyPrefix, std::string line, int lineCount);
std::string TrimEnds(std::string str); std::string TrimEnds(std::string str);
typedef std::map<std::string, std::string> PropertiesType; typedef std::map<std::string, std::string> PropertiesType;
typedef std::pair<std::string, std::string> PropertiesPair; typedef std::pair<std::string, std::string> PropertiesPair;
bool Verbose; bool Verbose;
static std::string AbsolutePath; static std::string AbsolutePath;
PropertiesType Properties; PropertiesType Properties;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "DB.h" #include "DB.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
@@ -8,42 +8,42 @@
#include <fstream> #include <fstream>
DB::DB(std::string dbFile) DB::DB(std::string dbFile)
: Path(dbFile) : Path(dbFile)
, Handle(NULL) , Handle(NULL)
{ {
} }
DB::~DB() DB::~DB()
{ {
DeInitialize(); DeInitialize();
} }
bool DB::Initialize() bool DB::Initialize()
{ {
bool retVal = false; bool retVal = false;
if(sqlite3_open(Path.c_str(), &Handle) != 0) if(sqlite3_open(Path.c_str(), &Handle) != 0)
{ {
std::stringstream ss; std::stringstream ss;
ss << "Cannot open database: \"" << Path << "\"" << sqlite3_errmsg(Handle); ss << "Cannot open database: \"" << Path << "\"" << sqlite3_errmsg(Handle);
Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Database", ss.str());
} }
else else
{ {
Logger::Write(Logger::ZONE_INFO, "Database", "Opened database \"" + Path + "\""); Logger::Write(Logger::ZONE_INFO, "Database", "Opened database \"" + Path + "\"");
retVal = true; retVal = true;
} }
return retVal; return retVal;
} }
void DB::DeInitialize() void DB::DeInitialize()
{ {
if(Handle != NULL) if(Handle != NULL)
{ {
sqlite3_close(Handle); sqlite3_close(Handle);
Handle = NULL; Handle = NULL;
} }
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -8,14 +8,17 @@
class DB class DB
{ {
public: public:
DB(std::string dbFile); DB(std::string dbFile);
bool Initialize(); bool Initialize();
void DeInitialize(); void DeInitialize();
virtual ~DB(); virtual ~DB();
sqlite3 *GetHandle() { return Handle; } sqlite3 *GetHandle()
{
return Handle;
}
private: private:
sqlite3 *Handle; sqlite3 *Handle;
std::string Path; std::string Path;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "MamelistMetadata.h" #include "MamelistMetadata.h"
#include "DB.h" #include "DB.h"
@@ -13,7 +13,7 @@
MamelistMetadata::MamelistMetadata(DB *dbInstance) MamelistMetadata::MamelistMetadata(DB *dbInstance)
: DBInstance(dbInstance) : DBInstance(dbInstance)
{ {
} }
@@ -23,97 +23,97 @@ MamelistMetadata::~MamelistMetadata()
bool MamelistMetadata::Import(std::string filename, std::string collection) bool MamelistMetadata::Import(std::string filename, std::string collection)
{ {
bool retVal = true; bool retVal = true;
rapidxml::xml_document<> doc; rapidxml::xml_document<> doc;
rapidxml::xml_node<> * rootNode; rapidxml::xml_node<> * rootNode;
char *error = NULL; char *error = NULL;
sqlite3 *handle = DBInstance->GetHandle(); sqlite3 *handle = DBInstance->GetHandle();
std::ifstream f(filename.c_str()); std::ifstream f(filename.c_str());
if (!f.good()) if (!f.good())
{ {
Logger::Write(Logger::ZONE_ERROR, "Mamelist", "Could not find mamelist metadata file at \"" + filename + "\""); Logger::Write(Logger::ZONE_ERROR, "Mamelist", "Could not find mamelist metadata file at \"" + filename + "\"");
retVal = false; retVal = false;
} }
f.close(); f.close();
if(retVal) if(retVal)
{ {
Logger::Write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\""); Logger::Write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\"");
std::ifstream file(filename.c_str()); std::ifstream file(filename.c_str());
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
buffer.push_back('\0'); buffer.push_back('\0');
doc.parse<0>(&buffer[0]); doc.parse<0>(&buffer[0]);
rootNode = doc.first_node("mame"); rootNode = doc.first_node("mame");
sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error);
for (rapidxml::xml_node<> * game = rootNode->first_node("game"); game; game = game->next_sibling()) for (rapidxml::xml_node<> * game = rootNode->first_node("game"); game; game = game->next_sibling())
{ {
rapidxml::xml_attribute<> *nameNode = game->first_attribute("name"); rapidxml::xml_attribute<> *nameNode = game->first_attribute("name");
rapidxml::xml_attribute<> *cloneOfXml = game->first_attribute("cloneof"); rapidxml::xml_attribute<> *cloneOfXml = game->first_attribute("cloneof");
if(nameNode != NULL) if(nameNode != NULL)
{ {
std::string name = nameNode->value(); std::string name = nameNode->value();
rapidxml::xml_node<> *descriptionNode = game->first_node("description"); rapidxml::xml_node<> *descriptionNode = game->first_node("description");
rapidxml::xml_node<> *yearNode = game->first_node("year"); rapidxml::xml_node<> *yearNode = game->first_node("year");
rapidxml::xml_node<> *manufacturerNode = game->first_node("manufacturer"); rapidxml::xml_node<> *manufacturerNode = game->first_node("manufacturer");
rapidxml::xml_node<> *inputNode = game->first_node("input"); rapidxml::xml_node<> *inputNode = game->first_node("input");
std::string description = (descriptionNode == NULL) ? nameNode->value() : descriptionNode->value(); std::string description = (descriptionNode == NULL) ? nameNode->value() : descriptionNode->value();
std::string year = (yearNode == NULL) ? "" : yearNode->value(); std::string year = (yearNode == NULL) ? "" : yearNode->value();
std::string manufacturer = (manufacturerNode == NULL) ? "" : manufacturerNode->value(); std::string manufacturer = (manufacturerNode == NULL) ? "" : manufacturerNode->value();
std::string cloneOf = (cloneOfXml == NULL) ? "" : cloneOfXml->value(); std::string cloneOf = (cloneOfXml == NULL) ? "" : cloneOfXml->value();
std::string players; std::string players;
std::string buttons; std::string buttons;
if(inputNode != NULL) if(inputNode != NULL)
{ {
rapidxml::xml_attribute<> *playersAttribute = inputNode->first_attribute("players"); rapidxml::xml_attribute<> *playersAttribute = inputNode->first_attribute("players");
rapidxml::xml_attribute<> *buttonsAttribute = inputNode->first_attribute("buttons"); rapidxml::xml_attribute<> *buttonsAttribute = inputNode->first_attribute("buttons");
if(playersAttribute) if(playersAttribute)
{ {
players = playersAttribute->value(); players = playersAttribute->value();
} }
if(buttonsAttribute) if(buttonsAttribute)
{ {
buttons = buttonsAttribute->value(); buttons = buttonsAttribute->value();
} }
} }
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
sqlite3_prepare_v2(handle, sqlite3_prepare_v2(handle,
"UPDATE OR REPLACE Meta SET title=?, year=?, manufacturer=?, players=?, buttons=?, cloneOf=? WHERE name=? AND collectionName=?;", "UPDATE OR REPLACE Meta SET title=?, year=?, manufacturer=?, players=?, buttons=?, cloneOf=? WHERE name=? AND collectionName=?;",
-1, &stmt, 0); -1, &stmt, 0);
sqlite3_bind_text(stmt, 1, description.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 1, description.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, year.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 2, year.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 3, manufacturer.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 3, manufacturer.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 4, players.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 4, players.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 5, buttons.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 5, buttons.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 6, cloneOf.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 6, cloneOf.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 7, name.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 7, name.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 8, collection.c_str(), -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 8, collection.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_step(stmt); sqlite3_step(stmt);
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
} }
} }
sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error);
} }
return retVal; return retVal;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -10,9 +10,9 @@ class DB;
class MamelistMetadata : Metadata class MamelistMetadata : Metadata
{ {
public: public:
MamelistMetadata(DB *dbInstance); MamelistMetadata(DB *dbInstance);
virtual ~MamelistMetadata(); virtual ~MamelistMetadata();
bool Import(std::string file, std::string collectionName); bool Import(std::string file, std::string collectionName);
private: private:
DB *DBInstance; DB *DBInstance;
}; };

View File

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

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "Launcher.h" #include "Launcher.h"
#include "../Collection/Item.h" #include "../Collection/Item.h"
@@ -18,309 +18,309 @@
#endif #endif
Launcher::Launcher(RetroFE *p) Launcher::Launcher(RetroFE *p)
: Config(p->GetConfiguration()) : Config(p->GetConfiguration())
, RetroFEInst(p) , RetroFEInst(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->GetLauncher();
std::string executablePath; std::string executablePath;
std::string selectedItemsDirectory; std::string selectedItemsDirectory;
std::string selectedItemsPath; std::string selectedItemsPath;
std::string currentDirectory; std::string currentDirectory;
std::string extensions; std::string extensions;
std::string matchedExtension; std::string matchedExtension;
std::string args; std::string args;
if(!GetLauncherExecutable(executablePath, currentDirectory, launcherName)) if(!GetLauncherExecutable(executablePath, currentDirectory, launcherName))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")"); Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")");
return false; return false;
} }
if(!GetExtensions(extensions, collection)) if(!GetExtensions(extensions, collection))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\""); Logger::Write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\"");
return false; return false;
} }
if(!GetCollectionDirectory(selectedItemsDirectory, collection)) if(!GetCollectionDirectory(selectedItemsDirectory, collection))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\""); Logger::Write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\"");
return false; return false;
} }
if(!GetLauncherArgs(args, launcherName)) if(!GetLauncherArgs(args, launcherName))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName); Logger::Write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName);
return false; return false;
} }
if(!FindFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->GetName(), extensions)) if(!FindFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->GetName(), extensions))
{ {
// FindFile() prints out diagnostic messages for us, no need to print anything here // FindFile() prints out diagnostic messages for us, no need to print anything here
return false; return false;
} }
args = ReplaceVariables(args, args = ReplaceVariables(args,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->GetName(),
collectionItem->GetFileName(), collectionItem->GetFileName(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
executablePath = ReplaceVariables(executablePath, executablePath = ReplaceVariables(executablePath,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->GetName(),
collectionItem->GetFileName(), collectionItem->GetFileName(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
currentDirectory = ReplaceVariables(currentDirectory, currentDirectory = ReplaceVariables(currentDirectory,
selectedItemsPath, selectedItemsPath,
collectionItem->GetName(), collectionItem->GetName(),
collectionItem->GetFileName(), collectionItem->GetFileName(),
selectedItemsDirectory, selectedItemsDirectory,
collection); collection);
if(!ExecuteCommand(executablePath, args, currentDirectory)) if(!ExecuteCommand(executablePath, args, currentDirectory))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to launch."); Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to launch.");
return false; return false;
} }
return true; return true;
} }
std::string Launcher::ReplaceVariables(std::string str, std::string Launcher::ReplaceVariables(std::string str,
std::string itemFilePath, std::string itemFilePath,
std::string itemName, std::string itemName,
std::string itemFilename, std::string itemFilename,
std::string itemDirectory, std::string itemDirectory,
std::string itemCollectionName) std::string itemCollectionName)
{ {
str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath); str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath);
str = Utils::Replace(str, "%ITEM_NAME%", itemName); str = Utils::Replace(str, "%ITEM_NAME%", itemName);
str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename); str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename);
str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory); str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory);
str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName); str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName);
str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath()); str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath());
#ifdef WIN32 #ifdef WIN32
str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE.exe"); str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE.exe");
#else #else
str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE"); str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE");
#endif #endif
return str; return str;
} }
bool Launcher::ExecuteCommand(std::string executable, std::string args, std::string currentDirectory) bool Launcher::ExecuteCommand(std::string executable, std::string args, std::string currentDirectory)
{ {
bool retVal = false; bool retVal = false;
std::string executionString = "\"" + executable + "\" " + args; std::string executionString = "\"" + executable + "\" " + args;
Logger::Write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString); Logger::Write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString);
Logger::Write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory); Logger::Write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory);
//todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface) //todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface)
RetroFEInst->LaunchEnter(); RetroFEInst->LaunchEnter();
#ifdef WIN32 #ifdef WIN32
STARTUPINFO startupInfo; STARTUPINFO startupInfo;
PROCESS_INFORMATION processInfo; PROCESS_INFORMATION processInfo;
char applicationName[256]; char applicationName[256];
char currDir[256]; char currDir[256];
memset(&applicationName, 0, sizeof(applicationName)); memset(&applicationName, 0, sizeof(applicationName));
memset(&startupInfo, 0, sizeof(startupInfo)); memset(&startupInfo, 0, sizeof(startupInfo));
memset(&processInfo, 0, sizeof(processInfo)); memset(&processInfo, 0, sizeof(processInfo));
strncpy(applicationName, executionString.c_str(), sizeof(applicationName)); strncpy(applicationName, executionString.c_str(), sizeof(applicationName));
strncpy(currDir, currentDirectory.c_str(), sizeof(currDir)); strncpy(currDir, currentDirectory.c_str(), sizeof(currDir));
startupInfo.dwFlags = STARTF_USESTDHANDLES; startupInfo.dwFlags = STARTF_USESTDHANDLES;
startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startupInfo.wShowWindow = SW_SHOWDEFAULT; startupInfo.wShowWindow = SW_SHOWDEFAULT;
if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo)) if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo))
#else #else
if(system(executionString.c_str()) != 0) if(system(executionString.c_str()) != 0)
#endif #endif
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable); Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable);
} }
else else
{ {
#ifdef WIN32 #ifdef WIN32
while(WAIT_OBJECT_0 != MsgWaitForMultipleObjects(1, &processInfo.hProcess, FALSE, INFINITE, QS_ALLINPUT)) while(WAIT_OBJECT_0 != MsgWaitForMultipleObjects(1, &processInfo.hProcess, FALSE, INFINITE, QS_ALLINPUT))
{ {
MSG msg; MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{ {
DispatchMessage(&msg); DispatchMessage(&msg);
} }
} }
// result = GetExitCodeProcess(processInfo.hProcess, &exitCode); // result = GetExitCodeProcess(processInfo.hProcess, &exitCode);
CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hProcess);
#endif #endif
retVal = true; retVal = true;
} }
Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed"); Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed");
RetroFEInst->LaunchExit(); RetroFEInst->LaunchExit();
return retVal; return retVal;
} }
bool Launcher::GetLauncherName(std::string &launcherName, std::string collection) bool Launcher::GetLauncherName(std::string &launcherName, std::string collection)
{ {
std::string launcherKey = "collections." + collection + ".launcher"; std::string launcherKey = "collections." + collection + ".launcher";
// find the launcher for the particular item // find the launcher for the particular item
if(!Config->GetProperty(launcherKey, launcherName)) if(!Config->GetProperty(launcherKey, launcherName))
{ {
std::stringstream ss; std::stringstream ss;
ss << "Launch failed. Could not find a configured launcher for collection \"" ss << "Launch failed. Could not find a configured launcher for collection \""
<< collection << collection
<< "\" (could not find a property for \"" << "\" (could not find a property for \""
<< launcherKey << launcherKey
<< "\")"; << "\")";
Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str());
return false; return false;
} }
std::stringstream ss; std::stringstream ss;
ss << "collections." ss << "collections."
<< collection << collection
<< " is configured to use launchers." << " is configured to use launchers."
<< launcherName << launcherName
<< "\""; << "\"";
Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str()); Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str());
return true; return true;
} }
bool Launcher::GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName) bool Launcher::GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName)
{ {
std::string executableKey = "launchers." + launcherName + ".executable"; std::string executableKey = "launchers." + launcherName + ".executable";
if(!Config->GetProperty(executableKey, executable)) if(!Config->GetProperty(executableKey, executable))
{ {
return false; return false;
} }
std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory"; std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory";
currentDirectory = Utils::GetDirectory(executable); currentDirectory = Utils::GetDirectory(executable);
Config->GetProperty(currentDirectoryKey, currentDirectory); Config->GetProperty(currentDirectoryKey, currentDirectory);
return true; return true;
} }
bool Launcher::GetLauncherArgs(std::string &args, std::string launcherName) bool Launcher::GetLauncherArgs(std::string &args, std::string launcherName)
{ {
std::string argsKey = "launchers." + launcherName + ".arguments"; std::string argsKey = "launchers." + launcherName + ".arguments";
if(!Config->GetProperty(argsKey, args)) if(!Config->GetProperty(argsKey, args))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey); Logger::Write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey);
return false; return false;
} }
return true; return true;
} }
bool Launcher::GetExtensions(std::string &extensions, std::string collection) bool Launcher::GetExtensions(std::string &extensions, std::string collection)
{ {
std::string extensionsKey = "collections." + collection + ".list.extensions"; std::string extensionsKey = "collections." + collection + ".list.extensions";
if(!Config->GetProperty(extensionsKey, extensions)) if(!Config->GetProperty(extensionsKey, extensions))
{ {
Logger::Write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey); Logger::Write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey);
return false; return false;
} }
extensions = Utils::Replace(extensions, " ", ""); extensions = Utils::Replace(extensions, " ", "");
extensions = Utils::Replace(extensions, ".", ""); extensions = Utils::Replace(extensions, ".", "");
return true; return true;
} }
bool Launcher::GetCollectionDirectory(std::string &directory, std::string collection) bool Launcher::GetCollectionDirectory(std::string &directory, std::string collection)
{ {
std::string itemsPathKey = "collections." + collection + ".list.path"; std::string itemsPathKey = "collections." + collection + ".list.path";
std::string itemsPathValue; std::string itemsPathValue;
// find the items path folder (i.e. ROM path) // find the items path folder (i.e. ROM path)
if(!Config->GetPropertyAbsolutePath(itemsPathKey, itemsPathValue)) if(!Config->GetPropertyAbsolutePath(itemsPathKey, itemsPathValue))
{ {
directory = ""; directory = "";
} }
else else
{ {
directory += itemsPathValue + "/"; directory += itemsPathValue + "/";
} }
return true; return true;
} }
bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions) bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions)
{ {
std::string extension; std::string extension;
bool fileFound = false; bool fileFound = false;
std::stringstream ss; std::stringstream ss;
ss << extensions; ss << extensions;
while(!fileFound && std::getline(ss, extension, ',') ) while(!fileFound && std::getline(ss, extension, ',') )
{ {
std::string selectedItemsPath = directory + filenameWithoutExtension + "." + extension; std::string selectedItemsPath = directory + filenameWithoutExtension + "." + extension;
std::ifstream f(selectedItemsPath.c_str()); std::ifstream f(selectedItemsPath.c_str());
if (f.good()) if (f.good())
{ {
std::stringstream ss; std::stringstream ss;
ss <<"Checking to see if \"" ss <<"Checking to see if \""
<< selectedItemsPath << "\" exists [Yes]"; << selectedItemsPath << "\" exists [Yes]";
fileFound = true; fileFound = true;
Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str()); Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str());
foundFilePath = selectedItemsPath; foundFilePath = selectedItemsPath;
foundFilename = extension; foundFilename = extension;
} }
else else
{ {
std::stringstream ss; std::stringstream ss;
ss << "Checking to see if \"" ss << "Checking to see if \""
<< selectedItemsPath << "\" exists [No]"; << selectedItemsPath << "\" exists [No]";
Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str()); Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str());
} }
f.close(); f.close();
} }
// get the launchers executable // get the launchers executable
if(!fileFound) if(!fileFound)
{ {
std::stringstream ss; std::stringstream ss;
ss <<"Could not find any files with the name \"" ss <<"Could not find any files with the name \""
<< filenameWithoutExtension << "\" in folder \"" << filenameWithoutExtension << "\" in folder \""
<< directory; << directory;
Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str());
} }
return fileFound; return fileFound;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -12,29 +12,29 @@ class RetroFE;
class Launcher class Launcher
{ {
public: public:
Launcher(RetroFE *p); Launcher(RetroFE *p);
bool Run(std::string collection, Item *collectionItem); bool Run(std::string collection, Item *collectionItem);
private: private:
std::string ReplaceString( std::string ReplaceString(
std::string subject, std::string subject,
const std::string &search, const std::string &search,
const std::string &replace); const std::string &replace);
bool GetLauncherName(std::string &launcherName, std::string collection); bool GetLauncherName(std::string &launcherName, std::string collection);
bool GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName); bool GetLauncherExecutable(std::string &executable, std::string &currentDirectory, std::string launcherName);
bool GetLauncherArgs(std::string &args, std::string launcherName); bool GetLauncherArgs(std::string &args, std::string launcherName);
bool GetExtensions(std::string &extensions, std::string launcherName); bool GetExtensions(std::string &extensions, std::string launcherName);
bool GetCollectionDirectory(std::string &directory, std::string collection); bool GetCollectionDirectory(std::string &directory, std::string collection);
bool ExecuteCommand(std::string executable, std::string arguments, std::string currentDirectory); 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); bool FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions);
std::string ReplaceVariables(std::string str, std::string ReplaceVariables(std::string str,
std::string itemFilePath, std::string itemFilePath,
std::string itemName, std::string itemName,
std::string itemFilename, std::string itemFilename,
std::string itemDirectory, std::string itemDirectory,
std::string itemCollectionName); std::string itemCollectionName);
Configuration *Config; Configuration *Config;
RetroFE *RetroFEInst; RetroFE *RetroFEInst;
}; };

View File

@@ -11,360 +11,360 @@ std::map<std::string, TweenAlgorithm> Tween::TweenTypeMap;
std::map<std::string, TweenProperty> Tween::TweenPropertyMap; std::map<std::string, TweenProperty> Tween::TweenPropertyMap;
Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration) Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration)
: Property(property) : Property(property)
, Type(type) , Type(type)
, Start(start) , Start(start)
, End(end) , End(end)
, Duration(duration) , Duration(duration)
{ {
} }
TweenProperty Tween::GetProperty() const TweenProperty Tween::GetProperty() const
{ {
return Property; return Property;
} }
bool Tween::GetTweenProperty(std::string name, TweenProperty &property) bool Tween::GetTweenProperty(std::string name, TweenProperty &property)
{ {
bool retVal = false; bool retVal = false;
if(TweenPropertyMap.size() == 0) if(TweenPropertyMap.size() == 0)
{ {
TweenPropertyMap["x"] = TWEEN_PROPERTY_X; TweenPropertyMap["x"] = TWEEN_PROPERTY_X;
TweenPropertyMap["y"] = TWEEN_PROPERTY_Y; TweenPropertyMap["y"] = TWEEN_PROPERTY_Y;
TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE; TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE;
TweenPropertyMap["transparency"] = TWEEN_PROPERTY_TRANSPARENCY; TweenPropertyMap["transparency"] = TWEEN_PROPERTY_TRANSPARENCY;
TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH; TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH;
TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT; TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT;
TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN; TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN;
TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN; TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN;
TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET; TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET;
TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET; TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET;
TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE; TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE;
} }
std::transform(name.begin(), name.end(), name.begin(), ::tolower); std::transform(name.begin(), name.end(), name.begin(), ::tolower);
if(TweenPropertyMap.find(name) != TweenPropertyMap.end()) if(TweenPropertyMap.find(name) != TweenPropertyMap.end())
{ {
property = TweenPropertyMap[name]; property = TweenPropertyMap[name];
retVal = true; retVal = true;
} }
return retVal; return retVal;
} }
TweenAlgorithm Tween::GetTweenType(std::string name) TweenAlgorithm Tween::GetTweenType(std::string name)
{ {
if(TweenTypeMap.size() == 0) if(TweenTypeMap.size() == 0)
{ {
TweenTypeMap["easeinquadratic"] = EASE_IN_QUADRATIC; TweenTypeMap["easeinquadratic"] = EASE_IN_QUADRATIC;
TweenTypeMap["easeoutquadratic"] = EASE_OUT_QUADRATIC; TweenTypeMap["easeoutquadratic"] = EASE_OUT_QUADRATIC;
TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC; TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC;
TweenTypeMap["easeincubic"] = EASE_IN_CUBIC; TweenTypeMap["easeincubic"] = EASE_IN_CUBIC;
TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC; TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC;
TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC; TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC;
TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC; TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC;
TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC; TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC;
TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC; TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC;
TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC; TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC;
TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC; TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC;
TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC; TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC;
TweenTypeMap["easeinsine"] = EASE_IN_SINE; TweenTypeMap["easeinsine"] = EASE_IN_SINE;
TweenTypeMap["easeoutsine"] = EASE_OUT_SINE; TweenTypeMap["easeoutsine"] = EASE_OUT_SINE;
TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE; TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE;
TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL; TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL;
TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL; TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL;
TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL; TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL;
TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR; TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR;
TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR; TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR;
TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR; TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR;
TweenTypeMap["linear"] = LINEAR; TweenTypeMap["linear"] = LINEAR;
} }
std::transform(name.begin(), name.end(), name.begin(), ::tolower); std::transform(name.begin(), name.end(), name.begin(), ::tolower);
if(TweenTypeMap.find(name) != TweenTypeMap.end()) if(TweenTypeMap.find(name) != TweenTypeMap.end())
{ {
return TweenTypeMap[name]; return TweenTypeMap[name];
} }
else else
{ {
return TweenTypeMap["linear"]; return TweenTypeMap["linear"];
} }
} }
float Tween::Animate(double elapsedTime) float Tween::Animate(double elapsedTime)
{ {
return AnimateSingle(Type, Start, End, Duration, elapsedTime); return AnimateSingle(Type, Start, End, Duration, elapsedTime);
} }
//todo: SDL likes floats, consider having casting being performed elsewhere //todo: SDL likes floats, consider having casting being performed elsewhere
float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime) float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime)
{ {
double a = start; double a = start;
double b = end - start; double b = end - start;
double result = 0; double result = 0;
switch(type) switch(type)
{ {
case EASE_IN_QUADRATIC: case EASE_IN_QUADRATIC:
result = EaseInQuadratic(elapsedTime, duration, a, b); result = EaseInQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUADRATIC: case EASE_OUT_QUADRATIC:
result = EaseOutQuadratic(elapsedTime, duration, a, b); result = EaseOutQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUADRATIC: case EASE_INOUT_QUADRATIC:
result = EaseInOutQuadratic(elapsedTime, duration, a, b); result = EaseInOutQuadratic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_CUBIC: case EASE_IN_CUBIC:
result = EaseInCubic(elapsedTime, duration, a, b); result = EaseInCubic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_CUBIC: case EASE_OUT_CUBIC:
result = EaseOutCubic(elapsedTime, duration, a, b); result = EaseOutCubic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_CUBIC: case EASE_INOUT_CUBIC:
result = EaseInOutCubic(elapsedTime, duration, a, b); result = EaseInOutCubic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_QUARTIC: case EASE_IN_QUARTIC:
result = EaseInQuartic(elapsedTime, duration, a, b); result = EaseInQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUARTIC: case EASE_OUT_QUARTIC:
result = EaseOutQuartic(elapsedTime, duration, a, b); result = EaseOutQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUARTIC: case EASE_INOUT_QUARTIC:
result = EaseInOutQuartic(elapsedTime, duration, a, b); result = EaseInOutQuartic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_QUINTIC: case EASE_IN_QUINTIC:
result = EaseInQuintic(elapsedTime, duration, a, b); result = EaseInQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_QUINTIC: case EASE_OUT_QUINTIC:
result = EaseOutQuintic(elapsedTime, duration, a, b); result = EaseOutQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_QUINTIC: case EASE_INOUT_QUINTIC:
result = EaseInOutQuintic(elapsedTime, duration, a, b); result = EaseInOutQuintic(elapsedTime, duration, a, b);
break; break;
case EASE_IN_SINE: case EASE_IN_SINE:
result = EaseInSine(elapsedTime, duration, a, b); result = EaseInSine(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_SINE: case EASE_OUT_SINE:
result = EaseOutSine(elapsedTime, duration, a, b); result = EaseOutSine(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_SINE: case EASE_INOUT_SINE:
result = EaseInOutSine(elapsedTime, duration, a, b); result = EaseInOutSine(elapsedTime, duration, a, b);
break; break;
case EASE_IN_EXPONENTIAL: case EASE_IN_EXPONENTIAL:
result = EaseInExponential(elapsedTime, duration, a, b); result = EaseInExponential(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_EXPONENTIAL: case EASE_OUT_EXPONENTIAL:
result = EaseOutExponential(elapsedTime, duration, a, b); result = EaseOutExponential(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_EXPONENTIAL: case EASE_INOUT_EXPONENTIAL:
result = EaseInOutExponential(elapsedTime, duration, a, b); result = EaseInOutExponential(elapsedTime, duration, a, b);
break; break;
case EASE_IN_CIRCULAR: case EASE_IN_CIRCULAR:
result = EaseInCircular(elapsedTime, duration, a, b); result = EaseInCircular(elapsedTime, duration, a, b);
break; break;
case EASE_OUT_CIRCULAR: case EASE_OUT_CIRCULAR:
result = EaseOutCircular(elapsedTime, duration, a, b); result = EaseOutCircular(elapsedTime, duration, a, b);
break; break;
case EASE_INOUT_CIRCULAR: case EASE_INOUT_CIRCULAR:
result = EaseInOutCircular(elapsedTime, duration, a, b); result = EaseInOutCircular(elapsedTime, duration, a, b);
break; break;
case LINEAR: case LINEAR:
default: default:
result = Linear(elapsedTime, duration, a, b); result = Linear(elapsedTime, duration, a, b);
break; break;
} }
return static_cast<float>(result); return static_cast<float>(result);
} }
double Tween::Linear(double t, double d, double b, double c) double Tween::Linear(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
return c*t/d + b; return c*t/d + b;
}; };
double Tween::EaseInQuadratic(double t, double d, double b, double c) double Tween::EaseInQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t + b; return c*t*t + b;
}; };
double Tween::EaseOutQuadratic(double t, double d, double b, double c) double Tween::EaseOutQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return -c * t*(t-2) + b; return -c * t*(t-2) + b;
}; };
double Tween::EaseInOutQuadratic(double t, double d, double b, double c) double Tween::EaseInOutQuadratic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
if (t < 1) return c/2*t*t + b; if (t < 1) return c/2*t*t + b;
t--; t--;
return -c/2 * (t*(t-2) - 1) + b; return -c/2 * (t*(t-2) - 1) + b;
}; };
double Tween::EaseInCubic(double t, double d, double b, double c) double Tween::EaseInCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t*t + b; return c*t*t*t + b;
}; };
double Tween::EaseOutCubic(double t, double d, double b, double c) double Tween::EaseOutCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
t--; t--;
return c*(t*t*t + 1) + b; return c*(t*t*t + 1) + b;
}; };
double Tween::EaseInOutCubic(double t, double d, double b, double c) double Tween::EaseInOutCubic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
if (t < 1) return c/2*t*t*t + b; if (t < 1) return c/2*t*t*t + b;
t -= 2; t -= 2;
return c/2*(t*t*t + 2) + b; return c/2*(t*t*t + 2) + b;
}; };
double Tween::EaseInQuartic(double t, double d, double b, double c) double Tween::EaseInQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t*t*t + b; return c*t*t*t*t + b;
}; };
double Tween::EaseOutQuartic(double t, double d, double b, double c) double Tween::EaseOutQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
t--; t--;
return -c * (t*t*t*t - 1) + b; return -c * (t*t*t*t - 1) + b;
}; };
double Tween::EaseInOutQuartic(double t, double d, double b, double c) double Tween::EaseInOutQuartic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
if (t < 1) return c/2*t*t*t*t + b; if (t < 1) return c/2*t*t*t*t + b;
t -= 2; t -= 2;
return -c/2 * (t*t*t*t - 2) + b; return -c/2 * (t*t*t*t - 2) + b;
}; };
double Tween::EaseInQuintic(double t, double d, double b, double c) double Tween::EaseInQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
return c*t*t*t*t*t + b; return c*t*t*t*t*t + b;
}; };
double Tween::EaseOutQuintic(double t, double d, double b, double c) double Tween::EaseOutQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d; t /= d;
t--; t--;
return c*(t*t*t*t*t + 1) + b; return c*(t*t*t*t*t + 1) + b;
}; };
double Tween::EaseInOutQuintic(double t, double d, double b, double c) double Tween::EaseInOutQuintic(double t, double d, double b, double c)
{ {
if(d == 0) return b; if(d == 0) return b;
t /= d/2; t /= d/2;
if (t < 1) return c/2*t*t*t*t*t + b; if (t < 1) return c/2*t*t*t*t*t + b;
t -= 2; t -= 2;
return c/2*(t*t*t*t*t + 2) + b; return c/2*(t*t*t*t*t + 2) + b;
}; };
double Tween::EaseInSine(double t, double d, double b, double c) double Tween::EaseInSine(double t, double d, double b, double c)
{ {
return -c * cos(t/d * (M_PI/2)) + c + b; return -c * cos(t/d * (M_PI/2)) + c + b;
}; };
double Tween::EaseOutSine(double t, double d, double b, double c) double Tween::EaseOutSine(double t, double d, double b, double c)
{ {
return c * sin(t/d * (M_PI/2)) + b; return c * sin(t/d * (M_PI/2)) + b;
}; };
double Tween::EaseInOutSine(double t, double d, double b, double c) double Tween::EaseInOutSine(double t, double d, double b, double c)
{ {
return -c/2 * (cos( M_PI*t/d) - 1) + b; return -c/2 * (cos( M_PI*t/d) - 1) + b;
}; };
double Tween::EaseInExponential(double t, double d, double b, double c) double Tween::EaseInExponential(double t, double d, double b, double c)
{ {
return c * pow( 2, 10 * (t/d - 1) ) + b; return c * pow( 2, 10 * (t/d - 1) ) + b;
}; };
double Tween::EaseOutExponential(double t, double d, double b, double c) double Tween::EaseOutExponential(double t, double d, double b, double c)
{ {
return c * ( - pow( 2, -10 * t/d ) + 1 ) + b; return c * ( - pow( 2, -10 * t/d ) + 1 ) + b;
}; };
double Tween::EaseInOutExponential(double t, double d, double b, double c) double Tween::EaseInOutExponential(double t, double d, double b, double c)
{ {
t /= d/2; t /= d/2;
if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b; if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b;
t--; t--;
return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b; return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b;
}; };
double Tween::EaseInCircular(double t, double d, double b, double c) double Tween::EaseInCircular(double t, double d, double b, double c)
{ {
t /= d; t /= d;
return -c * (sqrt(1 - t*t) - 1) + b; return -c * (sqrt(1 - t*t) - 1) + b;
}; };
double Tween::EaseOutCircular(double t, double d, double b, double c) double Tween::EaseOutCircular(double t, double d, double b, double c)
{ {
t /= d; t /= d;
t--; t--;
return c * sqrt(1 - t*t) + b; return c * sqrt(1 - t*t) + b;
}; };
double Tween::EaseInOutCircular(double t, double d, double b, double c) double Tween::EaseInOutCircular(double t, double d, double b, double c)
{ {
t /= d/2; t /= d/2;
if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b; if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b;
t -= 2; t -= 2;
return c/2 * (sqrt(1 - t*t) + 1) + b; return c/2 * (sqrt(1 - t*t) + 1) + b;
} }
; ;
//todo: sdl requires floats, should the casting be done at this layer? //todo: sdl requires floats, should the casting be done at this layer?
float Tween::GetDuration() const float Tween::GetDuration() const
{ {
return static_cast<float>(Duration); return static_cast<float>(Duration);
} }

View File

@@ -13,43 +13,43 @@ class Tween
{ {
public: public:
Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration); Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration);
float Animate(double elapsedTime); float Animate(double elapsedTime);
static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime); static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime);
static TweenAlgorithm GetTweenType(std::string name); static TweenAlgorithm GetTweenType(std::string name);
static bool GetTweenProperty(std::string name, TweenProperty &property); static bool GetTweenProperty(std::string name, TweenProperty &property);
TweenProperty GetProperty() const; TweenProperty GetProperty() const;
float GetDuration() const; float GetDuration() const;
private: private:
static double EaseInQuadratic(double elapsedTime, double duration, double b, double c); static double EaseInQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuadratic(double elapsedTime, double duration, double b, double c); static double EaseOutQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuadratic(double elapsedTime, double duration, double b, double c); static double EaseInOutQuadratic(double elapsedTime, double duration, double b, double c);
static double EaseInCubic(double elapsedTime, double duration, double b, double c); static double EaseInCubic(double elapsedTime, double duration, double b, double c);
static double EaseOutCubic(double elapsedTime, double duration, double b, double c); static double EaseOutCubic(double elapsedTime, double duration, double b, double c);
static double EaseInOutCubic(double elapsedTime, double duration, double b, double c); static double EaseInOutCubic(double elapsedTime, double duration, double b, double c);
static double EaseInQuartic(double elapsedTime, double duration, double b, double c); static double EaseInQuartic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuartic(double elapsedTime, double duration, double b, double c); static double EaseOutQuartic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuartic(double elapsedTime, double duration, double b, double c); static double EaseInOutQuartic(double elapsedTime, double duration, double b, double c);
static double EaseInQuintic(double elapsedTime, double duration, double b, double c); static double EaseInQuintic(double elapsedTime, double duration, double b, double c);
static double EaseOutQuintic(double elapsedTime, double duration, double b, double c); static double EaseOutQuintic(double elapsedTime, double duration, double b, double c);
static double EaseInOutQuintic(double elapsedTime, double duration, double b, double c); static double EaseInOutQuintic(double elapsedTime, double duration, double b, double c);
static double EaseInSine(double elapsedTime, double duration, double b, double c); static double EaseInSine(double elapsedTime, double duration, double b, double c);
static double EaseOutSine(double elapsedTime, double duration, double b, double c); static double EaseOutSine(double elapsedTime, double duration, double b, double c);
static double EaseInOutSine(double elapsedTime, double duration, double b, double c); static double EaseInOutSine(double elapsedTime, double duration, double b, double c);
static double EaseInExponential(double elapsedTime, double duration, double b, double c); static double EaseInExponential(double elapsedTime, double duration, double b, double c);
static double EaseOutExponential(double elapsedTime, double duration, double b, double c); static double EaseOutExponential(double elapsedTime, double duration, double b, double c);
static double EaseInOutExponential(double elapsedTime, double duration, double b, double c); static double EaseInOutExponential(double elapsedTime, double duration, double b, double c);
static double EaseInCircular(double elapsedTime, double duration, double b, double c); static double EaseInCircular(double elapsedTime, double duration, double b, double c);
static double EaseOutCircular(double elapsedTime, double duration, double b, double c); static double EaseOutCircular(double elapsedTime, double duration, double b, double c);
static double EaseInOutCircular(double elapsedTime, double duration, double b, double c); static double EaseInOutCircular(double elapsedTime, double duration, double b, double c);
static double Linear(double elapsedTime, double duration, double b, double c); static double Linear(double elapsedTime, double duration, double b, double c);
static std::map<std::string, TweenAlgorithm> TweenTypeMap; static std::map<std::string, TweenAlgorithm> TweenTypeMap;
static std::map<std::string, TweenProperty> TweenPropertyMap; static std::map<std::string, TweenProperty> TweenPropertyMap;
TweenProperty Property; TweenProperty Property;
TweenAlgorithm Type; TweenAlgorithm Type;
double Start; double Start;
double End; double End;
double Duration; double Duration;
}; };

View File

@@ -1,45 +1,45 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
enum TweenAlgorithm enum TweenAlgorithm
{ {
LINEAR, LINEAR,
EASE_IN_QUADRATIC, EASE_IN_QUADRATIC,
EASE_OUT_QUADRATIC, EASE_OUT_QUADRATIC,
EASE_INOUT_QUADRATIC, EASE_INOUT_QUADRATIC,
EASE_IN_CUBIC, EASE_IN_CUBIC,
EASE_OUT_CUBIC, EASE_OUT_CUBIC,
EASE_INOUT_CUBIC, EASE_INOUT_CUBIC,
EASE_IN_QUARTIC, EASE_IN_QUARTIC,
EASE_OUT_QUARTIC, EASE_OUT_QUARTIC,
EASE_INOUT_QUARTIC, EASE_INOUT_QUARTIC,
EASE_IN_QUINTIC, EASE_IN_QUINTIC,
EASE_OUT_QUINTIC, EASE_OUT_QUINTIC,
EASE_INOUT_QUINTIC, EASE_INOUT_QUINTIC,
EASE_IN_SINE, EASE_IN_SINE,
EASE_OUT_SINE, EASE_OUT_SINE,
EASE_INOUT_SINE, EASE_INOUT_SINE,
EASE_IN_EXPONENTIAL, EASE_IN_EXPONENTIAL,
EASE_OUT_EXPONENTIAL, EASE_OUT_EXPONENTIAL,
EASE_INOUT_EXPONENTIAL, EASE_INOUT_EXPONENTIAL,
EASE_IN_CIRCULAR, EASE_IN_CIRCULAR,
EASE_OUT_CIRCULAR, EASE_OUT_CIRCULAR,
EASE_INOUT_CIRCULAR, EASE_INOUT_CIRCULAR,
}; };
enum TweenProperty enum TweenProperty
{ {
TWEEN_PROPERTY_HEIGHT, TWEEN_PROPERTY_HEIGHT,
TWEEN_PROPERTY_WIDTH, TWEEN_PROPERTY_WIDTH,
TWEEN_PROPERTY_ANGLE, TWEEN_PROPERTY_ANGLE,
TWEEN_PROPERTY_TRANSPARENCY, TWEEN_PROPERTY_TRANSPARENCY,
TWEEN_PROPERTY_X, TWEEN_PROPERTY_X,
TWEEN_PROPERTY_Y, TWEEN_PROPERTY_Y,
TWEEN_PROPERTY_X_ORIGIN, TWEEN_PROPERTY_X_ORIGIN,
TWEEN_PROPERTY_Y_ORIGIN, TWEEN_PROPERTY_Y_ORIGIN,
TWEEN_PROPERTY_X_OFFSET, TWEEN_PROPERTY_X_OFFSET,
TWEEN_PROPERTY_Y_OFFSET, TWEEN_PROPERTY_Y_OFFSET,
TWEEN_PROPERTY_FONT_SIZE TWEEN_PROPERTY_FONT_SIZE
}; };

View File

@@ -8,34 +8,34 @@
Component::Component() Component::Component()
{ {
OnEnterTweens = NULL; OnEnterTweens = NULL;
OnExitTweens = NULL; OnExitTweens = NULL;
OnIdleTweens = NULL; OnIdleTweens = NULL;
OnHighlightEnterTweens = NULL; OnHighlightEnterTweens = NULL;
OnHighlightExitTweens = NULL; OnHighlightExitTweens = NULL;
SelectedItem = NULL; SelectedItem = NULL;
NewItemSelectedSinceEnter = false; NewItemSelectedSinceEnter = false;
FreeGraphicsMemory(); FreeGraphicsMemory();
} }
Component::~Component() Component::~Component()
{ {
FreeGraphicsMemory(); FreeGraphicsMemory();
} }
void Component::FreeGraphicsMemory() void Component::FreeGraphicsMemory()
{ {
CurrentAnimationState = HIDDEN; CurrentAnimationState = HIDDEN;
EnterRequested = false; EnterRequested = false;
ExitRequested = false; ExitRequested = false;
NewItemSelected = false; NewItemSelected = false;
HighlightExitComplete = false; HighlightExitComplete = false;
CurrentTweens = NULL; CurrentTweens = NULL;
CurrentTweenIndex = 0; CurrentTweenIndex = 0;
CurrentTweenComplete = false; CurrentTweenComplete = false;
ElapsedTweenTime =0; ElapsedTweenTime =0;
ScrollActive = false; ScrollActive = false;
} }
void Component::AllocateGraphicsMemory() void Component::AllocateGraphicsMemory()
{ {
@@ -43,240 +43,240 @@ void Component::AllocateGraphicsMemory()
void Component::TriggerEnterEvent() void Component::TriggerEnterEvent()
{ {
EnterRequested = true; EnterRequested = true;
} }
void Component::TriggerExitEvent() void Component::TriggerExitEvent()
{ {
ExitRequested = true; ExitRequested = true;
} }
void Component::TriggerHighlightEvent(Item *selectedItem) void Component::TriggerHighlightEvent(Item *selectedItem)
{ {
NewItemSelected = true; NewItemSelected = true;
this->SelectedItem = selectedItem; this->SelectedItem = selectedItem;
} }
bool Component::IsIdle() bool Component::IsIdle()
{ {
return (CurrentAnimationState == IDLE); return (CurrentAnimationState == IDLE);
} }
bool Component::IsHidden() bool Component::IsHidden()
{ {
return (CurrentAnimationState == HIDDEN); return (CurrentAnimationState == HIDDEN);
} }
bool Component::IsWaiting() bool Component::IsWaiting()
{ {
return (CurrentAnimationState == HIGHLIGHT_WAIT); return (CurrentAnimationState == HIGHLIGHT_WAIT);
} }
void Component::Update(float dt) void Component::Update(float dt)
{ {
ElapsedTweenTime += dt; ElapsedTweenTime += dt;
HighlightExitComplete = false; HighlightExitComplete = false;
if(IsHidden() || IsWaiting() || (IsIdle() && ExitRequested)) if(IsHidden() || IsWaiting() || (IsIdle() && ExitRequested))
{ {
CurrentTweenComplete = true; CurrentTweenComplete = true;
} }
if(CurrentTweenComplete) if(CurrentTweenComplete)
{ {
CurrentTweens = NULL; CurrentTweens = NULL;
// There was no request to override our state path. Continue on as normal. // There was no request to override our state path. Continue on as normal.
switch(CurrentAnimationState) switch(CurrentAnimationState)
{ {
case ENTER: case ENTER:
CurrentTweens = OnHighlightEnterTweens; CurrentTweens = OnHighlightEnterTweens;
CurrentAnimationState = HIGHLIGHT_ENTER; CurrentAnimationState = HIGHLIGHT_ENTER;
break; break;
case EXIT: case EXIT:
CurrentTweens = NULL; CurrentTweens = NULL;
CurrentAnimationState = HIDDEN; CurrentAnimationState = HIDDEN;
break; break;
case HIGHLIGHT_ENTER: case HIGHLIGHT_ENTER:
CurrentTweens = OnIdleTweens; CurrentTweens = OnIdleTweens;
CurrentAnimationState = IDLE; CurrentAnimationState = IDLE;
break; break;
case IDLE: case IDLE:
// prevent us from automatically jumping to the exit tween upon enter // prevent us from automatically jumping to the exit tween upon enter
if(EnterRequested) if(EnterRequested)
{ {
EnterRequested = false; EnterRequested = false;
NewItemSelected = false; NewItemSelected = false;
} }
else if(IsScrollActive() || NewItemSelected || ExitRequested) else if(IsScrollActive() || NewItemSelected || ExitRequested)
{ {
CurrentTweens = OnHighlightExitTweens; CurrentTweens = OnHighlightExitTweens;
CurrentAnimationState = HIGHLIGHT_EXIT; CurrentAnimationState = HIGHLIGHT_EXIT;
} }
else else
{ {
CurrentTweens = OnIdleTweens; CurrentTweens = OnIdleTweens;
CurrentAnimationState = IDLE; CurrentAnimationState = IDLE;
} }
break; break;
case HIGHLIGHT_EXIT: case HIGHLIGHT_EXIT:
// intentionally break down // intentionally break down
case HIGHLIGHT_WAIT: case HIGHLIGHT_WAIT:
if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_WAIT)) if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_WAIT))
{ {
CurrentTweens = OnHighlightExitTweens; CurrentTweens = OnHighlightExitTweens;
CurrentAnimationState = HIGHLIGHT_EXIT; CurrentAnimationState = HIGHLIGHT_EXIT;
} }
else if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_EXIT)) else if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_EXIT))
{ {
CurrentTweens = OnExitTweens; CurrentTweens = OnExitTweens;
CurrentAnimationState = EXIT; CurrentAnimationState = EXIT;
ExitRequested = false; ExitRequested = false;
} }
else if(IsScrollActive()) else if(IsScrollActive())
{ {
CurrentTweens = NULL; CurrentTweens = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT; CurrentAnimationState = HIGHLIGHT_WAIT;
} }
else if(NewItemSelected) else if(NewItemSelected)
{ {
CurrentTweens = OnHighlightEnterTweens; CurrentTweens = OnHighlightEnterTweens;
CurrentAnimationState = HIGHLIGHT_ENTER; CurrentAnimationState = HIGHLIGHT_ENTER;
HighlightExitComplete = true; HighlightExitComplete = true;
NewItemSelected = false; NewItemSelected = false;
} }
else else
{ {
CurrentTweens = NULL; CurrentTweens = NULL;
CurrentAnimationState = HIGHLIGHT_WAIT; CurrentAnimationState = HIGHLIGHT_WAIT;
} }
break; break;
case HIDDEN: case HIDDEN:
if(EnterRequested || ExitRequested) if(EnterRequested || ExitRequested)
{ {
CurrentTweens = OnEnterTweens; CurrentTweens = OnEnterTweens;
CurrentAnimationState = ENTER; CurrentAnimationState = ENTER;
} }
else else
{ {
CurrentTweens = NULL; CurrentTweens = NULL;
CurrentAnimationState = HIDDEN; CurrentAnimationState = HIDDEN;
} }
} }
CurrentTweenIndex = 0; CurrentTweenIndex = 0;
CurrentTweenComplete = false; CurrentTweenComplete = false;
ElapsedTweenTime = 0; ElapsedTweenTime = 0;
} }
CurrentTweenComplete = Animate(IsIdle()); CurrentTweenComplete = Animate(IsIdle());
} }
bool Component::Animate(bool loop) bool Component::Animate(bool loop)
{ {
bool completeDone = false; bool completeDone = false;
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size())
{ {
completeDone = true; completeDone = true;
} }
else if(CurrentTweens) else if(CurrentTweens)
{ {
bool currentDone = true; bool currentDone = true;
std::vector<Tween *> *tweenSet = CurrentTweens->at(CurrentTweenIndex); std::vector<Tween *> *tweenSet = CurrentTweens->at(CurrentTweenIndex);
for(unsigned int i = 0; i < tweenSet->size(); i++) for(unsigned int i = 0; i < tweenSet->size(); i++)
{ {
Tween *tween = tweenSet->at(i); Tween *tween = tweenSet->at(i);
float elapsedTime = ElapsedTweenTime; float elapsedTime = ElapsedTweenTime;
//todo: too many levels of nesting //todo: too many levels of nesting
if(elapsedTime < tween->GetDuration()) if(elapsedTime < tween->GetDuration())
{ {
currentDone = false; currentDone = false;
} }
else else
{ {
elapsedTime = tween->GetDuration(); elapsedTime = tween->GetDuration();
} }
float value = tween->Animate(elapsedTime); float value = tween->Animate(elapsedTime);
switch(tween->GetProperty()) switch(tween->GetProperty())
{ {
case TWEEN_PROPERTY_X: case TWEEN_PROPERTY_X:
GetBaseViewInfo()->SetX(value); GetBaseViewInfo()->SetX(value);
break; break;
case TWEEN_PROPERTY_Y: case TWEEN_PROPERTY_Y:
GetBaseViewInfo()->SetY(value); GetBaseViewInfo()->SetY(value);
break; break;
case TWEEN_PROPERTY_HEIGHT: case TWEEN_PROPERTY_HEIGHT:
GetBaseViewInfo()->SetHeight(value); GetBaseViewInfo()->SetHeight(value);
break; break;
case TWEEN_PROPERTY_WIDTH: case TWEEN_PROPERTY_WIDTH:
GetBaseViewInfo()->SetWidth(value); GetBaseViewInfo()->SetWidth(value);
break; break;
case TWEEN_PROPERTY_ANGLE: case TWEEN_PROPERTY_ANGLE:
GetBaseViewInfo()->SetAngle(value); GetBaseViewInfo()->SetAngle(value);
break; break;
case TWEEN_PROPERTY_TRANSPARENCY: case TWEEN_PROPERTY_TRANSPARENCY:
GetBaseViewInfo()->SetTransparency(value); GetBaseViewInfo()->SetTransparency(value);
break; break;
case TWEEN_PROPERTY_X_ORIGIN: case TWEEN_PROPERTY_X_ORIGIN:
GetBaseViewInfo()->SetXOrigin(value); GetBaseViewInfo()->SetXOrigin(value);
break; break;
case TWEEN_PROPERTY_Y_ORIGIN: case TWEEN_PROPERTY_Y_ORIGIN:
GetBaseViewInfo()->SetYOrigin(value); GetBaseViewInfo()->SetYOrigin(value);
break; break;
case TWEEN_PROPERTY_X_OFFSET: case TWEEN_PROPERTY_X_OFFSET:
GetBaseViewInfo()->SetXOffset(value); GetBaseViewInfo()->SetXOffset(value);
break; break;
case TWEEN_PROPERTY_Y_OFFSET: case TWEEN_PROPERTY_Y_OFFSET:
GetBaseViewInfo()->SetYOffset(value); GetBaseViewInfo()->SetYOffset(value);
break; break;
case TWEEN_PROPERTY_FONT_SIZE: case TWEEN_PROPERTY_FONT_SIZE:
GetBaseViewInfo()->SetFontSize(value); GetBaseViewInfo()->SetFontSize(value);
break; break;
} }
} }
if(currentDone) if(currentDone)
{ {
CurrentTweenIndex++; CurrentTweenIndex++;
ElapsedTweenTime = 0; ElapsedTweenTime = 0;
} }
} }
if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size())
{ {
if(loop) if(loop)
{ {
CurrentTweenIndex = 0; CurrentTweenIndex = 0;
} }
completeDone = true; completeDone = true;
} }
return completeDone; return completeDone;
} }

View File

@@ -13,110 +13,110 @@
class Component class Component
{ {
public: public:
Component(); Component();
virtual ~Component(); virtual ~Component();
virtual void FreeGraphicsMemory(); virtual void FreeGraphicsMemory();
virtual void AllocateGraphicsMemory(); virtual void AllocateGraphicsMemory();
virtual void LaunchEnter() {} virtual void LaunchEnter() {}
virtual void LaunchExit() {} virtual void LaunchExit() {}
void TriggerEnterEvent(); void TriggerEnterEvent();
void TriggerExitEvent(); void TriggerExitEvent();
void TriggerHighlightEvent(Item *selectedItem); void TriggerHighlightEvent(Item *selectedItem);
bool IsIdle(); bool IsIdle();
bool IsHidden(); bool IsHidden();
bool IsWaiting(); bool IsWaiting();
typedef std::vector<std::vector<Tween *> *> TweenSets; typedef std::vector<std::vector<Tween *> *> TweenSets;
void SetOnEnterTweens(TweenSets *tweens) void SetOnEnterTweens(TweenSets *tweens)
{ {
this->OnEnterTweens = tweens; this->OnEnterTweens = tweens;
} }
void SetOnExitTweens(TweenSets *tweens) void SetOnExitTweens(TweenSets *tweens)
{ {
this->OnExitTweens = tweens; this->OnExitTweens = tweens;
} }
void SetOnIdleTweens(TweenSets *tweens) void SetOnIdleTweens(TweenSets *tweens)
{ {
this->OnIdleTweens = tweens; this->OnIdleTweens = tweens;
} }
void SetOnHighlightEnterTweens(TweenSets *tweens) void SetOnHighlightEnterTweens(TweenSets *tweens)
{ {
this->OnHighlightEnterTweens = tweens; this->OnHighlightEnterTweens = tweens;
} }
void SetOnHighlightExitTweens(TweenSets *tweens) void SetOnHighlightExitTweens(TweenSets *tweens)
{ {
this->OnHighlightExitTweens = tweens; this->OnHighlightExitTweens = tweens;
} }
virtual void Update(float dt); virtual void Update(float dt);
virtual void Draw() = 0; virtual void Draw() = 0;
ViewInfo *GetBaseViewInfo() ViewInfo *GetBaseViewInfo()
{ {
return &BaseViewInfo; return &BaseViewInfo;
} }
void UpdateBaseViewInfo(ViewInfo &info) void UpdateBaseViewInfo(ViewInfo &info)
{ {
BaseViewInfo = info; BaseViewInfo = info;
} }
bool IsScrollActive() const bool IsScrollActive() const
{ {
return ScrollActive; return ScrollActive;
} }
void SetScrollActive(bool scrollActive) void SetScrollActive(bool scrollActive)
{ {
ScrollActive = scrollActive; ScrollActive = scrollActive;
} }
protected: protected:
Item *GetSelectedItem() Item *GetSelectedItem()
{ {
return SelectedItem; return SelectedItem;
} }
enum AnimationState enum AnimationState
{ {
IDLE, IDLE,
ENTER, ENTER,
HIGHLIGHT_EXIT, HIGHLIGHT_EXIT,
HIGHLIGHT_WAIT, HIGHLIGHT_WAIT,
HIGHLIGHT_ENTER, HIGHLIGHT_ENTER,
EXIT, EXIT,
HIDDEN HIDDEN
}; };
AnimationState CurrentAnimationState; AnimationState CurrentAnimationState;
bool EnterRequested; bool EnterRequested;
bool ExitRequested; bool ExitRequested;
bool NewItemSelected; bool NewItemSelected;
bool HighlightExitComplete; bool HighlightExitComplete;
bool NewItemSelectedSinceEnter; bool NewItemSelectedSinceEnter;
private: private:
bool Animate(bool loop); bool Animate(bool loop);
bool IsTweenSequencingComplete(); bool IsTweenSequencingComplete();
void ResetTweenSequence(std::vector<ViewInfo *> *tweens); void ResetTweenSequence(std::vector<ViewInfo *> *tweens);
TweenSets *OnEnterTweens; TweenSets *OnEnterTweens;
TweenSets *OnExitTweens; TweenSets *OnExitTweens;
TweenSets *OnIdleTweens; TweenSets *OnIdleTweens;
TweenSets *OnHighlightEnterTweens; TweenSets *OnHighlightEnterTweens;
TweenSets *OnHighlightExitTweens; TweenSets *OnHighlightExitTweens;
TweenSets *CurrentTweens; TweenSets *CurrentTweens;
unsigned int CurrentTweenIndex; unsigned int CurrentTweenIndex;
bool CurrentTweenComplete; bool CurrentTweenComplete;
ViewInfo BaseViewInfo; ViewInfo BaseViewInfo;
float ElapsedTweenTime; float ElapsedTweenTime;
Tween *TweenInst; Tween *TweenInst;
Item *SelectedItem; Item *SelectedItem;
bool ScrollActive; bool ScrollActive;
}; };

View File

@@ -8,68 +8,68 @@
#include <SDL2/SDL_image.h> #include <SDL2/SDL_image.h>
Image::Image(std::string file, float scaleX, float scaleY) Image::Image(std::string file, float scaleX, float scaleY)
: Texture(NULL) : Texture(NULL)
, File(file) , File(file)
, ScaleX(scaleX) , ScaleX(scaleX)
, ScaleY(scaleY) , ScaleY(scaleY)
{ {
AllocateGraphicsMemory(); AllocateGraphicsMemory();
} }
Image::~Image() Image::~Image()
{ {
FreeGraphicsMemory(); FreeGraphicsMemory();
} }
void Image::FreeGraphicsMemory() void Image::FreeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::FreeGraphicsMemory();
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
if (Texture != NULL) if (Texture != NULL)
{ {
SDL_DestroyTexture(Texture); SDL_DestroyTexture(Texture);
Texture = NULL; Texture = NULL;
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
void Image::AllocateGraphicsMemory() void Image::AllocateGraphicsMemory()
{ {
int width; int width;
int height; int height;
Component::AllocateGraphicsMemory(); Component::AllocateGraphicsMemory();
if(!Texture) if(!Texture)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str()); Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str());
if (Texture != NULL) if (Texture != NULL)
{ {
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND);
SDL_QueryTexture(Texture, NULL, NULL, &width, &height); SDL_QueryTexture(Texture, NULL, NULL, &width, &height);
GetBaseViewInfo()->SetImageWidth(width * ScaleX); GetBaseViewInfo()->SetImageWidth(width * ScaleX);
GetBaseViewInfo()->SetImageHeight(height * ScaleY); GetBaseViewInfo()->SetImageHeight(height * ScaleY);
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
} }
void Image::Draw() void Image::Draw()
{ {
if(Texture) if(Texture)
{ {
ViewInfo *info = GetBaseViewInfo(); ViewInfo *info = GetBaseViewInfo();
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(info->GetXRelativeToOrigin()); rect.x = static_cast<int>(info->GetXRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin()); rect.y = static_cast<int>(info->GetYRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight()); rect.h = static_cast<int>(info->GetHeight());
rect.w = static_cast<int>(info->GetWidth()); rect.w = static_cast<int>(info->GetWidth());
SDL::RenderCopy(Texture, static_cast<char>((info->GetTransparency() * 255)), NULL, &rect, info->GetAngle()); SDL::RenderCopy(Texture, static_cast<char>((info->GetTransparency() * 255)), NULL, &rect, info->GetAngle());
} }
} }

View File

@@ -10,15 +10,15 @@
class Image : public Component class Image : public Component
{ {
public: public:
Image(std::string file, float scaleX, float scaleY); Image(std::string file, float scaleX, float scaleY);
virtual ~Image(); virtual ~Image();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void Draw(); void Draw();
protected: protected:
SDL_Texture *Texture; SDL_Texture *Texture;
std::string File; std::string File;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
}; };

View File

@@ -8,23 +8,23 @@
Image * ImageBuilder::CreateImage(std::string path, std::string name, float scaleX, float scaleY) Image * ImageBuilder::CreateImage(std::string path, std::string name, float scaleX, float scaleY)
{ {
Image *image = NULL; Image *image = NULL;
std::vector<std::string> extensions; std::vector<std::string> extensions;
extensions.push_back("png"); extensions.push_back("png");
extensions.push_back("PNG"); extensions.push_back("PNG");
extensions.push_back("jpg"); extensions.push_back("jpg");
extensions.push_back("JPG"); extensions.push_back("JPG");
extensions.push_back("jpeg"); extensions.push_back("jpeg");
extensions.push_back("JPEG"); extensions.push_back("JPEG");
std::string prefix = path + "/" + name; std::string prefix = path + "/" + name;
std::string file; std::string file;
if(Utils::FindMatchingFile(prefix, extensions, file)) if(Utils::FindMatchingFile(prefix, extensions, file))
{ {
image = new Image(file, scaleX, scaleY); image = new Image(file, scaleX, scaleY);
} }
return image; return image;
} }

View File

@@ -11,5 +11,5 @@
class ImageBuilder class ImageBuilder
{ {
public: public:
Image * CreateImage(std::string path, std::string name, float scaleX, float scaleY); Image * CreateImage(std::string path, std::string name, float scaleX, float scaleY);
}; };

View File

@@ -15,158 +15,158 @@
#include <iostream> #include <iostream>
ReloadableMedia::ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY) ReloadableMedia::ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY)
: LoadedComponent(NULL) : LoadedComponent(NULL)
, ImagePath(imagePath) , ImagePath(imagePath)
, VideoPath(videoPath) , VideoPath(videoPath)
, ReloadRequested(false) , ReloadRequested(false)
, FirstLoad(true) , FirstLoad(true)
, IsVideo(isVideo) , IsVideo(isVideo)
, ScaleX(scaleX) , ScaleX(scaleX)
, ScaleY(scaleY) , ScaleY(scaleY)
{ {
AllocateGraphicsMemory(); AllocateGraphicsMemory();
} }
ReloadableMedia::~ReloadableMedia() ReloadableMedia::~ReloadableMedia()
{ {
if (LoadedComponent != NULL) if (LoadedComponent != NULL)
{ {
delete LoadedComponent; delete LoadedComponent;
} }
} }
void ReloadableMedia::Update(float dt) void ReloadableMedia::Update(float dt)
{ {
if(NewItemSelected) if(NewItemSelected)
{ {
ReloadRequested = true; ReloadRequested = true;
} }
// wait for the right moment to reload the image // wait for the right moment to reload the image
if (ReloadRequested && (HighlightExitComplete || FirstLoad)) if (ReloadRequested && (HighlightExitComplete || FirstLoad))
{ {
ReloadTexture(); ReloadTexture();
ReloadRequested = false; ReloadRequested = false;
FirstLoad = false; FirstLoad = false;
} }
if(LoadedComponent) if(LoadedComponent)
{ {
LoadedComponent->Update(dt); LoadedComponent->Update(dt);
} }
// needs to be ran at the end to prevent the NewItemSelected flag from being detected // needs to be ran at the end to prevent the NewItemSelected flag from being detected
Component::Update(dt); Component::Update(dt);
} }
void ReloadableMedia::AllocateGraphicsMemory() void ReloadableMedia::AllocateGraphicsMemory()
{ {
FirstLoad = true; FirstLoad = true;
if(LoadedComponent) if(LoadedComponent)
{ {
LoadedComponent->AllocateGraphicsMemory(); LoadedComponent->AllocateGraphicsMemory();
} }
// NOTICE! needs to be done last to prevent flags from being missed // NOTICE! needs to be done last to prevent flags from being missed
Component::AllocateGraphicsMemory(); Component::AllocateGraphicsMemory();
} }
void ReloadableMedia::LaunchEnter() void ReloadableMedia::LaunchEnter()
{ {
if(LoadedComponent) if(LoadedComponent)
{ {
LoadedComponent->LaunchEnter(); LoadedComponent->LaunchEnter();
} }
} }
void ReloadableMedia::LaunchExit() void ReloadableMedia::LaunchExit()
{ {
if(LoadedComponent) if(LoadedComponent)
{ {
LoadedComponent->LaunchExit(); LoadedComponent->LaunchExit();
} }
} }
void ReloadableMedia::FreeGraphicsMemory() void ReloadableMedia::FreeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::FreeGraphicsMemory();
if(LoadedComponent) if(LoadedComponent)
{ {
LoadedComponent->FreeGraphicsMemory(); LoadedComponent->FreeGraphicsMemory();
} }
} }
void ReloadableMedia::ReloadTexture() void ReloadableMedia::ReloadTexture()
{ {
bool found = false; bool found = false;
if(LoadedComponent) if(LoadedComponent)
{ {
delete LoadedComponent; delete LoadedComponent;
LoadedComponent = NULL; LoadedComponent = NULL;
} }
Item *selectedItem = GetSelectedItem(); Item *selectedItem = GetSelectedItem();
if (selectedItem != NULL) if (selectedItem != NULL)
{ {
if(IsVideo) if(IsVideo)
{ {
std::vector<std::string> names; std::vector<std::string> names;
names.push_back(selectedItem->GetName()); names.push_back(selectedItem->GetName());
if(selectedItem->GetCloneOf().length() > 0) if(selectedItem->GetCloneOf().length() > 0)
{
names.push_back(selectedItem->GetCloneOf());
}
for(unsigned int n = 0; n < names.size() && !found; ++n)
{
std::string filePrefix;
filePrefix.append(VideoPath);
filePrefix.append("/");
filePrefix.append(names[n]);
std::string file;
VideoBuilder videoBuild;
LoadedComponent = videoBuild.CreateVideo(VideoPath, names[n], ScaleX, ScaleY);
if(LoadedComponent)
{ {
LoadedComponent->AllocateGraphicsMemory(); names.push_back(selectedItem->GetCloneOf());
found = true;
} }
}
}
if(!LoadedComponent) for(unsigned int n = 0; n < names.size() && !found; ++n)
{ {
ImageBuilder imageBuild; std::string filePrefix;
LoadedComponent = imageBuild.CreateImage(ImagePath, selectedItem->GetFullTitle(), ScaleX, ScaleY); filePrefix.append(VideoPath);
filePrefix.append("/");
filePrefix.append(names[n]);
if (LoadedComponent != NULL) std::string file;
{
LoadedComponent->AllocateGraphicsMemory(); VideoBuilder videoBuild;
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); LoadedComponent = videoBuild.CreateVideo(VideoPath, names[n], ScaleX, ScaleY);
}
} if(LoadedComponent)
} {
LoadedComponent->AllocateGraphicsMemory();
found = true;
}
}
}
if(!LoadedComponent)
{
ImageBuilder imageBuild;
LoadedComponent = imageBuild.CreateImage(ImagePath, selectedItem->GetFullTitle(), ScaleX, ScaleY);
if (LoadedComponent != NULL)
{
LoadedComponent->AllocateGraphicsMemory();
GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
}
}
}
} }
void ReloadableMedia::Draw() void ReloadableMedia::Draw()
{ {
ViewInfo *info = GetBaseViewInfo(); ViewInfo *info = GetBaseViewInfo();
if(LoadedComponent) if(LoadedComponent)
{ {
info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight());
info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth());
LoadedComponent->UpdateBaseViewInfo(*info); LoadedComponent->UpdateBaseViewInfo(*info);
LoadedComponent->Draw(); LoadedComponent->Draw();
} }
} }

View File

@@ -14,25 +14,25 @@ class Image;
class ReloadableMedia : public Component class ReloadableMedia : public Component
{ {
public: public:
ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY); ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY);
virtual ~ReloadableMedia(); virtual ~ReloadableMedia();
void Update(float dt); void Update(float dt);
void Draw(); void Draw();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void LaunchEnter(); void LaunchEnter();
void LaunchExit(); void LaunchExit();
private: private:
void ReloadTexture(); void ReloadTexture();
Component *LoadedComponent; Component *LoadedComponent;
std::string ImagePath; std::string ImagePath;
std::string VideoPath; std::string VideoPath;
bool ReloadRequested; bool ReloadRequested;
bool FirstLoad; bool FirstLoad;
IVideo *VideoInst; IVideo *VideoInst;
bool IsVideo; bool IsVideo;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
}; };

View File

@@ -11,80 +11,80 @@
#include <iostream> #include <iostream>
ReloadableText::ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collection, float scaleX, float scaleY) ReloadableText::ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collection, float scaleX, float scaleY)
: ImageInst(NULL) : ImageInst(NULL)
, LayoutKey(layoutKey) , LayoutKey(layoutKey)
, Collection(collection) , Collection(collection)
, ReloadRequested(false) , ReloadRequested(false)
, FirstLoad(true) , FirstLoad(true)
, FontInst(font) , FontInst(font)
, FontColor(color) , FontColor(color)
, ScaleX(scaleX) , ScaleX(scaleX)
, ScaleY(scaleY) , ScaleY(scaleY)
{ {
Type = TextTypeUnknown; Type = TextTypeUnknown;
if(type == "numberButtons") if(type == "numberButtons")
{ {
Type = TextTypeNumberButtons; Type = TextTypeNumberButtons;
} }
else if(type == "numberPlayers") else if(type == "numberPlayers")
{ {
Type = TextTypeNumberPlayers; Type = TextTypeNumberPlayers;
} }
else if(type == "year") else if(type == "year")
{ {
Type = TextTypeYear; Type = TextTypeYear;
} }
else if(type == "title") else if(type == "title")
{ {
Type = TextTypeTitle; Type = TextTypeTitle;
} }
else if(type == "manufacturer") else if(type == "manufacturer")
{ {
Type = TextTypeManufacturer; Type = TextTypeManufacturer;
} }
AllocateGraphicsMemory(); AllocateGraphicsMemory();
} }
ReloadableText::~ReloadableText() ReloadableText::~ReloadableText()
{ {
if (ImageInst != NULL) if (ImageInst != NULL)
{ {
delete ImageInst; delete ImageInst;
} }
} }
void ReloadableText::Update(float dt) void ReloadableText::Update(float dt)
{ {
if(NewItemSelected) if(NewItemSelected)
{ {
ReloadRequested = true; ReloadRequested = true;
} }
// wait for the right moment to reload the image // wait for the right moment to reload the image
if (ReloadRequested && (HighlightExitComplete || FirstLoad)) if (ReloadRequested && (HighlightExitComplete || FirstLoad))
{ {
ReloadTexture(); ReloadTexture();
ReloadRequested = false; ReloadRequested = false;
FirstLoad = false; FirstLoad = false;
} }
// needs to be ran at the end to prevent the NewItemSelected flag from being detected // needs to be ran at the end to prevent the NewItemSelected flag from being detected
Component::Update(dt); Component::Update(dt);
} }
void ReloadableText::AllocateGraphicsMemory() void ReloadableText::AllocateGraphicsMemory()
{ {
FirstLoad = true; FirstLoad = true;
ReloadTexture(); ReloadTexture();
// NOTICE! needs to be done last to prevent flags from being missed // NOTICE! needs to be done last to prevent flags from being missed
Component::AllocateGraphicsMemory(); Component::AllocateGraphicsMemory();
} }
void ReloadableText::LaunchEnter() void ReloadableText::LaunchEnter()
@@ -97,61 +97,61 @@ void ReloadableText::LaunchExit()
void ReloadableText::FreeGraphicsMemory() void ReloadableText::FreeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::FreeGraphicsMemory();
if (ImageInst != NULL) if (ImageInst != NULL)
{ {
delete ImageInst; delete ImageInst;
ImageInst = NULL; ImageInst = NULL;
} }
} }
void ReloadableText::ReloadTexture() void ReloadableText::ReloadTexture()
{ {
if (ImageInst != NULL) if (ImageInst != NULL)
{ {
delete ImageInst; delete ImageInst;
ImageInst = NULL; ImageInst = NULL;
} }
Item *selectedItem = GetSelectedItem(); Item *selectedItem = GetSelectedItem();
if (selectedItem != NULL) if (selectedItem != NULL)
{ {
std::stringstream ss; std::stringstream ss;
std::string text; std::string text;
switch(Type) switch(Type)
{ {
case TextTypeNumberButtons: case TextTypeNumberButtons:
ss << selectedItem->GetNumberButtons(); ss << selectedItem->GetNumberButtons();
break; break;
case TextTypeNumberPlayers: case TextTypeNumberPlayers:
ss << selectedItem->GetNumberPlayers(); ss << selectedItem->GetNumberPlayers();
break; break;
case TextTypeYear: case TextTypeYear:
ss << selectedItem->GetYear(); ss << selectedItem->GetYear();
break; break;
case TextTypeTitle: case TextTypeTitle:
ss << selectedItem->GetTitle(); ss << selectedItem->GetTitle();
break; break;
case TextTypeManufacturer: case TextTypeManufacturer:
ss << selectedItem->GetManufacturer(); ss << selectedItem->GetManufacturer();
break; break;
default: default:
break; break;
} }
ImageInst = new Text(ss.str(), FontInst, FontColor, ScaleX, ScaleY); ImageInst = new Text(ss.str(), FontInst, FontColor, ScaleX, ScaleY);
} }
} }
void ReloadableText::Draw() void ReloadableText::Draw()
{ {
ViewInfo *info = GetBaseViewInfo(); ViewInfo *info = GetBaseViewInfo();
if(ImageInst) if(ImageInst)
{ {
ImageInst->UpdateBaseViewInfo(*info); ImageInst->UpdateBaseViewInfo(*info);
ImageInst->Draw(); ImageInst->Draw();
} }
} }

View File

@@ -12,37 +12,37 @@
class ReloadableText : public Component class ReloadableText : public Component
{ {
public: public:
ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collectionName, float scaleX, float scaleY); ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collectionName, float scaleX, float scaleY);
virtual ~ReloadableText(); virtual ~ReloadableText();
void Update(float dt); void Update(float dt);
void Draw(); void Draw();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void LaunchEnter(); void LaunchEnter();
void LaunchExit(); void LaunchExit();
private: private:
enum TextType enum TextType
{ {
TextTypeUnknown = 0, TextTypeUnknown = 0,
TextTypeNumberButtons, TextTypeNumberButtons,
TextTypeNumberPlayers, TextTypeNumberPlayers,
TextTypeYear, TextTypeYear,
TextTypeTitle, TextTypeTitle,
TextTypeManufacturer, TextTypeManufacturer,
}; };
void ReloadTexture(); void ReloadTexture();
Text *ImageInst; Text *ImageInst;
TextType Type; TextType Type;
std::string LayoutKey; std::string LayoutKey;
std::string Collection; std::string Collection;
bool ReloadRequested; bool ReloadRequested;
bool FirstLoad; bool FirstLoad;
Font *FontInst; Font *FontInst;
SDL_Color FontColor; SDL_Color FontColor;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -23,83 +23,83 @@ class Font;
class ScrollingList : public Component class ScrollingList : public Component
{ {
public: public:
enum ScrollDirection enum ScrollDirection
{ {
ScrollDirectionBack, ScrollDirectionBack,
ScrollDirectionForward, ScrollDirectionForward,
ScrollDirectionIdle, ScrollDirectionIdle,
}; };
ScrollingList(Configuration *c, float scaleX, float scaleY, Font *font, SDL_Color fontColor, std::string layoutKey, std::string CollectionName, std::string imageType); ScrollingList(Configuration *c, float scaleX, float scaleY, Font *font, SDL_Color fontColor, std::string layoutKey, std::string CollectionName, std::string imageType);
virtual ~ScrollingList(); virtual ~ScrollingList();
void AllocateTexture(ComponentItemBinding *s); void AllocateTexture(ComponentItemBinding *s);
void DeallocateTexture(ComponentItemBinding *s); void DeallocateTexture(ComponentItemBinding *s);
void SetItems(std::vector<ComponentItemBinding *> *spriteList); void SetItems(std::vector<ComponentItemBinding *> *spriteList);
void SetPoints(std::vector<ViewInfo *> *scrollPoints); void SetPoints(std::vector<ViewInfo *> *scrollPoints);
void SetScrollDirection(ScrollDirection direction); void SetScrollDirection(ScrollDirection direction);
void PageUp(); void PageUp();
void PageDown(); void PageDown();
bool IsIdle(); bool IsIdle();
void SetSelectedIndex(int selectedIndex); void SetSelectedIndex(int selectedIndex);
ComponentItemBinding *GetSelectedCollectionItemSprite(); ComponentItemBinding *GetSelectedCollectionItemSprite();
ComponentItemBinding *GetPendingCollectionItemSprite(); ComponentItemBinding *GetPendingCollectionItemSprite();
ComponentItemBinding *GetPendingSelectedCollectionItemSprite(); ComponentItemBinding *GetPendingSelectedCollectionItemSprite();
void AddComponentForNotifications(MenuNotifierInterface *c); void AddComponentForNotifications(MenuNotifierInterface *c);
void RemoveComponentForNotifications(MenuNotifierInterface *c); void RemoveComponentForNotifications(MenuNotifierInterface *c);
std::vector<ComponentItemBinding *> *GetCollectionItemSprites(); std::vector<ComponentItemBinding *> *GetCollectionItemSprites();
void RemoveSelectedItem(); void RemoveSelectedItem();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void Update(float dt); void Update(float dt);
void Draw(); void Draw();
void Draw(unsigned int layer); void Draw(unsigned int layer);
private: private:
void Click(); void Click();
unsigned int GetNextTween(unsigned int currentIndex, std::vector<ViewInfo *> *list); unsigned int GetNextTween(unsigned int currentIndex, std::vector<ViewInfo *> *list);
bool IsScrollChangedStarted; bool IsScrollChangedStarted;
bool IsScrollChangedSignalled; bool IsScrollChangedSignalled;
bool IsScrollChangedComplete; bool IsScrollChangedComplete;
enum ScrollState enum ScrollState
{ {
ScrollStateActive, ScrollStateActive,
ScrollStatePageChange, ScrollStatePageChange,
ScrollStateStopping, ScrollStateStopping,
ScrollStateIdle ScrollStateIdle
}; };
std::vector<ComponentItemBinding *> *SpriteList; std::vector<ComponentItemBinding *> *SpriteList;
std::vector<ViewInfo *> *ScrollPoints; std::vector<ViewInfo *> *ScrollPoints;
std::vector<MenuNotifierInterface *> NotificationComponents; std::vector<MenuNotifierInterface *> NotificationComponents;
float TweenEnterTime; float TweenEnterTime;
unsigned int FirstSpriteIndex; unsigned int FirstSpriteIndex;
unsigned int SelectedSpriteListIndex; unsigned int SelectedSpriteListIndex;
float CurrentAnimateTime; float CurrentAnimateTime;
float ScrollTime; float ScrollTime;
ScrollDirection CurrentScrollDirection; ScrollDirection CurrentScrollDirection;
ScrollDirection RequestedScrollDirection; ScrollDirection RequestedScrollDirection;
ScrollState CurrentScrollState; ScrollState CurrentScrollState;
float ScrollAcceleration; float ScrollAcceleration;
float ScrollVelocity; float ScrollVelocity;
void CircularIncrement(unsigned &index, std::vector<ComponentItemBinding *> *list); void CircularIncrement(unsigned &index, std::vector<ComponentItemBinding *> *list);
void CircularDecrement(unsigned &index, std::vector<ComponentItemBinding *> *list); void CircularDecrement(unsigned &index, std::vector<ComponentItemBinding *> *list);
void CircularIncrement(unsigned &index, std::vector<ViewInfo *> *list); void CircularIncrement(unsigned &index, std::vector<ViewInfo *> *list);
void CircularDecrement(unsigned &index, std::vector<ViewInfo *> *list); void CircularDecrement(unsigned &index, std::vector<ViewInfo *> *list);
void UpdateOffset(float dt); void UpdateOffset(float dt);
std::string Collection; std::string Collection;
Configuration *Config; Configuration *Config;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
Font *FontInst; Font *FontInst;
SDL_Color FontColor; SDL_Color FontColor;
std::string LayoutKey; std::string LayoutKey;
std::string CollectionName; std::string CollectionName;
std::string ImageType; std::string ImageType;
unsigned int MaxLayer; unsigned int MaxLayer;
}; };

View File

@@ -8,96 +8,96 @@
#include <sstream> #include <sstream>
Text::Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY) Text::Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY)
: TextData(text) : TextData(text)
, FontInst(font) , FontInst(font)
, FontColor(fontColor) , FontColor(fontColor)
, ScaleX(scaleX) , ScaleX(scaleX)
, ScaleY(scaleY) , ScaleY(scaleY)
{ {
AllocateGraphicsMemory(); AllocateGraphicsMemory();
} }
Text::~Text() Text::~Text()
{ {
FreeGraphicsMemory(); FreeGraphicsMemory();
} }
void Text::FreeGraphicsMemory() void Text::FreeGraphicsMemory()
{ {
Component::FreeGraphicsMemory(); Component::FreeGraphicsMemory();
} }
void Text::AllocateGraphicsMemory() void Text::AllocateGraphicsMemory()
{ {
//todo: make the font blend color a parameter that is passed in //todo: make the font blend color a parameter that is passed in
Component::AllocateGraphicsMemory(); Component::AllocateGraphicsMemory();
} }
void Text::Draw() void Text::Draw()
{ {
SDL_Texture *t = FontInst->GetTexture(); SDL_Texture *t = FontInst->GetTexture();
ViewInfo *info = GetBaseViewInfo(); ViewInfo *info = GetBaseViewInfo();
float imageHeight = 0; float imageHeight = 0;
float imageWidth = 0; float imageWidth = 0;
// determine image width // determine image width
for(unsigned int i = 0; i < TextData.size(); ++i) for(unsigned int i = 0; i < TextData.size(); ++i)
{ {
Font::GlyphInfo glyph; Font::GlyphInfo glyph;
if(FontInst->GetRect(TextData[i], glyph)) if(FontInst->GetRect(TextData[i], glyph))
{ {
imageWidth += glyph.Advance; imageWidth += glyph.Advance;
imageHeight = (imageHeight >= glyph.Rect.h) ? imageHeight : glyph.Rect.h; imageHeight = (imageHeight >= glyph.Rect.h) ? imageHeight : glyph.Rect.h;
} }
} }
float scale = (float)info->GetFontSize() / (float)imageHeight; float scale = (float)info->GetFontSize() / (float)imageHeight;
float width = info->GetRawWidth(); float width = info->GetRawWidth();
float height = info->GetRawHeight(); float height = info->GetRawHeight();
info->SetWidth(imageWidth*scale); info->SetWidth(imageWidth*scale);
info->SetHeight(imageHeight*scale); info->SetHeight(imageHeight*scale);
float xOrigin = info->GetXRelativeToOrigin(); float xOrigin = info->GetXRelativeToOrigin();
float yOrigin = info->GetYRelativeToOrigin(); float yOrigin = info->GetYRelativeToOrigin();
info->SetWidth(width); info->SetWidth(width);
info->SetHeight(height); info->SetHeight(height);
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(xOrigin); rect.x = static_cast<int>(xOrigin);
for(unsigned int i = 0; i < TextData.size(); ++i) for(unsigned int i = 0; i < TextData.size(); ++i)
{ {
Font::GlyphInfo glyph; Font::GlyphInfo glyph;
if(FontInst->GetRect(TextData[i], glyph) && glyph.Rect.h > 0) if(FontInst->GetRect(TextData[i], glyph) && glyph.Rect.h > 0)
{ {
SDL_Rect charRect = glyph.Rect; SDL_Rect charRect = glyph.Rect;
float h = static_cast<float>(charRect.h * scale); float h = static_cast<float>(charRect.h * scale);
float w = static_cast<float>(charRect.w * scale); float w = static_cast<float>(charRect.w * scale);
rect.h = static_cast<int>(h); rect.h = static_cast<int>(h);
rect.w = static_cast<int>(w); rect.w = static_cast<int>(w);
rect.y = static_cast<int>(yOrigin); rect.y = static_cast<int>(yOrigin);
/* /*
std::stringstream ss; std::stringstream ss;
ss << " cx:" << charRect.x << " cy:" << charRect.y << " cw:" << charRect.w << " ch:" << charRect.h; ss << " cx:" << charRect.x << " cy:" << charRect.y << " cw:" << charRect.w << " ch:" << charRect.h;
ss << " x:" << rect.x << " y:" << rect.y << " w:" << rect.w << " h:" << rect.h; ss << " x:" << rect.x << " y:" << rect.y << " w:" << rect.w << " h:" << rect.h;
Logger::Write(Logger::ZONE_DEBUG, "Text", ss.str()); Logger::Write(Logger::ZONE_DEBUG, "Text", ss.str());
*/ */
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
SDL_SetTextureColorMod(t, FontColor.r, FontColor.g, FontColor.b); SDL_SetTextureColorMod(t, FontColor.r, FontColor.g, FontColor.b);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
SDL::RenderCopy(t, static_cast<char>(info->GetTransparency() * 255), &charRect, &rect, info->GetAngle()); SDL::RenderCopy(t, static_cast<char>(info->GetTransparency() * 255), &charRect, &rect, info->GetAngle());
rect.x += static_cast<int>(glyph.Advance * scale); rect.x += static_cast<int>(glyph.Advance * scale);
} }
} }
} }

View File

@@ -13,17 +13,17 @@ class Font;
class Text : public Component class Text : public Component
{ {
public: public:
//todo: should have a Font flass that references fontcache, pass that in as an argument //todo: should have a Font flass that references fontcache, pass that in as an argument
Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY); Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY);
virtual ~Text(); virtual ~Text();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void Draw(); void Draw();
private: private:
std::string TextData; std::string TextData;
Font *FontInst; Font *FontInst;
SDL_Color FontColor; SDL_Color FontColor;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
}; };

View File

@@ -10,27 +10,27 @@
VideoComponent * VideoBuilder::CreateVideo(std::string path, std::string name, float scaleX, float scaleY) VideoComponent * VideoBuilder::CreateVideo(std::string path, std::string name, float scaleX, float scaleY)
{ {
VideoComponent *component = NULL; VideoComponent *component = NULL;
std::vector<std::string> extensions; std::vector<std::string> extensions;
extensions.push_back("mp4"); extensions.push_back("mp4");
extensions.push_back("MP4"); extensions.push_back("MP4");
extensions.push_back("avi"); extensions.push_back("avi");
extensions.push_back("AVI"); extensions.push_back("AVI");
std::string prefix = path + "/" + name; std::string prefix = path + "/" + name;
std::string file; std::string file;
if(Utils::FindMatchingFile(prefix, extensions, file)) if(Utils::FindMatchingFile(prefix, extensions, file))
{ {
IVideo *video = Factory.CreateVideo(); IVideo *video = Factory.CreateVideo();
if(video) if(video)
{ {
component = new VideoComponent(video, file, scaleX, scaleY); component = new VideoComponent(video, file, scaleX, scaleY);
} }
} }
return component; return component;
} }

View File

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

View File

@@ -8,77 +8,77 @@
#include "../../SDL.h" #include "../../SDL.h"
VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY) VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY)
: VideoTexture(NULL) : VideoTexture(NULL)
, VideoFile(videoFile) , VideoFile(videoFile)
, VideoInst(videoInst) , VideoInst(videoInst)
, ScaleX(scaleX) , ScaleX(scaleX)
, ScaleY(scaleY) , ScaleY(scaleY)
, IsPlaying(false) , IsPlaying(false)
{ {
// AllocateGraphicsMemory(); // AllocateGraphicsMemory();
} }
VideoComponent::~VideoComponent() VideoComponent::~VideoComponent()
{ {
FreeGraphicsMemory(); FreeGraphicsMemory();
if(VideoInst) if(VideoInst)
{ {
VideoInst->Stop(); VideoInst->Stop();
} }
} }
void VideoComponent::Update(float dt) void VideoComponent::Update(float dt)
{ {
if(IsPlaying) if(IsPlaying)
{ {
VideoInst->Update(dt); VideoInst->Update(dt);
} }
Component::Update(dt); Component::Update(dt);
} }
void VideoComponent::AllocateGraphicsMemory() void VideoComponent::AllocateGraphicsMemory()
{ {
Component::AllocateGraphicsMemory(); Component::AllocateGraphicsMemory();
if(!IsPlaying) if(!IsPlaying)
{ {
IsPlaying = VideoInst->Play(VideoFile); IsPlaying = VideoInst->Play(VideoFile);
} }
} }
void VideoComponent::FreeGraphicsMemory() void VideoComponent::FreeGraphicsMemory()
{ {
VideoInst->Stop(); VideoInst->Stop();
IsPlaying = false; IsPlaying = false;
if (VideoTexture != NULL) if (VideoTexture != NULL)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
SDL_DestroyTexture(VideoTexture); SDL_DestroyTexture(VideoTexture);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
Component::FreeGraphicsMemory(); Component::FreeGraphicsMemory();
} }
void VideoComponent::Draw() void VideoComponent::Draw()
{ {
ViewInfo *info = GetBaseViewInfo(); ViewInfo *info = GetBaseViewInfo();
SDL_Rect rect; SDL_Rect rect;
rect.x = static_cast<int>(info->GetXRelativeToOrigin()); rect.x = static_cast<int>(info->GetXRelativeToOrigin());
rect.y = static_cast<int>(info->GetYRelativeToOrigin()); rect.y = static_cast<int>(info->GetYRelativeToOrigin());
rect.h = static_cast<int>(info->GetHeight()); rect.h = static_cast<int>(info->GetHeight());
rect.w = static_cast<int>(info->GetWidth()); rect.w = static_cast<int>(info->GetWidth());
VideoInst->Draw(); VideoInst->Draw();
SDL_Texture *texture = VideoInst->GetTexture(); SDL_Texture *texture = VideoInst->GetTexture();
if(texture) if(texture)
{ {
SDL::RenderCopy(texture, static_cast<int>(info->GetTransparency() * 255), NULL, &rect, info->GetAngle()); SDL::RenderCopy(texture, static_cast<int>(info->GetTransparency() * 255), NULL, &rect, info->GetAngle());
} }
} }

View File

@@ -12,21 +12,27 @@
class VideoComponent : public Component class VideoComponent : public Component
{ {
public: public:
VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY); VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY);
virtual ~VideoComponent(); virtual ~VideoComponent();
void Update(float dt); void Update(float dt);
void Draw(); void Draw();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void LaunchEnter() {FreeGraphicsMemory(); } void LaunchEnter()
void LaunchExit() { AllocateGraphicsMemory(); } {
FreeGraphicsMemory();
}
void LaunchExit()
{
AllocateGraphicsMemory();
}
private: private:
SDL_Texture *VideoTexture; SDL_Texture *VideoTexture;
std::string VideoFile; std::string VideoFile;
std::string Name; std::string Name;
IVideo *VideoInst; IVideo *VideoInst;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
bool IsPlaying; bool IsPlaying;
}; };

View File

@@ -1,17 +1,17 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "ComponentItemBinding.h" #include "ComponentItemBinding.h"
ComponentItemBinding::ComponentItemBinding( Component *c, Item *item) ComponentItemBinding::ComponentItemBinding( Component *c, Item *item)
: CollectionComponent(c) : CollectionComponent(c)
, CollectionItem(item) , CollectionItem(item)
{ {
} }
ComponentItemBinding::ComponentItemBinding(Item *item) ComponentItemBinding::ComponentItemBinding(Item *item)
: CollectionComponent(NULL) : CollectionComponent(NULL)
, CollectionItem(item) , CollectionItem(item)
{ {
} }
@@ -21,15 +21,15 @@ ComponentItemBinding::~ComponentItemBinding()
Item* ComponentItemBinding::GetCollectionItem() const Item* ComponentItemBinding::GetCollectionItem() const
{ {
return CollectionItem; return CollectionItem;
} }
void ComponentItemBinding::SetComponent(Component *c) void ComponentItemBinding::SetComponent(Component *c)
{ {
CollectionComponent = c; CollectionComponent = c;
} }
Component* ComponentItemBinding::GetComponent() const Component* ComponentItemBinding::GetComponent() const
{ {
return CollectionComponent; return CollectionComponent;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -9,15 +9,15 @@
class ComponentItemBinding class ComponentItemBinding
{ {
public: public:
ComponentItemBinding(Component *c, Item *item); ComponentItemBinding(Component *c, Item *item);
ComponentItemBinding(Item *item); ComponentItemBinding(Item *item);
virtual ~ComponentItemBinding(); virtual ~ComponentItemBinding();
Item* GetCollectionItem() const; Item* GetCollectionItem() const;
void SetComponent(Component *c); void SetComponent(Component *c);
Component* GetComponent() const; Component* GetComponent() const;
private: private:
Component *CollectionComponent; Component *CollectionComponent;
Item *CollectionItem; Item *CollectionItem;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "ComponentItemBindingBuilder.h" #include "ComponentItemBindingBuilder.h"
#include "ComponentItemBinding.h" #include "ComponentItemBinding.h"
@@ -16,14 +16,14 @@ ComponentItemBindingBuilder::~ComponentItemBindingBuilder()
std::vector<ComponentItemBinding *> *ComponentItemBindingBuilder::BuildCollectionItems(std::vector<Item *> *infoList) std::vector<ComponentItemBinding *> *ComponentItemBindingBuilder::BuildCollectionItems(std::vector<Item *> *infoList)
{ {
std::vector<ComponentItemBinding *> *sprites = new std::vector<ComponentItemBinding *>(); std::vector<ComponentItemBinding *> *sprites = new std::vector<ComponentItemBinding *>();
std::vector<Item *>::iterator it; std::vector<Item *>::iterator it;
for(it = infoList->begin(); it != infoList->end(); ++it) for(it = infoList->begin(); it != infoList->end(); ++it)
{ {
ComponentItemBinding *s = new ComponentItemBinding(*it); ComponentItemBinding *s = new ComponentItemBinding(*it);
sprites->push_back(s); sprites->push_back(s);
} }
return sprites; return sprites;
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -12,7 +12,7 @@ class ComponentItemBinding;
class ComponentItemBindingBuilder class ComponentItemBindingBuilder
{ {
public: public:
ComponentItemBindingBuilder(); ComponentItemBindingBuilder();
virtual ~ComponentItemBindingBuilder(); virtual ~ComponentItemBindingBuilder();
static std::vector<ComponentItemBinding *> *BuildCollectionItems(std::vector<Item *> *infoList); static std::vector<ComponentItemBinding *> *BuildCollectionItems(std::vector<Item *> *infoList);
}; };

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "Font.h" #include "Font.h"
#include "../SDL.h" #include "../SDL.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
@@ -8,138 +8,138 @@
#include <SDL2/SDL_ttf.h> #include <SDL2/SDL_ttf.h>
Font::Font() Font::Font()
: Texture(NULL) : Texture(NULL)
{ {
} }
Font::~Font() Font::~Font()
{ {
DeInitialize(); DeInitialize();
} }
SDL_Texture *Font::GetTexture() SDL_Texture *Font::GetTexture()
{ {
return Texture; return Texture;
} }
bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph) bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph)
{ {
std::map<unsigned int, GlyphInfoBuild *>::iterator it = Atlas.find(charCode); std::map<unsigned int, GlyphInfoBuild *>::iterator it = Atlas.find(charCode);
if(it != Atlas.end()) if(it != Atlas.end())
{ {
GlyphInfoBuild *info = it->second; GlyphInfoBuild *info = it->second;
glyph = info->Glyph; glyph = info->Glyph;
return true; return true;
} }
return false; return false;
} }
bool Font::Initialize(std::string fontPath, SDL_Color color) bool Font::Initialize(std::string fontPath, SDL_Color color)
{ {
TTF_Font *font = TTF_OpenFont(fontPath.c_str(), 128); TTF_Font *font = TTF_OpenFont(fontPath.c_str(), 128);
if (!font) if (!font)
{ {
Logger::Write(Logger::ZONE_ERROR, "FontCache", "TTF_OpenFont failed"); Logger::Write(Logger::ZONE_ERROR, "FontCache", "TTF_OpenFont failed");
return false; return false;
} }
int x = 0; int x = 0;
int y = 0; int y = 0;
int atlasHeight = 0; int atlasHeight = 0;
int atlasWidth = 0; int atlasWidth = 0;
for(unsigned short int i = 32; i < 128; ++i) for(unsigned short int i = 32; i < 128; ++i)
{ {
GlyphInfoBuild *info = new GlyphInfoBuild; GlyphInfoBuild *info = new GlyphInfoBuild;
memset(info, sizeof(GlyphInfoBuild), 0); memset(info, sizeof(GlyphInfoBuild), 0);
info->Surface = TTF_RenderGlyph_Blended(font, i, color); info->Surface = TTF_RenderGlyph_Blended(font, i, color);
TTF_GlyphMetrics(font, i, &info->Glyph.MinX, &info->Glyph.MaxX, &info->Glyph.MinY, &info->Glyph.MaxY, &info->Glyph.Advance); TTF_GlyphMetrics(font, i, &info->Glyph.MinX, &info->Glyph.MaxX, &info->Glyph.MinY, &info->Glyph.MaxY, &info->Glyph.Advance);
if(x + info->Surface->w >= 1024) if(x + info->Surface->w >= 1024)
{ {
atlasHeight += y; atlasHeight += y;
atlasWidth = (atlasWidth >= x) ? atlasWidth : x; atlasWidth = (atlasWidth >= x) ? atlasWidth : x;
x = 0; x = 0;
y = 0; y = 0;
} }
info->Glyph.Rect.w = info->Surface->w; info->Glyph.Rect.w = info->Surface->w;
info->Glyph.Rect.h = info->Surface->h; info->Glyph.Rect.h = info->Surface->h;
info->Glyph.Rect.x = x; info->Glyph.Rect.x = x;
info->Glyph.Rect.y = atlasHeight; info->Glyph.Rect.y = atlasHeight;
Atlas[i] = info; Atlas[i] = info;
x += info->Glyph.Rect.w; x += info->Glyph.Rect.w;
y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h; y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h;
/* /*
std::stringstream ss; std::stringstream ss;
ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h; ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h;
Logger::Write(Logger::ZONE_ERROR, "FontCache", ss.str()); Logger::Write(Logger::ZONE_ERROR, "FontCache", ss.str());
*/ */
} }
atlasWidth = (atlasWidth >= x) ? atlasWidth : x; atlasWidth = (atlasWidth >= x) ? atlasWidth : x;
atlasHeight += y; atlasHeight += y;
unsigned int rmask; unsigned int rmask;
unsigned int gmask; unsigned int gmask;
unsigned int bmask; unsigned int bmask;
unsigned int amask; unsigned int amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN #if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000; rmask = 0xff000000;
gmask = 0x00ff0000; gmask = 0x00ff0000;
bmask = 0x0000ff00; bmask = 0x0000ff00;
amask = 0x000000ff; amask = 0x000000ff;
#else #else
rmask = 0x000000ff; rmask = 0x000000ff;
gmask = 0x0000ff00; gmask = 0x0000ff00;
bmask = 0x00ff0000; bmask = 0x00ff0000;
amask = 0xff000000; amask = 0xff000000;
#endif #endif
SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 24, rmask, gmask, bmask, amask); SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 24, rmask, gmask, bmask, amask);
std::map<unsigned int, GlyphInfoBuild *>::iterator it; std::map<unsigned int, GlyphInfoBuild *>::iterator it;
for(it = Atlas.begin(); it != Atlas.end(); it++) for(it = Atlas.begin(); it != Atlas.end(); it++)
{ {
GlyphInfoBuild *info = it->second; GlyphInfoBuild *info = it->second;
SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect); SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect);
SDL_FreeSurface(info->Surface); SDL_FreeSurface(info->Surface);
info->Surface = NULL; info->Surface = NULL;
} }
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
SDL_SetColorKey(atlasSurface, SDL_TRUE, SDL_MapRGB(atlasSurface->format, 0, 0, 0)); SDL_SetColorKey(atlasSurface, SDL_TRUE, SDL_MapRGB(atlasSurface->format, 0, 0, 0));
Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface); Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface);
SDL_FreeSurface(atlasSurface); SDL_FreeSurface(atlasSurface);
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
TTF_CloseFont(font); TTF_CloseFont(font);
return true; return true;
} }
void Font::DeInitialize() void Font::DeInitialize()
{ {
if(Texture) if(Texture)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
SDL_DestroyTexture(Texture); SDL_DestroyTexture(Texture);
Texture = NULL; Texture = NULL;
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = Atlas.begin(); std::map<unsigned int, GlyphInfoBuild *>::iterator atlasIt = Atlas.begin();
while(atlasIt != Atlas.end()) while(atlasIt != Atlas.end())
{ {
delete atlasIt->second; delete atlasIt->second;
Atlas.erase(atlasIt); Atlas.erase(atlasIt);
atlasIt = Atlas.begin(); atlasIt = Atlas.begin();
} }
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
@@ -10,33 +10,33 @@
class Font class Font
{ {
public: public:
struct GlyphInfo struct GlyphInfo
{ {
int MinX; int MinX;
int MaxX; int MaxX;
int MinY; int MinY;
int MaxY; int MaxY;
int Advance; int Advance;
SDL_Rect Rect; SDL_Rect Rect;
}; };
Font(); Font();
virtual ~Font(); virtual ~Font();
bool Initialize(std::string fontPath, SDL_Color color); bool Initialize(std::string fontPath, SDL_Color color);
void DeInitialize(); void DeInitialize();
SDL_Texture *GetTexture(); SDL_Texture *GetTexture();
bool GetRect(unsigned int charCode, GlyphInfo &glyph); bool GetRect(unsigned int charCode, GlyphInfo &glyph);
private: private:
struct GlyphInfoBuild struct GlyphInfoBuild
{ {
Font::GlyphInfo Glyph; Font::GlyphInfo Glyph;
SDL_Surface *Surface; SDL_Surface *Surface;
}; };
std::map<unsigned int, GlyphInfoBuild *> Atlas; std::map<unsigned int, GlyphInfoBuild *> Atlas;
SDL_Texture *Texture; SDL_Texture *Texture;
}; };

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "FontCache.h" #include "FontCache.h"
#include "Font.h" #include "Font.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
@@ -10,63 +10,63 @@
//todo: memory leak when launching games //todo: memory leak when launching games
FontCache::FontCache() FontCache::FontCache()
: IsInitialized(false) : IsInitialized(false)
{ {
} }
FontCache::~FontCache() FontCache::~FontCache()
{ {
DeInitialize(); DeInitialize();
} }
void FontCache::DeInitialize() void FontCache::DeInitialize()
{ {
IsInitialized = false; IsInitialized = false;
std::map<std::string, Font *>::iterator it = FontFaceMap.begin(); std::map<std::string, Font *>::iterator it = FontFaceMap.begin();
while(it != FontFaceMap.end()) while(it != FontFaceMap.end())
{ {
delete it->second; delete it->second;
FontFaceMap.erase(it); FontFaceMap.erase(it);
it = FontFaceMap.begin(); it = FontFaceMap.begin();
} }
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
TTF_Quit(); TTF_Quit();
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
void FontCache::Initialize() void FontCache::Initialize()
{ {
//todo: make bool //todo: make bool
TTF_Init(); TTF_Init();
IsInitialized = true; IsInitialized = true;
} }
Font *FontCache::GetFont(std::string fontPath) Font *FontCache::GetFont(std::string fontPath)
{ {
Font *t = NULL; Font *t = NULL;
std::map<std::string, Font *>::iterator it = FontFaceMap.find(fontPath); std::map<std::string, Font *>::iterator it = FontFaceMap.find(fontPath);
if(it != FontFaceMap.end()) if(it != FontFaceMap.end())
{ {
t = it->second; t = it->second;
} }
return t; return t;
} }
bool FontCache::LoadFont(std::string fontPath, SDL_Color color) bool FontCache::LoadFont(std::string fontPath, SDL_Color color)
{ {
std::map<std::string, Font *>::iterator it = FontFaceMap.find(fontPath); std::map<std::string, Font *>::iterator it = FontFaceMap.find(fontPath);
if(it == FontFaceMap.end()) if(it == FontFaceMap.end())
{ {
Font *f = new Font(); Font *f = new Font();
f->Initialize(fontPath, color); f->Initialize(fontPath, color);
FontFaceMap[fontPath] = f; FontFaceMap[fontPath] = f;
} }
return true; return true;
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include "Font.h" #include "Font.h"
@@ -10,17 +10,17 @@
class FontCache class FontCache
{ {
public: public:
void Initialize(); void Initialize();
void DeInitialize(); void DeInitialize();
FontCache(); FontCache();
bool LoadFont(std::string font, SDL_Color color); bool LoadFont(std::string font, SDL_Color color);
Font *GetFont(std::string font); Font *GetFont(std::string font);
virtual ~FontCache(); virtual ~FontCache();
private: private:
bool IsInitialized; bool IsInitialized;
std::map<std::string, Font *> FontFaceMap; std::map<std::string, Font *> FontFaceMap;
}; };

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include "../Collection/Item.h" #include "../Collection/Item.h"
@@ -8,7 +8,7 @@
class MenuNotifierInterface class MenuNotifierInterface
{ {
public: public:
virtual ~MenuNotifierInterface() {} virtual ~MenuNotifierInterface() {}
virtual void OnNewItemSelected(Item *) = 0; virtual void OnNewItemSelected(Item *) = 0;
}; };

View File

@@ -11,145 +11,145 @@
#include <sstream> #include <sstream>
Page::Page(std::string collectionName) Page::Page(std::string collectionName)
: CollectionName(collectionName) : CollectionName(collectionName)
, Menu(NULL) , Menu(NULL)
, Items(NULL) , Items(NULL)
, ScrollActive(false) , ScrollActive(false)
, SelectedItem(NULL) , SelectedItem(NULL)
, SelectedItemChanged(false) , SelectedItemChanged(false)
, LoadSoundChunk(NULL) , LoadSoundChunk(NULL)
, UnloadSoundChunk(NULL) , UnloadSoundChunk(NULL)
, HighlightSoundChunk(NULL) , HighlightSoundChunk(NULL)
, SelectSoundChunk(NULL) , SelectSoundChunk(NULL)
, HasSoundedWhenActive(false) , HasSoundedWhenActive(false)
, FirstSoundPlayed(false) , FirstSoundPlayed(false)
{ {
} }
Page::~Page() Page::~Page()
{ {
if(Menu) if(Menu)
{ {
Menu->RemoveComponentForNotifications(this); Menu->RemoveComponentForNotifications(this);
} }
for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i) for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
delete *it; delete *it;
} }
LayerComponents[i].clear(); LayerComponents[i].clear();
} }
if(Menu) if(Menu)
{ {
delete Menu; delete Menu;
} }
if(LoadSoundChunk) if(LoadSoundChunk)
{ {
delete LoadSoundChunk; delete LoadSoundChunk;
LoadSoundChunk = NULL; LoadSoundChunk = NULL;
} }
if(UnloadSoundChunk) if(UnloadSoundChunk)
{ {
delete UnloadSoundChunk; delete UnloadSoundChunk;
UnloadSoundChunk = NULL; UnloadSoundChunk = NULL;
} }
if(HighlightSoundChunk) if(HighlightSoundChunk)
{ {
delete HighlightSoundChunk; delete HighlightSoundChunk;
HighlightSoundChunk = NULL; HighlightSoundChunk = NULL;
} }
if(SelectSoundChunk) if(SelectSoundChunk)
{ {
delete SelectSoundChunk; delete SelectSoundChunk;
SelectSoundChunk = NULL; SelectSoundChunk = NULL;
} }
} }
void Page::OnNewItemSelected(Item *item) void Page::OnNewItemSelected(Item *item)
{ {
SelectedItem = item; SelectedItem = item;
SelectedItemChanged = true; SelectedItemChanged = true;
} }
void Page::SetMenu(ScrollingList *s) void Page::SetMenu(ScrollingList *s)
{ {
// todo: delete the old menu // todo: delete the old menu
Menu = s; Menu = s;
if(Menu) if(Menu)
{ {
Menu->AddComponentForNotifications(this); Menu->AddComponentForNotifications(this);
} }
} }
bool Page::AddComponent(Component *c) bool Page::AddComponent(Component *c)
{ {
bool retVal = false; bool retVal = false;
unsigned int layer = c->GetBaseViewInfo()->GetLayer(); unsigned int layer = c->GetBaseViewInfo()->GetLayer();
if(layer < NUM_LAYERS) if(layer < NUM_LAYERS)
{ {
LayerComponents[layer].push_back(c); LayerComponents[layer].push_back(c);
retVal = true; retVal = true;
} }
else else
{ {
std::stringstream ss; std::stringstream ss;
ss << "Component layer too large Layer: " << layer; ss << "Component layer too large Layer: " << layer;
Logger::Write(Logger::ZONE_ERROR, "Page", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Page", ss.str());
} }
return retVal; return retVal;
} }
bool Page::IsIdle() bool Page::IsIdle()
{ {
bool idle = true; bool idle = true;
if(Menu != NULL && !Menu->IsIdle()) if(Menu != NULL && !Menu->IsIdle())
{ {
idle = false; idle = false;
} }
for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i) for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it)
{ {
idle = (*it)->IsIdle(); idle = (*it)->IsIdle();
} }
} }
return idle; return idle;
} }
bool Page::IsHidden() bool Page::IsHidden()
{ {
bool hidden = true; bool hidden = true;
if(Menu != NULL) if(Menu != NULL)
{ {
hidden = Menu->IsHidden(); hidden = Menu->IsHidden();
} }
for(unsigned int i = 0; hidden && i < NUM_LAYERS; ++i) for(unsigned int i = 0; hidden && i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it)
{ {
hidden = (*it)->IsHidden(); hidden = (*it)->IsHidden();
} }
} }
return hidden; return hidden;
@@ -157,250 +157,250 @@ bool Page::IsHidden()
void Page::Start() void Page::Start()
{ {
Menu->TriggerEnterEvent(); Menu->TriggerEnterEvent();
if(LoadSoundChunk) if(LoadSoundChunk)
{ {
LoadSoundChunk->Play(); LoadSoundChunk->Play();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerEnterEvent(); (*it)->TriggerEnterEvent();
} }
} }
} }
void Page::Stop() void Page::Stop()
{ {
Menu->TriggerExitEvent(); Menu->TriggerExitEvent();
if(UnloadSoundChunk) if(UnloadSoundChunk)
{ {
UnloadSoundChunk->Play(); UnloadSoundChunk->Play();
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerExitEvent(); (*it)->TriggerExitEvent();
} }
} }
} }
Item *Page::GetSelectedItem() Item *Page::GetSelectedItem()
{ {
return SelectedItem; return SelectedItem;
} }
void Page::RemoveSelectedItem() void Page::RemoveSelectedItem()
{ {
if(Menu) if(Menu)
{ {
//todo: change method to RemoveItem() and pass in SelectedItem //todo: change method to RemoveItem() and pass in SelectedItem
Menu->RemoveSelectedItem(); Menu->RemoveSelectedItem();
SelectedItem = NULL; SelectedItem = NULL;
} }
} }
void Page::Highlight() void Page::Highlight()
{ {
Item *item = SelectedItem; Item *item = SelectedItem;
if(item) if(item)
{ {
if(Menu) if(Menu)
{ {
Menu->TriggerHighlightEvent(item); Menu->TriggerHighlightEvent(item);
Menu->SetScrollActive(ScrollActive); Menu->SetScrollActive(ScrollActive);
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->TriggerHighlightEvent(item); (*it)->TriggerHighlightEvent(item);
(*it)->SetScrollActive(ScrollActive); (*it)->SetScrollActive(ScrollActive);
} }
} }
} }
} }
void Page::SetScrolling(ScrollDirection direction) void Page::SetScrolling(ScrollDirection direction)
{ {
ScrollingList::ScrollDirection menuDirection; ScrollingList::ScrollDirection menuDirection;
switch(direction) switch(direction)
{ {
case ScrollDirectionForward: case ScrollDirectionForward:
menuDirection = ScrollingList::ScrollDirectionForward; menuDirection = ScrollingList::ScrollDirectionForward;
ScrollActive = true; ScrollActive = true;
break; break;
case ScrollDirectionBack: case ScrollDirectionBack:
menuDirection = ScrollingList::ScrollDirectionBack; menuDirection = ScrollingList::ScrollDirectionBack;
ScrollActive = true; ScrollActive = true;
break; break;
case ScrollDirectionIdle: case ScrollDirectionIdle:
default: default:
menuDirection = ScrollingList::ScrollDirectionIdle; menuDirection = ScrollingList::ScrollDirectionIdle;
ScrollActive = false; ScrollActive = false;
break; break;
} }
if(Menu) if(Menu)
{ {
Menu->SetScrollDirection(menuDirection); Menu->SetScrollDirection(menuDirection);
} }
} }
void Page::PageScroll(ScrollDirection direction) void Page::PageScroll(ScrollDirection direction)
{ {
if(Menu) if(Menu)
{ {
if(direction == ScrollDirectionForward) if(direction == ScrollDirectionForward)
{ {
Menu->PageDown(); Menu->PageDown();
} }
if(direction == ScrollDirectionBack) if(direction == ScrollDirectionBack)
{ {
Menu->PageUp(); Menu->PageUp();
} }
} }
} }
void Page::SetItems(std::vector<Item *> *items) void Page::SetItems(std::vector<Item *> *items)
{ {
std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::BuildCollectionItems(items); std::vector<ComponentItemBinding *> *sprites = ComponentItemBindingBuilder::BuildCollectionItems(items);
if(Menu != NULL) if(Menu != NULL)
{ {
Menu->SetItems(sprites); Menu->SetItems(sprites);
} }
} }
void Page::Update(float dt) void Page::Update(float dt)
{ {
if(Menu != NULL) if(Menu != NULL)
{ {
Menu->Update(dt); Menu->Update(dt);
} }
if(SelectedItemChanged && !HasSoundedWhenActive && HighlightSoundChunk) if(SelectedItemChanged && !HasSoundedWhenActive && HighlightSoundChunk)
{ {
// skip the first sound being played (as it is part of the on-enter) // skip the first sound being played (as it is part of the on-enter)
if(FirstSoundPlayed) if(FirstSoundPlayed)
{ {
HighlightSoundChunk->Play(); HighlightSoundChunk->Play();
HasSoundedWhenActive = true; HasSoundedWhenActive = true;
} }
FirstSoundPlayed = true; FirstSoundPlayed = true;
} }
if(SelectedItemChanged && !ScrollActive) if(SelectedItemChanged && !ScrollActive)
{ {
Highlight(); Highlight();
SelectedItemChanged = false; SelectedItemChanged = false;
HasSoundedWhenActive = false; HasSoundedWhenActive = false;
} }
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->Update(dt); (*it)->Update(dt);
} }
} }
} }
void Page::Draw() void Page::Draw()
{ {
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->Draw(); (*it)->Draw();
} }
Menu->Draw(i); Menu->Draw(i);
} }
} }
const std::string& Page::GetCollectionName() const const std::string& Page::GetCollectionName() const
{ {
return CollectionName; return CollectionName;
} }
void Page::FreeGraphicsMemory() void Page::FreeGraphicsMemory()
{ {
Logger::Write(Logger::ZONE_DEBUG, "Page", "Free"); Logger::Write(Logger::ZONE_DEBUG, "Page", "Free");
Menu->FreeGraphicsMemory(); Menu->FreeGraphicsMemory();
if(LoadSoundChunk) LoadSoundChunk->Free(); if(LoadSoundChunk) LoadSoundChunk->Free();
if(UnloadSoundChunk) UnloadSoundChunk->Free(); if(UnloadSoundChunk) UnloadSoundChunk->Free();
if(HighlightSoundChunk) HighlightSoundChunk->Free(); if(HighlightSoundChunk) HighlightSoundChunk->Free();
if(SelectSoundChunk) SelectSoundChunk->Free(); if(SelectSoundChunk) SelectSoundChunk->Free();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->FreeGraphicsMemory(); (*it)->FreeGraphicsMemory();
} }
} }
} }
void Page::AllocateGraphicsMemory() void Page::AllocateGraphicsMemory()
{ {
FirstSoundPlayed = false; FirstSoundPlayed = false;
Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory"); Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory");
Menu->AllocateGraphicsMemory(); Menu->AllocateGraphicsMemory();
if(LoadSoundChunk) LoadSoundChunk->Allocate(); if(LoadSoundChunk) LoadSoundChunk->Allocate();
if(UnloadSoundChunk) UnloadSoundChunk->Allocate(); if(UnloadSoundChunk) UnloadSoundChunk->Allocate();
if(HighlightSoundChunk) HighlightSoundChunk->Allocate(); if(HighlightSoundChunk) HighlightSoundChunk->Allocate();
if(SelectSoundChunk) SelectSoundChunk->Allocate(); if(SelectSoundChunk) SelectSoundChunk->Allocate();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->AllocateGraphicsMemory(); (*it)->AllocateGraphicsMemory();
} }
} }
Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete"); Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete");
} }
void Page::LaunchEnter() void Page::LaunchEnter()
{ {
Menu->LaunchEnter(); Menu->LaunchEnter();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->LaunchEnter(); (*it)->LaunchEnter();
} }
} }
} }
void Page::LaunchExit() void Page::LaunchExit()
{ {
Menu->LaunchExit(); Menu->LaunchExit();
for(unsigned int i = 0; i < NUM_LAYERS; ++i) for(unsigned int i = 0; i < NUM_LAYERS; ++i)
{ {
for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) for(std::vector<Component *>::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it)
{ {
(*it)->LaunchExit(); (*it)->LaunchExit();
} }
} }
} }

View File

@@ -16,56 +16,68 @@ class Sound;
class Page : public MenuNotifierInterface class Page : public MenuNotifierInterface
{ {
public: public:
enum ScrollDirection enum ScrollDirection
{ {
ScrollDirectionForward, ScrollDirectionForward,
ScrollDirectionBack, ScrollDirectionBack,
ScrollDirectionIdle ScrollDirectionIdle
}; };
Page(std::string collectionName); Page(std::string collectionName);
virtual ~Page(); virtual ~Page();
virtual void OnNewItemSelected(Item *); virtual void OnNewItemSelected(Item *);
void SetItems(std::vector<Item *> *items); void SetItems(std::vector<Item *> *items);
void SetMenu(ScrollingList *s); void SetMenu(ScrollingList *s);
void SetLoadSound(Sound *chunk) { LoadSoundChunk = chunk; } void SetLoadSound(Sound *chunk)
void SetUnloadSound(Sound *chunk) { UnloadSoundChunk = chunk; } {
void SetHighlightSound(Sound *chunk) { HighlightSoundChunk = chunk; } LoadSoundChunk = chunk;
void SetSelectSound(Sound *chunk) { SelectSoundChunk = chunk; } }
bool AddComponent(Component *c); void SetUnloadSound(Sound *chunk)
void PageScroll(ScrollDirection direction); {
void Start(); UnloadSoundChunk = chunk;
void Stop(); }
void SetScrolling(ScrollDirection direction); void SetHighlightSound(Sound *chunk)
Item *GetSelectedItem(); {
Item *GetPendingSelectedItem(); HighlightSoundChunk = chunk;
void RemoveSelectedItem(); }
bool IsIdle(); void SetSelectSound(Sound *chunk)
bool IsHidden(); {
void Update(float dt); SelectSoundChunk = chunk;
void Draw(); }
void FreeGraphicsMemory(); bool AddComponent(Component *c);
void AllocateGraphicsMemory(); void PageScroll(ScrollDirection direction);
void LaunchEnter(); void Start();
void LaunchExit(); void Stop();
const std::string& GetCollectionName() const; void SetScrolling(ScrollDirection direction);
Item *GetSelectedItem();
Item *GetPendingSelectedItem();
void RemoveSelectedItem();
bool IsIdle();
bool IsHidden();
void Update(float dt);
void Draw();
void FreeGraphicsMemory();
void AllocateGraphicsMemory();
void LaunchEnter();
void LaunchExit();
const std::string& GetCollectionName() const;
private: private:
void Highlight(); void Highlight();
std::string CollectionName; std::string CollectionName;
ScrollingList *Menu; ScrollingList *Menu;
static const unsigned int NUM_LAYERS = 8; static const unsigned int NUM_LAYERS = 8;
std::vector<Component *> LayerComponents[NUM_LAYERS]; std::vector<Component *> LayerComponents[NUM_LAYERS];
std::vector<Item *> *Items; std::vector<Item *> *Items;
bool ScrollActive; bool ScrollActive;
Item *SelectedItem; Item *SelectedItem;
bool SelectedItemChanged; bool SelectedItemChanged;
Sound *LoadSoundChunk; Sound *LoadSoundChunk;
Sound *UnloadSoundChunk; Sound *UnloadSoundChunk;
Sound *HighlightSoundChunk; Sound *HighlightSoundChunk;
Sound *SelectSoundChunk; Sound *SelectSoundChunk;
bool HasSoundedWhenActive; bool HasSoundedWhenActive;
bool FirstSoundPlayed; bool FirstSoundPlayed;
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -18,42 +18,42 @@ class Configuration;
class PageBuilder class PageBuilder
{ {
public: public:
PageBuilder(std::string layoutKey, std::string collection, Configuration *c, FontCache *fc); PageBuilder(std::string layoutKey, std::string collection, Configuration *c, FontCache *fc);
virtual ~PageBuilder(); virtual ~PageBuilder();
Page *BuildPage(); Page *BuildPage();
private: private:
std::string LayoutKey; std::string LayoutKey;
std::string LayoutPath; std::string LayoutPath;
std::string Collection; std::string Collection;
Configuration *Config; Configuration *Config;
float ScaleX; float ScaleX;
float ScaleY; float ScaleY;
int ScreenHeight; int ScreenHeight;
int ScreenWidth; int ScreenWidth;
SDL_Color FontColor; SDL_Color FontColor;
std::string Font; std::string Font;
FontCache *FC; //todo: don't need Font itself, just need cache instances FontCache *FC; //todo: don't need Font itself, just need cache instances
void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page); void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page);
float GetVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); float GetVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull);
float GetHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); float GetHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull);
void BuildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo *info); void BuildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo *info);
bool BuildComponents(rapidxml::xml_node<> *layout, Page *page); bool BuildComponents(rapidxml::xml_node<> *layout, Page *page);
void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml); void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml);
ScrollingList * BuildCustomMenu(rapidxml::xml_node<> *menuXml); ScrollingList * BuildCustomMenu(rapidxml::xml_node<> *menuXml);
rapidxml::xml_attribute<> *FindRecursiveAttribute(rapidxml::xml_node<> *componentXml, std::string attribute); rapidxml::xml_attribute<> *FindRecursiveAttribute(rapidxml::xml_node<> *componentXml, std::string attribute);
void GetTweenSets(rapidxml::xml_node<> *node, std::vector<std::vector<Tween *> *> *tweenSets); void GetTweenSets(rapidxml::xml_node<> *node, std::vector<std::vector<Tween *> *> *tweenSets);
void GetTweenSet(rapidxml::xml_node<> *node, std::vector<Tween *> &tweens); void GetTweenSet(rapidxml::xml_node<> *node, std::vector<Tween *> &tweens);
void LoadLayoutXml(); void LoadLayoutXml();
void LoadAnimations(std::string keyPrefix, Component &component, ViewInfo *defaults); void LoadAnimations(std::string keyPrefix, Component &component, ViewInfo *defaults);
std::vector<ViewInfo *> *BuildTweenPoints(std::string iteratorPrefix, ViewInfo *defaults); std::vector<ViewInfo *> *BuildTweenPoints(std::string iteratorPrefix, ViewInfo *defaults);
Component * LoadComponent(std::string keyPrefix); Component * LoadComponent(std::string keyPrefix);
ScrollingList * LoadMenu(); ScrollingList * LoadMenu();
void LoadListItems(std::string keyPrefix, std::vector<ViewInfo *> *tweenPointList, ViewInfo *defaults, int &selectedItemIndex); void LoadListItems(std::string keyPrefix, std::vector<ViewInfo *> *tweenPointList, ViewInfo *defaults, int &selectedItemIndex);
void UpdateViewInfoFromTag(std::string keyPrefix, ViewInfo *p, ViewInfo *defaults); void UpdateViewInfoFromTag(std::string keyPrefix, ViewInfo *p, ViewInfo *defaults);
}; };

View File

@@ -7,24 +7,24 @@
#include <cfloat> #include <cfloat>
ViewInfo::ViewInfo() ViewInfo::ViewInfo()
: X(0) : X(0)
, Y(0) , Y(0)
, XOrigin(0) , XOrigin(0)
, YOrigin(0) , YOrigin(0)
, XOffset(0) , XOffset(0)
, YOffset(0) , YOffset(0)
, Width(-1) , Width(-1)
, MinWidth(0) , MinWidth(0)
, MaxWidth(FLT_MAX) , MaxWidth(FLT_MAX)
, Height(-1) , Height(-1)
, MinHeight(0) , MinHeight(0)
, MaxHeight(FLT_MAX) , MaxHeight(FLT_MAX)
, ImageWidth(0) , ImageWidth(0)
, ImageHeight(0) , ImageHeight(0)
, FontSize(-1) , FontSize(-1)
, Angle(0) , Angle(0)
, Transparency(1) , Transparency(1)
, Layer(0) , Layer(0)
{ {
} }
@@ -35,266 +35,266 @@ ViewInfo::~ViewInfo()
float ViewInfo::GetXRelativeToOrigin() const float ViewInfo::GetXRelativeToOrigin() const
{ {
return X + XOffset - XOrigin*GetWidth(); return X + XOffset - XOrigin*GetWidth();
} }
float ViewInfo::GetYRelativeToOrigin() const float ViewInfo::GetYRelativeToOrigin() const
{ {
return Y + YOffset - YOrigin*GetHeight(); return Y + YOffset - YOrigin*GetHeight();
} }
float ViewInfo::GetHeight() const float ViewInfo::GetHeight() const
{ {
float value = Height; float value = Height;
if(Height == -1 && Width == -1) if(Height == -1 && Width == -1)
{ {
value = ImageHeight; value = ImageHeight;
} }
else else
{ {
if (Height == -1 && ImageWidth != 0) if (Height == -1 && ImageWidth != 0)
{ {
value = ImageHeight * Width / ImageWidth; value = ImageHeight * Width / ImageWidth;
} }
if (value < MinHeight) if (value < MinHeight)
{ {
value = MinHeight; value = MinHeight;
} }
else if (value > MaxHeight) else if (value > MaxHeight)
{ {
value = MaxHeight; value = MaxHeight;
} }
} }
return value; return value;
} }
float ViewInfo::GetWidth() const float ViewInfo::GetWidth() const
{ {
float value = Width; float value = Width;
if(Height == -1 && Width == -1) if(Height == -1 && Width == -1)
{ {
value = ImageWidth; value = ImageWidth;
} }
else else
{ {
if (Width == -1 && ImageHeight != 0) if (Width == -1 && ImageHeight != 0)
{ {
value = ImageWidth * Height / ImageHeight; value = ImageWidth * Height / ImageHeight;
} }
if (value < MinWidth) if (value < MinWidth)
{ {
value = MinWidth; value = MinWidth;
} }
else if (value > MaxWidth) else if (value > MaxWidth)
{ {
value = MaxWidth; value = MaxWidth;
} }
} }
return value; return value;
} }
float ViewInfo::GetXOffset() const float ViewInfo::GetXOffset() const
{ {
return XOffset; return XOffset;
} }
float ViewInfo::GetXOrigin() const float ViewInfo::GetXOrigin() const
{ {
return XOrigin; return XOrigin;
} }
float ViewInfo::GetYOffset() const float ViewInfo::GetYOffset() const
{ {
return YOffset; return YOffset;
} }
float ViewInfo::GetYOrigin() const float ViewInfo::GetYOrigin() const
{ {
return YOrigin; return YOrigin;
} }
float ViewInfo::GetAngle() const float ViewInfo::GetAngle() const
{ {
return Angle; return Angle;
} }
void ViewInfo::SetAngle(float angle) void ViewInfo::SetAngle(float angle)
{ {
Angle = angle; Angle = angle;
} }
float ViewInfo::GetImageHeight() const float ViewInfo::GetImageHeight() const
{ {
return ImageHeight; return ImageHeight;
} }
void ViewInfo::SetImageHeight(float imageheight) void ViewInfo::SetImageHeight(float imageheight)
{ {
ImageHeight = imageheight; ImageHeight = imageheight;
} }
float ViewInfo::GetImageWidth() const float ViewInfo::GetImageWidth() const
{ {
return ImageWidth; return ImageWidth;
} }
void ViewInfo::SetImageWidth(float imagewidth) void ViewInfo::SetImageWidth(float imagewidth)
{ {
ImageWidth = imagewidth; ImageWidth = imagewidth;
} }
unsigned int ViewInfo::GetLayer() const unsigned int ViewInfo::GetLayer() const
{ {
return Layer; return Layer;
} }
void ViewInfo::SetLayer(unsigned int layer) void ViewInfo::SetLayer(unsigned int layer)
{ {
Layer = layer; Layer = layer;
} }
float ViewInfo::GetMaxHeight() const float ViewInfo::GetMaxHeight() const
{ {
return MaxHeight; return MaxHeight;
} }
void ViewInfo::SetMaxHeight(float maxheight) void ViewInfo::SetMaxHeight(float maxheight)
{ {
MaxHeight = maxheight; MaxHeight = maxheight;
} }
float ViewInfo::GetMaxWidth() const float ViewInfo::GetMaxWidth() const
{ {
return MaxWidth; return MaxWidth;
} }
void ViewInfo::SetMaxWidth(float maxwidth) void ViewInfo::SetMaxWidth(float maxwidth)
{ {
MaxWidth = maxwidth; MaxWidth = maxwidth;
} }
float ViewInfo::GetMinHeight() const float ViewInfo::GetMinHeight() const
{ {
return MinHeight; return MinHeight;
} }
void ViewInfo::SetMinHeight(float minheight) void ViewInfo::SetMinHeight(float minheight)
{ {
MinHeight = minheight; MinHeight = minheight;
} }
float ViewInfo::GetMinWidth() const float ViewInfo::GetMinWidth() const
{ {
return MinWidth; return MinWidth;
} }
void ViewInfo::SetMinWidth(float minwidth) void ViewInfo::SetMinWidth(float minwidth)
{ {
MinWidth = minwidth; MinWidth = minwidth;
} }
float ViewInfo::GetTransparency() const float ViewInfo::GetTransparency() const
{ {
return Transparency; return Transparency;
} }
void ViewInfo::SetTransparency(float transparency) void ViewInfo::SetTransparency(float transparency)
{ {
Transparency = transparency; Transparency = transparency;
} }
float ViewInfo::GetX() const float ViewInfo::GetX() const
{ {
return X; return X;
} }
void ViewInfo::SetX(float x) void ViewInfo::SetX(float x)
{ {
X = x; X = x;
} }
void ViewInfo::SetXOffset(float offset) void ViewInfo::SetXOffset(float offset)
{ {
XOffset = offset; XOffset = offset;
} }
void ViewInfo::SetXOrigin(float origin) void ViewInfo::SetXOrigin(float origin)
{ {
XOrigin = origin; XOrigin = origin;
} }
float ViewInfo::GetY() const float ViewInfo::GetY() const
{ {
return Y; return Y;
} }
void ViewInfo::SetY(float y) void ViewInfo::SetY(float y)
{ {
Y = y; Y = y;
} }
void ViewInfo::SetYOffset(float offset) void ViewInfo::SetYOffset(float offset)
{ {
YOffset = offset; YOffset = offset;
} }
void ViewInfo::SetYOrigin(float origin) void ViewInfo::SetYOrigin(float origin)
{ {
YOrigin = origin; YOrigin = origin;
} }
float ViewInfo::GetRawYOrigin() float ViewInfo::GetRawYOrigin()
{ {
return YOrigin; return YOrigin;
} }
float ViewInfo::GetRawXOrigin() float ViewInfo::GetRawXOrigin()
{ {
return XOrigin; return XOrigin;
} }
float ViewInfo::GetRawWidth() float ViewInfo::GetRawWidth()
{ {
return Width; return Width;
} }
float ViewInfo::GetRawHeight() float ViewInfo::GetRawHeight()
{ {
return Height; return Height;
} }
void ViewInfo::SetHeight(float height) void ViewInfo::SetHeight(float height)
{ {
Height = height; Height = height;
} }
void ViewInfo::SetWidth(float width) void ViewInfo::SetWidth(float width)
{ {
Width = width; Width = width;
} }
float ViewInfo::GetFontSize() const float ViewInfo::GetFontSize() const
{ {
if(FontSize == -1) if(FontSize == -1)
{ {
return GetHeight(); return GetHeight();
} }
else else
{ {
return FontSize; return FontSize;
} }
} }
void ViewInfo::SetFontSize(float fontSize) void ViewInfo::SetFontSize(float fontSize)
{ {
FontSize = fontSize; FontSize = fontSize;
} }

View File

@@ -11,79 +11,79 @@ class ViewInfo
{ {
public: public:
ViewInfo(); ViewInfo();
virtual ~ViewInfo(); virtual ~ViewInfo();
float GetXRelativeToOrigin() const; float GetXRelativeToOrigin() const;
float GetYRelativeToOrigin() const; float GetYRelativeToOrigin() const;
float GetHeight() const; float GetHeight() const;
float GetWidth() const; float GetWidth() const;
float GetAngle() const; float GetAngle() const;
void SetAngle(float angle); void SetAngle(float angle);
float GetImageHeight() const; float GetImageHeight() const;
void SetImageHeight(float imageheight); void SetImageHeight(float imageheight);
float GetImageWidth() const; float GetImageWidth() const;
void SetImageWidth(float imagewidth); void SetImageWidth(float imagewidth);
unsigned int GetLayer() const; unsigned int GetLayer() const;
void SetLayer(unsigned int layer); void SetLayer(unsigned int layer);
float GetMaxHeight() const; float GetMaxHeight() const;
void SetMaxHeight(float maxheight); void SetMaxHeight(float maxheight);
float GetMaxWidth() const; float GetMaxWidth() const;
void SetMaxWidth(float maxwidth); void SetMaxWidth(float maxwidth);
float GetMinHeight() const; float GetMinHeight() const;
void SetMinHeight(float minheight); void SetMinHeight(float minheight);
float GetMinWidth() const; float GetMinWidth() const;
void SetMinWidth(float minwidth); void SetMinWidth(float minwidth);
float GetTransparency() const; float GetTransparency() const;
void SetTransparency(float transparency); void SetTransparency(float transparency);
float GetX() const; float GetX() const;
void SetX(float x); void SetX(float x);
float GetXOffset() const; float GetXOffset() const;
void SetXOffset(float offset); void SetXOffset(float offset);
float GetXOrigin() const; float GetXOrigin() const;
void SetXOrigin(float origin); void SetXOrigin(float origin);
float GetY() const; float GetY() const;
void SetY(float y); void SetY(float y);
float GetYOffset() const; float GetYOffset() const;
void SetYOffset(float offset); void SetYOffset(float offset);
float GetYOrigin() const; float GetYOrigin() const;
void SetYOrigin(float origin); void SetYOrigin(float origin);
float GetRawYOrigin(); float GetRawYOrigin();
float GetRawXOrigin(); float GetRawXOrigin();
float GetRawWidth(); float GetRawWidth();
float GetRawHeight(); float GetRawHeight();
void SetHeight(float height); void SetHeight(float height);
void SetWidth(float width); void SetWidth(float width);
float GetFontSize() const; float GetFontSize() const;
void SetFontSize(float fontSize); void SetFontSize(float fontSize);
static const int AlignCenter = -1; static const int AlignCenter = -1;
static const int AlignLeft = -2; static const int AlignLeft = -2;
static const int AlignTop = -3; static const int AlignTop = -3;
static const int AlignRight = -4; static const int AlignRight = -4;
static const int AlignBottom = -5; static const int AlignBottom = -5;
private: private:
float X; float X;
float Y; float Y;
float XOrigin; float XOrigin;
float YOrigin; float YOrigin;
float XOffset; float XOffset;
float YOffset; float YOffset;
float Width; float Width;
float MinWidth; float MinWidth;
float MaxWidth; float MaxWidth;
float Height; float Height;
float MinHeight; float MinHeight;
float MaxHeight; float MaxHeight;
float ImageWidth; float ImageWidth;
float ImageHeight; float ImageHeight;
float FontSize; float FontSize;
float Angle; float Angle;
float Transparency; float Transparency;
unsigned int Layer; unsigned int Layer;
float HorizontalScale; float HorizontalScale;
float VerticalScale; float VerticalScale;
}; };

View File

@@ -22,171 +22,173 @@ CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config);
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
Configuration::Initialize(); Configuration::Initialize();
Configuration config; Configuration config;
if(!StartLogging()) { if(!StartLogging())
return -1; {
} return -1;
}
if(!ImportConfiguration(&config)) if(!ImportConfiguration(&config))
{ {
return -1; return -1;
} }
DB db(Configuration::GetAbsolutePath() + "/cache.db"); DB db(Configuration::GetAbsolutePath() + "/cache.db");
if(!db.Initialize()) if(!db.Initialize())
{ {
return -1; return -1;
} }
CollectionDatabase *cdb = InitializeCollectionDatabase(db, config);
if(!cdb) {
return -1;
}
RetroFE p(cdb, &config); CollectionDatabase *cdb = InitializeCollectionDatabase(db, config);
if(!cdb)
{
return -1;
}
if(p.Initialize()) RetroFE p(cdb, &config);
{
p.Run();
}
p.DeInitialize(); if(p.Initialize())
{
p.Run();
}
Logger::DeInitialize(); p.DeInitialize();
return 0; Logger::DeInitialize();
return 0;
} }
bool ImportConfiguration(Configuration *c) bool ImportConfiguration(Configuration *c)
{ {
std::string configPath = Configuration::GetAbsolutePath(); std::string configPath = Configuration::GetAbsolutePath();
std::string launchersPath = Configuration::GetAbsolutePath() + "/Launchers"; std::string launchersPath = Configuration::GetAbsolutePath() + "/Launchers";
std::string collectionsPath = Configuration::GetAbsolutePath() + "/Collections"; std::string collectionsPath = Configuration::GetAbsolutePath() + "/Collections";
DIR *dp; DIR *dp;
struct dirent *dirp; struct dirent *dirp;
if(!c->Import("", configPath + "/Settings.conf")) if(!c->Import("", configPath + "/Settings.conf"))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\"");
return false; return false;
} }
if(!c->Import("controls", configPath + "/Controls.conf")) if(!c->Import("controls", configPath + "/Controls.conf"))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\"");
return false; return false;
} }
dp = opendir(launchersPath.c_str()); dp = opendir(launchersPath.c_str());
if(dp == NULL) if(dp == NULL)
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + launchersPath + "\""); Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + launchersPath + "\"");
return false; return false;
} }
while((dirp = readdir(dp)) != NULL) while((dirp = readdir(dp)) != NULL)
{ {
if (dirp->d_type != DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..") if (dirp->d_type != DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..")
{
std::string basename = dirp->d_name;
// if(basename.length() > 0)
{
std::string extension = basename.substr(basename.find_last_of("."), basename.size()-1);
basename = basename.substr(0, basename.find_last_of("."));
if(extension == ".conf")
{
std::string prefix = "launchers." + basename;
std::string importFile = launchersPath + "/" + std::string(dirp->d_name);
if(!c->Import(prefix, importFile))
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\"");
return false;
}
}
}
}
}
dp = opendir(collectionsPath.c_str());
if(dp == NULL)
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\"");
return false;
}
while((dirp = readdir(dp)) != NULL)
{
if (dirp->d_type == DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..")
{
std::string prefix = "collections." + std::string(dirp->d_name);
std::string settingsFile = collectionsPath + "/" + dirp->d_name + "/Settings.conf";
if(!c->Import(prefix, settingsFile))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\""); std::string basename = dirp->d_name;
return false;
// if(basename.length() > 0)
{
std::string extension = basename.substr(basename.find_last_of("."), basename.size()-1);
basename = basename.substr(0, basename.find_last_of("."));
if(extension == ".conf")
{
std::string prefix = "launchers." + basename;
std::string importFile = launchersPath + "/" + std::string(dirp->d_name);
if(!c->Import(prefix, importFile))
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\"");
return false;
}
}
}
} }
} }
}
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration"); dp = opendir(collectionsPath.c_str());
return true; if(dp == NULL)
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\"");
return false;
}
while((dirp = readdir(dp)) != NULL)
{
if (dirp->d_type == DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..")
{
std::string prefix = "collections." + std::string(dirp->d_name);
std::string settingsFile = collectionsPath + "/" + dirp->d_name + "/Settings.conf";
if(!c->Import(prefix, settingsFile))
{
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\"");
return false;
}
}
}
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration");
return true;
} }
bool StartLogging() bool StartLogging()
{ {
std::string logFile = Configuration::GetAbsolutePath() + "/Log.txt"; std::string logFile = Configuration::GetAbsolutePath() + "/Log.txt";
if(!Logger::Initialize(logFile)) if(!Logger::Initialize(logFile))
{ {
Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing"); Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing");
return false; return false;
} }
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting"); Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting");
#ifdef WIN32 #ifdef WIN32
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows"); Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows");
#else #else
Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux"); Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux");
#endif #endif
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath()); Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath());
return true; return true;
} }
CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config) CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config)
{ {
CollectionDatabase *cdb = NULL; CollectionDatabase *cdb = NULL;
std::string dbFile = (Configuration::GetAbsolutePath() + "/cache.db"); std::string dbFile = (Configuration::GetAbsolutePath() + "/cache.db");
std::ifstream infile(dbFile.c_str()); std::ifstream infile(dbFile.c_str());
cdb = new CollectionDatabase(&db, &config); cdb = new CollectionDatabase(&db, &config);
if(!cdb->Initialize()) if(!cdb->Initialize())
{ {
delete cdb; delete cdb;
cdb = NULL; cdb = NULL;
} }
else if(!cdb->Import()) else if(!cdb->Import())
{ {
delete cdb; delete cdb;
cdb = NULL; cdb = NULL;
} }
return cdb; return cdb;
} }

View File

@@ -26,474 +26,474 @@
Page *page = NULL; Page *page = NULL;
RetroFE::RetroFE(CollectionDatabase *db, Configuration *c) RetroFE::RetroFE(CollectionDatabase *db, Configuration *c)
: Config(c) : Config(c)
, CollectionDB(db) , CollectionDB(db)
, Input(Config) , Input(Config)
, KeyInputDisable(0) , KeyInputDisable(0)
, InactiveKeyTime(0) , InactiveKeyTime(0)
, AttractMode(false) , AttractMode(false)
, CurrentTime(0) , CurrentTime(0)
, VideoInst(NULL) , VideoInst(NULL)
{ {
} }
RetroFE::~RetroFE() RetroFE::~RetroFE()
{ {
DeInitialize(); DeInitialize();
} }
void RetroFE::Render() void RetroFE::Render()
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF); SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF);
SDL_RenderClear(SDL::GetRenderer()); SDL_RenderClear(SDL::GetRenderer());
Page *page = PageChain.back(); Page *page = PageChain.back();
if(page) if(page)
{ {
page->Draw(); page->Draw();
} }
SDL_RenderPresent(SDL::GetRenderer()); SDL_RenderPresent(SDL::GetRenderer());
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
bool RetroFE::Initialize() bool RetroFE::Initialize()
{ {
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Initializing"); Logger::Write(Logger::ZONE_INFO, "RetroFE", "Initializing");
if(!Input.Initialize()) return false; if(!Input.Initialize()) return false;
if(!SDL::Initialize(Config)) return false; if(!SDL::Initialize(Config)) return false;
FC.Initialize(); FC.Initialize();
bool videoEnable = true; bool videoEnable = true;
int videoLoop = 0; int videoLoop = 0;
Config->GetProperty("videoEnable", videoEnable); Config->GetProperty("videoEnable", videoEnable);
Config->GetProperty("videoLoop", videoLoop); Config->GetProperty("videoLoop", videoLoop);
VideoFactory::SetEnabled(videoEnable); VideoFactory::SetEnabled(videoEnable);
VideoFactory::SetNumLoops(videoLoop); VideoFactory::SetNumLoops(videoLoop);
VideoFactory vf; VideoFactory vf;
VideoInst = vf.CreateVideo(); VideoInst = vf.CreateVideo();
return true; return true;
} }
void RetroFE::LaunchEnter() void RetroFE::LaunchEnter()
{ {
if(PageChain.size() > 0) if(PageChain.size() > 0)
{ {
Page *p = PageChain.back(); Page *p = PageChain.back();
p->LaunchEnter(); p->LaunchEnter();
} }
SDL_SetWindowGrab(SDL::GetWindow(), SDL_FALSE); SDL_SetWindowGrab(SDL::GetWindow(), SDL_FALSE);
} }
void RetroFE::LaunchExit() void RetroFE::LaunchExit()
{ {
SDL_RestoreWindow(SDL::GetWindow()); SDL_RestoreWindow(SDL::GetWindow());
SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE); SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE);
if(PageChain.size() > 0) if(PageChain.size() > 0)
{ {
Page *p = PageChain.back(); Page *p = PageChain.back();
p->LaunchExit(); p->LaunchExit();
} }
} }
void RetroFE::FreeGraphicsMemory() void RetroFE::FreeGraphicsMemory()
{ {
if(PageChain.size() > 0) if(PageChain.size() > 0)
{ {
Page *p = PageChain.back(); Page *p = PageChain.back();
p->FreeGraphicsMemory(); p->FreeGraphicsMemory();
} }
FC.DeInitialize(); FC.DeInitialize();
SDL::DeInitialize(); SDL::DeInitialize();
} }
void RetroFE::AllocateGraphicsMemory() void RetroFE::AllocateGraphicsMemory()
{ {
SDL::Initialize(Config); SDL::Initialize(Config);
FC.Initialize(); FC.Initialize();
if(PageChain.size() > 0) if(PageChain.size() > 0)
{ {
Page *p = PageChain.back(); Page *p = PageChain.back();
p->AllocateGraphicsMemory(); p->AllocateGraphicsMemory();
p->Start(); p->Start();
} }
} }
bool RetroFE::DeInitialize() bool RetroFE::DeInitialize()
{ {
bool retVal = true; bool retVal = true;
FreeGraphicsMemory(); FreeGraphicsMemory();
bool videoEnable = true; bool videoEnable = true;
while(PageChain.size() > 0) while(PageChain.size() > 0)
{ {
Page *page = PageChain.back(); Page *page = PageChain.back();
delete page; delete page;
PageChain.pop_back(); PageChain.pop_back();
} }
if(VideoInst) if(VideoInst)
{ {
delete VideoInst; delete VideoInst;
VideoInst = NULL; VideoInst = NULL;
} }
//todo: handle video deallocation //todo: handle video deallocation
return retVal; return retVal;
} }
Configuration *RetroFE::GetConfiguration() Configuration *RetroFE::GetConfiguration()
{ {
return Config; return Config;
} }
void RetroFE::Run() void RetroFE::Run()
{ {
int attractModeTime = 0; int attractModeTime = 0;
bool attractMode = false; bool attractMode = false;
std::string firstCollection = "Main"; std::string firstCollection = "Main";
Config->GetProperty("attractModeTime", attractModeTime); Config->GetProperty("attractModeTime", attractModeTime);
Config->GetProperty("firstCollection", firstCollection); Config->GetProperty("firstCollection", firstCollection);
bool running = true; bool running = true;
Item *nextPageItem = NULL; Item *nextPageItem = NULL;
bool adminMode = false; bool adminMode = false;
float attractModeRandomTime = 0; float attractModeRandomTime = 0;
bool selectActive = false; bool selectActive = false;
//todo: break up into helper methods //todo: break up into helper methods
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Loading first page"); Logger::Write(Logger::ZONE_INFO, "RetroFE", "Loading first page");
page = LoadPage(firstCollection); page = LoadPage(firstCollection);
float frameCount = 0; float frameCount = 0;
float fpsStartTime = 0; float fpsStartTime = 0;
RETROFE_STATE state = RETROFE_IDLE; RETROFE_STATE state = RETROFE_IDLE;
while (running) while (running)
{ {
float lastTime = 0; float lastTime = 0;
float deltaTime = 0; float deltaTime = 0;
page = PageChain.back(); page = PageChain.back();
Launcher l(this); Launcher l(this);
if(!page) if(!page)
{ {
Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page"); Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page");
running = false; running = false;
break; break;
} }
// todo: This could be transformed to use the state design pattern. // todo: This could be transformed to use the state design pattern.
switch(state) switch(state)
{ {
case RETROFE_IDLE: case RETROFE_IDLE:
state = ProcessUserInput(); state = ProcessUserInput();
break; break;
case RETROFE_NEXT_PAGE_REQUEST: case RETROFE_NEXT_PAGE_REQUEST:
page->Stop(); page->Stop();
state = RETROFE_NEXT_PAGE_WAIT; state = RETROFE_NEXT_PAGE_WAIT;
break; break;
case RETROFE_NEXT_PAGE_WAIT: case RETROFE_NEXT_PAGE_WAIT:
if(page->IsHidden()) if(page->IsHidden())
{ {
page = LoadPage(NextPageItem->GetName()); page = LoadPage(NextPageItem->GetName());
state = RETROFE_NEW; state = RETROFE_NEW;
} }
break; break;
case RETROFE_LAUNCH_REQUEST: case RETROFE_LAUNCH_REQUEST:
l.Run(page->GetCollectionName(), NextPageItem); l.Run(page->GetCollectionName(), NextPageItem);
state = RETROFE_IDLE; state = RETROFE_IDLE;
break; break;
case RETROFE_BACK_REQUEST: case RETROFE_BACK_REQUEST:
page->Stop(); page->Stop();
state = RETROFE_BACK_WAIT; state = RETROFE_BACK_WAIT;
break; break;
case RETROFE_BACK_WAIT: case RETROFE_BACK_WAIT:
if(page->IsHidden()) if(page->IsHidden())
{ {
PageChain.pop_back(); PageChain.pop_back();
delete page; delete page;
page = PageChain.back(); page = PageChain.back();
CurrentTime = (float)SDL_GetTicks() / 1000;
page->AllocateGraphicsMemory();
page->Start();
state = RETROFE_NEW;
}
break;
case RETROFE_NEW:
if(page->IsIdle())
{
state = RETROFE_IDLE;
}
break;
case RETROFE_QUIT_REQUEST:
page->Stop();
state = RETROFE_QUIT;
break;
case RETROFE_QUIT:
if(page->IsHidden())
{
running = false;
}
break;
}
// the logic below could be done in a helper method
if(running)
{
lastTime = CurrentTime;
CurrentTime = (float)SDL_GetTicks() / 1000; CurrentTime = (float)SDL_GetTicks() / 1000;
page->AllocateGraphicsMemory(); if (CurrentTime < lastTime)
page->Start();
state = RETROFE_NEW;
}
break;
case RETROFE_NEW:
if(page->IsIdle())
{
state = RETROFE_IDLE;
}
break;
case RETROFE_QUIT_REQUEST:
page->Stop();
state = RETROFE_QUIT;
break;
case RETROFE_QUIT:
if(page->IsHidden())
{
running = false;
}
break;
}
// the logic below could be done in a helper method
if(running)
{
lastTime = CurrentTime;
CurrentTime = (float)SDL_GetTicks() / 1000;
if (CurrentTime < lastTime)
{
CurrentTime = lastTime;
}
deltaTime = CurrentTime - lastTime;
double sleepTime = 1000.0/60.0 - deltaTime*1000;
if(sleepTime > 0)
{
SDL_Delay(static_cast<unsigned int>(sleepTime));
}
++frameCount;
if(CurrentTime - fpsStartTime > 1.0)
{
// don't print the first framerate, it's likely inaccurate
bool logFps = false;
Config->GetProperty("debug.logfps", logFps);
if(fpsStartTime != 0 && logFps)
{ {
std::stringstream fpsstream; CurrentTime = lastTime;
fpsstream << frameCount/(CurrentTime - fpsStartTime) << " FPS";
Logger::Write(Logger::ZONE_DEBUG, "RetroFE", fpsstream.str());
} }
fpsStartTime = CurrentTime; deltaTime = CurrentTime - lastTime;
frameCount = 0; double sleepTime = 1000.0/60.0 - deltaTime*1000;
} if(sleepTime > 0)
InactiveKeyTime += deltaTime;
if(!AttractMode && InactiveKeyTime > attractModeTime)
{
AttractMode = true;
InactiveKeyTime = 0;
attractModeRandomTime = ((float)((1000+rand()) % 5000)) / 1000;
}
if(attractMode)
{
page->SetScrolling(Page::ScrollDirectionForward);
if(InactiveKeyTime > attractModeRandomTime)
{ {
InactiveKeyTime = 0; SDL_Delay(static_cast<unsigned int>(sleepTime));
attractMode = false;
page->SetScrolling(Page::ScrollDirectionIdle);
} }
}
page->Update(deltaTime); ++frameCount;
Render();
} if(CurrentTime - fpsStartTime > 1.0)
} {
// don't print the first framerate, it's likely inaccurate
bool logFps = false;
Config->GetProperty("debug.logfps", logFps);
if(fpsStartTime != 0 && logFps)
{
std::stringstream fpsstream;
fpsstream << frameCount/(CurrentTime - fpsStartTime) << " FPS";
Logger::Write(Logger::ZONE_DEBUG, "RetroFE", fpsstream.str());
}
fpsStartTime = CurrentTime;
frameCount = 0;
}
InactiveKeyTime += deltaTime;
if(!AttractMode && InactiveKeyTime > attractModeTime)
{
AttractMode = true;
InactiveKeyTime = 0;
attractModeRandomTime = ((float)((1000+rand()) % 5000)) / 1000;
}
if(attractMode)
{
page->SetScrolling(Page::ScrollDirectionForward);
if(InactiveKeyTime > attractModeRandomTime)
{
InactiveKeyTime = 0;
attractMode = false;
page->SetScrolling(Page::ScrollDirectionIdle);
}
}
page->Update(deltaTime);
Render();
}
}
} }
bool RetroFE::ItemSelected() bool RetroFE::ItemSelected()
{ {
Item *item = page->GetSelectedItem(); Item *item = page->GetSelectedItem();
if(!item) return false; if(!item) return false;
if(item->IsLeaf()) if(item->IsLeaf())
{ {
Launcher l(this); Launcher l(this);
l.Run(page->GetCollectionName(), item); l.Run(page->GetCollectionName(), item);
} }
else else
{ {
NextPageItem = item; NextPageItem = item;
LoadPage(page->GetCollectionName()); LoadPage(page->GetCollectionName());
page->Stop(); page->Stop();
} }
return true; return true;
} }
bool RetroFE::Back(bool &exit) bool RetroFE::Back(bool &exit)
{ {
bool canGoBack = false; bool canGoBack = false;
bool exitOnBack = false; bool exitOnBack = false;
Config->GetProperty("exitOnFirstPageBack", exitOnBack); Config->GetProperty("exitOnFirstPageBack", exitOnBack);
exit = false; exit = false;
if(PageChain.size() > 1) if(PageChain.size() > 1)
{ {
page->Stop(); page->Stop();
canGoBack = true; canGoBack = true;
} }
else if(PageChain.size() == 1 && exitOnBack) else if(PageChain.size() == 1 && exitOnBack)
{ {
page->Stop(); page->Stop();
exit = true; exit = true;
canGoBack = true; canGoBack = true;
} }
return canGoBack; return canGoBack;
} }
RetroFE::RETROFE_STATE RetroFE::ProcessUserInput() RetroFE::RETROFE_STATE RetroFE::ProcessUserInput()
{ {
SDL_Event e; SDL_Event e;
bool exit = false; bool exit = false;
RETROFE_STATE state = RETROFE_IDLE; RETROFE_STATE state = RETROFE_IDLE;
if (SDL_PollEvent(&e) == 0) return state; if (SDL_PollEvent(&e) == 0) return state;
if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)
{ {
const Uint8 *keys = SDL_GetKeyboardState(NULL); const Uint8 *keys = SDL_GetKeyboardState(NULL);
InactiveKeyTime = 0; InactiveKeyTime = 0;
AttractMode = false; AttractMode = false;
if (keys[Input.GetScancode(UserInput::KeyCodePreviousItem)]) if (keys[Input.GetScancode(UserInput::KeyCodePreviousItem)])
{ {
page->SetScrolling(Page::ScrollDirectionBack); page->SetScrolling(Page::ScrollDirectionBack);
} }
if (keys[Input.GetScancode(UserInput::KeyCodeNextItem)]) if (keys[Input.GetScancode(UserInput::KeyCodeNextItem)])
{ {
page->SetScrolling(Page::ScrollDirectionForward); page->SetScrolling(Page::ScrollDirectionForward);
} }
if (keys[Input.GetScancode(UserInput::KeyCodePageUp)]) if (keys[Input.GetScancode(UserInput::KeyCodePageUp)])
{ {
page->PageScroll(Page::ScrollDirectionBack); page->PageScroll(Page::ScrollDirectionBack);
} }
if (keys[Input.GetScancode(UserInput::KeyCodePageDown)]) if (keys[Input.GetScancode(UserInput::KeyCodePageDown)])
{ {
page->PageScroll(Page::ScrollDirectionForward); page->PageScroll(Page::ScrollDirectionForward);
} }
if (keys[Input.GetScancode(UserInput::KeyCodeAdminMode)]) if (keys[Input.GetScancode(UserInput::KeyCodeAdminMode)])
{ {
//todo: add admin mode support //todo: add admin mode support
} }
if (keys[Input.GetScancode(UserInput::KeyCodeSelect)]) if (keys[Input.GetScancode(UserInput::KeyCodeSelect)])
{ {
NextPageItem = page->GetSelectedItem(); NextPageItem = page->GetSelectedItem();
if(NextPageItem) if(NextPageItem)
{ {
state = (NextPageItem->IsLeaf()) ? RETROFE_LAUNCH_REQUEST : RETROFE_NEXT_PAGE_REQUEST; state = (NextPageItem->IsLeaf()) ? RETROFE_LAUNCH_REQUEST : RETROFE_NEXT_PAGE_REQUEST;
} }
} }
if (keys[Input.GetScancode(UserInput::KeyCodeBack)]) if (keys[Input.GetScancode(UserInput::KeyCodeBack)])
{ {
if(Back(exit)) if(Back(exit))
{ {
state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST; state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST;
} }
} }
if (keys[Input.GetScancode(UserInput::KeyCodeQuit)]) if (keys[Input.GetScancode(UserInput::KeyCodeQuit)])
{ {
state = RETROFE_QUIT_REQUEST; state = RETROFE_QUIT_REQUEST;
} }
if(!keys[Input.GetScancode(UserInput::KeyCodePreviousItem)] && if(!keys[Input.GetScancode(UserInput::KeyCodePreviousItem)] &&
!keys[Input.GetScancode(UserInput::KeyCodeNextItem)] && !keys[Input.GetScancode(UserInput::KeyCodeNextItem)] &&
!keys[Input.GetScancode(UserInput::KeyCodePageUp)] && !keys[Input.GetScancode(UserInput::KeyCodePageUp)] &&
!keys[Input.GetScancode(UserInput::KeyCodePageDown)]) !keys[Input.GetScancode(UserInput::KeyCodePageDown)])
{ {
page->SetScrolling(Page::ScrollDirectionIdle); page->SetScrolling(Page::ScrollDirectionIdle);
} }
} }
return state; return state;
} }
Page *RetroFE::LoadPage(std::string collectionName) Page *RetroFE::LoadPage(std::string collectionName)
{ {
Logger::Write(Logger::ZONE_INFO, "RetroFE", "Creating page for collection " + collectionName); Logger::Write(Logger::ZONE_INFO, "RetroFE", "Creating page for collection " + collectionName);
Page *page = NULL; Page *page = NULL;
std::vector<Item *> *collection = new std::vector<Item *>(); // the page will deallocate this once its done std::vector<Item *> *collection = new std::vector<Item *>(); // the page will deallocate this once its done
MenuParser mp; MenuParser mp;
mp.GetMenuItems(CollectionDB, collectionName, *collection); mp.GetMenuItems(CollectionDB, collectionName, *collection);
CollectionDB->GetCollection(collectionName, *collection); CollectionDB->GetCollection(collectionName, *collection);
//todo: handle this in a more esthetically pleasing way instead of crashing //todo: handle this in a more esthetically pleasing way instead of crashing
if(collection->size() == 0) if(collection->size() == 0)
{ {
Logger::Write(Logger::ZONE_WARNING, "RetroFE", "No list items found for collection " + collectionName); Logger::Write(Logger::ZONE_WARNING, "RetroFE", "No list items found for collection " + collectionName);
} }
else else
{ {
std::string layoutKeyName = "collections." + collectionName + ".layout"; std::string layoutKeyName = "collections." + collectionName + ".layout";
std::string layoutName = "Default 16x9"; std::string layoutName = "Default 16x9";
if(!Config->GetProperty(layoutKeyName, layoutName)) if(!Config->GetProperty(layoutKeyName, layoutName))
{ {
Config->GetProperty("layout", layoutName); Config->GetProperty("layout", layoutName);
} }
if(PageChain.size() > 0) if(PageChain.size() > 0)
{ {
Page *oldPage = PageChain.back(); Page *oldPage = PageChain.back();
if(oldPage) if(oldPage)
{ {
oldPage->FreeGraphicsMemory(); oldPage->FreeGraphicsMemory();
} }
} }
PageBuilder pb(layoutName, collectionName, Config, &FC); PageBuilder pb(layoutName, collectionName, Config, &FC);
page = pb.BuildPage(); page = pb.BuildPage();
page->SetItems(collection); page->SetItems(collection);
page->Start(); page->Start();
if(page) if(page)
{ {
PageChain.push_back(page); PageChain.push_back(page);
} }
} }
return page; return page;
} }

View File

@@ -17,49 +17,49 @@ class Page;
class RetroFE class RetroFE
{ {
public: public:
RetroFE(CollectionDatabase *db, Configuration *c); RetroFE(CollectionDatabase *db, Configuration *c);
virtual ~RetroFE(); virtual ~RetroFE();
bool Initialize(); bool Initialize();
bool DeInitialize(); bool DeInitialize();
void Run(); void Run();
Configuration *GetConfiguration(); Configuration *GetConfiguration();
void FreeGraphicsMemory(); void FreeGraphicsMemory();
void AllocateGraphicsMemory(); void AllocateGraphicsMemory();
void LaunchEnter(); void LaunchEnter();
void LaunchExit(); void LaunchExit();
private: private:
enum RETROFE_STATE enum RETROFE_STATE
{ {
RETROFE_IDLE, RETROFE_IDLE,
RETROFE_NEXT_PAGE_REQUEST, RETROFE_NEXT_PAGE_REQUEST,
RETROFE_NEXT_PAGE_WAIT, RETROFE_NEXT_PAGE_WAIT,
RETROFE_LAUNCH_REQUEST, RETROFE_LAUNCH_REQUEST,
RETROFE_BACK_REQUEST, RETROFE_BACK_REQUEST,
RETROFE_BACK_WAIT, RETROFE_BACK_WAIT,
RETROFE_NEW, RETROFE_NEW,
RETROFE_QUIT_REQUEST, RETROFE_QUIT_REQUEST,
RETROFE_QUIT, RETROFE_QUIT,
}; };
void Render(); void Render();
bool ItemSelected(); bool ItemSelected();
bool Back(bool &exit); bool Back(bool &exit);
void Quit(); void Quit();
Page *LoadPage(std::string collectionName); Page *LoadPage(std::string collectionName);
RETROFE_STATE ProcessUserInput(); RETROFE_STATE ProcessUserInput();
void Update(float dt, bool scrollActive); void Update(float dt, bool scrollActive);
Configuration *Config; Configuration *Config;
CollectionDatabase *CollectionDB; CollectionDatabase *CollectionDB;
UserInput Input; UserInput Input;
std::list<Page *> PageChain; std::list<Page *> PageChain;
float KeyInputDisable; float KeyInputDisable;
float InactiveKeyTime; float InactiveKeyTime;
bool AttractMode; bool AttractMode;
float CurrentTime; float CurrentTime;
Item *NextPageItem; Item *NextPageItem;
FontCache FC; FontCache FC;
IVideo *VideoInst; IVideo *VideoInst;
}; };

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "SDL.h" #include "SDL.h"
#include "Database/Configuration.h" #include "Database/Configuration.h"
#include "Utility/Log.h" #include "Utility/Log.h"
@@ -18,239 +18,239 @@ bool SDL::Fullscreen = false;
bool SDL::Initialize(Configuration *config) bool SDL::Initialize(Configuration *config)
{ {
bool retVal = true; bool retVal = true;
std::string hString; std::string hString;
std::string vString; std::string vString;
Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS; Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS;
int audioRate = MIX_DEFAULT_FREQUENCY; int audioRate = MIX_DEFAULT_FREQUENCY;
Uint16 audioFormat = MIX_DEFAULT_FORMAT; /* 16-bit stereo */ Uint16 audioFormat = MIX_DEFAULT_FORMAT; /* 16-bit stereo */
int audioChannels = 1; int audioChannels = 1;
int audioBuffers = 4096; int audioBuffers = 4096;
bool hideMouse; bool hideMouse;
Logger::Write(Logger::ZONE_DEBUG, "SDL", "Initializing"); Logger::Write(Logger::ZONE_DEBUG, "SDL", "Initializing");
if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0) if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0)
{ {
std::string error = SDL_GetError(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error); Logger::Write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error);
retVal = false; retVal = false;
} }
if(retVal && config->GetProperty("hideMouse", hideMouse)) if(retVal && config->GetProperty("hideMouse", hideMouse))
{ {
if(hideMouse) if(hideMouse)
{ {
SDL_ShowCursor(SDL_FALSE); SDL_ShowCursor(SDL_FALSE);
} }
else else
{ {
SDL_ShowCursor(SDL_TRUE); SDL_ShowCursor(SDL_TRUE);
} }
} }
// check for a few other necessary Configurations // check for a few other necessary Configurations
if(retVal) if(retVal)
{ {
// Get current display mode of all displays. // Get current display mode of all displays.
for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i)
{ {
SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{
DisplayWidth = mode.w;
DisplayHeight = mode.h;
break;
}
}
if(!config->GetProperty("horizontal", hString))
{
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\"");
retVal = false;
}
else if(hString == "stretch")
{
// Get current display mode of all displays.
for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i)
{
SDL_DisplayMode mode; SDL_DisplayMode mode;
if(SDL_GetCurrentDisplayMode(i, &mode) == 0) if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{ {
WindowWidth = mode.w; DisplayWidth = mode.w;
break; DisplayHeight = mode.h;
break;
} }
} }
}
else if(!config->GetProperty("horizontal", WindowWidth))
{
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\"");
}
}
// check for a few other necessary Configurations
if(retVal) if(!config->GetProperty("horizontal", hString))
{ {
if(!config->GetProperty("vertical", hString)) Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\"");
{ retVal = false;
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\""); }
retVal = false; else if(hString == "stretch")
} {
else if(hString == "stretch") // Get current display mode of all displays.
{ for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i)
// Get current display mode of all displays.
for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i)
{
SDL_DisplayMode mode;
if(SDL_GetDesktopDisplayMode(i, &mode) == 0)
{ {
WindowHeight = mode.h; SDL_DisplayMode mode;
break; if(SDL_GetCurrentDisplayMode(i, &mode) == 0)
{
WindowWidth = mode.w;
break;
}
} }
} }
} else if(!config->GetProperty("horizontal", WindowWidth))
else if(!config->GetProperty("vertical", WindowHeight)) {
{ Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\"");
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\""); }
} }
}
if(retVal && !config->GetProperty("fullscreen", Fullscreen)) // check for a few other necessary Configurations
{ if(retVal)
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\""); {
retVal = false; if(!config->GetProperty("vertical", hString))
} {
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\"");
retVal = false;
}
else if(hString == "stretch")
{
// Get current display mode of all displays.
for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i)
{
SDL_DisplayMode mode;
if(SDL_GetDesktopDisplayMode(i, &mode) == 0)
{
WindowHeight = mode.h;
break;
}
}
}
else if(!config->GetProperty("vertical", WindowHeight))
{
Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\"");
}
}
if (retVal && Fullscreen) if(retVal && !config->GetProperty("fullscreen", Fullscreen))
{ {
windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\"");
} retVal = false;
}
if(retVal) if (retVal && Fullscreen)
{ {
std::stringstream ss; windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: " << Fullscreen << ")"; }
Logger::Write(Logger::ZONE_DEBUG, "SDL", ss.str());
Window = SDL_CreateWindow("RetroFE", if(retVal)
SDL_WINDOWPOS_CENTERED, {
SDL_WINDOWPOS_CENTERED, std::stringstream ss;
WindowWidth, ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: " << Fullscreen << ")";
WindowHeight, Logger::Write(Logger::ZONE_DEBUG, "SDL", ss.str());
windowFlags);
if (Window == NULL) Window = SDL_CreateWindow("RetroFE",
{ SDL_WINDOWPOS_CENTERED,
std::string error = SDL_GetError(); SDL_WINDOWPOS_CENTERED,
Logger::Write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error); WindowWidth,
retVal = false; WindowHeight,
} windowFlags);
}
if(retVal) if (Window == NULL)
{ {
Renderer = SDL_CreateRenderer(Window, std::string error = SDL_GetError();
-1, Logger::Write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error);
SDL_RENDERER_ACCELERATED); retVal = false;
}
}
if (Renderer == NULL) if(retVal)
{ {
std::string error = SDL_GetError(); Renderer = SDL_CreateRenderer(Window,
Logger::Write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error); -1,
retVal = false; SDL_RENDERER_ACCELERATED);
}
}
if(retVal) if (Renderer == NULL)
{ {
Mutex = SDL_CreateMutex(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error);
retVal = false;
}
}
if (Mutex == NULL) if(retVal)
{ {
std::string error = SDL_GetError(); Mutex = SDL_CreateMutex();
Logger::Write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error);
retVal = false;
}
}
//todo: specify in configuration file if (Mutex == NULL)
if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1) {
{ std::string error = SDL_GetError();
std::string error = Mix_GetError(); Logger::Write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error);
Logger::Write(Logger::ZONE_ERROR, "SDL", "Audio initialize failed: " + error); retVal = false;
retVal = false; }
} }
return retVal; //todo: specify in configuration file
if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1)
{
std::string error = Mix_GetError();
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(); std::string error = SDL_GetError();
Logger::Write(Logger::ZONE_DEBUG, "SDL", "DeInitializing"); Logger::Write(Logger::ZONE_DEBUG, "SDL", "DeInitializing");
Mix_CloseAudio(); Mix_CloseAudio();
Mix_Quit(); Mix_Quit();
if(Mutex) if(Mutex)
{ {
SDL_DestroyMutex(Mutex); SDL_DestroyMutex(Mutex);
Mutex = NULL; Mutex = NULL;
} }
if(Renderer) if(Renderer)
{ {
SDL_DestroyRenderer(Renderer); SDL_DestroyRenderer(Renderer);
Renderer = NULL; Renderer = NULL;
} }
if(Window) if(Window)
{ {
SDL_DestroyWindow(Window); SDL_DestroyWindow(Window);
Window = NULL; Window = NULL;
} }
SDL_ShowCursor(SDL_TRUE); SDL_ShowCursor(SDL_TRUE);
SDL_Quit(); SDL_Quit();
return true; return true;
} }
SDL_Renderer* SDL::GetRenderer() SDL_Renderer* SDL::GetRenderer()
{ {
return Renderer; return Renderer;
} }
SDL_mutex* SDL::GetMutex() SDL_mutex* SDL::GetMutex()
{ {
return Mutex; return Mutex;
} }
SDL_Window* SDL::GetWindow() SDL_Window* SDL::GetWindow()
{ {
return Window; return Window;
} }
bool SDL::RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle) bool SDL::RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle)
{ {
SDL_Rect rotateRect; SDL_Rect rotateRect;
rotateRect.w = dest->w; rotateRect.w = dest->w;
rotateRect.h = dest->h; rotateRect.h = dest->h;
if(Fullscreen) if(Fullscreen)
{ {
rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2; rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2;
rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2; rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2;
} }
else else
{ {
rotateRect.x = dest->x; rotateRect.x = dest->x;
rotateRect.y = dest->y; rotateRect.y = dest->y;
} }
SDL_SetTextureAlphaMod(texture, transparency); SDL_SetTextureAlphaMod(texture, transparency);
SDL_RenderCopyEx(GetRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE); SDL_RenderCopyEx(GetRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE);
return true; return true;
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
@@ -10,23 +10,32 @@ class Configuration;
class SDL class SDL
{ {
public: public:
static bool Initialize(Configuration *config); static bool Initialize(Configuration *config);
static bool DeInitialize(); static bool DeInitialize();
static SDL_Renderer *GetRenderer(); static SDL_Renderer *GetRenderer();
static SDL_mutex *GetMutex(); static SDL_mutex *GetMutex();
static SDL_Window *GetWindow(); static SDL_Window *GetWindow();
static bool RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle); static bool RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle);
static int GetWindowWidth() { return WindowWidth; } static int GetWindowWidth()
static int GetWindowHeight() { return WindowHeight; } {
static bool IsFullscreen() { return Fullscreen; } return WindowWidth;
}
static int GetWindowHeight()
{
return WindowHeight;
}
static bool IsFullscreen()
{
return Fullscreen;
}
private: private:
static SDL_Window *Window; static SDL_Window *Window;
static SDL_Renderer *Renderer; static SDL_Renderer *Renderer;
static SDL_mutex *Mutex; static SDL_mutex *Mutex;
static int DisplayWidth; static int DisplayWidth;
static int DisplayHeight; static int DisplayHeight;
static int WindowWidth; static int WindowWidth;
static int WindowHeight; static int WindowHeight;
static bool Fullscreen; static bool Fullscreen;
}; };

View File

@@ -1,54 +1,54 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "Sound.h" #include "Sound.h"
#include "../Utility/Log.h" #include "../Utility/Log.h"
Sound::Sound(std::string file) Sound::Sound(std::string file)
: File(file) : File(file)
, Chunk(NULL) , Chunk(NULL)
{ {
if(!Allocate()) if(!Allocate())
{ {
Logger::Write(Logger::ZONE_ERROR, "Sound", "Cannot load " + File); Logger::Write(Logger::ZONE_ERROR, "Sound", "Cannot load " + File);
} }
} }
Sound::~Sound() Sound::~Sound()
{ {
if(Chunk) if(Chunk)
{ {
Mix_FreeChunk(Chunk); Mix_FreeChunk(Chunk);
Chunk = NULL; Chunk = NULL;
} }
} }
void Sound::Play() void Sound::Play()
{ {
if(Chunk) if(Chunk)
{ {
(void)Mix_PlayChannel(-1, Chunk, 0); (void)Mix_PlayChannel(-1, Chunk, 0);
} }
} }
bool Sound::Free() bool Sound::Free()
{ {
if(Chunk) if(Chunk)
{ {
Mix_FreeChunk(Chunk); Mix_FreeChunk(Chunk);
Chunk = NULL; Chunk = NULL;
} }
return true; return true;
} }
bool Sound::Allocate() bool Sound::Allocate()
{ {
if(!Chunk) if(!Chunk)
{ {
Chunk = Mix_LoadWAV(File.c_str()); Chunk = Mix_LoadWAV(File.c_str());
} }
return (Chunk != NULL); return (Chunk != NULL);
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include <string> #include <string>
@@ -8,12 +8,12 @@
class Sound class Sound
{ {
public: public:
Sound(std::string file); Sound(std::string file);
virtual ~Sound(); virtual ~Sound();
void Play(); void Play();
bool Allocate(); bool Allocate();
bool Free(); bool Free();
private: private:
std::string File; std::string File;
Mix_Chunk *Chunk; Mix_Chunk *Chunk;
}; };

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "Log.h" #include "Log.h"
#include <iostream> #include <iostream>
@@ -12,53 +12,53 @@ std::streambuf *Logger::CoutStream = NULL;
bool Logger::Initialize(std::string file) bool Logger::Initialize(std::string file)
{ {
WriteFileStream.open(file.c_str()); WriteFileStream.open(file.c_str());
CerrStream = std::cerr.rdbuf(WriteFileStream.rdbuf()); CerrStream = std::cerr.rdbuf(WriteFileStream.rdbuf());
CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf()); CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf());
return WriteFileStream.is_open(); return WriteFileStream.is_open();
} }
void Logger::DeInitialize() void Logger::DeInitialize()
{ {
if(WriteFileStream.is_open()) if(WriteFileStream.is_open())
{ {
WriteFileStream.close(); WriteFileStream.close();
} }
std::cerr.rdbuf(CerrStream); std::cerr.rdbuf(CerrStream);
std::cout.rdbuf(CoutStream); std::cout.rdbuf(CoutStream);
} }
void Logger::Write(Zone zone, std::string component, std::string message) void Logger::Write(Zone zone, std::string component, std::string message)
{ {
std::string zoneStr; std::string zoneStr;
switch(zone) switch(zone)
{ {
case ZONE_INFO: case ZONE_INFO:
zoneStr = "INFO"; zoneStr = "INFO";
break; break;
case ZONE_DEBUG: case ZONE_DEBUG:
zoneStr = "DEBUG"; zoneStr = "DEBUG";
break; break;
case ZONE_WARNING: case ZONE_WARNING:
zoneStr = "WARNING"; zoneStr = "WARNING";
break; break;
case ZONE_ERROR: case ZONE_ERROR:
zoneStr = "ERROR"; zoneStr = "ERROR";
break; break;
} }
std::time_t rawtime = std::time(NULL); std::time_t rawtime = std::time(NULL);
struct tm* timeinfo = std::localtime(&rawtime); struct tm* timeinfo = std::localtime(&rawtime);
static char timeStr[60]; static char timeStr[60];
std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", timeinfo); std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", timeinfo);
std::stringstream ss; std::stringstream ss;
ss << "[" << timeStr << "] [" << zoneStr << "] [" << component << "] " << message << std::endl; ss << "[" << timeStr << "] [" << zoneStr << "] [" << component << "] " << message << std::endl;
std::cout << ss.str(); std::cout << ss.str();
} }

View File

@@ -1,5 +1,5 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
@@ -12,20 +12,20 @@
class Logger class Logger
{ {
public: public:
enum Zone enum Zone
{ {
ZONE_DEBUG, ZONE_DEBUG,
ZONE_INFO, ZONE_INFO,
ZONE_WARNING, ZONE_WARNING,
ZONE_ERROR ZONE_ERROR
}; };
static bool Initialize(std::string file); static bool Initialize(std::string file);
static void Write(Zone zone, std::string component, std::string message); static void Write(Zone zone, std::string component, std::string message);
static void DeInitialize(); static void DeInitialize();
private: private:
static std::streambuf *CerrStream; static std::streambuf *CerrStream;
static std::streambuf *CoutStream; static std::streambuf *CoutStream;
static std::ofstream WriteFileStream; static std::ofstream WriteFileStream;
}; };

View File

@@ -20,112 +20,112 @@ Utils::~Utils()
bool Utils::FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file) bool Utils::FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file)
{ {
for(unsigned int i = 0; i < extensions.size(); ++i) for(unsigned int i = 0; i < extensions.size(); ++i)
{ {
std::string temp = prefix + "." + extensions[i]; std::string temp = prefix + "." + extensions[i];
temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp); temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp);
std::ifstream f(temp.c_str()); std::ifstream f(temp.c_str());
if (f.good()) if (f.good())
{ {
file = temp; file = temp;
return true; return true;
} }
} }
return false; return false;
} }
std::string Utils::Replace( std::string Utils::Replace(
std::string subject, std::string subject,
const std::string& search, const std::string& search,
const std::string& replace) const std::string& replace)
{ {
size_t pos = 0; size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) while ((pos = subject.find(search, pos)) != std::string::npos)
{ {
subject.replace(pos, search.length(), replace); subject.replace(pos, search.length(), replace);
pos += replace.length(); pos += replace.length();
} }
return subject; return subject;
} }
float Utils::ConvertFloat(std::string content) float Utils::ConvertFloat(std::string content)
{ {
float retVal = 0; float retVal = 0;
std::stringstream ss; std::stringstream ss;
ss << content; ss << content;
ss >> retVal; ss >> retVal;
return retVal; return retVal;
} }
int Utils::ConvertInt(std::string content) int Utils::ConvertInt(std::string content)
{ {
int retVal = 0; int retVal = 0;
std::stringstream ss; std::stringstream ss;
ss << content; ss << content;
ss >> retVal; ss >> retVal;
return retVal; return retVal;
} }
void Utils::NormalizeBackSlashes(std::string& content) void Utils::NormalizeBackSlashes(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)
{ {
NormalizeBackSlashes(filePath); NormalizeBackSlashes(filePath);
std::string directory = filePath; std::string directory = filePath;
const size_t last_slash_idx = filePath.rfind('/'); const size_t last_slash_idx = filePath.rfind('/');
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
{ {
directory = filePath.substr(0, last_slash_idx); directory = filePath.substr(0, last_slash_idx);
} }
return directory; return directory;
} }
std::string Utils::GetParentDirectory(std::string directory) std::string Utils::GetParentDirectory(std::string directory)
{ {
NormalizeBackSlashes(directory); NormalizeBackSlashes(directory);
size_t last_slash_idx = directory.find_last_of('/'); size_t last_slash_idx = directory.find_last_of('/');
if(directory.length() - 1 == last_slash_idx) if(directory.length() - 1 == last_slash_idx)
{ {
directory = directory.erase(last_slash_idx, directory.length()-1); directory = directory.erase(last_slash_idx, directory.length()-1);
last_slash_idx = directory.find_last_of('/'); last_slash_idx = directory.find_last_of('/');
} }
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
{ {
directory = directory.erase(last_slash_idx, directory.length()); directory = directory.erase(last_slash_idx, directory.length());
} }
return directory; return directory;
} }
std::string Utils::GetFileName(std::string filePath) std::string Utils::GetFileName(std::string filePath)
{ {
NormalizeBackSlashes(filePath); NormalizeBackSlashes(filePath);
std::string filename = filePath; std::string filename = filePath;
const size_t last_slash_idx = filePath.rfind('/'); const size_t last_slash_idx = filePath.rfind('/');
if (std::string::npos != last_slash_idx) if (std::string::npos != last_slash_idx)
{ {
filename = filePath.erase(0, last_slash_idx+1); filename = filePath.erase(0, last_slash_idx+1);
} }
return filename; return filename;
} }

View File

@@ -9,18 +9,18 @@
class Utils class Utils
{ {
public: public:
static std::string Replace(std::string subject, const std::string& search, static std::string Replace(std::string subject, const std::string& search,
const std::string& replace); const std::string& replace);
static float ConvertFloat(std::string content); static float ConvertFloat(std::string content);
static int ConvertInt(std::string content); static int ConvertInt(std::string content);
static void NormalizeBackSlashes(std::string &content); static void NormalizeBackSlashes(std::string &content);
static std::string GetDirectory(std::string filePath); static std::string GetDirectory(std::string filePath);
static std::string GetParentDirectory(std::string filePath); static std::string GetParentDirectory(std::string filePath);
static std::string GetFileName(std::string filePath); static std::string GetFileName(std::string filePath);
static bool FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file); static bool FindMatchingFile(std::string prefix, std::vector<std::string> &extensions, std::string &file);
private: private:
Utils(); Utils();
virtual ~Utils(); virtual ~Utils();
}; };

View File

@@ -22,16 +22,16 @@
std::string Version::GetString() std::string Version::GetString()
{ {
std::stringstream version; std::stringstream version;
version << RETROFE_VERSION_MAJOR; version << RETROFE_VERSION_MAJOR;
version << "."; version << ".";
version << RETROFE_VERSION_MINOR; version << RETROFE_VERSION_MINOR;
version << "."; version << ".";
version << RETROFE_VERSION_BUILD; version << RETROFE_VERSION_BUILD;
#ifdef RETROFE_VERSION_BETA #ifdef RETROFE_VERSION_BETA
version << "-beta"; version << "-beta";
#endif #endif
return version.str(); return version.str();
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
#include <string> #include <string>
@@ -8,5 +8,5 @@
class Version class Version
{ {
public: public:
static std::string GetString(); static std::string GetString();
}; };

View File

@@ -23,329 +23,329 @@ bool GStreamerVideo::Initialized = false;
// MUST match video size // MUST match video size
gboolean GStreamerVideo::BusCallback(GstBus *bus, GstMessage *msg, gpointer data) gboolean GStreamerVideo::BusCallback(GstBus *bus, GstMessage *msg, gpointer data)
{ {
// this callback only needs to be defined so we can loop the video once it completes // this callback only needs to be defined so we can loop the video once it completes
return TRUE; return TRUE;
} }
GStreamerVideo::GStreamerVideo() GStreamerVideo::GStreamerVideo()
: Playbin(NULL) : Playbin(NULL)
, VideoBin(NULL) , VideoBin(NULL)
, VideoSink(NULL) , VideoSink(NULL)
, VideoConvert(NULL) , VideoConvert(NULL)
, VideoConvertCaps(NULL) , VideoConvertCaps(NULL)
, VideoBus(NULL) , VideoBus(NULL)
, Texture(NULL) , Texture(NULL)
, Height(0) , Height(0)
, Width(0) , Width(0)
, VideoBuffer(NULL) , VideoBuffer(NULL)
, FrameReady(false) , FrameReady(false)
, IsPlaying(false) , IsPlaying(false)
, PlayCount(0) , PlayCount(0)
, NumLoops(0) , NumLoops(0)
{ {
} }
GStreamerVideo::~GStreamerVideo() GStreamerVideo::~GStreamerVideo()
{ {
Stop(); Stop();
} }
void GStreamerVideo::SetNumLoops(int n) void GStreamerVideo::SetNumLoops(int n)
{ {
NumLoops = n; NumLoops = n;
} }
SDL_Texture *GStreamerVideo::GetTexture() const SDL_Texture *GStreamerVideo::GetTexture() const
{ {
return Texture; return Texture;
} }
void GStreamerVideo::ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *new_pad, gpointer userdata) void GStreamerVideo::ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *new_pad, gpointer userdata)
{ {
GStreamerVideo *video = (GStreamerVideo *)userdata; GStreamerVideo *video = (GStreamerVideo *)userdata;
GstMapInfo map; GstMapInfo map;
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
if (!video->FrameReady && video && video->IsPlaying && gst_buffer_map (buf, &map, GST_MAP_READ)) if (!video->FrameReady && video && video->IsPlaying && gst_buffer_map (buf, &map, GST_MAP_READ))
{ {
if(!video->Width || !video->Height) if(!video->Width || !video->Height)
{ {
GstCaps *caps = gst_pad_get_current_caps (new_pad); GstCaps *caps = gst_pad_get_current_caps (new_pad);
GstStructure *s = gst_caps_get_structure(caps, 0); GstStructure *s = gst_caps_get_structure(caps, 0);
gst_structure_get_int(s, "width", &video->Width); gst_structure_get_int(s, "width", &video->Width);
gst_structure_get_int(s, "height", &video->Height); gst_structure_get_int(s, "height", &video->Height);
} }
if(video->Height && video->Width) if(video->Height && video->Width)
{ {
if(!video->VideoBuffer) if(!video->VideoBuffer)
{ {
video->VideoBuffer = new char[map.size]; video->VideoBuffer = new char[map.size];
} }
memcpy(video->VideoBuffer, map.data, map.size); memcpy(video->VideoBuffer, map.data, map.size);
gst_buffer_unmap(buf, &map); gst_buffer_unmap(buf, &map);
video->FrameReady = true; video->FrameReady = true;
} }
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
} }
bool GStreamerVideo::Initialize() bool GStreamerVideo::Initialize()
{ {
bool retVal = true; bool retVal = true;
std::string path = Configuration::GetAbsolutePath() + "/Core"; std::string path = Configuration::GetAbsolutePath() + "/Core";
gst_init(NULL, NULL); gst_init(NULL, NULL);
GstRegistry *registry = gst_registry_get(); GstRegistry *registry = gst_registry_get();
gst_registry_scan_path(registry, path.c_str()); gst_registry_scan_path(registry, path.c_str());
Initialized = true; Initialized = true;
return retVal; return retVal;
} }
bool GStreamerVideo::DeInitialize() bool GStreamerVideo::DeInitialize()
{ {
gst_deinit(); gst_deinit();
Initialized = false; Initialized = false;
return true; return true;
} }
bool GStreamerVideo::Stop() bool GStreamerVideo::Stop()
{ {
if(!Initialized) if(!Initialized)
{ {
return false; return false;
} }
if(VideoSink) if(VideoSink)
{ {
g_object_set(G_OBJECT(VideoSink), "signal-handoffs", FALSE, NULL); g_object_set(G_OBJECT(VideoSink), "signal-handoffs", FALSE, NULL);
} }
if(Playbin) if(Playbin)
{ {
(void)gst_element_set_state(Playbin, GST_STATE_NULL); (void)gst_element_set_state(Playbin, GST_STATE_NULL);
} }
FreeElements(); FreeElements();
IsPlaying = false; IsPlaying = false;
if(Texture) if(Texture)
{ {
SDL_DestroyTexture(Texture); SDL_DestroyTexture(Texture);
Texture = NULL; Texture = NULL;
} }
IsPlaying = false; IsPlaying = false;
Height = 0; Height = 0;
Width = 0; Width = 0;
FrameReady = false; FrameReady = false;
if(VideoBuffer) if(VideoBuffer)
{ {
delete VideoBuffer; delete VideoBuffer;
VideoBuffer = NULL; VideoBuffer = NULL;
} }
return true; return true;
} }
bool GStreamerVideo::Play(std::string file) bool GStreamerVideo::Play(std::string file)
{ {
PlayCount = 0; PlayCount = 0;
if(!Initialized) if(!Initialized)
{ {
return false; return false;
} }
CurrentFile = file; CurrentFile = file;
const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL); const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL);
if(!uriFile) if(!uriFile)
{ {
return false; return false;
} }
else else
{ {
Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file); Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file);
file = uriFile; file = uriFile;
// Pipeline = gst_pipeline_new("pipeline"); // Pipeline = gst_pipeline_new("pipeline");
Playbin = gst_element_factory_make("playbin", "player"); Playbin = gst_element_factory_make("playbin", "player");
VideoBin = gst_bin_new("SinkBin"); VideoBin = gst_bin_new("SinkBin");
VideoSink = gst_element_factory_make("fakesink", "video_sink"); VideoSink = gst_element_factory_make("fakesink", "video_sink");
VideoConvert = gst_element_factory_make("capsfilter", "video_convert"); VideoConvert = gst_element_factory_make("capsfilter", "video_convert");
VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2"); VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2");
Height = 0; Height = 0;
Width = 0; Width = 0;
if(!Playbin) if(!Playbin)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin");
FreeElements(); FreeElements();
return false; return false;
} }
if(!VideoSink) if(!VideoSink)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink");
FreeElements(); FreeElements();
return false; return false;
} }
if(!VideoConvert) if(!VideoConvert)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter");
FreeElements(); FreeElements();
return false; return false;
} }
if(!VideoConvertCaps) if(!VideoConvertCaps)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps");
FreeElements(); FreeElements();
return false; return false;
} }
gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL); gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL);
gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps); gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps);
GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink"); GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink");
if(!videoConvertSinkPad) if(!videoConvertSinkPad)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad");
FreeElements(); FreeElements();
return false; return false;
} }
g_object_set(G_OBJECT(VideoSink), "sync", TRUE, "qos", TRUE, NULL); g_object_set(G_OBJECT(VideoSink), "sync", TRUE, "qos", TRUE, NULL);
GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad); GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad);
if(!videoSinkPad) if(!videoSinkPad)
{ {
Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad"); Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad");
FreeElements(); FreeElements();
gst_object_unref(videoConvertSinkPad); gst_object_unref(videoConvertSinkPad);
videoConvertSinkPad = NULL; videoConvertSinkPad = NULL;
return false; return false;
} }
gst_element_add_pad(VideoBin, videoSinkPad); gst_element_add_pad(VideoBin, videoSinkPad);
gst_object_unref(videoConvertSinkPad); gst_object_unref(videoConvertSinkPad);
videoConvertSinkPad = NULL; videoConvertSinkPad = NULL;
g_object_set(G_OBJECT(Playbin), "uri", file.c_str(), "video-sink", VideoBin, NULL); g_object_set(G_OBJECT(Playbin), "uri", file.c_str(), "video-sink", VideoBin, NULL);
IsPlaying = true; IsPlaying = true;
g_object_set(G_OBJECT(VideoSink), "signal-handoffs", TRUE, NULL); g_object_set(G_OBJECT(VideoSink), "signal-handoffs", TRUE, NULL);
g_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this); g_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this);
VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin)); VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin));
gst_bus_add_watch(VideoBus, &BusCallback, this); gst_bus_add_watch(VideoBus, &BusCallback, this);
/* Start playing */ /* Start playing */
GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(Playbin), GST_STATE_PLAYING); GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(Playbin), GST_STATE_PLAYING);
if (playState != GST_STATE_CHANGE_ASYNC) if (playState != GST_STATE_CHANGE_ASYNC)
{ {
IsPlaying = false; IsPlaying = false;
std::stringstream ss; std::stringstream ss;
ss << "Unable to set the pipeline to the playing state: "; ss << "Unable to set the pipeline to the playing state: ";
ss << playState; ss << playState;
Logger::Write(Logger::ZONE_ERROR, "Video", ss.str()); Logger::Write(Logger::ZONE_ERROR, "Video", ss.str());
FreeElements(); FreeElements();
return false; return false;
} }
} }
return true; return true;
} }
void GStreamerVideo::FreeElements() void GStreamerVideo::FreeElements()
{ {
if(VideoBin) if(VideoBin)
{ {
gst_object_unref(VideoBin); gst_object_unref(VideoBin);
VideoBin = NULL; VideoBin = NULL;
} }
if(VideoSink) if(VideoSink)
{ {
gst_object_unref(VideoSink); gst_object_unref(VideoSink);
VideoSink = NULL; VideoSink = NULL;
} }
if(VideoConvert) if(VideoConvert)
{ {
gst_object_unref(VideoConvert); gst_object_unref(VideoConvert);
VideoConvert = NULL; VideoConvert = NULL;
} }
if(VideoConvertCaps) if(VideoConvertCaps)
{ {
gst_object_unref(VideoConvertCaps); gst_object_unref(VideoConvertCaps);
VideoConvertCaps = NULL; VideoConvertCaps = NULL;
} }
if(Playbin) if(Playbin)
{ {
gst_object_unref(Playbin); gst_object_unref(Playbin);
Playbin = NULL; Playbin = NULL;
} }
} }
void GStreamerVideo::Draw() void GStreamerVideo::Draw()
{ {
FrameReady = false; FrameReady = false;
} }
void GStreamerVideo::Update(float dt) void GStreamerVideo::Update(float dt)
{ {
SDL_LockMutex(SDL::GetMutex()); SDL_LockMutex(SDL::GetMutex());
if(!Texture && Width != 0 && Height != 0) if(!Texture && Width != 0 && Height != 0)
{ {
Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2, Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2,
SDL_TEXTUREACCESS_STREAMING, Width, Height); SDL_TEXTUREACCESS_STREAMING, Width, Height);
SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND);
} }
if(VideoBuffer && FrameReady && Texture && Width && Height) if(VideoBuffer && FrameReady && Texture && Width && Height)
{ {
//todo: change to width of cap //todo: change to width of cap
void *pixels; void *pixels;
int pitch; int pitch;
SDL_LockTexture(Texture, NULL, &pixels, &pitch); SDL_LockTexture(Texture, NULL, &pixels, &pitch);
memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number
SDL_UnlockTexture(Texture); SDL_UnlockTexture(Texture);
} }
SDL_UnlockMutex(SDL::GetMutex()); SDL_UnlockMutex(SDL::GetMutex());
if(VideoBus) if(VideoBus)
{ {
GstMessage *msg = gst_bus_pop(VideoBus); GstMessage *msg = gst_bus_pop(VideoBus);
if(msg) if(msg)
{ {
if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS) if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS)
{
Logger::Write(Logger::ZONE_ERROR, "Video", "EOS!");
PlayCount++;
//todo: nesting hazard
// if number of loops is 0, set to infinite (todo: this is misleading, rename variable)
if(!NumLoops || NumLoops > PlayCount)
{ {
gst_element_seek(Playbin, Logger::Write(Logger::ZONE_ERROR, "Video", "EOS!");
1.0,
GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH,
GST_SEEK_TYPE_SET,
0,
GST_SEEK_TYPE_NONE,
GST_CLOCK_TIME_NONE);
}
}
gst_message_unref(msg); PlayCount++;
}
} //todo: nesting hazard
// if number of loops is 0, set to infinite (todo: this is misleading, rename variable)
if(!NumLoops || NumLoops > PlayCount)
{
gst_element_seek(Playbin,
1.0,
GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH,
GST_SEEK_TYPE_SET,
0,
GST_SEEK_TYPE_NONE,
GST_CLOCK_TIME_NONE);
}
}
gst_message_unref(msg);
}
}
} }

View File

@@ -15,36 +15,36 @@ extern "C"
class GStreamerVideo : public IVideo class GStreamerVideo : public IVideo
{ {
public: public:
GStreamerVideo(); GStreamerVideo();
~GStreamerVideo(); ~GStreamerVideo();
bool Initialize(); bool Initialize();
bool Play(std::string file); bool Play(std::string file);
bool Stop(); bool Stop();
bool DeInitialize(); bool DeInitialize();
SDL_Texture *GetTexture() const; SDL_Texture *GetTexture() const;
void Update(float dt); void Update(float dt);
void Draw(); void Draw();
void SetNumLoops(int n); void SetNumLoops(int n);
void FreeElements(); void FreeElements();
private: private:
static void ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data); static void ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data);
static gboolean BusCallback(GstBus *bus, GstMessage *msg, gpointer data); static gboolean BusCallback(GstBus *bus, GstMessage *msg, gpointer data);
GstElement *Playbin; GstElement *Playbin;
GstElement *VideoBin; GstElement *VideoBin;
GstElement *VideoSink; GstElement *VideoSink;
GstElement *VideoConvert; GstElement *VideoConvert;
GstCaps *VideoConvertCaps; GstCaps *VideoConvertCaps;
GstBus *VideoBus; GstBus *VideoBus;
SDL_Texture* Texture; SDL_Texture* Texture;
gint Height; gint Height;
gint Width; gint Width;
char *VideoBuffer; char *VideoBuffer;
bool FrameReady; bool FrameReady;
bool IsPlaying; bool IsPlaying;
static bool Initialized; static bool Initialized;
int PlayCount; int PlayCount;
std::string CurrentFile; std::string CurrentFile;
int NumLoops; int NumLoops;
}; };

View File

@@ -9,12 +9,12 @@
class IVideo class IVideo
{ {
public: public:
virtual ~IVideo() {} virtual ~IVideo() {}
virtual bool Initialize() = 0; virtual bool Initialize() = 0;
virtual bool Play(std::string file) = 0; virtual bool Play(std::string file) = 0;
virtual bool Stop() = 0; virtual bool Stop() = 0;
virtual bool DeInitialize() = 0; virtual bool DeInitialize() = 0;
virtual SDL_Texture *GetTexture() const = 0; virtual SDL_Texture *GetTexture() const = 0;
virtual void Update(float dt) = 0; virtual void Update(float dt) = 0;
virtual void Draw() = 0; virtual void Draw() = 0;
}; };

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#include "VideoFactory.h" #include "VideoFactory.h"
#include "IVideo.h" #include "IVideo.h"
#include "GStreamerVideo.h" #include "GStreamerVideo.h"
@@ -10,24 +10,24 @@ int VideoFactory::NumLoops = 0;
IVideo *VideoFactory::CreateVideo() IVideo *VideoFactory::CreateVideo()
{ {
IVideo *instance = NULL; IVideo *instance = NULL;
if(Enabled) if(Enabled)
{ {
instance = new GStreamerVideo(); instance = new GStreamerVideo();
instance->Initialize(); instance->Initialize();
((GStreamerVideo *)(instance))->SetNumLoops(NumLoops); ((GStreamerVideo *)(instance))->SetNumLoops(NumLoops);
} }
return instance; return instance;
} }
void VideoFactory::SetEnabled(bool enabled) void VideoFactory::SetEnabled(bool enabled)
{ {
Enabled = enabled; Enabled = enabled;
} }
void VideoFactory::SetNumLoops(int numLoops) void VideoFactory::SetNumLoops(int numLoops)
{ {
NumLoops = numLoops; NumLoops = numLoops;
} }

View File

@@ -1,6 +1,6 @@
/* This file is subject to the terms and conditions defined in /* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package. * file 'LICENSE.txt', which is part of this source code package.
*/ */
#pragma once #pragma once
class IVideo; class IVideo;
@@ -8,11 +8,11 @@ class IVideo;
class VideoFactory class VideoFactory
{ {
public: public:
IVideo *CreateVideo(); IVideo *CreateVideo();
static void SetEnabled(bool enabled); static void SetEnabled(bool enabled);
static void SetNumLoops(int numLoops); static void SetNumLoops(int numLoops);
private: private:
static bool Enabled; static bool Enabled;
static int NumLoops; static int NumLoops;
}; };

View File

@@ -2,11 +2,11 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include <Utility/Utils.h> #include <Utility/Utils.h>
class UtilsTest : public ::testing::Test class UtilsTest : public ::testing::Test
{ {
}; };
TEST_F(UtilsTest, ConvertsStringToInt) TEST_F(UtilsTest, ConvertsStringToInt)
{ {
ASSERT_EQ(5, Utils::ConvertInt("5")); ASSERT_EQ(5, Utils::ConvertInt("5"));
} }