Fixed the god-awful indentation

This commit is contained in:
mathusummut
2018-05-06 00:01:36 +02:00
parent 643e3820f5
commit 35b7b1f1a6
459 changed files with 204893 additions and 217545 deletions

View File

@@ -16,13 +16,15 @@
using std::string;
namespace Shared{ namespace CompressionUtil{
namespace Shared {
namespace CompressionUtil {
bool compressFileToZIPFile(string inFile, string outFile, int compressionLevel=5);
bool extractFileFromZIPFile(string inFile, string outFile);
std::pair<unsigned char *,unsigned long> compressMemoryToMemory(unsigned char *input, unsigned long input_len, int compressionLevel=5);
std::pair<unsigned char *,unsigned long> extractMemoryToMemory(unsigned char *input, unsigned long input_len, unsigned long max_output_len);
bool compressFileToZIPFile(string inFile, string outFile, int compressionLevel = 5);
bool extractFileFromZIPFile(string inFile, string outFile);
std::pair<unsigned char *, unsigned long> compressMemoryToMemory(unsigned char *input, unsigned long input_len, int compressionLevel = 5);
std::pair<unsigned char *, unsigned long> extractMemoryToMemory(unsigned char *input, unsigned long input_len, unsigned long max_output_len);
}};
}
};
#endif

View File

@@ -26,12 +26,11 @@
#define FTP_H_
/**
* @brief specifies the type of operation that is in progress
*/
typedef enum
{
OP_NOP = 0, ///< no operation
/**
* @brief specifies the type of operation that is in progress
*/
typedef enum {
OP_NOP = 0, ///< no operation
OP_RETR = 1, ///< RETR command
OP_STOR = 2, ///< STOR command
OP_LIST = 3 ///< LIST command
@@ -41,8 +40,7 @@ typedef enum
* @brief infos about a file/directory transmittion
* @see ftpExecTransmission
*/
typedef struct
{
typedef struct {
operation_E op; ///< active transmission
void* fsHandle; ///< file or directory handle of current transmission
socket_t dataSocket; ///< data socket of current transmission
@@ -53,8 +51,7 @@ typedef struct
/**
* @brief Data of a ftp session
*/
typedef struct
{
typedef struct {
int open; ///< TRUE, if the session is open
int authenticated; ///< TRUE, if user is authenticated via USER and PASS commands
int userId; ///< id of the dedicated user account, is 0 until execution of USER command
@@ -79,18 +76,16 @@ typedef struct
/**
* @brief format in which a message is to be displayed
*/
typedef enum
{
MSG_NORMAL = 0, ///< normal message, no translation
MSG_QUOTE = 1, ///< message will be displayed between doublequotes
typedef enum {
MSG_NORMAL = 0, ///< normal message, no translation
MSG_QUOTE = 1, ///< message will be displayed between doublequotes
MSG_MULTILINE = 2 ///< message contains multiple lines
}msgmode_E;
/**
* @brief time-structure
*/
typedef struct
{
typedef struct {
uint16_t year; ///< year 0000-9999
uint8_t month; ///< month 1 - 12
uint8_t day; ///< day 1 - 31
@@ -103,10 +98,9 @@ typedef struct
/**
* @brief type of a file
*/
typedef enum
{
typedef enum {
TYPE_FILE = 1, ///< regular file
TYPE_DIR = 2, ///< directory
TYPE_DIR = 2, ///< directory
TYPE_LINK = 4 ///< hard link
}ftpFileType_E;
@@ -114,8 +108,7 @@ typedef enum
/**
* @brief infos about a file or directory similar to stat
*/
typedef struct
{
typedef struct {
ftpFileType_E type; ///< filetype
uint16_t mode; ///< access rights (currently unused)
ftpTime_S cTime; ///< creation time (currently unused)
@@ -171,7 +164,7 @@ extern int ftpStat(const char* path, ftpPathInfo_S *info);
# define ftpRemoveFile remove
#else
extern void* ftpOpenFile(const char *filename, const char *mode);
extern int ftpCloseFile(void *stream );
extern int ftpCloseFile(void *stream);
extern int ftpReadFile(void *buffer, size_t size, size_t count, void *stream);
extern int ftpWriteFile(const void *buffer, size_t size, size_t count, void *stream);
extern int ftpRemoveFile(const char* path);

View File

@@ -22,65 +22,65 @@
#ifndef FTPCONFIG_H_
#define FTPCONFIG_H_
/**
* @brief max. possible simultaneous FTP client connections
*/
/**
* @brief max. possible simultaneous FTP client connections
*/
#define MAX_CONNECTIONS 20
/**
* @brief max. possible user accounts
*/
/**
* @brief max. possible user accounts
*/
#define MAX_USERS 10
/**
* @brief max. length of a user account name
*/
/**
* @brief max. length of a user account name
*/
#define MAXLEN_USERNAME 40
/**
* @brief max. length of a user account password
*/
/**
* @brief max. length of a user account password
*/
#define MAXLEN_PASSWORD 40
/**
* @brief session timeout in seconds
*/
/**
* @brief session timeout in seconds
*/
#define SESSION_TIMEOUT 600
/**
* @brief maximum length of a complete directory path
*/
/**
* @brief maximum length of a complete directory path
*/
#define MAX_PATH_LEN 1024
/**
* @brief Size of the scratch buffer
*
* The scratch buffer is used for
* send / receive of files and directory listings
*/
/**
* @brief Size of the scratch buffer
*
* The scratch buffer is used for
* send / receive of files and directory listings
*/
#define LEN_SCRATCHBUF 1024
/**
* @brief Size of the receive buffer for ftp commands
*
* Buffer must be big enough to hold a complete ftp command.
* command (4) + space (1) + path (MAX_PATH_LEN) + quotes (2) + CRLF (2) + end of string (1)
*/
/**
* @brief Size of the receive buffer for ftp commands
*
* Buffer must be big enough to hold a complete ftp command.
* command (4) + space (1) + path (MAX_PATH_LEN) + quotes (2) + CRLF (2) + end of string (1)
*/
#define LEN_RXBUF (MAX_PATH_LEN + 10)
/**
* @brief activates ftp extentions according to RFC 3659
*/
/**
* @brief activates ftp extentions according to RFC 3659
*/
#define RFC3659 1
/**
* @brief set to 1 to activate debug messages on stdout
*/
//#define DBG_LOG 1
/**
* @brief set to 1 to activate debug messages on stdout
*/
//#define DBG_LOG 1
/**
* @brief set to 1 if target-plattform supports ANSI-C file-IO functions
*/
/**
* @brief set to 1 if target-plattform supports ANSI-C file-IO functions
*/
#define ANSI_FILE_IO 1
#endif /* FTPCONFIG_H_ */

View File

@@ -38,16 +38,16 @@
extern "C" {
#endif
void ftpInit(ftpFindExternalFTPServerIpType cb1, ftpAddUPNPPortForwardType cb2,
ftpRemoveUPNPPortForwardType cb3, ftpIsValidClientType cb4,
ftpIsClientAllowedToGetFileType cb5);
int ftpCreateAccount(const char* name, const char* passw, const char* root, int accRights);
int ftpDeleteAccount(const char* name);
int ftpStart(int portNumber);
int ftpShutdown(void);
int ftpExecute(void);
int ftpState(void);
void ftpSignalShutdown(void);
void ftpInit(ftpFindExternalFTPServerIpType cb1, ftpAddUPNPPortForwardType cb2,
ftpRemoveUPNPPortForwardType cb3, ftpIsValidClientType cb4,
ftpIsClientAllowedToGetFileType cb5);
int ftpCreateAccount(const char* name, const char* passw, const char* root, int accRights);
int ftpDeleteAccount(const char* name);
int ftpStart(int portNumber);
int ftpShutdown(void);
int ftpExecute(void);
int ftpState(void);
void ftpSignalShutdown(void);
#ifdef __cplusplus
}

View File

@@ -25,7 +25,7 @@
#define FTPTYPES_H_
// if the compiler is c99 complient, we don't need to define our own types
// if the compiler is c99 complient, we don't need to define our own types
#if __STDC_VERSION__ == 199901L || (defined(WIN32) && defined(_MSC_VER) && _MSC_VER >= 1600)
# include <stdint.h>
#else
@@ -48,9 +48,9 @@ typedef uint16_t port_t;
*/
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
/**
* @brief defines functions/variables local to a module
*/
/**
* @brief defines functions/variables local to a module
*/
#define LOCAL static
#ifndef FALSE
@@ -69,19 +69,19 @@ typedef uint16_t port_t;
extern "C" {
#endif
int VERBOSE_MODE_ENABLED;
int VERBOSE_MODE_ENABLED;
typedef ip_t (*ftpFindExternalFTPServerIpType)(ip_t clientIp);
typedef void (*ftpAddUPNPPortForwardType)(int internalPort, int externalPort);
typedef void (*ftpRemoveUPNPPortForwardType)(int internalPort, int externalPort);
typedef int (*ftpIsValidClientType)(ip_t clientIp);
typedef int (*ftpIsClientAllowedToGetFileType)(ip_t clientIp, const char *username, const char *filename);
typedef ip_t(*ftpFindExternalFTPServerIpType)(ip_t clientIp);
typedef void(*ftpAddUPNPPortForwardType)(int internalPort, int externalPort);
typedef void(*ftpRemoveUPNPPortForwardType)(int internalPort, int externalPort);
typedef int(*ftpIsValidClientType)(ip_t clientIp);
typedef int(*ftpIsClientAllowedToGetFileType)(ip_t clientIp, const char *username, const char *filename);
ftpFindExternalFTPServerIpType ftpFindExternalFTPServerIp;
ftpAddUPNPPortForwardType ftpAddUPNPPortForward;
ftpRemoveUPNPPortForwardType ftpRemoveUPNPPortForward;
ftpIsValidClientType ftpIsValidClient;
ftpIsClientAllowedToGetFileType ftpIsClientAllowedToGetFile;
ftpFindExternalFTPServerIpType ftpFindExternalFTPServerIp;
ftpAddUPNPPortForwardType ftpAddUPNPPortForward;
ftpRemoveUPNPPortForwardType ftpRemoveUPNPPortForward;
ftpIsValidClientType ftpIsValidClient;
ftpIsClientAllowedToGetFileType ftpIsClientAllowedToGetFile;
#ifdef __cplusplus
}

View File

@@ -20,16 +20,18 @@
#include "pixmap.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class BMPReader: FileReader<Pixmap2D> {
public:
BMPReader();
class BMPReader : FileReader<Pixmap2D> {
public:
BMPReader();
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
}} //end namespace
}
} //end namespace
#endif

View File

@@ -32,131 +32,308 @@ using Shared::PlatformCommon::extractExtension;
#define AS_STRING(...) #__VA_ARGS__
namespace Shared{
namespace Shared {
// =====================================================
// class FileReader
// =====================================================
// =====================================================
// class FileReader
// =====================================================
template <class T>
class FileReader {
public:
//string const * extensions;
std::vector<string> extensions;
template <class T>
class FileReader {
public:
//string const * extensions;
std::vector<string> extensions;
/**Creates a filereader being able to possibly load files
* from the specified extension
**/
//FileReader(string const * extensions);
FileReader(std::vector<string> extensions);
/**Creates a filereader being able to possibly load files
* from the specified extension
**/
//FileReader(string const * extensions);
FileReader(std::vector<string> extensions);
/**Creates a low-priority filereader
**/
FileReader();
/**Creates a low-priority filereader
**/
FileReader();
public:
/*Return the - existing and initialized - fileReadersMap
*/
static map<string, vector<FileReader<T> const * >* >& getFileReadersMap() {
static map<string, vector<FileReader<T> const * >* > fileReaderByExtension;
return fileReaderByExtension;
}
public:
/*Return the - existing and initialized - fileReadersMap
*/
static map<string, vector<FileReader<T> const * >* >& getFileReadersMap() {
static map<string, vector<FileReader<T> const * >* > fileReaderByExtension;
return fileReaderByExtension;
}
static vector<FileReader<T> const * >& getFileReaders() {
static vector<FileReader<T> const*> fileReaders;
return fileReaders;
static vector<FileReader<T> const * >& getFileReaders() {
static vector<FileReader<T> const*> fileReaders;
return fileReaders;
};
static vector<FileReader<T> const * >& getLowPriorityFileReaders() {
static vector<FileReader<T> const*> lowPriorityFileReaders;
return lowPriorityFileReaders;
};
public:
/**Tries to read a file
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
static T* readPath(const string& filepath);
/**Tries to read a file from an object
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
static T* readPath(const string& filepath, T* object);
/**Gives a quick estimation of whether the specified file
* can be read or not depending on the filename*/
virtual bool canRead(const string& filepath) const;
/**Gives a better estimation of whether the specified file
* can be read or not depending on the file content*/
virtual bool canRead(ifstream& file) const;
virtual void cleanupExtensions();
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(const string& filepath) const;
/**Reads a file to an object
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(const string& filepath, T* object) const;
/**Reads a file
* This method tries to read the specified file
* If it failes, either <code>null</code> is returned or an exception
* Default implementation generates an object using T()
* is thrown
*/
virtual T* read(ifstream& file, const string& path) const {
T* obj = new T();
T* ret = read(file, path, obj);
if (obj != ret) {
delete obj;
}
return ret;
}
/**Reads a file onto the specified object
* This method tries to read the specified file
* If it failes, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(ifstream& file, const string& path, T* former) const = 0;
virtual ~FileReader() {
cleanupExtensions();
}; //Well ... these objects aren't supposed to be destroyed
};
static vector<FileReader<T> const * >& getLowPriorityFileReaders() {
static vector<FileReader<T> const*> lowPriorityFileReaders;
return lowPriorityFileReaders;
};
template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath) {
//try to assign file
#if defined(WIN32) && !defined(__MINGW32__)
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
if (!file.is_open()) {
throw megaglest_runtime_error("[#1] Could not open file " + filepath);
}
for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
T* ret = NULL;
file.seekg(0, ios::beg); //Set position to first
try {
FileReader<T> const * reader = *i;
ret = reader->read(file, filepath); //It is guaranteed that at least the filepath matches ...
}
#if defined(WIN32)
catch (megaglest_runtime_error) {
#else
catch (megaglest_runtime_error &ex) {
#endif
throw;
} catch (...) {
continue;
}
if (ret != NULL) {
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if (fp) fclose(fp);
#endif
return ret;
}
}
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if (fp) fclose(fp);
#endif
return NULL;
}
public:
template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath, T* object) {
//try to assign file
#if defined(WIN32) && !defined(__MINGW32__)
wstring wstr = utf8_decode(filepath);
FILE *fp = _wfopen(wstr.c_str(), L"rb");
int fileErrno = errno;
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
if (!file.is_open()) {
#if defined(WIN32) && !defined(__MINGW32__)
DWORD error = GetLastError();
throw megaglest_runtime_error("[#2] Could not open file, result: " + intToStr(error) + " - " + intToStr(fileErrno) + " [" + filepath + "]");
#else
throw megaglest_runtime_error("[#2] Could not open file [" + filepath + "]");
#endif
}
for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
T* ret = NULL;
file.seekg(0, ios::beg); //Set position to first
try {
FileReader<T> const * reader = *i;
ret = reader->read(file, filepath, object); //It is guaranteed that at least the filepath matches ...
}
#if defined(WIN32)
catch (megaglest_runtime_error) {
#else
catch (megaglest_runtime_error &ex) {
#endif
throw;
} catch (...) {
continue;
}
if (ret != NULL) {
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if (fp) fclose(fp);
#endif
return ret;
}
}
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if (fp) fclose(fp);
#endif
return NULL;
}
/**Tries to read a file
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
static T* readPath(const string& filepath);
* is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath) {
const string& extension = extractExtension(filepath);
vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
if (possibleReaders != NULL) {
//Search in these possible readers
T* ret = readFromFileReaders(possibleReaders, filepath);
if (ret != NULL) {
return ret;
}
}
T* ret = readFromFileReaders(&(getFileReaders()), filepath); //Try all other
if (ret == NULL) {
std::cerr << "ERROR #1 - Could not parse filepath: " << filepath << std::endl;
throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
}
return ret;
}
/**Tries to read a file from an object
/**Tries to read a file
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
static T* readPath(const string& filepath, T* object);
* is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath, T* object) {
const string& extension = extractExtension(filepath);
vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
if (possibleReaders != NULL) {
//Search in these possible readers
T* ret = readFromFileReaders(possibleReaders, filepath, object);
if (ret != NULL) {
return ret;
}
}
T* ret = readFromFileReaders(&(getFileReaders()), filepath, object); //Try all other
if (ret == NULL) {
std::cerr << "ERROR #2 - Could not parse filepath: " << filepath << std::endl;
ret = readFromFileReaders(&(getLowPriorityFileReaders()), filepath); //Try to get dummy file
if (ret == NULL) {
throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
}
}
return ret;
}
template <typename T>
FileReader<T>::FileReader(std::vector<string> extensions) : extensions(extensions) {
getFileReaders().push_back(this);
std::vector<string> nextExtension = extensions;
for (unsigned int i = 0; i < nextExtension.size(); ++i) {
vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
if (curPossibleReaders == NULL) {
(getFileReadersMap())[nextExtension[i]] = (curPossibleReaders = new vector<FileReader<T> const *>());
}
curPossibleReaders->push_back(this);
}
}
template <typename T>
void FileReader<T>::cleanupExtensions() {
std::vector<string> nextExtension = extensions;
for (unsigned int i = 0; i < nextExtension.size(); ++i) {
vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
if (curPossibleReaders != NULL) {
delete curPossibleReaders;
(getFileReadersMap())[nextExtension[i]] = NULL;
}
}
}
/**Gives a quick estimation of whether the specified file
* can be read or not depending on the filename*/
virtual bool canRead(const string& filepath) const;
* can be read or not depending on the filename*/
template <typename T>
bool FileReader<T>::canRead(const string& filepath) const {
const string& realExtension = extractExtension(filepath);
//const string* haveExtension = extensions;
std::vector<string> haveExtension = extensions;
//while (*haveExtension != "") {
for (unsigned int i = 0; i < haveExtension.size(); ++i) {
//if (realExtension == *haveExtension) {
if (realExtension == haveExtension[i]) {
return true;
}
//++haveExtension;
}
return false;
}
/**Gives a better estimation of whether the specified file
* can be read or not depending on the file content*/
virtual bool canRead(ifstream& file) const;
virtual void cleanupExtensions();
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(const string& filepath) const;
/**Reads a file to an object
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(const string& filepath, T* object) const;
/**Reads a file
* This method tries to read the specified file
* If it failes, either <code>null</code> is returned or an exception
* Default implementation generates an object using T()
* is thrown
*/
virtual T* read(ifstream& file, const string& path) const {
T* obj = new T();
T* ret = read(file,path,obj);
if (obj != ret) {
delete obj;
}
return ret;
}
/**Reads a file onto the specified object
* This method tries to read the specified file
* If it failes, either <code>null</code> is returned or an exception
* is thrown
*/
virtual T* read(ifstream& file, const string& path, T* former) const = 0;
virtual ~FileReader() {
cleanupExtensions();
}; //Well ... these objects aren't supposed to be destroyed
};
template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath) {
//try to assign file
#if defined(WIN32) && !defined(__MINGW32__)
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
if (!file.is_open()) {
throw megaglest_runtime_error("[#1] Could not open file " + filepath);
}
for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
T* ret = NULL;
file.seekg(0, ios::beg); //Set position to first
template <typename T>
bool FileReader<T>::canRead(ifstream& file) const {
try {
FileReader<T> const * reader = *i;
ret = reader->read(file, filepath); //It is guaranteed that at least the filepath matches ...
T* wouldRead = read(file, "unknown file");
bool ret = (wouldRead != NULL);
delete wouldRead;
return ret;
}
#if defined(WIN32)
catch (megaglest_runtime_error) {
@@ -164,242 +341,62 @@ static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, con
catch (megaglest_runtime_error &ex) {
#endif
throw;
} catch (...) {
return false;
}
catch (...) {
continue;
}
if (ret != NULL) {
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return ret;
}
}
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return NULL;
}
template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath, T* object) {
//try to assign file
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
template <typename T>
T* FileReader<T>::read(const string& filepath) const {
#if defined(WIN32) && !defined(__MINGW32__)
wstring wstr = utf8_decode(filepath);
FILE *fp = _wfopen(wstr.c_str(), L"rb");
int fileErrno = errno;
ifstream file(fp);
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
if (!file.is_open()) {
if (!file.is_open()) {
throw megaglest_runtime_error("[#3] Could not open file " + filepath);
}
T* ret = read(file, filepath);
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
DWORD error = GetLastError();
throw megaglest_runtime_error("[#2] Could not open file, result: " + intToStr(error) + " - " + intToStr(fileErrno) + " [" + filepath + "]");
#else
throw megaglest_runtime_error("[#2] Could not open file [" + filepath + "]");
if (fp) fclose(fp);
#endif
}
for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
T* ret = NULL;
file.seekg(0, ios::beg); //Set position to first
try {
FileReader<T> const * reader = *i;
ret = reader->read(file, filepath, object); //It is guaranteed that at least the filepath matches ...
}
#if defined(WIN32)
catch (megaglest_runtime_error) {
#else
catch (megaglest_runtime_error &ex) {
#endif
throw;
}
catch (...) {
continue;
}
if (ret != NULL) {
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return ret;
}
}
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return NULL;
}
/**Tries to read a file
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath) {
const string& extension = extractExtension(filepath);
vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
if (possibleReaders != NULL) {
//Search in these possible readers
T* ret = readFromFileReaders(possibleReaders, filepath);
if (ret != NULL) {
return ret;
}
}
T* ret = readFromFileReaders(&(getFileReaders()), filepath); //Try all other
if (ret == NULL) {
std::cerr << "ERROR #1 - Could not parse filepath: " << filepath << std::endl;
throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
}
return ret;
}
/**Tries to read a file
* This method tries to read the file with the specified filepath.
* If it fails, either <code>null</code> is returned or an exception
* is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath, T* object) {
const string& extension = extractExtension(filepath);
vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
if (possibleReaders != NULL) {
//Search in these possible readers
T* ret = readFromFileReaders(possibleReaders, filepath, object);
if (ret != NULL) {
return ret;
}
}
T* ret = readFromFileReaders(&(getFileReaders()), filepath, object); //Try all other
if (ret == NULL) {
std::cerr << "ERROR #2 - Could not parse filepath: " << filepath << std::endl;
ret = readFromFileReaders(&(getLowPriorityFileReaders()), filepath); //Try to get dummy file
if (ret == NULL) {
throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
}
}
return ret;
}
template <typename T>
FileReader<T>::FileReader(std::vector<string> extensions): extensions(extensions) {
getFileReaders().push_back(this);
std::vector<string> nextExtension = extensions;
for(unsigned int i = 0; i < nextExtension.size(); ++i) {
vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
if (curPossibleReaders == NULL) {
(getFileReadersMap())[nextExtension[i]] = (curPossibleReaders = new vector<FileReader<T> const *>());
}
curPossibleReaders->push_back(this);
}
}
template <typename T>
void FileReader<T>::cleanupExtensions() {
std::vector<string> nextExtension = extensions;
for(unsigned int i = 0; i < nextExtension.size(); ++i) {
vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
if (curPossibleReaders != NULL) {
delete curPossibleReaders;
(getFileReadersMap())[nextExtension[i]] = NULL;
}
}
}
/**Gives a quick estimation of whether the specified file
* can be read or not depending on the filename*/
template <typename T>
bool FileReader<T>::canRead(const string& filepath) const {
const string& realExtension = extractExtension(filepath);
//const string* haveExtension = extensions;
std::vector<string> haveExtension = extensions;
//while (*haveExtension != "") {
for(unsigned int i = 0; i < haveExtension.size(); ++i) {
//if (realExtension == *haveExtension) {
if (realExtension == haveExtension[i]) {
return true;
}
//++haveExtension;
}
return false;
}
/**Gives a better estimation of whether the specified file
* can be read or not depending on the file content*/
template <typename T>
bool FileReader<T>::canRead(ifstream& file) const {
try {
T* wouldRead = read(file,"unknown file");
bool ret = (wouldRead != NULL);
delete wouldRead;
return ret;
}
#if defined(WIN32)
catch (megaglest_runtime_error) {
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
template <typename T>
T* FileReader<T>::read(const string& filepath, T* object) const {
#if defined(WIN32) && !defined(__MINGW32__)
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
catch (megaglest_runtime_error &ex) {
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
throw;
}
catch (...) {
return false;
}
}
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
template <typename T>
T* FileReader<T>::read(const string& filepath) const {
if (!file.is_open()) {
throw megaglest_runtime_error("[#4] Could not open file " + filepath);
}
T* ret = read(file, filepath, object);
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
if (fp) fclose(fp);
#endif
if (!file.is_open()) {
throw megaglest_runtime_error("[#3] Could not open file " + filepath);
return ret;
}
T* ret = read(file,filepath);
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return ret;
}
/**Reads a file
* This method tries to read the file with the specified filepath
* If it fails, either <code>null</code> is returned or an exception
* is thrown
*/
template <typename T>
T* FileReader<T>::read(const string& filepath, T* object) const {
#if defined(WIN32) && !defined(__MINGW32__)
FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
ifstream file(fp);
#else
ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
if (!file.is_open()) {
throw megaglest_runtime_error("[#4] Could not open file " + filepath);
}
T* ret = read(file,filepath,object);
file.close();
#if defined(WIN32) && !defined(__MINGW32__)
if(fp) fclose(fp);
#endif
return ret;
}
} //end namespace
} //end namespace
#endif

View File

@@ -20,25 +20,27 @@
#include "leak_dumper.h"
//Initialize some objects
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// namespace ImageRegisterer
// =====================================================
// =====================================================
// namespace ImageRegisterer
// =====================================================
namespace ImageRegisterer {
namespace ImageRegisterer {
//This function registers all image-readers, but only once (any further call is unnecessary)
bool registerImageReaders();
//This function registers all image-readers, but only once (any further call is unnecessary)
bool registerImageReaders();
//Since you can't call void methods here, I have used a method doing nothing except initializing the image Readers
//Since you can't call void methods here, I have used a method doing nothing except initializing the image Readers
#ifdef WIN32
static bool readersRegistered = registerImageReaders(); //should always return true, this should guarantee that the readers are registered <--> ImageReaders is included anywhere
static bool readersRegistered = registerImageReaders(); //should always return true, this should guarantee that the readers are registered <--> ImageReaders is included anywhere
#else
static bool readersRegistered __attribute__((unused)) = registerImageReaders(); //should always return true, this should guarantee that the readers are registered <--> ImageReaders is included anywhere
static bool readersRegistered __attribute__((unused)) = registerImageReaders(); //should always return true, this should guarantee that the readers are registered <--> ImageReaders is included anywhere
#endif
}
}
}} //end namespace
}
} //end namespace
#endif

View File

@@ -20,16 +20,18 @@
#include "pixmap.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class JPGReader: FileReader<Pixmap2D> {
public:
JPGReader();
class JPGReader : FileReader<Pixmap2D> {
public:
JPGReader();
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
}} //end namespace
}
} //end namespace
#endif

View File

@@ -20,23 +20,25 @@
#include "pixmap.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class PNGReader: FileReader<Pixmap2D> {
public:
PNGReader();
class PNGReader : FileReader<Pixmap2D> {
public:
PNGReader();
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
class PNGReader3D: FileReader<Pixmap3D> {
public:
PNGReader3D();
class PNGReader3D : FileReader<Pixmap3D> {
public:
PNGReader3D();
Pixmap3D* read(ifstream& in, const string& path, Pixmap3D* ret) const;
};
Pixmap3D* read(ifstream& in, const string& path, Pixmap3D* ret) const;
};
}} //end namespace
}
} //end namespace
#endif

View File

@@ -20,22 +20,24 @@
#include "pixmap.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class TGAReader: FileReader<Pixmap2D> {
public:
TGAReader();
class TGAReader : FileReader<Pixmap2D> {
public:
TGAReader();
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
Pixmap2D* read(ifstream& in, const string& path, Pixmap2D* ret) const;
};
class TGAReader3D: FileReader<Pixmap3D> {
public:
TGAReader3D();
class TGAReader3D : FileReader<Pixmap3D> {
public:
TGAReader3D();
Pixmap3D* read(ifstream& in, const string& path, Pixmap3D* ret) const;
};
Pixmap3D* read(ifstream& in, const string& path, Pixmap3D* ret) const;
};
}} //end namespace
}
} //end namespace
#endif

View File

@@ -13,57 +13,61 @@
using std::string;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class VertexBuffer
// =====================================================
// =====================================================
// class VertexBuffer
// =====================================================
class VertexBuffer{
private:
static const int texCoordCount = 8;
static const int attribCount = 8;
class VertexBuffer {
private:
static const int texCoordCount = 8;
static const int attribCount = 8;
private:
void *positionPointer;
void *normalPointer;
private:
void *positionPointer;
void *normalPointer;
void *texCoordPointers[texCoordCount];
int texCoordCoordCounts[texCoordCount];
void *texCoordPointers[texCoordCount];
int texCoordCoordCounts[texCoordCount];
void *attribPointers[attribCount];
int attribCoordCounts[attribCount];
string attribNames[attribCount];
void *attribPointers[attribCount];
int attribCoordCounts[attribCount];
string attribNames[attribCount];
public:
VertexBuffer();
virtual ~VertexBuffer(){};
public:
VertexBuffer();
virtual ~VertexBuffer() {
};
virtual void init(int size)= 0;
virtual void init(int size) = 0;
void setPositionPointer(void *pointer);
void setNormalPointer(void *pointer);
void setTexCoordPointer(void *pointer, int texCoordIndex, int coordCount);
void setAttribPointer(void *pointer, int attribIndex, int coordCount, const string &name);
};
void setPositionPointer(void *pointer);
void setNormalPointer(void *pointer);
void setTexCoordPointer(void *pointer, int texCoordIndex, int coordCount);
void setAttribPointer(void *pointer, int attribIndex, int coordCount, const string &name);
};
// =====================================================
// class IndexBuffer
// =====================================================
// =====================================================
// class IndexBuffer
// =====================================================
class IndexBuffer{
private:
void *indexPointer;
class IndexBuffer {
private:
void *indexPointer;
public:
IndexBuffer();
virtual ~IndexBuffer(){}
public:
IndexBuffer();
virtual ~IndexBuffer() {
}
virtual void init(int size)= 0;
virtual void init(int size) = 0;
void setIndexPointer(void *pointer);
};
void setIndexPointer(void *pointer);
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -16,37 +16,51 @@
#include "quaternion.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class Camera
// =====================================================
// =====================================================
// class Camera
// =====================================================
class Camera{
private:
Quaternion orientation;
Vec3f position;
public:
Camera();
class Camera {
private:
Quaternion orientation;
Vec3f position;
public:
Camera();
Vec3f getPosition() const {return position;}
Quaternion getOrientation() const {return orientation;}
Vec3f getPosition() const {
return position;
}
Quaternion getOrientation() const {
return orientation;
}
const Vec3f & getConstPosition() const {return position;}
const Quaternion & getConstOrientation() const {return orientation;}
const Vec3f & getConstPosition() const {
return position;
}
const Quaternion & getConstOrientation() const {
return orientation;
}
void setPosition(const Vec3f &position) {this->position= position;}
void setOrientation(const Quaternion &orientation) {this->orientation= orientation;}
void setPosition(const Vec3f &position) {
this->position = position;
}
void setOrientation(const Quaternion &orientation) {
this->orientation = orientation;
}
void moveLocalX(float amount);
void moveLocalY(float amount);
void moveLocalZ(float amount);
void moveLocalX(float amount);
void moveLocalY(float amount);
void moveLocalZ(float amount);
void addYaw(float amount);
void addPitch(float amount);
void addRoll(float amount);
};
void addYaw(float amount);
void addPitch(float amount);
void addRoll(float amount);
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -15,50 +15,77 @@
#include "data_types.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
using Platform::uint32;
using Platform::int8;
using Platform::uint32;
using Platform::int8;
// =====================================================
// class Context
// =====================================================
// =====================================================
// class Context
// =====================================================
class Context{
protected:
uint32 colorBits;
uint32 depthBits;
uint32 stencilBits;
int8 hardware_acceleration;
int8 fullscreen_anti_aliasing;
float gammaValue;
class Context {
protected:
uint32 colorBits;
uint32 depthBits;
uint32 stencilBits;
int8 hardware_acceleration;
int8 fullscreen_anti_aliasing;
float gammaValue;
public:
Context();
virtual ~Context(){}
public:
Context();
virtual ~Context() {
}
uint32 getColorBits() const {return colorBits;}
uint32 getDepthBits() const {return depthBits;}
uint32 getStencilBits() const {return stencilBits;}
int8 getHardware_acceleration() const { return hardware_acceleration; }
int8 getFullscreen_anti_aliasing() const { return fullscreen_anti_aliasing; }
float getGammaValue() const { return gammaValue; }
uint32 getColorBits() const {
return colorBits;
}
uint32 getDepthBits() const {
return depthBits;
}
uint32 getStencilBits() const {
return stencilBits;
}
int8 getHardware_acceleration() const {
return hardware_acceleration;
}
int8 getFullscreen_anti_aliasing() const {
return fullscreen_anti_aliasing;
}
float getGammaValue() const {
return gammaValue;
}
void setColorBits(uint32 colorBits) {this->colorBits= colorBits;}
void setDepthBits(uint32 depthBits) {this->depthBits= depthBits;}
void setStencilBits(uint32 stencilBits) {this->stencilBits= stencilBits;}
void setHardware_acceleration(int8 value) { hardware_acceleration = value; }
void setFullscreen_anti_aliasing(int8 value) { fullscreen_anti_aliasing = value; }
void setGammaValue(float value) { gammaValue = value; }
void setColorBits(uint32 colorBits) {
this->colorBits = colorBits;
}
void setDepthBits(uint32 depthBits) {
this->depthBits = depthBits;
}
void setStencilBits(uint32 stencilBits) {
this->stencilBits = stencilBits;
}
void setHardware_acceleration(int8 value) {
hardware_acceleration = value;
}
void setFullscreen_anti_aliasing(int8 value) {
fullscreen_anti_aliasing = value;
}
void setGammaValue(float value) {
gammaValue = value;
}
virtual void init()= 0;
virtual void end()= 0;
virtual void reset()= 0;
virtual void init() = 0;
virtual void end() = 0;
virtual void reset() = 0;
virtual void makeCurrent()= 0;
virtual void swapBuffers()= 0;
};
virtual void makeCurrent() = 0;
virtual void swapBuffers() = 0;
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -21,142 +21,163 @@ using std::string;
//class Text;
namespace Shared { namespace Graphics {
namespace Shared {
namespace Graphics {
// =====================================================
// class FontMetrics
// =====================================================
// =====================================================
// class FontMetrics
// =====================================================
class FontMetrics {
class FontMetrics {
private:
float *widths;
float height;
private:
float *widths;
float height;
//float yOffsetFactor;
Text *textHandler;
//float yOffsetFactor;
Text *textHandler;
public:
//static float DEFAULT_Y_OFFSET_FACTOR;
public:
//static float DEFAULT_Y_OFFSET_FACTOR;
FontMetrics(Text *textHandler=NULL);
~FontMetrics();
FontMetrics(Text *textHandler = NULL);
~FontMetrics();
//void setYOffsetFactor(float yOffsetFactor);
//float getYOffsetFactor() const;
//void setYOffsetFactor(float yOffsetFactor);
//float getYOffsetFactor() const;
void setTextHandler(Text *textHandler);
Text * getTextHandler();
void setTextHandler(Text *textHandler);
Text * getTextHandler();
void setWidth(int i, float width) {this->widths[i] = width;}
void setHeight(float height) {this->height= height;}
void setWidth(int i, float width) {
this->widths[i] = width;
}
void setHeight(float height) {
this->height = height;
}
float getTextWidth(const string &str);
float getHeight(const string &str) const;
float getTextWidth(const string &str);
float getHeight(const string &str) const;
string wordWrapText(string text, int maxWidth);
string wordWrapText(string text, int maxWidth);
};
};
// =====================================================
// class Font
// =====================================================
// =====================================================
// class Font
// =====================================================
class Font {
public:
static int charCount;
static std::string fontTypeName;
static bool fontIsMultibyte;
static bool forceLegacyFonts;
static bool fontIsRightToLeft;
static bool fontSupportMixedRightToLeft;
static float scaleFontValue;
static float scaleFontValueCenterHFactor;
static int baseSize;
static int faceResolution;
static string langHeightText;
public:
enum Width {
wNormal= 400,
wBold= 700
};
class Font {
public:
static int charCount;
static std::string fontTypeName;
static bool fontIsMultibyte;
static bool forceLegacyFonts;
static bool fontIsRightToLeft;
static bool fontSupportMixedRightToLeft;
static float scaleFontValue;
static float scaleFontValueCenterHFactor;
static int baseSize;
static int faceResolution;
static string langHeightText;
protected:
string type;
int width;
bool inited;
int size;
FontMetrics metrics;
Text *textHandler;
string fontUniqueId;
public:
enum Width {
wNormal = 400,
wBold = 700
};
public:
//constructor & destructor
Font(FontTextHandlerType type);
virtual ~Font();
virtual void init()=0;
virtual void end()=0;
protected:
string type;
int width;
bool inited;
int size;
FontMetrics metrics;
void setFontUniqueId(string id) { fontUniqueId = id; }
string getFontUniqueId() { return fontUniqueId; }
//get
int getWidth() const;
FontMetrics *getMetrics() {return &metrics;}
Text * getTextHandler() {return textHandler;}
string getType() const;
Text *textHandler;
string fontUniqueId;
//set
void setType(string typeX11, string typeGeneric, string typeGenericFamily);
void setWidth(int width);
public:
//constructor & destructor
Font(FontTextHandlerType type);
virtual ~Font();
virtual void init() = 0;
virtual void end() = 0;
int getSize() const;
void setSize(int size);
void setFontUniqueId(string id) {
fontUniqueId = id;
}
string getFontUniqueId() {
return fontUniqueId;
}
static void bidi_cvt(string &str_);
//get
int getWidth() const;
FontMetrics *getMetrics() {
return &metrics;
}
Text * getTextHandler() {
return textHandler;
}
string getType() const;
static void resetToDefaults();
};
//set
void setType(string typeX11, string typeGeneric, string typeGenericFamily);
void setWidth(int width);
// =====================================================
// class Font2D
// =====================================================
int getSize() const;
void setSize(int size);
class Font2D: public Font {
static void bidi_cvt(string &str_);
public:
Font2D(FontTextHandlerType type=ftht_2D);
virtual ~Font2D() {};
};
static void resetToDefaults();
};
// =====================================================
// class Font3D
// =====================================================
// =====================================================
// class Font2D
// =====================================================
class Font3D: public Font {
protected:
float depth;
class Font2D : public Font {
public:
Font3D(FontTextHandlerType type=ftht_3D);
virtual ~Font3D() {};
float getDepth() const {return depth;}
void setDepth(float depth) {this->depth= depth;}
};
public:
Font2D(FontTextHandlerType type = ftht_2D);
virtual ~Font2D() {
};
};
Font3D *ConvertFont2DTo3D(Font2D *font);
// =====================================================
// class Font3D
// =====================================================
const char* findFont(const char *firstFontToTry=NULL,const char *firstFontFamilyToTry=NULL);
class Font3D : public Font {
protected:
float depth;
class FontChangedCallbackInterface {
public:
virtual void FontChangedCallback(std::string fontUniqueId, Font *font) = 0;
virtual ~FontChangedCallbackInterface() {};
};
public:
Font3D(FontTextHandlerType type = ftht_3D);
virtual ~Font3D() {
};
}}//end namespace
float getDepth() const {
return depth;
}
void setDepth(float depth) {
this->depth = depth;
}
};
Font3D *ConvertFont2DTo3D(Font2D *font);
const char* findFont(const char *firstFontToTry = NULL, const char *firstFontFamilyToTry = NULL);
class FontChangedCallbackInterface {
public:
virtual void FontChangedCallback(std::string fontUniqueId, Font *font) = 0;
virtual ~FontChangedCallbackInterface() {
};
};
}
}//end namespace
#endif

View File

@@ -18,34 +18,36 @@
using namespace std;
namespace Shared { namespace Graphics {
namespace Shared {
namespace Graphics {
// =====================================================
// class FontManager
//
/// Creates, Intializes, Finalizes, and Deletes fonts
// =====================================================
// =====================================================
// class FontManager
//
/// Creates, Intializes, Finalizes, and Deletes fonts
// =====================================================
class FontManager {
protected:
typedef vector<Font*> FontContainer;
class FontManager {
protected:
typedef vector<Font*> FontContainer;
protected:
FontContainer fonts;
protected:
FontContainer fonts;
public:
FontManager();
virtual ~FontManager();
public:
FontManager();
virtual ~FontManager();
Font2D *newFont2D();
Font3D *newFont3D();
Font2D *newFont2D();
Font3D *newFont3D();
void endFont(Font *font,bool mustExistInList=false);
void endFont(Font *font, bool mustExistInList = false);
void init();
void end();
};
void init();
void end();
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -24,9 +24,8 @@ enum FontTextHandlerType {
/**
* Base class upon which all text rendering calls are made.
*/
//====================================================================
class Text
{
//====================================================================
class Text {
protected:
FontTextHandlerType type;
public:

View File

@@ -15,21 +15,25 @@
#include "graphics_interface.h"
#include "leak_dumper.h"
namespace Shared { namespace Graphics {
namespace Shared {
namespace Graphics {
// ===============================================
// class BaseRenderer
// ===============================================
// ===============================================
// class BaseRenderer
// ===============================================
class BaseRenderer : public RendererMapInterface {
public:
BaseRenderer() { }
virtual ~BaseRenderer() { }
class BaseRenderer : public RendererMapInterface {
public:
BaseRenderer() {
}
virtual ~BaseRenderer() {
}
virtual void initMapSurface(int clientW, int clientH);
virtual void renderMap(MapPreview *map, int x, int y, int clientW, int clientH, int cellSize, bool grid=false, bool heightMap=false, bool hideWater=false);
};
virtual void initMapSurface(int clientW, int clientH);
virtual void renderMap(MapPreview *map, int x, int y, int clientW, int clientH, int cellSize, bool grid = false, bool heightMap = false, bool hideWater = false);
};
}} // end namespace
}
} // end namespace
#endif

View File

@@ -16,33 +16,42 @@
#include "gl_wrap.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
using Platform::PlatformContextGl;
using Platform::PlatformContextGl;
// =====================================================
// class ContextGl
// =====================================================
// =====================================================
// class ContextGl
// =====================================================
class ContextGl: public Context {
protected:
PlatformContextGl pcgl;
class ContextGl : public Context {
protected:
PlatformContextGl pcgl;
public:
ContextGl();
virtual ~ContextGl();
public:
ContextGl();
virtual ~ContextGl();
virtual void init();
virtual void end();
virtual void reset(){};
virtual void init();
virtual void end();
virtual void reset() {
};
virtual void makeCurrent();
virtual void swapBuffers();
virtual void makeCurrent();
virtual void swapBuffers();
const PlatformContextGl *getPlatformContextGl() const {return &pcgl;}
PlatformContextGl *getPlatformContextGlPtr() {return &pcgl;}
};
const PlatformContextGl *getPlatformContextGl() const {
return &pcgl;
}
PlatformContextGl *getPlatformContextGlPtr() {
return &pcgl;
}
};
}}}//end namespace
}
}
}//end namespace
#endif

View File

@@ -19,52 +19,62 @@
using namespace std;
namespace Shared { namespace Graphics { namespace Gl {
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class FontGl
// =====================================================
// =====================================================
// class FontGl
// =====================================================
class FontGl {
protected:
class FontGl {
protected:
GLuint handle;
static string default_fonttype;
GLuint handle;
static string default_fonttype;
public:
public:
GLuint getHandle() const {return handle;}
GLuint getHandle() const {
return handle;
}
static string getDefault_fontType() {return default_fonttype;}
static void setDefault_fontType(string value) {default_fonttype = value;}
};
static string getDefault_fontType() {
return default_fonttype;
}
static void setDefault_fontType(string value) {
default_fonttype = value;
}
};
// =====================================================
// class Font2DGl
//
/// OpenGL bitmap font
// =====================================================
// =====================================================
// class Font2DGl
//
/// OpenGL bitmap font
// =====================================================
class Font2DGl: public Font2D, public FontGl {
public:
class Font2DGl : public Font2D, public FontGl {
public:
virtual void init();
virtual void end();
};
virtual void init();
virtual void end();
};
// =====================================================
// class Font3DGl
//
/// OpenGL outline font
// =====================================================
// =====================================================
// class Font3DGl
//
/// OpenGL outline font
// =====================================================
class Font3DGl: public Font3D, public FontGl {
public:
class Font3DGl : public Font3D, public FontGl {
public:
virtual void init();
virtual void end();
};
virtual void init();
virtual void end();
};
}}}//end namespace
}
}
}//end namespace
#endif

View File

@@ -18,42 +18,45 @@
#include "font_text.h"
namespace Shared { namespace Graphics { namespace Gl {
namespace Shared {
namespace Graphics {
namespace Gl {
/**
* Use FTGL for rendering text in OpenGL
*/
//====================================================================
class TextFTGL : public Text
{
public:
/**
* Use FTGL for rendering text in OpenGL
*/
//====================================================================
class TextFTGL : public Text {
public:
static string langHeightText;
static int faceResolution;
static string langHeightText;
static int faceResolution;
TextFTGL(FontTextHandlerType type);
virtual ~TextFTGL();
virtual void init(string fontName, string fontFamilyName, int fontSize);
TextFTGL(FontTextHandlerType type);
virtual ~TextFTGL();
virtual void init(string fontName, string fontFamilyName, int fontSize);
virtual void SetFaceSize(int);
virtual int GetFaceSize();
virtual void SetFaceSize(int);
virtual int GetFaceSize();
virtual void Render(const char*, const int = -1);
virtual float Advance(const char*, const int = -1);
virtual float LineHeight(const char*, const int = -1);
virtual void Render(const char*, const int = -1);
virtual float Advance(const char*, const int = -1);
virtual float LineHeight(const char*, const int = -1);
virtual void Render(const wchar_t*, const int = -1);
virtual float Advance(const wchar_t*, const int = -1);
virtual float LineHeight(const wchar_t* = L" ", const int = -1);
virtual void Render(const wchar_t*, const int = -1);
virtual float Advance(const wchar_t*, const int = -1);
virtual float LineHeight(const wchar_t* = L" ", const int = -1);
private:
FTFont *ftFont;
const char* fontFile;
private:
FTFont *ftFont;
const char* fontFile;
void cleanupFont();
};
void cleanupFont();
};
}}}//end namespace
}
}
}//end namespace
#endif // USE_FTGL

View File

@@ -21,24 +21,44 @@
#include "font_gl.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class GraphicsFactoryBasicGl
// =====================================================
// =====================================================
// class GraphicsFactoryBasicGl
// =====================================================
class GraphicsFactoryBasicGl: public GraphicsFactory{
public:
virtual TextRenderer2D *newTextRenderer2D() {return new TextRenderer2DGl();}
virtual TextRenderer3D *newTextRenderer3D() {return new TextRenderer3DGl();}
virtual ModelRenderer *newModelRenderer() {return new ModelRendererGl();}
virtual Context *newContext() {return new ContextGl();}
virtual Model *newModel(const string &path,TextureManager* textureManager,bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList, string *sourceLoader) { return new ModelGl(path,textureManager,deletePixMapAfterLoad,loadedFileList,sourceLoader); }
virtual Texture2D *newTexture2D() {return new Texture2DGl();}
virtual Font2D *newFont2D() {return new Font2DGl();}
virtual Font3D *newFont3D() {return new Font3DGl();}
};
class GraphicsFactoryBasicGl : public GraphicsFactory {
public:
virtual TextRenderer2D *newTextRenderer2D() {
return new TextRenderer2DGl();
}
virtual TextRenderer3D *newTextRenderer3D() {
return new TextRenderer3DGl();
}
virtual ModelRenderer *newModelRenderer() {
return new ModelRendererGl();
}
virtual Context *newContext() {
return new ContextGl();
}
virtual Model *newModel(const string &path, TextureManager* textureManager, bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList, string *sourceLoader) {
return new ModelGl(path, textureManager, deletePixMapAfterLoad, loadedFileList, sourceLoader);
}
virtual Texture2D *newTexture2D() {
return new Texture2DGl();
}
virtual Font2D *newFont2D() {
return new Font2DGl();
}
virtual Font3D *newFont3D() {
return new Font3DGl();
}
};
}}}//end namespace
}
}
}//end namespace
#endif

View File

@@ -26,41 +26,77 @@
#include "font_gl.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class GraphicsFactoryGl
// =====================================================
// =====================================================
// class GraphicsFactoryGl
// =====================================================
class GraphicsFactoryGl: public GraphicsFactory{
public:
//context
virtual Context *newContext() {return new ContextGl();}
class GraphicsFactoryGl : public GraphicsFactory {
public:
//context
virtual Context *newContext() {
return new ContextGl();
}
//textures
virtual TextureManager *newTextureManager() {return new TextureManager();}
virtual Texture1D *newTexture1D() {return new Texture1DGl();}
virtual Texture2D *newTexture2D() {return new Texture2DGl();}
virtual Texture3D *newTexture3D() {return new Texture3DGl();}
virtual TextureCube *newTextureCube() {return new TextureCubeGl();}
//models
virtual ModelManager *newModelManager() {return new ModelManager();}
virtual ModelRenderer *newModelRenderer() {return new ModelRendererGl();}
virtual Model *newModel(const string &path,TextureManager* textureManager,bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList, string *sourceLoader) { return new ModelGl(path,textureManager,deletePixMapAfterLoad,loadedFileList,sourceLoader); }
//textures
virtual TextureManager *newTextureManager() {
return new TextureManager();
}
virtual Texture1D *newTexture1D() {
return new Texture1DGl();
}
virtual Texture2D *newTexture2D() {
return new Texture2DGl();
}
virtual Texture3D *newTexture3D() {
return new Texture3DGl();
}
virtual TextureCube *newTextureCube() {
return new TextureCubeGl();
}
//text
virtual FontManager *newFontManager() {return new FontManager();}
virtual TextRenderer2D *newTextRenderer2D() {return new TextRenderer2DGl();}
virtual TextRenderer3D *newTextRenderer3D() {return new TextRenderer3DGl();}
virtual Font2D *newFont2D() {return new Font2DGl();}
virtual Font3D *newFont3D() {return new Font3DGl();}
//models
virtual ModelManager *newModelManager() {
return new ModelManager();
}
virtual ModelRenderer *newModelRenderer() {
return new ModelRendererGl();
}
virtual Model *newModel(const string &path, TextureManager* textureManager, bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList, string *sourceLoader) {
return new ModelGl(path, textureManager, deletePixMapAfterLoad, loadedFileList, sourceLoader);
}
//particles
virtual ParticleManager *newParticleManager() {return new ParticleManager();}
virtual ParticleRenderer *newParticleRenderer() {return new ParticleRendererGl();}
};
//text
virtual FontManager *newFontManager() {
return new FontManager();
}
virtual TextRenderer2D *newTextRenderer2D() {
return new TextRenderer2DGl();
}
virtual TextRenderer3D *newTextRenderer3D() {
return new TextRenderer3DGl();
}
virtual Font2D *newFont2D() {
return new Font2DGl();
}
virtual Font3D *newFont3D() {
return new Font3DGl();
}
}}}//end namespace
//particles
virtual ParticleManager *newParticleManager() {
return new ParticleManager();
}
virtual ParticleRenderer *newParticleRenderer() {
return new ParticleRendererGl();
}
};
}
}
}//end namespace
#endif

View File

@@ -15,21 +15,27 @@
#include "model.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class ModelGl
// =====================================================
// =====================================================
// class ModelGl
// =====================================================
class ModelGl: public Model{
friend class GraphicsFactoryGl;
protected:
ModelGl(const string &path,TextureManager* textureManager,bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList, string *sourceLoader);
public:
virtual void init(){}
virtual void end(){}
};
class ModelGl : public Model {
friend class GraphicsFactoryGl;
protected:
ModelGl(const string &path, TextureManager* textureManager, bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList, string *sourceLoader);
public:
virtual void init() {
}
virtual void end() {
}
};
}}}//end namespace
}
}
}//end namespace
#endif

View File

@@ -17,35 +17,43 @@
#include "opengl.h"
#include "leak_dumper.h"
namespace Shared { namespace Graphics { namespace Gl {
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class ModelRendererGl
// =====================================================
// =====================================================
// class ModelRendererGl
// =====================================================
class ModelRendererGl: public ModelRenderer {
private:
bool rendering;
bool duplicateTexCoords;
int secondaryTexCoordUnit;
GLuint lastTexture;
class ModelRendererGl : public ModelRenderer {
private:
bool rendering;
bool duplicateTexCoords;
int secondaryTexCoordUnit;
GLuint lastTexture;
public:
ModelRendererGl();
virtual void begin(bool renderNormals, bool renderTextures, bool renderColors, bool colorPickingMode, MeshCallback *meshCallback);
virtual void end();
virtual void render(Model *model,int renderMode=rmNormal);
virtual void renderNormalsOnly(Model *model);
public:
ModelRendererGl();
virtual void begin(bool renderNormals, bool renderTextures, bool renderColors, bool colorPickingMode, MeshCallback *meshCallback);
virtual void end();
virtual void render(Model *model, int renderMode = rmNormal);
virtual void renderNormalsOnly(Model *model);
void setDuplicateTexCoords(bool duplicateTexCoords) {this->duplicateTexCoords= duplicateTexCoords;}
void setSecondaryTexCoordUnit(int secondaryTexCoordUnit) {this->secondaryTexCoordUnit= secondaryTexCoordUnit;}
void setDuplicateTexCoords(bool duplicateTexCoords) {
this->duplicateTexCoords = duplicateTexCoords;
}
void setSecondaryTexCoordUnit(int secondaryTexCoordUnit) {
this->secondaryTexCoordUnit = secondaryTexCoordUnit;
}
private:
void renderMesh(Mesh *mesh,int renderMode=rmNormal);
void renderMeshNormals(Mesh *mesh);
};
private:
}}}//end namespace
void renderMesh(Mesh *mesh, int renderMode = rmNormal);
void renderMeshNormals(Mesh *mesh);
};
}
}
}//end namespace
#endif

View File

@@ -24,51 +24,53 @@
using std::runtime_error;
using std::string;
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
using Util::intToStr;
using Util::intToStr;
// =====================================================
// Globals
// =====================================================
// =====================================================
// Globals
// =====================================================
bool getVBOSupported();
void setVBOSupported(bool value);
bool getVBOSupported();
void setVBOSupported(bool value);
//void overrideGlExtensionSupport(const char *extensionName,bool value);
bool isGlExtensionSupported(const char *extensionName);
//bool isGlVersionSupported(int major, int minor, int release);
const char *getGlVersion();
const char *getGlRenderer();
const char *getGlVendor();
const char *getGlExtensions();
const char *getGlPlatformExtensions();
int getGlMaxLights();
int getGlMaxTextureSize();
int getGlMaxTextureUnits();
int getGlModelviewMatrixStackDepth();
int getGlProjectionMatrixStackDepth();
//void checkGlExtension(const char *extensionName);
//void overrideGlExtensionSupport(const char *extensionName,bool value);
bool isGlExtensionSupported(const char *extensionName);
//bool isGlVersionSupported(int major, int minor, int release);
const char *getGlVersion();
const char *getGlRenderer();
const char *getGlVendor();
const char *getGlExtensions();
const char *getGlPlatformExtensions();
int getGlMaxLights();
int getGlMaxTextureSize();
int getGlMaxTextureUnits();
int getGlModelviewMatrixStackDepth();
int getGlProjectionMatrixStackDepth();
//void checkGlExtension(const char *extensionName);
void inline _assertGl(const char *file, int line, GLenum *forceErrorNumber = NULL) {
GLenum error = (forceErrorNumber != NULL ? *forceErrorNumber : glGetError());
if(error != GL_NO_ERROR) {
void inline _assertGl(const char *file, int line, GLenum *forceErrorNumber = NULL) {
GLenum error = (forceErrorNumber != NULL ? *forceErrorNumber : glGetError());
if (error != GL_NO_ERROR) {
#ifdef _DEBUG
if(error == GL_INVALID_ENUM) {
return;
}
if (error == GL_INVALID_ENUM) {
return;
}
#endif
//if(error != GL_INVALID_ENUM) {
const char *errorString= reinterpret_cast<const char*>(gluErrorString(error));
char szBuf[8096]="";
snprintf(szBuf,8096,"OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d",error,error,errorString,file,line);
//throw megaglest_runtime_error("OpenGL error #" + intToStr(error) + " : " + string(errorString) + " at file: " + string(file) + ", line " + intToStr(line));
throw megaglest_runtime_error(szBuf);
//}
}
//if(error != GL_INVALID_ENUM) {
const char *errorString = reinterpret_cast<const char*>(gluErrorString(error));
char szBuf[8096] = "";
snprintf(szBuf, 8096, "OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d", error, error, errorString, file, line);
//throw megaglest_runtime_error("OpenGL error #" + intToStr(error) + " : " + string(errorString) + " at file: " + string(file) + ", line " + intToStr(line));
throw megaglest_runtime_error(szBuf);
//}
}
}
}
#ifdef NDEBUG
@@ -79,9 +81,11 @@ void inline _assertGl(const char *file, int line, GLenum *forceErrorNumber = NUL
#define assertGl() _assertGl(__FILE__, __LINE__);
#define assertGlWithErrorNumber(forceErrorNumber) _assertGl(__FILE__, __LINE__, &forceErrorNumber);
#endif
}}}//end namespace
#endif
}
}
}//end namespace
#endif

View File

@@ -15,37 +15,41 @@
#include "particle_renderer.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class ParticleRendererGl
// =====================================================
// =====================================================
// class ParticleRendererGl
// =====================================================
class ParticleRendererGl: public ParticleRenderer{
public:
static const int bufferSize = 1024;
class ParticleRendererGl : public ParticleRenderer {
public:
static const int bufferSize = 1024;
private:
bool rendering;
Vec3f vertexBuffer[bufferSize];
Vec2f texCoordBuffer[bufferSize];
Vec4f colorBuffer[bufferSize];
private:
bool rendering;
Vec3f vertexBuffer[bufferSize];
Vec2f texCoordBuffer[bufferSize];
Vec4f colorBuffer[bufferSize];
public:
//particles
ParticleRendererGl();
virtual void renderManager(ParticleManager *pm, ModelRenderer *mr);
virtual void renderSystem(ParticleSystem *ps);
virtual void renderSystemLine(ParticleSystem *ps);
virtual void renderSystemLineAlpha(ParticleSystem *ps);
virtual void renderModel(GameParticleSystem *ps, ModelRenderer *mr);
protected:
void renderBufferQuads(int quadCount);
void renderBufferLines(int lineCount);
void setBlendMode(ParticleSystem::BlendMode blendMode);
};
public:
//particles
ParticleRendererGl();
virtual void renderManager(ParticleManager *pm, ModelRenderer *mr);
virtual void renderSystem(ParticleSystem *ps);
virtual void renderSystemLine(ParticleSystem *ps);
virtual void renderSystemLineAlpha(ParticleSystem *ps);
virtual void renderModel(GameParticleSystem *ps, ModelRenderer *mr);
}}}//end namespace
protected:
void renderBufferQuads(int quadCount);
void renderBufferLines(int lineCount);
void setBlendMode(ParticleSystem::BlendMode blendMode);
};
}
}
}//end namespace
#endif

View File

@@ -22,90 +22,100 @@ using std::vector;
using std::string;
using std::pair;
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class ShaderProgramGl
// =====================================================
// =====================================================
// class ShaderProgramGl
// =====================================================
class ShaderProgramGl: public ShaderProgram{
private:
typedef pair<string, int> AttributePair;
typedef vector<AttributePair> Attributes;
class ShaderProgramGl : public ShaderProgram {
private:
typedef pair<string, int> AttributePair;
typedef vector<AttributePair> Attributes;
private:
Attributes attributes;
GLhandleARB handle;
VertexShader *vertexShader;
FragmentShader *fragmentShader;
bool inited;
private:
Attributes attributes;
GLhandleARB handle;
VertexShader *vertexShader;
FragmentShader *fragmentShader;
bool inited;
public:
ShaderProgramGl();
public:
ShaderProgramGl();
GLhandleARB getHandle() const {return handle;}
GLhandleARB getHandle() const {
return handle;
}
virtual void init();
virtual void end();
virtual void init();
virtual void end();
virtual void attach(VertexShader *vertexShader, FragmentShader *fragmentShader);
virtual bool link(string &messages);
virtual void activate();
virtual void deactivate();
virtual void attach(VertexShader *vertexShader, FragmentShader *fragmentShader);
virtual bool link(string &messages);
virtual void activate();
virtual void deactivate();
virtual void setUniform(const string &name, int value);
virtual void setUniform(const string &name, float value);
virtual void setUniform(const string &name, const Vec2f &value);
virtual void setUniform(const string &name, const Vec3f &value);
virtual void setUniform(const string &name, const Vec4f &value);
virtual void setUniform(const string &name, const Matrix3f &value);
virtual void setUniform(const string &name, const Matrix4f &value);
virtual void setUniform(const string &name, int value);
virtual void setUniform(const string &name, float value);
virtual void setUniform(const string &name, const Vec2f &value);
virtual void setUniform(const string &name, const Vec3f &value);
virtual void setUniform(const string &name, const Vec4f &value);
virtual void setUniform(const string &name, const Matrix3f &value);
virtual void setUniform(const string &name, const Matrix4f &value);
void bindAttribute(const string &name, int index);
void bindAttribute(const string &name, int index);
private:
GLint getLocation(const string &name);
};
private:
GLint getLocation(const string &name);
};
// =====================================================
// class ShaderGl
// =====================================================
// =====================================================
// class ShaderGl
// =====================================================
class ShaderGl: virtual public Shader{
protected:
GLhandleARB handle;
ShaderSource source;
bool inited;
class ShaderGl : virtual public Shader {
protected:
GLhandleARB handle;
ShaderSource source;
bool inited;
public:
ShaderGl();
const ShaderSource *getSource() const {return &source;}
GLhandleARB getHandle() const {return handle;}
public:
ShaderGl();
virtual void load(const string &path);
virtual bool compile(string &messages);
virtual void end();
};
const ShaderSource *getSource() const {
return &source;
}
GLhandleARB getHandle() const {
return handle;
}
// =====================================================
// class VertexShaderGl
// =====================================================
virtual void load(const string &path);
virtual bool compile(string &messages);
virtual void end();
};
class VertexShaderGl: public VertexShader, public ShaderGl{
public:
virtual void init();
};
// =====================================================
// class VertexShaderGl
// =====================================================
// =====================================================
// class FragmentShaderGl
// =====================================================
class VertexShaderGl : public VertexShader, public ShaderGl {
public:
virtual void init();
};
class FragmentShaderGl: public FragmentShader, public ShaderGl{
public:
virtual void init();
};
// =====================================================
// class FragmentShaderGl
// =====================================================
}}}//end namespace
class FragmentShaderGl : public FragmentShader, public ShaderGl {
public:
virtual void init();
};
}
}
}//end namespace
#endif

View File

@@ -15,100 +15,103 @@
#include "text_renderer.h"
#include "leak_dumper.h"
namespace Shared { namespace Graphics { namespace Gl {
namespace Shared {
namespace Graphics {
namespace Gl {
class Font2DGl;
class Font3DGl;
class TextRenderer2DGl;
class TextRenderer3DGl;
class Font2DGl;
class Font3DGl;
class TextRenderer2DGl;
class TextRenderer3DGl;
// =====================================================
// class TextRenderer2DGl
// =====================================================
// =====================================================
// class TextRenderer2DGl
// =====================================================
class TextRenderer2DGl: public TextRenderer2D {
private:
Font2DGl *font;
bool rendering;
class TextRenderer2DGl : public TextRenderer2D {
private:
Font2DGl *font;
bool rendering;
//Font3DGl *font3D;
//TextRenderer3DGl *tester;
//Font3DGl *font3D;
//TextRenderer3DGl *tester;
public:
TextRenderer2DGl();
virtual ~TextRenderer2DGl();
public:
TextRenderer2DGl();
virtual ~TextRenderer2DGl();
virtual void begin(Font2D *font);
virtual void render(const string &text, float x, float y, bool centered=false, Vec3f *color=NULL);
virtual void end();
};
virtual void begin(Font2D *font);
virtual void render(const string &text, float x, float y, bool centered = false, Vec3f *color = NULL);
virtual void end();
};
// =====================================================
// class TextRenderer3DGl
// =====================================================
// =====================================================
// class TextRenderer3DGl
// =====================================================
class TextRenderer3DGl: public TextRenderer3D {
private:
Font3DGl *font;
bool rendering;
int currentFTGLErrorCount;
class TextRenderer3DGl : public TextRenderer3D {
private:
Font3DGl *font;
bool rendering;
int currentFTGLErrorCount;
void internalRender(const string &text, float x, float y, bool centered, Vec3f *color);
void specialFTGLErrorCheckWorkaround(string text);
void internalRender(const string &text, float x, float y, bool centered, Vec3f *color);
void specialFTGLErrorCheckWorkaround(string text);
public:
TextRenderer3DGl();
virtual ~TextRenderer3DGl();
public:
TextRenderer3DGl();
virtual ~TextRenderer3DGl();
virtual void begin(Font3D *font);
virtual void render(const string &text, float x, float y, bool centered=false, Vec3f *color=NULL);
virtual void end();
};
virtual void begin(Font3D *font);
virtual void render(const string &text, float x, float y, bool centered = false, Vec3f *color = NULL);
virtual void end();
};
class TextRendererSafeWrapper {
protected:
TextRenderer *renderer;
Font *font;
bool mustEnd;
class TextRendererSafeWrapper {
protected:
TextRenderer *renderer;
Font *font;
bool mustEnd;
public:
public:
TextRendererSafeWrapper(TextRenderer *renderer,Font *font) {
mustEnd = false;
this->renderer = renderer;
this->font = font;
begin();
}
~TextRendererSafeWrapper() {
end();
}
void begin() {
if(this->renderer != NULL) {
TextRenderer2DGl *txtrender2d = dynamic_cast<TextRenderer2DGl *>(renderer);
if(txtrender2d != NULL) {
txtrender2d->begin(dynamic_cast<Font2D *>(this->font));
mustEnd = true;
}
else {
TextRenderer3DGl *txtrender3d = dynamic_cast<TextRenderer3DGl *>(renderer);
if(txtrender3d != NULL) {
mustEnd = true;
txtrender3d->begin(dynamic_cast<Font3D *>(this->font));
TextRendererSafeWrapper(TextRenderer *renderer, Font *font) {
mustEnd = false;
this->renderer = renderer;
this->font = font;
begin();
}
~TextRendererSafeWrapper() {
end();
}
}
}
}
void end() {
if(this->renderer != NULL && mustEnd == true) {
this->renderer->end();
mustEnd = false;
}
}
};
}}}//end namespace
void begin() {
if (this->renderer != NULL) {
TextRenderer2DGl *txtrender2d = dynamic_cast<TextRenderer2DGl *>(renderer);
if (txtrender2d != NULL) {
txtrender2d->begin(dynamic_cast<Font2D *>(this->font));
mustEnd = true;
} else {
TextRenderer3DGl *txtrender3d = dynamic_cast<TextRenderer3DGl *>(renderer);
if (txtrender3d != NULL) {
mustEnd = true;
txtrender3d->begin(dynamic_cast<Font3D *>(this->font));
}
}
}
}
void end() {
if (this->renderer != NULL && mustEnd == true) {
this->renderer->end();
mustEnd = false;
}
}
};
}
}
}//end namespace
#endif

View File

@@ -16,116 +16,146 @@
#include "opengl.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{ namespace Gl{
namespace Shared {
namespace Graphics {
namespace Gl {
// =====================================================
// class TextureGl
// =====================================================
// =====================================================
// class TextureGl
// =====================================================
class TextureGl {
protected:
GLuint handle;
GLuint renderBufferId;
GLuint frameBufferId;
class TextureGl {
protected:
GLuint handle;
GLuint renderBufferId;
GLuint frameBufferId;
static bool enableATIHacks;
static bool enableATIHacks;
void initRenderBuffer();
void initFrameBuffer();
void attachRenderBuffer();
void initRenderBuffer();
void initFrameBuffer();
void attachRenderBuffer();
public:
TextureGl();
virtual ~TextureGl();
public:
TextureGl();
virtual ~TextureGl();
static void setEnableATIHacks(bool value) { enableATIHacks = value; }
static bool getEnableATIHacks() { return enableATIHacks; }
static void setEnableATIHacks(bool value) {
enableATIHacks = value;
}
static bool getEnableATIHacks() {
return enableATIHacks;
}
GLuint getHandle() const {return handle;}
GLuint getRenderBufferHandle() const {return renderBufferId;}
GLuint getFrameBufferHandle() const {return frameBufferId;}
GLuint getHandle() const {
return handle;
}
GLuint getRenderBufferHandle() const {
return renderBufferId;
}
GLuint getFrameBufferHandle() const {
return frameBufferId;
}
bool supports_FBO_RBO();
void setup_FBO_RBO();
void attachFrameBufferToTexture();
void dettachFrameBufferFromTexture();
void dettachRenderBufferFromTexture();
bool checkFrameBufferStatus();
void teardown_FBO_RBO();
bool supports_FBO_RBO();
void setup_FBO_RBO();
void attachFrameBufferToTexture();
void dettachFrameBufferFromTexture();
void dettachRenderBufferFromTexture();
bool checkFrameBufferStatus();
void teardown_FBO_RBO();
virtual int getTextureWidth() const = 0;
virtual int getTextureHeight() const = 0;
virtual int getTextureWidth() const = 0;
virtual int getTextureHeight() const = 0;
void OutputTextureDebugInfo(Texture::Format format, int components, const string path,std::size_t rawSize,GLenum texType);
};
void OutputTextureDebugInfo(Texture::Format format, int components, const string path, std::size_t rawSize, GLenum texType);
};
// =====================================================
// class Texture1DGl
// =====================================================
// =====================================================
// class Texture1DGl
// =====================================================
class Texture1DGl: public Texture1D, public TextureGl {
public:
Texture1DGl();
virtual ~Texture1DGl();
class Texture1DGl : public Texture1D, public TextureGl {
public:
Texture1DGl();
virtual ~Texture1DGl();
virtual void init(Filter filter, int maxAnisotropy= 1);
virtual void end(bool deletePixelBuffer=true);
virtual void init(Filter filter, int maxAnisotropy = 1);
virtual void end(bool deletePixelBuffer = true);
virtual int getTextureWidth() const { return Texture1D::getTextureWidth();}
virtual int getTextureHeight() const { return Texture1D::getTextureHeight();}
};
virtual int getTextureWidth() const {
return Texture1D::getTextureWidth();
}
virtual int getTextureHeight() const {
return Texture1D::getTextureHeight();
}
};
// =====================================================
// class Texture2DGl
// =====================================================
// =====================================================
// class Texture2DGl
// =====================================================
class Texture2DGl: public Texture2D, public TextureGl{
public:
Texture2DGl();
virtual ~Texture2DGl();
class Texture2DGl : public Texture2D, public TextureGl {
public:
Texture2DGl();
virtual ~Texture2DGl();
virtual void init(Filter filter, int maxAnisotropy= 1);
virtual void end(bool deletePixelBuffer=true);
virtual void init(Filter filter, int maxAnisotropy = 1);
virtual void end(bool deletePixelBuffer = true);
virtual int getTextureWidth() const { return Texture2D::getTextureWidth();}
virtual int getTextureHeight() const { return Texture2D::getTextureHeight();}
};
virtual int getTextureWidth() const {
return Texture2D::getTextureWidth();
}
virtual int getTextureHeight() const {
return Texture2D::getTextureHeight();
}
};
// =====================================================
// class Texture3DGl
// =====================================================
// =====================================================
// class Texture3DGl
// =====================================================
class Texture3DGl: public Texture3D, public TextureGl{
public:
class Texture3DGl : public Texture3D, public TextureGl {
public:
Texture3DGl();
virtual ~Texture3DGl();
Texture3DGl();
virtual ~Texture3DGl();
virtual void init(Filter filter, int maxAnisotropy= 1);
virtual void end(bool deletePixelBuffer=true);
virtual void init(Filter filter, int maxAnisotropy = 1);
virtual void end(bool deletePixelBuffer = true);
virtual int getTextureWidth() const { return Texture3D::getTextureWidth();}
virtual int getTextureHeight() const { return Texture3D::getTextureHeight();}
};
virtual int getTextureWidth() const {
return Texture3D::getTextureWidth();
}
virtual int getTextureHeight() const {
return Texture3D::getTextureHeight();
}
};
// =====================================================
// class TextureCubeGl
// =====================================================
// =====================================================
// class TextureCubeGl
// =====================================================
class TextureCubeGl: public TextureCube, public TextureGl{
public:
class TextureCubeGl : public TextureCube, public TextureGl {
public:
TextureCubeGl();
virtual ~TextureCubeGl();
TextureCubeGl();
virtual ~TextureCubeGl();
virtual void init(Filter filter, int maxAnisotropy= 1);
virtual void end(bool deletePixelBuffer=true);
virtual void init(Filter filter, int maxAnisotropy = 1);
virtual void end(bool deletePixelBuffer = true);
virtual int getTextureWidth() const { return TextureCube::getTextureWidth();}
virtual int getTextureHeight() const { return TextureCube::getTextureHeight();}
virtual int getTextureWidth() const {
return TextureCube::getTextureWidth();
}
virtual int getTextureHeight() const {
return TextureCube::getTextureHeight();
}
};
};
}}}//end namespace
}
}
}//end namespace
#endif

View File

@@ -20,75 +20,118 @@ using std::string;
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class Context;
class Context;
class TextureManager;
class Texture1D;
class Texture2D;
class Texture3D;
class TextureCube;
class ModelManager;
class ModelRenderer;
class Model;
class TextureManager;
class Texture1D;
class Texture2D;
class Texture3D;
class TextureCube;
class FontManager;
class TextRenderer2D;
class TextRenderer3D;
class Font2D;
class Font3D;
class ModelManager;
class ModelRenderer;
class Model;
class ParticleManager;
class ParticleRenderer;
class ShaderManager;
class ShaderProgram;
class VertexShader;
class FragmentShader;
class FontManager;
class TextRenderer2D;
class TextRenderer3D;
class Font2D;
class Font3D;
// =====================================================
// class GraphicsFactory
// =====================================================
class ParticleManager;
class ParticleRenderer;
class GraphicsFactory{
public:
virtual ~GraphicsFactory(){}
class ShaderManager;
class ShaderProgram;
class VertexShader;
class FragmentShader;
//context
virtual Context *newContext() {return NULL;}
// =====================================================
// class GraphicsFactory
// =====================================================
//textures
virtual TextureManager *newTextureManager() {return NULL;}
virtual Texture1D *newTexture1D() {return NULL;}
virtual Texture2D *newTexture2D() {return NULL;}
virtual Texture3D *newTexture3D() {return NULL;}
virtual TextureCube *newTextureCube() {return NULL;}
//models
virtual ModelManager *newModelManager() {return NULL;}
virtual ModelRenderer *newModelRenderer() {return NULL;}
virtual Model *newModel(const string &path,TextureManager* textureManager,bool deletePixMapAfterLoad,std::map<string,std::vector<std::pair<string, string> > > *loadedFileList, string *sourceLoader) {return NULL;}
class GraphicsFactory {
public:
virtual ~GraphicsFactory() {
}
//text
virtual FontManager *newFontManager() {return NULL;}
virtual TextRenderer2D *newTextRenderer2D() {return NULL;}
virtual TextRenderer3D *newTextRenderer3D() {return NULL;}
virtual Font2D *newFont2D() {return NULL;}
virtual Font3D *newFont3D() {return NULL;}
//context
virtual Context *newContext() {
return NULL;
}
//particles
virtual ParticleManager *newParticleManager() {return NULL;}
virtual ParticleRenderer *newParticleRenderer() {return NULL;}
//shaders
virtual ShaderManager *newShaderManager() {return NULL;}
virtual ShaderProgram *newShaderProgram() {return NULL;}
virtual VertexShader *newVertexShader() {return NULL;}
virtual FragmentShader *newFragmentShader() {return NULL;}
};
//textures
virtual TextureManager *newTextureManager() {
return NULL;
}
virtual Texture1D *newTexture1D() {
return NULL;
}
virtual Texture2D *newTexture2D() {
return NULL;
}
virtual Texture3D *newTexture3D() {
return NULL;
}
virtual TextureCube *newTextureCube() {
return NULL;
}
}}//end namespace
//models
virtual ModelManager *newModelManager() {
return NULL;
}
virtual ModelRenderer *newModelRenderer() {
return NULL;
}
virtual Model *newModel(const string &path, TextureManager* textureManager, bool deletePixMapAfterLoad, std::map<string, std::vector<std::pair<string, string> > > *loadedFileList, string *sourceLoader) {
return NULL;
}
//text
virtual FontManager *newFontManager() {
return NULL;
}
virtual TextRenderer2D *newTextRenderer2D() {
return NULL;
}
virtual TextRenderer3D *newTextRenderer3D() {
return NULL;
}
virtual Font2D *newFont2D() {
return NULL;
}
virtual Font3D *newFont3D() {
return NULL;
}
//particles
virtual ParticleManager *newParticleManager() {
return NULL;
}
virtual ParticleRenderer *newParticleRenderer() {
return NULL;
}
//shaders
virtual ShaderManager *newShaderManager() {
return NULL;
}
virtual ShaderProgram *newShaderProgram() {
return NULL;
}
virtual VertexShader *newVertexShader() {
return NULL;
}
virtual FragmentShader *newFragmentShader() {
return NULL;
}
};
}
}//end namespace
#endif

View File

@@ -17,67 +17,75 @@
using namespace Shared::Map;
namespace Shared { namespace Graphics {
namespace Shared {
namespace Graphics {
class GraphicsFactory;
class Context;
class Texture2D;
class Model;
class GraphicsFactory;
class Context;
class Texture2D;
class Model;
enum ResourceScope {
rsGlobal,
rsMenu,
rsGame,
enum ResourceScope {
rsGlobal,
rsMenu,
rsGame,
rsCount
};
rsCount
};
class RendererInterface {
public:
virtual Texture2D *newTexture2D(ResourceScope rs) = 0;
virtual Model *newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad=false,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL, string *sourceLoader=NULL) = 0;
class RendererInterface {
public:
virtual Texture2D *newTexture2D(ResourceScope rs) = 0;
virtual Model *newModel(ResourceScope rs, const string &path, bool deletePixMapAfterLoad = false, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string *sourceLoader = NULL) = 0;
virtual ~RendererInterface() {}
};
virtual ~RendererInterface() {
}
};
class RendererMapInterface {
public:
virtual void initMapSurface(int clientW, int clientH) = 0;
virtual void renderMap(MapPreview *map, int x, int y, int clientW, int clientH, int cellSize, bool grid, bool heightMap, bool hideWater) = 0;
class RendererMapInterface {
public:
virtual void initMapSurface(int clientW, int clientH) = 0;
virtual void renderMap(MapPreview *map, int x, int y, int clientW, int clientH, int cellSize, bool grid, bool heightMap, bool hideWater) = 0;
virtual ~RendererMapInterface() {}
};
virtual ~RendererMapInterface() {
}
};
// =====================================================
// class GraphicsInterface
//
/// Interface for the graphic engine
// =====================================================
// =====================================================
// class GraphicsInterface
//
/// Interface for the graphic engine
// =====================================================
class GraphicsInterface {
private:
GraphicsFactory *graphicsFactory;
Context *currentContext;
class GraphicsInterface {
private:
GraphicsFactory *graphicsFactory;
Context *currentContext;
private:
friend class TextureManager;
friend class FontManager;
private:
friend class TextureManager;
friend class FontManager;
private:
GraphicsInterface();
GraphicsInterface(GraphicsInterface &);
void operator=(GraphicsInterface &);
private:
GraphicsInterface();
GraphicsInterface(GraphicsInterface &);
void operator=(GraphicsInterface &);
public:
static GraphicsInterface &getInstance();
public:
static GraphicsInterface &getInstance();
void setFactory(GraphicsFactory *graphicsFactory);
void setCurrentContext(Context *context);
void setFactory(GraphicsFactory *graphicsFactory);
void setCurrentContext(Context *context);
Context *getCurrentContext() const {return currentContext;}
GraphicsFactory *getFactory() const {return graphicsFactory;}
};
Context *getCurrentContext() const {
return currentContext;
}
GraphicsFactory *getFactory() const {
return graphicsFactory;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -17,39 +17,47 @@
#include <map>
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class InterpolationData
// =====================================================
// =====================================================
// class InterpolationData
// =====================================================
class InterpolationData{
private:
const Mesh *mesh;
class InterpolationData {
private:
const Mesh *mesh;
Vec3f *vertices;
Vec3f *normals;
Vec3f *vertices;
Vec3f *normals;
int raw_frame_ofs;
int raw_frame_ofs;
static bool enableInterpolation;
void update(const Vec3f* src, Vec3f* &dest, float t, bool cycle);
static bool enableInterpolation;
public:
InterpolationData(const Mesh *mesh);
~InterpolationData();
void update(const Vec3f* src, Vec3f* &dest, float t, bool cycle);
static void setEnableInterpolation(bool enabled) { enableInterpolation = enabled; }
public:
InterpolationData(const Mesh *mesh);
~InterpolationData();
const Vec3f *getVertices() const {return !vertices || !enableInterpolation? mesh->getVertices()+raw_frame_ofs: vertices;}
const Vec3f *getNormals() const {return !normals || !enableInterpolation? mesh->getNormals()+raw_frame_ofs: normals;}
void update(float t, bool cycle);
void updateVertices(float t, bool cycle);
void updateNormals(float t, bool cycle);
};
static void setEnableInterpolation(bool enabled) {
enableInterpolation = enabled;
}
}}//end namespace
const Vec3f *getVertices() const {
return !vertices || !enableInterpolation ? mesh->getVertices() + raw_frame_ofs : vertices;
}
const Vec3f *getNormals() const {
return !normals || !enableInterpolation ? mesh->getNormals() + raw_frame_ofs : normals;
}
void update(float t, bool cycle);
void updateVertices(float t, bool cycle);
void updateNormals(float t, bool cycle);
};
}
}//end namespace
#endif

View File

@@ -20,299 +20,301 @@
using namespace std;
using namespace Shared::Platform;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
const float pi= 3.1415926f;
const float sqrt2= 1.41421356f;
const float zero= 1e-6f;
const float infinity= 1e6f;
const float pi = 3.1415926f;
const float sqrt2 = 1.41421356f;
const float zero = 1e-6f;
const float infinity = 1e6f;
// =====================================================
// class Rect
// =====================================================
// =====================================================
// class Rect
// =====================================================
// 0 +-+
// | |
// +-+ 1
// 0 +-+
// | |
// +-+ 1
template<typename T>
class Rect2{
public:
Vec2<T> p[2];
public:
Rect2(){
};
template<typename T>
class Rect2 {
public:
Vec2<T> p[2];
public:
Rect2() {
};
Rect2(const Vec2<T> &p0, const Vec2<T> &p1){
this->p[0]= p0;
this->p[1]= p1;
}
Rect2(T p0x, T p0y, T p1x, T p1y){
p[0].x= p0x;
p[0].y= p0y;
p[1].x= p1x;
p[1].y= p1y;
}
Rect2<T> operator*(T scalar){
return Rect2<T>(
p[0]*scalar,
p[1]*scalar);
}
Rect2<T> operator/(T scalar){
return Rect2<T>(
p[0]/scalar,
p[1]/scalar);
}
bool isInside(const Vec2<T> &p) const{
return
p.x>=this->p[0].x &&
p.y>=this->p[0].y &&
p.x<this->p[1].x &&
p.y<this->p[1].y;
}
void clamp(T minX, T minY,T maxX, T maxY){
for(int i=0; i<2; ++i){
if(p[i].x<minX){
p[i].x= minX;
Rect2(const Vec2<T> &p0, const Vec2<T> &p1) {
this->p[0] = p0;
this->p[1] = p1;
}
if(p[i].y<minY){
p[i].y= minY;
Rect2(T p0x, T p0y, T p1x, T p1y) {
p[0].x = p0x;
p[0].y = p0y;
p[1].x = p1x;
p[1].y = p1y;
}
if(p[i].x>maxX){
p[i].x= maxX;
Rect2<T> operator*(T scalar) {
return Rect2<T>(
p[0] * scalar,
p[1] * scalar);
}
if(p[i].y>maxY){
p[i].y= maxY;
Rect2<T> operator/(T scalar) {
return Rect2<T>(
p[0] / scalar,
p[1] / scalar);
}
}
}
std::string getString() const {
std::ostringstream streamOut;
streamOut << "#1: " << this->p[0].getString();
streamOut << "#2: " << this->p[1].getString();
std::string result = streamOut.str();
streamOut.str(std::string());
return result;
}
bool isInside(const Vec2<T> &p) const {
return
p.x >= this->p[0].x &&
p.y >= this->p[0].y &&
p.x < this->p[1].x &&
p.y < this->p[1].y;
}
};
void clamp(T minX, T minY, T maxX, T maxY) {
for (int i = 0; i < 2; ++i) {
if (p[i].x < minX) {
p[i].x = minX;
}
if (p[i].y < minY) {
p[i].y = minY;
}
if (p[i].x > maxX) {
p[i].x = maxX;
}
if (p[i].y > maxY) {
p[i].y = maxY;
}
}
}
typedef Rect2<int> Rect2i;
typedef Rect2<char> Rect2c;
typedef Rect2<float> Rect2f;
typedef Rect2<double> Rect2d;
std::string getString() const {
std::ostringstream streamOut;
streamOut << "#1: " << this->p[0].getString();
streamOut << "#2: " << this->p[1].getString();
std::string result = streamOut.str();
streamOut.str(std::string());
return result;
}
// =====================================================
// class Quad
// =====================================================
};
// 0 +-+ 2
// | |
// 1 +-+ 3
typedef Rect2<int> Rect2i;
typedef Rect2<char> Rect2c;
typedef Rect2<float> Rect2f;
typedef Rect2<double> Rect2d;
template<typename T>
class Quad2{
public:
Vec2<T> p[4];
public:
Quad2(){
};
// =====================================================
// class Quad
// =====================================================
Quad2(const Vec2<T> &p0, const Vec2<T> &p1, const Vec2<T> &p2, const Vec2<T> &p3){
this->p[0]= p0;
this->p[1]= p1;
this->p[2]= p2;
this->p[3]= p3;
}
// 0 +-+ 2
// | |
// 1 +-+ 3
explicit Quad2(const Rect2<T> &rect){
this->p[0]= rect.p[0];
this->p[1]= Vec2<T>(rect.p[0].x, rect.p[1].y);
this->p[2]= rect.p[1];
this->p[3]= Vec2<T>(rect.p[1].x, rect.p[0].y);
}
template<typename T>
class Quad2 {
public:
Vec2<T> p[4];
public:
Quad2() {
};
Quad2<T> operator*(T scalar){
return Quad2<T>(
p[0]*scalar,
p[1]*scalar,
p[2]*scalar,
p[3]*scalar);
}
Quad2(const Vec2<T> &p0, const Vec2<T> &p1, const Vec2<T> &p2, const Vec2<T> &p3) {
this->p[0] = p0;
this->p[1] = p1;
this->p[2] = p2;
this->p[3] = p3;
}
Quad2<T> operator/(T scalar){
return Quad2<T>(
p[0]/scalar,
p[1]/scalar,
p[2]/scalar,
p[3]/scalar);
}
explicit Quad2(const Rect2<T> &rect) {
this->p[0] = rect.p[0];
this->p[1] = Vec2<T>(rect.p[0].x, rect.p[1].y);
this->p[2] = rect.p[1];
this->p[3] = Vec2<T>(rect.p[1].x, rect.p[0].y);
}
bool operator <(const Quad2<T> &v) const {
if(p[0] < v.p[0]) {
return true;
}
if(p[1] < v.p[1]) {
return true;
}
if(p[2] < v.p[2]) {
return true;
}
if(p[3] < v.p[3]) {
return true;
}
return false;
}
Quad2<T> operator*(T scalar) {
return Quad2<T>(
p[0] * scalar,
p[1] * scalar,
p[2] * scalar,
p[3] * scalar);
}
bool operator !=(const Quad2<T> &v) const {
if(p[0] != v.p[0]) {
return true;
}
if(p[1] != v.p[1]) {
return true;
}
if(p[2] != v.p[2]) {
return true;
}
if(p[3] != v.p[3]) {
return true;
}
return false;
}
Quad2<T> operator/(T scalar) {
return Quad2<T>(
p[0] / scalar,
p[1] / scalar,
p[2] / scalar,
p[3] / scalar);
}
Rect2<T> computeBoundingRect() const{
return Rect2i(
bool operator <(const Quad2<T> &v) const {
if (p[0] < v.p[0]) {
return true;
}
if (p[1] < v.p[1]) {
return true;
}
if (p[2] < v.p[2]) {
return true;
}
if (p[3] < v.p[3]) {
return true;
}
return false;
}
bool operator !=(const Quad2<T> &v) const {
if (p[0] != v.p[0]) {
return true;
}
if (p[1] != v.p[1]) {
return true;
}
if (p[2] != v.p[2]) {
return true;
}
if (p[3] != v.p[3]) {
return true;
}
return false;
}
Rect2<T> computeBoundingRect() const {
return Rect2i(
#ifdef WIN32
min(p[0].x, p[1].x),
min(p[0].y, p[2].y),
max(p[2].x, p[3].x),
max(p[1].y, p[3].y));
min(p[0].x, p[1].x),
min(p[0].y, p[2].y),
max(p[2].x, p[3].x),
max(p[1].y, p[3].y));
#else
std::min(p[0].x, p[1].x),
std::min(p[0].y, p[2].y),
std::max(p[2].x, p[3].x),
std::max(p[1].y, p[3].y));
std::min(p[0].x, p[1].x),
std::min(p[0].y, p[2].y),
std::max(p[2].x, p[3].x),
std::max(p[1].y, p[3].y));
#endif
}
bool isInside(const Vec2<T> &pt) const{
if(!computeBoundingRect().isInside(pt))
return false;
bool left[4];
left[0]= (pt.y - p[0].y)*(p[1].x - p[0].x) - (pt.x - p[0].x)*(p[1].y - p[0].y) < 0;
left[1]= (pt.y - p[1].y)*(p[3].x - p[1].x) - (pt.x - p[1].x)*(p[3].y - p[1].y) < 0;
left[2]= (pt.y - p[3].y)*(p[2].x - p[3].x) - (pt.x - p[3].x)*(p[2].y - p[3].y) < 0;
left[3]= (pt.y - p[2].y)*(p[0].x - p[2].x) - (pt.x - p[2].x)*(p[0].y - p[2].y) < 0;
return left[0] && left[1] && left[2] && left[3];
}
void clamp(T minX, T minY, T maxX, T maxY){
for(int i=0; i<4; ++i){
if(p[i].x<minX){
p[i].x= minX;
}
if(p[i].y<minY){
p[i].y= minY;
bool isInside(const Vec2<T> &pt) const {
if (!computeBoundingRect().isInside(pt))
return false;
bool left[4];
left[0] = (pt.y - p[0].y)*(p[1].x - p[0].x) - (pt.x - p[0].x)*(p[1].y - p[0].y) < 0;
left[1] = (pt.y - p[1].y)*(p[3].x - p[1].x) - (pt.x - p[1].x)*(p[3].y - p[1].y) < 0;
left[2] = (pt.y - p[3].y)*(p[2].x - p[3].x) - (pt.x - p[3].x)*(p[2].y - p[3].y) < 0;
left[3] = (pt.y - p[2].y)*(p[0].x - p[2].x) - (pt.x - p[2].x)*(p[0].y - p[2].y) < 0;
return left[0] && left[1] && left[2] && left[3];
}
if(p[i].x>maxX){
p[i].x= maxX;
void clamp(T minX, T minY, T maxX, T maxY) {
for (int i = 0; i < 4; ++i) {
if (p[i].x < minX) {
p[i].x = minX;
}
if (p[i].y < minY) {
p[i].y = minY;
}
if (p[i].x > maxX) {
p[i].x = maxX;
}
if (p[i].y > maxY) {
p[i].y = maxY;
}
}
}
if(p[i].y>maxY){
p[i].y= maxY;
float area() {
Vec2i v0 = p[3] - p[0];
Vec2i v1 = p[1] - p[2];
return 0.5f * ((v0.x * v1.y) - (v0.y * v1.x));
}
std::string getString() const {
std::ostringstream streamOut;
streamOut << "#1: " << this->p[0].getString();
streamOut << "#2: " << this->p[1].getString();
streamOut << "#3: " << this->p[2].getString();
streamOut << "#4: " << this->p[3].getString();
std::string result = streamOut.str();
streamOut.str(std::string());
return result;
}
};
typedef Quad2<int> Quad2i;
typedef Quad2<char> Quad2c;
typedef Quad2<float> Quad2f;
typedef Quad2<double> Quad2d;
// =====================================================
// Misc
// =====================================================
inline int next2Power(int n) {
int i;
for (i = 1; i < n; i *= 2);
return i;
}
template<typename T>
inline T degToRad(T deg) {
return (deg * 2 * pi) / 360;
}
template<typename T>
inline T radToDeg(T rad) {
return (rad * 360) / (2 * pi);
}
// ====================================================================================================================
// ====================================================================================================================
// Inline implementation
// ====================================================================================================================
// ====================================================================================================================
//#if _xs_BigEndian_
// #define _xs_iexp_ 0
// #define _xs_iman_ 1
//#else
// #define _xs_iexp_ 1 //intel is little endian
// #define _xs_iman_ 0
//#endif //BigEndian_
//
////#define finline __forceinline
//#define finline inline
//
//#ifndef _xs_DEFAULT_CONVERSION
//#define _xs_DEFAULT_CONVERSION 0
//#endif
//
////typedef long int32;
//typedef double real64;
//const real64 _xs_doublemagic = real64 (6755399441055744.0); //2^52 * 1.5, uses limited precisicion to floor
//
//finline int32 xs_CRoundToInt(real64 val, real64 dmr = _xs_doublemagic) {
//#if _xs_DEFAULT_CONVERSION==0
// val = val + dmr;
// return ((int32*)&val)[_xs_iman_];
// //return 0;
//#else
// return int32(floor(val+.5));
//#endif
//}
}
float area() {
Vec2i v0= p[3]-p[0];
Vec2i v1= p[1]-p[2];
return 0.5f * ((v0.x * v1.y) - (v0.y * v1.x));
}
std::string getString() const {
std::ostringstream streamOut;
streamOut << "#1: " << this->p[0].getString();
streamOut << "#2: " << this->p[1].getString();
streamOut << "#3: " << this->p[2].getString();
streamOut << "#4: " << this->p[3].getString();
std::string result = streamOut.str();
streamOut.str(std::string());
return result;
}
};
typedef Quad2<int> Quad2i;
typedef Quad2<char> Quad2c;
typedef Quad2<float> Quad2f;
typedef Quad2<double> Quad2d;
// =====================================================
// Misc
// =====================================================
inline int next2Power(int n){
int i;
for (i=1; i<n; i*=2);
return i;
}
template<typename T>
inline T degToRad(T deg){
return (deg*2*pi)/360;
}
template<typename T>
inline T radToDeg(T rad){
return (rad*360)/(2*pi);
}
// ====================================================================================================================
// ====================================================================================================================
// Inline implementation
// ====================================================================================================================
// ====================================================================================================================
//#if _xs_BigEndian_
// #define _xs_iexp_ 0
// #define _xs_iman_ 1
//#else
// #define _xs_iexp_ 1 //intel is little endian
// #define _xs_iman_ 0
//#endif //BigEndian_
//
////#define finline __forceinline
//#define finline inline
//
//#ifndef _xs_DEFAULT_CONVERSION
//#define _xs_DEFAULT_CONVERSION 0
//#endif
//
////typedef long int32;
//typedef double real64;
//const real64 _xs_doublemagic = real64 (6755399441055744.0); //2^52 * 1.5, uses limited precisicion to floor
//
//finline int32 xs_CRoundToInt(real64 val, real64 dmr = _xs_doublemagic) {
//#if _xs_DEFAULT_CONVERSION==0
// val = val + dmr;
// return ((int32*)&val)[_xs_iman_];
// //return 0;
//#else
// return int32(floor(val+.5));
//#endif
//}
}}//end namespace
}//end namespace
#endif

View File

@@ -15,147 +15,151 @@
#include "vec.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class Matrix3
// =====================================================
// =====================================================
// class Matrix3
// =====================================================
template<typename T>
class Matrix3{
private:
T data[9];
public:
Matrix3(){};
template<typename T>
class Matrix3 {
private:
T data[9];
public:
Matrix3() {
};
Matrix3(T *p){
for(int i=0; i<9; ++i){
data[i]= p[i];
}
}
T *ptr(){
return data;
}
const T *ptr() const{
return data;
}
T &operator[](int i){
return data[i];
}
T &operator()(int i, int j){
return data[i*3+j];
}
Vec3<T> operator * (const Vec3<T> &v) const{
Vec3<T> rv;
return Vec3f(
data[0]*v.x + data[1]*v.y + data[2]*v.z,
data[3]*v.x + data[4]*v.y + data[5]*v.z,
data[6]*v.x + data[7]*v.y + data[8]*v.z);
}
Matrix3<T> operator * (const Matrix3<T> &m) const{
Matrix3<T> rm;
for(int i=0; i<3; ++i){
for(int j=0; j<3; ++j){
T acum= 0.0f;
for(int k=0; k<3; ++k){
acum+= data[i*3+k]*m[k*3+j];
Matrix3(T *p) {
for (int i = 0; i < 9; ++i) {
data[i] = p[i];
}
rm[i*3+j]= acum;
}
}
return rm;
}
void traspose(){
for(int i=0; i<3; ++i){
for(int j=0; j<3; ++j){
T tmp= data[j*3+i];
data[j*3+i]= data[i*3+j];
data[i*3+j]= tmp;
T *ptr() {
return data;
}
}
}
};
typedef Matrix3<float> Matrix3f;
typedef Matrix3<double> Matrix3d;
const T *ptr() const {
return data;
}
// =====================================================
// class Matrix4
// =====================================================
T &operator[](int i) {
return data[i];
}
template<typename T>
class Matrix4{
private:
T data[16];
public:
Matrix4(){};
T &operator()(int i, int j) {
return data[i * 3 + j];
}
Matrix4(T *p){
for(int i=0; i<16; ++i){
data[i]= p[i];
}
}
Vec3<T> operator * (const Vec3<T> &v) const {
Vec3<T> rv;
T *ptr(){
return data;
}
return Vec3f(
data[0] * v.x + data[1] * v.y + data[2] * v.z,
data[3] * v.x + data[4] * v.y + data[5] * v.z,
data[6] * v.x + data[7] * v.y + data[8] * v.z);
}
const T *ptr() const{
return data;
}
Matrix3<T> operator * (const Matrix3<T> &m) const {
Matrix3<T> rm;
T &operator[](int i){
return data[i];
}
const T &operator[](int i) const{
return data[i];
}
T &operator()(int i, int j){
return data[i*4+j];
}
Vec4<T> operator * (const Vec4<T> &v) const{
Vec4<T> rv;
return Vec4f(
data[0]*v.x + data[1]*v.y + data[2]*v.z + data[3]*v.w,
data[4]*v.x + data[5]*v.y + data[6]*v.z + data[7]*v.w,
data[8]*v.x + data[9]*v.y + data[10]*v.z + data[11]*v.w,
data[12]*v.x + data[13]*v.y + data[14]*v.z + data[15]*v.w);
}
Matrix4<T> operator * (const Matrix4<T> &m) const{
Matrix4<T> rm;
for(int i=0; i<4; ++i){
for(int j=0; j<4; ++j){
T acum= 0.0f;
for(int k=0; k<4; ++k){
acum+= data[i*4+k]*m[k*4+j];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
T acum = 0.0f;
for (int k = 0; k < 3; ++k) {
acum += data[i * 3 + k] * m[k * 3 + j];
}
rm[i * 3 + j] = acum;
}
}
rm[i*4+j]= acum;
return rm;
}
}
return rm;
void traspose() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
T tmp = data[j * 3 + i];
data[j * 3 + i] = data[i * 3 + j];
data[i * 3 + j] = tmp;
}
}
}
};
typedef Matrix3<float> Matrix3f;
typedef Matrix3<double> Matrix3d;
// =====================================================
// class Matrix4
// =====================================================
template<typename T>
class Matrix4 {
private:
T data[16];
public:
Matrix4() {
};
Matrix4(T *p) {
for (int i = 0; i < 16; ++i) {
data[i] = p[i];
}
}
T *ptr() {
return data;
}
const T *ptr() const {
return data;
}
T &operator[](int i) {
return data[i];
}
const T &operator[](int i) const {
return data[i];
}
T &operator()(int i, int j) {
return data[i * 4 + j];
}
Vec4<T> operator * (const Vec4<T> &v) const {
Vec4<T> rv;
return Vec4f(
data[0] * v.x + data[1] * v.y + data[2] * v.z + data[3] * v.w,
data[4] * v.x + data[5] * v.y + data[6] * v.z + data[7] * v.w,
data[8] * v.x + data[9] * v.y + data[10] * v.z + data[11] * v.w,
data[12] * v.x + data[13] * v.y + data[14] * v.z + data[15] * v.w);
}
Matrix4<T> operator * (const Matrix4<T> &m) const {
Matrix4<T> rm;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
T acum = 0.0f;
for (int k = 0; k < 4; ++k) {
acum += data[i * 4 + k] * m[k * 4 + j];
}
rm[i * 4 + j] = acum;
}
}
return rm;
}
};
typedef Matrix4<float> Matrix4f;
typedef Matrix4<double> Matrix4d;
}
};
typedef Matrix4<float> Matrix4f;
typedef Matrix4<double> Matrix4d;
}} //enmd namespace
} //enmd namespace
#endif

View File

@@ -28,304 +28,378 @@ using std::string;
using std::map;
using std::pair;
namespace Shared { namespace Graphics {
class Model;
class Mesh;
class ShadowVolumeData;
class InterpolationData;
class TextureManager;
// =====================================================
// class Mesh
//
// Part of a 3D model
// =====================================================
class Mesh {
private:
//mesh data
Texture2D *textures[meshTextureCount];
bool texturesOwned[meshTextureCount];
string texturePaths[meshTextureCount];
string name;
//vertex data counts
uint32 frameCount;
uint32 vertexCount;
uint32 indexCount;
uint32 texCoordFrameCount;
//vertex data
Vec3f *vertices;
Vec3f *normals;
Vec2f *texCoords;
Vec3f *tangents;
uint32 *indices;
//material data
Vec3f diffuseColor;
Vec3f specularColor;
float specularPower;
float opacity;
//properties
bool twoSided;
bool customColor;
bool noSelect;
bool glow;
uint32 textureFlags;
InterpolationData *interpolationData;
TextureManager *textureManager;
// Vertex Buffer Object Names
bool hasBuiltVBOs;
uint32 m_nVBOVertices; // Vertex VBO Name
uint32 m_nVBOTexCoords; // Texture Coordinate VBO Name
uint32 m_nVBONormals; // Normal VBO Name
uint32 m_nVBOIndexes; // Indexes VBO Name
public:
//init & end
Mesh();
~Mesh();
void init();
void end();
void copyInto(Mesh *dest, bool ignoreInterpolationData, bool destinationOwnsTextures);
//maps
const Texture2D *getTexture(int i) const {return textures[i];}
//counts
uint32 getFrameCount() const {return frameCount;}
uint32 getVertexCount() const {return vertexCount;}
uint32 getIndexCount() const {return indexCount;}
uint32 getTriangleCount() const;
uint32 getVBOVertices() const { return m_nVBOVertices;}
uint32 getVBOTexCoords() const { return m_nVBOTexCoords;}
uint32 getVBONormals() const { return m_nVBONormals;}
uint32 getVBOIndexes() const { return m_nVBOIndexes;}
bool hasBuiltVBOEntities() const { return hasBuiltVBOs;}
void BuildVBOs();
void ReleaseVBOs();
//data
const Vec3f *getVertices() const {return vertices;}
const Vec3f *getNormals() const {return normals;}
const Vec2f *getTexCoords() const {return texCoords;}
const Vec3f *getTangents() const {return tangents;}
const uint32 *getIndices() const {return indices;}
void setVertices(Vec3f *data, uint32 count);
void setNormals(Vec3f *data, uint32 count);
void setTexCoords(Vec2f *data, uint32 count);
void setIndices(uint32 *data, uint32 count);
//material
const Vec3f &getDiffuseColor() const {return diffuseColor;}
const Vec3f &getSpecularColor() const {return specularColor;}
float getSpecularPower() const {return specularPower;}
float getOpacity() const {return opacity;}
//properties
bool getTwoSided() const {return twoSided;}
bool getCustomTexture() const {return customColor;}
bool getNoSelect() const {return noSelect;}
bool getGlow() const {return glow;}
string getName() const {return name;}
uint32 getTextureFlags() const { return textureFlags; }
//external data
const InterpolationData *getInterpolationData() const {return interpolationData;}
//interpolation
void buildInterpolationData();
void cleanupInterpolationData();
void updateInterpolationData(float t, bool cycle);
void updateInterpolationVertices(float t, bool cycle);
Texture2D *loadMeshTexture(int meshIndex, int textureIndex, TextureManager *textureManager, string textureFile,
int textureChannelCount, bool &textureOwned,
bool deletePixMapAfterLoad, std::map<string,vector<pair<string, string> > > *loadedFileList=NULL,
string sourceLoader="",string modelFile="");
//load
void loadV2(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL,string sourceLoader="",string modelFile="");
void loadV3(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL,string sourceLoader="",string modelFile="");
void load(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL,string sourceLoader="",string modelFile="");
void save(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
string convertTextureToFormat, std::map<string,int> &textureDeleteList,
bool keepsmallest,string modelFile);
void deletePixels();
void toEndian();
void fromEndian();
private:
string findAlternateTexture(vector<string> conversionList, string textureFile);
void computeTangents();
};
// =====================================================
// class Model
//
// 3D Model, than can be loaded from a g3d file
// =====================================================
class Model {
private:
TextureManager *textureManager;
private:
uint8 fileVersion;
uint32 meshCount;
Mesh *meshes;
float lastTData;
bool lastCycleData;
float lastTVertex;
bool lastCycleVertex;
string fileName;
string sourceLoader;
//static bool masterserverMode;
public:
//constructor & destructor
Model();
virtual ~Model();
virtual void init()= 0;
virtual void end()= 0;
//static void setMasterserverMode(bool value) { masterserverMode=value; }
namespace Shared {
namespace Graphics {
class Model;
class Mesh;
class ShadowVolumeData;
class InterpolationData;
class TextureManager;
// =====================================================
// class Mesh
//
// Part of a 3D model
// =====================================================
class Mesh {
private:
//mesh data
Texture2D *textures[meshTextureCount];
bool texturesOwned[meshTextureCount];
string texturePaths[meshTextureCount];
string name;
//vertex data counts
uint32 frameCount;
uint32 vertexCount;
uint32 indexCount;
uint32 texCoordFrameCount;
//vertex data
Vec3f *vertices;
Vec3f *normals;
Vec2f *texCoords;
Vec3f *tangents;
uint32 *indices;
//material data
Vec3f diffuseColor;
Vec3f specularColor;
float specularPower;
float opacity;
//properties
bool twoSided;
bool customColor;
bool noSelect;
bool glow;
uint32 textureFlags;
InterpolationData *interpolationData;
TextureManager *textureManager;
// Vertex Buffer Object Names
bool hasBuiltVBOs;
uint32 m_nVBOVertices; // Vertex VBO Name
uint32 m_nVBOTexCoords; // Texture Coordinate VBO Name
uint32 m_nVBONormals; // Normal VBO Name
uint32 m_nVBOIndexes; // Indexes VBO Name
public:
//init & end
Mesh();
~Mesh();
void init();
void end();
void copyInto(Mesh *dest, bool ignoreInterpolationData, bool destinationOwnsTextures);
//maps
const Texture2D *getTexture(int i) const {
return textures[i];
}
//counts
uint32 getFrameCount() const {
return frameCount;
}
uint32 getVertexCount() const {
return vertexCount;
}
uint32 getIndexCount() const {
return indexCount;
}
uint32 getTriangleCount() const;
uint32 getVBOVertices() const {
return m_nVBOVertices;
}
uint32 getVBOTexCoords() const {
return m_nVBOTexCoords;
}
uint32 getVBONormals() const {
return m_nVBONormals;
}
uint32 getVBOIndexes() const {
return m_nVBOIndexes;
}
bool hasBuiltVBOEntities() const {
return hasBuiltVBOs;
}
void BuildVBOs();
void ReleaseVBOs();
//data
const Vec3f *getVertices() const {
return vertices;
}
const Vec3f *getNormals() const {
return normals;
}
const Vec2f *getTexCoords() const {
return texCoords;
}
const Vec3f *getTangents() const {
return tangents;
}
const uint32 *getIndices() const {
return indices;
}
void setVertices(Vec3f *data, uint32 count);
void setNormals(Vec3f *data, uint32 count);
void setTexCoords(Vec2f *data, uint32 count);
void setIndices(uint32 *data, uint32 count);
//material
const Vec3f &getDiffuseColor() const {
return diffuseColor;
}
const Vec3f &getSpecularColor() const {
return specularColor;
}
float getSpecularPower() const {
return specularPower;
}
float getOpacity() const {
return opacity;
}
//properties
bool getTwoSided() const {
return twoSided;
}
bool getCustomTexture() const {
return customColor;
}
bool getNoSelect() const {
return noSelect;
}
bool getGlow() const {
return glow;
}
string getName() const {
return name;
}
uint32 getTextureFlags() const {
return textureFlags;
}
//external data
const InterpolationData *getInterpolationData() const {
return interpolationData;
}
//interpolation
void buildInterpolationData();
void cleanupInterpolationData();
void updateInterpolationData(float t, bool cycle);
void updateInterpolationVertices(float t, bool cycle);
Texture2D *loadMeshTexture(int meshIndex, int textureIndex, TextureManager *textureManager, string textureFile,
int textureChannelCount, bool &textureOwned,
bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL,
string sourceLoader = "", string modelFile = "");
//load
void loadV2(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string sourceLoader = "", string modelFile = "");
void loadV3(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string sourceLoader = "", string modelFile = "");
void load(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager, bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string sourceLoader = "", string modelFile = "");
void save(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
string convertTextureToFormat, std::map<string, int> &textureDeleteList,
bool keepsmallest, string modelFile);
void deletePixels();
void toEndian();
void fromEndian();
private:
string findAlternateTexture(vector<string> conversionList, string textureFile);
void computeTangents();
};
// =====================================================
// class Model
//
// 3D Model, than can be loaded from a g3d file
// =====================================================
class Model {
private:
TextureManager *textureManager;
private:
uint8 fileVersion;
uint32 meshCount;
Mesh *meshes;
float lastTData;
bool lastCycleData;
float lastTVertex;
bool lastCycleVertex;
string fileName;
string sourceLoader;
//static bool masterserverMode;
public:
//constructor & destructor
Model();
virtual ~Model();
virtual void init() = 0;
virtual void end() = 0;
//static void setMasterserverMode(bool value) { masterserverMode=value; }
//data
void updateInterpolationData(float t, bool cycle);
void updateInterpolationVertices(float t, bool cycle);
void buildShadowVolumeData() const;
//get
uint8 getFileVersion() const {
return fileVersion;
}
uint32 getMeshCount() const {
return meshCount;
}
const Mesh *getMesh(int i) const {
return &meshes[i];
}
Mesh *getMeshPtr(int i) const {
return &meshes[i];
}
uint32 getTriangleCount() const;
uint32 getVertexCount() const;
//io
void save(const string &path, string convertTextureToFormat, bool keepsmallest);
void saveG3d(const string &path, string convertTextureToFormat, bool keepsmallest);
void setTextureManager(TextureManager *textureManager) {
this->textureManager = textureManager;
}
void deletePixels();
string getFileName() const {
return fileName;
}
void toEndian();
void fromEndian();
protected:
void load(const string &path, bool deletePixMapAfterLoad = false, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string *sourceLoader = NULL);
void loadG3d(const string &path, bool deletePixMapAfterLoad = false, std::map<string, vector<pair<string, string> > > *loadedFileList = NULL, string sourceLoader = "");
private:
void buildInterpolationData() const;
void autoJoinMeshFrames();
};
class PixelBufferWrapper {
public:
PixelBufferWrapper(int pboCount, int bufferSize);
~PixelBufferWrapper();
//data
void updateInterpolationData(float t, bool cycle);
void updateInterpolationVertices(float t, bool cycle);
void buildShadowVolumeData() const;
Pixmap2D *getPixelBufferFor(int x, int y, int w, int h, int colorComponents);
static void begin();
static void end();
static bool getIsPBOEnable() {
return isPBOEnabled;
}
//get
uint8 getFileVersion() const {return fileVersion;}
uint32 getMeshCount() const {return meshCount;}
const Mesh *getMesh(int i) const {return &meshes[i];}
Mesh *getMeshPtr(int i) const {return &meshes[i];}
private:
static bool isPBOEnabled;
static int index;
static vector<uint32> pboIds;
int bufferSize;
uint32 getTriangleCount() const;
uint32 getVertexCount() const;
void cleanup();
void addBuffersToPixelBuf(int pboCount);
};
//io
void save(const string &path, string convertTextureToFormat,bool keepsmallest);
void saveG3d(const string &path, string convertTextureToFormat,bool keepsmallest);
class BaseColorPickEntity {
void setTextureManager(TextureManager *textureManager) {this->textureManager= textureManager;}
void deletePixels();
public:
BaseColorPickEntity();
virtual ~BaseColorPickEntity() {
recycleUniqueColor();
}
string getFileName() const { return fileName; }
//static const int COLOR_COMPONENTS = 3;
static const int COLOR_COMPONENTS = 4;
static void init(int bufferSize);
static void beginPicking();
static void endPicking();
static vector<int> getPickedList(int x, int y, int w, int h, const vector<BaseColorPickEntity *> &rendererModels);
void toEndian();
void fromEndian();
void setUniquePickingColor() const;
bool isUniquePickingColor(unsigned char *pixel) const;
protected:
void load(const string &path,bool deletePixMapAfterLoad=false,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL, string *sourceLoader=NULL);
void loadG3d(const string &path,bool deletePixMapAfterLoad=false,std::map<string,vector<pair<string, string> > > *loadedFileList=NULL, string sourceLoader="");
string getColorDescription() const;
virtual string getUniquePickName() const = 0;
private:
void buildInterpolationData() const;
void autoJoinMeshFrames();
};
static void resetUniqueColors();
static void setUsingLoopMethod(bool value) {
using_loop_method = value;
}
class PixelBufferWrapper {
public:
PixelBufferWrapper(int pboCount,int bufferSize);
~PixelBufferWrapper();
static void setTrackColorUse(bool value) {
trackColorUse = value;
}
unsigned char * getUniqueColorID() {
return &uniqueColorID[0];
}
bool get_next_assign_color(unsigned char *assign_to);
Pixmap2D *getPixelBufferFor(int x,int y,int w,int h, int colorComponents);
static void begin();
static void end();
static bool getIsPBOEnable() { return isPBOEnabled; }
static int getUsedColorIDListSize() {
return (int) usedColorIDList.size();
}
private:
static bool isPBOEnabled;
static int index;
static vector<uint32> pboIds;
int bufferSize;
static void cleanupPBO();
void cleanup();
void addBuffersToPixelBuf(int pboCount);
};
private:
class BaseColorPickEntity {
static int bufferSizeRequired;
unsigned char uniqueColorID[COLOR_COMPONENTS];
public:
BaseColorPickEntity();
virtual ~BaseColorPickEntity() {
recycleUniqueColor();
}
static unsigned char nextColorID[COLOR_COMPONENTS];
static unsigned int nextColorRGB;
static const unsigned int k, p;
//static const int COLOR_COMPONENTS = 3;
static const int COLOR_COMPONENTS = 4;
static void init(int bufferSize);
static void beginPicking();
static void endPicking();
static vector<int> getPickedList(int x,int y,int w,int h, const vector<BaseColorPickEntity *> &rendererModels);
static bool using_loop_method;
void setUniquePickingColor() const;
bool isUniquePickingColor(unsigned char *pixel) const;
static bool trackColorUse;
static map<string, bool> usedColorIDList;
string getColorDescription() const;
virtual string getUniquePickName() const = 0;
static vector<vector<unsigned char> > nextColorIDReuseList;
static void resetUniqueColors();
static auto_ptr<PixelBufferWrapper> pbo;
//static auto_ptr<Pixmap2D> cachedPixels;
static void setUsingLoopMethod(bool value) { using_loop_method = value; }
void assign_color();
static void setTrackColorUse(bool value) { trackColorUse = value; }
unsigned char * getUniqueColorID() { return &uniqueColorID[0]; }
bool get_next_assign_color(unsigned char *assign_to);
void assign_color_using_prime(unsigned char *assign_to);
void assign_color_using_loop(unsigned char *assign_to);
static int getUsedColorIDListSize() { return (int)usedColorIDList.size(); }
void recycleUniqueColor();
};
static void cleanupPBO();
private:
static int bufferSizeRequired;
unsigned char uniqueColorID[COLOR_COMPONENTS];
static unsigned char nextColorID[COLOR_COMPONENTS];
static unsigned int nextColorRGB;
static const unsigned int k, p;
static bool using_loop_method;
static bool trackColorUse;
static map<string,bool> usedColorIDList;
static vector<vector<unsigned char> > nextColorIDReuseList;
static auto_ptr<PixelBufferWrapper> pbo;
//static auto_ptr<Pixmap2D> cachedPixels;
void assign_color();
void assign_color_using_prime(unsigned char *assign_to);
void assign_color_using_loop(unsigned char *assign_to);
void recycleUniqueColor();
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -20,102 +20,104 @@ using Shared::Platform::uint16;
using Shared::Platform::uint32;
using Shared::Platform::float32;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
#pragma pack(push, 1)
struct FileHeader{
uint8 id[3];
uint8 version;
};
struct FileHeader {
uint8 id[3];
uint8 version;
};
//version 4
//version 4
struct ModelHeader{
uint16 meshCount;
uint8 type;
};
struct ModelHeader {
uint16 meshCount;
uint8 type;
};
enum ModelType{
mtMorphMesh
};
enum ModelType {
mtMorphMesh
};
enum MeshPropertyFlag{
mpfCustomColor= 1,
mpfTwoSided= 2,
mpfNoSelect= 4,
mpfGlow= 8
};
enum MeshPropertyFlag {
mpfCustomColor = 1,
mpfTwoSided = 2,
mpfNoSelect = 4,
mpfGlow = 8
};
enum MeshTexture{
mtDiffuse,
mtSpecular,
mtNormal,
mtReflection,
mtColorMask,
enum MeshTexture {
mtDiffuse,
mtSpecular,
mtNormal,
mtReflection,
mtColorMask,
meshTextureCount
};
meshTextureCount
};
const int meshTextureChannelCount[]= {-1, 1, 3, 1, 1};
const int meshTextureChannelCount[] = { -1, 1, 3, 1, 1 };
const uint32 meshNameSize= 64;
const uint32 mapPathSize= 64;
const uint32 meshNameSize = 64;
const uint32 mapPathSize = 64;
struct MeshHeader{
uint8 name[meshNameSize];
uint32 frameCount;
uint32 vertexCount;
uint32 indexCount;
float32 diffuseColor[3];
float32 specularColor[3];
float32 specularPower;
float32 opacity;
uint32 properties;
uint32 textures;
};
struct MeshHeader {
uint8 name[meshNameSize];
uint32 frameCount;
uint32 vertexCount;
uint32 indexCount;
float32 diffuseColor[3];
float32 specularColor[3];
float32 specularPower;
float32 opacity;
uint32 properties;
uint32 textures;
};
#pragma pack(pop)
//version 3
//version 3
//front faces are clockwise faces
struct ModelHeaderV3{
uint32 meshCount;
};
//front faces are clockwise faces
struct ModelHeaderV3 {
uint32 meshCount;
};
enum MeshPropertyV3{
mp3NoTexture= 1,
mp3TwoSided= 2,
mp3CustomColor= 4
};
enum MeshPropertyV3 {
mp3NoTexture = 1,
mp3TwoSided = 2,
mp3CustomColor = 4
};
struct MeshHeaderV3{
uint32 vertexFrameCount;
uint32 normalFrameCount;
uint32 texCoordFrameCount;
uint32 colorFrameCount;
uint32 pointCount;
uint32 indexCount;
uint32 properties;
uint8 texName[64];
};
struct MeshHeaderV3 {
uint32 vertexFrameCount;
uint32 normalFrameCount;
uint32 texCoordFrameCount;
uint32 colorFrameCount;
uint32 pointCount;
uint32 indexCount;
uint32 properties;
uint8 texName[64];
};
//version 2
//version 2
struct MeshHeaderV2{
uint32 vertexFrameCount;
uint32 normalFrameCount;
uint32 texCoordFrameCount;
uint32 colorFrameCount;
uint32 pointCount;
uint32 indexCount;
uint8 hasTexture;
uint8 primitive;
uint8 cullFace;
uint8 texName[64];
};
struct MeshHeaderV2 {
uint32 vertexFrameCount;
uint32 normalFrameCount;
uint32 texCoordFrameCount;
uint32 colorFrameCount;
uint32 pointCount;
uint32 indexCount;
uint8 hasTexture;
uint8 primitive;
uint8 cullFace;
uint8 texName[64];
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -18,36 +18,40 @@
using namespace std;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class TextureManager;
class TextureManager;
// =====================================================
// class ModelManager
// =====================================================
// =====================================================
// class ModelManager
// =====================================================
class ModelManager{
protected:
typedef vector<Model*> ModelContainer;
class ModelManager {
protected:
typedef vector<Model*> ModelContainer;
protected:
ModelContainer models;
TextureManager *textureManager;
protected:
ModelContainer models;
TextureManager *textureManager;
public:
ModelManager();
virtual ~ModelManager();
public:
ModelManager();
virtual ~ModelManager();
Model *newModel(const string &path,bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList, string *sourceLoader);
Model *newModel(const string &path, bool deletePixMapAfterLoad, std::map<string, vector<pair<string, string> > > *loadedFileList, string *sourceLoader);
void init();
void end();
void endModel(Model *model,bool mustExistInList=false);
void endLastModel(bool mustExistInList=false);
void init();
void end();
void endModel(Model *model, bool mustExistInList = false);
void endLastModel(bool mustExistInList = false);
void setTextureManager(TextureManager *textureManager) {this->textureManager= textureManager;}
};
void setTextureManager(TextureManager *textureManager) {
this->textureManager = textureManager;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -16,60 +16,64 @@
#include "model.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
enum RenderMode{
rmNormal,
rmSelection,
enum RenderMode {
rmNormal,
rmSelection,
renderModeCount
};
renderModeCount
};
class Texture;
class Texture;
// =====================================================
// class MeshCallback
//
/// This gets called before rendering mesh
// =====================================================
// =====================================================
// class MeshCallback
//
/// This gets called before rendering mesh
// =====================================================
class MeshCallback{
public:
virtual ~MeshCallback(){};
virtual void execute(const Mesh *mesh)= 0;
};
class MeshCallback {
public:
virtual ~MeshCallback() {
};
virtual void execute(const Mesh *mesh) = 0;
};
// =====================================================
// class ModelRenderer
// =====================================================
// =====================================================
// class ModelRenderer
// =====================================================
class ModelRenderer{
protected:
bool renderNormals;
bool renderTextures;
bool renderColors;
bool colorPickingMode;
MeshCallback *meshCallback;
class ModelRenderer {
protected:
bool renderNormals;
bool renderTextures;
bool renderColors;
bool colorPickingMode;
MeshCallback *meshCallback;
public:
ModelRenderer() {
renderNormals = false;
renderTextures = false;
renderColors = false;
colorPickingMode = false;
public:
ModelRenderer() {
renderNormals = false;
renderTextures = false;
renderColors = false;
colorPickingMode = false;
meshCallback = NULL;
}
virtual ~ModelRenderer() {
};
virtual void begin(bool renderNormals, bool renderTextures, bool renderColors, bool colorPickingMode, MeshCallback *meshCallback = NULL) = 0;
virtual void end() = 0;
virtual void render(Model *model, int renderMode = rmNormal) = 0;
virtual void renderNormalsOnly(Model *model) = 0;
};
meshCallback= NULL;
}
virtual ~ModelRenderer(){};
virtual void begin(bool renderNormals, bool renderTextures, bool renderColors, bool colorPickingMode, MeshCallback *meshCallback= NULL)=0;
virtual void end()=0;
virtual void render(Model *model,int renderMode=rmNormal)=0;
virtual void renderNormalsOnly(Model *model)=0;
};
}}//end namespace
}//end namespace
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -15,25 +15,28 @@
#include "particle.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class ModelRenderer;
class ModelRenderer;
// =====================================================
// class ParticleRenderer
// =====================================================
// =====================================================
// class ParticleRenderer
// =====================================================
class ParticleRenderer{
public:
//particles
virtual ~ParticleRenderer(){};
virtual void renderManager(ParticleManager *pm, ModelRenderer *mr)=0;
virtual void renderSystem(ParticleSystem *ps)=0;
virtual void renderSystemLine(ParticleSystem *ps)=0;
virtual void renderSystemLineAlpha(ParticleSystem *ps)=0;
virtual void renderModel(GameParticleSystem *ps, ModelRenderer *mr)=0;
};
class ParticleRenderer {
public:
//particles
virtual ~ParticleRenderer() {
};
virtual void renderManager(ParticleManager *pm, ModelRenderer *mr) = 0;
virtual void renderSystem(ParticleSystem *ps) = 0;
virtual void renderSystemLine(ParticleSystem *ps) = 0;
virtual void renderSystemLineAlpha(ParticleSystem *ps) = 0;
virtual void renderModel(GameParticleSystem *ps, ModelRenderer *mr) = 0;
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -29,367 +29,420 @@ using Shared::Platform::uint32;
using Shared::Platform::float32;
using Shared::Util::Checksum;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
/**
* @brief Next power of 2
* @param x The number to be rounded
* @return the rounded number
*
* Rounds an unsigned integer up to the
* next power of 2; i.e. 2, 4, 8, 16, etc.
*/
static inline unsigned int next_power_of_2(unsigned int x)
{
x--;
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return ++x;
}
/**
* @brief Next power of 2
* @param x The number to be rounded
* @return the rounded number
*
* Rounds an unsigned integer up to the
* next power of 2; i.e. 2, 4, 8, 16, etc.
*/
static inline unsigned int next_power_of_2(unsigned int x) {
x--;
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return ++x;
}
/**
* @brief Count bits set
* @param w Number in which to count bits
* @return The number of bits set
*
* Counts the number of bits in an unsigned int
* that are set to 1. So, for example, in the
* number 5, hich is 101 in binary, there are
* two bits set to 1.
*/
static inline unsigned int count_bits_set(unsigned int w)
{
/*
* This is faster, and runs in parallel
*/
const int S[] = {1, 2, 4, 8, 16};
const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};
int c = w;
c = ((c >> S[0]) & B[0]) + (c & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) & B[2]) + (c & B[2]);
c = ((c >> S[3]) & B[3]) + (c & B[3]);
c = ((c >> S[4]) & B[4]) + (c & B[4]);
return c;
}
/**
* @brief Count bits set
* @param w Number in which to count bits
* @return The number of bits set
*
* Counts the number of bits in an unsigned int
* that are set to 1. So, for example, in the
* number 5, hich is 101 in binary, there are
* two bits set to 1.
*/
static inline unsigned int count_bits_set(unsigned int w) {
/*
* This is faster, and runs in parallel
*/
const int S[] = { 1, 2, 4, 8, 16 };
const int B[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF };
int c = w;
c = ((c >> S[0]) & B[0]) + (c & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) & B[2]) + (c & B[2]);
c = ((c >> S[3]) & B[3]) + (c & B[3]);
c = ((c >> S[4]) & B[4]) + (c & B[4]);
return c;
}
// =====================================================
// class PixmapIo
// =====================================================
// =====================================================
// class PixmapIo
// =====================================================
class PixmapIo {
protected:
int w;
int h;
int components;
class PixmapIo {
protected:
int w;
int h;
int components;
public:
virtual ~PixmapIo(){}
public:
virtual ~PixmapIo() {
}
int getW() const {return w;}
int getH() const {return h;}
int getComponents() const {return components;}
int getW() const {
return w;
}
int getH() const {
return h;
}
int getComponents() const {
return components;
}
virtual void openRead(const string &path)= 0;
virtual void read(uint8 *pixels)= 0;
virtual void read(uint8 *pixels, int components)= 0;
virtual void openRead(const string &path) = 0;
virtual void read(uint8 *pixels) = 0;
virtual void read(uint8 *pixels, int components) = 0;
virtual void openWrite(const string &path, int w, int h, int components)= 0;
virtual void write(uint8 *pixels)= 0;
};
virtual void openWrite(const string &path, int w, int h, int components) = 0;
virtual void write(uint8 *pixels) = 0;
};
// =====================================================
// class PixmapIoTga
// =====================================================
// =====================================================
// class PixmapIoTga
// =====================================================
class PixmapIoTga: public PixmapIo {
private:
FILE *file;
class PixmapIoTga : public PixmapIo {
private:
FILE *file;
public:
PixmapIoTga();
virtual ~PixmapIoTga();
public:
PixmapIoTga();
virtual ~PixmapIoTga();
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
// =====================================================
// class PixmapIoBmp
// =====================================================
// =====================================================
// class PixmapIoBmp
// =====================================================
class PixmapIoBmp: public PixmapIo {
private:
FILE *file;
class PixmapIoBmp : public PixmapIo {
private:
FILE *file;
public:
PixmapIoBmp();
virtual ~PixmapIoBmp();
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
public:
PixmapIoBmp();
virtual ~PixmapIoBmp();
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
// =====================================================
// class PixmapIoBmp
// =====================================================
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
class PixmapIoPng: public PixmapIo {
private:
FILE *file;
string path;
// =====================================================
// class PixmapIoBmp
// =====================================================
public:
PixmapIoPng();
virtual ~PixmapIoPng();
class PixmapIoPng : public PixmapIo {
private:
FILE *file;
string path;
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
public:
PixmapIoPng();
virtual ~PixmapIoPng();
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
class PixmapIoJpg: public PixmapIo {
private:
FILE *file;
string path;
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
public:
PixmapIoJpg();
virtual ~PixmapIoJpg();
class PixmapIoJpg : public PixmapIo {
private:
FILE *file;
string path;
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
public:
PixmapIoJpg();
virtual ~PixmapIoJpg();
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
virtual void openRead(const string &path);
virtual void read(uint8 *pixels);
virtual void read(uint8 *pixels, int components);
// =====================================================
// class Pixmap1D
// =====================================================
virtual void openWrite(const string &path, int w, int h, int components);
virtual void write(uint8 *pixels);
};
class Pixmap1D {
protected:
int w;
int components;
uint8 *pixels;
string path;
Checksum crc;
// =====================================================
// class Pixmap1D
// =====================================================
public:
//constructor & destructor
Pixmap1D();
Pixmap1D(int components);
Pixmap1D(int w, int components);
void init(int components);
void init(int w, int components);
~Pixmap1D();
//load & save
void load(const string &path);
void loadTga(const string &path);
void loadBmp(const string &path);
class Pixmap1D {
protected:
int w;
int components;
uint8 *pixels;
string path;
Checksum crc;
//get
int getW() const {return w;}
int getComponents() const {return components;}
uint8 *getPixels() const {return pixels;}
void deletePixels();
string getPath() const { return path;}
std::size_t getPixelByteCount() const;
public:
//constructor & destructor
Pixmap1D();
Pixmap1D(int components);
Pixmap1D(int w, int components);
void init(int components);
void init(int w, int components);
~Pixmap1D();
Checksum * getCRC() { return &crc; }
};
//load & save
void load(const string &path);
void loadTga(const string &path);
void loadBmp(const string &path);
// =====================================================
// class Pixmap2D
// =====================================================
//get
int getW() const {
return w;
}
int getComponents() const {
return components;
}
uint8 *getPixels() const {
return pixels;
}
void deletePixels();
string getPath() const {
return path;
}
std::size_t getPixelByteCount() const;
class Pixmap2D {
protected:
int h;
int w;
int components;
uint8 *pixels;
string path;
Checksum crc;
Checksum * getCRC() {
return &crc;
}
};
public:
//constructor & destructor
Pixmap2D();
Pixmap2D(int components);
Pixmap2D(int w, int h, int components);
void init(int components);
void init(int w, int h, int components);
~Pixmap2D();
void Scale(int format, int newW, int newH);
// =====================================================
// class Pixmap2D
// =====================================================
//load & save
static Pixmap2D* loadPath(const string& path);
void load(const string &path);
/*void loadTga(const string &path);
void loadBmp(const string &path);*/
void save(const string &path);
void saveBmp(const string &path);
void saveTga(const string &path);
void savePng(const string &path);
void saveJpg(const string &path);
class Pixmap2D {
protected:
int h;
int w;
int components;
uint8 *pixels;
string path;
Checksum crc;
//get
int getW() const {return w;}
int getH() const {return h;}
int getComponents() const {return components;}
uint8 *getPixels() const {return pixels;}
void deletePixels();
//get data
void getPixel(int x, int y, uint8 *value) const;
void getPixel(int x, int y, float32 *value) const;
void getComponent(int x, int y, int component, uint8 &value) const;
void getComponent(int x, int y, int component, float32 &value) const;
public:
//constructor & destructor
Pixmap2D();
Pixmap2D(int components);
Pixmap2D(int w, int h, int components);
void init(int components);
void init(int w, int h, int components);
~Pixmap2D();
//vector get
Vec4f getPixel4f(int x, int y) const;
Vec3f getPixel3f(int x, int y) const;
float getPixelf(int x, int y) const;
float getComponentf(int x, int y, int component) const;
void Scale(int format, int newW, int newH);
//set data
void setPixel(int x, int y, const uint8 *value, int arraySize);
void setPixel(int x, int y, const float32 *value, int arraySize);
void setComponent(int x, int y, int component, uint8 value);
void setComponent(int x, int y, int component, float32 value);
//load & save
static Pixmap2D* loadPath(const string& path);
void load(const string &path);
/*void loadTga(const string &path);
void loadBmp(const string &path);*/
void save(const string &path);
void saveBmp(const string &path);
void saveTga(const string &path);
void savePng(const string &path);
void saveJpg(const string &path);
//vector set
void setPixel(int x, int y, const Vec3f &p);
void setPixel(int x, int y, const Vec4f &p);
void setPixel(int x, int y, float p);
//mass set
void setPixels(const uint8 *value, int arraySize);
void setPixels(const float32 *value, int arraySize);
void setComponents(int component, uint8 value);
void setComponents(int component, float32 value);
//get
int getW() const {
return w;
}
int getH() const {
return h;
}
int getComponents() const {
return components;
}
uint8 *getPixels() const {
return pixels;
}
void deletePixels();
//operations
void splat(const Pixmap2D *leftUp, const Pixmap2D *rightUp, const Pixmap2D *leftDown, const Pixmap2D *rightDown);
void lerp(float t, const Pixmap2D *pixmap1, const Pixmap2D *pixmap2);
void copy(const Pixmap2D *sourcePixmap);
void subCopy(int x, int y, const Pixmap2D *sourcePixmap);
void copyImagePart(int x, int y, const Pixmap2D *sourcePixmap);
string getPath() const { return path;}
std::size_t getPixelByteCount() const;
//get data
void getPixel(int x, int y, uint8 *value) const;
void getPixel(int x, int y, float32 *value) const;
void getComponent(int x, int y, int component, uint8 &value) const;
void getComponent(int x, int y, int component, float32 &value) const;
Checksum * getCRC() { return &crc; }
//vector get
Vec4f getPixel4f(int x, int y) const;
Vec3f getPixel3f(int x, int y) const;
float getPixelf(int x, int y) const;
float getComponentf(int x, int y, int component) const;
private:
bool doDimensionsAgree(const Pixmap2D *pixmap);
};
//set data
void setPixel(int x, int y, const uint8 *value, int arraySize);
void setPixel(int x, int y, const float32 *value, int arraySize);
void setComponent(int x, int y, int component, uint8 value);
void setComponent(int x, int y, int component, float32 value);
// =====================================================
// class Pixmap3D
// =====================================================
//vector set
void setPixel(int x, int y, const Vec3f &p);
void setPixel(int x, int y, const Vec4f &p);
void setPixel(int x, int y, float p);
class Pixmap3D {
protected:
int h;
int w;
int d;
int components;
int slice;
uint8 *pixels;
string path;
Checksum crc;
//mass set
void setPixels(const uint8 *value, int arraySize);
void setPixels(const float32 *value, int arraySize);
void setComponents(int component, uint8 value);
void setComponents(int component, float32 value);
public:
//constructor & destructor
Pixmap3D();
Pixmap3D(int w, int h, int d, int components);
Pixmap3D(int d, int components);
void init(int w, int h, int d, int components);
void init(int d, int components);
void init(int components);
~Pixmap3D();
//load & save
void loadSlice(const string &path, int slice);
void loadSliceBmp(const string &path, int slice);
void loadSliceTga(const string &path, int slice);
void loadSlicePng(const string &path, int slice);
//get
int getSlice() const { return slice; }
int getW() const {return w;}
int getH() const {return h;}
int getD() const {return d;}
int getComponents() const {return components;}
uint8 *getPixels() const {return pixels;}
void deletePixels();
string getPath() const { return path;}
std::size_t getPixelByteCount() const;
//operations
void splat(const Pixmap2D *leftUp, const Pixmap2D *rightUp, const Pixmap2D *leftDown, const Pixmap2D *rightDown);
void lerp(float t, const Pixmap2D *pixmap1, const Pixmap2D *pixmap2);
void copy(const Pixmap2D *sourcePixmap);
void subCopy(int x, int y, const Pixmap2D *sourcePixmap);
void copyImagePart(int x, int y, const Pixmap2D *sourcePixmap);
string getPath() const {
return path;
}
std::size_t getPixelByteCount() const;
Checksum * getCRC() { return &crc; }
};
Checksum * getCRC() {
return &crc;
}
// =====================================================
// class PixmapCube
// =====================================================
private:
bool doDimensionsAgree(const Pixmap2D *pixmap);
};
class PixmapCube {
public:
enum Face{
fPositiveX,
fNegativeX,
fPositiveY,
fNegativeY,
fPositiveZ,
fNegativeZ
};
// =====================================================
// class Pixmap3D
// =====================================================
protected:
Pixmap2D faces[6];
string path[6];
Checksum crc;
class Pixmap3D {
protected:
int h;
int w;
int d;
int components;
int slice;
uint8 *pixels;
string path;
Checksum crc;
public:
PixmapCube();
~PixmapCube();
public:
//constructor & destructor
Pixmap3D();
Pixmap3D(int w, int h, int d, int components);
Pixmap3D(int d, int components);
void init(int w, int h, int d, int components);
void init(int d, int components);
void init(int components);
~Pixmap3D();
//init
void init(int w, int h, int components);
void init(int components);
//load & save
void loadSlice(const string &path, int slice);
void loadSliceBmp(const string &path, int slice);
void loadSliceTga(const string &path, int slice);
void loadSlicePng(const string &path, int slice);
//load & save
void loadFace(const string &path, int face);
/*void loadFaceBmp(const string &path, int face);
void loadFaceTga(const string &path, int face);*/
//get
Pixmap2D *getFace(int face) {return &faces[face];}
const Pixmap2D *getFace(int face) const {return &faces[face];}
void deletePixels();
string getPath(int face) const { return path[face];}
std::size_t getPixelByteCount() const;
//get
int getSlice() const {
return slice;
}
int getW() const {
return w;
}
int getH() const {
return h;
}
int getD() const {
return d;
}
int getComponents() const {
return components;
}
uint8 *getPixels() const {
return pixels;
}
void deletePixels();
string getPath() const {
return path;
}
std::size_t getPixelByteCount() const;
Checksum * getCRC() { return &crc; }
};
Checksum * getCRC() {
return &crc;
}
};
}}//end namespace
// =====================================================
// class PixmapCube
// =====================================================
class PixmapCube {
public:
enum Face {
fPositiveX,
fNegativeX,
fPositiveY,
fNegativeY,
fPositiveZ,
fNegativeZ
};
protected:
Pixmap2D faces[6];
string path[6];
Checksum crc;
public:
PixmapCube();
~PixmapCube();
//init
void init(int w, int h, int components);
void init(int components);
//load & save
void loadFace(const string &path, int face);
/*void loadFaceBmp(const string &path, int face);
void loadFaceTga(const string &path, int face);*/
//get
Pixmap2D *getFace(int face) {
return &faces[face];
}
const Pixmap2D *getFace(int face) const {
return &faces[face];
}
void deletePixels();
string getPath(int face) const {
return path[face];
}
std::size_t getPixelByteCount() const;
Checksum * getCRC() {
return &crc;
}
};
}
}//end namespace
#endif

View File

@@ -20,85 +20,87 @@
using namespace std;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class AxisAngle
// =====================================================
// =====================================================
// class AxisAngle
// =====================================================
class AxisAngle{
public:
Vec3f axis;
float angle;
class AxisAngle {
public:
Vec3f axis;
float angle;
AxisAngle() {
angle = 0.0f;
}
AxisAngle(const Vec3f &axis, float angle);
};
// =====================================================
// class EulerAngles
// =====================================================
class EulerAngles {
public:
float x, y, z;
EulerAngles() {
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
EulerAngles(float x, float y, float z);
};
// =====================================================
// class Quaternion
// =====================================================
class Quaternion {
private:
float w;
Vec3f v;
public:
Quaternion();
Quaternion(float w, const Vec3f &v);
Quaternion(const EulerAngles &eulerAngles);
//Quaternion(const AxisAngle &axisAngle);
//initializers
void setMultIdentity();
void setAddIdentity();
void setAxisAngle(const AxisAngle &axisAngle);
void setEuler(const EulerAngles &eulerAngles);
//unary operators
//float length();
Quaternion conjugate();
//void normalize();
//binary operators
Quaternion operator + (const Quaternion &q) const;
Quaternion operator * (const Quaternion &q) const;
void operator += (const Quaternion &q);
void operator *= (const Quaternion &q);
//ternary operators
Quaternion lerp(float t, const Quaternion &q) const;
//conversions
Matrix3f toMatrix3() const;
Matrix4f toMatrix4() const;
//AxisAngle toAxisAngle() const;
//local axis
Vec3f getLocalXAxis() const;
Vec3f getLocalYAxis() const;
Vec3f getLocalZAxis() const;
};
AxisAngle() {
angle = 0.0f;
}
AxisAngle(const Vec3f &axis, float angle);
};
// =====================================================
// class EulerAngles
// =====================================================
class EulerAngles{
public:
float x, y, z;
EulerAngles() {
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
EulerAngles(float x, float y, float z);
};
// =====================================================
// class Quaternion
// =====================================================
class Quaternion{
private:
float w;
Vec3f v;
public:
Quaternion();
Quaternion(float w, const Vec3f &v);
Quaternion(const EulerAngles &eulerAngles);
//Quaternion(const AxisAngle &axisAngle);
//initializers
void setMultIdentity();
void setAddIdentity();
void setAxisAngle(const AxisAngle &axisAngle);
void setEuler(const EulerAngles &eulerAngles);
//unary operators
//float length();
Quaternion conjugate();
//void normalize();
//binary operators
Quaternion operator + (const Quaternion &q) const;
Quaternion operator * (const Quaternion &q) const;
void operator += (const Quaternion &q);
void operator *= (const Quaternion &q);
//ternary operators
Quaternion lerp(float t, const Quaternion &q) const;
//conversions
Matrix3f toMatrix3() const;
Matrix4f toMatrix4() const;
//AxisAngle toAxisAngle() const;
//local axis
Vec3f getLocalXAxis() const;
Vec3f getLocalYAxis() const;
Vec3f getLocalZAxis() const;
};
}}//end namespace
}//end namespace
#endif

View File

@@ -17,71 +17,79 @@
#include "texture.h"
#include "leak_dumper.h"
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class ShaderProgram
// =====================================================
// =====================================================
// class ShaderProgram
// =====================================================
class VertexShader;
class FragmentShader;
class VertexShader;
class FragmentShader;
class ShaderProgram{
public:
virtual ~ShaderProgram(){}
virtual void init()= 0;
virtual void end()= 0;
class ShaderProgram {
public:
virtual ~ShaderProgram() {
}
virtual void init() = 0;
virtual void end() = 0;
virtual void attach(VertexShader *vs, FragmentShader *fs)= 0;
virtual bool link(string &messages)= 0;
virtual void activate()= 0;
virtual void deactivate()= 0;
virtual void attach(VertexShader *vs, FragmentShader *fs) = 0;
virtual bool link(string &messages) = 0;
virtual void activate() = 0;
virtual void deactivate() = 0;
virtual void setUniform(const string &name, int value)= 0;
virtual void setUniform(const string &name, float value)= 0;
virtual void setUniform(const string &name, const Vec2f &value)= 0;
virtual void setUniform(const string &name, const Vec3f &value)= 0;
virtual void setUniform(const string &name, const Vec4f &value)= 0;
virtual void setUniform(const string &name, const Matrix3f &value)= 0;
virtual void setUniform(const string &name, const Matrix4f &value)= 0;
};
virtual void setUniform(const string &name, int value) = 0;
virtual void setUniform(const string &name, float value) = 0;
virtual void setUniform(const string &name, const Vec2f &value) = 0;
virtual void setUniform(const string &name, const Vec3f &value) = 0;
virtual void setUniform(const string &name, const Vec4f &value) = 0;
virtual void setUniform(const string &name, const Matrix3f &value) = 0;
virtual void setUniform(const string &name, const Matrix4f &value) = 0;
};
// =====================================================
// class Shader
// =====================================================
// =====================================================
// class Shader
// =====================================================
class Shader{
public:
virtual ~Shader(){}
virtual void init()= 0;
virtual void end()= 0;
class Shader {
public:
virtual ~Shader() {
}
virtual void init() = 0;
virtual void end() = 0;
virtual void load(const string &path)= 0;
virtual bool compile(string &messages)= 0;
};
virtual void load(const string &path) = 0;
virtual bool compile(string &messages) = 0;
};
class VertexShader: virtual public Shader{
};
class VertexShader : virtual public Shader {
};
class FragmentShader: virtual public Shader{
};
class FragmentShader : virtual public Shader {
};
// =====================================================
// class ShaderSource
// =====================================================
// =====================================================
// class ShaderSource
// =====================================================
class ShaderSource{
private:
string pathInfo;
string code;
class ShaderSource {
private:
string pathInfo;
string code;
public:
const string &getPathInfo() const {return pathInfo;}
const string &getCode() const {return code;}
public:
const string &getPathInfo() const {
return pathInfo;
}
const string &getCode() const {
return code;
}
void load(const string &path);
};
void load(const string &path);
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -18,36 +18,40 @@
using namespace std;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class ShaderManager
// =====================================================
// =====================================================
// class ShaderManager
// =====================================================
class ShaderManager{
protected:
typedef vector<ShaderProgram*> ShaderProgramContainer;
typedef vector<Shader*> ShaderContainer;
class ShaderManager {
protected:
typedef vector<ShaderProgram*> ShaderProgramContainer;
typedef vector<Shader*> ShaderContainer;
protected:
ShaderProgramContainer shaderPrograms;
ShaderContainer shaders;
string logString;
protected:
ShaderProgramContainer shaderPrograms;
ShaderContainer shaders;
string logString;
public:
ShaderManager();
virtual ~ShaderManager();
public:
ShaderManager();
virtual ~ShaderManager();
ShaderProgram *newShaderProgram();
VertexShader *newVertexShader();
FragmentShader *newFragmentShader();
ShaderProgram *newShaderProgram();
VertexShader *newVertexShader();
FragmentShader *newFragmentShader();
void init();
void end();
void init();
void end();
const string &getLogString() const {return logString;}
};
const string &getLogString() const {
return logString;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -19,42 +19,47 @@
using std::string;
namespace Shared { namespace Graphics {
namespace Shared {
namespace Graphics {
// =====================================================
// class TextRenderer2D
// =====================================================
// =====================================================
// class TextRenderer2D
// =====================================================
class TextRenderer {
public:
virtual void render(const string &text, float x, float y, bool centered=false, Vec3f *color=NULL) = 0;
virtual void end()= 0;
class TextRenderer {
public:
virtual void render(const string &text, float x, float y, bool centered = false, Vec3f *color = NULL) = 0;
virtual void end() = 0;
virtual ~TextRenderer() {}
};
virtual ~TextRenderer() {
}
};
class TextRenderer2D : public TextRenderer {
public:
virtual ~TextRenderer2D(){};
class TextRenderer2D : public TextRenderer {
public:
virtual ~TextRenderer2D() {
};
virtual void begin(Font2D *font)= 0;
//virtual void render(const string &text, int x, int y, bool centered= false,Vec3f *color=NULL)= 0;
//virtual void end()= 0;
};
virtual void begin(Font2D *font) = 0;
//virtual void render(const string &text, int x, int y, bool centered= false,Vec3f *color=NULL)= 0;
//virtual void end()= 0;
};
// =====================================================
// class TextRenderer3D
// =====================================================
// =====================================================
// class TextRenderer3D
// =====================================================
class TextRenderer3D : public TextRenderer {
public:
virtual ~TextRenderer3D(){};
class TextRenderer3D : public TextRenderer {
public:
virtual ~TextRenderer3D() {
};
virtual void begin(Font3D *font)= 0;
//virtual void render(const string &text, float x, float y, bool centered= false,Vec3f *color=NULL)= 0;
//virtual void end()= 0;
};
virtual void begin(Font3D *font) = 0;
//virtual void render(const string &text, float x, float y, bool centered= false,Vec3f *color=NULL)= 0;
//virtual void end()= 0;
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -22,178 +22,257 @@ using Shared::Platform::uint8;
struct SDL_Surface;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class TextureParams;
class TextureParams;
// =====================================================
// class Texture
// =====================================================
// =====================================================
// class Texture
// =====================================================
class Texture {
public:
static const int defaultSize;
static const int defaultComponents;
static bool useTextureCompression;
class Texture {
public:
static const int defaultSize;
static const int defaultComponents;
static bool useTextureCompression;
enum WrapMode{
wmRepeat,
wmClamp,
wmClampToEdge
};
enum WrapMode {
wmRepeat,
wmClamp,
wmClampToEdge
};
enum Filter{
fBilinear,
fTrilinear
};
enum Filter {
fBilinear,
fTrilinear
};
enum Format{
fAuto,
fAlpha,
fLuminance,
fRgb,
fRgba
};
enum Format {
fAuto,
fAlpha,
fLuminance,
fRgb,
fRgba
};
protected:
string path;
bool mipmap;
WrapMode wrapMode;
bool pixmapInit;
Format format;
protected:
string path;
bool mipmap;
WrapMode wrapMode;
bool pixmapInit;
Format format;
bool inited;
bool forceCompressionDisabled;
int textureSystemId;
bool inited;
bool forceCompressionDisabled;
int textureSystemId;
public:
Texture();
virtual ~Texture(){};
bool getMipmap() const {return mipmap;}
WrapMode getWrapMode() const {return wrapMode;}
bool getPixmapInit() const {return pixmapInit;}
Format getFormat() const {return format;}
bool getInited() const {return inited;}
public:
Texture();
virtual ~Texture() {
};
int getTextureSystemId() const { return textureSystemId; }
void setTextureSystemId(int id) { textureSystemId = id; }
bool getMipmap() const {
return mipmap;
}
WrapMode getWrapMode() const {
return wrapMode;
}
bool getPixmapInit() const {
return pixmapInit;
}
Format getFormat() const {
return format;
}
bool getInited() const {
return inited;
}
void setMipmap(bool mipmap) {this->mipmap= mipmap;}
void setWrapMode(WrapMode wrapMode) {this->wrapMode= wrapMode;}
void setPixmapInit(bool pixmapInit) {this->pixmapInit= pixmapInit;}
void setFormat(Format format) {this->format= format;}
int getTextureSystemId() const {
return textureSystemId;
}
void setTextureSystemId(int id) {
textureSystemId = id;
}
virtual void init(Filter filter= fBilinear, int maxAnisotropy= 1)=0;
virtual void end(bool deletePixelBuffer=true)=0;
virtual string getPath() const = 0;
virtual void deletePixels() = 0;
virtual std::size_t getPixelByteCount() const = 0;
void setMipmap(bool mipmap) {
this->mipmap = mipmap;
}
void setWrapMode(WrapMode wrapMode) {
this->wrapMode = wrapMode;
}
void setPixmapInit(bool pixmapInit) {
this->pixmapInit = pixmapInit;
}
void setFormat(Format format) {
this->format = format;
}
virtual void reseInitState() { inited = false; }
virtual void init(Filter filter = fBilinear, int maxAnisotropy = 1) = 0;
virtual void end(bool deletePixelBuffer = true) = 0;
virtual string getPath() const = 0;
virtual void deletePixels() = 0;
virtual std::size_t getPixelByteCount() const = 0;
virtual void setForceCompressionDisabled(bool value) { forceCompressionDisabled = value;}
virtual bool getForceCompressionDisabled() const {return forceCompressionDisabled;}
virtual void reseInitState() {
inited = false;
}
virtual uint32 getCRC() = 0;
virtual void setForceCompressionDisabled(bool value) {
forceCompressionDisabled = value;
}
virtual bool getForceCompressionDisabled() const {
return forceCompressionDisabled;
}
};
virtual uint32 getCRC() = 0;
// =====================================================
// class Texture1D
// =====================================================
};
class Texture1D: public Texture {
protected:
Pixmap1D pixmap;
// =====================================================
// class Texture1D
// =====================================================
public:
void load(const string &path);
class Texture1D : public Texture {
protected:
Pixmap1D pixmap;
Pixmap1D *getPixmap() {return &pixmap;}
const Pixmap1D *getPixmap() const {return &pixmap;}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {return pixmap.getPixelByteCount();}
public:
void load(const string &path);
virtual int getTextureWidth() const {return pixmap.getW();}
virtual int getTextureHeight() const {return -1;}
Pixmap1D *getPixmap() {
return &pixmap;
}
const Pixmap1D *getPixmap() const {
return &pixmap;
}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {
return pixmap.getPixelByteCount();
}
virtual uint32 getCRC() { return pixmap.getCRC()->getSum(); }
};
virtual int getTextureWidth() const {
return pixmap.getW();
}
virtual int getTextureHeight() const {
return -1;
}
// =====================================================
// class Texture2D
// =====================================================
virtual uint32 getCRC() {
return pixmap.getCRC()->getSum();
}
};
class Texture2D: public Texture {
protected:
Pixmap2D pixmap;
// =====================================================
// class Texture2D
// =====================================================
public:
void load(const string &path);
class Texture2D : public Texture {
protected:
Pixmap2D pixmap;
Pixmap2D *getPixmap() {return &pixmap;}
const Pixmap2D *getPixmapConst() const {return &pixmap;}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {return pixmap.getPixelByteCount();}
public:
void load(const string &path);
virtual int getTextureWidth() const {return pixmap.getW();}
virtual int getTextureHeight() const {return pixmap.getH();}
Pixmap2D *getPixmap() {
return &pixmap;
}
const Pixmap2D *getPixmapConst() const {
return &pixmap;
}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {
return pixmap.getPixelByteCount();
}
virtual uint32 getCRC() { return pixmap.getCRC()->getSum(); }
virtual int getTextureWidth() const {
return pixmap.getW();
}
virtual int getTextureHeight() const {
return pixmap.getH();
}
std::pair<SDL_Surface*,unsigned char*> CreateSDLSurface(bool newPixelData) const;
};
virtual uint32 getCRC() {
return pixmap.getCRC()->getSum();
}
// =====================================================
// class Texture3D
// =====================================================
std::pair<SDL_Surface*, unsigned char*> CreateSDLSurface(bool newPixelData) const;
};
class Texture3D: public Texture {
protected:
Pixmap3D pixmap;
// =====================================================
// class Texture3D
// =====================================================
public:
void loadSlice(const string &path, int slice);
class Texture3D : public Texture {
protected:
Pixmap3D pixmap;
Pixmap3D *getPixmap() {return &pixmap;}
const Pixmap3D *getPixmap() const {return &pixmap;}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {return pixmap.getPixelByteCount();}
public:
void loadSlice(const string &path, int slice);
virtual int getTextureWidth() const {return pixmap.getW();}
virtual int getTextureHeight() const {return pixmap.getH();}
Pixmap3D *getPixmap() {
return &pixmap;
}
const Pixmap3D *getPixmap() const {
return &pixmap;
}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {
return pixmap.getPixelByteCount();
}
virtual uint32 getCRC() { return pixmap.getCRC()->getSum(); }
};
virtual int getTextureWidth() const {
return pixmap.getW();
}
virtual int getTextureHeight() const {
return pixmap.getH();
}
// =====================================================
// class TextureCube
// =====================================================
virtual uint32 getCRC() {
return pixmap.getCRC()->getSum();
}
};
class TextureCube: public Texture{
protected:
PixmapCube pixmap;
// =====================================================
// class TextureCube
// =====================================================
public:
void loadFace(const string &path, int face);
class TextureCube : public Texture {
protected:
PixmapCube pixmap;
PixmapCube *getPixmap() {return &pixmap;}
const PixmapCube *getPixmap() const {return &pixmap;}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {return pixmap.getPixelByteCount();}
public:
void loadFace(const string &path, int face);
virtual int getTextureWidth() const {return -1;}
virtual int getTextureHeight() const {return -1;}
PixmapCube *getPixmap() {
return &pixmap;
}
const PixmapCube *getPixmap() const {
return &pixmap;
}
virtual string getPath() const;
virtual void deletePixels();
virtual std::size_t getPixelByteCount() const {
return pixmap.getPixelByteCount();
}
virtual uint32 getCRC() { return pixmap.getCRC()->getSum(); }
};
virtual int getTextureWidth() const {
return -1;
}
virtual int getTextureHeight() const {
return -1;
}
}}//end namespace
virtual uint32 getCRC() {
return pixmap.getCRC()->getSum();
}
};
}
}//end namespace
#endif

View File

@@ -18,48 +18,56 @@
using std::vector;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
// =====================================================
// class TextureManager
// =====================================================
typedef vector<Texture*> TextureContainer;
// =====================================================
// class TextureManager
// =====================================================
typedef vector<Texture*> TextureContainer;
//manages textures, creation on request and deletion on destruction
class TextureManager{
protected:
TextureContainer textures;
Texture::Filter textureFilter;
int maxAnisotropy;
//manages textures, creation on request and deletion on destruction
class TextureManager {
public:
TextureManager();
~TextureManager();
void init(bool forceInit=false);
void end();
protected:
TextureContainer textures;
void setFilter(Texture::Filter textureFilter);
void setMaxAnisotropy(int maxAnisotropy);
void initTexture(Texture *texture);
void endTexture(Texture *texture,bool mustExistInList=false);
void endLastTexture(bool mustExistInList=false);
void reinitTextures();
Texture::Filter textureFilter;
int maxAnisotropy;
Texture::Filter getTextureFilter() const {return textureFilter;}
int getMaxAnisotropy() const {return maxAnisotropy;}
public:
TextureManager();
~TextureManager();
void init(bool forceInit = false);
void end();
Texture *getTexture(const string &path);
Texture1D *newTexture1D();
Texture2D *newTexture2D();
Texture3D *newTexture3D();
TextureCube *newTextureCube();
void setFilter(Texture::Filter textureFilter);
void setMaxAnisotropy(int maxAnisotropy);
void initTexture(Texture *texture);
void endTexture(Texture *texture, bool mustExistInList = false);
void endLastTexture(bool mustExistInList = false);
void reinitTextures();
const TextureContainer &getTextures() const {return textures;}
};
Texture::Filter getTextureFilter() const {
return textureFilter;
}
int getMaxAnisotropy() const {
return maxAnisotropy;
}
Texture *getTexture(const string &path);
Texture1D *newTexture1D();
Texture2D *newTexture2D();
Texture3D *newTexture3D();
TextureCube *newTextureCube();
const TextureContainer &getTextures() const {
return textures;
}
};
}}//end namespace
}
}//end namespace
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -18,70 +18,79 @@ class ctx;
using namespace std;
namespace Shared{ namespace Graphics{
namespace Shared {
namespace Graphics {
class VideoLoadingCallbackInterface {
public:
virtual ~VideoLoadingCallbackInterface() {}
/** a value from 1 to 100 representing % done */
virtual void renderVideoLoading(int progressPercent) = 0;
};
class VideoLoadingCallbackInterface {
public:
virtual ~VideoLoadingCallbackInterface() {
}
/** a value from 1 to 100 representing % done */
virtual void renderVideoLoading(int progressPercent) = 0;
};
class VideoPlayer {
protected:
class VideoPlayer {
protected:
string filename;
string filenameFallback;
SDL_Window *window;
int x;
int y;
int width;
int height;
int colorBits;
string filename;
string filenameFallback;
SDL_Window *window;
int x;
int y;
int width;
int height;
int colorBits;
bool successLoadingLib;
string pluginsPath;
bool verboseEnabled;
bool successLoadingLib;
string pluginsPath;
bool verboseEnabled;
bool stop;
bool finished;
bool loop;
bool stop;
bool finished;
bool loop;
VideoLoadingCallbackInterface *loadingCB;
ctx *ctxPtr;
VideoLoadingCallbackInterface *loadingCB;
ctx *ctxPtr;
static bool disabled;
void init();
static bool disabled;
void init();
void cleanupPlayer();
bool initPlayer(string mediaURL);
void cleanupPlayer();
bool initPlayer(string mediaURL);
public:
VideoPlayer(VideoLoadingCallbackInterface *loadingCB,
string filename,
string filenameFallback,
SDL_Window *window, int x, int y,
int width, int height, int colorBits,
bool loop, string pluginsPath,bool verboseEnabled=false);
virtual ~VideoPlayer();
public:
VideoPlayer(VideoLoadingCallbackInterface *loadingCB,
string filename,
string filenameFallback,
SDL_Window *window, int x, int y,
int width, int height, int colorBits,
bool loop, string pluginsPath, bool verboseEnabled = false);
virtual ~VideoPlayer();
static void setDisabled(bool value) { disabled = value; }
static bool getDisabled() { return disabled; }
static void setDisabled(bool value) {
disabled = value;
}
static bool getDisabled() {
return disabled;
}
void PlayVideo();
void StopVideo() { stop = true; }
void PlayVideo();
void StopVideo() {
stop = true;
}
bool initPlayer();
void closePlayer();
bool initPlayer();
void closePlayer();
bool playFrame(bool swapBuffers = true);
bool isPlaying() const;
bool playFrame(bool swapBuffers = true);
bool isPlaying() const;
static bool hasBackEndVideoPlayer();
static bool hasBackEndVideoPlayer();
void RestartVideo();
};
void RestartVideo();
};
}}
}
}
#endif /* VIDEO_PLAYER_H_ */

View File

@@ -28,94 +28,104 @@ using Shared::Graphics::Vec4f;
using Shared::Xml::XmlNode;
namespace Shared { namespace Lua {
namespace Shared {
namespace Lua {
typedef lua_State LuaHandle;
typedef int(*LuaFunction)(LuaHandle*);
typedef lua_State LuaHandle;
typedef int(*LuaFunction)(LuaHandle*);
// =====================================================
// class LuaScript
// =====================================================
// =====================================================
// class LuaScript
// =====================================================
class LuaScript {
private:
LuaHandle *luaState;
int argumentCount;
string currentLuaFunction;
bool currentLuaFunctionIsValid;
string sandboxWrapperFunctionName;
string sandboxCode;
class LuaScript {
private:
LuaHandle *luaState;
int argumentCount;
string currentLuaFunction;
bool currentLuaFunctionIsValid;
string sandboxWrapperFunctionName;
string sandboxCode;
static bool disableSandbox;
static bool debugModeEnabled;
static bool disableSandbox;
static bool debugModeEnabled;
void DumpGlobals();
void DumpGlobals();
public:
LuaScript();
~LuaScript();
public:
LuaScript();
~LuaScript();
static void setDebugModeEnabled(bool value) { debugModeEnabled = value; }
static bool getDebugModeEnabled() { return debugModeEnabled; }
static void setDebugModeEnabled(bool value) {
debugModeEnabled = value;
}
static bool getDebugModeEnabled() {
return debugModeEnabled;
}
static void setDisableSandbox(bool value) { disableSandbox = value; }
static void setDisableSandbox(bool value) {
disableSandbox = value;
}
void loadCode(string code, string name);
void loadCode(string code, string name);
void beginCall(string functionName);
void endCall();
void beginCall(string functionName);
void endCall();
int runCode(const string code);
void setSandboxWrapperFunctionName(string name);
void setSandboxCode(string code);
int runCode(const string code);
void setSandboxWrapperFunctionName(string name);
void setSandboxCode(string code);
void registerFunction(LuaFunction luaFunction, string functionName);
void registerFunction(LuaFunction luaFunction, string functionName);
void saveGame(XmlNode *rootNode);
void loadGame(const XmlNode *rootNode);
void saveGame(XmlNode *rootNode);
void loadGame(const XmlNode *rootNode);
private:
string errorToString(int errorCode);
};
private:
string errorToString(int errorCode);
};
// =====================================================
// class LuaArguments
// =====================================================
// =====================================================
// class LuaArguments
// =====================================================
class LuaArguments {
private:
lua_State *luaState;
int returnCount;
class LuaArguments {
private:
lua_State *luaState;
int returnCount;
public:
LuaArguments(lua_State *luaState);
public:
LuaArguments(lua_State *luaState);
int getInt(int argumentIndex) const;
string getString(int argumentIndex) const;
void * getGenericData(int argumentIndex) const;
Vec2i getVec2i(int argumentIndex) const;
Vec4i getVec4i(int argumentIndex) const;
int getInt(int argumentIndex) const;
string getString(int argumentIndex) const;
void * getGenericData(int argumentIndex) const;
Vec2i getVec2i(int argumentIndex) const;
Vec4i getVec4i(int argumentIndex) const;
float getFloat(int argumentIndex) const;
Vec2f getVec2f(int argumentIndex) const;
Vec3f getVec3f(int argumentIndex) const;
Vec4f getVec4f(int argumentIndex) const;
float getFloat(int argumentIndex) const;
Vec2f getVec2f(int argumentIndex) const;
Vec3f getVec3f(int argumentIndex) const;
Vec4f getVec4f(int argumentIndex) const;
int getReturnCount() const {return returnCount;}
int getReturnCount() const {
return returnCount;
}
void returnInt(int value);
void returnFloat(float value);
void returnString(const string &value);
void returnVec2i(const Vec2i &value);
void returnVec4i(const Vec4i &value);
void returnVectorInt(const vector<int> &value);
void returnInt(int value);
void returnFloat(float value);
void returnString(const string &value);
void returnVec2i(const Vec2i &value);
void returnVec4i(const Vec4i &value);
void returnVectorInt(const vector<int> &value);
private:
private:
void throwLuaError(const string &message) const;
string getStackText() const;
};
void throwLuaError(const string &message) const;
string getStackText() const;
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -25,212 +25,242 @@ using Shared::Platform::float32;
using Shared::Util::RandomGen;
using Shared::Graphics::Vec2i;
namespace Shared { namespace Map {
namespace Shared {
namespace Map {
enum MapSurfaceType {
st_Grass = 1,
st_Secondary_Grass,
st_Road,
st_Stone,
st_Ground
enum MapSurfaceType {
st_Grass = 1,
st_Secondary_Grass,
st_Road,
st_Stone,
st_Ground
};
};
static const int MAX_TITLE_LENGTH = 128;
static const int MAX_AUTHOR_LENGTH = 128;
static const int MAX_DESCRIPTION_LENGTH = 256;
static const int MAX_DESCRIPTION_LENGTH_VERSION2 = 128;
static const int MAX_TITLE_LENGTH = 128;
static const int MAX_AUTHOR_LENGTH = 128;
static const int MAX_DESCRIPTION_LENGTH = 256;
static const int MAX_DESCRIPTION_LENGTH_VERSION2 = 128;
static const int MIN_MAP_CELL_DIMENSION = 16;
static const int MAX_MAP_CELL_DIMENSION = 1024;
static const int MIN_MAP_CELL_DIMENSION = 16;
static const int MAX_MAP_CELL_DIMENSION = 1024;
static const int MIN_MAP_CELL_HEIGHT = 0;
static const int MAX_MAP_CELL_HEIGHT = 20;
static const int DEFAULT_MAP_CELL_HEIGHT = 10;
static const int MIN_MAP_CELL_HEIGHT = 0;
static const int MAX_MAP_CELL_HEIGHT = 20;
static const int DEFAULT_MAP_CELL_HEIGHT = 10;
static const int MIN_MAP_FACTIONCOUNT = 1;
static const int MAX_MAP_FACTIONCOUNT = 8;
static const int DEFAULT_MAP_FACTIONCOUNT = 8;
static const int MIN_MAP_FACTIONCOUNT = 1;
static const int MAX_MAP_FACTIONCOUNT = 8;
static const int DEFAULT_MAP_FACTIONCOUNT = 8;
static const int DEFAULT_MAP_CELL_WIDTH = 128;
static const int DEFAULT_MAP_CELL_LENGTH = 128;
static const int DEFAULT_MAP_CELL_WIDTH = 128;
static const int DEFAULT_MAP_CELL_LENGTH = 128;
static const MapSurfaceType DEFAULT_MAP_CELL_SURFACE_TYPE = st_Grass;
static const MapSurfaceType DEFAULT_MAP_CELL_SURFACE_TYPE = st_Grass;
static const int DEFAULT_MAP_CELL_HEIGHT_FACTOR = 3;
static const int DEFAULT_MAP_WATER_DEPTH = 4;
static const int DEFAULT_CLIFF_HEIGHT = 0;
static const int DEFAULT_MAP_CELL_HEIGHT_FACTOR = 3;
static const int DEFAULT_MAP_WATER_DEPTH = 4;
static const int DEFAULT_CLIFF_HEIGHT = 0;
enum MapVersionType {
mapver_1 = 1,
mapver_2,
enum MapVersionType {
mapver_1 = 1,
mapver_2,
mapver_MAX
};
mapver_MAX
};
static const int MAP_FORMAT_VERSION = mapver_MAX - 1;
static const int MAP_FORMAT_VERSION = mapver_MAX - 1;
struct MapFileHeader {
int32 version;
int32 maxFactions;
int32 width;
int32 height;
int32 heightFactor;
int32 waterLevel;
int8 title[MAX_TITLE_LENGTH];
int8 author[MAX_AUTHOR_LENGTH];
union {
int8 description[MAX_DESCRIPTION_LENGTH];
struct {
int8 short_desc[MAX_DESCRIPTION_LENGTH_VERSION2];
int32 magic; // 0x01020304 for meta
int32 cliffLevel;
int32 cameraHeight;
int8 meta[116];
} version2;
};
};
struct MapFileHeader {
int32 version;
int32 maxFactions;
int32 width;
int32 height;
int32 heightFactor;
int32 waterLevel;
int8 title[MAX_TITLE_LENGTH];
int8 author[MAX_AUTHOR_LENGTH];
union {
int8 description[MAX_DESCRIPTION_LENGTH];
struct {
int8 short_desc[MAX_DESCRIPTION_LENGTH_VERSION2];
int32 magic; // 0x01020304 for meta
int32 cliffLevel;
int32 cameraHeight;
int8 meta[116];
} version2;
};
};
void toEndianMapFileHeader(MapFileHeader &header);
void fromEndianMapFileHeader(MapFileHeader &header);
void toEndianMapFileHeader(MapFileHeader &header);
void fromEndianMapFileHeader(MapFileHeader &header);
class MapInfo {
public:
class MapInfo {
public:
Vec2i size;
int players;
int hardMaxPlayers;
string desc;
Vec2i size;
int players;
int hardMaxPlayers;
string desc;
MapInfo() {
size = Vec2i(0, 0);
players = 0;
hardMaxPlayers = 0;
desc = "";
}
};
// ===============================================
// class Map
// ===============================================
class MapPreview {
public:
static const int maxHeight = 20;
static const int minHeight = 0;
private:
struct Cell {
int surface;
int object;
int resource;
float height;
};
struct StartLocation {
int x;
int y;
};
RandomGen random;
string title;
string author;
string desc;
string recScn;
int type;
int h;
int w;
int heightFactor;
int waterLevel;
int cliffLevel;
int cameraHeight;
//Cell **cells;
std::vector<std::vector<Cell> > cells;
int maxFactions;
//StartLocation *startLocations;
std::vector<StartLocation> startLocations;
int refAlt;
bool fileLoaded;
string mapFileLoaded;
bool hasChanged;
public:
MapPreview();
~MapPreview();
bool getHasChanged() const {
return hasChanged;
}
void setHasChanged(bool value) {
hasChanged = value;
}
float getHeight(int x, int y) const;
bool isCliff(int x, int y);
MapSurfaceType getSurface(int x, int y) const;
int getObject(int x, int y) const;
int getResource(int x, int y) const;
int getStartLocationX(int index) const;
int getStartLocationY(int index) const;
int getHeightFactor() const {
return heightFactor;
}
int getWaterLevel() const {
return waterLevel;
}
int getCliffLevel() const {
return cliffLevel;
}
int getCameraHeight() const {
return cameraHeight;
}
bool inside(int x, int y);
void setRefAlt(int x, int y);
void setAdvanced(int heightFactor, int waterLevel, int cliffLevel, int cameraHeight);
void setTitle(const string &title);
void setDesc(const string &desc);
void setAuthor(const string &author);
int getH() const {
return h;
}
int getW() const {
return w;
}
int getMaxFactions() const {
return maxFactions;
}
string getTitle() const {
return title;
}
string getDesc() const {
return desc;
}
string getAuthor() const {
return author;
}
void glestChangeHeight(int x, int y, int height, int radius);
void pirateChangeHeight(int x, int y, int height, int radius);
void changeSurface(int x, int y, MapSurfaceType surface, int radius);
void changeObject(int x, int y, int object, int radius);
void changeResource(int x, int y, int resource, int radius);
void changeStartLocation(int x, int y, int player);
void setHeight(int x, int y, float height);
void setSurface(int x, int y, MapSurfaceType surface);
void setObject(int x, int y, int object);
void setResource(int x, int y, int resource);
void flipX();
void flipY();
void copyXY(int x, int y, int sx, int sy); // destination x,y = source sx,sy
void swapXY(int x, int y, int sx, int sy);
void reset(int w, int h, float alt, MapSurfaceType surf);
void resize(int w, int h, float alt, MapSurfaceType surf);
void resetFactions(int maxFactions);
void randomizeHeights(bool withReset, int minimumHeight, int maximumHeight, int chanceDevider, int smoothRecursions);
void randomizeFactions();
void smoothSurface(bool limitHeights);
void switchSurfaces(MapSurfaceType surf1, MapSurfaceType surf2);
void loadFromFile(const string &path);
void saveToFile(const string &path);
void resetHeights(int height);
void realRandomize(int minimumHeight, int maximumHeight, int chanceDivider, int smoothRecursions);
void applyNewHeight(float newHeight, int x, int y, int strenght);
bool hasFileLoaded() const {
return fileLoaded;
}
string getMapFileLoaded() const {
return mapFileLoaded;
}
static bool loadMapInfo(string file, MapInfo *mapInfo, string i18nMaxMapPlayersTitle, string i18nMapSizeTitle, bool errorOnInvalidMap = true);
static string getMapPath(const vector<string> &pathList, const string &mapName, string scenarioDir = "", bool errorOnNotFound = true);
static vector<string> findAllValidMaps(const vector<string> &pathList,
string scenarioDir, bool getUserDataOnly = false, bool cutExtension = true,
vector<string> *invalidMapList = NULL);
};
MapInfo() {
size = Vec2i(0,0);
players = 0;
hardMaxPlayers = 0;
desc = "";
}
};
// ===============================================
// class Map
// ===============================================
class MapPreview {
public:
static const int maxHeight = 20;
static const int minHeight = 0;
private:
struct Cell {
int surface;
int object;
int resource;
float height;
};
struct StartLocation {
int x;
int y;
};
RandomGen random;
string title;
string author;
string desc;
string recScn;
int type;
int h;
int w;
int heightFactor;
int waterLevel;
int cliffLevel;
int cameraHeight;
//Cell **cells;
std::vector<std::vector<Cell> > cells;
int maxFactions;
//StartLocation *startLocations;
std::vector<StartLocation> startLocations;
int refAlt;
bool fileLoaded;
string mapFileLoaded;
bool hasChanged;
public:
MapPreview();
~MapPreview();
bool getHasChanged() const { return hasChanged; }
void setHasChanged(bool value) { hasChanged = value; }
float getHeight(int x, int y) const;
bool isCliff(int x,int y);
MapSurfaceType getSurface(int x, int y) const;
int getObject(int x, int y) const;
int getResource(int x, int y) const;
int getStartLocationX(int index) const;
int getStartLocationY(int index) const;
int getHeightFactor() const{return heightFactor;}
int getWaterLevel() const{return waterLevel;}
int getCliffLevel() const{return cliffLevel;}
int getCameraHeight() const{return cameraHeight;}
bool inside(int x, int y);
void setRefAlt(int x, int y);
void setAdvanced(int heightFactor, int waterLevel, int cliffLevel, int cameraHeight);
void setTitle(const string &title);
void setDesc(const string &desc);
void setAuthor(const string &author);
int getH() const {return h;}
int getW() const {return w;}
int getMaxFactions() const {return maxFactions;}
string getTitle() const {return title;}
string getDesc() const {return desc;}
string getAuthor() const {return author;}
void glestChangeHeight(int x, int y, int height, int radius);
void pirateChangeHeight(int x, int y, int height, int radius);
void changeSurface(int x, int y, MapSurfaceType surface, int radius);
void changeObject(int x, int y, int object, int radius);
void changeResource(int x, int y, int resource, int radius);
void changeStartLocation(int x, int y, int player);
void setHeight(int x, int y, float height);
void setSurface(int x, int y, MapSurfaceType surface);
void setObject(int x, int y, int object);
void setResource(int x, int y, int resource);
void flipX();
void flipY();
void copyXY(int x, int y, int sx, int sy); // destination x,y = source sx,sy
void swapXY(int x, int y, int sx, int sy);
void reset(int w, int h, float alt, MapSurfaceType surf);
void resize(int w, int h, float alt, MapSurfaceType surf);
void resetFactions(int maxFactions);
void randomizeHeights(bool withReset,int minimumHeight, int maximumHeight, int chanceDevider, int smoothRecursions);
void randomizeFactions();
void smoothSurface(bool limitHeights);
void switchSurfaces(MapSurfaceType surf1, MapSurfaceType surf2);
void loadFromFile(const string &path);
void saveToFile(const string &path);
void resetHeights(int height);
void realRandomize(int minimumHeight, int maximumHeight, int chanceDivider, int smoothRecursions);
void applyNewHeight(float newHeight, int x, int y, int strenght);
bool hasFileLoaded() const {return fileLoaded;}
string getMapFileLoaded() const { return mapFileLoaded; }
static bool loadMapInfo(string file, MapInfo *mapInfo, string i18nMaxMapPlayersTitle,string i18nMapSizeTitle,bool errorOnInvalidMap=true);
static string getMapPath(const vector<string> &pathList, const string &mapName, string scenarioDir="", bool errorOnNotFound=true);
static vector<string> findAllValidMaps(const vector<string> &pathList,
string scenarioDir, bool getUserDataOnly=false, bool cutExtension=true,
vector<string> *invalidMapList=NULL);
};
}}// end namespace
}// end namespace
#endif

View File

@@ -20,147 +20,152 @@
using namespace Shared::Platform;
using namespace std;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
// =====================================================
// class BaseThread
// =====================================================
// =====================================================
// class BaseThread
// =====================================================
class BaseThread : public Thread
{
protected:
Mutex *mutexRunning;
Mutex *mutexQuit;
Mutex *mutexBeginExecution;
Mutex *mutexDeleteSelfOnExecutionDone;
class BaseThread : public Thread {
protected:
Mutex *mutexRunning;
Mutex *mutexQuit;
Mutex *mutexBeginExecution;
Mutex *mutexDeleteSelfOnExecutionDone;
Mutex *mutexThreadObjectAccessor;
Mutex *mutexThreadObjectAccessor;
bool threadOwnerValid;
Mutex *mutexThreadOwnerValid;
bool threadOwnerValid;
Mutex *mutexThreadOwnerValid;
Mutex *mutexExecutingTask;
bool executingTask;
Mutex *mutexExecutingTask;
bool executingTask;
void *ptr;
static Mutex mutexMasterThreadList;
static std::map<void *,int> masterThreadList;
void *ptr;
static Mutex mutexMasterThreadList;
static std::map<void *, int> masterThreadList;
bool quit;
bool running;
string uniqueID;
bool hasBeginExecution;
bool deleteSelfOnExecutionDone;
bool quit;
bool running;
string uniqueID;
bool hasBeginExecution;
bool deleteSelfOnExecutionDone;
Mutex *mutexStarted;
bool started;
Mutex *mutexStarted;
bool started;
virtual void setQuitStatus(bool value);
void deleteSelfIfRequired();
virtual void setQuitStatus(bool value);
void deleteSelfIfRequired();
void *genericData;
void *genericData;
public:
BaseThread();
virtual ~BaseThread();
virtual void execute()=0;
public:
BaseThread();
virtual ~BaseThread();
virtual void execute() = 0;
virtual void signalQuit();
virtual bool getQuitStatus();
virtual bool getRunningStatus();
virtual void signalQuit();
virtual bool getQuitStatus();
virtual bool getRunningStatus();
virtual bool getStarted();
virtual void setStarted(bool value);
virtual bool getStarted();
virtual void setStarted(bool value);
virtual bool getHasBeginExecution();
virtual void setHasBeginExecution(bool value);
virtual bool getHasBeginExecution();
virtual void setHasBeginExecution(bool value);
static bool shutdownAndWait(BaseThread *ppThread);
virtual bool shutdownAndWait();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false);
static bool shutdownAndWait(BaseThread *ppThread);
virtual bool shutdownAndWait();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false);
virtual bool getDeleteSelfOnExecutionDone();
virtual void setDeleteSelfOnExecutionDone(bool value);
virtual bool getDeleteSelfOnExecutionDone();
virtual void setDeleteSelfOnExecutionDone(bool value);
void setUniqueID(string value) { uniqueID = value; }
string getUniqueID() { return uniqueID; }
void setUniqueID(string value) {
uniqueID = value;
}
string getUniqueID() {
return uniqueID;
}
virtual void setRunningStatus(bool value);
virtual void setRunningStatus(bool value);
void setExecutingTask(bool value);
bool getExecutingTask();
void setExecutingTask(bool value);
bool getExecutingTask();
void setThreadOwnerValid(bool value);
bool getThreadOwnerValid();
Mutex * getMutexThreadOwnerValid();
void setThreadOwnerValid(bool value);
bool getThreadOwnerValid();
Mutex * getMutexThreadOwnerValid();
Mutex * getMutexThreadObjectAccessor();
template <typename T>
T * getGenericData() {
return genericData;
}
template <typename T>
void setGenericData(T *value) {
genericData = value;
}
static bool isThreadDeleted(void *ptr);
};
class RunningStatusSafeWrapper {
protected:
BaseThread *thread;
public:
RunningStatusSafeWrapper(BaseThread *thread) {
this->thread = thread;
Enable();
}
~RunningStatusSafeWrapper() {
Disable();
}
void Enable() {
if (this->thread != NULL) {
this->thread->setRunningStatus(true);
}
}
void Disable() {
if (this->thread != NULL) {
this->thread->setRunningStatus(false);
}
}
};
class ExecutingTaskSafeWrapper {
protected:
BaseThread *thread;
public:
ExecutingTaskSafeWrapper(BaseThread *thread) {
this->thread = thread;
Enable();
}
~ExecutingTaskSafeWrapper() {
Disable();
}
void Enable() {
if (this->thread != NULL) {
this->thread->setExecutingTask(true);
}
}
void Disable() {
if (this->thread != NULL) {
this->thread->setExecutingTask(false);
}
}
};
Mutex * getMutexThreadObjectAccessor();
template <typename T>
T * getGenericData() {
return genericData;
}
template <typename T>
void setGenericData(T *value) {
genericData = value;
}
static bool isThreadDeleted(void *ptr);
};
class RunningStatusSafeWrapper {
protected:
BaseThread *thread;
public:
RunningStatusSafeWrapper(BaseThread *thread) {
this->thread = thread;
Enable();
}
~RunningStatusSafeWrapper() {
Disable();
}
void Enable() {
if(this->thread != NULL) {
this->thread->setRunningStatus(true);
}
}
void Disable() {
if(this->thread != NULL) {
this->thread->setRunningStatus(false);
}
}
};
class ExecutingTaskSafeWrapper {
protected:
BaseThread *thread;
public:
ExecutingTaskSafeWrapper(BaseThread *thread) {
this->thread = thread;
Enable();
}
~ExecutingTaskSafeWrapper() {
Disable();
}
void Enable() {
if(this->thread != NULL) {
this->thread->setExecutingTask(true);
}
}
void Disable() {
if(this->thread != NULL) {
this->thread->setExecutingTask(false);
}
}
};
}}//end namespace
}//end namespace
#endif

View File

@@ -15,65 +15,67 @@
#include <algorithm>
#include "leak_dumper.h"
namespace Shared{ namespace PlatformByteOrder {
namespace Shared {
namespace PlatformByteOrder {
template<class T> T EndianReverse(T t) {
// unsigned char uc[sizeof t];
// memcpy(uc, &t, sizeof t);
//
// for (unsigned char *b = uc, *e = uc + sizeof(T) - 1; b < e; ++b, --e) {
// std::swap(*b, *e);
// }
// memcpy(&t, uc, sizeof t);
// return t;
template<class T> T EndianReverse(T t) {
// unsigned char uc[sizeof t];
// memcpy(uc, &t, sizeof t);
//
// for (unsigned char *b = uc, *e = uc + sizeof(T) - 1; b < e; ++b, --e) {
// std::swap(*b, *e);
// }
// memcpy(&t, uc, sizeof t);
// return t;
char& raw = reinterpret_cast<char&>(t);
std::reverse(&raw, &raw + sizeof(T));
return t;
}
inline static bool isBigEndian() {
short n = 0x1;
return (*(char*)(&n) == 0x0);
}
template<class T> T toCommonEndian(T t) {
static bool bigEndianSystem = isBigEndian();
if(bigEndianSystem == true) {
t = EndianReverse(t);
}
return t;
}
template<class T> T fromCommonEndian(T t) {
static bool bigEndianSystem = isBigEndian();
if(bigEndianSystem == true) {
t = EndianReverse(t);
}
return t;
}
template<class T>
void toEndianTypeArray(T *data, size_t size) {
static bool bigEndianSystem = isBigEndian();
if(bigEndianSystem == true) {
for(size_t i = 0; i < size; ++i) {
data[i] = toCommonEndian(data[i]);
char& raw = reinterpret_cast<char&>(t);
std::reverse(&raw, &raw + sizeof(T));
return t;
}
}
}
template<class T>
void fromEndianTypeArray(T *data, size_t size) {
static bool bigEndianSystem = isBigEndian();
if(bigEndianSystem == true) {
for(size_t i = 0; i < size; ++i) {
data[i] = fromCommonEndian(data[i]);
inline static bool isBigEndian() {
short n = 0x1;
return (*(char*) (&n) == 0x0);
}
template<class T> T toCommonEndian(T t) {
static bool bigEndianSystem = isBigEndian();
if (bigEndianSystem == true) {
t = EndianReverse(t);
}
return t;
}
template<class T> T fromCommonEndian(T t) {
static bool bigEndianSystem = isBigEndian();
if (bigEndianSystem == true) {
t = EndianReverse(t);
}
return t;
}
template<class T>
void toEndianTypeArray(T *data, size_t size) {
static bool bigEndianSystem = isBigEndian();
if (bigEndianSystem == true) {
for (size_t i = 0; i < size; ++i) {
data[i] = toCommonEndian(data[i]);
}
}
}
template<class T>
void fromEndianTypeArray(T *data, size_t size) {
static bool bigEndianSystem = isBigEndian();
if (bigEndianSystem == true) {
for (size_t i = 0; i < size; ++i) {
data[i] = fromCommonEndian(data[i]);
}
}
}
}
}
}}
#endif

View File

@@ -23,116 +23,116 @@
using namespace std;
using namespace Shared::Platform;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
// =====================================================
// class BaseThread
// =====================================================
// =====================================================
// class BaseThread
// =====================================================
class CacheManager
{
public:
class CacheManager {
public:
static const char *getFolderTreeContentsCheckSumRecursivelyCacheLookupKey1;
static const char *getFolderTreeContentsCheckSumRecursivelyCacheLookupKey2;
static const char *getFolderTreeContentsCheckSumListRecursivelyCacheLookupKey1;
static const char *getFolderTreeContentsCheckSumListRecursivelyCacheLookupKey2;
static const char *getFolderTreeContentsCheckSumRecursivelyCacheLookupKey1;
static const char *getFolderTreeContentsCheckSumRecursivelyCacheLookupKey2;
static const char *getFolderTreeContentsCheckSumListRecursivelyCacheLookupKey1;
static const char *getFolderTreeContentsCheckSumListRecursivelyCacheLookupKey2;
protected:
static std::map<string, Mutex *> itemCacheMutexList;
static Mutex mutexMap;
typedef enum {
cacheItemGet,
cacheItemSet
} CacheAccessorType;
protected:
static std::map<string, Mutex *> itemCacheMutexList;
static Mutex mutexMap;
typedef enum {
cacheItemGet,
cacheItemSet
} CacheAccessorType;
static Mutex & manageCachedItemMutex(string cacheKey) {
if(itemCacheMutexList.find(cacheKey) == itemCacheMutexList.end()) {
MutexSafeWrapper safeMutex(&mutexMap);
if(itemCacheMutexList.find(cacheKey) == itemCacheMutexList.end()) {
itemCacheMutexList[cacheKey] = new Mutex(CODE_AT_LINE);
}
safeMutex.ReleaseLock();
}
Mutex *mutex = itemCacheMutexList[cacheKey];
return *mutex;
}
template <typename T>
static T & manageCachedItem(string cacheKey, T *value,CacheAccessorType accessor) {
// Here is the actual type-safe instantiation
static std::map<string, T > itemCache;
if(accessor == cacheItemSet) {
if(value == NULL) {
try {
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
if(itemCache.find(cacheKey) != itemCache.end()) {
itemCache.erase(cacheKey);
static Mutex & manageCachedItemMutex(string cacheKey) {
if (itemCacheMutexList.find(cacheKey) == itemCacheMutexList.end()) {
MutexSafeWrapper safeMutex(&mutexMap);
if (itemCacheMutexList.find(cacheKey) == itemCacheMutexList.end()) {
itemCacheMutexList[cacheKey] = new Mutex(CODE_AT_LINE);
}
safeMutex.ReleaseLock();
}
catch(const std::exception &ex) {
throw megaglest_runtime_error(ex.what());
}
Mutex *mutex = itemCacheMutexList[cacheKey];
return *mutex;
}
if(value != NULL) {
try {
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
itemCache[cacheKey] = *value;
safeMutex.ReleaseLock();
}
catch(const std::exception &ex) {
throw megaglest_runtime_error(ex.what());
template <typename T>
static T & manageCachedItem(string cacheKey, T *value, CacheAccessorType accessor) {
// Here is the actual type-safe instantiation
static std::map<string, T > itemCache;
if (accessor == cacheItemSet) {
if (value == NULL) {
try {
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
if (itemCache.find(cacheKey) != itemCache.end()) {
itemCache.erase(cacheKey);
}
safeMutex.ReleaseLock();
} catch (const std::exception &ex) {
throw megaglest_runtime_error(ex.what());
}
}
if (value != NULL) {
try {
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
itemCache[cacheKey] = *value;
safeMutex.ReleaseLock();
} catch (const std::exception &ex) {
throw megaglest_runtime_error(ex.what());
}
}
}
// If this is the first access we return a default object of the type
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
return itemCache[cacheKey];
}
}
// If this is the first access we return a default object of the type
Mutex &mutexCache = manageCachedItemMutex(cacheKey);
MutexSafeWrapper safeMutex(&mutexCache);
return itemCache[cacheKey];
}
public:
public:
CacheManager() {
}
static void cleanupMutexes() {
MutexSafeWrapper safeMutex(&mutexMap);
for (std::map<string, Mutex *>::iterator iterMap = itemCacheMutexList.begin();
iterMap != itemCacheMutexList.end(); iterMap++) {
delete iterMap->second;
iterMap->second = NULL;
}
itemCacheMutexList.clear();
safeMutex.ReleaseLock();
}
~CacheManager() {
CacheManager::cleanupMutexes();
}
CacheManager() { }
static void cleanupMutexes() {
MutexSafeWrapper safeMutex(&mutexMap);
for(std::map<string, Mutex *>::iterator iterMap = itemCacheMutexList.begin();
iterMap != itemCacheMutexList.end(); iterMap++) {
delete iterMap->second;
iterMap->second = NULL;
}
itemCacheMutexList.clear();
safeMutex.ReleaseLock();
}
~CacheManager() {
CacheManager::cleanupMutexes();
}
template <typename T>
static void setCachedItem(string cacheKey, const T value) {
manageCachedItem<T>(cacheKey, value, cacheItemSet);
}
template <typename T>
static T & getCachedItem(string cacheKey) {
return manageCachedItem<T>(cacheKey, NULL, cacheItemGet);
}
template <typename T>
static void clearCachedItem(string cacheKey) {
return manageCachedItem<T>(cacheKey, NULL, cacheItemSet);
}
template <typename T>
static void setCachedItem(string cacheKey, const T value) {
manageCachedItem<T>(cacheKey,value,cacheItemSet);
}
template <typename T>
static T & getCachedItem(string cacheKey) {
return manageCachedItem<T>(cacheKey,NULL,cacheItemGet);
}
template <typename T>
static void clearCachedItem(string cacheKey) {
return manageCachedItem<T>(cacheKey,NULL,cacheItemSet);
}
template <typename T>
static Mutex & getMutexForItem(string cacheKey) {
return manageCachedItemMutex(cacheKey);
}
};
template <typename T>
static Mutex & getMutexForItem(string cacheKey) {
return manageCachedItemMutex(cacheKey);
}
};
}}//end namespace
}//end namespace
#endif

View File

@@ -25,7 +25,7 @@
#if defined(WIN32)
#define auto_ptr unique_ptr
#else
#define auto_ptr std::unique_ptr
#define auto_ptr std::unique_ptr
#endif
#endif

View File

@@ -40,295 +40,297 @@ using std::exception;
using Shared::Platform::int64;
using Shared::Util::Checksum;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define CODE_AT_LINE __FILE__ ":" TOSTRING(__LINE__)
#define CODE_AT_LINE_X(x) __FILE__ ":" TOSTRING(__LINE__) ":" TOSTRING(x)
static const int IGNORE_CMD_RESULT_VALUE = -999999;
static const int IGNORE_CMD_RESULT_VALUE = -999999;
// keycode constants (unfortunately designed after DirectInput and therefore not
// very specific)
// They also have to fit into a char. The positive numbers seem to be equal
// to ascii, for the rest we have to find sensefull mappings from SDL (which is
// alot more fine grained like left/right control instead of just control...)
const char vkAdd = -1;
const char vkSubtract = -2;
const char vkAlt = -3;
const char vkControl = -4;
const char vkShift = -5;
const char vkEscape = -6;
const char vkUp = -7;
const char vkLeft = -8;
const char vkRight = -9;
const char vkDown = -10;
const char vkReturn = -11;
const char vkBack = -12;
const char vkTab = -13;
const char vkF1 = -14;
const char vkF2 = -15;
const char vkF3 = -16;
const char vkF4 = -17;
const char vkF5 = -18;
const char vkF6 = -19;
const char vkF7 = -20;
const char vkF8 = -21;
const char vkF9 = -22;
const char vkF10 = -23;
const char vkF11 = -24;
const char vkF12 = -25;
const char vkDelete = -26;
const char vkPrint = -27;
const char vkPause = -29;
// keycode constants (unfortunately designed after DirectInput and therefore not
// very specific)
// They also have to fit into a char. The positive numbers seem to be equal
// to ascii, for the rest we have to find sensefull mappings from SDL (which is
// alot more fine grained like left/right control instead of just control...)
const char vkAdd = -1;
const char vkSubtract = -2;
const char vkAlt = -3;
const char vkControl = -4;
const char vkShift = -5;
const char vkEscape = -6;
const char vkUp = -7;
const char vkLeft = -8;
const char vkRight = -9;
const char vkDown = -10;
const char vkReturn = -11;
const char vkBack = -12;
const char vkTab = -13;
const char vkF1 = -14;
const char vkF2 = -15;
const char vkF3 = -16;
const char vkF4 = -17;
const char vkF5 = -18;
const char vkF6 = -19;
const char vkF7 = -20;
const char vkF8 = -21;
const char vkF9 = -22;
const char vkF10 = -23;
const char vkF11 = -24;
const char vkF12 = -25;
const char vkDelete = -26;
const char vkPrint = -27;
const char vkPause = -29;
class ShellCommandOutputCallbackInterface {
public:
virtual ~ShellCommandOutputCallbackInterface() {}
class ShellCommandOutputCallbackInterface {
public:
virtual ~ShellCommandOutputCallbackInterface() {
}
virtual void * getShellCommandOutput_UserData(string cmd) = 0;
virtual void ShellCommandOutput_CallbackEvent(string cmd,char *output,void *userdata) = 0;
};
virtual void * getShellCommandOutput_UserData(string cmd) = 0;
virtual void ShellCommandOutput_CallbackEvent(string cmd, char *output, void *userdata) = 0;
};
//typedef std::chrono::time_point<std::chrono::system_clock> system_time_point;
tm threadsafe_localtime(const time_t &time);
// extracting std::time_t from std:chrono for "now"
time_t systemtime_now();
//typedef std::chrono::time_point<std::chrono::system_clock> system_time_point;
tm threadsafe_localtime(const time_t &time);
// extracting std::time_t from std:chrono for "now"
time_t systemtime_now();
// =====================================================
// class PerformanceTimer
// =====================================================
// =====================================================
// class PerformanceTimer
// =====================================================
class PerformanceTimer {
private:
Uint32 lastTicks;
Uint32 updateTicks;
class PerformanceTimer {
private:
Uint32 lastTicks;
Uint32 updateTicks;
int times; // number of consecutive times
int maxTimes; // maximum number consecutive times
int times; // number of consecutive times
int maxTimes; // maximum number consecutive times
public:
void init(float fps, int maxTimes= -1);
public:
void init(float fps, int maxTimes = -1);
bool isTime();
void reset();
};
bool isTime();
void reset();
};
// =====================================================
// class Chrono
// =====================================================
// =====================================================
// class Chrono
// =====================================================
class Chrono {
private:
Uint32 startCount;
Uint32 accumCount;
Uint32 freq;
bool stopped;
class Chrono {
private:
Uint32 startCount;
Uint32 accumCount;
Uint32 freq;
bool stopped;
Uint32 lastStartCount;
Uint32 lastTickCount;
int64 lastResult;
int64 lastMultiplier;
bool lastStopped;
Uint32 lastStartCount;
Uint32 lastTickCount;
int64 lastResult;
int64 lastMultiplier;
bool lastStopped;
public:
Chrono(bool autoStart=false);
void start();
void stop();
void reset();
int64 getMicros();
int64 getMillis();
int64 getSeconds();
public:
Chrono(bool autoStart = false);
void start();
void stop();
void reset();
int64 getMicros();
int64 getMillis();
int64 getSeconds();
bool isStarted() const;
static int64 getCurTicks();
static int64 getCurMillis();
bool isStarted() const;
static int64 getCurTicks();
static int64 getCurMillis();
private:
int64 queryCounter(int64 multiplier);
};
private:
int64 queryCounter(int64 multiplier);
};
// =====================================================
// class ModeInfo
// =====================================================
class ModeInfo {
public:
int width;
int height;
int depth;
// =====================================================
// class ModeInfo
// =====================================================
class ModeInfo {
public:
int width;
int height;
int depth;
ModeInfo(int width, int height, int depth);
ModeInfo(int width, int height, int depth);
bool operator< (const ModeInfo &j) const {
if(this->width < j.width) {
return true;
}
else if(this->width == j.width && this->height < j.height) {
return true;
}
else if(this->width == j.width &&
this->height == j.height &&
this->depth < j.depth) {
return true;
bool operator< (const ModeInfo &j) const {
if (this->width < j.width) {
return true;
} else if (this->width == j.width && this->height < j.height) {
return true;
} else if (this->width == j.width &&
this->height == j.height &&
this->depth < j.depth) {
return true;
}
return false;
}
string getString() const;
};
// =====================================================
// Misc
// =====================================================
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ");
bool isdir(const char *path);
bool fileExists(const string &path);
inline bool folderExists(const string &path) {
return isdir(path.c_str());
}
return false;
}
string getString() const;
};
void findDirs(const string &path, vector<string> &results, bool errorOnNotFound, bool keepDuplicates);
void findDirs(const vector<string> &paths, vector<string> &results, bool errorOnNotFound = false, bool keepDuplicates = false);
void findAll(const vector<string> &paths, const string &fileFilter, vector<string> &results, bool cutExtension = false, bool errorOnNotFound = true, bool keepDuplicates = false);
void findAll(const string &path, vector<string> &results, bool cutExtension = false, bool errorOnNotFound = true);
vector<string> getFolderTreeContentsListRecursively(const string &path, const string &filterFileExt, bool includeFolders = false, vector<string> *recursiveMap = NULL);
// =====================================================
// Misc
// =====================================================
void Tokenize(const string& str,vector<string>& tokens,const string& delimiters = " ");
bool isdir(const char *path);
bool fileExists(const string &path);
inline bool folderExists(const string &path) { return isdir(path.c_str()); }
//string getGameVersion();
//string getGameGITVersion();
void setGameVersion(const string &version);
void setGameGITVersion(const string &git);
void findDirs(const string &path, vector<string> &results, bool errorOnNotFound,bool keepDuplicates);
void findDirs(const vector<string> &paths, vector<string> &results, bool errorOnNotFound=false,bool keepDuplicates=false);
void findAll(const vector<string> &paths, const string &fileFilter, vector<string> &results, bool cutExtension=false, bool errorOnNotFound=true,bool keepDuplicates=false);
void findAll(const string &path, vector<string> &results, bool cutExtension=false, bool errorOnNotFound=true);
vector<string> getFolderTreeContentsListRecursively(const string &path, const string &filterFileExt, bool includeFolders=false, vector<string> *recursiveMap=NULL);
string getCRCCacheFilePath();
void setCRCCacheFilePath(const string &path);
//string getGameVersion();
//string getGameGITVersion();
void setGameVersion(const string &version);
void setGameGITVersion(const string &git);
std::pair<string, string> getFolderTreeContentsCheckSumCacheKey(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
void clearFolderTreeContentsCheckSum(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
uint32 getFolderTreeContentsCheckSumRecursively(vector<string> paths, string pathSearchString, const string &filterFileExt, Checksum *recursiveChecksum, bool forceNoCache = false);
time_t getFolderTreeContentsCheckSumRecursivelyLastGenerated(const vector<string> &paths, string pathSearchString, const string &filterFileExt);
string getCRCCacheFilePath();
void setCRCCacheFilePath(const string &path);
std::pair<string, string> getFolderTreeContentsCheckSumCacheKey(const string &path, const string &filterFileExt);
void clearFolderTreeContentsCheckSum(const string &path, const string &filterFileExt);
uint32 getFolderTreeContentsCheckSumRecursively(const string &path, const string &filterFileExt, Checksum *recursiveChecksum, bool forceNoCache = false);
std::pair<string,string> getFolderTreeContentsCheckSumCacheKey(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
void clearFolderTreeContentsCheckSum(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
uint32 getFolderTreeContentsCheckSumRecursively(vector<string> paths, string pathSearchString, const string &filterFileExt, Checksum *recursiveChecksum,bool forceNoCache=false);
time_t getFolderTreeContentsCheckSumRecursivelyLastGenerated(const vector<string> &paths, string pathSearchString, const string &filterFileExt);
std::pair<string, string> getFolderTreeContentsCheckSumListCacheKey(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
void clearFolderTreeContentsCheckSumList(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
vector<std::pair<string, uint32> > getFolderTreeContentsCheckSumListRecursively(vector<string> paths, const string &pathSearchString, const string &filterFileExt, vector<std::pair<string, uint32> > *recursiveMap);
std::pair<string,string> getFolderTreeContentsCheckSumCacheKey(const string &path, const string &filterFileExt);
void clearFolderTreeContentsCheckSum(const string &path, const string &filterFileExt);
uint32 getFolderTreeContentsCheckSumRecursively(const string &path, const string &filterFileExt, Checksum *recursiveChecksum,bool forceNoCache=false);
std::pair<string, string> getFolderTreeContentsCheckSumListCacheKey(const string &path, const string &filterFileExt);
void clearFolderTreeContentsCheckSumList(const string &path, const string &filterFileExt);
vector<std::pair<string, uint32> > getFolderTreeContentsCheckSumListRecursively(const string &path, const string &filterFileExt, vector<std::pair<string, uint32> > *recursiveMap);
std::pair<string,string> getFolderTreeContentsCheckSumListCacheKey(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
void clearFolderTreeContentsCheckSumList(vector<string> paths, const string &pathSearchString, const string &filterFileExt);
vector<std::pair<string,uint32> > getFolderTreeContentsCheckSumListRecursively(vector<string> paths, const string &pathSearchString, const string &filterFileExt, vector<std::pair<string,uint32> > *recursiveMap);
void createDirectoryPaths(string Path);
string extractFileFromDirectoryPath(string filename);
string extractDirectoryPathFromFile(string filename);
string extractLastDirectoryFromPath(string Path);
string extractExtension(const string& filename);
std::pair<string,string> getFolderTreeContentsCheckSumListCacheKey(const string &path, const string &filterFileExt);
void clearFolderTreeContentsCheckSumList(const string &path, const string &filterFileExt);
vector<std::pair<string,uint32> > getFolderTreeContentsCheckSumListRecursively(const string &path, const string &filterFileExt, vector<std::pair<string,uint32> > *recursiveMap);
void getFullscreenVideoModes(vector<ModeInfo> *modeinfos, bool isFullscreen);
void getFullscreenVideoInfo(int &colorBits, int &screenWidth, int &screenHeight, bool isFullscreen);
void changeVideoModeFullScreen(bool value);
void restoreVideoMode(SDL_Window *sdlWindow, bool exitingApp = false);
void createDirectoryPaths(string Path);
string extractFileFromDirectoryPath(string filename);
string extractDirectoryPathFromFile(string filename);
string extractLastDirectoryFromPath(string Path);
string extractExtension(const string& filename);
bool StartsWith(const std::string &str, const std::string &key);
bool EndsWith(const string &str, const string& key);
void getFullscreenVideoModes(vector<ModeInfo> *modeinfos,bool isFullscreen);
void getFullscreenVideoInfo(int &colorBits,int &screenWidth,int &screenHeight,bool isFullscreen);
void changeVideoModeFullScreen(bool value);
void restoreVideoMode(SDL_Window *sdlWindow,bool exitingApp=false);
void endPathWithSlash(string &path, bool requireOSSlash = false);
void trimPathWithStartingSlash(string &path);
void updatePathClimbingParts(string &path, bool processPreviousDirTokenCheck = true);
string formatPath(string path);
bool StartsWith(const std::string &str, const std::string &key);
bool EndsWith(const string &str, const string& key);
string replaceAllHTMLEntities(string& context);
string replaceAll(string& context, const string& from, const string& to);
vector<char> replaceAllBetweenTokens(vector<char>& context, const string &startToken, const string &endToken, const string &newText, bool removeTokens = true);
string replaceAllBetweenTokens(string& context, const string &startToken, const string &endToken, const string &newText, bool removeTokens = true);
bool removeFile(string file);
bool renameFile(string oldFile, string newFile);
void removeFolder(const string &path);
off_t getFileSize(string filename);
bool searchAndReplaceTextInFile(string fileName, string findText, string replaceText, bool simulateOnly);
void copyFileTo(string fromFileName, string toFileName);
void endPathWithSlash(string &path, bool requireOSSlash=false);
void trimPathWithStartingSlash(string &path);
void updatePathClimbingParts(string &path,bool processPreviousDirTokenCheck=true);
string formatPath(string path);
//int getScreenW();
//int getScreenH();
string replaceAllHTMLEntities(string& context);
string replaceAll(string& context, const string& from, const string& to);
vector<char> replaceAllBetweenTokens(vector<char>& context, const string &startToken, const string &endToken, const string &newText, bool removeTokens=true);
string replaceAllBetweenTokens(string& context, const string &startToken, const string &endToken, const string &newText, bool removeTokens=true);
bool removeFile(string file);
bool renameFile(string oldFile, string newFile);
void removeFolder(const string &path);
off_t getFileSize(string filename);
bool searchAndReplaceTextInFile(string fileName, string findText, string replaceText, bool simulateOnly);
void copyFileTo(string fromFileName, string toFileName);
void sleep(int millis);
//int getScreenW();
//int getScreenH();
bool isCursorShowing();
void showCursor(bool b);
bool isKeyDown(int virtualKey);
//bool isKeyDown(SDLKey key);
string getCommandLine();
void sleep(int millis);
bool isCursorShowing();
void showCursor(bool b);
bool isKeyDown(int virtualKey);
//bool isKeyDown(SDLKey key);
string getCommandLine();
string getUserHome();
string getUserHome();
#define SPACES " "
inline string trim_at_delim (const string & s, const string &t) {
string d (s);
string::size_type i(d.find(t));
//printf("Searching for [%s] in [%s] got " MG_SIZE_T_SPECIFIER "\n",t.c_str(),d.c_str(),i);
inline string trim_at_delim(const string & s, const string &t) {
string d(s);
string::size_type i(d.find(t));
//printf("Searching for [%s] in [%s] got " MG_SIZE_T_SPECIFIER "\n",t.c_str(),d.c_str(),i);
if (i == string::npos) {
return d;
}
else {
d = d.erase (i) ;
//printf("returning [%s]\n",d.c_str());
return d;
}
}
if (i == string::npos) {
return d;
} else {
d = d.erase(i);
//printf("returning [%s]\n",d.c_str());
return d;
}
}
inline string trim_right (const string & s, const string & t = SPACES) {
string d (s);
string::size_type i (d.find_last_not_of (t));
if (i == string::npos)
return "";
else
return d.erase (d.find_last_not_of (t) + 1) ;
} // end of trim_right
inline string trim_right(const string & s, const string & t = SPACES) {
string d(s);
string::size_type i(d.find_last_not_of(t));
if (i == string::npos)
return "";
else
return d.erase(d.find_last_not_of(t) + 1);
} // end of trim_right
inline string trim_left (const string & s, const string & t = SPACES) {
string d (s);
return d.erase (0, s.find_first_not_of (t)) ;
} // end of trim_left
inline string trim_left(const string & s, const string & t = SPACES) {
string d(s);
return d.erase(0, s.find_first_not_of(t));
} // end of trim_left
inline string trim (const string & s, const string & t = SPACES) {
string d (s);
return trim_left (trim_right (d, t), t) ;
} // end of trim
inline string trim(const string & s, const string & t = SPACES) {
string d(s);
return trim_left(trim_right(d, t), t);
} // end of trim
string getFullFileArchiveExtractCommand(const string &fileArchiveExtractCommand,
string fileArchiveExtractCommandParameters, const string &outputpath, const string &archivename);
string getFullFileArchiveCompressCommand(const string &fileArchiveCompressCommand,
string fileArchiveCompressCommandParameters, const string &archivename, const string &archivefiles);
string getFullFileArchiveExtractCommand(const string &fileArchiveExtractCommand,
string fileArchiveExtractCommandParameters, const string &outputpath, const string &archivename);
string getFullFileArchiveCompressCommand(const string &fileArchiveCompressCommand,
string fileArchiveCompressCommandParameters, const string &archivename, const string &archivefiles);
bool executeShellCommand(string cmd,int expectedResult=IGNORE_CMD_RESULT_VALUE,ShellCommandOutputCallbackInterface *cb=NULL);
string executable_path(const string &exeName,bool includeExeNameInPath=false);
bool executeShellCommand(string cmd, int expectedResult = IGNORE_CMD_RESULT_VALUE, ShellCommandOutputCallbackInterface *cb = NULL);
string executable_path(const string &exeName, bool includeExeNameInPath = false);
void saveDataToFile(string filename, const string &data);
void saveDataToFile(string filename, const string &data);
bool valid_utf8_file(const char* file_name);
bool valid_utf8_file(const char* file_name);
//string getFileTextContents(string path);
//string getFileTextContents(string path);
string safeCharPtrCopy(const char *ptr, int maxLength=-1);
string safeCharPtrCopy(const char *ptr, int maxLength = -1);
class ValueCheckerVault {
class ValueCheckerVault {
protected:
std::map<const void *,uint32> vaultList;
protected:
std::map<const void *, uint32> vaultList;
void addItemToVault(const void *ptr,int value);
void checkItemInVault(const void *ptr,int value) const;
void addItemToVault(const void *ptr, int value);
void checkItemInVault(const void *ptr, int value) const;
public:
ValueCheckerVault() {
vaultList.clear();
}
};
public:
ValueCheckerVault() {
vaultList.clear();
}
};
}}//end namespace
}//end namespace
#endif

View File

@@ -22,153 +22,166 @@ using namespace std;
using namespace Shared::Util;
using namespace Shared::Graphics;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
//
// This interface describes the methods a callback object must implement
//
class FileCRCPreCacheThreadCallbackInterface {
public:
virtual vector<Texture2D *> processTech(string techName) = 0;
virtual ~FileCRCPreCacheThreadCallbackInterface() {}
};
//
// This interface describes the methods a callback object must implement
//
class FileCRCPreCacheThreadCallbackInterface {
public:
virtual vector<Texture2D *> processTech(string techName) = 0;
virtual ~FileCRCPreCacheThreadCallbackInterface() {
}
};
// =====================================================
// class FileCRCPreCacheThread
// =====================================================
// =====================================================
// class FileCRCPreCacheThread
// =====================================================
class FileCRCPreCacheThread : public BaseThread
{
protected:
vector<string> techDataPaths;
vector<string> workerThreadTechPaths;
FileCRCPreCacheThreadCallbackInterface *processTechCB;
class FileCRCPreCacheThread : public BaseThread {
protected:
vector<string> techDataPaths;
vector<string> workerThreadTechPaths;
FileCRCPreCacheThreadCallbackInterface *processTechCB;
static string preCacheThreadCacheLookupKey;
Mutex *mutexPauseForGame;
bool pauseForGame;
std::vector<FileCRCPreCacheThread *> preCacheWorkerThreadList;
static string preCacheThreadCacheLookupKey;
Mutex *mutexPauseForGame;
bool pauseForGame;
std::vector<FileCRCPreCacheThread *> preCacheWorkerThreadList;
public:
FileCRCPreCacheThread();
FileCRCPreCacheThread(vector<string> techDataPaths,vector<string> workerThreadTechPaths,FileCRCPreCacheThreadCallbackInterface *processTechCB);
virtual ~FileCRCPreCacheThread();
public:
FileCRCPreCacheThread();
FileCRCPreCacheThread(vector<string> techDataPaths, vector<string> workerThreadTechPaths, FileCRCPreCacheThreadCallbackInterface *processTechCB);
virtual ~FileCRCPreCacheThread();
static void setPreCacheThreadCacheLookupKey(string value) { preCacheThreadCacheLookupKey = value; }
static void setPreCacheThreadCacheLookupKey(string value) {
preCacheThreadCacheLookupKey = value;
}
virtual void execute();
void setTechDataPaths(vector<string> value) { this->techDataPaths = value; }
void setWorkerThreadTechPaths(vector<string> value) { this->workerThreadTechPaths = value; }
void setFileCRCPreCacheThreadCallbackInterface(FileCRCPreCacheThreadCallbackInterface *value) { processTechCB = value; }
virtual void execute();
void setTechDataPaths(vector<string> value) {
this->techDataPaths = value;
}
void setWorkerThreadTechPaths(vector<string> value) {
this->workerThreadTechPaths = value;
}
void setFileCRCPreCacheThreadCallbackInterface(FileCRCPreCacheThreadCallbackInterface *value) {
processTechCB = value;
}
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed);
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed);
void setPauseForGame(bool pauseForGame);
bool getPauseForGame();
};
void setPauseForGame(bool pauseForGame);
bool getPauseForGame();
};
// =====================================================
// class SimpleTaskThread
// =====================================================
typedef void taskFunctionCallback(BaseThread *callingThread);
//
// This interface describes the methods a callback object must implement
//
class SimpleTaskCallbackInterface {
public:
virtual void simpleTask(BaseThread *callingThread,void *userdata) = 0;
// =====================================================
// class SimpleTaskThread
// =====================================================
typedef void taskFunctionCallback(BaseThread *callingThread);
//
// This interface describes the methods a callback object must implement
//
class SimpleTaskCallbackInterface {
public:
virtual void simpleTask(BaseThread *callingThread, void *userdata) = 0;
virtual void setupTask(BaseThread *callingThread,void *userdata) { }
virtual void shutdownTask(BaseThread *callingThread,void *userdata) { }
virtual void setupTask(BaseThread *callingThread, void *userdata) {
}
virtual void shutdownTask(BaseThread *callingThread, void *userdata) {
}
virtual ~SimpleTaskCallbackInterface() {}
};
virtual ~SimpleTaskCallbackInterface() {
}
};
class SimpleTaskThread : public BaseThread
{
protected:
class SimpleTaskThread : public BaseThread {
protected:
Mutex *mutexSimpleTaskInterfaceValid;
bool simpleTaskInterfaceValid;
SimpleTaskCallbackInterface *simpleTaskInterface;
unsigned int executionCount;
unsigned int millisecsBetweenExecutions;
Mutex *mutexSimpleTaskInterfaceValid;
bool simpleTaskInterfaceValid;
SimpleTaskCallbackInterface *simpleTaskInterface;
unsigned int executionCount;
unsigned int millisecsBetweenExecutions;
Mutex *mutexTaskSignaller;
bool taskSignalled;
bool needTaskSignal;
Mutex *mutexTaskSignaller;
bool taskSignalled;
bool needTaskSignal;
Mutex *mutexLastExecuteTimestamp;
time_t lastExecuteTimestamp;
Mutex *mutexLastExecuteTimestamp;
time_t lastExecuteTimestamp;
taskFunctionCallback *overrideShutdownTask;
void *userdata;
bool wantSetupAndShutdown;
taskFunctionCallback *overrideShutdownTask;
void *userdata;
bool wantSetupAndShutdown;
public:
SimpleTaskThread(SimpleTaskCallbackInterface *simpleTaskInterface,
unsigned int executionCount=0,
unsigned int millisecsBetweenExecutions=0,
bool needTaskSignal = false,
void *userdata=NULL,
bool wantSetupAndShutdown=true);
virtual ~SimpleTaskThread();
public:
SimpleTaskThread(SimpleTaskCallbackInterface *simpleTaskInterface,
unsigned int executionCount = 0,
unsigned int millisecsBetweenExecutions = 0,
bool needTaskSignal = false,
void *userdata = NULL,
bool wantSetupAndShutdown = true);
virtual ~SimpleTaskThread();
virtual void * getUserdata() {
return userdata;
}
virtual int getUserdataAsInt() {
int value = 0;
if (userdata) {
value = *((int*) &userdata);
}
return value;
}
virtual void execute();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false);
void setTaskSignalled(bool value);
bool getTaskSignalled();
bool isThreadExecutionLagging();
void cleanup();
void setOverrideShutdownTask(taskFunctionCallback *ptr);
bool getSimpleTaskInterfaceValid();
void setSimpleTaskInterfaceValid(bool value);
};
// =====================================================
// class LogFileThread
// =====================================================
class LogFileEntry {
public:
SystemFlags::DebugType type;
string entry;
time_t entryDateTime;
};
class LogFileThread : public BaseThread {
protected:
Mutex *mutexLogList;
vector<LogFileEntry> logList;
time_t lastSaveToDisk;
void saveToDisk(bool forceSaveAll, bool logListAlreadyLocked);
bool checkSaveCurrentLogBufferToDisk();
public:
LogFileThread();
virtual ~LogFileThread();
virtual void execute();
void addLogEntry(SystemFlags::DebugType type, string logEntry);
std::size_t getLogEntryBufferCount();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false);
};
virtual void * getUserdata() { return userdata; }
virtual int getUserdataAsInt() {
int value = 0;
if(userdata) {
value = *((int*)&userdata);
}
return value;
}
virtual void execute();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false);
void setTaskSignalled(bool value);
bool getTaskSignalled();
bool isThreadExecutionLagging();
void cleanup();
void setOverrideShutdownTask(taskFunctionCallback *ptr);
bool getSimpleTaskInterfaceValid();
void setSimpleTaskInterfaceValid(bool value);
};
// =====================================================
// class LogFileThread
// =====================================================
class LogFileEntry {
public:
SystemFlags::DebugType type;
string entry;
time_t entryDateTime;
};
class LogFileThread : public BaseThread
{
protected:
Mutex *mutexLogList;
vector<LogFileEntry> logList;
time_t lastSaveToDisk;
void saveToDisk(bool forceSaveAll,bool logListAlreadyLocked);
bool checkSaveCurrentLogBufferToDisk();
public:
LogFileThread();
virtual ~LogFileThread();
virtual void execute();
void addLogEntry(SystemFlags::DebugType type, string logEntry);
std::size_t getLogEntryBufferCount();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false);
};
}}//end namespace
}//end namespace
#endif

View File

@@ -49,7 +49,7 @@ namespace math {
using std::exp;
using std::frexp;
using std::ldexp;
// the following are C99 functions -> not supported by VS C
// the following are C99 functions -> not supported by VS C
#if !defined(_MSC_VER) || _MSC_VER < 1500
using std::isnan;
using std::isinf;

View File

@@ -35,52 +35,52 @@
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues, and circular queues.
*
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* A circle queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A circle queue may be traversed in either direction, but has a more
* complex end of list detection.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues, and circular queues.
*
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* A circle queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A circle queue may be traversed in either direction, but has a more
* complex end of list detection.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
#ifdef QUEUE_MACRO_DEBUG
#define _Q_INVALIDATE(a) (a) = ((void *)-1)
@@ -88,9 +88,9 @@
#define _Q_INVALIDATE(a)
#endif
/*
* Singly-linked List definitions.
*/
/*
* Singly-linked List definitions.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
@@ -108,9 +108,9 @@ struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List access methods.
*/
/*
* Singly-linked List access methods.
*/
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_END(head) NULL
#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head))
@@ -126,9 +126,9 @@ struct { \
((var) = *(varp)) != SLIST_END(head); \
(varp) = &SLIST_NEXT((var), field))
/*
* Singly-linked List functions.
*/
/*
* Singly-linked List functions.
*/
#define SLIST_INIT(head) { \
SLIST_FIRST(head) = SLIST_END(head); \
}
@@ -165,9 +165,9 @@ struct { \
} \
} while (0)
/*
* List definitions.
*/
/*
* List definitions.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
@@ -182,9 +182,9 @@ struct { \
struct type **le_prev; /* address of previous next element */ \
}
/*
* List access methods
*/
/*
* List access methods
*/
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_END(head) NULL
#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head))
@@ -195,9 +195,9 @@ struct { \
(var)!= LIST_END(head); \
(var) = LIST_NEXT(var, field))
/*
* List functions.
*/
/*
* List functions.
*/
#define LIST_INIT(head) do { \
LIST_FIRST(head) = LIST_END(head); \
} while (0)
@@ -243,9 +243,9 @@ struct { \
_Q_INVALIDATE((elm)->field.le_next); \
} while (0)
/*
* Simple queue definitions.
*/
/*
* Simple queue definitions.
*/
#define SIMPLEQ_HEAD(name, type) \
struct name { \
struct type *sqh_first; /* first element */ \
@@ -260,9 +260,9 @@ struct { \
struct type *sqe_next; /* next element */ \
}
/*
* Simple queue access methods.
*/
/*
* Simple queue access methods.
*/
#define SIMPLEQ_FIRST(head) ((head)->sqh_first)
#define SIMPLEQ_END(head) NULL
#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
@@ -273,9 +273,9 @@ struct { \
(var) != SIMPLEQ_END(head); \
(var) = SIMPLEQ_NEXT(var, field))
/*
* Simple queue functions.
*/
/*
* Simple queue functions.
*/
#define SIMPLEQ_INIT(head) do { \
(head)->sqh_first = NULL; \
(head)->sqh_last = &(head)->sqh_first; \
@@ -304,9 +304,9 @@ struct { \
(head)->sqh_last = &(head)->sqh_first; \
} while (0)
/*
* Tail queue definitions.
*/
/*
* Tail queue definitions.
*/
#define TAILQ_HEAD(name, type) \
struct name { \
struct type *tqh_first; /* first element */ \
@@ -322,15 +322,15 @@ struct { \
struct type **tqe_prev; /* address of previous next element */ \
}
/*
* tail queue access methods
*/
/*
* tail queue access methods
*/
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_END(head) NULL
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
/* XXX */
/* XXX */
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_EMPTY(head) \
@@ -411,9 +411,9 @@ struct { \
_Q_INVALIDATE((elm)->field.tqe_next); \
} while (0)
/*
* Circular queue definitions.
*/
/*
* Circular queue definitions.
*/
#define CIRCLEQ_HEAD(name, type) \
struct name { \
struct type *cqh_first; /* first element */ \
@@ -429,9 +429,9 @@ struct { \
struct type *cqe_prev; /* previous element */ \
}
/*
* Circular queue access methods
*/
/*
* Circular queue access methods
*/
#define CIRCLEQ_FIRST(head) ((head)->cqh_first)
#define CIRCLEQ_LAST(head) ((head)->cqh_last)
#define CIRCLEQ_END(head) ((void *)(head))
@@ -450,9 +450,9 @@ struct { \
(var) != CIRCLEQ_END(head); \
(var) = CIRCLEQ_PREV(var, field))
/*
* Circular queue functions.
*/
/*
* Circular queue functions.
*/
#define CIRCLEQ_INIT(head) do { \
(head)->cqh_first = CIRCLEQ_END(head); \
(head)->cqh_last = CIRCLEQ_END(head); \

View File

@@ -7,20 +7,20 @@
#ifndef CODELENGTH_H_INCLUDED
#define CODELENGTH_H_INCLUDED
/* Encode length by using 7bit per Byte :
* Most significant bit of each byte specifies that the
* following byte is part of the code */
/* Encode length by using 7bit per Byte :
* Most significant bit of each byte specifies that the
* following byte is part of the code */
/* n : unsigned
* p : unsigned char *
*/
/* n : unsigned
* p : unsigned char *
*/
#define DECODELENGTH(n, p) n = 0; \
do { n = (n << 7) | (*p & 0x7f); } \
while((*(p++)&0x80) && (n<(1<<25)));
/* n : unsigned
* READ : function/macro to read one byte (unsigned char)
*/
/* n : unsigned
* READ : function/macro to read one byte (unsigned char)
*/
#define DECODELENGTH_READ(n, READ) \
n = 0; \
do { \
@@ -30,10 +30,10 @@
if(!(c&0x80)) break; \
} while(n<(1<<25));
/* n : unsigned
* p : unsigned char *
* p_limit : unsigned char *
*/
/* n : unsigned
* p : unsigned char *
* p_limit : unsigned char *
*/
#define DECODELENGTH_CHECKLIMIT(n, p, p_limit) \
n = 0; \
do { \
@@ -42,9 +42,9 @@
} while((*((p)++)&0x80) && (n<(1<<25)));
/* n : unsigned
* p : unsigned char *
*/
/* n : unsigned
* p : unsigned char *
*/
#define CODELENGTH(n, p) if(n>=268435456) *(p++) = (n >> 28) | 0x80; \
if(n>=2097152) *(p++) = (n >> 21) | 0x80; \
if(n>=16384) *(p++) = (n >> 14) | 0x80; \

View File

@@ -8,11 +8,11 @@
#ifndef CONNECTHOSTPORT_H_INCLUDED
#define CONNECTHOSTPORT_H_INCLUDED
/* connecthostport()
* return a socket connected (TCP) to the host and port
* or -1 in case of error */
/* connecthostport()
* return a socket connected (TCP) to the host and port
* or -1 in case of error */
int connecthostport(const char * host, unsigned short port,
unsigned int scope_id);
unsigned int scope_id);
#endif

View File

@@ -2,13 +2,13 @@
#define __DECLSPEC_H__
#if defined(_WIN32) && !defined(STATICLIB)
#ifdef MINIUPNP_EXPORTS
#define LIBSPEC __declspec(dllexport)
#else
#define LIBSPEC __declspec(dllimport)
#endif
#ifdef MINIUPNP_EXPORTS
#define LIBSPEC __declspec(dllexport)
#else
#define LIBSPEC
#define LIBSPEC __declspec(dllimport)
#endif
#else
#define LIBSPEC
#endif
#endif

View File

@@ -9,8 +9,8 @@
#ifndef IGD_DESC_PARSE_H_INCLUDED
#define IGD_DESC_PARSE_H_INCLUDED
/* Structure to store the result of the parsing of UPnP
* descriptions of Internet Gateway Devices */
/* Structure to store the result of the parsing of UPnP
* descriptions of Internet Gateway Devices */
#define MINIUPNPC_URL_MAXSIZE (128)
struct IGDdatas_service {
char controlurl[MINIUPNPC_URL_MAXSIZE];

View File

@@ -7,9 +7,9 @@
#ifndef MINISOAP_H_INCLUDED
#define MINISOAP_H_INCLUDED
/*int httpWrite(int, const char *, int, const char *);*/
/*int httpWrite(int, const char *, int, const char *);*/
int soapPostSubmit(int, const char *, const char *, unsigned short,
const char *, const char *, const char *);
const char *, const char *, const char *);
#endif

View File

@@ -11,7 +11,7 @@
#include "miniupnpc_declspec.h"
#include "upnpdev.h"
/* error codes : */
/* error codes : */
#define MINISSDPC_SUCCESS (0)
#define MINISSDPC_UNKNOWN_ERROR (-1)
#define MINISSDPC_SOCKET_ERROR (-101)
@@ -25,30 +25,30 @@ extern "C" {
#if !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__))
MINIUPNP_LIBSPEC struct UPNPDev *
getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath, int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath, int * error);
MINIUPNP_LIBSPEC int
connectToMiniSSDPD(const char * socketpath);
MINIUPNP_LIBSPEC int
connectToMiniSSDPD(const char * socketpath);
MINIUPNP_LIBSPEC int
disconnectFromMiniSSDPD(int fd);
MINIUPNP_LIBSPEC int
disconnectFromMiniSSDPD(int fd);
MINIUPNP_LIBSPEC int
requestDevicesFromMiniSSDPD(int fd, const char * devtype);
MINIUPNP_LIBSPEC int
requestDevicesFromMiniSSDPD(int fd, const char * devtype);
MINIUPNP_LIBSPEC struct UPNPDev *
receiveDevicesFromMiniSSDPD(int fd, int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
receiveDevicesFromMiniSSDPD(int fd, int * error);
#endif /* !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__)) */
MINIUPNP_LIBSPEC struct UPNPDev *
ssdpDiscoverDevices(const char * const deviceTypes[],
int delay, const char * multicastif,
int localport,
int ipv6, unsigned char ttl,
int * error,
int searchalltypes);
MINIUPNP_LIBSPEC struct UPNPDev *
ssdpDiscoverDevices(const char * const deviceTypes[],
int delay, const char * multicastif,
int localport,
int ipv6, unsigned char ttl,
int * error,
int searchalltypes);
#ifdef __cplusplus
}

View File

@@ -12,7 +12,7 @@
#include "igd_desc_parse.h"
#include "upnpdev.h"
/* error codes : */
/* error codes : */
#define UPNPDISCOVER_SUCCESS (0)
#define UPNPDISCOVER_UNKNOWN_ERROR (-1)
#define UPNPDISCOVER_SOCKET_ERROR (-101)
@@ -32,116 +32,118 @@
extern "C" {
#endif
/* Structures definitions : */
struct UPNParg { const char * elt; const char * val; };
/* Structures definitions : */
struct UPNParg {
const char * elt; const char * val;
};
char *
simpleUPnPcommand(int, const char *, const char *,
const char *, struct UPNParg *,
int *);
char *
simpleUPnPcommand(int, const char *, const char *,
const char *, struct UPNParg *,
int *);
/* upnpDiscover()
* discover UPnP devices on the network.
* The discovered devices are returned as a chained list.
* It is up to the caller to free the list with freeUPNPDevlist().
* delay (in millisecond) is the maximum time for waiting any device
* response.
* If available, device list will be obtained from MiniSSDPd.
* Default path for minissdpd socket will be used if minissdpdsock argument
* is NULL.
* If multicastif is not NULL, it will be used instead of the default
* multicast interface for sending SSDP discover packets.
* If localport is set to UPNP_LOCAL_PORT_SAME(1) SSDP packets will be sent
* from the source port 1900 (same as destination port), if set to
* UPNP_LOCAL_PORT_ANY(0) system assign a source port, any other value will
* be attempted as the source port.
* "searchalltypes" parameter is useful when searching several types,
* if 0, the discovery will stop with the first type returning results.
* TTL should default to 2. */
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscover(int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
/* upnpDiscover()
* discover UPnP devices on the network.
* The discovered devices are returned as a chained list.
* It is up to the caller to free the list with freeUPNPDevlist().
* delay (in millisecond) is the maximum time for waiting any device
* response.
* If available, device list will be obtained from MiniSSDPd.
* Default path for minissdpd socket will be used if minissdpdsock argument
* is NULL.
* If multicastif is not NULL, it will be used instead of the default
* multicast interface for sending SSDP discover packets.
* If localport is set to UPNP_LOCAL_PORT_SAME(1) SSDP packets will be sent
* from the source port 1900 (same as destination port), if set to
* UPNP_LOCAL_PORT_ANY(0) system assign a source port, any other value will
* be attempted as the source port.
* "searchalltypes" parameter is useful when searching several types,
* if 0, the discovery will stop with the first type returning results.
* TTL should default to 2. */
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscover(int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverAll(int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverAll(int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverDevice(const char * device, int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverDevice(const char * device, int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverDevices(const char * const deviceTypes[],
int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error,
int searchalltypes);
MINIUPNP_LIBSPEC struct UPNPDev *
upnpDiscoverDevices(const char * const deviceTypes[],
int delay, const char * multicastif,
const char * minissdpdsock, int localport,
int ipv6, unsigned char ttl,
int * error,
int searchalltypes);
/* parserootdesc() :
* parse root XML description of a UPnP device and fill the IGDdatas
* structure. */
MINIUPNP_LIBSPEC void parserootdesc(const char *, int, struct IGDdatas *);
/* parserootdesc() :
* parse root XML description of a UPnP device and fill the IGDdatas
* structure. */
MINIUPNP_LIBSPEC void parserootdesc(const char *, int, struct IGDdatas *);
/* structure used to get fast access to urls
* controlURL: controlURL of the WANIPConnection
* ipcondescURL: url of the description of the WANIPConnection
* controlURL_CIF: controlURL of the WANCommonInterfaceConfig
* controlURL_6FC: controlURL of the WANIPv6FirewallControl
*/
struct UPNPUrls {
char * controlURL;
char * ipcondescURL;
char * controlURL_CIF;
char * controlURL_6FC;
char * rootdescURL;
};
/* structure used to get fast access to urls
* controlURL: controlURL of the WANIPConnection
* ipcondescURL: url of the description of the WANIPConnection
* controlURL_CIF: controlURL of the WANCommonInterfaceConfig
* controlURL_6FC: controlURL of the WANIPv6FirewallControl
*/
struct UPNPUrls {
char * controlURL;
char * ipcondescURL;
char * controlURL_CIF;
char * controlURL_6FC;
char * rootdescURL;
};
/* UPNP_GetValidIGD() :
* return values :
* 0 = NO IGD found
* 1 = A valid connected IGD has been found
* 2 = A valid IGD has been found but it reported as
* not connected
* 3 = an UPnP device has been found but was not recognized as an IGD
*
* In any non zero return case, the urls and data structures
* passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to
* free allocated memory.
*/
MINIUPNP_LIBSPEC int
UPNP_GetValidIGD(struct UPNPDev * devlist,
struct UPNPUrls * urls,
struct IGDdatas * data,
char * lanaddr, int lanaddrlen);
/* UPNP_GetValidIGD() :
* return values :
* 0 = NO IGD found
* 1 = A valid connected IGD has been found
* 2 = A valid IGD has been found but it reported as
* not connected
* 3 = an UPnP device has been found but was not recognized as an IGD
*
* In any non zero return case, the urls and data structures
* passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to
* free allocated memory.
*/
MINIUPNP_LIBSPEC int
UPNP_GetValidIGD(struct UPNPDev * devlist,
struct UPNPUrls * urls,
struct IGDdatas * data,
char * lanaddr, int lanaddrlen);
/* UPNP_GetIGDFromUrl()
* Used when skipping the discovery process.
* When succeding, urls, data, and lanaddr arguments are set.
* return value :
* 0 - Not ok
* 1 - OK */
MINIUPNP_LIBSPEC int
UPNP_GetIGDFromUrl(const char * rootdescurl,
struct UPNPUrls * urls,
struct IGDdatas * data,
char * lanaddr, int lanaddrlen);
/* UPNP_GetIGDFromUrl()
* Used when skipping the discovery process.
* When succeding, urls, data, and lanaddr arguments are set.
* return value :
* 0 - Not ok
* 1 - OK */
MINIUPNP_LIBSPEC int
UPNP_GetIGDFromUrl(const char * rootdescurl,
struct UPNPUrls * urls,
struct IGDdatas * data,
char * lanaddr, int lanaddrlen);
MINIUPNP_LIBSPEC void
GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *,
const char *, unsigned int);
MINIUPNP_LIBSPEC void
GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *,
const char *, unsigned int);
MINIUPNP_LIBSPEC void
FreeUPNPUrls(struct UPNPUrls *);
MINIUPNP_LIBSPEC void
FreeUPNPUrls(struct UPNPUrls *);
/* return 0 or 1 */
MINIUPNP_LIBSPEC int UPNPIGD_IsConnected(struct UPNPUrls *, struct IGDdatas *);
/* return 0 or 1 */
MINIUPNP_LIBSPEC int UPNPIGD_IsConnected(struct UPNPUrls *, struct IGDdatas *);
#ifdef __cplusplus

View File

@@ -2,19 +2,19 @@
#define MINIUPNPC_DECLSPEC_H_INCLUDED
#if defined(_WIN32) && !defined(MINIUPNP_STATICLIB)
/* for windows dll */
#ifdef MINIUPNP_EXPORTS
#define MINIUPNP_LIBSPEC __declspec(dllexport)
#else
#define MINIUPNP_LIBSPEC __declspec(dllimport)
#endif
/* for windows dll */
#ifdef MINIUPNP_EXPORTS
#define MINIUPNP_LIBSPEC __declspec(dllexport)
#else
#if defined(__GNUC__) && __GNUC__ >= 4
/* fix dynlib for OS X 10.9.2 and Apple LLVM version 5.0 */
#define MINIUPNP_LIBSPEC __attribute__ ((visibility ("default")))
#else
#define MINIUPNP_LIBSPEC
#endif
#define MINIUPNP_LIBSPEC __declspec(dllimport)
#endif
#else
#if defined(__GNUC__) && __GNUC__ >= 4
/* fix dynlib for OS X 10.9.2 and Apple LLVM version 5.0 */
#define MINIUPNP_LIBSPEC __attribute__ ((visibility ("default")))
#else
#define MINIUPNP_LIBSPEC
#endif
#endif
#endif /* MINIUPNPC_DECLSPEC_H_INCLUDED */

View File

@@ -8,7 +8,7 @@
#ifndef __MINIUPNPCSTRINGS_H__
#define __MINIUPNPCSTRINGS_H__
//#include "lib/framework/wzglobal.h"
//#include "lib/framework/wzglobal.h"
#if defined(WIN32)
#define OS_STRING "Windows"

View File

@@ -14,13 +14,13 @@
extern "C" {
#endif
MINIUPNP_LIBSPEC void * getHTTPResponse(int s, int * size);
MINIUPNP_LIBSPEC void * getHTTPResponse(int s, int * size);
MINIUPNP_LIBSPEC void * miniwget(const char *, int *, unsigned int);
MINIUPNP_LIBSPEC void * miniwget(const char *, int *, unsigned int);
MINIUPNP_LIBSPEC void * miniwget_getaddr(const char *, int *, char *, int, unsigned int);
MINIUPNP_LIBSPEC void * miniwget_getaddr(const char *, int *, char *, int, unsigned int);
int parseURL(const char *, char *, unsigned short *, char * *, unsigned int *);
int parseURL(const char *, char *, unsigned short *, char * *, unsigned int *);
#ifdef __cplusplus
}

View File

@@ -12,18 +12,18 @@
#define MINIXML_H_INCLUDED
#define IS_WHITE_SPACE(c) ((c==' ') || (c=='\t') || (c=='\r') || (c=='\n'))
/* if a callback function pointer is set to NULL,
* the function is not called */
/* if a callback function pointer is set to NULL,
* the function is not called */
struct xmlparser {
const char *xmlstart;
const char *xmlend;
const char *xml; /* pointer to current character */
int xmlsize;
void * data;
void (*starteltfunc) (void *, const char *, int);
void (*endeltfunc) (void *, const char *, int);
void (*datafunc) (void *, const char *, int);
void (*attfunc) (void *, const char *, int, const char *, int);
void(*starteltfunc) (void *, const char *, int);
void(*endeltfunc) (void *, const char *, int);
void(*datafunc) (void *, const char *, int);
void(*attfunc) (void *, const char *, int, const char *, int);
};
/* parsexml()

View File

@@ -8,55 +8,57 @@
#define PORTLISTINGPARSE_H_INCLUDED
#include "miniupnpc_declspec.h"
/* for the definition of UNSIGNED_INTEGER */
/* for the definition of UNSIGNED_INTEGER */
#include "miniupnpctypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/* sample of PortMappingEntry :
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
*/
typedef enum { PortMappingEltNone,
PortMappingEntry, NewRemoteHost,
NewExternalPort, NewProtocol,
NewInternalPort, NewInternalClient,
NewEnabled, NewDescription,
NewLeaseTime } portMappingElt;
/* sample of PortMappingEntry :
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
*/
typedef enum {
PortMappingEltNone,
PortMappingEntry, NewRemoteHost,
NewExternalPort, NewProtocol,
NewInternalPort, NewInternalClient,
NewEnabled, NewDescription,
NewLeaseTime
} portMappingElt;
struct PortMapping {
struct PortMapping * l_next; /* list next element */
UNSIGNED_INTEGER leaseTime;
unsigned short externalPort;
unsigned short internalPort;
char remoteHost[64];
char internalClient[64];
char description[64];
char protocol[4];
unsigned char enabled;
};
struct PortMapping {
struct PortMapping * l_next; /* list next element */
UNSIGNED_INTEGER leaseTime;
unsigned short externalPort;
unsigned short internalPort;
char remoteHost[64];
char internalClient[64];
char description[64];
char protocol[4];
unsigned char enabled;
};
struct PortMappingParserData {
struct PortMapping * l_head; /* list head */
portMappingElt curelt;
};
struct PortMappingParserData {
struct PortMapping * l_head; /* list head */
portMappingElt curelt;
};
MINIUPNP_LIBSPEC void
ParsePortListing(const char * buffer, int bufsize,
struct PortMappingParserData * pdata);
MINIUPNP_LIBSPEC void
ParsePortListing(const char * buffer, int bufsize,
struct PortMappingParserData * pdata);
MINIUPNP_LIBSPEC void
FreePortListing(struct PortMappingParserData * pdata);
MINIUPNP_LIBSPEC void
FreePortListing(struct PortMappingParserData * pdata);
#ifdef __cplusplus
}

View File

@@ -8,12 +8,12 @@
#ifndef RECEIVEDATA_H_INCLUDED
#define RECEIVEDATA_H_INCLUDED
/* Reads data from the specified socket.
* Returns the number of bytes read if successful, zero if no bytes were
* read or if we timed out. Returns negative if there was an error. */
/* Reads data from the specified socket.
* Returns the number of bytes read if successful, zero if no bytes were
* read or if we timed out. Returns negative if there was an error. */
int receivedata(int socket,
char * data, int length,
int timeout, unsigned int * scope_id);
char * data, int length,
int timeout, unsigned int * scope_id);
#endif

View File

@@ -12,7 +12,7 @@
#include "miniupnpc_declspec.h"
#include "miniupnpctypes.h"
/* MiniUPnPc return codes : */
/* MiniUPnPc return codes : */
#define UPNPCOMMAND_SUCCESS (0)
#define UPNPCOMMAND_UNKNOWN_ERROR (-1)
#define UPNPCOMMAND_INVALID_ARGS (-2)
@@ -24,321 +24,321 @@
extern "C" {
#endif
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalBytesSent(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalBytesSent(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalBytesReceived(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalBytesReceived(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalPacketsSent(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalPacketsSent(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalPacketsReceived(const char * controlURL,
const char * servicetype);
MINIUPNP_LIBSPEC UNSIGNED_INTEGER
UPNP_GetTotalPacketsReceived(const char * controlURL,
const char * servicetype);
/* UPNP_GetStatusInfo()
* status and lastconnerror are 64 byte buffers
* Return values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error code */
MINIUPNP_LIBSPEC int
UPNP_GetStatusInfo(const char * controlURL,
const char * servicetype,
char * status,
unsigned int * uptime,
char * lastconnerror);
/* UPNP_GetStatusInfo()
* status and lastconnerror are 64 byte buffers
* Return values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error code */
MINIUPNP_LIBSPEC int
UPNP_GetStatusInfo(const char * controlURL,
const char * servicetype,
char * status,
unsigned int * uptime,
char * lastconnerror);
/* UPNP_GetConnectionTypeInfo()
* argument connectionType is a 64 character buffer
* Return Values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error code */
MINIUPNP_LIBSPEC int
UPNP_GetConnectionTypeInfo(const char * controlURL,
const char * servicetype,
char * connectionType);
/* UPNP_GetConnectionTypeInfo()
* argument connectionType is a 64 character buffer
* Return Values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error code */
MINIUPNP_LIBSPEC int
UPNP_GetConnectionTypeInfo(const char * controlURL,
const char * servicetype,
char * connectionType);
/* UPNP_GetExternalIPAddress() call the corresponding UPNP method.
* if the third arg is not null the value is copied to it.
* at least 16 bytes must be available
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR Either an UPnP error code or an unknown error.
*
* possible UPnP Errors :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control. */
MINIUPNP_LIBSPEC int
UPNP_GetExternalIPAddress(const char * controlURL,
const char * servicetype,
char * extIpAdd);
/* UPNP_GetExternalIPAddress() call the corresponding UPNP method.
* if the third arg is not null the value is copied to it.
* at least 16 bytes must be available
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR Either an UPnP error code or an unknown error.
*
* possible UPnP Errors :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control. */
MINIUPNP_LIBSPEC int
UPNP_GetExternalIPAddress(const char * controlURL,
const char * servicetype,
char * extIpAdd);
/* UPNP_GetLinkLayerMaxBitRates()
* call WANCommonInterfaceConfig:1#GetCommonLinkProperties
*
* return values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code. */
MINIUPNP_LIBSPEC int
UPNP_GetLinkLayerMaxBitRates(const char* controlURL,
const char* servicetype,
unsigned int * bitrateDown,
unsigned int * bitrateUp);
/* UPNP_GetLinkLayerMaxBitRates()
* call WANCommonInterfaceConfig:1#GetCommonLinkProperties
*
* return values :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code. */
MINIUPNP_LIBSPEC int
UPNP_GetLinkLayerMaxBitRates(const char* controlURL,
const char* servicetype,
unsigned int * bitrateDown,
unsigned int * bitrateUp);
/* UPNP_AddPortMapping()
* if desc is NULL, it will be defaulted to "libminiupnpc"
* remoteHost is usually NULL because IGD don't support it.
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR. Either an UPnP error code or an unknown error.
*
* List of possible UPnP errors for AddPortMapping :
* errorCode errorDescription (short) - Description (long)
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization and
* the sender was not authorized.
* 715 WildCardNotPermittedInSrcIP - The source IP address cannot be
* wild-carded
* 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded
* 718 ConflictInMappingEntry - The port mapping entry specified conflicts
* with a mapping assigned previously to another client
* 724 SamePortValuesRequired - Internal and External port values
* must be the same
* 725 OnlyPermanentLeasesSupported - The NAT implementation only supports
* permanent lease times on port mappings
* 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard
* and cannot be a specific IP address or DNS name
* 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and
* cannot be a specific port value
* 728 NoPortMapsAvailable - There are not enough free ports available to
* complete port mapping.
* 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed
* due to conflict with other mechanisms.
* 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded
*/
MINIUPNP_LIBSPEC int
UPNP_AddPortMapping(const char * controlURL, const char * servicetype,
const char * extPort,
const char * inPort,
const char * inClient,
const char * desc,
const char * proto,
const char * remoteHost,
const char * leaseDuration);
/* UPNP_AddPortMapping()
* if desc is NULL, it will be defaulted to "libminiupnpc"
* remoteHost is usually NULL because IGD don't support it.
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR. Either an UPnP error code or an unknown error.
*
* List of possible UPnP errors for AddPortMapping :
* errorCode errorDescription (short) - Description (long)
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization and
* the sender was not authorized.
* 715 WildCardNotPermittedInSrcIP - The source IP address cannot be
* wild-carded
* 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded
* 718 ConflictInMappingEntry - The port mapping entry specified conflicts
* with a mapping assigned previously to another client
* 724 SamePortValuesRequired - Internal and External port values
* must be the same
* 725 OnlyPermanentLeasesSupported - The NAT implementation only supports
* permanent lease times on port mappings
* 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard
* and cannot be a specific IP address or DNS name
* 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and
* cannot be a specific port value
* 728 NoPortMapsAvailable - There are not enough free ports available to
* complete port mapping.
* 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed
* due to conflict with other mechanisms.
* 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded
*/
MINIUPNP_LIBSPEC int
UPNP_AddPortMapping(const char * controlURL, const char * servicetype,
const char * extPort,
const char * inPort,
const char * inClient,
const char * desc,
const char * proto,
const char * remoteHost,
const char * leaseDuration);
/* UPNP_AddAnyPortMapping()
* if desc is NULL, it will be defaulted to "libminiupnpc"
* remoteHost is usually NULL because IGD don't support it.
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR. Either an UPnP error code or an unknown error.
*
* List of possible UPnP errors for AddPortMapping :
* errorCode errorDescription (short) - Description (long)
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization and
* the sender was not authorized.
* 715 WildCardNotPermittedInSrcIP - The source IP address cannot be
* wild-carded
* 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded
* 728 NoPortMapsAvailable - There are not enough free ports available to
* complete port mapping.
* 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed
* due to conflict with other mechanisms.
* 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded
*/
MINIUPNP_LIBSPEC int
UPNP_AddAnyPortMapping(const char * controlURL, const char * servicetype,
const char * extPort,
const char * inPort,
const char * inClient,
const char * desc,
const char * proto,
const char * remoteHost,
const char * leaseDuration,
char * reservedPort);
/* UPNP_AddAnyPortMapping()
* if desc is NULL, it will be defaulted to "libminiupnpc"
* remoteHost is usually NULL because IGD don't support it.
*
* Return values :
* 0 : SUCCESS
* NON ZERO : ERROR. Either an UPnP error code or an unknown error.
*
* List of possible UPnP errors for AddPortMapping :
* errorCode errorDescription (short) - Description (long)
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization and
* the sender was not authorized.
* 715 WildCardNotPermittedInSrcIP - The source IP address cannot be
* wild-carded
* 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded
* 728 NoPortMapsAvailable - There are not enough free ports available to
* complete port mapping.
* 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed
* due to conflict with other mechanisms.
* 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded
*/
MINIUPNP_LIBSPEC int
UPNP_AddAnyPortMapping(const char * controlURL, const char * servicetype,
const char * extPort,
const char * inPort,
const char * inClient,
const char * desc,
const char * proto,
const char * remoteHost,
const char * leaseDuration,
char * reservedPort);
/* UPNP_DeletePortMapping()
* Use same argument values as what was used for AddPortMapping().
* remoteHost is usually NULL because IGD don't support it.
* Return Values :
* 0 : SUCCESS
* NON ZERO : error. Either an UPnP error code or an undefined error.
*
* List of possible UPnP errors for DeletePortMapping :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 714 NoSuchEntryInArray - The specified value does not exist in the array */
MINIUPNP_LIBSPEC int
UPNP_DeletePortMapping(const char * controlURL, const char * servicetype,
const char * extPort, const char * proto,
const char * remoteHost);
/* UPNP_DeletePortMapping()
* Use same argument values as what was used for AddPortMapping().
* remoteHost is usually NULL because IGD don't support it.
* Return Values :
* 0 : SUCCESS
* NON ZERO : error. Either an UPnP error code or an undefined error.
*
* List of possible UPnP errors for DeletePortMapping :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 714 NoSuchEntryInArray - The specified value does not exist in the array */
MINIUPNP_LIBSPEC int
UPNP_DeletePortMapping(const char * controlURL, const char * servicetype,
const char * extPort, const char * proto,
const char * remoteHost);
/* UPNP_DeletePortRangeMapping()
* Use same argument values as what was used for AddPortMapping().
* remoteHost is usually NULL because IGD don't support it.
* Return Values :
* 0 : SUCCESS
* NON ZERO : error. Either an UPnP error code or an undefined error.
*
* List of possible UPnP errors for DeletePortMapping :
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 730 PortMappingNotFound - This error message is returned if no port
* mapping is found in the specified range.
* 733 InconsistentParameters - NewStartPort and NewEndPort values are not consistent. */
MINIUPNP_LIBSPEC int
UPNP_DeletePortMappingRange(const char * controlURL, const char * servicetype,
const char * extPortStart, const char * extPortEnd,
const char * proto,
const char * manage);
/* UPNP_DeletePortRangeMapping()
* Use same argument values as what was used for AddPortMapping().
* remoteHost is usually NULL because IGD don't support it.
* Return Values :
* 0 : SUCCESS
* NON ZERO : error. Either an UPnP error code or an undefined error.
*
* List of possible UPnP errors for DeletePortMapping :
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 730 PortMappingNotFound - This error message is returned if no port
* mapping is found in the specified range.
* 733 InconsistentParameters - NewStartPort and NewEndPort values are not consistent. */
MINIUPNP_LIBSPEC int
UPNP_DeletePortMappingRange(const char * controlURL, const char * servicetype,
const char * extPortStart, const char * extPortEnd,
const char * proto,
const char * manage);
/* UPNP_GetPortMappingNumberOfEntries()
* not supported by all routers */
MINIUPNP_LIBSPEC int
UPNP_GetPortMappingNumberOfEntries(const char* controlURL,
const char* servicetype,
unsigned int * num);
/* UPNP_GetPortMappingNumberOfEntries()
* not supported by all routers */
MINIUPNP_LIBSPEC int
UPNP_GetPortMappingNumberOfEntries(const char* controlURL,
const char* servicetype,
unsigned int * num);
/* UPNP_GetSpecificPortMappingEntry()
* retrieves an existing port mapping
* params :
* in extPort
* in proto
* in remoteHost
* out intClient (16 bytes)
* out intPort (6 bytes)
* out desc (80 bytes)
* out enabled (4 bytes)
* out leaseDuration (16 bytes)
*
* return value :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code.
*
* List of possible UPnP errors for _GetSpecificPortMappingEntry :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 714 NoSuchEntryInArray - The specified value does not exist in the array.
*/
MINIUPNP_LIBSPEC int
UPNP_GetSpecificPortMappingEntry(const char * controlURL,
const char * servicetype,
const char * extPort,
const char * proto,
const char * remoteHost,
char * intClient,
char * intPort,
char * desc,
char * enabled,
char * leaseDuration);
/* UPNP_GetSpecificPortMappingEntry()
* retrieves an existing port mapping
* params :
* in extPort
* in proto
* in remoteHost
* out intClient (16 bytes)
* out intPort (6 bytes)
* out desc (80 bytes)
* out enabled (4 bytes)
* out leaseDuration (16 bytes)
*
* return value :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code.
*
* List of possible UPnP errors for _GetSpecificPortMappingEntry :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 501 Action Failed - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 714 NoSuchEntryInArray - The specified value does not exist in the array.
*/
MINIUPNP_LIBSPEC int
UPNP_GetSpecificPortMappingEntry(const char * controlURL,
const char * servicetype,
const char * extPort,
const char * proto,
const char * remoteHost,
char * intClient,
char * intPort,
char * desc,
char * enabled,
char * leaseDuration);
/* UPNP_GetGenericPortMappingEntry()
* params :
* in index
* out extPort (6 bytes)
* out intClient (16 bytes)
* out intPort (6 bytes)
* out protocol (4 bytes)
* out desc (80 bytes)
* out enabled (4 bytes)
* out rHost (64 bytes)
* out duration (16 bytes)
*
* return value :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code.
*
* Possible UPNP Error codes :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds
*/
MINIUPNP_LIBSPEC int
UPNP_GetGenericPortMappingEntry(const char * controlURL,
const char * servicetype,
const char * index,
char * extPort,
char * intClient,
char * intPort,
char * protocol,
char * desc,
char * enabled,
char * rHost,
char * duration);
/* UPNP_GetGenericPortMappingEntry()
* params :
* in index
* out extPort (6 bytes)
* out intClient (16 bytes)
* out intPort (6 bytes)
* out protocol (4 bytes)
* out desc (80 bytes)
* out enabled (4 bytes)
* out rHost (64 bytes)
* out duration (16 bytes)
*
* return value :
* UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR
* or a UPnP Error Code.
*
* Possible UPNP Error codes :
* 402 Invalid Args - See UPnP Device Architecture section on Control.
* 606 Action not authorized - The action requested REQUIRES authorization
* and the sender was not authorized.
* 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds
*/
MINIUPNP_LIBSPEC int
UPNP_GetGenericPortMappingEntry(const char * controlURL,
const char * servicetype,
const char * index,
char * extPort,
char * intClient,
char * intPort,
char * protocol,
char * desc,
char * enabled,
char * rHost,
char * duration);
/* UPNP_GetListOfPortMappings() Available in IGD v2
*
*
* Possible UPNP Error codes :
* 606 Action not Authorized
* 730 PortMappingNotFound - no port mapping is found in the specified range.
* 733 InconsistantParameters - NewStartPort and NewEndPort values are not
* consistent.
*/
MINIUPNP_LIBSPEC int
UPNP_GetListOfPortMappings(const char * controlURL,
const char * servicetype,
const char * startPort,
const char * endPort,
const char * protocol,
const char * numberOfPorts,
struct PortMappingParserData * data);
/* UPNP_GetListOfPortMappings() Available in IGD v2
*
*
* Possible UPNP Error codes :
* 606 Action not Authorized
* 730 PortMappingNotFound - no port mapping is found in the specified range.
* 733 InconsistantParameters - NewStartPort and NewEndPort values are not
* consistent.
*/
MINIUPNP_LIBSPEC int
UPNP_GetListOfPortMappings(const char * controlURL,
const char * servicetype,
const char * startPort,
const char * endPort,
const char * protocol,
const char * numberOfPorts,
struct PortMappingParserData * data);
/* IGD:2, functions for service WANIPv6FirewallControl:1 */
MINIUPNP_LIBSPEC int
UPNP_GetFirewallStatus(const char * controlURL,
const char * servicetype,
int * firewallEnabled,
int * inboundPinholeAllowed);
/* IGD:2, functions for service WANIPv6FirewallControl:1 */
MINIUPNP_LIBSPEC int
UPNP_GetFirewallStatus(const char * controlURL,
const char * servicetype,
int * firewallEnabled,
int * inboundPinholeAllowed);
MINIUPNP_LIBSPEC int
UPNP_GetOutboundPinholeTimeout(const char * controlURL, const char * servicetype,
const char * remoteHost,
const char * remotePort,
const char * intClient,
const char * intPort,
const char * proto,
int * opTimeout);
MINIUPNP_LIBSPEC int
UPNP_GetOutboundPinholeTimeout(const char * controlURL, const char * servicetype,
const char * remoteHost,
const char * remotePort,
const char * intClient,
const char * intPort,
const char * proto,
int * opTimeout);
MINIUPNP_LIBSPEC int
UPNP_AddPinhole(const char * controlURL, const char * servicetype,
const char * remoteHost,
const char * remotePort,
const char * intClient,
const char * intPort,
const char * proto,
const char * leaseTime,
char * uniqueID);
MINIUPNP_LIBSPEC int
UPNP_AddPinhole(const char * controlURL, const char * servicetype,
const char * remoteHost,
const char * remotePort,
const char * intClient,
const char * intPort,
const char * proto,
const char * leaseTime,
char * uniqueID);
MINIUPNP_LIBSPEC int
UPNP_UpdatePinhole(const char * controlURL, const char * servicetype,
const char * uniqueID,
const char * leaseTime);
MINIUPNP_LIBSPEC int
UPNP_UpdatePinhole(const char * controlURL, const char * servicetype,
const char * uniqueID,
const char * leaseTime);
MINIUPNP_LIBSPEC int
UPNP_DeletePinhole(const char * controlURL, const char * servicetype, const char * uniqueID);
MINIUPNP_LIBSPEC int
UPNP_DeletePinhole(const char * controlURL, const char * servicetype, const char * uniqueID);
MINIUPNP_LIBSPEC int
UPNP_CheckPinholeWorking(const char * controlURL, const char * servicetype,
const char * uniqueID, int * isWorking);
MINIUPNP_LIBSPEC int
UPNP_CheckPinholeWorking(const char * controlURL, const char * servicetype,
const char * uniqueID, int * isWorking);
MINIUPNP_LIBSPEC int
UPNP_GetPinholePackets(const char * controlURL, const char * servicetype,
const char * uniqueID, int * packets);
MINIUPNP_LIBSPEC int
UPNP_GetPinholePackets(const char * controlURL, const char * servicetype,
const char * uniqueID, int * packets);
#ifdef __cplusplus
}

View File

@@ -14,18 +14,18 @@
extern "C" {
#endif
struct UPNPDev {
struct UPNPDev * pNext;
char * descURL;
char * st;
unsigned int scope_id;
char * usn;
char buffer[3];
};
struct UPNPDev {
struct UPNPDev * pNext;
char * descURL;
char * st;
unsigned int scope_id;
char * usn;
char buffer[3];
};
/* freeUPNPDevlist()
* free list returned by upnpDiscover() */
MINIUPNP_LIBSPEC void freeUPNPDevlist(struct UPNPDev * devlist);
/* freeUPNPDevlist()
* free list returned by upnpDiscover() */
MINIUPNP_LIBSPEC void freeUPNPDevlist(struct UPNPDev * devlist);
#ifdef __cplusplus

View File

@@ -14,10 +14,10 @@
extern "C" {
#endif
/* strupnperror()
* Return a string description of the UPnP error code
* or NULL for undefinded errors */
MINIUPNP_LIBSPEC const char * strupnperror(int err);
/* strupnperror()
* Return a string description of the UPnP error code
* or NULL for undefinded errors */
MINIUPNP_LIBSPEC const char * strupnperror(int err);
#ifdef __cplusplus
}

View File

@@ -12,47 +12,47 @@
extern "C" {
#endif
struct NameValue {
struct NameValue * l_next;
char name[64];
char value[128];
};
struct NameValue {
struct NameValue * l_next;
char name[64];
char value[128];
};
struct NameValueParserData {
struct NameValue * l_head;
char curelt[64];
char * portListing;
int portListingLength;
int topelt;
const char * cdata;
int cdatalen;
};
struct NameValueParserData {
struct NameValue * l_head;
char curelt[64];
char * portListing;
int portListingLength;
int topelt;
const char * cdata;
int cdatalen;
};
/* ParseNameValue() */
void
ParseNameValue(const char * buffer, int bufsize,
struct NameValueParserData * data);
/* ParseNameValue() */
void
ParseNameValue(const char * buffer, int bufsize,
struct NameValueParserData * data);
/* ClearNameValueList() */
void
ClearNameValueList(struct NameValueParserData * pdata);
/* ClearNameValueList() */
void
ClearNameValueList(struct NameValueParserData * pdata);
/* GetValueFromNameValueList() */
char *
GetValueFromNameValueList(struct NameValueParserData * pdata,
const char * Name);
/* GetValueFromNameValueList() */
char *
GetValueFromNameValueList(struct NameValueParserData * pdata,
const char * Name);
#if 0
/* GetValueFromNameValueListIgnoreNS() */
char *
GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata,
const char * Name);
/* GetValueFromNameValueListIgnoreNS() */
char *
GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata,
const char * Name);
#endif
/* DisplayNameValueList() */
/* DisplayNameValueList() */
#ifdef DEBUG
void
DisplayNameValueList(char * buffer, int bufsize);
void
DisplayNameValueList(char * buffer, int bufsize);
#endif
#ifdef __cplusplus

View File

@@ -13,8 +13,8 @@
#define _SHARED_PLATFORMCOMMON_IRCTHREAD_H_
#ifdef WIN32
#include <winsock2.h>
#include <winsock.h>
#include <winsock2.h>
#include <winsock.h>
#endif
#include "base_thread.h"
@@ -30,116 +30,154 @@ typedef struct irc_session_s irc_session_t;
using namespace std;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
// =====================================================
// class IRCThreadThread
// =====================================================
// =====================================================
// class IRCThreadThread
// =====================================================
enum IRCEventType {
IRC_evt_chatText = 0,
IRC_evt_exitThread = 1
};
enum IRCEventType {
IRC_evt_chatText = 0,
IRC_evt_exitThread = 1
};
void normalizeNick(char *nick);
void normalizeNick(char *nick);
class IRCCallbackInterface {
public:
virtual void IRC_CallbackEvent(IRCEventType evt, const char* origin, const char **params, unsigned int count) = 0;
class IRCCallbackInterface {
public:
virtual void IRC_CallbackEvent(IRCEventType evt, const char* origin, const char **params, unsigned int count) = 0;
virtual ~IRCCallbackInterface() {}
};
virtual ~IRCCallbackInterface() {
}
};
class IRCThread : public BaseThread
{
public:
static bool debugEnabled;
protected:
static const char *globalCacheContainerName;
class IRCThread : public BaseThread {
public:
static bool debugEnabled;
protected:
static const char *globalCacheContainerName;
std::vector<string> argv;
std::vector<string> argv;
Mutex mutexIRCSession;
irc_session_t *ircSession;
Mutex mutexIRCSession;
irc_session_t *ircSession;
string execute_cmd_onconnect;
//string password;
string username;
string channel;
string nick;
string execute_cmd_onconnect;
//string password;
string username;
string channel;
string nick;
string playerName;
string glestVersionString;
string playerName;
string glestVersionString;
bool hasJoinedChannel;
bool hasJoinedChannel;
Mutex mutexEventDataDone;
bool eventDataDone;
Mutex mutexEventDataDone;
bool eventDataDone;
Mutex mutexNickList;
time_t lastNickListUpdate;
std::vector<string> eventData;
Mutex mutexNickList;
time_t lastNickListUpdate;
std::vector<string> eventData;
Mutex mutexIRCCB;
IRCCallbackInterface *callbackObj;
Mutex mutexIRCCB;
IRCCallbackInterface *callbackObj;
bool wantToLeaveChannel;
bool wantToLeaveChannel;
int irc_run_session(irc_session_t * session);
int irc_run_session(irc_session_t * session);
public:
public:
IRCThread(const std::vector<string> &argv,IRCCallbackInterface *callbackObj);
virtual ~IRCThread();
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
IRCThread(const std::vector<string> &argv, IRCCallbackInterface *callbackObj);
virtual ~IRCThread();
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
static void setGlobalCacheContainerName(const char *name) { globalCacheContainerName = name; }
static void setGlobalCacheContainerName(const char *name) {
globalCacheContainerName = name;
}
void setPlayerName(string value) { playerName = value; }
void setGlestVersionString(string value) { glestVersionString = value; }
string getPlayerName() const { return playerName; }
void setPlayerName(string value) {
playerName = value;
}
void setGlestVersionString(string value) {
glestVersionString = value;
}
string getPlayerName() const {
return playerName;
}
bool getWantToLeaveChannel() const { return wantToLeaveChannel; }
bool getWantToLeaveChannel() const {
return wantToLeaveChannel;
}
void SendIRCCmdMessage(string target, string msg);
std::vector<string> getNickList();
bool isConnected(bool mutexLockRequired=true);
void SendIRCCmdMessage(string target, string msg);
std::vector<string> getNickList();
bool isConnected(bool mutexLockRequired = true);
std::vector<string> GetIRCConnectedNickList(string target, bool waitForCompletion);
std::vector<string> GetIRCConnectedNickList(string target, bool waitForCompletion);
bool getEventDataDone();
void setEventDataDone(bool value);
bool getEventDataDone();
void setEventDataDone(bool value);
bool getHasJoinedChannel() const { return hasJoinedChannel; }
void setHasJoinedChannel(bool value) { hasJoinedChannel=value; }
bool getHasJoinedChannel() const {
return hasJoinedChannel;
}
void setHasJoinedChannel(bool value) {
hasJoinedChannel = value;
}
time_t getLastNickListUpdate() const { return lastNickListUpdate; }
void setLastNickListUpdate(time_t value) { lastNickListUpdate = value;}
time_t getLastNickListUpdate() const {
return lastNickListUpdate;
}
void setLastNickListUpdate(time_t value) {
lastNickListUpdate = value;
}
string getChannel() const { return channel;}
string getNick() const { return nick;}
string getChannel() const {
return channel;
}
string getNick() const {
return nick;
}
string getExecute_cmd_onconnect() const { return execute_cmd_onconnect; }
void setExecute_cmd_onconnect(string value) { execute_cmd_onconnect = value; }
string getExecute_cmd_onconnect() const {
return execute_cmd_onconnect;
}
void setExecute_cmd_onconnect(string value) {
execute_cmd_onconnect = value;
}
std::vector<string> getArgs() const { return argv;}
std::vector<string> getArgs() const {
return argv;
}
Mutex * getMutexNickList() { return &mutexNickList; }
std::vector<string> & getCachedNickList() { return eventData; }
void setCachedNickList(std::vector<string> &list) { eventData = list; }
Mutex * getMutexNickList() {
return &mutexNickList;
}
std::vector<string> & getCachedNickList() {
return eventData;
}
void setCachedNickList(std::vector<string> &list) {
eventData = list;
}
Mutex * getMutexIRCCB() { return &mutexIRCCB; }
IRCCallbackInterface * getCallbackObj(bool lockObj=true);
void setCallbackObj(IRCCallbackInterface *cb);
Mutex * getMutexIRCCB() {
return &mutexIRCCB;
}
IRCCallbackInterface * getCallbackObj(bool lockObj = true);
void setCallbackObj(IRCCallbackInterface *cb);
void joinChannel();
void leaveChannel();
void connectToHost();
void disconnect();
};
void joinChannel();
void leaveChannel();
void connectToHost();
void disconnect();
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -20,143 +20,147 @@
using namespace std;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
// =====================================================
// class FTPClientThread
// =====================================================
// =====================================================
// class FTPClientThread
// =====================================================
enum FTP_Client_ResultType {
ftp_crt_SUCCESS = 0,
ftp_crt_PARTIALFAIL = 1,
ftp_crt_FAIL = 2,
ftp_crt_ABORTED = 3,
ftp_crt_HOST_NOT_ACCEPTING = 4
};
enum FTP_Client_ResultType {
ftp_crt_SUCCESS = 0,
ftp_crt_PARTIALFAIL = 1,
ftp_crt_FAIL = 2,
ftp_crt_ABORTED = 3,
ftp_crt_HOST_NOT_ACCEPTING = 4
};
enum FTP_Client_CallbackType {
ftp_cct_Map = 0,
ftp_cct_Tileset = 1,
ftp_cct_Techtree = 2,
ftp_cct_Scenario = 3,
ftp_cct_File = 4,
ftp_cct_TempFile = 5,
ftp_cct_DownloadProgress = 6,
ftp_cct_ExtractProgress = 7
};
enum FTP_Client_CallbackType {
ftp_cct_Map = 0,
ftp_cct_Tileset = 1,
ftp_cct_Techtree = 2,
ftp_cct_Scenario = 3,
ftp_cct_File = 4,
ftp_cct_TempFile = 5,
ftp_cct_DownloadProgress = 6,
ftp_cct_ExtractProgress = 7
};
class FTPClientCallbackInterface {
public:
virtual ~FTPClientCallbackInterface() {}
struct FtpProgressStats {
double download_total;
double download_now;
double upload_total;
double upload_now;
string currentFilename;
FTP_Client_CallbackType downloadType;
};
class FTPClientCallbackInterface {
public:
virtual ~FTPClientCallbackInterface() {
}
struct FtpProgressStats {
double download_total;
double download_now;
double upload_total;
double upload_now;
string currentFilename;
FTP_Client_CallbackType downloadType;
};
virtual void FTPClient_CallbackEvent(string itemName,
FTP_Client_CallbackType type,
pair<FTP_Client_ResultType,string> result,
void *userdata) = 0;
};
virtual void FTPClient_CallbackEvent(string itemName,
FTP_Client_CallbackType type,
pair<FTP_Client_ResultType, string> result,
void *userdata) = 0;
};
class FTPClientThread : public BaseThread, public ShellCommandOutputCallbackInterface
{
protected:
int portNumber;
string serverUrl;
FTPClientCallbackInterface *pCBObject;
std::pair<string,string> mapsPath;
std::pair<string,string> tilesetsPath;
std::pair<string,string> techtreesPath;
std::pair<string,string> scenariosPath;
string tempFilesPath;
class FTPClientThread : public BaseThread, public ShellCommandOutputCallbackInterface {
protected:
int portNumber;
string serverUrl;
FTPClientCallbackInterface *pCBObject;
std::pair<string, string> mapsPath;
std::pair<string, string> tilesetsPath;
std::pair<string, string> techtreesPath;
std::pair<string, string> scenariosPath;
string tempFilesPath;
Mutex mutexMapFileList;
vector<pair<string,string> > mapFileList;
Mutex mutexMapFileList;
vector<pair<string, string> > mapFileList;
Mutex mutexTilesetList;
vector<pair<string,string> > tilesetList;
Mutex mutexTilesetList;
vector<pair<string, string> > tilesetList;
Mutex mutexTechtreeList;
vector<pair<string,string> > techtreeList;
Mutex mutexTechtreeList;
vector<pair<string, string> > techtreeList;
Mutex mutexScenarioList;
vector<pair<string,string> > scenarioList;
Mutex mutexScenarioList;
vector<pair<string, string> > scenarioList;
Mutex mutexFileList;
vector<pair<string,string> > fileList;
Mutex mutexFileList;
vector<pair<string, string> > fileList;
Mutex mutexTempFileList;
vector<pair<string,string> > tempFileList;
Mutex mutexTempFileList;
vector<pair<string, string> > tempFileList;
void getMapFromServer(pair<string,string> mapFilename);
pair<FTP_Client_ResultType,string> getMapFromServer(pair<string,string> mapFileName, string ftpUser, string ftpUserPassword);
void getMapFromServer(pair<string, string> mapFilename);
pair<FTP_Client_ResultType, string> getMapFromServer(pair<string, string> mapFileName, string ftpUser, string ftpUserPassword);
void getTilesetFromServer(pair<string,string> tileSetName);
pair<FTP_Client_ResultType,string> getTilesetFromServer(pair<string,string> tileSetName, string tileSetNameSubfolder, string ftpUser, string ftpUserPassword, bool findArchive);
void getTilesetFromServer(pair<string, string> tileSetName);
pair<FTP_Client_ResultType, string> getTilesetFromServer(pair<string, string> tileSetName, string tileSetNameSubfolder, string ftpUser, string ftpUserPassword, bool findArchive);
void getTechtreeFromServer(pair<string,string> techtreeName);
pair<FTP_Client_ResultType,string> getTechtreeFromServer(pair<string,string> techtreeName, string ftpUser, string ftpUserPassword);
void getTechtreeFromServer(pair<string, string> techtreeName);
pair<FTP_Client_ResultType, string> getTechtreeFromServer(pair<string, string> techtreeName, string ftpUser, string ftpUserPassword);
void getScenarioFromServer(pair<string,string> fileName);
pair<FTP_Client_ResultType,string> getScenarioInternalFromServer(pair<string,string> fileName);
void getScenarioFromServer(pair<string, string> fileName);
pair<FTP_Client_ResultType, string> getScenarioInternalFromServer(pair<string, string> fileName);
void getFileFromServer(pair<string,string> fileName);
pair<FTP_Client_ResultType,string> getFileInternalFromServer(pair<string,string> fileName);
void getFileFromServer(pair<string, string> fileName);
pair<FTP_Client_ResultType, string> getFileInternalFromServer(pair<string, string> fileName);
void getTempFileFromServer(pair<string,string> fileName);
pair<FTP_Client_ResultType,string> getTempFileInternalFromServer(pair<string,string> fileName);
void getTempFileFromServer(pair<string, string> fileName);
pair<FTP_Client_ResultType, string> getTempFileInternalFromServer(pair<string, string> fileName);
Mutex mutexProgressMutex;
Mutex mutexProgressMutex;
string fileArchiveExtension;
string fileArchiveExtractCommand;
string fileArchiveExtractCommandParameters;
int fileArchiveExtractCommandSuccessResult;
string fileArchiveExtension;
string fileArchiveExtractCommand;
string fileArchiveExtractCommandParameters;
int fileArchiveExtractCommandSuccessResult;
pair<FTP_Client_ResultType,string> getFileFromServer(FTP_Client_CallbackType downloadType,
pair<string,string> fileNameTitle,
string remotePath, string destFileSaveAs, string ftpUser,
string ftpUserPassword, vector <string> *wantDirListOnly=NULL);
pair<FTP_Client_ResultType, string> getFileFromServer(FTP_Client_CallbackType downloadType,
pair<string, string> fileNameTitle,
string remotePath, string destFileSaveAs, string ftpUser,
string ftpUserPassword, vector <string> *wantDirListOnly = NULL);
string shellCommandCallbackUserData;
virtual void * getShellCommandOutput_UserData(string cmd);
virtual void ShellCommandOutput_CallbackEvent(string cmd,char *output,void *userdata);
string shellCommandCallbackUserData;
virtual void * getShellCommandOutput_UserData(string cmd);
virtual void ShellCommandOutput_CallbackEvent(string cmd, char *output, void *userdata);
public:
public:
FTPClientThread(int portNumber,string serverUrl,
std::pair<string,string> mapsPath,
std::pair<string,string> tilesetsPath,
std::pair<string,string> techtreesPath,
std::pair<string,string> scenariosPath,
FTPClientCallbackInterface *pCBObject,
string fileArchiveExtension,
string fileArchiveExtractCommand,
string fileArchiveExtractCommandParameters,
int fileArchiveExtractCommandSuccessResult,
string tempFilesPath);
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
FTPClientThread(int portNumber, string serverUrl,
std::pair<string, string> mapsPath,
std::pair<string, string> tilesetsPath,
std::pair<string, string> techtreesPath,
std::pair<string, string> scenariosPath,
FTPClientCallbackInterface *pCBObject,
string fileArchiveExtension,
string fileArchiveExtractCommand,
string fileArchiveExtractCommandParameters,
int fileArchiveExtractCommandSuccessResult,
string tempFilesPath);
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
void addMapToRequests(string mapFilename,string URL="");
void addTilesetToRequests(string tileSetName,string URL="");
void addTechtreeToRequests(string techtreeName,string URL="");
void addScenarioToRequests(string fileName,string URL="");
void addFileToRequests(string fileName,string URL="");
void addTempFileToRequests(string fileName,string URL="");
void addMapToRequests(string mapFilename, string URL = "");
void addTilesetToRequests(string tileSetName, string URL = "");
void addTechtreeToRequests(string techtreeName, string URL = "");
void addScenarioToRequests(string fileName, string URL = "");
void addFileToRequests(string fileName, string URL = "");
void addTempFileToRequests(string fileName, string URL = "");
FTPClientCallbackInterface * getCallBackObject();
void setCallBackObject(FTPClientCallbackInterface *value);
FTPClientCallbackInterface * getCallBackObject();
void setCallBackObject(FTPClientCallbackInterface *value);
Mutex * getProgressMutex() { return &mutexProgressMutex; }
};
Mutex * getProgressMutex() {
return &mutexProgressMutex;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -13,8 +13,8 @@
#define _SHARED_PLATFORMCOMMON_MINIFTPSERVERTHREAD_H_
#ifdef WIN32
#include <winsock2.h>
#include <winsock.h>
#include <winsock2.h>
#include <winsock.h>
#endif
#include "base_thread.h"
@@ -27,47 +27,50 @@
using namespace std;
namespace Shared { namespace PlatformCommon {
namespace Shared {
namespace PlatformCommon {
// =====================================================
// class FTPServerThread
// =====================================================
// =====================================================
// class FTPServerThread
// =====================================================
class FTPServerThread : public BaseThread
{
protected:
std::pair<string,string> mapsPath;
std::pair<string,string> tilesetsPath;
std::pair<string,string> techtreesPath;
string tempFilesPath;
class FTPServerThread : public BaseThread {
protected:
std::pair<string, string> mapsPath;
std::pair<string, string> tilesetsPath;
std::pair<string, string> techtreesPath;
string tempFilesPath;
int portNumber;
int maxPlayers;
static FTPClientValidationInterface *ftpValidationIntf;
int portNumber;
int maxPlayers;
static FTPClientValidationInterface *ftpValidationIntf;
bool internetEnabled;
bool allowInternetTilesetFileTransfers;
bool allowInternetTechtreeFileTransfers;
bool internetEnabled;
bool allowInternetTilesetFileTransfers;
bool allowInternetTechtreeFileTransfers;
public:
public:
FTPServerThread(std::pair<string,string> mapsPath,
std::pair<string,string> tilesetsPath, std::pair<string,string> techtreesPath,
bool internetEnabledFlag,
bool allowInternetTilesetFileTransfers, bool allowInternetTechtreeFileTransfers,
int portNumber,int maxPlayers, FTPClientValidationInterface *ftpValidationIntf,
string tempFilesPath);
~FTPServerThread();
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
FTPServerThread(std::pair<string, string> mapsPath,
std::pair<string, string> tilesetsPath, std::pair<string, string> techtreesPath,
bool internetEnabledFlag,
bool allowInternetTilesetFileTransfers, bool allowInternetTechtreeFileTransfers,
int portNumber, int maxPlayers, FTPClientValidationInterface *ftpValidationIntf,
string tempFilesPath);
~FTPServerThread();
virtual void execute();
virtual void signalQuit();
virtual bool shutdownAndWait();
void setInternetEnabled(bool value, bool forceChange=false);
static void addClientToServerIPAddress(uint32 clientIp,uint32 ServerIp);
static FTPClientValidationInterface * getFtpValidationIntf() { return ftpValidationIntf; }
void setInternetEnabled(bool value, bool forceChange = false);
static void addClientToServerIPAddress(uint32 clientIp, uint32 ServerIp);
static FTPClientValidationInterface * getFtpValidationIntf() {
return ftpValidationIntf;
}
};
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -13,28 +13,28 @@
#define _SHARED_PLATFORM_SOCKET_H_
#ifdef WIN32
#ifdef __MINGW32__
#include <winsock2.h>
#else
#include <winsock2.h>
#include <winsock.h>
#endif
typedef SOCKET PLATFORM_SOCKET;
#if defined(_WIN64)
#define PLATFORM_SOCKET_FORMAT_TYPE MG_I64U_SPECIFIER
#else
#define PLATFORM_SOCKET_FORMAT_TYPE "%d"
#endif
#ifdef __MINGW32__
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <winsock2.h>
#include <winsock.h>
#endif
typedef int PLATFORM_SOCKET;
#define PLATFORM_SOCKET_FORMAT_TYPE "%d"
typedef SOCKET PLATFORM_SOCKET;
#if defined(_WIN64)
#define PLATFORM_SOCKET_FORMAT_TYPE MG_I64U_SPECIFIER
#else
#define PLATFORM_SOCKET_FORMAT_TYPE "%d"
#endif
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
typedef int PLATFORM_SOCKET;
#define PLATFORM_SOCKET_FORMAT_TYPE "%d"
#endif
#include <string>
@@ -53,312 +53,345 @@ using std::string;
using namespace Shared::PlatformCommon;
namespace Shared { namespace Platform {
namespace Shared {
namespace Platform {
#ifdef WIN32
#define PLATFORM_SOCKET_TRY_AGAIN WSAEWOULDBLOCK
#define PLATFORM_SOCKET_INPROGRESS WSAEINPROGRESS
#define PLATFORM_SOCKET_INTERRUPTED WSAEWOULDBLOCK
#define PLATFORM_SOCKET_TRY_AGAIN WSAEWOULDBLOCK
#define PLATFORM_SOCKET_INPROGRESS WSAEINPROGRESS
#define PLATFORM_SOCKET_INTERRUPTED WSAEWOULDBLOCK
#else
#define PLATFORM_SOCKET_TRY_AGAIN EAGAIN
#define PLATFORM_SOCKET_INPROGRESS EINPROGRESS
#define PLATFORM_SOCKET_INTERRUPTED EINTR
#define PLATFORM_SOCKET_TRY_AGAIN EAGAIN
#define PLATFORM_SOCKET_INPROGRESS EINPROGRESS
#define PLATFORM_SOCKET_INTERRUPTED EINTR
#endif
// The callback Interface used by the UPNP discovery process
class FTPClientValidationInterface {
public:
virtual int isValidClientType(uint32 clientIp) = 0;
virtual int isClientAllowedToGetFile(uint32 clientIp, const char *username, const char *filename) = 0;
// The callback Interface used by the UPNP discovery process
class FTPClientValidationInterface {
public:
virtual int isValidClientType(uint32 clientIp) = 0;
virtual int isClientAllowedToGetFile(uint32 clientIp, const char *username, const char *filename) = 0;
virtual ~FTPClientValidationInterface() {}
};
virtual ~FTPClientValidationInterface() {
}
};
// The callback Interface used by the UPNP discovery process
class UPNPInitInterface {
public:
virtual void UPNPInitStatus(bool result) = 0;
// The callback Interface used by the UPNP discovery process
class UPNPInitInterface {
public:
virtual void UPNPInitStatus(bool result) = 0;
virtual ~UPNPInitInterface() {}
};
virtual ~UPNPInitInterface() {
}
};
//
// This interface describes the methods a callback object must implement
// when signaled with detected servers
//
class DiscoveredServersInterface {
public:
virtual void DiscoveredServers(std::vector<string> serverList) = 0;
virtual ~DiscoveredServersInterface() {}
};
//
// This interface describes the methods a callback object must implement
// when signaled with detected servers
//
class DiscoveredServersInterface {
public:
virtual void DiscoveredServers(std::vector<string> serverList) = 0;
virtual ~DiscoveredServersInterface() {
}
};
// =====================================================
// class IP
// =====================================================
class Ip {
private:
unsigned char bytes[4];
// =====================================================
// class IP
// =====================================================
class Ip {
private:
unsigned char bytes[4];
public:
Ip();
Ip(unsigned char byte0, unsigned char byte1, unsigned char byte2, unsigned char byte3);
Ip(const string& ipString);
static void Inet_NtoA(uint32 addr, char * ipbuf);
public:
Ip();
Ip(unsigned char byte0, unsigned char byte1, unsigned char byte2, unsigned char byte3);
Ip(const string& ipString);
static void Inet_NtoA(uint32 addr, char * ipbuf);
unsigned char getByte(int byteIndex) {return bytes[byteIndex];}
string getString() const;
};
unsigned char getByte(int byteIndex) {
return bytes[byteIndex];
}
string getString() const;
};
// =====================================================
// class Socket
// =====================================================
// =====================================================
// class Socket
// =====================================================
#ifdef WIN32
class SocketManager{
public:
SocketManager();
~SocketManager();
};
class SocketManager {
public:
SocketManager();
~SocketManager();
};
#endif
class Socket {
class Socket {
protected:
//#ifdef WIN32
//static SocketManager wsaManager;
//#endif
PLATFORM_SOCKET sock;
time_t lastDebugEvent;
static int broadcast_portno;
std::string ipAddress;
std::string connectedIpAddress;
protected:
//#ifdef WIN32
//static SocketManager wsaManager;
//#endif
PLATFORM_SOCKET sock;
time_t lastDebugEvent;
static int broadcast_portno;
std::string ipAddress;
std::string connectedIpAddress;
//SimpleTaskThread *pingThread;
std::map<string,double> pingCache;
time_t lastThreadedPing;
//Mutex pingThreadAccessor;
//SimpleTaskThread *pingThread;
std::map<string, double> pingCache;
time_t lastThreadedPing;
//Mutex pingThreadAccessor;
Mutex *dataSynchAccessorRead;
Mutex *dataSynchAccessorWrite;
Mutex *dataSynchAccessorRead;
Mutex *dataSynchAccessorWrite;
Mutex *inSocketDestructorSynchAccessor;
bool inSocketDestructor;
Mutex *inSocketDestructorSynchAccessor;
bool inSocketDestructor;
bool isSocketBlocking;
time_t lastSocketError;
bool isSocketBlocking;
time_t lastSocketError;
static string host_name;
static std::vector<string> intfTypes;
static string host_name;
static std::vector<string> intfTypes;
public:
Socket(PLATFORM_SOCKET sock);
Socket();
virtual ~Socket();
public:
Socket(PLATFORM_SOCKET sock);
Socket();
virtual ~Socket();
static int getLastSocketError();
static const char * getLastSocketErrorText(int *errNumber=NULL);
static string getLastSocketErrorFormattedText(int *errNumber=NULL);
static int getLastSocketError();
static const char * getLastSocketErrorText(int *errNumber = NULL);
static string getLastSocketErrorFormattedText(int *errNumber = NULL);
static void setIntfTypes(std::vector<string> intfTypes) { Socket::intfTypes = intfTypes; }
static bool disableNagle;
static int DEFAULT_SOCKET_SENDBUF_SIZE;
static int DEFAULT_SOCKET_RECVBUF_SIZE;
static void setIntfTypes(std::vector<string> intfTypes) {
Socket::intfTypes = intfTypes;
}
static bool disableNagle;
static int DEFAULT_SOCKET_SENDBUF_SIZE;
static int DEFAULT_SOCKET_RECVBUF_SIZE;
static int getBroadCastPort() { return broadcast_portno; }
static void setBroadCastPort(int value) { broadcast_portno = value; }
static std::vector<std::string> getLocalIPAddressList();
static int getBroadCastPort() {
return broadcast_portno;
}
static void setBroadCastPort(int value) {
broadcast_portno = value;
}
static std::vector<std::string> getLocalIPAddressList();
// Int lookup is socket fd while bool result is whether or not that socket was signalled for reading
static bool hasDataToRead(std::map<PLATFORM_SOCKET,bool> &socketTriggeredList);
static bool hasDataToRead(PLATFORM_SOCKET socket);
bool hasDataToRead();
// Int lookup is socket fd while bool result is whether or not that socket was signalled for reading
static bool hasDataToRead(std::map<PLATFORM_SOCKET, bool> &socketTriggeredList);
static bool hasDataToRead(PLATFORM_SOCKET socket);
bool hasDataToRead();
static bool hasDataToReadWithWait(PLATFORM_SOCKET socket,int waitMicroseconds);
bool hasDataToReadWithWait(int waitMicroseconds);
static bool hasDataToReadWithWait(PLATFORM_SOCKET socket, int waitMicroseconds);
bool hasDataToReadWithWait(int waitMicroseconds);
virtual void disconnectSocket();
virtual void disconnectSocket();
PLATFORM_SOCKET getSocketId() const { return sock; }
PLATFORM_SOCKET getSocketId() const {
return sock;
}
int getDataToRead(bool wantImmediateReply=false);
int send(const void *data, int dataSize);
int receive(void *data, int dataSize, bool tryReceiveUntilDataSizeMet);
int peek(void *data, int dataSize, bool mustGetData=true,int *pLastSocketError=NULL);
int getDataToRead(bool wantImmediateReply = false);
int send(const void *data, int dataSize);
int receive(void *data, int dataSize, bool tryReceiveUntilDataSizeMet);
int peek(void *data, int dataSize, bool mustGetData = true, int *pLastSocketError = NULL);
void setBlock(bool block);
static void setBlock(bool block, PLATFORM_SOCKET socket);
bool getBlock();
void setBlock(bool block);
static void setBlock(bool block, PLATFORM_SOCKET socket);
bool getBlock();
bool isReadable(bool lockMutex=false);
bool isWritable(struct timeval *timeVal=NULL,bool lockMutex=false);
bool isConnected();
bool isReadable(bool lockMutex = false);
bool isWritable(struct timeval *timeVal = NULL, bool lockMutex = false);
bool isConnected();
static string getHostName();
static string getIp();
bool isSocketValid() const;
static bool isSocketValid(const PLATFORM_SOCKET *validateSocket);
static string getHostName();
static string getIp();
bool isSocketValid() const;
static bool isSocketValid(const PLATFORM_SOCKET *validateSocket);
static double getAveragePingMS(std::string host, int pingCount=5);
float getThreadedPingMS(std::string host);
static double getAveragePingMS(std::string host, int pingCount = 5);
float getThreadedPingMS(std::string host);
virtual std::string getIpAddress();
virtual void setIpAddress(std::string value) { ipAddress = value; }
virtual std::string getIpAddress();
virtual void setIpAddress(std::string value) {
ipAddress = value;
}
uint32 getConnectedIPAddress(string IP="");
uint32 getConnectedIPAddress(string IP = "");
protected:
static void throwException(string str);
static void getLocalIPAddressListForPlatform(std::vector<std::string> &ipList);
};
protected:
static void throwException(string str);
static void getLocalIPAddressListForPlatform(std::vector<std::string> &ipList);
};
class SafeSocketBlockToggleWrapper {
protected:
Socket *socket;
bool originallyBlocked;
bool newBlocked;
public:
SafeSocketBlockToggleWrapper(Socket *socket, bool toggle);
~SafeSocketBlockToggleWrapper();
void Restore();
};
class SafeSocketBlockToggleWrapper {
protected:
Socket *socket;
bool originallyBlocked;
bool newBlocked;
public:
SafeSocketBlockToggleWrapper(Socket *socket, bool toggle);
~SafeSocketBlockToggleWrapper();
void Restore();
};
class BroadCastClientSocketThread : public BaseThread
{
private:
DiscoveredServersInterface *discoveredServersCB;
class BroadCastClientSocketThread : public BaseThread {
private:
DiscoveredServersInterface *discoveredServersCB;
public:
BroadCastClientSocketThread(DiscoveredServersInterface *cb);
virtual void execute();
};
public:
BroadCastClientSocketThread(DiscoveredServersInterface *cb);
virtual void execute();
};
// =====================================================
// class ClientSocket
// =====================================================
class ClientSocket: public Socket {
public:
ClientSocket();
virtual ~ClientSocket();
// =====================================================
// class ClientSocket
// =====================================================
class ClientSocket : public Socket {
public:
ClientSocket();
virtual ~ClientSocket();
void connect(const Ip &ip, int port);
static void discoverServers(DiscoveredServersInterface *cb);
void connect(const Ip &ip, int port);
static void discoverServers(DiscoveredServersInterface *cb);
static void stopBroadCastClientThread();
static void stopBroadCastClientThread();
protected:
protected:
static BroadCastClientSocketThread *broadCastClientThread;
static void startBroadCastClientThread(DiscoveredServersInterface *cb);
};
static BroadCastClientSocketThread *broadCastClientThread;
static void startBroadCastClientThread(DiscoveredServersInterface *cb);
};
class BroadCastSocketThread : public BaseThread
{
private:
Mutex *mutexPauseBroadcast;
bool pauseBroadcast;
int boundPort;
class BroadCastSocketThread : public BaseThread {
private:
Mutex *mutexPauseBroadcast;
bool pauseBroadcast;
int boundPort;
public:
BroadCastSocketThread(int boundPort);
virtual ~BroadCastSocketThread();
virtual void execute();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false);
public:
BroadCastSocketThread(int boundPort);
virtual ~BroadCastSocketThread();
virtual void execute();
virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false);
bool getPauseBroadcast();
void setPauseBroadcast(bool value);
};
bool getPauseBroadcast();
void setPauseBroadcast(bool value);
};
// =====================================================
// class ServerSocket
// =====================================================
class ServerSocket: public Socket, public UPNPInitInterface {
protected:
// =====================================================
// class ServerSocket
// =====================================================
class ServerSocket : public Socket, public UPNPInitInterface {
protected:
bool portBound;
int boundPort;
string bindSpecificAddress;
bool portBound;
int boundPort;
string bindSpecificAddress;
static int externalPort;
static int ftpServerPort;
static int externalPort;
static int ftpServerPort;
static int maxPlayerCount;
static int maxPlayerCount;
virtual void UPNPInitStatus(bool result);
BroadCastSocketThread *broadCastThread;
void startBroadCastThread();
void resumeBroadcast();
bool isBroadCastThreadRunning();
vector<string> blockIPList;
virtual void UPNPInitStatus(bool result);
BroadCastSocketThread *broadCastThread;
void startBroadCastThread();
void resumeBroadcast();
bool isBroadCastThreadRunning();
vector<string> blockIPList;
bool basicMode;
bool basicMode;
public:
ServerSocket(bool basicMode = false);
virtual ~ServerSocket();
void bind(int port);
void listen(int connectionQueueSize= SOMAXCONN);
Socket *accept(bool errorOnFail=true);
void stopBroadCastThread();
void pauseBroadcast();
public:
ServerSocket(bool basicMode = false);
virtual ~ServerSocket();
void bind(int port);
void listen(int connectionQueueSize = SOMAXCONN);
Socket *accept(bool errorOnFail = true);
void stopBroadCastThread();
void pauseBroadcast();
void addIPAddressToBlockedList(string value);
bool isIPAddressBlocked(string value) const;
void removeBlockedIPAddress(string value);
void clearBlockedIPAddress();
bool hasBlockedIPAddresses() const;
void addIPAddressToBlockedList(string value);
bool isIPAddressBlocked(string value) const;
void removeBlockedIPAddress(string value);
void clearBlockedIPAddress();
bool hasBlockedIPAddresses() const;
void setBindPort(int port) { boundPort = port; }
int getBindPort() const { return boundPort; }
bool isPortBound() const { return portBound; }
void setBindPort(int port) {
boundPort = port;
}
int getBindPort() const {
return boundPort;
}
bool isPortBound() const {
return portBound;
}
void setBindSpecificAddress(string value) { bindSpecificAddress = value;}
void setBindSpecificAddress(string value) {
bindSpecificAddress = value;
}
static void setExternalPort(int port) { externalPort = port; }
static int getExternalPort() { return externalPort; }
static void setExternalPort(int port) {
externalPort = port;
}
static int getExternalPort() {
return externalPort;
}
static void setFTPServerPort(int port) { ftpServerPort = port; }
static int getFTPServerPort() { return ftpServerPort; }
static void setFTPServerPort(int port) {
ftpServerPort = port;
}
static int getFTPServerPort() {
return ftpServerPort;
}
virtual void disconnectSocket();
virtual void disconnectSocket();
void NETdiscoverUPnPDevices();
void NETdiscoverUPnPDevices();
static void setMaxPlayerCount(int value) { maxPlayerCount=value; }
static void setMaxPlayerCount(int value) {
maxPlayerCount = value;
}
static Mutex mutexUpnpdiscoverThread;
static SDL_Thread *upnpdiscoverThread;
static bool cancelUpnpdiscoverThread;
};
static Mutex mutexUpnpdiscoverThread;
static SDL_Thread *upnpdiscoverThread;
static bool cancelUpnpdiscoverThread;
};
// =====================================================
// class UPNP_Tools
// =====================================================
class UPNP_Tools {
// =====================================================
// class UPNP_Tools
// =====================================================
class UPNP_Tools {
public:
public:
static bool isUPNP;
static bool enabledUPNP;
static Mutex mutexUPNP;
static bool isUPNP;
static bool enabledUPNP;
static Mutex mutexUPNP;
static int upnp_init(void *param);
static int upnp_init(void *param);
static bool upnp_add_redirect(int ports[2],bool mutexLock=true);
static void upnp_rem_redirect(int ext_port);
static bool upnp_add_redirect(int ports[2], bool mutexLock = true);
static void upnp_rem_redirect(int ext_port);
static void NETaddRedirects(std::vector<int> UPNPPortForwardList, bool mutexLock=true);
static void NETremRedirects(int ext_port);
static void NETaddRedirects(std::vector<int> UPNPPortForwardList, bool mutexLock = true);
static void NETremRedirects(int ext_port);
static void AddUPNPPortForward(int internalPort, int externalPort);
static void RemoveUPNPPortForward(int internalPort, int externalPort);
};
static void AddUPNPPortForward(int internalPort, int externalPort);
static void RemoveUPNPPortForward(int internalPort, int externalPort);
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -36,61 +36,67 @@ using std::string;
using Shared::Graphics::FontMetrics;
namespace Shared{ namespace Platform{
namespace Shared {
namespace Platform {
// =====================================================
// class PlatformContextGl
// =====================================================
// =====================================================
// class PlatformContextGl
// =====================================================
class PlatformContextGl {
protected:
SDL_Surface *icon;
SDL_Window *window;
SDL_GLContext glcontext;
class PlatformContextGl {
protected:
SDL_Surface *icon;
SDL_Window *window;
SDL_GLContext glcontext;
public:
// Example values:
// DEFAULT_CHARSET (English) = 1
// GB2312_CHARSET (Chinese) = 134
#ifdef WIN32
static DWORD charSet;
#else
static int charSet;
#endif
public:
// Example values:
// DEFAULT_CHARSET (English) = 1
// GB2312_CHARSET (Chinese) = 134
#ifdef WIN32
static DWORD charSet;
#else
static int charSet;
#endif
public:
PlatformContextGl();
virtual ~PlatformContextGl();
public:
PlatformContextGl();
virtual ~PlatformContextGl();
virtual void init(int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
virtual void end();
virtual void init(int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
virtual void end();
virtual void makeCurrent();
virtual void swapBuffers();
virtual void makeCurrent();
virtual void swapBuffers();
SDL_Window * getScreenWindow() { return window; }
SDL_Surface * getScreenSurface();
SDL_Window * getScreenWindow() {
return window;
}
SDL_Surface * getScreenSurface();
DeviceContextHandle getHandle() const { return 0; }
};
DeviceContextHandle getHandle() const {
return 0;
}
};
// =====================================================
// Global Fcs
// =====================================================
// =====================================================
// Global Fcs
// =====================================================
#if defined(__APPLE__)
void createGlFontBitmaps(uint32 &base, const string &type, int size, int width, int charCount, FontMetrics &metrics);
void createGlFontOutlines(uint32 &base, const string &type, int width, float depth, int charCount, FontMetrics &metrics);
void createGlFontBitmaps(uint32 &base, const string &type, int size, int width, int charCount, FontMetrics &metrics);
void createGlFontOutlines(uint32 &base, const string &type, int width, float depth, int charCount, FontMetrics &metrics);
#else
void createGlFontBitmaps(uint32 &base, const string &type, int size, int width, int charCount, FontMetrics &metrics);
void createGlFontOutlines(uint32 &base, const string &type, int width, float depth, int charCount, FontMetrics &metrics);
void createGlFontBitmaps(uint32 &base, const string &type, int size, int width, int charCount, FontMetrics &metrics);
void createGlFontOutlines(uint32 &base, const string &type, int width, float depth, int charCount, FontMetrics &metrics);
#endif
const char *getPlatformExtensions(const PlatformContextGl *pcgl);
void* getGlProcAddress(const char *procName);
const char *getPlatformExtensions(const PlatformContextGl *pcgl);
void* getGlProcAddress(const char *procName);
}}//end namespace
}
}//end namespace
#endif

View File

@@ -17,9 +17,9 @@
#include "leak_dumper.h"
#ifndef WIN32
#define stricmp strcasecmp
#define strnicmp strncasecmp
#define _strnicmp strncasecmp
#define stricmp strcasecmp
#define strnicmp strncasecmp
#define _strnicmp strncasecmp
#endif
const char *GAME_ARGS[] = {
@@ -197,22 +197,22 @@ enum GAME_ARG_TYPE {
void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
// MAX WIDTH FOR MAN PAGE
// "================================================================================"
if(foundInvalidArgs == true) {
printf("\n");
if (foundInvalidArgs == true) {
printf("\n");
}
printf("\n%s, usage",extractFileFromDirectoryPath(argv0).c_str());
printf("\n%s, usage", extractFileFromDirectoryPath(argv0).c_str());
printf("\n\nCommandline Parameter: Description:");
printf("\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
printf("\n\n%s \t\tDisplays this help text.",GAME_ARGS[GAME_ARG_HELP]);
printf("\n\n%s \t\tDisplays this help text.", GAME_ARGS[GAME_ARG_HELP]);
printf("\n\n%s \tAutomatically starts a game with the last game",GAME_ARGS[GAME_ARG_AUTOSTART_LASTGAME]);
printf("\n\n%s \tAutomatically starts a game with the last game", GAME_ARGS[GAME_ARG_AUTOSTART_LASTGAME]);
printf("\n\n \tsettings you played.");
printf("\n\n%s=x \tLoads the last saved game.",GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME]);
printf("\n\n%s=x \tLoads the last saved game.", GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME]);
printf("\n\n \tWhere x is an optional name of the saved game file to load.");
printf("\n\n \tIf x is not specified we load the last game that was saved.");
printf("\n\n%s=x,y,z \tRun in auto test mode.",GAME_ARGS[GAME_ARG_AUTO_TEST]);
printf("\n\n%s=x,y,z \tRun in auto test mode.", GAME_ARGS[GAME_ARG_AUTO_TEST]);
printf("\n\n \tWhere x is an optional maximum # seconds to play.");
printf("\n\n \tIf x is not specified the default is 1200 seconds (20 minutes).");
printf("\n\n \tWhere y is an optional game settings file to play.");
@@ -222,18 +222,18 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \tafter the game is finished or the time runs out. If z is");
printf("\n\n \tnot specified (or is empty) then auto test continues to cycle.");
printf("\n\n%s=x:y \t\tAuto connect to host server at IP or hostname x using",GAME_ARGS[GAME_ARG_CONNECT]);
printf("\n\n \t port y. Shortcut version of using %s and %s.",GAME_ARGS[GAME_ARG_CLIENT],GAME_ARGS[GAME_ARG_USE_PORTS]);
printf("\n\n%s=x:y \t\tAuto connect to host server at IP or hostname x using", GAME_ARGS[GAME_ARG_CONNECT]);
printf("\n\n \t port y. Shortcut version of using %s and %s.", GAME_ARGS[GAME_ARG_CLIENT], GAME_ARGS[GAME_ARG_USE_PORTS]);
printf("\n\n \t*NOTE: to automatically connect to the first LAN host you may");
printf("\n\n \t use: %s=auto-connect",GAME_ARGS[GAME_ARG_CONNECT]);
printf("\n\n \t use: %s=auto-connect", GAME_ARGS[GAME_ARG_CONNECT]);
printf("\n\n%s=x \tAuto connect to host server at IP or hostname x.",GAME_ARGS[GAME_ARG_CLIENT]);
printf("\n\n%s=x \tAuto connect to host server at IP or hostname x.", GAME_ARGS[GAME_ARG_CLIENT]);
printf("\n\n \t*NOTE: to automatically connect to the first LAN host you may");
printf("\n\n \t use: %s=auto-connect",GAME_ARGS[GAME_ARG_CLIENT]);
printf("\n\n \t use: %s=auto-connect", GAME_ARGS[GAME_ARG_CLIENT]);
printf("\n\n%s \t\tAuto create a host server.",GAME_ARGS[GAME_ARG_SERVER]);
printf("\n\n%s \t\tAuto create a host server.", GAME_ARGS[GAME_ARG_SERVER]);
printf("\n\n%s=x,x ",GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]);
printf("\n\n%s=x,x ", GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]);
printf("\n\n \tRun as a headless server.");
printf("\n\n \tWhere x is an optional comma delimited command list of one or");
printf("\n\n \t more of the following: ");
@@ -244,10 +244,10 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \t'lan' - which does not broadcast the hosting server to the");
printf("\n\n \t masterserver (for local LAN games).");
printf("\n\n%s ",GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS]);
printf("\n\n%s ", GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS]);
printf("\n\n \tCheck the current status of a headless server.");
printf("\n\n%s=x,y,z \tForce hosted games to listen internally on port",GAME_ARGS[GAME_ARG_USE_PORTS]);
printf("\n\n%s=x,y,z \tForce hosted games to listen internally on port", GAME_ARGS[GAME_ARG_USE_PORTS]);
printf("\n\n \t x, externally on port y and for game status on port z.");
printf("\n\n \tWhere x is the internal port # on the local machine to");
printf("\n\n \t listen for connects.");
@@ -258,23 +258,23 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \t*NOTE: If enabled the FTP Server port #'s will be set");
printf("\n\n \t to x+1 to x+9.");
printf("\n\n%s=x \tSet server title.",GAME_ARGS[GAME_ARG_SERVER_TITLE]);
printf("\n\n%s=x \tSet server title.", GAME_ARGS[GAME_ARG_SERVER_TITLE]);
printf("\n\n%s=x \tAuto load a scenario by scenario name.",GAME_ARGS[GAME_ARG_LOADSCENARIO]);
printf("\n\n%s=x \t\tAuto load a mod by mod pathname.",GAME_ARGS[GAME_ARG_MOD]);
printf("\n\n%s=x \tAuto load a scenario by scenario name.", GAME_ARGS[GAME_ARG_LOADSCENARIO]);
printf("\n\n%s=x \t\tAuto load a mod by mod pathname.", GAME_ARGS[GAME_ARG_MOD]);
// "================================================================================"
printf("\n\n%s=Map,Tileset ",GAME_ARGS[GAME_ARG_PREVIEW_MAP]);
printf("\n\n%s=Map,Tileset ", GAME_ARGS[GAME_ARG_PREVIEW_MAP]);
printf("\n\n \tAuto Preview a map by map name. (tileset is optional)");
printf("\n\n%s \t\tDisplays the version string of this program.",GAME_ARGS[GAME_ARG_VERSION]);
printf("\n\n%s \t\tDisplays your video driver's OpenGL info.",GAME_ARGS[GAME_ARG_OPENGL_INFO]);
printf("\n\n%s \t\tDisplays your SDL version information.",GAME_ARGS[GAME_ARG_SDL_INFO]);
printf("\n\n%s \t\tDisplays your LUA version information.",GAME_ARGS[GAME_ARG_LUA_INFO]);
printf("\n\n%s \t\tDisplays LUA debug information.",GAME_ARGS[GAME_ARG_LUA_DEBUG]);
printf("\n\n%s \t\tDisplays your CURL version information.",GAME_ARGS[GAME_ARG_CURL_INFO]);
printf("\n\n%s \t\tDisplays your XERCES version information.",GAME_ARGS[GAME_ARG_XERCES_INFO]);
printf("\n\n%s \t\tDisplays the version string of this program.", GAME_ARGS[GAME_ARG_VERSION]);
printf("\n\n%s \t\tDisplays your video driver's OpenGL info.", GAME_ARGS[GAME_ARG_OPENGL_INFO]);
printf("\n\n%s \t\tDisplays your SDL version information.", GAME_ARGS[GAME_ARG_SDL_INFO]);
printf("\n\n%s \t\tDisplays your LUA version information.", GAME_ARGS[GAME_ARG_LUA_INFO]);
printf("\n\n%s \t\tDisplays LUA debug information.", GAME_ARGS[GAME_ARG_LUA_DEBUG]);
printf("\n\n%s \t\tDisplays your CURL version information.", GAME_ARGS[GAME_ARG_CURL_INFO]);
printf("\n\n%s \t\tDisplays your XERCES version information.", GAME_ARGS[GAME_ARG_XERCES_INFO]);
printf("\n\n%s=x=purgeunused=purgeduplicates=gitdelete=hideduplicates ",GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n%s=x=purgeunused=purgeduplicates=gitdelete=hideduplicates ", GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n \tDisplay a report detailing any known problems related to");
printf("\n\n \t your selected techtrees game data.");
printf("\n\n \tWhere x is a comma-delimited list of techtrees to validate.");
@@ -291,9 +291,9 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \t*NOTE: This only applies when files are purged due to the");
printf("\n\n \t above flags being set.");
printf("\n\n \texample:");
printf("\n\n \t%s %s=megapack,vbros_pack_5",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n \t%s %s=megapack,vbros_pack_5", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n%s=x=purgeunused=purgeduplicates=hideduplicates ",GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]);
printf("\n\n%s=x=purgeunused=purgeduplicates=hideduplicates ", GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]);
printf("\n\n \tDisplay a report detailing any known problems related to");
printf("\n\n \t your selected factions game data.");
printf("\n\n \tWhere x is a comma-delimited list of factions to validate.");
@@ -305,72 +305,72 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \tWhere 'hideduplicates' is an optional parameter telling the");
printf("\n\n \t validation to NOT SHOW duplicate files in the techtree.");
printf("\n\n \t*NOTE: leaving the list empty is the same as running:");
printf("\n\n \t %s",GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n \texample: %s %s=tech,egypt",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]);
printf("\n\n \t %s", GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]);
printf("\n\n \texample: %s %s=tech,egypt", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]);
printf("\n\n%s=x=purgeunused=gitdelete ",GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]);
printf("\n\n%s=x=purgeunused=gitdelete ", GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]);
printf("\n\n \tDisplay a report detailing any known problems related to");
printf("\n\n \t your selected scenario game data.");
printf("\n\n \tWhere x is a single scenario to validate.");
printf("\n\n \tWhere 'purgeunused' is an optional parameter telling the");
printf("\n\n \t validation to delete extra files in the scenario that");
printf("\n\n \t are not used.");
printf("\n\n \texample: %s %s=stranded",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]);
printf("\n\n \texample: %s %s=stranded", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]);
printf("\n\n%s=x=purgeunused=gitdelete ",GAME_ARGS[GAME_ARG_VALIDATE_TILESET]);
printf("\n\n%s=x=purgeunused=gitdelete ", GAME_ARGS[GAME_ARG_VALIDATE_TILESET]);
printf("\n\n \tDisplay a report detailing any known problems related to");
printf("\n\n \t your selected tileset game data.");
printf("\n\n \tWhere x is a single tileset to validate.");
printf("\n\n \tWhere 'purgeunused' is an optional parameter telling the");
printf("\n\n \t validation to delete extra files in the tileset that");
printf("\n\n \t are not used.");
printf("\n\n \texample: %s %s=desert2",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_VALIDATE_TILESET]);
printf("\n\n \texample: %s %s=desert2", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_VALIDATE_TILESET]);
printf("\n\n%s=x ",GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]);
printf("\n\n%s=x ", GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]);
printf("\n\n \tProduces a default lng file for the specified techtree to");
printf("\n\n \t prepare for translation into other languages.");
printf("\n\n \tWhere x is a techtree name.");
printf("\n\n%s=x \t\tDisplay a list of game content: maps.",GAME_ARGS[GAME_ARG_LIST_MAPS]);
printf("\n\n%s=x \t\tDisplay a list of game content: maps.", GAME_ARGS[GAME_ARG_LIST_MAPS]);
printf("\n\n \tWhere x is an optional name filter.");
printf("\n\n \texample: %s %s=island*",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LIST_MAPS]);
printf("\n\n \texample: %s %s=island*", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LIST_MAPS]);
printf("\n\n%s=showfactions ",GAME_ARGS[GAME_ARG_LIST_TECHTRESS]);
printf("\n\n%s=showfactions ", GAME_ARGS[GAME_ARG_LIST_TECHTRESS]);
printf("\n\n \tDisplay a list of game content: techtrees.");
printf("\n\n \tWhere 'showfactions' is an optional parameter to display");
printf("\n\n \t factions in each techtree.");
printf("\n\n \texample: %s %s=showfactions",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LIST_TECHTRESS]);
printf("\n\n \texample: %s %s=showfactions", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LIST_TECHTRESS]);
printf("\n\n%s=x \tDisplay a list of game content: scenarios.",GAME_ARGS[GAME_ARG_LIST_SCENARIOS]);
printf("\n\n%s=x \tDisplay a list of game content: scenarios.", GAME_ARGS[GAME_ARG_LIST_SCENARIOS]);
printf("\n\n \tWhere x is an optional name filter.");
printf("\n\n \texample: %s %s=beginner*",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LIST_SCENARIOS]);
printf("\n\n \texample: %s %s=beginner*", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LIST_SCENARIOS]);
printf("\n\n%s=x \tDisplay a list of game content: tilesets.",GAME_ARGS[GAME_ARG_LIST_TILESETS]);
printf("\n\n%s=x \tDisplay a list of game content: tilesets.", GAME_ARGS[GAME_ARG_LIST_TILESETS]);
printf("\n\n \tWhere x is an optional name filter.");
printf("\n\n \texample: %s %s=f*",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LIST_TILESETS]);
printf("\n\n \texample: %s %s=f*", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LIST_TILESETS]);
printf("\n\n%s=x \tDisplay a list of game content: tutorials.",GAME_ARGS[GAME_ARG_LIST_TUTORIALS]);
printf("\n\n%s=x \tDisplay a list of game content: tutorials.", GAME_ARGS[GAME_ARG_LIST_TUTORIALS]);
printf("\n\n \tWhere x is an optional name filter.");
printf("\n\n \texample: %s %s=*",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LIST_TUTORIALS]);
printf("\n\n \texample: %s %s=*", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LIST_TUTORIALS]);
// "================================================================================"
printf("\n\n%s=x \t\tSets the game data path to x.",GAME_ARGS[GAME_ARG_DATA_PATH]);
printf("\n\n%s=x \t\tSets the game data path to x.", GAME_ARGS[GAME_ARG_DATA_PATH]);
printf("\n\n \texample:");
printf("\n\n \t%s %s=/usr/local/game_data/",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_DATA_PATH]);
printf("\n\n%s=x \t\tSets the game ini path to x.",GAME_ARGS[GAME_ARG_INI_PATH]);
printf("\n\n \texample: %s %s=~/game_config/",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_INI_PATH]);
printf("\n\n%s=x \t\tSets the game logs path to x.",GAME_ARGS[GAME_ARG_LOG_PATH]);
printf("\n\n \texample: %s %s=~/game_logs/",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_LOG_PATH]);
printf("\n\n%s=x \t\tSets the game fonts path to x.",GAME_ARGS[GAME_ARG_FONT_PATH]);
printf("\n\n \texample: %s %s=~/myfonts/",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_FONT_PATH]);
printf("\n\n \t%s %s=/usr/local/game_data/", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_DATA_PATH]);
printf("\n\n%s=x \t\tSets the game ini path to x.", GAME_ARGS[GAME_ARG_INI_PATH]);
printf("\n\n \texample: %s %s=~/game_config/", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_INI_PATH]);
printf("\n\n%s=x \t\tSets the game logs path to x.", GAME_ARGS[GAME_ARG_LOG_PATH]);
printf("\n\n \texample: %s %s=~/game_logs/", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_LOG_PATH]);
printf("\n\n%s=x \t\tSets the game fonts path to x.", GAME_ARGS[GAME_ARG_FONT_PATH]);
printf("\n\n \texample: %s %s=~/myfonts/", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_FONT_PATH]);
printf("\n\n%s=x \tDisplay merged ini settings information.",GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]);
printf("\n\n%s=x \tDisplay merged ini settings information.", GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]);
printf("\n\n \tWhere x is an optional property name to filter (default");
printf("\n\n \t shows all).");
printf("\n\n \texample:");
printf("\n\n \t%s %s=DebugMode",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]);
printf("\n\n \t%s %s=DebugMode", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]);
printf("\n\n%s=x=textureformat=keepsmallest ",GAME_ARGS[GAME_ARG_CONVERT_MODELS]);
printf("\n\n%s=x=textureformat=keepsmallest ", GAME_ARGS[GAME_ARG_CONVERT_MODELS]);
printf("\n\n \tConvert a model file or folder to the current g3d version");
printf("\n\n \t format.");
printf("\n\n \tWhere x is a filename or folder containing the g3d model(s).");
@@ -380,116 +380,116 @@ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
printf("\n\n \t the original texture if its filesize is smaller than the");
printf("\n\n \t converted format.");
printf("\n\n \texample:");
printf("\n\n \t%s %s=techs/megapack/factions/tech/",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_CONVERT_MODELS]);
printf("\n\n \t%s %s=techs/megapack/factions/tech/", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_CONVERT_MODELS]);
printf("\n\n \tunits/castle/models/castle.g3d=png=keepsmallest");
printf("\n\n%s=x \tForce the language to be the language specified",GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n%s=x \tForce the language to be the language specified", GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n \t by x. Where x is a language filename or ISO639-1 code.");
printf("\n\n \texample: %s %s=english",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n \texample: %s %s=en",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n \texample: %s %s=english", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n \texample: %s %s=en", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_LANGUAGE]);
printf("\n\n%s=x \tShow the calculated CRC for the map named x.",GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the map named x.", GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]);
printf("\n\n \tWhere x is a map name.");
printf("\n\n \texample: %s %s=four_rivers",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]);
printf("\n\n \texample: %s %s=four_rivers", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the tileset named x.",GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the tileset named x.", GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]);
printf("\n\n \tWhere x is a tileset name.");
printf("\n\n \texample: %s %s=forest",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]);
printf("\n\n \texample: %s %s=forest", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the techtree named x.",GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the techtree named x.", GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]);
printf("\n\n \tWhere x is a techtree name.");
printf("\n\n \texample: %s %s=megapack",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]);
printf("\n\n \texample: %s %s=megapack", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the scenario named x.",GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]);
printf("\n\n%s=x \tShow the calculated CRC for the scenario named x.", GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]);
printf("\n\n \tWhere x is a scenario name.");
printf("\n\n \texample: %s %s=storming",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]);
printf("\n\n \texample: %s %s=storming", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]);
// "================================================================================"
printf("\n\n%s=x=y \tShow the calculated CRC for files in the path",GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]);
printf("\n\n%s=x=y \tShow the calculated CRC for files in the path", GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]);
printf("\n\n \t located in x using file filter y.");
printf("\n\n \tWhere x is a path name and y is file(s) filter.");
printf("\n\n \texample: %s %s=techs/=megapack.7z",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]);
printf("\n\n \texample: %s %s=techs/=megapack.7z", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]);
printf("\n\n%s \tDisables stack backtrace on errors.",GAME_ARGS[GAME_ARG_DISABLE_BACKTRACE]);
printf("\n\n%s \tDisables stack backtrace on errors.", GAME_ARGS[GAME_ARG_DISABLE_BACKTRACE]);
printf("\n\n%s ",GAME_ARGS[GAME_ARG_DISABLE_SIGSEGV_HANDLER]);
printf("\n\n%s ", GAME_ARGS[GAME_ARG_DISABLE_SIGSEGV_HANDLER]);
printf("\n\n \tDisables the sigsegv error handler.");
printf("\n\n%s \t\tDisables trying to use Vertex Buffer Objects.",GAME_ARGS[GAME_ARG_DISABLE_VBO]);
printf("\n\n%s ",GAME_ARGS[GAME_ARG_DISABLE_VERTEX_INTERPOLATION]);
printf("\n\n%s \t\tDisables trying to use Vertex Buffer Objects.", GAME_ARGS[GAME_ARG_DISABLE_VBO]);
printf("\n\n%s ", GAME_ARGS[GAME_ARG_DISABLE_VERTEX_INTERPOLATION]);
printf("\n\n \tDisables interpolating animations to make them smoother.");
printf("\n\n%s \tDisables the sound system.",GAME_ARGS[GAME_ARG_DISABLE_SOUND]);
printf("\n\n%s \tDisables the sound system.", GAME_ARGS[GAME_ARG_DISABLE_SOUND]);
printf("\n\n%s \tEnables using the legacy font system.",GAME_ARGS[GAME_ARG_ENABLE_LEGACYFONTS]);
printf("\n\n%s \tEnables using the legacy font system.", GAME_ARGS[GAME_ARG_ENABLE_LEGACYFONTS]);
// "================================================================================"
printf("\n\n%s=x \tOverride the video resolution.",GAME_ARGS[GAME_ARG_USE_RESOLUTION]);
printf("\n\n%s=x \tOverride the video resolution.", GAME_ARGS[GAME_ARG_USE_RESOLUTION]);
printf("\n\n \tWhere x is a string with the following format: 'width x height'.");
printf("\n\n \texample: %s %s=1024x768",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_RESOLUTION]);
printf("\n\n \texample: %s %s=1024x768", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_RESOLUTION]);
printf("\n\n%s=x \t\tOverride the video colorbits.",GAME_ARGS[GAME_ARG_USE_COLORBITS]);
printf("\n\n%s=x \t\tOverride the video colorbits.", GAME_ARGS[GAME_ARG_USE_COLORBITS]);
printf("\n\n \tWhere x is a valid colorbits value supported by your video");
printf("\n\n \t driver.");
printf("\n\n \texample: %s %s=32",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_COLORBITS]);
printf("\n\n \texample: %s %s=32", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_COLORBITS]);
printf("\n\n%s=x \t\tOverride the video depthbits.",GAME_ARGS[GAME_ARG_USE_DEPTHBITS]);
printf("\n\n%s=x \t\tOverride the video depthbits.", GAME_ARGS[GAME_ARG_USE_DEPTHBITS]);
printf("\n\n \tWhere x is a valid depthbits value supported by your video");
printf("\n\n \t driver.");
printf("\n\n \texample: %s %s=24",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_DEPTHBITS]);
printf("\n\n \texample: %s %s=24", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_DEPTHBITS]);
printf("\n\n%s=x \tOverride the video fullscreen mode.",GAME_ARGS[GAME_ARG_USE_FULLSCREEN]);
printf("\n\n%s=x \tOverride the video fullscreen mode.", GAME_ARGS[GAME_ARG_USE_FULLSCREEN]);
printf("\n\n \tWhere x either true or false.");
printf("\n\n \texample: %s %s=true",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_FULLSCREEN]);
printf("\n\n \texample: %s %s=true", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_FULLSCREEN]);
printf("\n\n%s=x \t\tOverride the video gamma (contrast) value.",GAME_ARGS[GAME_ARG_SET_GAMMA]);
printf("\n\n%s=x \t\tOverride the video gamma (contrast) value.", GAME_ARGS[GAME_ARG_SET_GAMMA]);
printf("\n\n \tWhere x is a floating point value.");
printf("\n\n \texample: %s %s=1.5",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_SET_GAMMA]);
printf("\n\n \texample: %s %s=1.5", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_SET_GAMMA]);
printf("\n\n%s=x \t\tOverride the font to use.",GAME_ARGS[GAME_ARG_USE_FONT]);
printf("\n\n%s=x \t\tOverride the font to use.", GAME_ARGS[GAME_ARG_USE_FONT]);
printf("\n\n \tWhere x is the path and name of a font file supported by");
printf("\n\n \t freetype2.");
printf("\n\n \texample:");
printf("\n\n \t%s %s=$APPLICATIONDATAPATH/data/core/fonts/Vera.ttf",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_USE_FONT]);
printf("\n\n \t%s %s=$APPLICATIONDATAPATH/data/core/fonts/Vera.ttf", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_USE_FONT]);
printf("\n\n%s=x \tOverride the font base size.",GAME_ARGS[GAME_ARG_FONT_BASESIZE]);
printf("\n\n%s=x \tOverride the font base size.", GAME_ARGS[GAME_ARG_FONT_BASESIZE]);
printf("\n\n \tWhere x is the numeric base font size to use.");
printf("\n\n \texample: %s %s=5",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_FONT_BASESIZE]);
printf("\n\n \texample: %s %s=5", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_FONT_BASESIZE]);
printf("\n\n%s \tDisables video playback.",GAME_ARGS[GAME_ARG_DISABLE_VIDEOS]);
printf("\n\n%s \tDisables video playback.", GAME_ARGS[GAME_ARG_DISABLE_VIDEOS]);
printf("\n\n%s ",GAME_ARGS[GAME_ARG_DISABLE_OPENGL_CAPS_CHECK]);
printf("\n\n%s ", GAME_ARGS[GAME_ARG_DISABLE_OPENGL_CAPS_CHECK]);
printf("\n\n \tDisables opengl capability checks (for corrupt or flaky video");
printf("\n\n \t drivers).");
printf("\n\n%s=x=y ",GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]);
printf("\n\n%s=x=y ", GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]);
printf("\n\n \tCompress selected game data into archives for network sharing.");
printf("\n\n \tWhere x is one of the following data items to compress:");
printf("\n\n \t techtrees, tilesets or all.");
printf("\n\n \tWhere y = include_main to include main (non mod) data.");
printf("\n\n \texample: %s %s=all",extractFileFromDirectoryPath(argv0).c_str(),GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]);
printf("\n\n \texample: %s %s=all", extractFileFromDirectoryPath(argv0).c_str(), GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]);
printf("\n\n%s=x=y ",GAME_ARGS[GAME_ARG_STEAM]);
printf("\n\n%s=x=y ", GAME_ARGS[GAME_ARG_STEAM]);
printf("\n\n \tRun with Steam Client Integration.");
printf("\n\n%s \t\tDisplays verbose information in the console.",GAME_ARGS[GAME_ARG_VERBOSE_MODE]);
printf("\n\n%s \t\tDisplays verbose information in the console.", GAME_ARGS[GAME_ARG_VERBOSE_MODE]);
printf("\n\n");
}
bool hasCommandArgument(int argc, char** argv,const string argName, int *foundIndex=NULL, int startLookupIndex=1,bool useArgParamLen=false) {
bool hasCommandArgument(int argc, char** argv, const string argName, int *foundIndex = NULL, int startLookupIndex = 1, bool useArgParamLen = false) {
bool result = false;
if(foundIndex != NULL) {
if (foundIndex != NULL) {
*foundIndex = -1;
}
int compareLen = (int)strlen(argName.c_str());
int compareLen = (int) strlen(argName.c_str());
for(int idx = startLookupIndex; idx < argc; idx++) {
if(useArgParamLen == true) {
compareLen = (int)strlen(argv[idx]);
for (int idx = startLookupIndex; idx < argc; idx++) {
if (useArgParamLen == true) {
compareLen = (int) strlen(argv[idx]);
}
if(_strnicmp(argName.c_str(),argv[idx],compareLen) == 0) {
if (_strnicmp(argName.c_str(), argv[idx], compareLen) == 0) {
result = true;
if(foundIndex != NULL) {
if (foundIndex != NULL) {
*foundIndex = idx;
}
@@ -500,87 +500,87 @@ bool hasCommandArgument(int argc, char** argv,const string argName, int *foundIn
}
int mainSetup(int argc, char **argv) {
bool haveSpecialOutputCommandLineOption = false;
bool haveSpecialOutputCommandLineOption = false;
const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]);
if(knownArgCount != GAME_ARG_END) {
char szBuf[8096]="";
snprintf(szBuf,8096,"Internal arg count mismatch knownArgCount = %d, GAME_ARG_END = %d",knownArgCount,GAME_ARG_END);
throw megaglest_runtime_error(szBuf);
}
const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]);
if (knownArgCount != GAME_ARG_END) {
char szBuf[8096] = "";
snprintf(szBuf, 8096, "Internal arg count mismatch knownArgCount = %d, GAME_ARG_END = %d", knownArgCount, GAME_ARG_END);
throw megaglest_runtime_error(szBuf);
}
SystemFlags::VERBOSE_MODE_ENABLED = false;
if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERBOSE_MODE]) == true) {
SystemFlags::VERBOSE_MODE_ENABLED = true;
}
SystemFlags::VERBOSE_MODE_ENABLED = false;
if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERBOSE_MODE]) == true) {
SystemFlags::VERBOSE_MODE_ENABLED = true;
}
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_DISABLE_STREFLOP_CAPS_CHECK])) == false) {
// Ensure at runtime that the client has SSE
if (hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_DISABLE_STREFLOP_CAPS_CHECK])) == false) {
// Ensure at runtime that the client has SSE
#if defined(STREFLOP_SSE)
#if defined(WIN32)
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] About to validate SSE support\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] About to validate SSE support\n", __FILE__, __FUNCTION__, __LINE__);
int has_x64 = false;
int has_MMX = false;
int has_SSE = false;
int has_SSE2 = false;
int has_SSE3 = false;
int has_SSSE3 = false;
int has_SSE41 = false;
int has_SSE42 = false;
int has_SSE4a = false;
int has_AVX = false;
int has_XOP = false;
int has_FMA3 = false;
int has_FMA4 = false;
int has_x64 = false;
int has_MMX = false;
int has_SSE = false;
int has_SSE2 = false;
int has_SSE3 = false;
int has_SSSE3 = false;
int has_SSE41 = false;
int has_SSE42 = false;
int has_SSE4a = false;
int has_AVX = false;
int has_XOP = false;
int has_FMA3 = false;
int has_FMA4 = false;
int info[4];
__cpuid(info, 0);
int nIds = info[0];
int info[4];
__cpuid(info, 0);
int nIds = info[0];
__cpuid(info, 0x80000000);
int nExIds = info[0];
__cpuid(info, 0x80000000);
int nExIds = info[0];
// Detect Instruction Set
if (nIds >= 1){
__cpuid(info,0x00000001);
has_MMX = (info[3] & ((int)1 << 23)) != 0;
has_SSE = (info[3] & ((int)1 << 25)) != 0;
has_SSE2 = (info[3] & ((int)1 << 26)) != 0;
has_SSE3 = (info[2] & ((int)1 << 0)) != 0;
// Detect Instruction Set
if (nIds >= 1) {
__cpuid(info, 0x00000001);
has_MMX = (info[3] & ((int) 1 << 23)) != 0;
has_SSE = (info[3] & ((int) 1 << 25)) != 0;
has_SSE2 = (info[3] & ((int) 1 << 26)) != 0;
has_SSE3 = (info[2] & ((int) 1 << 0)) != 0;
has_SSSE3 = (info[2] & ((int)1 << 9)) != 0;
has_SSE41 = (info[2] & ((int)1 << 19)) != 0;
has_SSE42 = (info[2] & ((int)1 << 20)) != 0;
has_SSSE3 = (info[2] & ((int) 1 << 9)) != 0;
has_SSE41 = (info[2] & ((int) 1 << 19)) != 0;
has_SSE42 = (info[2] & ((int) 1 << 20)) != 0;
has_AVX = (info[2] & ((int)1 << 28)) != 0;
has_FMA3 = (info[2] & ((int)1 << 12)) != 0;
}
has_AVX = (info[2] & ((int) 1 << 28)) != 0;
has_FMA3 = (info[2] & ((int) 1 << 12)) != 0;
}
if (nExIds >= 0x80000001){
__cpuid(info,0x80000001);
has_x64 = (info[3] & ((int)1 << 29)) != 0;
has_SSE4a = (info[2] & ((int)1 << 6)) != 0;
has_FMA4 = (info[2] & ((int)1 << 16)) != 0;
has_XOP = (info[2] & ((int)1 << 11)) != 0;
}
if (nExIds >= 0x80000001) {
__cpuid(info, 0x80000001);
has_x64 = (info[3] & ((int) 1 << 29)) != 0;
has_SSE4a = (info[2] & ((int) 1 << 6)) != 0;
has_FMA4 = (info[2] & ((int) 1 << 16)) != 0;
has_XOP = (info[2] & ((int) 1 << 11)) != 0;
}
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sse check got [%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d]\n",__FILE__,__FUNCTION__,__LINE__,has_x64,has_MMX,has_SSE,has_SSE2,has_SSE3,has_SSSE3,has_SSE41,has_SSE42,has_SSE4a,has_AVX,has_XOP,has_FMA3,has_FMA4);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sse check got [%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d]\n", __FILE__, __FUNCTION__, __LINE__, has_x64, has_MMX, has_SSE, has_SSE2, has_SSE3, has_SSSE3, has_SSE41, has_SSE42, has_SSE4a, has_AVX, has_XOP, has_FMA3, has_FMA4);
if( has_SSE == false && has_SSE2 == false && has_SSE3 == false &&
has_SSSE3 == false && has_SSE41 == false && has_SSE42 == false &&
has_SSE4a == false) {
char szBuf[8096]="";
snprintf(szBuf,8096,"Error detected, your CPU does not seem to support SSE: [%d]\n",has_SSE);
throw megaglest_runtime_error(szBuf);
}
if (has_SSE == false && has_SSE2 == false && has_SSE3 == false &&
has_SSSE3 == false && has_SSE41 == false && has_SSE42 == false &&
has_SSE4a == false) {
char szBuf[8096] = "";
snprintf(szBuf, 8096, "Error detected, your CPU does not seem to support SSE: [%d]\n", has_SSE);
throw megaglest_runtime_error(szBuf);
}
#elif defined (__GNUC__) && !defined(__APPLE__)
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] About to validate SSE support\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] About to validate SSE support\n", __FILE__, __FUNCTION__, __LINE__);
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
@@ -588,80 +588,79 @@ int mainSetup(int argc, char **argv) {
__asm__ __volatile__ ("cpuid":\
"=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
int ax=0,bx=0,cx=0,dx=0;
cpuid(0x0000001,ax,bx,cx,dx)
int ax = 0, bx = 0, cx = 0, dx = 0;
cpuid(0x0000001, ax, bx, cx, dx)
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sse check got [%d,%d,%d,%d]\n",__FILE__,__FUNCTION__,__LINE__,ax,bx,cx,dx);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sse check got [%d,%d,%d,%d]\n", __FILE__, __FUNCTION__, __LINE__, ax, bx, cx, dx);
// Check SSE, SSE2 and SSE3 support (if all 3 fail throw exception)
if( !CHECK_BIT(dx,25) && !CHECK_BIT(dx,26) && !CHECK_BIT(cx,0) ) {
char szBuf[8096]="";
snprintf(szBuf,8096,"Error detected, your CPU does not seem to support SSE: [%d]\n",CHECK_BIT(dx,25));
throw megaglest_runtime_error(szBuf);
}
// Check SSE, SSE2 and SSE3 support (if all 3 fail throw exception)
if (!CHECK_BIT(dx, 25) && !CHECK_BIT(dx, 26) && !CHECK_BIT(cx, 0)) {
char szBuf[8096] = "";
snprintf(szBuf, 8096, "Error detected, your CPU does not seem to support SSE: [%d]\n", CHECK_BIT(dx, 25));
throw megaglest_runtime_error(szBuf);
}
#endif
#endif
}
if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SDL_INFO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_INFO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CURL_INFO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_XERCES_INFO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERSION]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true ||
hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true) {
if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SDL_INFO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_INFO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CURL_INFO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_XERCES_INFO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERSION]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true ||
hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true) {
haveSpecialOutputCommandLineOption = true;
}
if( haveSpecialOutputCommandLineOption == false) {
if (haveSpecialOutputCommandLineOption == false) {
#ifdef USE_STREFLOP
#define STREFLOP_NO_DENORMALS
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
streflop_init<streflop::Simple>();
streflop_init<streflop::Simple>();
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
#endif
}
if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_HELP])) == true ||
hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VERSION])) == true ||
hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS])) == true ||
hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true ||
hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS]))) {
// Use this for masterserver mode for timers like Chrono
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_HELP])) == true ||
hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_VERSION])) == true ||
hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS])) == true ||
hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true ||
hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS]))) {
// Use this for masterserver mode for timers like Chrono
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
if(SDL_Init(SDL_INIT_TIMER) < 0) {
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << "\n";
return 3;
}
}
else {
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | \
SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS) < 0) {
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (SDL_Init(SDL_INIT_TIMER) < 0) {
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << "\n";
return 3;
}
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
//SDL_EnableUNICODE(1);
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
//SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
}
} else {
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | \
SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS) < 0) {
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << "\n";
return 3;
}
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
//SDL_EnableUNICODE(1);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
//SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
}
if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
return 0;
}

View File

@@ -16,13 +16,17 @@
#include "leak_dumper.h"
namespace Shared{ namespace PlatformCommon { namespace Private {
namespace Shared {
namespace PlatformCommon {
namespace Private {
extern bool shouldBeFullscreen;
extern int ScreenWidth;
extern int ScreenHeight;
extern bool shouldBeFullscreen;
extern int ScreenWidth;
extern int ScreenHeight;
}}}
}
}
}
#endif

View File

@@ -38,503 +38,519 @@ using namespace std;
using namespace Shared::PlatformCommon;
#endif
namespace Shared { namespace PlatformCommon {
class Chrono;
}};
namespace Shared { namespace Platform {
class Mutex;
//class uint32;
enum ThreadState {
thrsNew,
thrsStarting,
thrsExecuteStart,
thrsExecuting,
thrsExecuted,
thrsExecuteAutoClean,
thrsExecuteComplete
namespace Shared {
namespace PlatformCommon {
class Chrono;
}
};
class Thread {
public:
enum Priority {
pIdle = 0,
pLow = 1,
pNormal = 2,
pHigh = 3,
pRealTime = 4
};
namespace Shared {
namespace Platform {
private:
SDL_Thread* thread;
//std::auto_ptr<Mutex> mutexthreadAccessor;
Mutex *mutexthreadAccessor;
ThreadState currentState;
bool threadObjectValid();
class Mutex;
//class uint32;
bool deleteAfterExecute;
static Mutex mutexthreadList;
static vector<Thread *> threadList;
static bool enableVerboseMode;
static unsigned long mainThreadId;
enum ThreadState {
thrsNew,
thrsStarting,
thrsExecuteStart,
thrsExecuting,
thrsExecuted,
thrsExecuteAutoClean,
thrsExecuteComplete
protected:
void addThreadToList();
void removeThreadFromList();
void queueAutoCleanThread();
bool isThreadExecuteCompleteStatus();
};
public:
Thread();
virtual ~Thread();
class Thread {
public:
enum Priority {
pIdle = 0,
pLow = 1,
pNormal = 2,
pHigh = 3,
pRealTime = 4
};
static unsigned long getCurrentThreadId();
static unsigned long getMainThreadId() { return mainThreadId; }
static void setMainThreadId();
static bool isCurrentThreadMainThread();
private:
SDL_Thread* thread;
//std::auto_ptr<Mutex> mutexthreadAccessor;
Mutex *mutexthreadAccessor;
ThreadState currentState;
bool threadObjectValid();
static void setEnableVerboseMode(bool value) { enableVerboseMode = value; }
static bool getEnableVerboseMode() { return enableVerboseMode; }
bool deleteAfterExecute;
static Mutex mutexthreadList;
static vector<Thread *> threadList;
static bool enableVerboseMode;
static unsigned long mainThreadId;
static std::vector<Thread *> getThreadList();
static void shutdownThreads();
protected:
void addThreadToList();
void removeThreadFromList();
void queueAutoCleanThread();
bool isThreadExecuteCompleteStatus();
void setDeleteAfterExecute(bool value) { deleteAfterExecute = value; }
bool getDeleteAfterExecute() const { return deleteAfterExecute; }
public:
Thread();
virtual ~Thread();
void start();
virtual void execute()=0;
void setPriority(Thread::Priority threadPriority);
void suspend();
void resume();
void kill();
static unsigned long getCurrentThreadId();
static unsigned long getMainThreadId() {
return mainThreadId;
}
static void setMainThreadId();
static bool isCurrentThreadMainThread();
private:
static int beginExecution(void *param);
};
// =====================================================
// class Mutex
// =====================================================
class Mutex {
private:
SDL_mutex* mutex;
int refCount;
string ownerId;
string deleteownerId;
SDL_mutex* mutexAccessor;
string lastownerId;
int maxRefCount;
Shared::PlatformCommon::Chrono *chronoPerf;
bool isStaticMutexListMutex;
static auto_ptr<Mutex> mutexMutexList;
static vector<Mutex *> mutexList;
public:
Mutex(string ownerId="");
~Mutex();
inline void setOwnerId(string ownerId) {
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
}
inline void p() {
SDL_LockMutex(mutex);
refCount++;
}
// Returns return 0, SDL_MUTEX_TIMEDOUT, or -1 on error;
// call SDL_GetError() for more information.
inline int TryLock(int millisecondsToWait=0) {
int result = SDL_TryLockMutex(mutex);
if(result == 0) {
refCount++;
}
return result;
}
inline void v() {
refCount--;
SDL_UnlockMutex(mutex);
}
inline int getRefCount() const { return refCount; }
inline SDL_mutex* getMutex() { return mutex; }
};
class MutexSafeWrapper {
protected:
Mutex *mutex;
string ownerId;
#ifdef DEBUG_PERFORMANCE_MUTEXES
Chrono chrono;
#endif
public:
MutexSafeWrapper(Mutex *mutex,string ownerId="") {
this->mutex = mutex;
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
~MutexSafeWrapper() {
ReleaseLock();
}
inline void setMutex(Mutex *mutex,string ownerId="") {
this->mutex = mutex;
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
inline int setMutexAndTryLock(Mutex *mutex,string ownerId="") {
this->mutex = mutex;
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
return this->mutex->TryLock();
}
inline bool isValidMutex() const {
return(this->mutex != NULL);
}
inline void Lock() {
if(this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("Locking Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
this->mutex->p();
if(this->mutex != NULL) {
this->mutex->setOwnerId(ownerId);
static void setEnableVerboseMode(bool value) {
enableVerboseMode = value;
}
static bool getEnableVerboseMode() {
return enableVerboseMode;
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if(chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),this->mutex->getRefCount(),ownerId.c_str());
chrono.start();
#endif
static std::vector<Thread *> getThreadList();
static void shutdownThreads();
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
}
}
inline int TryLock(int millisecondsToWait=0) {
if(this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("TryLocking Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
int result = this->mutex->TryLock(millisecondsToWait);
if(result == 0 && this->mutex != NULL) {
this->mutex->setOwnerId(ownerId);
void setDeleteAfterExecute(bool value) {
deleteAfterExecute = value;
}
bool getDeleteAfterExecute() const {
return deleteAfterExecute;
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if(chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),this->mutex->getRefCount(),ownerId.c_str());
chrono.start();
#endif
void start();
virtual void execute() = 0;
void setPriority(Thread::Priority threadPriority);
void suspend();
void resume();
void kill();
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
private:
static int beginExecution(void *param);
};
return result;
}
return 0;
}
// =====================================================
// class Mutex
// =====================================================
inline void ReleaseLock(bool keepMutex=false,bool deleteMutexOnRelease=false) {
if(this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("UnLocking Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
class Mutex {
private:
this->mutex->v();
SDL_mutex* mutex;
int refCount;
string ownerId;
string deleteownerId;
#ifdef DEBUG_PERFORMANCE_MUTEXES
if(chrono.getMillis() > 100) printf("In [%s::%s Line: %d] MUTEX UNLOCKED and held locked for msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),this->mutex->getRefCount(),ownerId.c_str());
#endif
SDL_mutex* mutexAccessor;
string lastownerId;
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("UnLocked Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
int maxRefCount;
Shared::PlatformCommon::Chrono *chronoPerf;
if(deleteMutexOnRelease == true) {
delete this->mutex;
this->mutex = NULL;
bool isStaticMutexListMutex;
static auto_ptr<Mutex> mutexMutexList;
static vector<Mutex *> mutexList;
public:
Mutex(string ownerId = "");
~Mutex();
inline void setOwnerId(string ownerId) {
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
}
inline void p() {
SDL_LockMutex(mutex);
refCount++;
}
// Returns return 0, SDL_MUTEX_TIMEDOUT, or -1 on error;
// call SDL_GetError() for more information.
inline int TryLock(int millisecondsToWait = 0) {
int result = SDL_TryLockMutex(mutex);
if (result == 0) {
refCount++;
}
return result;
}
inline void v() {
refCount--;
SDL_UnlockMutex(mutex);
}
inline int getRefCount() const {
return refCount;
}
if(keepMutex == false) {
this->mutex = NULL;
inline SDL_mutex* getMutex() {
return mutex;
}
}
}
};
// =====================================================
// class Semaphore
// =====================================================
class Semaphore {
private:
SDL_sem* semaphore;
public:
Semaphore(Uint32 initialValue = 0);
~Semaphore();
void signal();
int waitTillSignalled(int waitMilliseconds=-1);
bool tryDecrement();
uint32 getSemValue();
void resetSemValue(Uint32 initialValue);
};
class ReadWriteMutex
{
public:
ReadWriteMutex(int maxReaders = 32);
void LockRead();
void UnLockRead();
void LockWrite();
void UnLockWrite();
int maxReaders();
void setOwnerId(string ownerId) {
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
}
private:
Semaphore semaphore;
Mutex mutex;
int maxReadersCount;
string ownerId;
};
class ReadWriteMutexSafeWrapper {
protected:
ReadWriteMutex *mutex;
string ownerId;
bool isReadLock;
};
class MutexSafeWrapper {
protected:
Mutex *mutex;
string ownerId;
#ifdef DEBUG_PERFORMANCE_MUTEXES
Chrono chrono;
Chrono chrono;
#endif
public:
public:
ReadWriteMutexSafeWrapper(ReadWriteMutex *mutex,bool isReadLock=true, string ownerId="") {
this->mutex = mutex;
if(this->isReadLock != isReadLock) {
this->isReadLock = isReadLock;
}
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
~ReadWriteMutexSafeWrapper() {
ReleaseLock();
}
void setReadWriteMutex(ReadWriteMutex *mutex,bool isReadLock=true,string ownerId="") {
this->mutex = mutex;
if(this->isReadLock != isReadLock) {
this->isReadLock = isReadLock;
}
if(this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
bool isValidReadWriteMutex() const {
return(this->mutex != NULL);
}
void Lock() {
if(this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("Locking Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
if(this->isReadLock == true) {
this->mutex->LockRead();
}
else {
this->mutex->LockWrite();
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if(chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),this->mutex->getRefCount(),ownerId.c_str());
chrono.start();
#endif
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
}
}
void ReleaseLock(bool keepMutex=false) {
if(this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("UnLocking Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
if(this->isReadLock == true) {
this->mutex->UnLockRead();
}
else {
this->mutex->UnLockWrite();
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if(chrono.getMillis() > 100) printf("In [%s::%s Line: %d] MUTEX UNLOCKED and held locked for msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),this->mutex->getRefCount(),ownerId.c_str());
#endif
#ifdef DEBUG_MUTEXES
if(this->ownerId != "") {
printf("UnLocked Mutex [%s] refCount: %d\n",this->ownerId.c_str(),this->mutex->getRefCount());
}
#endif
if(keepMutex == false) {
this->mutex = NULL;
MutexSafeWrapper(Mutex *mutex, string ownerId = "") {
this->mutex = mutex;
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
}
~MutexSafeWrapper() {
ReleaseLock();
}
inline void setMutex(Mutex *mutex, string ownerId = "") {
this->mutex = mutex;
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
inline int setMutexAndTryLock(Mutex *mutex, string ownerId = "") {
this->mutex = mutex;
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
return this->mutex->TryLock();
}
inline bool isValidMutex() const {
return(this->mutex != NULL);
}
inline void Lock() {
if (this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("Locking Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
this->mutex->p();
if (this->mutex != NULL) {
this->mutex->setOwnerId(ownerId);
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if (chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n", __FILE__, __FUNCTION__, __LINE__, (long long int)chrono.getMillis(), this->mutex->getRefCount(), ownerId.c_str());
chrono.start();
#endif
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
}
}
inline int TryLock(int millisecondsToWait = 0) {
if (this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("TryLocking Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
int result = this->mutex->TryLock(millisecondsToWait);
if (result == 0 && this->mutex != NULL) {
this->mutex->setOwnerId(ownerId);
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if (chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n", __FILE__, __FUNCTION__, __LINE__, (long long int)chrono.getMillis(), this->mutex->getRefCount(), ownerId.c_str());
chrono.start();
#endif
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
return result;
}
return 0;
}
inline void ReleaseLock(bool keepMutex = false, bool deleteMutexOnRelease = false) {
if (this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("UnLocking Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
this->mutex->v();
#ifdef DEBUG_PERFORMANCE_MUTEXES
if (chrono.getMillis() > 100) printf("In [%s::%s Line: %d] MUTEX UNLOCKED and held locked for msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n", __FILE__, __FUNCTION__, __LINE__, (long long int)chrono.getMillis(), this->mutex->getRefCount(), ownerId.c_str());
#endif
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("UnLocked Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
if (deleteMutexOnRelease == true) {
delete this->mutex;
this->mutex = NULL;
}
if (keepMutex == false) {
this->mutex = NULL;
}
}
}
};
// =====================================================
// class Semaphore
// =====================================================
class Semaphore {
private:
SDL_sem* semaphore;
public:
Semaphore(Uint32 initialValue = 0);
~Semaphore();
void signal();
int waitTillSignalled(int waitMilliseconds = -1);
bool tryDecrement();
uint32 getSemValue();
void resetSemValue(Uint32 initialValue);
};
class ReadWriteMutex {
public:
ReadWriteMutex(int maxReaders = 32);
void LockRead();
void UnLockRead();
void LockWrite();
void UnLockWrite();
int maxReaders();
void setOwnerId(string ownerId) {
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
}
private:
Semaphore semaphore;
Mutex mutex;
int maxReadersCount;
string ownerId;
};
class ReadWriteMutexSafeWrapper {
protected:
ReadWriteMutex *mutex;
string ownerId;
bool isReadLock;
#ifdef DEBUG_PERFORMANCE_MUTEXES
Chrono chrono;
#endif
public:
ReadWriteMutexSafeWrapper(ReadWriteMutex *mutex, bool isReadLock = true, string ownerId = "") {
this->mutex = mutex;
if (this->isReadLock != isReadLock) {
this->isReadLock = isReadLock;
}
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
~ReadWriteMutexSafeWrapper() {
ReleaseLock();
}
void setReadWriteMutex(ReadWriteMutex *mutex, bool isReadLock = true, string ownerId = "") {
this->mutex = mutex;
if (this->isReadLock != isReadLock) {
this->isReadLock = isReadLock;
}
if (this->ownerId != ownerId) {
this->ownerId = ownerId;
}
Lock();
}
bool isValidReadWriteMutex() const {
return(this->mutex != NULL);
}
void Lock() {
if (this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("Locking Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
#ifdef DEBUG_PERFORMANCE_MUTEXES
chrono.start();
#endif
if (this->isReadLock == true) {
this->mutex->LockRead();
} else {
this->mutex->LockWrite();
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if (chrono.getMillis() > 5) printf("In [%s::%s Line: %d] MUTEX LOCK took msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n", __FILE__, __FUNCTION__, __LINE__, (long long int)chrono.getMillis(), this->mutex->getRefCount(), ownerId.c_str());
chrono.start();
#endif
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("Locked Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
}
}
void ReleaseLock(bool keepMutex = false) {
if (this->mutex != NULL) {
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("UnLocking Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
if (this->isReadLock == true) {
this->mutex->UnLockRead();
} else {
this->mutex->UnLockWrite();
}
#ifdef DEBUG_PERFORMANCE_MUTEXES
if (chrono.getMillis() > 100) printf("In [%s::%s Line: %d] MUTEX UNLOCKED and held locked for msecs: %lld, this->mutex->getRefCount() = %d ownerId [%s]\n", __FILE__, __FUNCTION__, __LINE__, (long long int)chrono.getMillis(), this->mutex->getRefCount(), ownerId.c_str());
#endif
#ifdef DEBUG_MUTEXES
if (this->ownerId != "") {
printf("UnLocked Mutex [%s] refCount: %d\n", this->ownerId.c_str(), this->mutex->getRefCount());
}
#endif
if (keepMutex == false) {
this->mutex = NULL;
}
}
}
};
const bool debugMasterSlaveThreadController = false;
// =====================================================
// class Trigger
// =====================================================
class Trigger {
private:
SDL_cond* trigger;
Mutex *mutex;
public:
Trigger(Mutex *mutex);
~Trigger();
void signal(bool allThreads = false);
int waitTillSignalled(Mutex *mutex, int waitMilliseconds = -1);
};
class MasterSlaveThreadController;
class SlaveThreadControllerInterface {
public:
virtual void setMasterController(MasterSlaveThreadController *master) = 0;
virtual void signalSlave(void *userdata) = 0;
virtual ~SlaveThreadControllerInterface() {
}
};
class MasterSlaveThreadController {
private:
static const int triggerBaseCount = 1;
Mutex *mutex;
Semaphore *slaveTriggerSem;
int slaveTriggerCounter;
std::vector<SlaveThreadControllerInterface *> slaveThreadList;
void init(std::vector<SlaveThreadControllerInterface *> &newSlaveThreadList);
public:
MasterSlaveThreadController();
MasterSlaveThreadController(std::vector<SlaveThreadControllerInterface *> &slaveThreadList);
~MasterSlaveThreadController();
void setSlaves(std::vector<SlaveThreadControllerInterface *> &slaveThreadList);
void clearSlaves(bool clearListOnly = false);
void signalSlaves(void *userdata);
void triggerMaster(int waitMilliseconds = -1);
bool waitTillSlavesTrigger(int waitMilliseconds = -1);
};
class MasterSlaveThreadControllerSafeWrapper {
protected:
MasterSlaveThreadController *master;
string ownerId;
int waitMilliseconds;
public:
MasterSlaveThreadControllerSafeWrapper(MasterSlaveThreadController *master, int waitMilliseconds = -1, string ownerId = "") {
if (debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
this->master = master;
this->waitMilliseconds = waitMilliseconds;
this->ownerId = ownerId;
if (debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
}
~MasterSlaveThreadControllerSafeWrapper() {
if (debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
if (master != NULL) {
if (debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
master->triggerMaster(this->waitMilliseconds);
}
if (debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__);
}
};
}
};
const bool debugMasterSlaveThreadController = false;
// =====================================================
// class Trigger
// =====================================================
class Trigger {
private:
SDL_cond* trigger;
Mutex *mutex;
public:
Trigger(Mutex *mutex);
~Trigger();
void signal(bool allThreads=false);
int waitTillSignalled(Mutex *mutex, int waitMilliseconds=-1);
};
class MasterSlaveThreadController;
class SlaveThreadControllerInterface {
public:
virtual void setMasterController(MasterSlaveThreadController *master) = 0;
virtual void signalSlave(void *userdata) = 0;
virtual ~SlaveThreadControllerInterface() {}
};
class MasterSlaveThreadController {
private:
static const int triggerBaseCount = 1;
Mutex *mutex;
Semaphore *slaveTriggerSem;
int slaveTriggerCounter;
std::vector<SlaveThreadControllerInterface *> slaveThreadList;
void init(std::vector<SlaveThreadControllerInterface *> &newSlaveThreadList);
public:
MasterSlaveThreadController();
MasterSlaveThreadController(std::vector<SlaveThreadControllerInterface *> &slaveThreadList);
~MasterSlaveThreadController();
void setSlaves(std::vector<SlaveThreadControllerInterface *> &slaveThreadList);
void clearSlaves(bool clearListOnly=false);
void signalSlaves(void *userdata);
void triggerMaster(int waitMilliseconds=-1);
bool waitTillSlavesTrigger(int waitMilliseconds=-1);
};
class MasterSlaveThreadControllerSafeWrapper {
protected:
MasterSlaveThreadController *master;
string ownerId;
int waitMilliseconds;
public:
MasterSlaveThreadControllerSafeWrapper(MasterSlaveThreadController *master, int waitMilliseconds=-1, string ownerId="") {
if(debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
this->master = master;
this->waitMilliseconds = waitMilliseconds;
this->ownerId = ownerId;
if(debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
}
~MasterSlaveThreadControllerSafeWrapper() {
if(debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(master != NULL) {
if(debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
master->triggerMaster(this->waitMilliseconds);
}
if(debugMasterSlaveThreadController) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
}
};
}}//end namespace
}//end namespace
#endif

View File

@@ -33,217 +33,290 @@ typedef SDL_Keysym SDL_keysym;
#endif
namespace Shared{ namespace Platform{
namespace Shared {
namespace Platform {
class Timer;
//class PlatformContextGl;
class Timer;
//class PlatformContextGl;
enum MouseButton {
mbUnknown,
mbLeft,
mbCenter,
mbRight,
mbButtonX1,
mbButtonX2,
enum MouseButton {
mbUnknown,
mbLeft,
mbCenter,
mbRight,
mbButtonX1,
mbButtonX2,
mbCount
};
mbCount
};
enum SizeState{
ssMaximized,
ssMinimized,
ssRestored
};
enum SizeState {
ssMaximized,
ssMinimized,
ssRestored
};
class MouseState {
private:
bool states[mbCount];
class MouseState {
private:
bool states[mbCount];
public:
MouseState() {
clear();
public:
MouseState() {
clear();
}
//MouseState(const MouseState &);
//MouseState &operator=(const MouseState &);
void clear() {
memset(this, 0, sizeof(MouseState));
}
bool get(MouseButton b) const {
if (b > 0 && b < mbCount) {
return states[b];
}
return false;
}
void set(MouseButton b, bool state) {
if (b > 0 && b < mbCount) {
states[b] = state;
}
}
};
enum WindowStyle {
wsFullscreen,
wsWindowedFixed,
wsWindowedResizable
};
// =====================================================
// class Window
// =====================================================
class Window {
private:
static SDL_Window *sdlWindow;
Uint32 lastMouseDown[mbCount];
int lastMouseX[mbCount];
int lastMouseY[mbCount];
static int64 lastMouseEvent; /** for use in mouse hover calculations */
static MouseState mouseState;
static Vec2i mousePos;
static bool isKeyPressedDown;
static bool isFullScreen;
static SDL_keysym keystate;
static bool tryVSynch;
static int64 lastToggle;
static void setLastToggle(int64 lastToggle) {
Window::lastToggle = lastToggle;
}
static int64 getLastToggle() {
return Window::lastToggle;
}
static void setLastMouseEvent(int64 lastMouseEvent) {
Window::lastMouseEvent = lastMouseEvent;
}
static int64 getLastMouseEvent() {
return Window::lastMouseEvent;
}
static const MouseState &getMouseState() {
return Window::mouseState;
}
static void setMouseState(MouseButton b, bool state) {
Window::mouseState.set(b, state);
}
static const Vec2i &getMousePos() {
return Window::mousePos;
}
static void setMousePos(const Vec2i &mousePos) {
Window::mousePos = mousePos;
}
static void setKeystate(SDL_keysym state) {
keystate = state;
}
//static bool masterserverMode;
static map<wchar_t, bool> mapAllowedKeys;
protected:
//int w, h;
static bool isActive;
static bool allowAltEnterFullscreenToggle;
static int lastShowMouseState;
public:
static SDL_Window *getSDLWindow();
static bool handleEvent();
static void revertMousePos();
static Vec2i getOldMousePos();
static bool isKeyDown() {
return isKeyPressedDown;
}
static void setupGraphicsScreen(int depthBits = -1, int stencilBits = -1, bool hardware_acceleration = false, bool fullscreen_anti_aliasing = false);
static const bool getIsFullScreen() {
return isFullScreen;
}
static void setIsFullScreen(bool value) {
isFullScreen = value;
}
//static SDL_keysym getKeystate() { return keystate; }
static bool isKeyStateModPressed(int mod);
static wchar_t extractLastKeyPressed();
Window();
Window(SDL_Window *sdlWindow);
virtual ~Window();
static void addAllowedKeys(string keyList);
static void clearAllowedKeys();
static bool isAllowedKey(wchar_t key);
virtual int getScreenWidth() = 0;
virtual int getScreenHeight() = 0;
virtual bool ChangeVideoMode(bool preserveContext, int resWidth, int resHeight,
bool fullscreenWindow, int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue) = 0;
//static void setMasterserverMode(bool value) { Window::masterserverMode = value;}
//static bool getMasterserverMode() { return Window::masterserverMode;}
static bool getTryVSynch() {
return tryVSynch;
}
static void setTryVSynch(bool value) {
tryVSynch = value;
}
WindowHandle getHandle() {
return 0;
}
string getText();
int getX() {
return 0;
}
int getY() {
return 0;
}
int getW() {
return getScreenWidth();
}
int getH() {
return getScreenHeight();
}
//component state
int getClientW() {
return getW();
}
int getClientH() {
return getH();
}
float getAspect();
//object state
void setText(string text);
void setStyle(WindowStyle windowStyle);
void setSize(int w, int h);
void setPos(int x, int y);
void setEnabled(bool enabled);
void setVisible(bool visible);
//misc
void create();
void destroy();
void minimize();
static void setAllowAltEnterFullscreenToggle(bool value) {
allowAltEnterFullscreenToggle = value;
}
static bool getAllowAltEnterFullscreenToggle() {
return allowAltEnterFullscreenToggle;
}
static char getRawKey(SDL_keysym keysym);
protected:
void setSDLWindow(SDL_Window *window);
virtual void eventCreate() {
}
virtual void eventMouseDown(int x, int y, MouseButton mouseButton) {
}
virtual void eventMouseUp(int x, int y, MouseButton mouseButton) {
}
virtual void eventMouseMove(int x, int y, const MouseState* mouseState) {
}
virtual void eventMouseDoubleClick(int x, int y, MouseButton mouseButton) {
}
virtual void eventMouseWheel(int x, int y, int zDelta) {
}
virtual void eventKeyDown(SDL_KeyboardEvent key) {
}
virtual void eventKeyUp(SDL_KeyboardEvent key) {
}
virtual void eventKeyPress(SDL_KeyboardEvent c) {
}
virtual bool eventTextInput(std::string text) {
return false;
}
virtual bool eventSdlKeyDown(SDL_KeyboardEvent key) {
return false;
}
virtual void eventResize() {
};
virtual void eventPaint() {
}
virtual void eventTimer(int timerId) {
}
virtual void eventActivate(bool activated) {
};
virtual void eventResize(SizeState sizeState) {
};
virtual void eventMenu(int menuId) {
}
virtual void eventClose() {
};
virtual void eventDestroy() {
};
virtual void eventToggleFullScreen(bool isFullscreen) {
};
virtual void eventWindowEvent(SDL_WindowEvent event) {
}
private:
/// needed to detect double clicks
void handleMouseDown(SDL_Event event);
void handleMouseWheel(SDL_Event event);
static MouseButton getMouseButton(int sdlButton);
//static char getKey(SDL_keysym keysym, bool skipSpecialKeys=false);
//static char getNormalKey(SDL_keysym keysym,bool skipSpecialKeys=false);
static void toggleFullscreen();
static wchar_t convertStringtoSDLKey(const string &value);
};
bool isKeyPressed(SDL_Keycode compareKey, SDL_KeyboardEvent input, vector<int> modifiersToCheck);
bool isKeyPressed(SDL_Keycode compareKey, SDL_KeyboardEvent input, bool modifiersAllowed = true);
SDL_Keycode extractKeyPressed(SDL_KeyboardEvent input);
//bool isAllowedInputTextKey(SDL_Keycode key);
//wchar_t extractKeyPressedUnicode(SDL_KeyboardEvent input);
vector<int> extractKeyPressedUnicodeLength(string text);
bool isAllowedInputTextKey(wchar_t &key);
}
//MouseState(const MouseState &);
//MouseState &operator=(const MouseState &);
void clear() { memset(this, 0, sizeof(MouseState)); }
bool get(MouseButton b) const {
if(b > 0 && b < mbCount) {
return states[b];
}
return false;
}
void set(MouseButton b, bool state) {
if(b > 0 && b < mbCount) {
states[b] = state;
}
}
};
enum WindowStyle{
wsFullscreen,
wsWindowedFixed,
wsWindowedResizable
};
// =====================================================
// class Window
// =====================================================
class Window {
private:
static SDL_Window *sdlWindow;
Uint32 lastMouseDown[mbCount];
int lastMouseX[mbCount];
int lastMouseY[mbCount];
static int64 lastMouseEvent; /** for use in mouse hover calculations */
static MouseState mouseState;
static Vec2i mousePos;
static bool isKeyPressedDown;
static bool isFullScreen;
static SDL_keysym keystate;
static bool tryVSynch;
static int64 lastToggle ;
static void setLastToggle(int64 lastToggle) {Window::lastToggle = lastToggle;}
static int64 getLastToggle() {return Window::lastToggle;}
static void setLastMouseEvent(int64 lastMouseEvent) {Window::lastMouseEvent = lastMouseEvent;}
static int64 getLastMouseEvent() {return Window::lastMouseEvent;}
static const MouseState &getMouseState() {return Window::mouseState;}
static void setMouseState(MouseButton b, bool state) {Window::mouseState.set(b, state);}
static const Vec2i &getMousePos() {return Window::mousePos;}
static void setMousePos(const Vec2i &mousePos) {Window::mousePos = mousePos;}
static void setKeystate(SDL_keysym state) { keystate = state; }
//static bool masterserverMode;
static map<wchar_t,bool> mapAllowedKeys;
protected:
//int w, h;
static bool isActive;
static bool allowAltEnterFullscreenToggle;
static int lastShowMouseState;
public:
static SDL_Window *getSDLWindow();
static bool handleEvent();
static void revertMousePos();
static Vec2i getOldMousePos();
static bool isKeyDown() { return isKeyPressedDown; }
static void setupGraphicsScreen(int depthBits=-1, int stencilBits=-1, bool hardware_acceleration=false, bool fullscreen_anti_aliasing=false);
static const bool getIsFullScreen() { return isFullScreen; }
static void setIsFullScreen(bool value) { isFullScreen = value; }
//static SDL_keysym getKeystate() { return keystate; }
static bool isKeyStateModPressed(int mod);
static wchar_t extractLastKeyPressed();
Window();
Window(SDL_Window *sdlWindow);
virtual ~Window();
static void addAllowedKeys(string keyList);
static void clearAllowedKeys();
static bool isAllowedKey(wchar_t key);
virtual int getScreenWidth() = 0;
virtual int getScreenHeight() = 0;
virtual bool ChangeVideoMode(bool preserveContext,int resWidth, int resHeight,
bool fullscreenWindow, int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue) = 0;
//static void setMasterserverMode(bool value) { Window::masterserverMode = value;}
//static bool getMasterserverMode() { return Window::masterserverMode;}
static bool getTryVSynch() { return tryVSynch; }
static void setTryVSynch(bool value) { tryVSynch = value; }
WindowHandle getHandle() {return 0;}
string getText();
int getX() { return 0; }
int getY() { return 0; }
int getW() { return getScreenWidth(); }
int getH() { return getScreenHeight(); }
//component state
int getClientW() { return getW(); }
int getClientH() { return getH(); }
float getAspect();
//object state
void setText(string text);
void setStyle(WindowStyle windowStyle);
void setSize(int w, int h);
void setPos(int x, int y);
void setEnabled(bool enabled);
void setVisible(bool visible);
//misc
void create();
void destroy();
void minimize();
static void setAllowAltEnterFullscreenToggle(bool value) { allowAltEnterFullscreenToggle = value; }
static bool getAllowAltEnterFullscreenToggle() { return allowAltEnterFullscreenToggle; }
static char getRawKey(SDL_keysym keysym);
protected:
void setSDLWindow(SDL_Window *window);
virtual void eventCreate(){}
virtual void eventMouseDown(int x, int y, MouseButton mouseButton){}
virtual void eventMouseUp(int x, int y, MouseButton mouseButton){}
virtual void eventMouseMove(int x, int y, const MouseState* mouseState){}
virtual void eventMouseDoubleClick(int x, int y, MouseButton mouseButton){}
virtual void eventMouseWheel(int x, int y, int zDelta) {}
virtual void eventKeyDown(SDL_KeyboardEvent key) {}
virtual void eventKeyUp(SDL_KeyboardEvent key) {}
virtual void eventKeyPress(SDL_KeyboardEvent c) {}
virtual bool eventTextInput(std::string text) { return false; }
virtual bool eventSdlKeyDown(SDL_KeyboardEvent key) { return false; }
virtual void eventResize() {};
virtual void eventPaint() {}
virtual void eventTimer(int timerId) {}
virtual void eventActivate(bool activated) {};
virtual void eventResize(SizeState sizeState) {};
virtual void eventMenu(int menuId) {}
virtual void eventClose() {};
virtual void eventDestroy() {};
virtual void eventToggleFullScreen(bool isFullscreen) {};
virtual void eventWindowEvent(SDL_WindowEvent event) {}
private:
/// needed to detect double clicks
void handleMouseDown(SDL_Event event);
void handleMouseWheel(SDL_Event event);
static MouseButton getMouseButton(int sdlButton);
//static char getKey(SDL_keysym keysym, bool skipSpecialKeys=false);
//static char getNormalKey(SDL_keysym keysym,bool skipSpecialKeys=false);
static void toggleFullscreen();
static wchar_t convertStringtoSDLKey(const string &value);
};
bool isKeyPressed(SDL_Keycode compareKey, SDL_KeyboardEvent input, vector<int> modifiersToCheck);
bool isKeyPressed(SDL_Keycode compareKey, SDL_KeyboardEvent input, bool modifiersAllowed=true);
SDL_Keycode extractKeyPressed(SDL_KeyboardEvent input);
//bool isAllowedInputTextKey(SDL_Keycode key);
//wchar_t extractKeyPressedUnicode(SDL_KeyboardEvent input);
vector<int> extractKeyPressedUnicodeLength(string text);
bool isAllowedInputTextKey(wchar_t &key);
}}//end namespace
}//end namespace
#endif

View File

@@ -18,45 +18,51 @@
using Shared::Graphics::Gl::ContextGl;
namespace Shared{ namespace Platform{
namespace Shared {
namespace Platform {
// =====================================================
// class WindowGl
// =====================================================
// =====================================================
// class WindowGl
// =====================================================
class WindowGl: public Window {
private:
ContextGl context;
class WindowGl : public Window {
private:
ContextGl context;
static void setGamma(SDL_Window *window,float gammaValue);
public:
WindowGl();
WindowGl(SDL_Window *sdlWindow);
virtual ~WindowGl();
static void setGamma(SDL_Window *window, float gammaValue);
public:
WindowGl();
WindowGl(SDL_Window *sdlWindow);
virtual ~WindowGl();
void initGl(int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
void makeCurrentGl();
void swapBuffersGl();
void setGamma(float gammaValue);
void initGl(int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
void makeCurrentGl();
void swapBuffersGl();
void setGamma(float gammaValue);
SDL_Window * getScreenWindow();
SDL_Surface * getScreenSurface();
virtual int getScreenWidth();
virtual int getScreenHeight();
virtual int getDesiredScreenWidth() { return getScreenWidth(); }
virtual int getDesiredScreenHeight() { return getScreenHeight(); }
SDL_Window * getScreenWindow();
SDL_Surface * getScreenSurface();
virtual int getScreenWidth();
virtual int getScreenHeight();
virtual int getDesiredScreenWidth() {
return getScreenWidth();
}
virtual int getDesiredScreenHeight() {
return getScreenHeight();
}
virtual bool ChangeVideoMode(bool preserveContext, int resWidth, int resHeight,
bool fullscreenWindow, int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
virtual bool ChangeVideoMode(bool preserveContext, int resWidth, int resHeight,
bool fullscreenWindow, int colorBits, int depthBits, int stencilBits,
bool hardware_acceleration, bool fullscreen_anti_aliasing,
float gammaValue);
protected:
virtual void eventToggleFullScreen(bool isFullscreen);
};
protected:
virtual void eventToggleFullScreen(bool isFullscreen);
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -39,29 +39,29 @@
* ////////////////////////////////////////////////////////////////////// */
/** \file glob.h
*
* Contains the declarations for the glob() API.
*/
/** \file glob.h
*
* Contains the declarations for the glob() API.
*/
#ifndef SYNSOFT_UNIXEM_INCL_H_GLOB
#define SYNSOFT_UNIXEM_INCL_H_GLOB
#include "leak_dumper.h"
/* ////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////// */
/** \weakgroup unixem Synesis Software UNIX Emulation for Win32
* \brief The UNIX emulation library
*/
/** \weakgroup unixem Synesis Software UNIX Emulation for Win32
* \brief The UNIX emulation library
*/
/** \weakgroup unixem_glob glob() API
* \ingroup UNIXem unixem
* \brief This API provides facilities for enumerating the file-system contents
* @{
*/
/** \weakgroup unixem_glob glob() API
* \ingroup UNIXem unixem
* \brief This API provides facilities for enumerating the file-system contents
* @{
*/
/* ////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////// */
#ifndef _WIN32
# error This file is only currently defined for compilation on Win32 systems
@@ -71,7 +71,7 @@
* Constants and definitions
*/
/* Error codes */
/* Error codes */
#define GLOB_NOSPACE (1) /*!< \brief (Error result code:) An attempt to allocate memory failed, or if errno was 0 GLOB_LIMIT was specified in the flags and ARG_MAX patterns were matched. */
#define GLOB_ABORTED (2) /*!< \brief (Error result code:) The scan was stopped because an error was encountered and either GLOB_ERR was set or (*errfunc)() returned non-zero. */
#define GLOB_NOMATCH (3) /*!< \brief (Error result code:) The pattern does not match any existing pathname, and GLOB_NOCHECK was not set int flags. */
@@ -103,17 +103,16 @@
* Typedefs
*/
/** \brief Result structure for glob()
*
* This structure is used by glob() to return the results of the search.
*/
typedef struct
{
int gl_pathc; /*!< count of total paths so far */
int gl_matchc; /*!< count of paths matching pattern */
int gl_offs; /*!< reserved at beginning of gl_pathv */
int gl_flags; /*!< returned flags */
char **gl_pathv; /*!< list of paths matching pattern */
/** \brief Result structure for glob()
*
* This structure is used by glob() to return the results of the search.
*/
typedef struct {
int gl_pathc; /*!< count of total paths so far */
int gl_matchc; /*!< count of paths matching pattern */
int gl_offs; /*!< reserved at beginning of gl_pathv */
int gl_flags; /*!< returned flags */
char **gl_pathv; /*!< list of paths matching pattern */
} glob_t;
/* /////////////////////////////////////////////////////////////////////////
@@ -124,34 +123,34 @@ typedef struct
extern "C" {
#endif /* __cplusplus */
/** \brief Generates pathnames matching a pattern
*
* This function is a pathname generator that implements the rules for
* file name pattern matching used by the UNIX shell.
*
* \param pattern The pattern controlling the search
* \param flags A combination of the <b>GLOB_*</b> flags
* \param errfunc A function that is called each time part of the search processing fails
* \param pglob Pointer to a glob_t structure to receive the search results
* \return 0 on success, otherwise one of the <b>GLOB_*</b> error codes
*/
int glob( char const *pattern
, int flags
/** \brief Generates pathnames matching a pattern
*
* This function is a pathname generator that implements the rules for
* file name pattern matching used by the UNIX shell.
*
* \param pattern The pattern controlling the search
* \param flags A combination of the <b>GLOB_*</b> flags
* \param errfunc A function that is called each time part of the search processing fails
* \param pglob Pointer to a glob_t structure to receive the search results
* \return 0 on success, otherwise one of the <b>GLOB_*</b> error codes
*/
int glob(char const *pattern
, int flags
#if defined(__COMO__)
, int (*errfunc)(char const *, int)
, int(*errfunc)(char const *, int)
#else /* ? compiler */
, const int (*errfunc)(char const *, int)
, const int(*errfunc)(char const *, int)
#endif /* compiler */
, glob_t *pglob);
, glob_t *pglob);
/** \brief Frees the results of a call to glob
*
* This function releases any memory allocated in a call to glob. It must
* always be called for a successful call to glob.
*
* \param pglob Pointer to a glob_t structure to receive the search results
*/
void globfree(glob_t *pglob);
/** \brief Frees the results of a call to glob
*
* This function releases any memory allocated in a call to glob. It must
* always be called for a successful call to glob.
*
* \param pglob Pointer to a glob_t structure to receive the search results
*/
void globfree(glob_t *pglob);
#ifdef __cplusplus
}

View File

@@ -14,10 +14,12 @@
#include "leak_dumper.h"
namespace Shared{ namespace Platform{
namespace Shared {
namespace Platform {
}}//end namespace
}
}//end namespace
#endif

View File

@@ -19,102 +19,140 @@
using namespace std;
using namespace Shared::Platform;
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
// =====================================================
// class SoundInfo
// =====================================================
// =====================================================
// class SoundInfo
// =====================================================
class SoundInfo{
private:
uint32 channels;
uint32 samplesPerSecond;
uint32 bitsPerSample;
uint32 size;
uint32 bitRate;
class SoundInfo {
private:
uint32 channels;
uint32 samplesPerSecond;
uint32 bitsPerSample;
uint32 size;
uint32 bitRate;
public:
SoundInfo();
virtual ~SoundInfo(){};
public:
SoundInfo();
virtual ~SoundInfo() {
};
uint32 getChannels() const {return channels;}
uint32 getSamplesPerSecond() const {return samplesPerSecond;}
uint32 getBitsPerSample() const {return bitsPerSample;}
uint32 getSize() const {return size;}
uint32 getBitRate() const {return bitRate;}
uint32 getChannels() const {
return channels;
}
uint32 getSamplesPerSecond() const {
return samplesPerSecond;
}
uint32 getBitsPerSample() const {
return bitsPerSample;
}
uint32 getSize() const {
return size;
}
uint32 getBitRate() const {
return bitRate;
}
void setChannels(uint32 channels) {this->channels= channels;}
void setsamplesPerSecond(uint32 samplesPerSecond) {this->samplesPerSecond= samplesPerSecond;}
void setBitsPerSample(uint32 bitsPerSample) {this->bitsPerSample= bitsPerSample;}
void setSize(uint32 size) {this->size= size;}
void setBitRate(uint32 value) {this->bitRate = value;}
};
void setChannels(uint32 channels) {
this->channels = channels;
}
void setsamplesPerSecond(uint32 samplesPerSecond) {
this->samplesPerSecond = samplesPerSecond;
}
void setBitsPerSample(uint32 bitsPerSample) {
this->bitsPerSample = bitsPerSample;
}
void setSize(uint32 size) {
this->size = size;
}
void setBitRate(uint32 value) {
this->bitRate = value;
}
};
// =====================================================
// class Sound
// =====================================================
// =====================================================
// class Sound
// =====================================================
class Sound {
protected:
SoundFileLoader *soundFileLoader;
SoundInfo info;
float volume;
string fileName;
//static bool masterserverMode;
class Sound {
protected:
SoundFileLoader *soundFileLoader;
SoundInfo info;
float volume;
string fileName;
public:
Sound();
virtual ~Sound(){};
//static bool masterserverMode;
//static void setMasterserverMode(bool value) { masterserverMode=value; }
public:
Sound();
virtual ~Sound() {
};
const SoundInfo *getInfo() const {return &info;}
float getVolume() const {return volume;}
void setVolume(float volume) {this->volume= volume;}
string getFileName() {return fileName; }
};
//static void setMasterserverMode(bool value) { masterserverMode=value; }
// =====================================================
// class StaticSound
// =====================================================
const SoundInfo *getInfo() const {
return &info;
}
float getVolume() const {
return volume;
}
class StaticSound: public Sound{
private:
int8 * samples;
void setVolume(float volume) {
this->volume = volume;
}
string getFileName() {
return fileName;
}
};
public:
StaticSound();
virtual ~StaticSound();
// =====================================================
// class StaticSound
// =====================================================
int8 *getSamples() const {return samples;}
void load(const string &path);
void close();
};
class StaticSound : public Sound {
private:
int8 * samples;
// =====================================================
// class StrSound
// =====================================================
public:
StaticSound();
virtual ~StaticSound();
class StrSound: public Sound{
private:
StrSound *next;
int8 *getSamples() const {
return samples;
}
public:
StrSound();
virtual ~StrSound();
void load(const string &path);
void close();
};
StrSound *getNext() const {return next;}
void setNext(StrSound *next) {this->next= next;}
// =====================================================
// class StrSound
// =====================================================
void open(const string &path);
uint32 read(int8 *samples, uint32 size);
void close();
void restart();
};
class StrSound : public Sound {
private:
StrSound *next;
}}//end namespace
public:
StrSound();
virtual ~StrSound();
StrSound *getNext() const {
return next;
}
void setNext(StrSound *next) {
this->next = next;
}
void open(const string &path);
uint32 read(int8 *samples, uint32 size);
void close();
void restart();
};
}
}//end namespace
#endif

View File

@@ -15,18 +15,23 @@
#include "sound_player.h"
#include "leak_dumper.h"
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
// =====================================================
// class SoundFactory
// =====================================================
// =====================================================
// class SoundFactory
// =====================================================
class SoundFactory{
public:
virtual ~SoundFactory(){}
virtual SoundPlayer *newSoundPlayer() {return NULL;}
};
class SoundFactory {
public:
virtual ~SoundFactory() {
}
virtual SoundPlayer *newSoundPlayer() {
return NULL;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -12,17 +12,21 @@
#include "sound_factory.h"
#include "leak_dumper.h"
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
// ===============================
// class SoundFactoryOpenAL
// ===============================
// ===============================
// class SoundFactoryOpenAL
// ===============================
class SoundFactoryNone : public SoundFactory{
public:
virtual SoundPlayer* newSoundPlayer() {return NULL;}
};
class SoundFactoryNone : public SoundFactory {
public:
virtual SoundPlayer* newSoundPlayer() {
return NULL;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -23,87 +23,94 @@ struct OggVorbis_File;
using std::string;
using std::ifstream;
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
using Platform::uint32;
using Platform::int8;
using Util::MultiFactory;
using Platform::uint32;
using Platform::int8;
using Util::MultiFactory;
class SoundInfo;
class SoundInfo;
// =====================================================
// class SoundFileLoader
//
/// Interface that all SoundFileLoaders will implement
// =====================================================
// =====================================================
// class SoundFileLoader
//
/// Interface that all SoundFileLoaders will implement
// =====================================================
class SoundFileLoader{
public:
virtual ~SoundFileLoader(){}
class SoundFileLoader {
public:
virtual ~SoundFileLoader() {
}
virtual void open(const string &path, SoundInfo *soundInfo)= 0;
virtual uint32 read(int8 *samples, uint32 size)= 0;
virtual void close()= 0;
virtual void restart()= 0;
virtual string getFileName() = 0;
};
virtual void open(const string &path, SoundInfo *soundInfo) = 0;
virtual uint32 read(int8 *samples, uint32 size) = 0;
virtual void close() = 0;
virtual void restart() = 0;
virtual string getFileName() = 0;
};
// =====================================================
// class WavSoundFileLoader
//
/// Wave file loader
// =====================================================
// =====================================================
// class WavSoundFileLoader
//
/// Wave file loader
// =====================================================
class WavSoundFileLoader: public SoundFileLoader{
private:
static const int maxDataRetryCount= 10;
string fileName;
private:
uint32 dataOffset;
uint32 dataSize;
uint32 bytesPerSecond;
ifstream f;
class WavSoundFileLoader : public SoundFileLoader {
private:
static const int maxDataRetryCount = 10;
string fileName;
private:
uint32 dataOffset;
uint32 dataSize;
uint32 bytesPerSecond;
ifstream f;
public:
virtual void open(const string &path, SoundInfo *soundInfo);
virtual uint32 read(int8 *samples, uint32 size);
virtual void close();
virtual void restart();
virtual string getFileName() { return fileName; }
};
public:
virtual void open(const string &path, SoundInfo *soundInfo);
virtual uint32 read(int8 *samples, uint32 size);
virtual void close();
virtual void restart();
virtual string getFileName() {
return fileName;
}
};
// =====================================================
// class OggSoundFileLoader
//
/// OGG sound file loader, uses ogg-vorbis library
// =====================================================
// =====================================================
// class OggSoundFileLoader
//
/// OGG sound file loader, uses ogg-vorbis library
// =====================================================
class OggSoundFileLoader: public SoundFileLoader{
private:
OggVorbis_File *vf;
FILE *f;
string fileName;
class OggSoundFileLoader : public SoundFileLoader {
private:
OggVorbis_File *vf;
FILE *f;
string fileName;
public:
OggSoundFileLoader();
virtual void open(const string &path, SoundInfo *soundInfo);
virtual uint32 read(int8 *samples, uint32 size);
virtual void close();
virtual void restart();
virtual string getFileName() { return fileName; }
};
public:
OggSoundFileLoader();
virtual void open(const string &path, SoundInfo *soundInfo);
virtual uint32 read(int8 *samples, uint32 size);
virtual void close();
virtual void restart();
virtual string getFileName() {
return fileName;
}
};
// =====================================================
// class SoundFileLoaderFactory
// =====================================================
// =====================================================
// class SoundFileLoaderFactory
// =====================================================
class SoundFileLoaderFactory: public MultiFactory<SoundFileLoader>{
private:
SoundFileLoaderFactory();
public:
static SoundFileLoaderFactory * getInstance();
};
class SoundFileLoaderFactory : public MultiFactory<SoundFileLoader> {
private:
SoundFileLoaderFactory();
public:
static SoundFileLoaderFactory * getInstance();
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -15,31 +15,33 @@
#include "sound_factory.h"
#include "leak_dumper.h"
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
// =====================================================
// class SoundInterface
// =====================================================
// =====================================================
// class SoundInterface
// =====================================================
class SoundInterface{
private:
SoundFactory *soundFactory;
class SoundInterface {
private:
SoundFactory *soundFactory;
private:
SoundInterface() {
soundFactory = 0;
}
SoundInterface(SoundInterface &);
void operator=(SoundInterface &);
public:
static SoundInterface &getInstance();
void setFactory(SoundFactory *soundFactory);
SoundPlayer *newSoundPlayer();
};
private:
SoundInterface() {
soundFactory = 0;
}
SoundInterface(SoundInterface &);
void operator=(SoundInterface &);
public:
static SoundInterface &getInstance();
void setFactory(SoundFactory *soundFactory);
SoundPlayer *newSoundPlayer();
};
}}//end namespace
}//end namespace
#endif

View File

@@ -18,47 +18,50 @@
using Shared::Platform::uint32;
namespace Shared{ namespace Sound{
namespace Shared {
namespace Sound {
// =====================================================
// class SoundPlayerParams
// =====================================================
// =====================================================
// class SoundPlayerParams
// =====================================================
class SoundPlayerParams{
public:
uint32 strBufferSize;
uint32 strBufferCount;
uint32 staticBufferCount;
class SoundPlayerParams {
public:
uint32 strBufferSize;
uint32 strBufferCount;
uint32 staticBufferCount;
SoundPlayerParams();
};
SoundPlayerParams();
};
// =====================================================
// class SoundPlayer
//
// Interface that every SoundPlayer will implement
// =====================================================
// =====================================================
// class SoundPlayer
//
// Interface that every SoundPlayer will implement
// =====================================================
class SoundPlayer{
protected:
class SoundPlayer {
protected:
bool initOk;
bool initOk;
public:
virtual ~SoundPlayer()
{
initOk = false;
};
virtual bool init(const SoundPlayerParams *params)= 0;
virtual void end()= 0;
virtual void play(StaticSound *staticSound, bool force=false)= 0;
virtual void play(StrSound *strSound, int64 fadeOn=0)= 0; //delay and fade in miliseconds
virtual void stop(StrSound *strSound, int64 fadeOff=0)= 0;
virtual void stopAllSounds(int64 fadeOff=0)= 0;
virtual void updateStreams()= 0;
virtual bool wasInitOk() const { return initOk; }
};
public:
virtual ~SoundPlayer() {
initOk = false;
};
virtual bool init(const SoundPlayerParams *params) = 0;
virtual void end() = 0;
virtual void play(StaticSound *staticSound, bool force = false) = 0;
virtual void play(StrSound *strSound, int64 fadeOn = 0) = 0; //delay and fade in miliseconds
virtual void stop(StrSound *strSound, int64 fadeOff = 0) = 0;
virtual void stopAllSounds(int64 fadeOff = 0) = 0;
virtual void updateStreams() = 0;
virtual bool wasInitOk() const {
return initOk;
}
};
}}//end namespace
}
}//end namespace
#endif

View File

@@ -13,7 +13,7 @@
#ifndef FPUCHECK_H
#define FPUCHECK_H
//#include "LogOutput.h"
//#include "LogOutput.h"
#include "util.h"
#include "../../include/platform/common/streflop_cond.h"
@@ -25,16 +25,16 @@
e.g. `assert(good_fpu_control_registers());'
For reference, the layout of the MXCSR register:
FZ:RC:RC:PM:UM:OM:ZM:DM:IM:Rsvd:PE:UE:OE:ZE:DE:IE
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
FZ:RC:RC:PM:UM:OM:ZM:DM:IM:Rsvd:PE:UE:OE:ZE:DE:IE
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Spring1: 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0 = 0x1D00 = 7424
Spring2: 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 = 0x1F80 = 8064
Default: 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 = 0x1F80 = 8064
MaskRsvd:1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 = 0xFF80
And the layout of the 387 FPU control word register:
Rsvd:Rsvd:Rsvd:X:RC:RC:PC:PC:Rsvd:Rsvd:PM:UM:OM:ZM:DM:IM
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Rsvd:Rsvd:Rsvd:X:RC:RC:PC:PC:Rsvd:Rsvd:PM:UM:OM:ZM:DM:IM
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Spring1: 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 = 0x003A = 58
Spring2: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 = 0x003F = 63
Default: 0 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1 = 0x033F = 831
@@ -66,12 +66,11 @@ MaskRsvd: 0 0 0 1 1 1 1 1 0 0 1 1 1 1 1 1 = 0x1F3F
Source: Intel Architecture Software Development Manual, Volume 1, Basic Architecture
*/
static inline void good_fpu_control_registers(const char* text, const char *file=NULL, const char *classname=NULL, const int line=-1)
{
static inline void good_fpu_control_registers(const char* text, const char *file = NULL, const char *classname = NULL, const int line = -1) {
const char *outText = text;
char szBuf[256]="";
if(outText == NULL) {
sprintf(szBuf,"In [%s::%s Line: %d]",file=NULL, classname, line);
char szBuf[256] = "";
if (outText == NULL) {
sprintf(szBuf, "In [%s::%s Line: %d]", file = NULL, classname, line);
outText = &szBuf[0];
}
// We are paranoid.
@@ -80,38 +79,38 @@ static inline void good_fpu_control_registers(const char* text, const char *file
fenv_t fenv;
fegetenv(&fenv);
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML) // -fsignaling-nans
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML) // -fsignaling-nans
bool ret = ((fenv.sse_mode & 0xFF80) == (0x1937 & 0xFF80) || (fenv.sse_mode & 0xFF80) == (0x1925 & 0xFF80)) &&
((fenv.x87_mode & 0x1F3F) == (0x0072 & 0x1F3F) || (fenv.x87_mode & 0x1F3F) == 0x003F);
#else
((fenv.x87_mode & 0x1F3F) == (0x0072 & 0x1F3F) || (fenv.x87_mode & 0x1F3F) == 0x003F);
#else
bool ret = ((fenv.sse_mode & 0xFF80) == 0x1D00 || (fenv.sse_mode & 0xFF80) == 0x1F80) &&
((fenv.x87_mode & 0x1F3F) == 0x003A || (fenv.x87_mode & 0x1F3F) == 0x003F);
#endif
((fenv.x87_mode & 0x1F3F) == 0x003A || (fenv.x87_mode & 0x1F3F) == 0x003F);
#endif
if (!ret) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"Sync warning: MXCSR 0x%04X instead of 0x1D00 or 0x1F80 (\"%s\")", fenv.sse_mode, outText);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"Sync warning: FPUCW 0x%04X instead of 0x003A or 0x003F (\"%s\")", fenv.x87_mode, outText);
SystemFlags::OutputDebug(SystemFlags::debugSystem, "Sync warning: MXCSR 0x%04X instead of 0x1D00 or 0x1F80 (\"%s\")", fenv.sse_mode, outText);
SystemFlags::OutputDebug(SystemFlags::debugSystem, "Sync warning: FPUCW 0x%04X instead of 0x003A or 0x003F (\"%s\")", fenv.x87_mode, outText);
// Set single precision floating point math.
streflop_init<streflop::Simple>();
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
#endif
#endif
}
#elif defined(STREFLOP_X87)
fenv_t fenv;
fegetenv(&fenv);
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
bool ret = (fenv & 0x1F3F) == 0x0072 || (fenv & 0x1F3F) == 0x003F;
#else
#else
bool ret = (fenv & 0x1F3F) == 0x003A || (fenv & 0x1F3F) == 0x003F;
#endif
#endif
if (!ret) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"Sync warning: FPUCW 0x%04X instead of 0x003A or 0x003F (\"%s\")", fenv, outText);
SystemFlags::OutputDebug(SystemFlags::debugSystem, "Sync warning: FPUCW 0x%04X instead of 0x003A or 0x003F (\"%s\")", fenv, outText);
// Set single precision floating point math.
streflop_init<streflop::Simple>();
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
#endif
#endif
}
#endif
}

View File

@@ -1,13 +1,13 @@
/*
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2012 Mark Vejvoda
Code released according to the GNU Lesser General Public License
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2012 Mark Vejvoda
Code released according to the GNU Lesser General Public License
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Please read the history and copyright information in the documentation provided with the source code
Please read the history and copyright information in the documentation provided with the source code
*/
/*
@@ -53,13 +53,13 @@
namespace streflop {
// We do not use libm, so let's copy a few flags and C99 functions
// Give warning in case these flags would be defined already, this is indication
// of potential confusion!
// We do not use libm, so let's copy a few flags and C99 functions
// Give warning in case these flags would be defined already, this is indication
// of potential confusion!
#if defined(FE_INVALID) || defined(FE_DENORMAL) || defined(FE_DIVBYZERO) || defined(FE_OVERFLOW) || defined(FE_UNDERFLOW) || defined(FE_INEXACT) || defined(FE_DOWNWARD) || defined(FE_TONEAREST) || defined(FE_TOWARDZERO) || defined(FE_UPWARD)
#warning STREFLOP: FE_XXX flags were already defined and will be redefined! Check you do not use the system libm.
#warning STREFLOP : FE_XXX flags were already defined and will be redefined!Check you do not use the system libm.
#undef FE_INVALID
#undef FE_DENORMAL
#undef FE_DIVBYZERO
@@ -75,74 +75,74 @@ namespace streflop {
#endif // defined(FE_INVALID) || ...
// Flags for FPU exceptions
enum FPU_Exceptions {
// Flags for FPU exceptions
enum FPU_Exceptions {
// Invalid operation. If not signaling, gives NaN instead
FE_INVALID = 0x0001,
#define FE_INVALID FE_INVALID
// Invalid operation. If not signaling, gives NaN instead
FE_INVALID = 0x0001,
#define FE_INVALID FE_INVALID
// Extension: for x86 and SSE
// Denormal operand. If not signaling, use denormal arithmetic as usual
FE_DENORMAL = 0x0002,
#define FE_DENORMAL FE_DENORMAL
// Extension: for x86 and SSE
// Denormal operand. If not signaling, use denormal arithmetic as usual
FE_DENORMAL = 0x0002,
#define FE_DENORMAL FE_DENORMAL
// Division by zero. If not signaling, uses +/- infinity
FE_DIVBYZERO = 0x0004,
#define FE_DIVBYZERO FE_DIVBYZERO
// Division by zero. If not signaling, uses +/- infinity
FE_DIVBYZERO = 0x0004,
#define FE_DIVBYZERO FE_DIVBYZERO
// Overflow. If not signaling, round to nearest (including infinity) according to rounding mode
FE_OVERFLOW = 0x0008,
#define FE_OVERFLOW FE_OVERFLOW
// Overflow. If not signaling, round to nearest (including infinity) according to rounding mode
FE_OVERFLOW = 0x0008,
#define FE_OVERFLOW FE_OVERFLOW
// Underflow. If not signaling, use 0 instead
FE_UNDERFLOW = 0x0010,
#define FE_UNDERFLOW FE_UNDERFLOW
// Underflow. If not signaling, use 0 instead
FE_UNDERFLOW = 0x0010,
#define FE_UNDERFLOW FE_UNDERFLOW
// Rounding was not exact (ex: sqrt(2) is never exact) or when overflow causes rounding
FE_INEXACT = 0x0020,
#define FE_INEXACT FE_INEXACT
// Rounding was not exact (ex: sqrt(2) is never exact) or when overflow causes rounding
FE_INEXACT = 0x0020,
#define FE_INEXACT FE_INEXACT
// Combination of all the above
FE_ALL_EXCEPT = 0x003F
#define FE_ALL_EXCEPT FE_ALL_EXCEPT
};
// Combination of all the above
FE_ALL_EXCEPT = 0x003F
#define FE_ALL_EXCEPT FE_ALL_EXCEPT
};
// Flags for FPU rounding modes
enum FPU_RoundMode {
FE_TONEAREST = 0x0000,
#define FE_TONEAREST FE_TONEAREST
// Flags for FPU rounding modes
enum FPU_RoundMode {
FE_TONEAREST = 0x0000,
#define FE_TONEAREST FE_TONEAREST
FE_DOWNWARD = 0x0400,
#define FE_DOWNWARD FE_DOWNWARD
FE_DOWNWARD = 0x0400,
#define FE_DOWNWARD FE_DOWNWARD
FE_UPWARD = 0x0800,
#define FE_UPWARD FE_UPWARD
FE_UPWARD = 0x0800,
#define FE_UPWARD FE_UPWARD
FE_TOWARDZERO = 0x0C00
#define FE_TOWARDZERO FE_TOWARDZERO
};
FE_TOWARDZERO = 0x0C00
#define FE_TOWARDZERO FE_TOWARDZERO
};
/* Note: SSE control word, bits 0..15
0->5: Run-time status flags
6: DAZ (denormals are zero, i.e. don't use denormals if bit is 1)
7->12: Exception flags, same meaning as for the x87 ones
13,14: Rounding flags, same meaning as for the x87 ones
15: Flush to zero (FTZ) for automatic handling of underflow (default is NO)
*/
/* Note: SSE control word, bits 0..15
0->5: Run-time status flags
6: DAZ (denormals are zero, i.e. don't use denormals if bit is 1)
7->12: Exception flags, same meaning as for the x87 ones
13,14: Rounding flags, same meaning as for the x87 ones
15: Flush to zero (FTZ) for automatic handling of underflow (default is NO)
*/
// plan for portability
// plan for portability
#if defined(_MSC_VER)
#if _WIN64
// No fldcw intrinsics on Windows x64, punt to external asm
// Seems like using unsigned is better on windows x64: http://www.virtualdub.org/blog/pivot/entry.php?id=340
extern "C" { void streflop_winx64_fldcw(unsigned short mode); }
extern "C" { unsigned short streflop_winx64_fstcw(); }
extern "C" { void streflop_winx64_fclex(void); }
extern "C" { void streflop_winx64_stmxcsr(unsigned int mode); }
extern "C" { void streflop_winx64_ldmxcsr(unsigned int mode); }
extern "C" { void streflop_winx64_fldcw(unsigned short mode); }
extern "C" { unsigned short streflop_winx64_fstcw(); }
extern "C" { void streflop_winx64_fclex(void); }
extern "C" { void streflop_winx64_stmxcsr(unsigned int mode); }
extern "C" { void streflop_winx64_ldmxcsr(unsigned int mode); }
#define STREFLOP_FSTCW(cw) do { short tmp = 0; tmp = streflop_winx64_fstcw(); (cw) = tmp; } while (0)
#define STREFLOP_FLDCW(cw) do { short tmp = (cw); streflop_winx64_fldcw(tmp); } while (0)
@@ -172,381 +172,382 @@ extern "C" { void streflop_winx64_ldmxcsr(unsigned int mode); }
#if defined(STREFLOP_X87)
/// Raise exception for these flags
inline int feraiseexcept(FPU_Exceptions excepts) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= ~( excepts ); // generate error for selection
STREFLOP_FLDCW(fpu_mode);
return 0;
}
inline int feraiseexcept(FPU_Exceptions excepts) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= ~(excepts); // generate error for selection
STREFLOP_FLDCW(fpu_mode);
return 0;
}
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode |= excepts;
STREFLOP_FLDCW(fpu_mode);
return 0;
}
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode |= excepts;
STREFLOP_FLDCW(fpu_mode);
return 0;
}
/// Get current rounding mode
inline int fegetround() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
return fpu_mode & 0x0C00;
}
/// Get current rounding mode
inline int fegetround() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
return fpu_mode & 0x0C00;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xF3FF; // clear current mode
fpu_mode |= roundMode; // sets new mode
STREFLOP_FLDCW(fpu_mode);
return 0;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xF3FF; // clear current mode
fpu_mode |= roundMode; // sets new mode
STREFLOP_FLDCW(fpu_mode);
return 0;
}
typedef short int fenv_t;
typedef short int fenv_t;
/// Default env. Defined in Math.cpp to be 0, and initalized on first use to the permanent holder
extern fenv_t FE_DFL_ENV;
/// Default env. Defined in Math.cpp to be 0, and initalized on first use to the permanent holder
extern fenv_t FE_DFL_ENV;
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV) STREFLOP_FSTCW(FE_DFL_ENV);
// Now store env into argument
STREFLOP_FSTCW(*envp);
return 0;
}
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV) STREFLOP_FSTCW(FE_DFL_ENV);
// Now store env into argument
STREFLOP_FSTCW(*envp);
return 0;
}
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV) STREFLOP_FSTCW(FE_DFL_ENV);
// Now overwrite current env by argument
STREFLOP_FLDCW(*envp);
return 0;
}
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV) STREFLOP_FSTCW(FE_DFL_ENV);
// Now overwrite current env by argument
STREFLOP_FLDCW(*envp);
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
template<typename T> inline void streflop_init() {
struct X {};
X Unknown_numeric_type;
// unknown types do not compile
T error = Unknown_numeric_type;
}
template<typename T> inline void streflop_init() {
struct X {
};
X Unknown_numeric_type;
// unknown types do not compile
T error = Unknown_numeric_type;
}
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF; // 32 bits internal operations
STREFLOP_FLDCW(fpu_mode);
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF; // 32 bits internal operations
STREFLOP_FLDCW(fpu_mode);
// Enable signaling nans if compiled with this option.
// Enable signaling nans if compiled with this option.
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
#endif
}
}
template<> inline void streflop_init<Double>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF;
fpu_mode |= 0x0200; // 64 bits internal operations
STREFLOP_FLDCW(fpu_mode);
template<> inline void streflop_init<Double>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF;
fpu_mode |= 0x0200; // 64 bits internal operations
STREFLOP_FLDCW(fpu_mode);
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
#endif
}
}
#if defined(Extended)
template<> inline void streflop_init<Extended>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF;
fpu_mode |= 0x0300; // 80 bits internal operations
STREFLOP_FLDCW(fpu_mode);
template<> inline void streflop_init<Extended>() {
unsigned short fpu_mode;
STREFLOP_FSTCW(fpu_mode);
fpu_mode &= 0xFCFF;
fpu_mode |= 0x0300; // 80 bits internal operations
STREFLOP_FLDCW(fpu_mode);
#if defined(__SUPPORT_SNAN__) && !defined(USE_GML)
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
feraiseexcept(streflop::FPU_Exceptions(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW));
#endif
}
}
#endif // defined(Extended)
#elif defined(STREFLOP_SSE)
/// Raise exception for these flags
inline int feraiseexcept(FPU_Exceptions excepts) {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= ~( excepts ); // generate error for selection
STREFLOP_FLDCW(x87_mode);
inline int feraiseexcept(FPU_Exceptions excepts) {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= ~(excepts); // generate error for selection
STREFLOP_FLDCW(x87_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode &= ~( excepts << 7 ); // generate error for selection
STREFLOP_LDMXCSR(sse_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode &= ~(excepts << 7); // generate error for selection
STREFLOP_LDMXCSR(sse_mode);
return 0;
}
return 0;
}
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode |= excepts;
STREFLOP_FLDCW(x87_mode);
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode |= excepts;
STREFLOP_FLDCW(x87_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode |= excepts << 7;
STREFLOP_LDMXCSR(sse_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode |= excepts << 7;
STREFLOP_LDMXCSR(sse_mode);
return 0;
}
return 0;
}
/// Get current rounding mode
inline int fegetround() {
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
return (sse_mode>>3) & 0x00000C00;
}
/// Get current rounding mode
inline int fegetround() {
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
return (sse_mode >> 3) & 0x00000C00;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode &= 0xFFFF9FFF; // clear current mode
sse_mode |= roundMode<<3; // sets new mode
STREFLOP_LDMXCSR(sse_mode);
return 0;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
sse_mode &= 0xFFFF9FFF; // clear current mode
sse_mode |= roundMode << 3; // sets new mode
STREFLOP_LDMXCSR(sse_mode);
return 0;
}
/// stores both x87 and SSE words
struct fenv_t {
int sse_mode;
short int x87_mode;
};
/// stores both x87 and SSE words
struct fenv_t {
int sse_mode;
short int x87_mode;
};
/// Default env. Defined in Math.cpp, structs are initialized to 0
extern fenv_t FE_DFL_ENV;
/// Default env. Defined in Math.cpp, structs are initialized to 0
extern fenv_t FE_DFL_ENV;
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV.x87_mode) STREFLOP_FSTCW(FE_DFL_ENV.x87_mode);
// Now store env into argument
STREFLOP_FSTCW(envp->x87_mode);
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV.x87_mode) STREFLOP_FSTCW(FE_DFL_ENV.x87_mode);
// Now store env into argument
STREFLOP_FSTCW(envp->x87_mode);
// For SSE
if (!FE_DFL_ENV.sse_mode) STREFLOP_STMXCSR(FE_DFL_ENV.sse_mode);
// Now store env into argument
STREFLOP_STMXCSR(envp->sse_mode);
return 0;
}
// For SSE
if (!FE_DFL_ENV.sse_mode) STREFLOP_STMXCSR(FE_DFL_ENV.sse_mode);
// Now store env into argument
STREFLOP_STMXCSR(envp->sse_mode);
return 0;
}
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV.x87_mode) STREFLOP_FSTCW(FE_DFL_ENV.x87_mode);
// Now overwrite current env by argument
STREFLOP_FLDCW(envp->x87_mode);
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (!FE_DFL_ENV.x87_mode) STREFLOP_FSTCW(FE_DFL_ENV.x87_mode);
// Now overwrite current env by argument
STREFLOP_FLDCW(envp->x87_mode);
// For SSE
if (!FE_DFL_ENV.sse_mode) STREFLOP_STMXCSR(FE_DFL_ENV.sse_mode);
// Now overwrite current env by argument
STREFLOP_LDMXCSR(envp->sse_mode);
return 0;
}
// For SSE
if (!FE_DFL_ENV.sse_mode) STREFLOP_STMXCSR(FE_DFL_ENV.sse_mode);
// Now overwrite current env by argument
STREFLOP_LDMXCSR(envp->sse_mode);
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
template<typename T> inline void streflop_init() {
// Do nothing by default, or for unknown types
}
template<typename T> inline void streflop_init() {
// Do nothing by default, or for unknown types
}
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF; // 32 bits internal operations
STREFLOP_FLDCW(x87_mode);
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF; // 32 bits internal operations
STREFLOP_FLDCW(x87_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
#if defined(STREFLOP_NO_DENORMALS)
sse_mode |= 0x8040; // set DAZ and FTZ
sse_mode |= 0x8040; // set DAZ and FTZ
#else
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
#endif
STREFLOP_LDMXCSR(sse_mode);
}
STREFLOP_LDMXCSR(sse_mode);
}
template<> inline void streflop_init<Double>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF;
x87_mode |= 0x0200; // 64 bits internal operations
STREFLOP_FLDCW(x87_mode);
template<> inline void streflop_init<Double>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF;
x87_mode |= 0x0200; // 64 bits internal operations
STREFLOP_FLDCW(x87_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
#if defined(STREFLOP_NO_DENORMALS)
sse_mode |= 0x8040; // set DAZ and FTZ
sse_mode |= 0x8040; // set DAZ and FTZ
#else
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
#endif
STREFLOP_LDMXCSR(sse_mode);
}
STREFLOP_LDMXCSR(sse_mode);
}
#if defined(Extended)
template<> inline void streflop_init<Extended>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF;
x87_mode |= 0x0300; // 80 bits internal operations
STREFLOP_FLDCW(x87_mode);
template<> inline void streflop_init<Extended>() {
// Just in case the compiler would store a value on the st(x) registers
unsigned short x87_mode;
STREFLOP_FSTCW(x87_mode);
x87_mode &= 0xFCFF;
x87_mode |= 0x0300; // 80 bits internal operations
STREFLOP_FLDCW(x87_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
int sse_mode;
STREFLOP_STMXCSR(sse_mode);
#if defined(STREFLOP_NO_DENORMALS)
sse_mode |= 0x8040; // set DAZ and FTZ
sse_mode |= 0x8040; // set DAZ and FTZ
#else
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
sse_mode &= 0xFFFF7FBF; // clear DAZ and FTZ
#endif
STREFLOP_LDMXCSR(sse_mode);
}
STREFLOP_LDMXCSR(sse_mode);
}
#endif // defined(Extended)
#elif defined(STREFLOP_SOFT)
/// Raise exception for these flags
inline int feraiseexcept(FPU_Exceptions excepts) {
// Use positive logic
SoftFloat::float_exception_realtraps |= excepts;
return 0;
}
inline int feraiseexcept(FPU_Exceptions excepts) {
// Use positive logic
SoftFloat::float_exception_realtraps |= excepts;
return 0;
}
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
// Use positive logic
SoftFloat::float_exception_realtraps &= ~( excepts );
return 0;
}
/// Clear exceptions for these flags
inline int feclearexcept(int excepts) {
// Use positive logic
SoftFloat::float_exception_realtraps &= ~(excepts);
return 0;
}
/// Get current rounding mode
inline int fegetround() {
// see softfloat.h for the definition
switch (SoftFloat::float_rounding_mode) {
case SoftFloat::float_round_down: return FE_DOWNWARD;
case SoftFloat::float_round_up: return FE_UPWARD;
case SoftFloat::float_round_to_zero: return FE_TOWARDZERO;
default:; // is also initial mode
}
// case SoftFloat::float_round_nearest_even:
return FE_TONEAREST;
}
/// Get current rounding mode
inline int fegetround() {
// see softfloat.h for the definition
switch (SoftFloat::float_rounding_mode) {
case SoftFloat::float_round_down: return FE_DOWNWARD;
case SoftFloat::float_round_up: return FE_UPWARD;
case SoftFloat::float_round_to_zero: return FE_TOWARDZERO;
default:; // is also initial mode
}
// case SoftFloat::float_round_nearest_even:
return FE_TONEAREST;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
// see softfloat.h for the definition
switch (roundMode) {
case FE_DOWNWARD: SoftFloat::float_rounding_mode = SoftFloat::float_round_down; return 0;
case FE_UPWARD: SoftFloat::float_rounding_mode = SoftFloat::float_round_up; return 0;
case FE_TOWARDZERO: SoftFloat::float_rounding_mode = SoftFloat::float_round_to_zero; return 0;
case FE_TONEAREST: SoftFloat::float_rounding_mode = SoftFloat::float_round_nearest_even; return 0;
}
// Error, invalid mode
return 1;
}
/// Set a new rounding mode
inline int fesetround(FPU_RoundMode roundMode) {
// see softfloat.h for the definition
switch (roundMode) {
case FE_DOWNWARD: SoftFloat::float_rounding_mode = SoftFloat::float_round_down; return 0;
case FE_UPWARD: SoftFloat::float_rounding_mode = SoftFloat::float_round_up; return 0;
case FE_TOWARDZERO: SoftFloat::float_rounding_mode = SoftFloat::float_round_to_zero; return 0;
case FE_TONEAREST: SoftFloat::float_rounding_mode = SoftFloat::float_round_nearest_even; return 0;
}
// Error, invalid mode
return 1;
}
/// SoftFloat environment comprises non-volatile state variables
struct fenv_t {
char tininess;
char rounding_mode;
int exception_realtraps;
};
/// SoftFloat environment comprises non-volatile state variables
struct fenv_t {
char tininess;
char rounding_mode;
int exception_realtraps;
};
/// Default env. Defined in Math.cpp, initialized to some invalid value for detection
extern fenv_t FE_DFL_ENV;
/// Default env. Defined in Math.cpp, initialized to some invalid value for detection
extern fenv_t FE_DFL_ENV;
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (FE_DFL_ENV.tininess==42) {
// First use: save default environment now
FE_DFL_ENV.tininess = SoftFloat::float_detect_tininess;
FE_DFL_ENV.rounding_mode = SoftFloat::float_rounding_mode;
FE_DFL_ENV.exception_realtraps = SoftFloat::float_exception_realtraps;
}
// Now get the current env in the given argument
envp->tininess = SoftFloat::float_detect_tininess;
envp->rounding_mode = SoftFloat::float_rounding_mode;
envp->exception_realtraps = SoftFloat::float_exception_realtraps;
return 0;
}
/// Get FP env into the given structure
inline int fegetenv(fenv_t *envp) {
// check that default env exists, otherwise save it now
if (FE_DFL_ENV.tininess == 42) {
// First use: save default environment now
FE_DFL_ENV.tininess = SoftFloat::float_detect_tininess;
FE_DFL_ENV.rounding_mode = SoftFloat::float_rounding_mode;
FE_DFL_ENV.exception_realtraps = SoftFloat::float_exception_realtraps;
}
// Now get the current env in the given argument
envp->tininess = SoftFloat::float_detect_tininess;
envp->rounding_mode = SoftFloat::float_rounding_mode;
envp->exception_realtraps = SoftFloat::float_exception_realtraps;
return 0;
}
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (FE_DFL_ENV.tininess==42) {
// First use: save default environment now
FE_DFL_ENV.tininess = SoftFloat::float_detect_tininess;
FE_DFL_ENV.rounding_mode = SoftFloat::float_rounding_mode;
FE_DFL_ENV.exception_realtraps = SoftFloat::float_exception_realtraps;
}
// Now get the current env in the given argument
SoftFloat::float_detect_tininess = envp->tininess;
SoftFloat::float_rounding_mode = envp->rounding_mode;
SoftFloat::float_exception_realtraps = envp->exception_realtraps;
return 0;
}
/// Sets FP env from the given structure
inline int fesetenv(const fenv_t *envp) {
// check that default env exists, otherwise save it now
if (FE_DFL_ENV.tininess == 42) {
// First use: save default environment now
FE_DFL_ENV.tininess = SoftFloat::float_detect_tininess;
FE_DFL_ENV.rounding_mode = SoftFloat::float_rounding_mode;
FE_DFL_ENV.exception_realtraps = SoftFloat::float_exception_realtraps;
}
// Now get the current env in the given argument
SoftFloat::float_detect_tininess = envp->tininess;
SoftFloat::float_rounding_mode = envp->rounding_mode;
SoftFloat::float_exception_realtraps = envp->exception_realtraps;
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
/// get env and clear exceptions
inline int feholdexcept(fenv_t *envp) {
fegetenv(envp);
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
template<typename T> inline void streflop_init() {
// Do nothing by default, or for unknown types
}
template<typename T> inline void streflop_init() {
// Do nothing by default, or for unknown types
}
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
}
template<> inline void streflop_init<Double>() {
}
template<> inline void streflop_init<Extended>() {
}
/// Initialize the FPU for the different types
/// this may also be called to switch between code sections using
/// different precisions
template<> inline void streflop_init<Simple>() {
}
template<> inline void streflop_init<Double>() {
}
template<> inline void streflop_init<Extended>() {
}
#else // defined(STREFLOP_X87)
#error STREFLOP: Invalid combination or unknown FPU type.

View File

@@ -1,13 +1,13 @@
/*
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2012 Mark Vejvoda
Code released according to the GNU Lesser General Public License
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2012 Mark Vejvoda
Code released according to the GNU Lesser General Public License
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Please read the history and copyright information in the documentation provided with the source code
Please read the history and copyright information in the documentation provided with the source code
*/
#ifndef STREFLOP_INTEGER_TYPES_H
@@ -27,113 +27,113 @@
// Avoid conflict with system types, if any
namespace streflop {
// Template meta-programming: this is the "program" which variables are types and constants are int template arguments
// Algorithm: provide an expected size, and recursively increase the integer types till the size match
template<typename int_type, int expected_size, bool final_recursion> struct SizedTypeMaker {
};
// Template meta-programming: this is the "program" which variables are types and constants are int template arguments
// Algorithm: provide an expected size, and recursively increase the integer types till the size match
template<typename int_type, int expected_size, bool final_recursion> struct SizedTypeMaker {
};
// start by long long to provide the recursion terminal condition
// start by long long to provide the recursion terminal condition
// false : the expected_size does not exist: do not define a type, there will be a compilation error
template<int expected_size> struct SizedTypeMaker<long long, expected_size, false> {
// Error: Integer type with expected size does not exist
};
// false : the expected_size does not exist: do not define a type, there will be a compilation error
template<int expected_size> struct SizedTypeMaker<long long, expected_size, false> {
// Error: Integer type with expected size does not exist
};
// true: end recursion by defining the correct type to be long long
template<int expected_size> struct SizedTypeMaker<long long, expected_size, true> {
typedef long long final_type;
};
// true: end recursion by defining the correct type to be long long
template<int expected_size> struct SizedTypeMaker<long long, expected_size, true> {
typedef long long final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<long, expected_size, false> {
typedef typename SizedTypeMaker<long long, expected_size, (sizeof(long long)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<long, expected_size, false> {
typedef typename SizedTypeMaker<long long, expected_size, (sizeof(long long) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be long
template<int expected_size> struct SizedTypeMaker<long, expected_size, true> {
typedef long final_type;
};
// true: end recursion by defining the correct type to be long
template<int expected_size> struct SizedTypeMaker<long, expected_size, true> {
typedef long final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<int, expected_size, false> {
typedef typename SizedTypeMaker<long, expected_size, (sizeof(long)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<int, expected_size, false> {
typedef typename SizedTypeMaker<long, expected_size, (sizeof(long) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be int
template<int expected_size> struct SizedTypeMaker<int, expected_size, true> {
typedef int final_type;
};
// true: end recursion by defining the correct type to be int
template<int expected_size> struct SizedTypeMaker<int, expected_size, true> {
typedef int final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<short, expected_size, false> {
typedef typename SizedTypeMaker<int, expected_size, (sizeof(int)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<short, expected_size, false> {
typedef typename SizedTypeMaker<int, expected_size, (sizeof(int) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be short
template<int expected_size> struct SizedTypeMaker<short, expected_size, true> {
typedef short final_type;
};
// true: end recursion by defining the correct type to be short
template<int expected_size> struct SizedTypeMaker<short, expected_size, true> {
typedef short final_type;
};
// Do it again for unsigned types
// Do it again for unsigned types
// false : the expected_size does not exist: do not define a type, there will be a compilation error
template<int expected_size> struct SizedTypeMaker<unsigned long long, expected_size, false> {
// Error: Integer type with expected size does not exist
};
// false : the expected_size does not exist: do not define a type, there will be a compilation error
template<int expected_size> struct SizedTypeMaker<unsigned long long, expected_size, false> {
// Error: Integer type with expected size does not exist
};
// true: end recursion by defining the correct type to be long long
template<int expected_size> struct SizedTypeMaker<unsigned long long, expected_size, true> {
typedef unsigned long long final_type;
};
// true: end recursion by defining the correct type to be long long
template<int expected_size> struct SizedTypeMaker<unsigned long long, expected_size, true> {
typedef unsigned long long final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned long, expected_size, false> {
typedef typename SizedTypeMaker<unsigned long long, expected_size, (sizeof(unsigned long long)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned long, expected_size, false> {
typedef typename SizedTypeMaker<unsigned long long, expected_size, (sizeof(unsigned long long) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be long
template<int expected_size> struct SizedTypeMaker<unsigned long, expected_size, true> {
typedef unsigned long final_type;
};
// true: end recursion by defining the correct type to be long
template<int expected_size> struct SizedTypeMaker<unsigned long, expected_size, true> {
typedef unsigned long final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned int, expected_size, false> {
typedef typename SizedTypeMaker<unsigned long, expected_size, (sizeof(unsigned long)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned int, expected_size, false> {
typedef typename SizedTypeMaker<unsigned long, expected_size, (sizeof(unsigned long) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be int
template<int expected_size> struct SizedTypeMaker<unsigned int, expected_size, true> {
typedef unsigned int final_type;
};
// true: end recursion by defining the correct type to be int
template<int expected_size> struct SizedTypeMaker<unsigned int, expected_size, true> {
typedef unsigned int final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned short, expected_size, false> {
typedef typename SizedTypeMaker<unsigned int, expected_size, (sizeof(unsigned int)==expected_size)>::final_type final_type;
};
// false : recurse by increasing the integer type till it reaches the expected size
template<int expected_size> struct SizedTypeMaker<unsigned short, expected_size, false> {
typedef typename SizedTypeMaker<unsigned int, expected_size, (sizeof(unsigned int) == expected_size)>::final_type final_type;
};
// true: end recursion by defining the correct type to be short
template<int expected_size> struct SizedTypeMaker<unsigned short, expected_size, true> {
typedef unsigned short final_type;
};
// true: end recursion by defining the correct type to be short
template<int expected_size> struct SizedTypeMaker<unsigned short, expected_size, true> {
typedef unsigned short final_type;
};
// Utility to get an int type with the selected size IN BITS
template<int N> struct SizedInteger {
typedef typename SizedTypeMaker<short, (N/STREFLOP_INTEGER_TYPES_CHAR_BITS), (sizeof(short)==(N/STREFLOP_INTEGER_TYPES_CHAR_BITS))>::final_type Type;
};
template<int N> struct SizedUnsignedInteger {
typedef typename SizedTypeMaker<unsigned short, (N/STREFLOP_INTEGER_TYPES_CHAR_BITS), (sizeof(unsigned short)==(N/STREFLOP_INTEGER_TYPES_CHAR_BITS))>::final_type Type;
};
// Utility to get an int type with the selected size IN BITS
template<int N> struct SizedInteger {
typedef typename SizedTypeMaker<short, (N / STREFLOP_INTEGER_TYPES_CHAR_BITS), (sizeof(short) == (N / STREFLOP_INTEGER_TYPES_CHAR_BITS))>::final_type Type;
};
template<int N> struct SizedUnsignedInteger {
typedef typename SizedTypeMaker<unsigned short, (N / STREFLOP_INTEGER_TYPES_CHAR_BITS), (sizeof(unsigned short) == (N / STREFLOP_INTEGER_TYPES_CHAR_BITS))>::final_type Type;
};
// Specialize for size = STREFLOP_INTEGER_TYPES_CHAR_BITS
// Specialize for size = STREFLOP_INTEGER_TYPES_CHAR_BITS
template<> struct SizedInteger<STREFLOP_INTEGER_TYPES_CHAR_BITS> {
typedef char Type;
};
template<> struct SizedInteger<STREFLOP_INTEGER_TYPES_CHAR_BITS> {
typedef char Type;
};
template<> struct SizedUnsignedInteger<STREFLOP_INTEGER_TYPES_CHAR_BITS> {
typedef unsigned char Type;
};
template<> struct SizedUnsignedInteger<STREFLOP_INTEGER_TYPES_CHAR_BITS> {
typedef unsigned char Type;
};
}

View File

@@ -1,14 +1,14 @@
/*
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2010 Mark Vejvoda
streflop: STandalone REproducible FLOating-Point
Copyright 2006 Nicolas Brodu
2010 Mark Vejvoda
Code released according to the GNU Lesser General Public License
Code released according to the GNU Lesser General Public License
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Heavily relies on GNU Libm, itself depending on netlib fplibm, GNU MP, and IBM MP lib.
Uses SoftFloat too.
Please read the history and copyright information in the documentation provided with the source code
Please read the history and copyright information in the documentation provided with the source code
*/
#ifndef RANDOM_H
@@ -19,107 +19,115 @@
namespace streflop {
/** Random state holder object
Declare one of this per thread, and use it as context to the random functions
Object is properly set by the RandomInit functions
This allows it to remain POD type
*/
struct RandomState {
/** Random state holder object
Declare one of this per thread, and use it as context to the random functions
Object is properly set by the RandomInit functions
This allows it to remain POD type
*/
struct RandomState {
#if !defined(STREFLOP_RANDOM_GEN_SIZE)
#define STREFLOP_RANDOM_GEN_SIZE 32
#endif
// state vector
SizedUnsignedInteger<STREFLOP_RANDOM_GEN_SIZE>::Type mt[19968/STREFLOP_RANDOM_GEN_SIZE];
int mti;
// random seed that was used for initialization
SizedUnsignedInteger<32>::Type seed;
}
// state vector
SizedUnsignedInteger<STREFLOP_RANDOM_GEN_SIZE>::Type mt[19968 / STREFLOP_RANDOM_GEN_SIZE];
int mti;
// random seed that was used for initialization
SizedUnsignedInteger<32>::Type seed;
}
#ifdef __GNUC__
__attribute__ ((aligned (64))) // align state vector on cache line size
__attribute__((aligned(64))) // align state vector on cache line size
#endif
;
;
/// Default random state holder
extern RandomState DefaultRandomState;
/// Default random state holder
extern RandomState DefaultRandomState;
/** Initialize the random number generator with the given seed.
/** Initialize the random number generator with the given seed.
By default, the seed is taken from system time and printed out
so the experiment is reproducible by inputing the same seed again.
By default, the seed is taken from system time and printed out
so the experiment is reproducible by inputing the same seed again.
You can set here a previous seed to reproduce it.
You can set here a previous seed to reproduce it.
This interface allows independance from the actual RNG used,
and/or system functions.
This interface allows independance from the actual RNG used,
and/or system functions.
The RNG used is the Mersenne twister implementation by the
original authors Takuji Nishimura and Makoto Matsumoto.
The RNG used is the Mersenne twister implementation by the
original authors Takuji Nishimura and Makoto Matsumoto.
See also Random.cpp for more information.
*/
SizedUnsignedInteger<32>::Type RandomInit(RandomState& state = DefaultRandomState);
SizedUnsignedInteger<32>::Type RandomInit(SizedUnsignedInteger<32>::Type seed, RandomState& state = DefaultRandomState);
See also Random.cpp for more information.
*/
SizedUnsignedInteger<32>::Type RandomInit(RandomState& state = DefaultRandomState);
SizedUnsignedInteger<32>::Type RandomInit(SizedUnsignedInteger<32>::Type seed, RandomState& state = DefaultRandomState);
/// Returns the random seed that was used for the initialization
/// Defaults to 0 if the RNG is not yet initialized
SizedUnsignedInteger<32>::Type RandomSeed(RandomState& state = DefaultRandomState);
/// Returns the random seed that was used for the initialization
/// Defaults to 0 if the RNG is not yet initialized
SizedUnsignedInteger<32>::Type RandomSeed(RandomState& state = DefaultRandomState);
/** Returns a random number from a uniform distribution.
/** Returns a random number from a uniform distribution.
All integer types are supported, as well as Simple, Double, and Extended
All integer types are supported, as well as Simple, Double, and Extended
The Random(min, max) template takes as argument:
- bool: whether or not including the min bound
- bool: whether or not including the max bound
- type: to generate a number from that type, and decide on min/max bounds
Example: Double x = Random<true, false, Double>(7.0, 18.0)
This will return a Double number between 7.0 (included) and 18.0 (excluded)
This works for both float and integer types.
The Random(min, max) template takes as argument:
- bool: whether or not including the min bound
- bool: whether or not including the max bound
- type: to generate a number from that type, and decide on min/max bounds
Example: Double x = Random<true, false, Double>(7.0, 18.0)
This will return a Double number between 7.0 (included) and 18.0 (excluded)
This works for both float and integer types.
Aliases are named like RandomXY with X,Y = E,I for bounds Excluded,Included.
Example: RandomEI(min,max) will return a number between min (excluded) and max (included).
Aliases are named like RandomXY with X,Y = E,I for bounds Excluded,Included.
Example: RandomEI(min,max) will return a number between min (excluded) and max (included).
The Random() template returns a number of the given type chosen uniformly between
all representable numbers of that type.
- For integer types, this means what you expect: any int, char, whatever on the whole range
- For float types, just recall that there are as many representable floats in each range
2^x - 2^(x+1), this is what floating-point means
The Random() template returns a number of the given type chosen uniformly between
all representable numbers of that type.
- For integer types, this means what you expect: any int, char, whatever on the whole range
- For float types, just recall that there are as many representable floats in each range
2^x - 2^(x+1), this is what floating-point means
Notes:
- If min > max then the result is undefined.
- If you ask for an empty interval (like RandomEE with min==max) then the result is undefined.
- If a NaN value is passed to the float functions, NaN is returned.
- By order of performance, for float types, IE is fastest, then EI, then EE, then II. For integer
types, it happens that the order is II, IE and EI ex-aequo, and EE, but the difference is much
less pronounced than for the float types. Use IE preferably for floats, II for ints.
Notes:
- If min > max then the result is undefined.
- If you ask for an empty interval (like RandomEE with min==max) then the result is undefined.
- If a NaN value is passed to the float functions, NaN is returned.
- By order of performance, for float types, IE is fastest, then EI, then EE, then II. For integer
types, it happens that the order is II, IE and EI ex-aequo, and EE, but the difference is much
less pronounced than for the float types. Use IE preferably for floats, II for ints.
The floating-point functions always compute a random number with the maximum digits of precision,
taking care of bounds. That is, it uses the 1-2 interval as this is a power-of-two bounded interval,
so each representable number in that interval (matching a distinct bit pattern) is given exactly
the same weight. This is really a truly uniform distribution, unlike the 0-1 range (see note below).
That 1-2 interval is then converted to the min-max range, hopefully resulting in the loss of as
few random bits as possible. See also the additional functions below for better performance.
The floating-point functions always compute a random number with the maximum digits of precision,
taking care of bounds. That is, it uses the 1-2 interval as this is a power-of-two bounded interval,
so each representable number in that interval (matching a distinct bit pattern) is given exactly
the same weight. This is really a truly uniform distribution, unlike the 0-1 range (see note below).
That 1-2 interval is then converted to the min-max range, hopefully resulting in the loss of as
few random bits as possible. See also the additional functions below for better performance.
Note: Getting numbers in the 0-1 interval may be tricky. Half the 2^X exponents are in that range as
well as denormal numbers. This could result in an horrible loss of bits when scaling from one exponent
to another. Fortunately, the numbers in 1-2 are generated with maximum precision, and then subtracting 1.0
to get a number in 0-1 keeps that precision because all the numbers obtained this way are still perfectly
representable. Moreover, the minimum exponent reached this way is still far above the denormals range.
Note: Getting numbers in the 0-1 interval may be tricky. Half the 2^X exponents are in that range as
well as denormal numbers. This could result in an horrible loss of bits when scaling from one exponent
to another. Fortunately, the numbers in 1-2 are generated with maximum precision, and then subtracting 1.0
to get a number in 0-1 keeps that precision because all the numbers obtained this way are still perfectly
representable. Moreover, the minimum exponent reached this way is still far above the denormals range.
Note3: The random number generator MUST be initialized for this function to work correctly.
Note3: The random number generator MUST be initialized for this function to work correctly.
Note4: These functions are thread-safe if you use one RandomState object per thread (or if you
synchronize the access to a shared state object, of course).
*/
Note4: These functions are thread-safe if you use one RandomState object per thread (or if you
synchronize the access to a shared state object, of course).
*/
template<bool include_min, bool include_max, typename a_type> a_type Random(a_type min, a_type max, RandomState& state = DefaultRandomState);
// function that returns a random number on the whole possible range
template<typename a_type> a_type Random(RandomState& state = DefaultRandomState);
// Alias that can be useful too
template<typename a_type> inline a_type RandomIE(a_type min, a_type max, RandomState& state = DefaultRandomState) {return Random<true, false, a_type>(min, max, state);}
template<typename a_type> inline a_type RandomEI(a_type min, a_type max, RandomState& state = DefaultRandomState) {return Random<false, true, a_type>(min, max, state);}
template<typename a_type> inline a_type RandomEE(a_type min, a_type max, RandomState& state = DefaultRandomState) {return Random<false, false, a_type>(min, max, state);}
template<typename a_type> inline a_type RandomII(a_type min, a_type max, RandomState& state = DefaultRandomState) {return Random<true, true, a_type>(min, max, state);}
template<bool include_min, bool include_max, typename a_type> a_type Random(a_type min, a_type max, RandomState& state = DefaultRandomState);
// function that returns a random number on the whole possible range
template<typename a_type> a_type Random(RandomState& state = DefaultRandomState);
// Alias that can be useful too
template<typename a_type> inline a_type RandomIE(a_type min, a_type max, RandomState& state = DefaultRandomState) {
return Random<true, false, a_type>(min, max, state);
}
template<typename a_type> inline a_type RandomEI(a_type min, a_type max, RandomState& state = DefaultRandomState) {
return Random<false, true, a_type>(min, max, state);
}
template<typename a_type> inline a_type RandomEE(a_type min, a_type max, RandomState& state = DefaultRandomState) {
return Random<false, false, a_type>(min, max, state);
}
template<typename a_type> inline a_type RandomII(a_type min, a_type max, RandomState& state = DefaultRandomState) {
return Random<true, true, a_type>(min, max, state);
}
#define STREFLOP_RANDOM_MAKE_REAL(a_type) \
template<> a_type Random<a_type>(RandomState& state); \
template<> a_type Random<true, true, a_type>(a_type min, a_type max, RandomState& state); \
@@ -127,46 +135,62 @@ template<> a_type Random<true, false, a_type>(a_type min, a_type max, RandomStat
template<> a_type Random<false, true, a_type>(a_type min, a_type max, RandomState& state); \
template<> a_type Random<false, false, a_type>(a_type min, a_type max, RandomState& state);
STREFLOP_RANDOM_MAKE_REAL(char)
STREFLOP_RANDOM_MAKE_REAL(unsigned char)
STREFLOP_RANDOM_MAKE_REAL(short)
STREFLOP_RANDOM_MAKE_REAL(unsigned short)
STREFLOP_RANDOM_MAKE_REAL(int)
STREFLOP_RANDOM_MAKE_REAL(unsigned int)
STREFLOP_RANDOM_MAKE_REAL(long)
STREFLOP_RANDOM_MAKE_REAL(unsigned long)
STREFLOP_RANDOM_MAKE_REAL(long long)
STREFLOP_RANDOM_MAKE_REAL(unsigned long long)
STREFLOP_RANDOM_MAKE_REAL(char)
STREFLOP_RANDOM_MAKE_REAL(unsigned char)
STREFLOP_RANDOM_MAKE_REAL(short)
STREFLOP_RANDOM_MAKE_REAL(unsigned short)
STREFLOP_RANDOM_MAKE_REAL(int)
STREFLOP_RANDOM_MAKE_REAL(unsigned int)
STREFLOP_RANDOM_MAKE_REAL(long)
STREFLOP_RANDOM_MAKE_REAL(unsigned long)
STREFLOP_RANDOM_MAKE_REAL(long long)
STREFLOP_RANDOM_MAKE_REAL(unsigned long long)
/** Additional and faster functions for real numbers
These return a number in the 1..2 range, the base for all the other random functions
*/
template<bool include_min, bool include_max, typename a_type> a_type Random12(RandomState& state = DefaultRandomState);
// Alias that can be useful too
template<typename a_type> inline a_type Random12IE(RandomState& state = DefaultRandomState) {return Random12<true, false, a_type>(state);}
template<typename a_type> inline a_type Random12EI(RandomState& state = DefaultRandomState) {return Random12<false, true, a_type>(state);}
template<typename a_type> inline a_type Random12EE(RandomState& state = DefaultRandomState) {return Random12<false, false, a_type>(state);}
template<typename a_type> inline a_type Random12II(RandomState& state = DefaultRandomState) {return Random12<true, true, a_type>(state);}
/** Additional and faster functions for real numbers
These return a number in the 1..2 range, the base for all the other random functions
*/
template<bool include_min, bool include_max, typename a_type> a_type Random12(RandomState& state = DefaultRandomState);
// Alias that can be useful too
template<typename a_type> inline a_type Random12IE(RandomState& state = DefaultRandomState) {
return Random12<true, false, a_type>(state);
}
template<typename a_type> inline a_type Random12EI(RandomState& state = DefaultRandomState) {
return Random12<false, true, a_type>(state);
}
template<typename a_type> inline a_type Random12EE(RandomState& state = DefaultRandomState) {
return Random12<false, false, a_type>(state);
}
template<typename a_type> inline a_type Random12II(RandomState& state = DefaultRandomState) {
return Random12<true, true, a_type>(state);
}
/** Additional and faster functions for real numbers
/** Additional and faster functions for real numbers
These return a number in the 0..1 range by subtracting one to the 1..2 function
This avoids a multiplication for the min...max scaling
These return a number in the 0..1 range by subtracting one to the 1..2 function
This avoids a multiplication for the min...max scaling
Provided for convenience only, use the 1..2 range as the base random function
*/
template<bool include_min, bool include_max, typename a_type> inline a_type Random01(RandomState& state = DefaultRandomState) {
return Random12<include_min, include_max, a_type>(state) - a_type(1.0);
}
// Alias that can be useful too
template<typename a_type> inline a_type Random01IE(RandomState& state = DefaultRandomState) {return Random01<true, false, a_type>(state);}
template<typename a_type> inline a_type Random01EI(RandomState& state = DefaultRandomState) {return Random01<false, true, a_type>(state);}
template<typename a_type> inline a_type Random01EE(RandomState& state = DefaultRandomState) {return Random01<false, false, a_type>(state);}
template<typename a_type> inline a_type Random01II(RandomState& state = DefaultRandomState) {return Random01<true, true, a_type>(state);}
Provided for convenience only, use the 1..2 range as the base random function
*/
template<bool include_min, bool include_max, typename a_type> inline a_type Random01(RandomState& state = DefaultRandomState) {
return Random12<include_min, include_max, a_type>(state) - a_type(1.0);
}
// Alias that can be useful too
template<typename a_type> inline a_type Random01IE(RandomState& state = DefaultRandomState) {
return Random01<true, false, a_type>(state);
}
template<typename a_type> inline a_type Random01EI(RandomState& state = DefaultRandomState) {
return Random01<false, true, a_type>(state);
}
template<typename a_type> inline a_type Random01EE(RandomState& state = DefaultRandomState) {
return Random01<false, false, a_type>(state);
}
template<typename a_type> inline a_type Random01II(RandomState& state = DefaultRandomState) {
return Random01<true, true, a_type>(state);
}
/// Define all 12 and 01 functions only for real types
/// use the 12 function to generate the other
/// Define all 12 and 01 functions only for real types
/// use the 12 function to generate the other
#define STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(a_type) \
template<> a_type Random12<true, true, a_type>(RandomState& state); \
@@ -192,53 +216,53 @@ template<> inline a_type Random<false, false, a_type>(a_type min, a_type max, Ra
}
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Simple)
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Double)
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Simple)
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Double)
#if defined(Extended)
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Extended)
STREFLOP_RANDOM_MAKE_REAL_FLOAT_TYPES(Extended)
#endif
/**
Utility to get a number from a Normal distribution
The no argument version returns a distribution with mean 0, variance 1.
The 2 argument version takes the desired mean standard deviation.
Both are only defined over the floating-point types
/**
Utility to get a number from a Normal distribution
The no argument version returns a distribution with mean 0, variance 1.
The 2 argument version takes the desired mean standard deviation.
Both are only defined over the floating-point types
This uses the common polar-coordinate method to transform between uniform and normal
Step 1: generate a pair of numbers in the -1,1 x -1,1 square
Step 2: loop over to step 1 until it is also in the unit circle
Step 3: Convert using the property property (U1, U2) = (X,Y) * sqrt( -2 * log(D) / D)
with D = X*X+Y*Y the squared distance and log(D) the natural logarithm function
Step 4: Choose U1 or U2, they are independent (keep the other for the next call)
Step 5 (optional): Scale and translate U to a given mean, std_dev
This uses the common polar-coordinate method to transform between uniform and normal
Step 1: generate a pair of numbers in the -1,1 x -1,1 square
Step 2: loop over to step 1 until it is also in the unit circle
Step 3: Convert using the property property (U1, U2) = (X,Y) * sqrt( -2 * log(D) / D)
with D = X*X+Y*Y the squared distance and log(D) the natural logarithm function
Step 4: Choose U1 or U2, they are independent (keep the other for the next call)
Step 5 (optional): Scale and translate U to a given mean, std_dev
There may be better numerical methods, but I'm too lazy to implement them.
Any suggestion/contribution is welcome!
There may be better numerical methods, but I'm too lazy to implement them.
Any suggestion/contribution is welcome!
In particular, it seems quite horrendous to do computations close to the 0, in the 0-1 range,
where there may be denormals and the lot, to scale and translate later on. It would be better
to compute everything in another float interval (ex: 2 to 4 centered on 3 for the same square
has a uniform representable range of floats), and only then convert to the given mean/std_dev
at the last moment.
In particular, it seems quite horrendous to do computations close to the 0, in the 0-1 range,
where there may be denormals and the lot, to scale and translate later on. It would be better
to compute everything in another float interval (ex: 2 to 4 centered on 3 for the same square
has a uniform representable range of floats), and only then convert to the given mean/std_dev
at the last moment.
Note: An optional argument "secondary" may be specified, and in that case, a second number
indepedent from the first will be returned at negligible cost (in other words, by default, half the values
are thrown away)
*/
template<typename a_type> a_type NRandom(a_type mean, a_type std_dev, a_type *secondary = 0, RandomState& state = DefaultRandomState);
template<> Simple NRandom(Simple mean, Simple std_dev, Simple *secondary, RandomState& state);
template<> Double NRandom(Double mean, Double std_dev, Double *secondary, RandomState& state);
Note: An optional argument "secondary" may be specified, and in that case, a second number
indepedent from the first will be returned at negligible cost (in other words, by default, half the values
are thrown away)
*/
template<typename a_type> a_type NRandom(a_type mean, a_type std_dev, a_type *secondary = 0, RandomState& state = DefaultRandomState);
template<> Simple NRandom(Simple mean, Simple std_dev, Simple *secondary, RandomState& state);
template<> Double NRandom(Double mean, Double std_dev, Double *secondary, RandomState& state);
#if defined(Extended)
template<> Extended NRandom(Extended mean, Extended std_dev, Extended *secondary, RandomState& state);
template<> Extended NRandom(Extended mean, Extended std_dev, Extended *secondary, RandomState& state);
#endif
/// Simplified versions
template<typename a_type> a_type NRandom(a_type *secondary = 0, RandomState& state = DefaultRandomState);
template<> Simple NRandom(Simple *secondary, RandomState& state);
template<> Double NRandom(Double *secondary, RandomState& state);
/// Simplified versions
template<typename a_type> a_type NRandom(a_type *secondary = 0, RandomState& state = DefaultRandomState);
template<> Simple NRandom(Simple *secondary, RandomState& state);
template<> Double NRandom(Double *secondary, RandomState& state);
#if defined(Extended)
template<> Extended NRandom(Extended *secondary, RandomState& state);
template<> Extended NRandom(Extended *secondary, RandomState& state);
#endif
}

File diff suppressed because it is too large Load Diff

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