code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#pragma once #include "Log.hpp" #include "RecordFile.hpp" namespace zzz{ // Auto select class IOObj { public: template<typename T> static void WriteFileB(FILE *fp, const T *src, zsize size) { IOObject<T>::WriteFileB(fp, src, size); } template<typename T> static void ReadFileB(FILE *fp, T *dst, zsize size) { IOObject<T>::ReadFileB(fp, dst, size); } template<typename T> static void WriteFileB(FILE *fp, const T &src) { IOObject<T>::WriteFileB(fp, src); } template<typename T> static void ReadFileB(FILE *fp, T &dst) { IOObject<T>::ReadFileB(fp, dst); } template<typename T> static void WriteFileR(RecordFile &fp, const zint32 label, const T &src) { IOObject<T>::WriteFileR(fp, label, src); } template<typename T> static void ReadFileR(RecordFile &fp, const zint32 label, T &dst) { IOObject<T>::ReadFileR(fp, label, dst); } template<typename T> static void WriteFileR1By1(RecordFile &fp, const zint32 label, const T &src) { IOObject<T>::WriteFileR1By1(fp, label, src); } template<typename T> static void ReadFileR1By1(RecordFile &fp, const zint32 label, T &dst) { IOObject<T>::ReadFileR1By1(fp, label, dst); } template<typename T> static void WriteFileR(RecordFile &fp, const T &src) { IOObject<T>::WriteFileR(fp, src); } template<typename T> static void ReadFileR(RecordFile &fp, T &dst) { IOObject<T>::ReadFileR(fp, dst); } template<typename T> static void WriteFileR(RecordFile &fp, const zint32 label, const T *src, zsize size) { IOObject<T>::WriteFileR(fp, label, src, size); } template<typename T> static void ReadFileR(RecordFile &fp, const zint32 label, T *dst, zsize size) { IOObject<T>::ReadFileR(fp, label, dst, size); } template<typename T> static void WriteFileR(RecordFile &fp, const T *src, zsize size) { IOObject<T>::WriteFileR(fp, src, size); } template<typename T> static void ReadFileR(RecordFile &fp, T *dst, zsize size) { IOObject<T>::ReadFileR(fp, dst, size); } template<typename T> static void CopyData(T* dst, const T* src, zsize size) { IOObject<T>::CopyData(dst, src, size); } }; // Default IOObject, simple call function in T // Should be specialized if needed. template<typename T> class IOObject { public: static void CopyData(T* dst, const T* src, zsize size) { for (zsize i=0; i<size; i++) dst[i]=src[i]; } static void WriteFileB(FILE *fp, const T *src, zsize size) { T::WriteFileB(fp, src, size); } static void ReadFileB(FILE *fp, T *dst, zsize size) { T::ReadFileB(fp, dst, size); } static void WriteFileB(FILE *fp, const T &src) { T::WriteFileB(fp, src); } static void ReadFileB(FILE *fp, T &dst) { T::ReadFileB(fp, dst); } static void WriteFileR(RecordFile &fp, const zint32 label, const T &src) { T::WriteFileR(fp, label, src); } static void ReadFileR(RecordFile &fp, const zint32 label, T &dst) { T::ReadFileR(fp, label, dst); } static void WriteFileR(RecordFile &fp, const T &src) { T::WriteFileR(fp, src); } static void ReadFileR(RecordFile &fp, T &dst) { T::ReadFileR(fp, dst); } static void WriteFileR(RecordFile &fp, const zint32 label, const T *src, zsize size) { T::WriteFileR(fp, label, src, size); } static void ReadFileR(RecordFile &fp, const zint32 label, T *dst, zsize size) { T::ReadFileR(fp, label, dst, size); } static void WriteFileR(RecordFile &fp, const T *src, zsize size) { T::WriteFileR(fp, src, size); } static void ReadFileR(RecordFile &fp, T *dst, zsize size) { T::ReadFileR(fp, dst, size); } }; #define SIMPLE_IOOBJECT(T) \ template<>\ class IOObject<T>\ {\ public:\ static void WriteFileB(FILE *fp, const T *src, zsize size) {\ fwrite(src, sizeof(T), size, fp); \ }\ static void ReadFileB(FILE *fp, T *dst, zsize size) {\ ZCHECK_EQ(fread(dst, sizeof(T), size, fp), size); \ }\ static void WriteFileB(FILE *fp, const T &src) {\ fwrite(&src, sizeof(T), 1, fp); \ }\ static void ReadFileB(FILE *fp, T &dst) {\ ZCHECK_EQ(fread(&dst, sizeof(T), 1, fp), 1); \ }\ static void WriteFileR(RecordFile &fp, const zint32 label, const T &src) {\ fp.Write(label, &src, sizeof(T), 1); \ }\ static void ReadFileR(RecordFile &fp, const zint32 label, T &dst) {\ fp.Read(label, &dst, sizeof(T), 1); \ }\ static void WriteFileR(RecordFile &fp, const T &src) {\ fp.Write(&src, sizeof(T), 1); \ }\ static void ReadFileR(RecordFile &fp, T &dst) {\ fp.Read(&dst, sizeof(T), 1); \ }\ static void WriteFileR(RecordFile &fp, const zint32 label, const T *src, zsize size) {\ fp.Write(label, src, sizeof(T), size); \ }\ static void ReadFileR(RecordFile &fp, const zint32 label, T *dst, zsize size) {\ fp.Read(label, dst, sizeof(T), size); \ }\ static void WriteFileR(RecordFile &fp, const T *src, zsize size) {\ fp.Write(src, sizeof(T), size); \ }\ static void ReadFileR(RecordFile &fp, T *dst, zsize size) {\ fp.Read(dst, sizeof(T), size); \ }\ static void CopyData(T* dst, const T* src, zsize size) {\ memcpy(dst,src,sizeof(T)*size); \ }\ }; SIMPLE_IOOBJECT(char); SIMPLE_IOOBJECT(long); SIMPLE_IOOBJECT(zint8); SIMPLE_IOOBJECT(zuint8); SIMPLE_IOOBJECT(zint16); SIMPLE_IOOBJECT(zuint16); SIMPLE_IOOBJECT(zint32); SIMPLE_IOOBJECT(zuint32); SIMPLE_IOOBJECT(zint64); SIMPLE_IOOBJECT(zuint64); SIMPLE_IOOBJECT(float); SIMPLE_IOOBJECT(double); SIMPLE_IOOBJECT(long double); template<typename T> class IOObject<vector<T*> > { public: /// When the object inside vector is not SIMPLE_IOOBJECT, it must access 1 by 1, /// instead of access as a raw array. static const int RF_SIZE = 1; static const int RF_DATA = 2; static void WriteFileR1By1(RecordFile &rf, const zint32 label, const vector<T*> &src) { zuint64 len = src.size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_DATA); for (zuint64 i = 0; i < len; ++i) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, *(src[i])); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR1By1(RecordFile &rf, const zint32 label, vector<T*> &dst) { for (zuint i = 0; i < dst.size(); ++i) delete dst[i]; dst.clear(); if (!rf.LabelExist(label)) { return; } rf.ReadChildBegin(label); zuint64 len; IOObj::ReadFileR(rf, RF_SIZE, len); if (len != 0) { dst.reserve(len); } rf.ReadRepeatBegin(RF_DATA); while(rf.ReadRepeatChild()) { T* v = new T; IOObj::ReadFileR(rf, *v); dst.push_back(v); } rf.ReadRepeatEnd(); ZCHECK_EQ(dst.size(), len) << "The length recorded is different from the actual length of data"; rf.ReadChildEnd(); } }; template<typename T> class IOObject<vector<T> > { public: static void WriteFileB(FILE *fp, const vector<T> &src) { zsize len = src.size(); IOObj::WriteFileB(fp, len); if (len != 0) IOObject<T>::WriteFileB(fp, src.data(), len); } static void ReadFileB(FILE *fp, vector<T> &dst) { zsize len; IOObj::ReadFileB(fp, len); if (len != 0) { dst.resize(len); IOObj::ReadFileB(fp, dst.data(), len); } else { dst.clear(); } } static void WriteFileR(RecordFile &rf, const zint32 label, const vector<T> &src) { zsize len = src.size(); IOObj::WriteFileR(rf, label, len); if (len != 0) IOObject<T>::WriteFileR(rf, src.data(), src.size()); } static void ReadFileR(RecordFile &rf, const zint32 label, vector<T> &dst) { if (!rf.LabelExist(label)) { dst.clear(); return; } zsize len; IOObj::ReadFileR(rf, label, len); if (len != 0) { dst.resize(len); IOObj::ReadFileR(rf, dst.data(), dst.size()); } else { dst.clear(); } } /// When the object inside STLVector is not SIMPLE_IOOBJECT, it must access 1 by 1, /// instead of access as a raw array. static const int RF_SIZE = 1; static const int RF_DATA = 2; static void WriteFileR1By1(RecordFile &rf, const zint32 label, const vector<T> &src) { zuint64 len = src.size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_DATA); for (zuint64 i = 0; i < len; ++i) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, src[i]); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR1By1(RecordFile &rf, const zint32 label, vector<T> &dst) { dst.clear(); if (!rf.LabelExist(label)) { return; } rf.ReadChildBegin(label); zuint64 len; IOObj::ReadFileR(rf, RF_SIZE, len); if (len != 0) { dst.reserve(len); } rf.ReadRepeatBegin(RF_DATA); while(rf.ReadRepeatChild()) { T v; IOObj::ReadFileR(rf, v); dst.push_back(v); } rf.ReadRepeatEnd(); ZCHECK_EQ(dst.size(), len) << "The length recorded is different from the actual length of data"; rf.ReadChildEnd(); } }; template<> class IOObject<std::string> { public: static void WriteFileB(FILE *fp, const std::string &src) { zsize len = src.size(); IOObj::WriteFileB(fp, len); if (len != 0) IOObj::WriteFileB(fp, src.data(), len); } static void ReadFileB(FILE *fp, std::string &dst) { zsize len; IOObj::ReadFileB(fp, len); if (len != 0) { char *str = new char[len+1]; IOObj::ReadFileB(fp, str, len); str[len]='\0'; dst=str; } else { dst.clear(); } } static void WriteFileR(RecordFile &rf, const zint32 label, const std::string &src) { zsize len = src.size(); IOObj::WriteFileR(rf, label, len); if (len != 0) IOObj::WriteFileR(rf, src.data(), src.size()); } static void ReadFileR(RecordFile &rf, const zint32 label, std::string &dst) { if (!rf.LabelExist(label)) { dst.clear(); return; } zsize len; IOObj::ReadFileR(rf, label, len); if (len != 0) { char *str = new char[len+1]; IOObj::ReadFileR(rf, str, len); str[len]='\0'; dst=str; } else { dst.clear(); } } }; template<typename T1, typename T2> class IOObject<map<T1, T2> > { private: static const zint32 RF_SIZE = 1; static const zint32 RF_ITEM = 2; static const zint32 RF_ITEM_KEY = 1; static const zint32 RF_ITEM_VALUE = 2; public: static void WriteFileR(RecordFile &rf, const zint32 label, const map<T1, T2> &src) { zsize len = src.size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_ITEM); for (map<T1, T2>::const_iterator mi = src.begin(); mi != src.end(); ++mi) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, RF_ITEM_KEY, mi->first); IOObj::WriteFileR(rf, RF_ITEM_VALUE, mi->second); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR(RecordFile &rf, const zint32 label, map<T1, T2> &dst) { dst.clear(); zsize len = 0; if (!rf.LabelExist(label)) return; rf.ReadChildBegin(label); IOObj::ReadFileR(rf, RF_SIZE, len); rf.ReadRepeatBegin(RF_ITEM); while (rf.ReadRepeatChild()) { T1 key; T2 value; IOObj::ReadFileR(rf, RF_ITEM_KEY, key); IOObj::ReadFileR(rf, RF_ITEM_VALUE, value); dst[key] = value; } rf.ReadRepeatEnd(); rf.ReadChildEnd(); ZCHECK_EQ(len, dst.size()); } }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/IOObject.hpp
C++
gpl3
11,820
#pragma once #include <zCoreConfig.hpp> #include <string> #include "Log.hpp" #include "IOObject.hpp" #include "../Math/Math.hpp" namespace zzz { #ifdef ZZZ_STLSTRING class STLString : public std::string { public: typedef std::string::iterator iterator; typedef std::string::reverse_iterator reverse_iterator; typedef std::string::const_iterator const_iterator; typedef std::string::const_reverse_iterator const_reverse_iterator; typedef std::string::reference reference; typedef std::string::const_reference const_reference; STLString():std::string(){} STLString(const string& str){assign(str);} STLString(const string& str, size_t pos, size_t n = std::string::npos) {assign(str, pos, n);} STLString(const char* s, size_t n){assign(s, s);} STLString(const char* s){assign(s);} STLString(size_t n, char c){assign(n, c);} template<class InputIterator> STLString(InputIterator begin, InputIterator end) { assign(begin, end); } STLString(const STLString& x){assign(x);} // iterators STLString& operator=(const std::string& x) {return assign(x);} STLString& operator=(const STLString& x) {return assign(x);} STLString& operator=(const char* s) {return assign(s);} STLString& operator=(char c) {clear(); push_back(c);} using std::string::begin; using std::string::end; using std::string::rbegin; using std::string::rend; // capacity using std::string::size; using std::string::length; using std::string::max_size; using std::string::resize; using std::string::capacity; using std::string::clear; using std::string::empty; void reserve(size_type n) { try { std::string::reserve(n); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } // element access reference operator[](size_type i) {return at(i);} const_reference operator[](size_type i) const {return at(i);} reference at(size_type i) { ZRCHECK_LT(i, size()); return std::string::at(i); } const_reference at(size_type i) const { ZRCHECK_LT(i, size()); return std::string::at(i); } // modifiers STLString& assign(const string& str) {assign(str.begin(), str.end()); return *this;} STLString& assign(const STLString& str) {return assign(static_cast<const std::string&>(str));} STLString& assign(const string& str, size_t pos, size_t n) { if (n == std::string::npos) n = str.size() - pos; else n = Min(str.size() - pos, n); assign(str.begin() + pos, str.begin() + pos + n); return *this; } STLString& assign(const char* s, size_t n) {assign(s, s + n); return *this;} STLString& assign(const char* s) {return assign(s, strlen(s));} template <class InputIterator> void assign(InputIterator first, InputIterator last) { try { std::string::assign(first, last); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } void assign(size_type n, char u) { try { std::string::assign(n, u); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } string& operator+=(const string& str) {return append(str);} string& operator+=(const char* s) {return append(s);} string& operator+=(char c) {push_back(c); return *this;} string& append(const string& str) {return append(str.begin(), str.end());} string& append(const string& str, size_t pos, size_t n) { if (n == std::string::npos) n = str.size() - pos; else n = Min(str.size() - pos, n); return append(str.begin() + pos, str.begin() + pos + n); } string& append(const char* s, size_t n) {return append(s, s+n);} string& append(const char* s){return append(s, s+strlen(s));} string& append(size_t n, char c) { try { return std::string::append(n, c); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } template <class InputIterator> string& append(InputIterator first, InputIterator last) { try { return std::string::append(first, last); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } void push_back(char x) {append(1, x);} string& insert(size_t pos1, const string& str) {insert(begin()+pos1, str.begin(), str.end()); return *this;} string& insert(size_t pos1, const string& str, size_t pos2, size_t n) { if (n == std::string::npos) n = str.size() - pos2; else n = Min(str.size() - pos2, n); insert(begin()+pos1, str.begin()+pos2, str.begin()+pos2+n); return *this; } string& insert(size_t pos1, const char* s, size_t n) {insert(begin()+pos1, s, s+n);} string& insert(size_t pos1, const char* s) {return insert(pos1, s, strlen(s));} string& insert(size_t pos1, size_t n, char c) {return insert(pos1, n, c);} iterator insert(iterator p, char c) { try { return std::string::insert(p, c); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } void insert(iterator p, size_t n, char c) { try { std::string::insert(p, n, c); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } template<class InputIterator> void insert(iterator p, InputIterator first, InputIterator last) { try { std::string::insert(p, first, last); } catch(std::bad_alloc) { ZLOGF<<"STLString: Failed to allocate memory!"; } catch(std::length_error) { ZLOGF<<"STLString: Length of string is longer than "<<ZVAR(max_size()); } } using std::string::erase; using std::string::replace; using std::string::swap; // String operations using std::string::c_str; using std::string::data; using std::string::get_allocator; using std::string::copy; using std::string::find; using std::string::rfind; using std::string::find_first_of; using std::string::find_last_of; using std::string::find_first_not_of; using std::string::find_last_not_of; using std::string::substr; using std::string::compare; // Special char* Data() {return &(at(0));} const char* Data() const {return &(at(0));} }; #else class STLString : public std::std::string { public: public: typedef std::std::string::iterator iterator; typedef std::std::string::reverse_iterator reverse_iterator; typedef std::std::string::const_iterator const_iterator; typedef std::std::string::const_reverse_iterator const_reverse_iterator; typedef typename std::std::string::reference reference; typedef typename std::std::string::const_reference const_reference; STLString():std::string(){} STLString(const string& str){assign(str);} STLString(const string& str, size_t pos, size_t n = std::string::npos) {assign(str, pos, n);} STLString(const char* s, size_t n){assign(s, s);} STLString(const char* s){assign(s);} STLString(size_t n, char c){assign(n, c);} template<class InputIterator> STLString(InputIterator begin, InputIterator end) { assgin(begin, end); } STLString(const STLString& x){assign(x);} // iterators using std::string::operator=; using std::string::begin; using std::string::end; using std::string::rbegin; using std::string::rend; // capacity using std::string::size; using std::string::length; using std::string::max_size; using std::string::resize; using std::string::capacity; using std::string::clear; using std::string::empty; using std::string::reserve(size_type n); // element access using std::string::operator[]; using std::string::at; // modifiers using std::string::assign; using std::string::append; using std::string::push_back; using std::string::insert; using std::string::erase; using std::string::replace; using std::string::swap; // String operations using std::string::c_str; using std::string::data; using std::string::get_allocator; using std::string::copy; using std::string::find; using std::string::rfind; using std::string::find_first_of; using std::string::find_last_of; using std::string::find_first_not_of; using std::string::find_last_not_of; using std::string::substr; using std::string::compare; // Special char* Data() {return std::string::data();} const char* Data() const {return std::string::data();} }; #endif template<> class IOObject<STLString> { public: static void WriteFileB(FILE *fp, const STLString &src) { zuint64 len = src.size(); IOObj::WriteFileB(fp, len); if (len != 0) IOObj::WriteFileB(fp, src.data(), len); } static void ReadFileB(FILE *fp, STLString &dst) { zuint64 len; IOObj::ReadFileB(fp, len); if (len != 0) { dst.resize(len); IOObj::ReadFileB(fp, dst.Data(), len); } else dst.clear(); } static void WriteFileR(RecordFile &rf, const zint32 label, const STLString &src) { zuint64 len = src.size(); IOObj::WriteFileR(rf, label, len); if (len != 0) IOObj::WriteFileR(rf, src.Data(), src.size()); } static void ReadFileR(RecordFile &rf, const zint32 label, STLString &dst) { if (!rf.LabelExist(label)) { dst.clear(); return; } zuint64 len; IOObj::ReadFileR(rf, label, len); if (len != 0) { dst.resize(len); IOObj::ReadFileR(rf, dst.Data(), dst.size()); } else dst.clear(); } }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/STLString.hpp
C++
gpl3
10,389
#pragma once #include <common.hpp> namespace zzz { class Timer { public: Timer():pauseTime_(0),paused_(false) { startTime_ = clock(); } void Restart() { startTime_ = clock(); pauseTime_=0; } void Pause() { if (!paused_) {paused_=true; pauseTime_=clock() - startTime_;} } void Resume() { if (paused_) {paused_=false; startTime_ = clock();} } double Elapsed() const { return paused_ ? double(pauseTime_) / CLOCKS_PER_SEC : double(clock() - startTime_ + pauseTime_) / CLOCKS_PER_SEC; } double Elapsed_max() const { return (double((std::numeric_limits<clock_t>::max)()) - double(startTime_)) / double(CLOCKS_PER_SEC); } double Elapsed_min() const { return double(1)/double(CLOCKS_PER_SEC); } //busy waiting static void Sleep(zuint msec){clock_t goal=msec*CLOCKS_PER_SEC/1000+clock(); while(goal > clock()) ; } private: clock_t startTime_; clock_t pauseTime_; bool paused_; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/Timer.hpp
C++
gpl3
926
#pragma once #include <zCoreConfig.hpp> #include <common.hpp> #include "Tools.hpp" namespace zzz{ inline bool StrCaseCmp(const string &str1, const string &str2) { int len1=str1.size(); int len2=str2.size(); int i1=0,i2=0; while(i1<len1 && i2<len2) { if (str1[i1]!=str2[i2]) return false; i1++; i2++; } if (i1==len1 && i2==len2) return true; return false; } inline string RawToFormat_copy(const string &str) { zuint len=str.size(); string ret; for (zuint i=0; i<len; i++) { if (str[i]=='\\') { if (i+1==len) break; i++; switch(str[i]) { case 'n':ret.push_back('\n');continue; case 'r':ret.push_back('\r');continue; case 't':ret.push_back('\t');continue; case 'b':ret.push_back('\b');continue; case '\\':ret.push_back('\\');continue; case '\"':ret.push_back('\"');continue; case '\'':ret.push_back('\'');continue; } } else ret.push_back(str[i]); } return ret; } inline void RawToFormat(string &str) { str=RawToFormat_copy(str); } inline void ToLow(char *str) { zuint len=strlen(str); for (zuint i=0; i<len; i++) { char x=str[i]; if (x>='A' && x<='Z') str[i]=x+'a'-'A'; } } inline void ToLow(string &str) { zuint len=str.size(); for (zuint i=0; i<len; i++) { char x=str[i]; if (x>='A' && x<='Z') str[i]=x+'a'-'A'; } } inline string ToLow_copy(const string &str) { zuint len=str.size(); string ret; for (zuint i=0; i<len; i++) { char x=str[i]; if (x>='A' && x<='Z') ret.push_back(x+'a'-'A'); else ret.push_back(x); } return ret; } ZCORE_FUNC string Replace(const string &ori, const string &from, const string &to); //////////////////////////////////////// extern const string BlankChars; ZCORE_FUNC string TrimFront(const string &str, const string &c=BlankChars); ZCORE_FUNC string TrimBack(const string &str, const string &c=BlankChars); ZCORE_FUNC string Trim(const string &str, const string &c=BlankChars); ZCORE_FUNC void SplitString(const string &str, vector<string> &ret, const char splitchar=' '); ZCORE_FUNC void JoinString(const vector<string> &strs, string &ret, const char joinchar=' '); ZCORE_FUNC string JoinCmd(int argc, char *argv[]); template <typename T> void StringToVector(const string &str, vector<T> &ret) { T tmp; istringstream iss(str); ret.clear(); while(true) { iss>>tmp; if (iss.fail()) return; ret.push_back(tmp); } } template<typename T> void FromString(const string& str, T& v) { istringstream iss(str); iss>>v; } template<typename T> void FromString(const string& str, std::vector<T>& v) { StringToVector(str, v); } template<> inline void FromString(const string& str, bool &x) { string newstr = Trim(str); ToLow(newstr); if (newstr == "true" || newstr == "t" || newstr == ".t." || newstr == "1") x = true; else x = false; } template<> inline void FromString(const string& str, string &x) { x = str; } template<typename T> T FromString(const string& str) { T ret; FromString(str, ret); return ret; } template<> inline string FromString<string>(const string& str) { return str; } template<typename T> void ToString(const T& val, string& str) { ostringstream oss; oss<<val; str=oss.str(); } template<typename T> string ToString(const T& val) { // DON'T CALL ToString(const T&, string&) which will make string copy three times ostringstream oss; oss<<val; return oss.str(); } template<> inline string ToString<bool>(const bool& var) { if (var) return "True"; else return "False"; } inline string operator<<(const string &strc, const string &add) { string str(strc); str+=add; return str; } inline string operator<<(const string &strc, const char *add) { string str(strc); str+=add; return str; } inline string& operator<<(string &str, const char *add) { str+=add; return str; } inline string& operator<<(string &str, const string &add) { str+=add; return str; } template<typename T> string operator<<(const string &strc, const T &val) { string str(strc); ostringstream oss; oss<<val; str+=oss.str(); return str; } template<typename T> string& operator<<(string &str, const T &val) { ostringstream oss; oss<<val; str+=oss.str(); return str; } inline bool StartsWith(const string &str, const string &pat) { if (str.size()<pat.size()) return false; return SafeEqual(pat.begin(), pat.end(), str.begin(), str.end()); } ZCORE_FUNC string RandomString(int length, bool letters=true, bool numbers=true, bool symbols=false); //BASE64 encode and decode ZCORE_FUNC void Base64Encode(const string &data, const zsize size, string &code); ZCORE_FUNC int Base64Decode(const string &code, char *data, const zsize size); }
zzz-engine
zzzEngine/zCore/zCore/Utility/StringTools.hpp
C++
gpl3
5,015
#pragma once #include "Tools.hpp" #include "IOObject.hpp" namespace zzz{ class HasFlags { public: HasFlags():flags_(0){} bool HasFlag(int bit) const {return CheckBit(flags_,bit);} bool HasNoFlag(int bit) const {return !CheckBit(flags_,bit);} void SetFlag(int bit){return SetBit(flags_,bit);} void ClrFlag(int bit){return ClearBit(flags_,bit);} void ToggleFlag(int bit){return ToggleBit(flags_,bit);} void SetAllFlags(){flags_=0xFFFFFFFF;} void ClrAllFlags(){flags_=0;} protected: unsigned int flags_; }; SIMPLE_IOOBJECT(HasFlags); }
zzz-engine
zzzEngine/zCore/zCore/Utility/HasFlag.hpp
C++
gpl3
573
#define ZCORE_SOURCE #include "StringTools.hpp" namespace zzz{ string Replace(const string &ori, const string &from, const string &to) { string ret; zuint i=0; while(i<ori.size()) { int x=ori.find(from, i); if (x==string::npos) { ret.append(ori.begin()+i,ori.end()); break; } ret.append(ori.begin()+i,ori.begin()+i+x); ret.append(to.begin(),to.end()); i+=x; i+=from.size(); } return ret; } ////////////////////////////////////////////////// //Ideas taken from work done by Bob Withers //2002-05-07 by Markus Ewald void Base64Encode(const string &data, zsize size, string &sResult) { static const std::string sBase64Table( // 0000000000111111111122222222223333333333444444444455555555556666 // 0123456789012345678901234567890123456789012345678901234567890123 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ); static const char cFillChar = '='; zuint nLength = size; sResult.clear(); // Allocate memory for the converted string sResult.reserve(nLength * 8 / 6 + 1); for(zuint nPos = 0; nPos < nLength; nPos++) { char cCode; // Encode the first 6 bits cCode = (data[nPos] >> 2) & 0x3f; sResult.append(1, sBase64Table[cCode]); // Encode the remaining 2 bits with the next 4 bits (if present) cCode = (data[nPos] << 4) & 0x3f; if(++nPos < nLength) cCode |= (data[nPos] >> 4) & 0x0f; sResult.append(1, sBase64Table[cCode]); if(nPos < nLength) { cCode = (data[nPos] << 2) & 0x3f; if(++nPos < nLength) cCode |= (data[nPos] >> 6) & 0x03; sResult.append(1, sBase64Table[cCode]); } else { ++nPos; sResult.append(1, cFillChar); } if(nPos < nLength) { cCode = data[nPos] & 0x3f; sResult.append(1, sBase64Table[cCode]); } else { sResult.append(1, cFillChar); } } } int Base64Decode(const string &sString, char *data, const zsize size) { static const std::string::size_type np = std::string::npos; static const std::string::size_type DecodeTable[] = { // 0 1 2 3 4 5 6 7 8 9 np, np, np, np, np, np, np, np, np, np, // 0 - 9 np, np, np, np, np, np, np, np, np, np, // 10 - 19 np, np, np, np, np, np, np, np, np, np, // 20 - 29 np, np, np, np, np, np, np, np, np, np, // 30 - 39 np, np, np, 62, np, np, np, 63, 52, 53, // 40 - 49 54, 55, 56, 57, 58, 59, 60, 61, np, np, // 50 - 59 np, np, np, np, np, 0, 1, 2, 3, 4, // 60 - 69 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89 25, np, np, np, np, np, np, 26, 27, 28, // 90 - 99 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119 49, 50, 51, np, np, np, np, np, np, np, // 120 - 129 np, np, np, np, np, np, np, np, np, np, // 130 - 139 np, np, np, np, np, np, np, np, np, np, // 140 - 149 np, np, np, np, np, np, np, np, np, np, // 150 - 159 np, np, np, np, np, np, np, np, np, np, // 160 - 169 np, np, np, np, np, np, np, np, np, np, // 170 - 179 np, np, np, np, np, np, np, np, np, np, // 180 - 189 np, np, np, np, np, np, np, np, np, np, // 190 - 199 np, np, np, np, np, np, np, np, np, np, // 200 - 209 np, np, np, np, np, np, np, np, np, np, // 210 - 219 np, np, np, np, np, np, np, np, np, np, // 220 - 229 np, np, np, np, np, np, np, np, np, np, // 230 - 239 np, np, np, np, np, np, np, np, np, np, // 240 - 249 np, np, np, np, np, np // 250 - 256 }; static const char cFillChar = '='; zuint nLength = sString.size(); zuint cur=0; if (size==0) return 0; for(zuint nPos = 0; nPos < nLength; nPos++) { unsigned char c, c1; c = (char) DecodeTable[(unsigned char)sString[nPos]]; nPos++; c1 = (char) DecodeTable[(unsigned char)sString[nPos]]; c = (c << 2) | ((c1 >> 4) & 0x3); data[cur++]=c; if (cur==size) break; if(++nPos < nLength) { c = sString[nPos]; if(cFillChar == c) break; c = (char) DecodeTable[(unsigned char)sString[nPos]]; c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); data[cur++]=c1; if (cur==size) break; } if(++nPos < nLength) { c1 = sString[nPos]; if(cFillChar == c1) break; c1 = (char) DecodeTable[(unsigned char)sString[nPos]]; c = ((c << 6) & 0xc0) | c1; data[cur++]=c; if (cur==size) break; } } return cur; } const string BlankChars = " \t\n\r\x0B"; string TrimFront(const string &str, const string &c/*=BlankChars*/) { if (str.empty()) return string(); int len=str.size(); int startpos; for (startpos=0;startpos<len;startpos++) { char now=str[startpos]; if (find(c.begin(), c.end() ,now)!=c.end()) continue; break; } string temp(str.begin()+startpos,str.end()); return temp; } string TrimBack(const string &str, const string &c/*=BlankChars*/) { if (str.empty()) return string(); int len=str.size(); int endpos; for (endpos=len-1;endpos>=0;endpos--) { char now=str[endpos]; if (find(c.begin(), c.end() ,now)!=c.end()) continue; break; } string temp(str.begin(),str.begin()+endpos+1); return temp; } string Trim(const string &str, const string &c/*=BlankChars*/) { if (str.empty()) return string(); int len=str.size(); int startpos,endpos; for (startpos=0;startpos<len;startpos++) { char now=str[startpos]; if (find(c.begin(), c.end() ,now)!=c.end()) continue; break; } for (endpos=len-1;endpos>=0;endpos--) { char now=str[endpos]; if (find(c.begin(), c.end() ,now)!=c.end()) continue; break; } if (endpos<=startpos) { return string(); } string temp(str.begin()+startpos,str.begin()+endpos+1); return temp; } void SplitString(const string &str, vector<string> &ret, const char splitchar) { ret.clear(); string tmp; for (string::const_iterator si=str.begin();si!=str.end();si++) { if (*si == splitchar && !tmp.empty()) { ret.push_back(tmp); tmp.clear(); continue; } tmp.push_back(*si); } if (!tmp.empty()) ret.push_back(tmp); } void JoinString(const vector<string> &strs, string &ret, const char joinchar) { ret.clear(); if (strs.empty()) return; ret = strs[0]; for (zuint i=1; i<strs.size(); i++) { ret += joinchar; ret += strs[i]; } } string JoinCmd(int argc, char *argv[]) { string ret = argv[0]; for (int i=1; i<argc; i++) { if (find(argv[i],argv[i]+strlen(argv[i]), ' ') != argv[i]+strlen(argv[i])) { ret += " \""; ret += argv[i]; ret += "\""; } else { ret += ' '; ret += argv[i]; } } return ret; } string RandomString(int length, bool letters, bool numbers, bool symbols) { // the shortest way to do this is to create a string, containing // all possible values. Then, simply add a random value from that string // to our return value std::string allPossible; // this will contain all necessary characters std::string str; // the random string if (letters) { // if you passed true for letters, we'll add letters to the possibilities allPossible += "abcdefghijklmnopqrstuvwxyz"; allPossible += "ABCDEFGHIJKLMNOPQRSUTVWXYZ"; } if (numbers) { // if you wanted numbers, we'll add numbers allPossible += "0123456789"; } if (symbols) { // if you want symbols, we'll add symbols (note, their ASCII values are scattered) allPossible += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; } // get the number of characters to use (used for rand()) int numberOfPossibilities = allPossible.length(); for (int i = 0; i < length; i++) { str += allPossible[rand() % numberOfPossibilities]; } return str; } }
zzz-engine
zzzEngine/zCore/zCore/Utility/StringTools.cpp
C++
gpl3
8,044
#pragma once #include "IOObject.hpp" namespace zzz { class IOFile { public: template<typename T> static bool SaveFileA(const string &filename, const T &obj) { ZLOGV << "Saving file " << filename << "...\n"; return IOFileA<T>::SaveFile(filename, obj); } template<typename T> static bool LoadFileA(const string &filename, T &obj) { ZLOGV << "Loading file " << filename << "...\n"; return IOFileA<T>::LoadFile(filename, obj); } template<typename T> static bool SaveFileB(const string &filename, const T &obj) { ZLOGV << "Saving file " << filename << "...\n"; return IOFileB<T>::SaveFile(filename, obj); } template<typename T> static bool LoadFileB(const string &filename, T &obj) { ZLOGV << "Loading file " << filename << "...\n"; return IOFileB<T>::LoadFile(filename, obj); } template<typename T> static bool SaveFileR(const string &filename, const T &obj) { ZLOGV << "Saving file " << filename << "...\n"; return IOFileR<T>::SaveFile(filename, obj); } template<typename T> static bool LoadFileR(const string &filename, T &obj) { ZLOGV << "Loading file " << filename << "...\n"; return IOFileR<T>::LoadFile(filename, obj); } }; template<typename T> class IOFileA { public: static bool SaveFile(const string &filename, const T &obj) { ofstream fo(filename); if (!fo.good()) return false; IOObject<T>::WriteFileA(fo, obj); fo.close(); return true; } static bool LoadFile(const string &filename, T &obj) { ifstream fi(filename); if (!fi.good()) return false; IOObject<T>::ReadFileA(fi, obj); fi.close(); return true; } }; template<typename T> class IOFileB { public: static bool SaveFile(const string &filename, const T &obj) { FILE *fp = fopen(filename.c_str(), "wb"); if (!fp) return false; IOObject<T>::WriteFileB(fp, obj); fclose(fp); return true; } static bool LoadFile(const string &filename, T &obj) { FILE *fp = fopen(filename.c_str(), "rb"); if (!fp) return false; IOObject<T>::ReadFileB(fp, obj); fclose(fp); return true; } }; const int IOFILER_MAGIC = 1025; template<typename T> class IOFileR { public: static bool SaveFile(const string &filename, const T &obj) { RecordFile rf; rf.SaveFileBegin(filename); IOObject<T>::WriteFileR(rf, IOFILER_MAGIC, obj); rf.SaveFileEnd(); return true; } static bool LoadFile(const string &filename, T &obj) { RecordFile rf; rf.LoadFileBegin(filename); IOObject<T>::ReadFileR(rf, IOFILER_MAGIC, obj); rf.LoadFileEnd(); return true; } }; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/IOFile.hpp
C++
gpl3
2,732
#pragma once namespace zzz { template<bool> struct StaticAssert; template<> struct StaticAssert<true> {}; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/StaticTools.hpp
C++
gpl3
131
#pragma once #include <common.hpp> #ifdef ZZZ_OS_WIN #include <conio.h> #endif namespace zzz{ // Bit Check inline bool CheckBit(const int check, const int bit){return ((check & bit)!=0)?true:false;} inline void SetBit(int &flag, const int bit){flag |= bit;} inline void ClearBit(int &flag, const int bit){flag &= ~bit;} inline void ToggleBit(int &flag, const int bit){flag ^= bit;} inline bool CheckBit(const zuint check, const int bit){return ((check & bit)!=0)?true:false;} inline void SetBit(zuint &flag, const int bit){flag |= bit;} inline void ClearBit(zuint &flag, const int bit){flag &= ~bit;} inline void ToggleBit(zuint &flag, const int bit){flag ^= bit;} #ifdef ZOPTIMIZE_SETCLEARBIT inline void SetClearBit(int &flag, const int bit, bool f) { flag ^= (-int(f) ^ flag) &bit; } inline void SetClearBit(zuint &flag, const zuint bit, bool f) { flag ^= (-int(f) ^ flag) &bit; } #else inline void SetClearBit(int &flag, const int bit, bool f){if (f) SetBit(flag,bit); else ClearBit(flag,bit);} inline void SetClearBit(zuint &flag, const zuint bit, bool f){if (f) SetBit(flag,bit); else ClearBit(flag,bit);} #endif // Misc template <typename InputIterator1, typename InputIterator2> bool SafeEqual(const InputIterator1 &first1, const InputIterator1 &last1, const InputIterator2 &first2, const InputIterator2 &last2) { InputIterator1 cur1 = first1; InputIterator2 cur2 = first2; while ((cur1 != last1)) { if (cur2 == last2) return false; if (*cur1 != *cur2) // or: if (!pred(*first1, *first2)), for pred version return false; cur1++; cur2++; } return true; } template <typename InputIterator1, typename InputIterator2, typename Pred> bool SafeEqual(const InputIterator1 &first1, const InputIterator1 &last1, const InputIterator2 &first2, const InputIterator2 &last2, const Pred &pred) { InputIterator1 cur1 = first1; InputIterator2 cur2 = first2; while ((cur1 != last1)) { if (cur2 == last2) return false; if (!pred(*cur1, *cur2)) return false; cur1++; cur2++; } return true; } inline void PressAnyKeyToContinue() { cout<<"~~~ HIT A KEY TO CONTINUE ~~~"<<endl; _getch(); } inline string GetEnv(const string &name) { char *value = getenv(name.c_str()); if (value != NULL) return string(value); else return string(""); } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/Tools.hpp
C++
gpl3
2,453
//modified from boost::any #pragma once #include "../common.hpp" #include "Uncopyable.hpp" #ifdef __GNUC__ #include <typeinfo> #endif namespace zzz{ //Any is NOT a template class class Any { public: // Empty construct Any():content_(0){} // Construct from T template<typename T> Any(const T & value):content_(new Holder<T>(value)){} // Copy construct, will reproduce a item // Attention that it is not template, no Type is required Any(const Any & other):content_(other.content_?other.content_->Clone():0){} ~Any(){delete content_;} public: // Copy from value template<typename T> const Any& operator=(const T & other) { if (content_) delete content_; content_=new Holder<T>(other); return *this; } // Copy from other Any const Any& operator=(const Any &other) { if (content_) delete content_; content_=other.content_->Clone(); return *this; } bool Empty() const { return !content_; } const std::type_info& Type() const { return content_ ? content_->Type() : typeid(void); } template<typename T> inline bool IsType() { return content_->Type() == typeid(T); } private: // types class PlaceHolder { public: virtual ~PlaceHolder(){} virtual const std::type_info & Type() const = 0; virtual PlaceHolder * Clone() const = 0; }; template<typename T> class Holder : public PlaceHolder, Uncopyable { public: Holder(const T & value):v(value){} virtual const std::type_info & Type() const{return typeid(T);} //for operator= for Any virtual PlaceHolder * Clone() const{return new Holder(v);} T v; }; PlaceHolder* content_; template<typename T> friend inline T& any_cast(Any* operand); template<typename T> friend inline const T& any_cast(const Any* operand); template<typename T> friend inline T& unsafe_any_cast(Any* operand); template<typename T> friend inline const T& unsafe_any_cast(const Any* operand); template<typename T> friend inline T& any_cast(Any& operand); template<typename T> friend inline const T& any_cast(const Any& operand); }; ///cast////////////////////////////////////////////////////////////////////////// class bad_any_cast : public std::bad_cast { public: virtual const char *what() const throw() { return "zzz::bad_any_cast: failed conversion using zzz::any_cast"; } }; //Any* -> T& template<typename T> inline T& any_cast(Any* operand) { if (operand==NULL || operand->Type() != typeid(T)) throw bad_any_cast(); return static_cast<Any::Holder<T> *>(operand->content_)->v; } //const Any* -> const T& template<typename T> inline const T& any_cast(const Any* operand) { if (operand==NULL || operand->Type() != typeid(T)) throw bad_any_cast(); return static_cast<Any::Holder<T> *>(operand->content_)->v; } //Any* -> T& template<typename T> inline T& unsafe_any_cast(Any* operand) { return static_cast<Any::Holder<T> *>(operand->content_)->v; } //const Any* -> const T& template<typename T> inline const T& unsafe_any_cast(const Any* operand) { return static_cast<Any::Holder<T> *>(operand->content_)->v; } //Any& -> T& template<typename T> inline T& any_cast(Any& operand) { if (operand.Type() != typeid(T)) throw bad_any_cast(); return static_cast<Any::Holder<T> *>(operand.content_)->v; } //const Any& -> const T& template<typename T> inline const T& any_cast(const Any& operand) { if (operand.Type() != typeid(T)) throw bad_any_cast(); return static_cast<Any::Holder<T> *>(operand.content_)->v; } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/Any.hpp
C++
gpl3
3,681
#define ZCORE_SOURCE #include "CmdParser.hpp" #include "StringTools.hpp" #include "Tools.hpp" #include "FileTools.hpp" #include "Log.hpp" #include <yaml-cpp/yaml.h> namespace zzz{ ZFLAGS_SWITCH2(help, "Show Help", 'h'); ZFLAGS_SWITCH(helplong, "Show All Help"); ZFLAGS_STRING(opt_file, "", "Option filename (If it is empty, will use program_name.zopt)"); ZFLAGS_STRING(opt_dir, GetEnv("ZOPT_DIR"), "Will find option file in initial folder in current folder or this folder"); const int INDEX_BEGIN=10000; ZGLOBAL_DEFINE(string, zCurrentProgramName, ""); void CmdParser::AddLongOption(const string &longopt, ArgRequirement re, int shortopt, const string &desc, const string &file) { option o; o.name=new char[longopt.size()+1]; strcpy((char*)o.name,longopt.c_str()); const int argre[3]={no_argument,optional_argument,required_argument}; o.has_arg=argre[re]; o.flag=0; o.val=shortopt; long_options.push_back(o); if (shortopt<255 && (isalpha(shortopt) || isdigit(shortopt))) { short_options+=shortopt; optstr.push_back(string("-") + char(shortopt) + "|"); if (re==CMDPARSER_ONEARG) short_options+=':'; else if (re==CMDPARSER_OPTARG) short_options+="::"; } else optstr.push_back(""); optstr.back()+=string("--")+longopt; optdesc.push_back(string(desc)); if (!option_file.empty() && option_file.back()==file) { option_file_n.back()++; } else { option_file.push_back(file); option_file_n.push_back(1); } } void CmdParser::AddShortOption(char shortopt, ArgRequirement re, const string &desc, const string &file) { short_options+=shortopt; optstr.push_back("-"); optstr.back()+=shortopt; if (re==CMDPARSER_ONEARG) { short_options+=':'; } else if (re==CMDPARSER_OPTARG) { short_options+="::"; } optdesc.push_back(string(desc)); if (option_file.back()==file) { option_file_n.back()++; }else { option_file.push_back(file); option_file_n.push_back(1); } } bool CmdParser::Parse(const string &usage, int argc, char *argv[], const char *currentfile) { *ZGLOBAL_GET(string*, "zCurrentProgramName")=argv[0]; LoadOptionFile(); sequential_.clear(); optind=0; if (long_options.back().name!=NULL) { option o; o.name=NULL; o.has_arg=no_argument; o.flag=0; o.val=0; long_options.push_back(o); } while(true) { int option_index; int c=getopt_long(argc,argv,short_options.c_str(), &(long_options[0]), &option_index); if (c==-1) break; //end if (c==0) continue; //flag if (c=='?') { zout<<"Please read " << argv[0] << " --help OR --helplong\n"; exit(-1); //error } if (ParseShortOption(c, optarg)) continue; ZLOG(ZFATAL)<<"Unknown opt: " << c << "\n[THIS SHOULD NOT HAPPEN!]"; } if (optind < argc) { while (optind < argc) sequential_.push_back(string(argv[optind++])); } if (ZFLAG_help==true) { Help(usage, currentfile); exit(0); } if (ZFLAG_helplong==true) { HelpLong(usage); exit(0); } for (zuint i=0; i<postparse_.size(); ++i) { (postparse_[i])(); } return true; } void CmdParser::Help(const string &usage, const char *currentfile) { // usage cout << "I was built on: " << ZGLOBAL_GET(string, "__MAIN_TIMESTAMP__") << endl; cout << "USAGE: " << usage << endl << endl; zuint start_opt = 0; zuint end_opt = 0; for (zuint i = 0; i < option_file.size(); ++i) { if (option_file[i] == currentfile) { start_opt = accumulate(option_file_n.begin(), option_file_n.begin() + i, 0); end_opt = start_opt + option_file_n[i]; break; } } cout << "OPTIONS in " << currentfile << ":\n"; // option description for (zuint i = start_opt; i < end_opt; ++i) { cout.width(18); cout << left << optstr[i]; cout.width(60); cout << left << optdesc[i] << endl; } } void CmdParser::HelpLong(const string &usage) { //usage cout << "USAGE: " << usage << endl << endl; zuint i=0,iend=0; for (zuint j=0; j<option_file.size(); j++) { cout<<"OPTIONS in "<<option_file[j]<<":\n"; //option description iend+=option_file_n[j]; for (; i<iend; ++i) { cout.width(18); cout << left << optstr[i]; cout.width(60); cout << left << optdesc[i] << endl; } cout << endl; } } CmdParser::~CmdParser() { if (long_options.back().name==NULL) { for (zuint i=0; i<long_options.size()-1; ++i) delete[] long_options[i].name; } else { for (zuint i=0; i<long_options.size(); ++i) delete[] long_options[i].name; } } void CmdParser::AddAutoOption(const string &longopt, const string &desc, const string &file, const char shortopt, bool is_switch) { string strvar = string("ZFLAG_") + longopt; string strdesc(desc); if (ZGLOBAL_ISTYPE(double*, strvar)) { strdesc += "(" + ToString(ZFLAG_GET(double, strvar)) + ")"; } else if (ZGLOBAL_ISTYPE(int*, strvar)) { strdesc += "(" + ToString(ZFLAG_GET(int, strvar)) + ")"; } else if (ZGLOBAL_ISTYPE(string*, strvar)) { strdesc += "(\"" + ZFLAG_GET(string, strvar) + "\")"; } else if (ZGLOBAL_ISTYPE(vector<string>*, strvar)) { strdesc << "(" << GetzVar(ZFLAG_GET(vector<string>, strvar)) << ")"; } else if (ZGLOBAL_ISTYPE(bool*, strvar) && !is_switch) { strdesc += "(" + ToString(ZFLAG_GET(bool, strvar)) + ")"; } int index; if (shortopt==0) // No short option, assign a number. index = INDEX_BEGIN + short_long_.size() + neg_short_long_.size(); else index = shortopt; if (ZGLOBAL_ISTYPE(bool*, strvar)) { if (is_switch) AddLongOption(longopt, CMDPARSER_NOARG, index, strdesc.c_str(), file); else AddLongOption(longopt, CMDPARSER_OPTARG, index, strdesc.c_str(), file); } else { AddLongOption(longopt, CMDPARSER_ONEARG, index, strdesc.c_str(), file); } short_long_[index] = strvar; if (!is_switch && ZGLOBAL_ISTYPE(bool*, strvar)) { int neg_index = INDEX_BEGIN + short_long_.size() + neg_short_long_.size(); string negopt = string("no_") + longopt; AddLongOption(negopt.c_str(), CMDPARSER_NOARG, neg_index, "", file); neg_short_long_[neg_index] = strvar; } } void CmdParser::AddPostParseFunc(PostParse post) { postparse_.push_back(post); } bool CmdParser::ParseShortOption(const int c, const char *arg) { map<int, string>::const_iterator mi = short_long_.find(c); if (mi == short_long_.end()) { mi = neg_short_long_.find(c); if (mi == neg_short_long_.end()) return false; return ParseLongOption(mi->second, "false"); } return ParseLongOption(mi->second, arg); } bool CmdParser::ParseLongOption(const string &name, const char *arg) { if (!ZGLOBAL_ISEXIST(name)) return false; if (ZGLOBAL_ISTYPE(bool*, name)) { if (arg == NULL) *(ZGLOBAL_GET(bool*,name)) = true; else *(ZGLOBAL_GET(bool*,name)) = FromString<bool>(arg); return true; } ZCHECK_NOT_NULL(arg) << ZVAR(name); #define TRY_TYPE(type) \ if (ZGLOBAL_ISTYPE(type*, name)) {*(ZGLOBAL_GET(type*,name)) = FromString<type>(arg); return true; } TRY_TYPE(double); TRY_TYPE(int); TRY_TYPE(std::string); #undef TRY_TYPE if (ZGLOBAL_ISTYPE(std::vector<std::string>*, name)) { ZGLOBAL_GET(std::vector<std::string>*,name)->push_back(arg); return true; } return false; } void CmdParser::LoadOptionFile() { string opt_filename; if (!ZFLAG_opt_file.empty()) { opt_filename = ZFLAG_opt_file; } else { opt_filename = GetBase(zCurrentProgramName) + ".zopt"; } if (FileExists(PathFile(InitialPath(), opt_filename))) { opt_filename = PathFile(InitialPath(), opt_filename); } else if (!ZFLAG_opt_dir.empty() && FileExists(PathFile(CompleteDirName(ZFLAG_opt_dir), opt_filename))) { opt_filename = PathFile(CompleteDirName(ZFLAG_opt_dir), opt_filename); } else { return; } ZLOGM << "Load option file from " << opt_filename << endl; ifstream fi(opt_filename); if (!fi.good()) { ZLOGE << "Option file exists but cannot open " << ZVAR(opt_filename) << endl; return; } YAML::Parser parser(fi); YAML::Node doc; parser.GetNextDocument(doc); // Decide what profile to use. // Load profile in use: // If in release, load profile in use_release: // If in debug, load profile in use_debug: // If no use/use_xxx, load "default" vector<string> profiles; for (YAML::Iterator it = doc.begin(); it != doc.end(); ++it) { std::string key, value; it.first() >> key; if (key == "use") { if (it.second().Type() == YAML::NodeType::Scalar) { it.second() >> value; profiles.push_back(value); } else { for (YAML::Iterator it2 = it.second().begin(); it2 != it.second().end(); ++it2) { *it2 >> value; profiles.push_back(value); } } } #ifdef ZZZ_DEBUG if (key == "use_debug") { #else if (key == "use_release") { #endif it.second() >> value; profiles.push_back(value); } } for (vector<string>::iterator vi = profiles.begin(); vi != profiles.end(); ++vi) { if (const YAML::Node *p_node = doc.FindValue(*vi)) { ZLOGM << "Load option profile " << ZVAR2("profile", *vi) << endl; LoadOptionProfile(p_node); } else { ZLOGE << "Unable to find profile " << ZVAR2("profile", *vi) << endl; } } if (profiles.empty()) { if (const YAML::Node *p_node = doc.FindValue("default")) { LoadOptionProfile(p_node); } } fi.close(); } void CmdParser::LoadOptionProfile(const YAML::Node *p_node) { for(YAML::Iterator it = p_node->begin(); it != p_node->end(); ++it) { std::string key, value; it.first() >> key; key = string("ZFLAG_") + key; if (it.second().Type() == YAML::NodeType::Scalar) { it.second() >> value; ZLOGD << ZVAR2("Flag", key) << ZVAR2("Value", value) <<endl; bool res = ParseLongOption(key, value.c_str()); if (!res) ZLOGE << "Unknown option: " << ZVAR(key) << ZVAR(value) <<endl; } else { for (YAML::Iterator it2 = it.second().begin(); it2 != it.second().end(); ++it2) { *it2 >> value; ZLOGD << ZVAR2("Flag", key) << ZVAR2("Value", value) <<endl; bool res = ParseLongOption(key, value.c_str()); if (!res) ZLOGE << "Unknown option: " << ZVAR(key) << ZVAR(value) <<endl; } } } } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/CmdParser.cpp
C++
gpl3
10,708
#pragma once namespace zzz{ class Uncopyable { protected: Uncopyable() {} ~Uncopyable() {} private: Uncopyable(const Uncopyable&); const Uncopyable& operator=(const Uncopyable&); }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/Uncopyable.hpp
C++
gpl3
205
#pragma once namespace zzz { //for automatically destroy template<typename T> class SingletonDestroyer { public: SingletonDestroyer():obj(0){} ~SingletonDestroyer(){delete obj;} T *obj; }; template<typename T> class Singleton { public: static T& Instance() { if (instance_ == 0) { instance_ = new T; destroyer_.obj=instance_; } return *instance_; } protected: Singleton() { instance_=0; } private: static T* instance_; static SingletonDestroyer<T> destroyer_; }; template<typename T> T* Singleton<T>::instance_ = 0; template<typename T> SingletonDestroyer<T> Singleton<T>::destroyer_; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/Singleton.hpp
C++
gpl3
706
#pragma once #include "../common.hpp" namespace zzz{ template <typename T> struct ObjectCounter { static size_t count_; ObjectCounter() {++count_;} ObjectCounter (const ObjectCounter<T> &) {++count_;} ~ObjectCounter() {--count_;} static size_t NumOfLiving() {return count_;} }; // initialize counter with zero template <typename T> size_t ObjectCounter<T>::count_ = 0; }
zzz-engine
zzzEngine/zCore/zCore/Utility/ObjectCounter.hpp
C++
gpl3
406
#pragma once #include "AutoloadCacheSet.hpp" namespace zzz{ // It need a IndexSet<string, IDX> to provide filename, and load will call LoadFile(filename) to load object. // The object need to implement IOData interface. // Image is a good example. template<typename T, typename IDX> class ObjectCacheSet : public AutoloadCacheSet<T*, IDX> { public: using AutoloadCacheSet<T*, IDX>::SetSize; using AutoloadCacheSet<T*, IDX>::Clear; void SetData(IndexSet<string, IDX> *fset, zuint cache_size) { Clear(); filenameSet=fset; SetSize(cache_size); } string GetFilename(const IDX &i) { return filenameSet->Get(i); } private: T* Load(const IDX &i) { T *obj=new T; obj->LoadFile(GetFilename(i).c_str()); return obj; } IndexSet<string, IDX> *filenameSet; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/ObjectCacheSet.hpp
C++
gpl3
831
#pragma once #include "../common.hpp" namespace zzz{ #ifdef NO_ZCHECKPOINT #define ZCHECKPOINT(msg) ; #else #define ZCHECKPOINT(msg) ZLOGI<<"*CP* "<<msg<<" at file: "<<__FILE__<<" line: "<<__LINE__<<endl; #endif }
zzz-engine
zzzEngine/zCore/zCore/Utility/CheckPoint.hpp
C++
gpl3
227
#pragma once #include <zCoreConfig.hpp> #include <LibraryConfig.hpp> #include "../common.hpp" #ifdef ZZZ_LIB_BOOST #define BOOST_FILESYSTEM_VERSION 2 #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #endif namespace zzz{ ////////////////////////////////////////////////////////////////////////// //path #ifdef ZZZ_LIB_BOOST typedef boost::filesystem::path Path; #else typedef string Path; #endif ZCORE_FUNC string GetExt(const string &str); ZCORE_FUNC string GetBase(const string &str); ZCORE_FUNC string GetFilename(const string &str); ZCORE_FUNC string GetPath(const string &str); ZCORE_FUNC vector<string> SplitPath(const string &path); ZCORE_FUNC string CompleteDirName(const string &str); ZCORE_FUNC string PathFile(const string &path,const string &file); ZCORE_FUNC string RelativeTo(const string &a,const string &to_a); ZCORE_FUNC void NormalizePath(string &path); ZCORE_FUNC bool PathEquals(const string &f1, const string &f2); ZCORE_FUNC string CurrentPath(); ZCORE_FUNC string InitialPath(); /////////////////////////////////////////////////////////////////////////// //file operation ZCORE_FUNC bool FileCanOpen(const string &filename); ZCORE_FUNC bool FileExists(const string &filename); ZCORE_FUNC bool DirExists(const string &filename); ZCORE_FUNC bool IsSymlink(const string &filename); ZCORE_FUNC void ListFileOnly(const string &path, bool recursive, vector<string> &files); ZCORE_FUNC void ListDirOnly(const string &path, bool recursive, vector<string> &files); ZCORE_FUNC void ListFileAndDir(const string &path, bool recursive, vector<string> &files); ZCORE_FUNC bool CopyFile(const string &from, const string &to); ZCORE_FUNC bool RenameFile(const string &from, const string &to); ZCORE_FUNC bool RemoveFile(const string &f, bool recursive=false); ZCORE_FUNC bool MakeDir(const string &dir); ZCORE_FUNC bool MakeHardLink(const string &from, const string &to); ZCORE_FUNC bool MakeSymLink(const string &from, const string &to); ////////////////////////////////////////////////////////////////////////// //file ZCORE_FUNC unsigned long GetFileSize(const string &filename); ZCORE_FUNC bool ReadFileToString(const string &filename,char **buf); ZCORE_FUNC bool ReadFileToString(const string &filename,string &buf); ZCORE_FUNC bool SaveStringToFile(const string &filename,string &buf); ZCORE_FUNC string RemoveComments_copy(const string &buf); ZCORE_FUNC bool RemoveComments(string &buf); /////////////////////////////////////////////////////////////////////////// //help function ZCORE_FUNC zuint FileCountLine(ifstream &fi); }
zzz-engine
zzzEngine/zCore/zCore/Utility/FileTools.hpp
C++
gpl3
2,660
#pragma once #include <common.hpp> namespace zzz { template <typename T> class zVar { public: zVar(const T &v):v_(v){} friend inline ostream& operator<<(ostream& os, const zVar<T> &me) { os<<me.v_; return os; } private: const T &v_; }; //Use zout<<GetzVar(X) will output x only //Use zout<<ZVAR(X) will output {X:x_value} template<typename T> inline const zVar<T> GetzVar(const T &v) {return zVar<T>(v);} #define ZVAR(x) "{"<<#x<<"="<<GetzVar(x)<<"}" #define ZVAR2(name, x) "{"<<name<<"="<<GetzVar(x)<<"}" template <typename T1, typename T2> class zVar<std::pair<T1, T2> > { public: zVar(const std::pair<T1, T2> &v):v_(v){} friend inline ostream& operator<<(ostream& os, const zVar<std::pair<T1, T2> > &me) { os<<GetzVar(me.v_.first)<<', '<<GetzVar(me.v_.second); return os; } private: const std::pair<T1, T2> &v_; }; #define STL_CONTAINER_ZVAR(CONTAINER) \ template <typename T>\ class zVar< CONTAINER<T> > {\ public:\ zVar(const CONTAINER<T> &v):v_(v){}\ friend inline ostream& operator<<(ostream& os, const zVar< CONTAINER<T> > &me) {\ os<<ZVAR2("Size", me.v_.size());\ int i;\ os << '[';\ CONTAINER<T>::const_iterator vi;\ for (i = 0, vi =me.v_.begin(); i < 10 && vi!=me.v_.end(); ++vi, ++i)\ os << '<' << GetzVar(*vi) << '>';\ if (i == 0 && vi != me.v_.end())\ os << "<...>";\ os << ']';\ return os;\ }\ private:\ const CONTAINER<T> &v_;\ }; STL_CONTAINER_ZVAR(std::vector); STL_CONTAINER_ZVAR(std::list); STL_CONTAINER_ZVAR(std::deque); STL_CONTAINER_ZVAR(std::stack); STL_CONTAINER_ZVAR(std::queue); STL_CONTAINER_ZVAR(std::set); STL_CONTAINER_ZVAR(std::multiset); }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/zVar.hpp
C++
gpl3
1,748
#define ZCORE_SOURCE #include "Port.hpp" #include "StringPrintf.hpp" namespace zzz { void StringAppendV(string &dst, const char *format, va_list ap) { char data[512]; va_list oldap; va_copy(oldap, ap); int result = vsnprintf(data, sizeof(data), format, oldap); va_end(oldap); if (result >= 0 && result < sizeof(data)) { dst.append(data, result); return; } int length = sizeof(data); while(true) { if (result < 0) { length *= 2; } else { length = result + 1; } char *moredata = new char[length]; va_copy(oldap, ap); result = vsnprintf(moredata, length, format, oldap); va_end(oldap); if (result > 0 && result < length) { dst.append(moredata, result); delete[] moredata; return; } delete[] moredata; } } string StringPrintf(const char *format, ...) { va_list ap; va_start(ap, format); string result; StringAppendV(result, format, ap); va_end(ap); return result; } const string &SStringPrintf(string &dst, const char *format, ...) { va_list ap; va_start(ap, format); dst.clear(); StringAppendV(dst, format, ap); va_end(ap); return dst; } void StringAppendF(string &dst, const char *format, ...) { va_list ap; va_start(ap, format); StringAppendV(dst, format ,ap); va_end(ap); } } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/StringPrintf.cpp
C++
gpl3
1,400
#pragma once #include <zCoreConfig.hpp> #include "../common.hpp" namespace zzz { ZCORE_FUNC string StringPrintf(const char *format, ...); ZCORE_FUNC const string &SStringPrintf(string &dst, const char *format, ...); ZCORE_FUNC void StringAppendF(string &dst, const char *format, ...); } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/StringPrintf.hpp
C++
gpl3
315
#pragma once #include <zCoreConfig.hpp> #include <common.hpp> #include "Singleton.hpp" #include "zVar.hpp" #include "StringTools.hpp" namespace zzz{ ///////////////////////////////////////////////// // VerboseLevel Setter class VerboseLevel { public: static int Set(int x) { old_=Get(); verbose_level_=x; return old_; } static void Restore() { Set(old_); } static int Get() { return verbose_level_; } private: ZCORE_FUNC static int old_; ZCORE_FUNC static int verbose_level_; }; class ZCORE_CLASS GlobalLogger : public Singleton<GlobalLogger> { public: GlobalLogger(); ~GlobalLogger(); void Clear(); void Add(ostream *s); typedef enum { WHITE, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, DARKRED, DARKGREEN, DARKYELLOW, DARKBLUE, DARKMAGENTA, DARKCYAN, } LoggerColor; void SetColor(LoggerColor color); void TestPrint(); ZCORE_FUNC friend GlobalLogger& operator<<(GlobalLogger &,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)); ZCORE_FUNC friend GlobalLogger& operator<<(GlobalLogger &,ostream &v); ZCORE_FUNC friend GlobalLogger& operator<<(GlobalLogger &,const string &v); ZCORE_FUNC friend GlobalLogger& operator<<(GlobalLogger &,const char *v); private: vector<ostream*> ostreams_; vector<ofstream*> ofstreams_; void ReallySetColor(); LoggerColor next_color_; LoggerColor cur_color_; }; ZCORE_FUNC GlobalLogger& operator<<(GlobalLogger &,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)); ZCORE_FUNC GlobalLogger& operator<<(GlobalLogger &,ostream &v); ZCORE_FUNC GlobalLogger& operator<<(GlobalLogger &,const string &v); ZCORE_FUNC GlobalLogger& operator<<(GlobalLogger &,const char *v); template<typename T> GlobalLogger& operator<<(GlobalLogger &g, const T &v) { return g<<(ToString(v)); } //////////////////////////////////////////// #ifdef ZZZ_NO_LOG #define zout (cout) #else #define zout (GlobalLogger::Instance()) #endif ///////////////////////////////////////////// // Predefined Verbose Level // All debug information, generally the information is useless. const int ZDEBUG=0; // Less important information, report more detailed message. const int ZVERBOSE=30; // Normal information. const int ZINFO=60; // More important information, highlighting. const int ZMORE=70; // An error occurred, but it can be handled. const int ZERROR=80; // An unhandlable error occurred, cannot continue. const int ZFATAL=100; //////////////////////////////////////////// class ZCORE_CLASS LevelLogger { public: explicit LevelLogger(int level, const char *filename=NULL, int line=-1):level_(level) { if (level_ >= ZFATAL) zout.SetColor(GlobalLogger::MAGENTA); else if (level_ >= ZERROR) zout.SetColor(GlobalLogger::RED); else if (level_ >= ZMORE) zout.SetColor(GlobalLogger::YELLOW); else if (level_ >= ZINFO) zout.SetColor(GlobalLogger::WHITE); else if (level_ >= ZVERBOSE) zout.SetColor(GlobalLogger::GRAY); else zout.SetColor(GlobalLogger::GREEN); if (filename!=NULL && level >= VerboseLevel::Get()) { // Visual Studio Style zout<<filename<<'('<<line<<"): "; } } ~LevelLogger(); ZCORE_FUNC friend const LevelLogger& operator<<(const LevelLogger &,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)); ZCORE_FUNC friend const LevelLogger& operator<<(const LevelLogger &,ostream &v); ZCORE_FUNC friend const LevelLogger& operator<<(const LevelLogger &,const string &v); ZCORE_FUNC friend const LevelLogger& operator<<(const LevelLogger &,const char *v); private: int level_; }; ZCORE_FUNC const LevelLogger& operator<<(const LevelLogger &,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)); ZCORE_FUNC const LevelLogger& operator<<(const LevelLogger &,ostream &v); ZCORE_FUNC const LevelLogger& operator<<(const LevelLogger &,const string &v); ZCORE_FUNC const LevelLogger& operator<<(const LevelLogger &,const char *v); template<typename T> const LevelLogger& operator<<(const LevelLogger &logger, const T &v) { ostringstream oss; oss<<v; return logger<<oss.str(); } ///////////////////////////////////////////// class DummyLevelLogger : public LevelLogger { public: DummyLevelLogger():LevelLogger(-1){}; friend const DummyLevelLogger& operator<<(const DummyLevelLogger &,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)); friend const DummyLevelLogger& operator<<(const DummyLevelLogger &,ostream &v); friend const DummyLevelLogger& operator<<(const DummyLevelLogger &,const string &v); friend const DummyLevelLogger& operator<<(const DummyLevelLogger &,const char *v); template<typename T> friend const DummyLevelLogger& operator<<(const DummyLevelLogger &, const T &v); }; template<typename T> const DummyLevelLogger& operator<<(const DummyLevelLogger &logger, const T &v) { return ; } // Normal log, always logging // ZL* will output the file and line of logging place #define ZLOG(level) if (level >= VerboseLevel::Get()) LevelLogger(level) #define ZLLOG(level) if (level >= VerboseLevel::Get()) LevelLogger(level,__FILE__,__LINE__) // Debug log, only log at debug mode #ifdef ZZZ_DEBUG #define ZDLOG(level) ZLOG(level) #define ZLDLOG(level) ZLLOG(level) #else #define ZDLOG(level) (DummyLevelLogger()) #define ZLDLOG(level) (DummyLevelLogger()) #endif // Release log, only log at non-fastest mode #ifndef ZZZ_FASTEST #define ZRLOG(level) ZLOG(level) #define ZLRLOG(level) ZLLOG(level) #else #define ZRLOG(level) (DummyLevelLogger()) #define ZLRLOG(level) (DummyLevelLogger()) #endif #define ZCHECK_WITH_MSG(x, msg) if (!(x)) ZLLOG(ZFATAL)<<msg #ifdef ZZZ_DEBUG #define ZDCHECK_WITH_MSG(x, msg) if (!(x)) ZLDLOG(ZFATAL)<<msg #else #define ZDCHECK_WITH_MSG(x, msg) (x);DummyLevelLogger() #endif #ifndef ZZZ_FASTEST #define ZRCHECK_WITH_MSG(x, msg) if (!(x)) ZLRLOG(ZFATAL)<<msg #else #define ZRCHECK_WITH_MSG(x, msg) (x);DummyLevelLogger() #endif #define ZCHECK(x) ZCHECK_WITH_MSG((x), #x<<" must be TRUE!") #define ZCHECK_FALSE(x) ZCHECK_WITH_MSG((!(x)), #x<<" must be FALSE!") #define ZDCHECK(x) ZDCHECK_WITH_MSG((x), #x<<" is false!") #define ZDCHECK_FALSE(x) ZDCHECK_WITH_MSG((!(x)), #x<<" must be FALSE!") #define ZRCHECK(x) ZRCHECK_WITH_MSG((x), #x<<" is false!") #define ZRCHECK_FALSE(x) ZRCHECK_WITH_MSG((!(x)), #x<<" must be FALSE!") // Combine #define ZCHECK_BOTH(x, y) ZCHECK_WITH_MSG((x) && (y), "Both "<< #x <<" and "<<#y<<" must be TRUE!") #define ZCHECK_EITHER(x, y) ZCHECK_WITH_MSG((x) || (y), "Either "<<#x <<" or "<<#y<<" must be TRUE!") #define ZCHECK_NEITHER(x, y) ZCHECK_WITH_MSG(!(x) && !(y), "Neither "<<#x <<" or "<<#y<<" can be TRUE!") #define ZDCHECK_BOTH(x, y) ZDCHECK_WITH_MSG((x) && (y), "Both "<< #x <<" and "<<#y<<" must be TRUE!") #define ZDCHECK_EITHER(x, y) ZDCHECK_WITH_MSG((x) || (y), "Either "<<#x <<" or "<<#y<<" must be TRUE!") #define ZDCHECK_NEITHER(x, y) ZDCHECK_WITH_MSG(!(x) && !(y), "Neither "<<#x <<" or "<<#y<<" can be TRUE!") // Math #define ZCHECK_EQ(x, y) ZCHECK_WITH_MSG((x)==(y), #x<<" must be equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZCHECK_NE(x, y) ZCHECK_WITH_MSG((x)!=(y), #x<<" must be not equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZCHECK_LT(x, y) ZCHECK_WITH_MSG((x)<(y), #x<<" must be less than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZCHECK_LE(x, y) ZCHECK_WITH_MSG((x)<=(y), #x<<" must be no more than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZCHECK_GT(x, y) ZCHECK_WITH_MSG((x)>(y), #x<<" must be greater than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZCHECK_GE(x, y) ZCHECK_WITH_MSG((x)>=(y), #x<<" must be no less than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_EQ(x, y) ZDCHECK_WITH_MSG((x)==(y), #x<<" must be equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_NE(x, y) ZDCHECK_WITH_MSG((x)!=(y), #x<<" must be not equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_LT(x, y) ZDCHECK_WITH_MSG((x)<(y), #x<<" must be less than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_LE(x, y) ZDCHECK_WITH_MSG((x)<=(y), #x<<" must be no more than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_GT(x, y) ZDCHECK_WITH_MSG((x)>(y), #x<<" must be greater than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZDCHECK_GE(x, y) ZDCHECK_WITH_MSG((x)>=(y), #x<<" must be no less than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_EQ(x, y) ZRCHECK_WITH_MSG((x)==(y), #x<<" must be equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_NE(x, y) ZRCHECK_WITH_MSG((x)!=(y), #x<<" must be not equal to "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_LT(x, y) ZRCHECK_WITH_MSG((x)<(y), #x<<" must be less than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_LE(x, y) ZRCHECK_WITH_MSG((x)<=(y), #x<<" must be no more than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_GT(x, y) ZRCHECK_WITH_MSG((x)>(y), #x<<" must be greater than "<<#y<<ZVAR(x)<<ZVAR(y)) #define ZRCHECK_GE(x, y) ZRCHECK_WITH_MSG((x)>=(y), #x<<" must be no less than "<<#y<<ZVAR(x)<<ZVAR(y)) // Within #define ZCHECK_WITHIN(_min, _x, _max) ZCHECK_WITH_MSG(Within(_min, _x, _max), #_x<<" must be within "<<_min<<" and "<<_max<<ZVAR(_x)) #define ZDCHECK_WITHIN(_min, _x, _max) ZDCHECK_WITH_MSG(Within(_min, _x, _max), #_x<<" must be within "<<_min<<" and "<<_max<<ZVAR(_x)) #define ZRCHECK_WITHIN(_min, _x, _max) ZRCHECK_WITH_MSG(Within(_min, _x, _max), #_x<<" must be within "<<_min<<" and "<<_max<<ZVAR(_x)) // NULL positive, negative #define ZCHECK_NULL(x) ZCHECK_WITH_MSG((x)==NULL, #x<<" must be NULL, "<<ZVAR(x)) #define ZCHECK_NOT_NULL(x) ZCHECK_WITH_MSG((x)!=NULL, #x<<" must NOT be NULL, "<<ZVAR(x)) #define ZCHECK_ZERO(x) ZCHECK_WITH_MSG((x)==0, #x<<" must be 0, "<<ZVAR(x)) #define ZCHECK_NOT_ZERO(x) ZCHECK_WITH_MSG((x)!=0, #x<<" must NOT be 0, "<<ZVAR(x)) #define ZDCHECK_NULL(x) ZDCHECK_WITH_MSG((x)==NULL, #x<<" must be NULL, "<<ZVAR(x)) #define ZDCHECK_NOT_NULL(x) ZDCHECK_WITH_MSG((x)!=NULL, #x<<" must NOT be NULL, "<<ZVAR(x)) #define ZDCHECK_ZERO(x) ZDCHECK_WITH_MSG((x)==0, #x<<" must be 0, "<<ZVAR(x)) #define ZDCHECK_NOT_ZERO(x) ZDCHECK_WITH_MSG((x)!=0, #x<<" must NOT be 0, "<<ZVAR(x)) #define ZRCHECK_NULL(x) ZRCHECK_WITH_MSG((x)==NULL, #x<<" must be NULL, "<<ZVAR(x)) #define ZRCHECK_NOT_NULL(x) ZRCHECK_WITH_MSG((x)!=NULL, #x<<" must NOT be NULL, "<<ZVAR(x)) #define ZRCHECK_ZERO(x) ZRCHECK_WITH_MSG((x)==0, #x<<" must be 0, "<<ZVAR(x)) #define ZRCHECK_NOT_ZERO(x) ZRCHECK_WITH_MSG((x)!=0, #x<<" must NOT be 0, "<<ZVAR(x)) #define ZLOGI ZLOG(ZINFO) #define ZLOGD ZLOG(ZDEBUG) #define ZLOGV ZLOG(ZVERBOSE) #define ZLOGM ZLOG(ZMORE) #define ZLOGE ZLLOG(ZERROR) #define ZLOGF ZLLOG(ZFATAL) #define ZDLOGI ZDLOG(ZINFO) #define ZDLOGD ZDLOG(ZDEBUG) #define ZDLOGV ZDLOG(ZVERBOSE) #define ZDLOGM ZDLOG(ZMORE) #define ZDLOGE ZLDLOG(ZERROR) #define ZDLOGF ZLDLOG(ZFATAL) #define ZRLOGI ZRLOG(ZINFO) #define ZRLOGD ZDLOG(ZDEBUG) #define ZRLOGV ZRLOG(ZVERBOSE) #define ZRLOGM ZRLOG(ZMORE) #define ZRLOGE ZLRLOG(ZERROR) #define ZRLOGF ZLRLOG(ZFATAL) #define ZMSG (ZLOGI) //////////////////////////////////////////////// string SplitLine(const string &msg, int linelen=60); string SplitLine3(const string &msg, int linelen=60); class ScopeMessage { public: ScopeMessage(const string &msg) {ZLOGI << msg << " ... ";} ~ScopeMessage() {ZLOGI << "Done.\n";} }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/Log.hpp
C++
gpl3
11,332
#pragma once #include "CacheSet.hpp" #include "Log.hpp" // It is a kind of cache set. // The different from cache set is it will automatically load when get fails. // Derived class should overload Load() to load correct object. namespace zzz{ template<typename T, typename IDX=zuint> class AutoloadCacheSet : public CacheSet<T, IDX> { public: // Get data. T Get(const IDX &i) { T ret = CacheSet<T,IDX>::Get(i); if (ret == NULL) { ret = Load(i); Add(i, ret); } return ret; } // Reload data T Reload(const IDX &i) { T ret = CacheSet<T,IDX>::Get(i); if (ret != NULL) { ret = Load(i); Add(i, ret); } else { delete ret; ret = Load(i); } return ret; } protected: virtual T Load(const IDX& i)=0; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/AutoloadCacheSet.hpp
C++
gpl3
826
#define ZCORE_SOURCE #include "RecordFile.hpp" #include "IOObject.hpp" namespace zzz { typedef pair<int, zint64> TableItem; SIMPLE_IOOBJECT(TableItem); RecordItem::RecordItem(FILE *fp, zint64 itebegin_pos_, RecordItem *parent) :fp_(fp), itebegin_pos__(itebegin_pos_), child_(NULL), repeat_label_(-1), parent_(parent) { SetPos(itebegin_pos__+sizeof(zint64)); } ////////////////////////////////////////////////////////////////////////// // Read void RecordItem::ReadTable() { SetPos(itebegin_pos__); IOObj::ReadFileB(fp_, table_begin_pos_); SetPos(table_begin_pos_); IOObject<vector<TableItem> >::ReadFileB(fp_, table_); } RecordItem* RecordItem::ReadChild(const zint32 label) { ZCHECK(CheckLabelExist(label)); if (child_) delete child_; child_=new RecordItem(fp_, GetChildPos(label), this); child_->ReadTable(); return child_; } RecordItem* RecordItem::ReadFinish() { return parent_; } RecordItem* RecordItem::ReadRepeatBegin(const zint32 label) { ZCHECK(CheckLabelExist(label)); if (child_) delete child_; child_ = new RecordItem(fp_, GetChildPos(label), this); child_->ReadTable(); child_->repeat_label_=0; return child_; } RecordItem* RecordItem::ReadRepeatChild() { if (parent_->repeat_label_>=0) { // It's parent is repeat head. return parent_->ReadRepeatChild(); } else { // Itself is repeat head. repeat_label_++; if (!CheckLabelExist(repeat_label_)) return NULL; return ReadChild(repeat_label_); } } size_t RecordItem::GetRepeatNumber() { if (parent_->repeat_label_>=0) { // It's child is repeat head. return parent_->GetItemNumber(); } else { // Itself is repeat head. return GetItemNumber(); } } RecordItem* RecordItem::ReadRepeatEnd() { if (parent_->repeat_label_>=0) { return parent_->ReadRepeatEnd(); } else { if (child_) { child_->ReadFinish(); delete child_; child_=NULL; } return ReadFinish(); } } size_t RecordItem::Read(const zint32 label, void *data, size_t size, size_t count) { if (!CheckLabelExist(label)) return 0; SetPos(GetChildPos(label)); return Read(data, size, count); } size_t RecordItem::Read(void *data, size_t size, size_t count) { return fread(data, size, count, fp_); } ////////////////////////////////////////////////////////////////////////// // Write RecordItem* RecordItem::WriteChild(const zint32 label) { ZCHECK_FALSE(CheckLabelExist(label)) << "Label "<<label<<" already existed!\n"; zint64 pos=GetPos(); if (child_) delete child_; child_=new RecordItem(fp_, pos, this); table_.push_back(make_pair(label, pos)); return child_; } RecordItem* RecordItem::WriteFinish() { // Save current position. table_begin_pos_ = GetPos(); // Write table. IOObject<vector<TableItem> >::WriteFileB(fp_, table_); zint64 end_pos = GetPos(); // Jump back. SetPos(itebegin_pos__); // Write table begin position. IOObject<zint64>::WriteFileB(fp_, table_begin_pos_); // Jump to end SetPos(end_pos); return parent_; } RecordItem* RecordItem::WriteRepeatBegin(const zint32 label) { WriteChild(label); child_->repeat_label_=0; return child_; } RecordItem* RecordItem::WriteRepeatChild() { if (parent_->repeat_label_>=0) { // It's parent is repeat head. return parent_->WriteRepeatChild(); } else { // Itself is repeat head if (child_) { child_->WriteFinish(); } repeat_label_++; return WriteChild(repeat_label_); } } RecordItem* RecordItem::WriteRepeatEnd() { if (parent_->repeat_label_>=0) { return parent_->WriteRepeatEnd(); } else { if (child_) { child_->WriteFinish(); delete child_; child_=NULL; } return WriteFinish(); } } size_t RecordItem::Write(const zint32 label, const void *data, size_t size, size_t count) { ZCHECK_FALSE(CheckLabelExist(label)) << "Label "<<label<<" already existed!\n"; table_.push_back(make_pair(label, GetPos())); return Write(data, size, count); } size_t RecordItem::Write(const void *data, size_t size, size_t count) { return fwrite(data, size, count, fp_); } bool RecordItem::LabelExist(const zint32 label) { if (child_!=NULL) return child_->LabelExist(label); return CheckLabelExist(label); } bool RecordItem::CheckLabelExist(const zint32 label) { for (zuint i=0; i<table_.size(); i++) if (table_[i].first==label) return true; return false; } zint64 RecordItem::GetChildPos(const zint32 label) { for (zuint i=0; i<table_.size(); i++) if (table_[i].first==label) return table_[i].second; return -1; } zint64 RecordItem::GetPos() { fpos_t pos; ZCHECK(fgetpos(fp_, &pos)==0); return pos; } void RecordItem::SetPos(zint64 pos) { fpos_t fpos=pos; ZCHECK(fsetpos(fp_, &fpos)==0); } size_t RecordItem::GetItemNumber() { return table_.size(); } ////////////////////////////////////////////////////////////////////////// // RecordFile const int RECORDFILE_MAGIC=1124; RecordFile::RecordFile() :head_(NULL), fp_(NULL), cur_(NULL) {} void RecordFile::LoadFileBegin(const string &filename) { ZCHECK_NULL(fp_); ZCHECK_NULL(head_); ZCHECK(fp_=fopen(filename.c_str(), "rb")); int magic; fread(&magic, sizeof(magic), 1, fp_); ZCHECK(magic==RECORDFILE_MAGIC); head_=new RecordItem(fp_, sizeof(RECORDFILE_MAGIC), NULL); head_->ReadTable(); cur_=head_; write_=false; } void RecordFile::LoadFileEnd() { ZCHECK_NOT_NULL(fp_); ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); head_->ReadFinish(); delete head_; head_=NULL; cur_=NULL; ZCHECK(fclose(fp_)==0); fp_=NULL; } void RecordFile::SaveFileBegin(const string &filename) { ZCHECK_NULL(fp_); ZCHECK_NULL(head_); ZCHECK(fp_=fopen(filename.c_str(), "wb")) << ZVAR(filename); fwrite(&RECORDFILE_MAGIC, sizeof(RECORDFILE_MAGIC), 1, fp_); head_=new RecordItem(fp_, sizeof(RECORDFILE_MAGIC), NULL); cur_=head_; write_=true; } void RecordFile::SaveFileEnd() { ZCHECK_NOT_NULL(fp_); ZCHECK_NOT_NULL(head_); ZCHECK(write_); head_->WriteFinish(); delete head_; head_=NULL; cur_=NULL; ZCHECK_ZERO(fclose(fp_)); fp_=NULL; } void RecordFile::ReadChildBegin(const zint32 label) { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); cur_=cur_->ReadChild(label); } void RecordFile::ReadChildEnd() { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); cur_=cur_->ReadFinish(); } void RecordFile::ReadRepeatBegin(const zint32 label) { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); cur_=cur_->ReadRepeatBegin(label); } bool RecordFile::ReadRepeatChild() { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); RecordItem *next=cur_->ReadRepeatChild(); if (next==NULL) return false; cur_=next; return true; } void RecordFile::ReadRepeatEnd() { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); cur_=cur_->ReadRepeatEnd(); } size_t RecordFile::Read(void *data, size_t size, size_t count) { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); return cur_->Read(data, size, count); } size_t RecordFile::Read(const zint32 label, void *data, size_t size, size_t count) { ZCHECK_NOT_NULL(head_); ZCHECK_FALSE(write_); return cur_->Read(label, data, size, count); } void RecordFile::WriteChildBegin(const zint32 label) { ZCHECK_NOT_NULL(head_); ZCHECK(write_); cur_=cur_->WriteChild(label); } void RecordFile::WriteChildEnd() { ZCHECK_NOT_NULL(head_); ZCHECK(write_); cur_=cur_->WriteFinish(); } void RecordFile::WriteRepeatBegin(const zint32 label) { ZCHECK_NOT_NULL(head_); ZCHECK(write_); cur_=cur_->WriteRepeatBegin(label); } void RecordFile::WriteRepeatChild() { ZCHECK_NOT_NULL(head_); ZCHECK(write_); cur_=cur_->WriteRepeatChild(); } void RecordFile::WriteRepeatEnd() { ZCHECK_NOT_NULL(head_); ZCHECK(write_); cur_=cur_->WriteRepeatEnd(); } size_t RecordFile::Write(const void *data, size_t size, size_t count) { ZCHECK_NOT_NULL(head_); ZCHECK(write_); return cur_->Write(data, size, count); } size_t RecordFile::Write(const zint32 label, const void *data, size_t size, size_t count) { ZCHECK_NOT_NULL(head_); ZCHECK(write_); return cur_->Write(label, data, size, count); } bool RecordFile::LabelExist(const zint32 label) { return cur_->LabelExist(label); } }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/RecordFile.cpp
C++
gpl3
8,578
#define ZCORE_SOURCE #include "Thread.hpp" #ifdef ZZZ_LIB_PTHREAD namespace zzz{ void *__start_thread(void *p) { Thread *pt=(Thread*)p; pt->running=true; pt->Main(); pt->running=false; // pthread_exit(NULL); return NULL; } Thread::Thread() { running=false; } void Thread::Start() { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int rc = pthread_create(&thread, &attr, __start_thread, (void *)this); pthread_attr_destroy(&attr); } void Thread::Wait() { void *status; int rc = pthread_join(thread, &status); } bool Thread::IsRunning() { return running; } Mutex::Mutex() { pthread_mutex_init(&mutex, NULL); } Mutex::~Mutex() { pthread_mutex_destroy(&mutex); } void Mutex::Lock() { pthread_mutex_lock(&mutex); } void Mutex::Unlock() { pthread_mutex_unlock(&mutex); } bool Mutex::TryLock() { if (pthread_mutex_trylock(&mutex)==0) return true; else return false; } Condition::Condition() { pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); } Condition::~Condition() { pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } void Condition::Check() { pthread_mutex_lock(&mutex); if (IsSatisfied()) pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } void Condition::Wait() { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } } #endif // ZZZ_LIB_PTHREAD
zzz-engine
zzzEngine/zCore/zCore/Utility/Thread.cpp
C++
gpl3
1,555
#pragma once #include <common.hpp> #include "Singleton.hpp" #include "AnyHolder.hpp" namespace zzz{ typedef Singleton<AnyHolder> Global; #define ZGLOBAL_ADD(v, name) zzz::Global::Instance().Add(v, name, false) #define ZGLOBAL_GET(type, name) (zzz::Global::Instance().Get<type>(name)) #define ZGLOBAL_ISTYPE(type, name) (zzz::Global::Instance().IsType<type>(name)) #define ZGLOBAL_ISEXIST(name) (zzz::Global::Instance().IsExist(name)) template<typename T> class GlobalRegisterHelper { public: GlobalRegisterHelper(const string &name, T* var) { ZGLOBAL_ADD(var, name); } }; #define ZGLOBAL_DEFINE(type, name, default_value) \ type name = default_value; \ GlobalRegisterHelper<type> ___GLOBAL_##name##_HELPER___(#name, &name); }
zzz-engine
zzzEngine/zCore/zCore/Utility/Global.hpp
C++
gpl3
767
#pragma once #include "Any.hpp" #include "Log.hpp" namespace zzz { class AnyHolder { public: virtual ~AnyHolder() { Clear(); } template<typename T> bool Add(T v, const string &name, bool cover=false) { if (holder_.find(name)!=holder_.end()) { if (cover) { Remove(name); ZLOG(ZVERBOSE)<<"Duplicated name in AnyHolder: "<<name<<", removed the old one!\n"; } else { ZLOG(ZVERBOSE)<<"Duplicated name in AnyHolder: "<<name<<", refuse to add!\n"; return false; } } holder_[name]=Any(v); return true; } virtual bool Remove(const string &name) { map<string,Any>::iterator mi=holder_.find(name); if (mi==holder_.end()) { ZLOG(ZERROR)<<"object "<<name<<" is not in ResourceManager\n"; return false; } Destroy(mi->second); holder_.erase(mi); return true; } virtual void Clear() { for (map<string,Any>::iterator mi=holder_.begin();mi!=holder_.end();mi++) Destroy(mi->second); holder_.clear(); } template<typename T> T Get(const string &name) { map<string,Any>::iterator mi=holder_.find(name); if (mi==holder_.end()) ZLOG(ZFATAL)<<"Any Holder cannot find: "<<name<<endl; return any_cast<T>(mi->second); } bool IsExist(const string &name) { return holder_.find(name) != holder_.end(); } template<typename T> bool IsType(const string &name) { map<string,Any>::iterator mi=holder_.find(name); if (mi==holder_.end()) { ZLOG(ZFATAL)<<"Any Holder cannot find: "<<name<<endl; return false; // Will exit before reach this line. } else return mi->second.IsType<T>(); } bool Rename(const string &oldname, const string &newname) { map<string,Any>::iterator mi=holder_.find(oldname); if (mi == holder_.end()) { ZLOG(ZERROR)<<"Cannot find: "<<oldname<<endl; return false; } if (holder_.find(newname)!=holder_.end()) { ZLOG(ZERROR)<<"Already existed: "<<newname<<endl; return false; } holder_[newname]=mi->second; holder_.erase(oldname); return true; } protected: virtual void Destroy(Any &v){} map<string, Any> holder_; }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Utility/AnyHolder.hpp
C++
gpl3
2,286
#pragma once #include "IndexSet.hpp" #include "../Math/Math.hpp" #include "Log.hpp" // It is a kind of indexed set. // It will return an object based on an index. // What's special is that it will cache some objects based on Least-Recent-Access. // When an object is added, and cache is full, one object will deleted. // When some objects need to be deleted, the Least-Recent-Access object will be deleted. namespace zzz{ template<typename T, typename IDX=zuint> class CacheSet : public IndexSet<T, IDX> { public: CacheSet(int cache_size=10):cache_size_(cache_size), INVALID_INDEX(MAX_UINT){} virtual ~CacheSet(){Clear();} // Set all data size and cache size // Will call Reset() void SetSize(zuint cache_size) { ZCHECK_GT(cache_size, 0); cache_size_=cache_size; Reset(); } void Add(const IDX &i, T x) { // Object is not in cache, replace the tail(least recent get one). if (data_[tail_]) { delete data_[tail_]; idx_to_obj_.erase(idx_[tail_]); } data_[tail_]=x; idx_[tail_]=i; idx_to_obj_[i]=tail_; MoveFront(tail_); } // Get data, user only need this T Get(const IDX &i) { if (!CheckIndex(i)) { ZLOG(ZERROR)<<"CheckIndex() failed!\n"; return NULL; } map<IDX, zuint>::iterator mi = idx_to_obj_.find(i); if (mi != idx_to_obj_.end()) { // Object is in cache, move item to front and return directly. MoveFront(mi->second); return data_[mi->second]; } // Object is not in cache, return NULL. return NULL; } // User can overload this function to check index, for security reasons. virtual bool CheckIndex(const IDX &i){return true;} //clear all void Clear() { for(zuint i=0; i<data_.size(); i++) { if(data_[i]!=NULL) { delete data_[i]; data_[i]=NULL; } } data_.clear(); idx_to_obj_.clear(); prev_.clear(); next_.clear(); } protected: // Reset and load cache. // Should be called before start. void Reset() { Clear(); idx_to_obj_.clear(); head_=0; tail_=cache_size_-1; data_.assign(cache_size_, 0); idx_.resize(cache_size_); prev_.assign(cache_size_, 0); next_.assign(cache_size_, 0); for (zuint i=0; i<cache_size_; i++) { if (i!=0) prev_[i]=i-1; else prev_[i]=INVALID_INDEX; if (i!=cache_size_-1) next_[i]=i+1; else next_[i]=INVALID_INDEX; } } //move to front void MoveFront(zuint i) { //head if (i==head_) return; else if (i==tail_) { //tail to head, prev of tail is tail prev_[head_]=i; next_[i]=head_; head_=i; tail_=prev_[i]; prev_[i]=INVALID_INDEX; next_[tail_]=INVALID_INDEX; return; } else { //middle next_[prev_[i]]=next_[i]; prev_[next_[i]]=prev_[i]; next_[i]=head_; prev_[i]=INVALID_INDEX; prev_[head_]=i; head_=i; } } zuint cache_size_; map<IDX,zuint> idx_to_obj_; zuint head_, tail_; vector<T> data_; vector<IDX> idx_; vector<zuint> prev_, next_; const zuint INVALID_INDEX; }; }
zzz-engine
zzzEngine/zCore/zCore/Utility/CacheSet.hpp
C++
gpl3
3,249
#define ZCORE_SOURCE #include "Log.hpp" #include "CmdParser.hpp" #include "Tools.hpp" #ifdef ZZZ_LIB_BOOST #include <boost/date_time/posix_time/posix_time.hpp> #else #include <ctime> #endif #include "FileTools.hpp" #include "StringPrintf.hpp" #include <EnvDetect.hpp> #include <3rdParty/StackWalker.h> #ifdef ZZZ_OS_WIN #include <windows.h> #endif namespace zzz{ int VerboseLevel::old_=ZINFO; int VerboseLevel::verbose_level_=ZINFO; // If VERBOSE_xxx is defined, a certain verbose level is used // else default for DEBUG is ZDEBUG and for RELEASE is ZVERBOSE #if defined VERBOSE_DEBUG const int DEFAULT_VERBOSE = ZDEBUG; #elif defined VERBOSE_VERBOSE const int DEFAULT_VERBOSE = ZVERBOSE; #elif defined VERBOSE_INFO const int DEFAULT_VERBOSE = ZINFO; #elif defined VERBOSE_WARNING const int DEFAULT_VERBOSE = ZWARNING; #elif defined VERBOSE_ERROR const int DEFAULT_VERBOSE = ZERROR; #elif defined VERBOSE_FATAL const int DEFAULT_VERBOSE = ZFATAL; #elif defined ZZZ_DEBUG const int DEFAULT_VERBOSE = ZDEBUG; #else const int DEFAULT_VERBOSE = ZVERBOSE; #endif ZFLAGS_INT(verbose_level, DEFAULT_VERBOSE, "Set Verbose Level"); ZFLAGS_SWITCH(verbose_debug, "Set Verbose Level: Debug (Show all msg)"); ZFLAGS_SWITCH(verbose_verbose, "Set Verbose Level: Verbose (Show additional msg)"); ZFLAGS_SWITCH(verbose_info, "Set Verbose Level: Info (Show normal msg)"); ZFLAGS_SWITCH(verbose_more, "Set Verbose Level: More (Show more important and error msg)"); ZFLAGS_SWITCH(verbose_error, "Set Verbose Level: Error (Only show error msg)"); ZFLAGS_SWITCH(verbose_fatal, "Set Verbose Level: Fatal (Only show fatal msg)"); ZFLAGS_STRING(glog_file, "", "Global Logger File"); ZFLAGS_BOOL(auto_log, true, "Automatically log to file"); ZFLAGS_STRING(auto_log_dir, GetEnv("ZLOG_DIR"), "Automatically log file directory"); void PostParseVerbose() { if (ZFLAG_verbose_debug) ZFLAG_verbose_level=ZDEBUG; else if (ZFLAG_verbose_verbose) ZFLAG_verbose_level=ZVERBOSE; else if (ZFLAG_verbose_info) ZFLAG_verbose_level=ZINFO; else if (ZFLAG_verbose_more) ZFLAG_verbose_level=ZMORE; else if (ZFLAG_verbose_error) ZFLAG_verbose_level=ZERROR; VerboseLevel::Set(ZFLAG_verbose_level); } ZFLAGS_POST(PostParseVerbose); GlobalLogger::GlobalLogger() : cur_color_(RED), next_color_(WHITE) { ReallySetColor(); // set color to white ostreams_.push_back(&cout); if (!ZFLAG_glog_file.empty()) { ofstream *fo = new ofstream(ZFLAG_glog_file.c_str()); // zlog is not available yet! so we cannot use ZCHECK if (!fo->good()) { cerr<<"Cannot open file "<<ZFLAG_glog_file<<endl; } ofstreams_.push_back(fo); ostreams_.push_back(fo); } if (ZFLAG_auto_log && !ZFLAG_auto_log_dir.empty()) { ZFLAG_auto_log_dir = CompleteDirName(ZFLAG_auto_log_dir); #ifdef ZZZ_LIB_BOOST std::ostringstream msg; const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); boost::posix_time::time_facet *lf = new boost::posix_time::time_facet("%Y_%m_%d-%H_%M_%S"); msg.imbue(std::locale(msg.getloc(),lf)); msg << now; const string timestr = msg.str(); #else time_t rawtime; time(&rawtime); const string timestr = ctime(&rawtime); #endif const string progstr = GetFilename(*ZGLOBAL_GET(string*, "zCurrentProgramName")); const string dirstr = CompleteDirName(PathFile(ZFLAG_auto_log_dir, progstr)); if (!DirExists(dirstr) && !MakeDir(dirstr)) { cerr<<"Cannot create directory "<<dirstr<<endl; cerr<<"This directory is to store default log files for GlobalLogger. If you do not need the log file, set --no_auto_log\n"; exit(-1); } #if defined(ZZZ_DEBUG) const string filename = PathFile(dirstr, StringPrintf("[%s][%s][DEBUG].zlog", timestr.c_str(), progstr.c_str())); #elif defined(ZZZ_FASTEST) const string filename = PathFile(dirstr, StringPrintf("[%s][%s][FASTEST].zlog", timestr.c_str(), progstr.c_str())); #else const string filename = PathFile(dirstr, StringPrintf("[%s][%s][RELEASE].zlog", timestr.c_str(), progstr.c_str())); #endif ofstream *fo = new ofstream(filename); // zlog is not available yet! so we cannot use ZCHECK if (!fo->good()) { cerr<<"Cannot open file "<<filename<<endl; cerr<<"This file is a default log file for GlobalLogger. If you do not need the log file, set --no_auto_log\n"; exit(-1); } ofstreams_.push_back(fo); ostreams_.push_back(fo); } } GlobalLogger::~GlobalLogger() { SetColor(GRAY); ReallySetColor(); } void GlobalLogger::Clear() { ostreams_.clear(); for (zuint i=0; i<ofstreams_.size(); i++) delete ofstreams_[i]; ofstreams_.clear(); } void GlobalLogger::Add(ostream *s) { ostreams_.push_back(s); } void GlobalLogger::SetColor(LoggerColor color) { next_color_ = color; } #ifdef ZZZ_OS_WIN void GlobalLogger::ReallySetColor() { if (cur_color_ == next_color_) return; static HANDLE hCon=NULL; if(hCon == NULL) { hCon = GetStdHandle(STD_OUTPUT_HANDLE); } switch(next_color_) { case WHITE: // White on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); break; case RED: // Red on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_RED); break; case GREEN: // Green on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; case BLUE: // Blue on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_BLUE); break; case YELLOW: // Yellow on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); break; case MAGENTA: // Magenta on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE); break; case CYAN: // Cyan on Black SetConsoleTextAttribute(hCon, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE); break; case GRAY: // White on Black SetConsoleTextAttribute(hCon, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); break; case DARKRED: // Red on Black SetConsoleTextAttribute(hCon, FOREGROUND_RED); break; case DARKGREEN: // Green on Black SetConsoleTextAttribute(hCon, FOREGROUND_GREEN); break; case DARKBLUE: // Blue on Black SetConsoleTextAttribute(hCon, FOREGROUND_BLUE); break; case DARKYELLOW: // Yellow on Black SetConsoleTextAttribute(hCon, FOREGROUND_RED | FOREGROUND_GREEN); break; case DARKMAGENTA: // Magenta on Black SetConsoleTextAttribute(hCon, FOREGROUND_RED | FOREGROUND_BLUE); break; case DARKCYAN: // Cyan on Black SetConsoleTextAttribute(hCon, FOREGROUND_GREEN | FOREGROUND_BLUE); break; } cur_color_ = next_color_; } #else void GlobalLogger::ReallySetColor(){} #endif void GlobalLogger::TestPrint() { SetColor(WHITE); zout<<"WHITE "; SetColor(RED); zout<<"RED "; SetColor(GREEN); zout<<"GREEN "; SetColor(BLUE); zout<<"BLUE "; SetColor(YELLOW); zout<<"YELLOW "; SetColor(MAGENTA); zout<<"MAGENTA "; SetColor(CYAN); zout<<"CYAN "; SetColor(GRAY); zout<<"GRAY "; SetColor(DARKRED); zout << "DARKRED "; SetColor(DARKGREEN); zout << "DARKGREEN "; SetColor(DARKBLUE); zout << "DARKBLUE "; SetColor(DARKYELLOW); zout << "DARKYELLOW "; SetColor(DARKMAGENTA); zout << "DARKMAGENTA "; SetColor(DARKCYAN); zout << "DARKCYAN"; zout << endl; VerboseLevel::Set(ZDEBUG); ZLOGD << "DEBUG MESSAGE\n"; ZLOGV << "VERBOSE MESSAGE\n"; ZLOGI << "INFO MESSAGE\n"; ZLOGM << "MORE IMPORTANT MESSAGE\n"; ZLOGE << "ERROR MESSAGE\n"; ZLOGF << "FATAL MESSAGE\n"; VerboseLevel::Restore(); } GlobalLogger& operator<<(GlobalLogger &g,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)) { g.ReallySetColor(); for (vector<ostream*>::iterator vi = g.ostreams_.begin(); vi != g.ostreams_.end(); ++vi) (**vi) << func << flush; return g; } GlobalLogger& operator<<(GlobalLogger &g,ostream &v) { g.ReallySetColor(); for (vector<ostream*>::iterator vi = g.ostreams_.begin(); vi != g.ostreams_.end(); ++vi) (**vi) << v << flush; return g; } GlobalLogger& operator<<(GlobalLogger &g, const string &v) { g.ReallySetColor(); for (vector<ostream*>::iterator vi = g.ostreams_.begin(); vi != g.ostreams_.end(); ++vi) (**vi) << v << flush; return g; } GlobalLogger& operator<<(GlobalLogger &g, const char *v) { g.ReallySetColor(); for (vector<ostream*>::iterator vi = g.ostreams_.begin(); vi != g.ostreams_.end(); ++vi) (**vi) << v << flush; return g; } //////////////////////////////////////////////// const LevelLogger& operator<<(const LevelLogger &g,basic_ostream<char>& (&func)(basic_ostream<char>& _Ostr)) { zout << func; return g; } const LevelLogger& operator<<(const LevelLogger &g,ostream &v) { zout << v; return g; } const LevelLogger& operator<<(const LevelLogger &g, const string &v) { zout << v; return g; } const LevelLogger& operator<<(const LevelLogger &g, const char *v) { zout << v; return g; } #ifdef ZZZ_OS_WIN class StackWalkerToConsole : public StackWalker { protected: virtual void OnOutput(LPCSTR szText) { ZLOGE << szText; } }; #endif LevelLogger::~LevelLogger() { if (level_ >= ZFATAL) { zout<<endl; #ifdef ZZZ_DEBUG assert(false); #else #ifdef ZZZ_OS_WIN StackWalkerToConsole sw; sw.ShowCallstack(); #endif PressAnyKeyToContinue(); exit(-1); #endif } } string SplitLine3(const string &msg, int linelen) { int len=msg.size(); if (len>=linelen) return string(msg); int flen=(linelen-len)/2; int blen=linelen-len-flen; return string(linelen, '=')+"\n*"+string(flen-1, ' ')+msg+string(blen-1, ' ')+"*\n"+string(linelen, '='); } }
zzz-engine
zzzEngine/zCore/zCore/Utility/Log.cpp
C++
gpl3
10,220
#include "Any.hpp" #include <common.hpp> #include "Singleton.hpp" namespace zzz { class AnyStack { public: template<typename T> void Push(const T &v) { stack_.push(Any(v)); } template<typename T> void Pop(T &v) { Top(v); stack_.pop(); } template<typename T> T Pop() { T v=Top(); stack_.pop(); return v; } template<typename T> void Top(T &v) { v=any_cast<T>(stack_.top()); } template<typename T> T Top() { T v=any_cast<T>(stack_.top()); return v; } void Clear() { while(!stack_.empty()) stack_.pop(); } bool Empty() { return stack_.empty(); } zuint Size() { return stack_.size(); } private: stack<Any> stack_; }; typedef Singleton<AnyStack> GlobalStack; }; // namespace zzz #define ZGS (zzz::GlobalStack::Instance())
zzz-engine
zzzEngine/zCore/zCore/Utility/AnyStack.hpp
C++
gpl3
907
#pragma once #include <3rdParty/getopt.h> #include "../common.hpp" #include "Singleton.hpp" #include "Global.hpp" namespace YAML { class Node; } namespace zzz{ typedef enum {CMDPARSER_NOARG=0,CMDPARSER_OPTARG=1,CMDPARSER_ONEARG=2} ArgRequirement; class CmdParser { public: ~CmdParser(); void AddShortOption(char shortopt, ArgRequirement re, const string &desc, const string &file); bool Parse(const string &usage, int argc, char *argv[], const char* currentfile); vector<string> sequential_; private: void Help(const string &usage, const char *currentfile); void HelpLong(const string &usage); void AddAutoOption(const string &longopt, const string &desc, const string &file, const char shortopt, bool is_switch = false); typedef void (*PostParse)(void); void AddPostParseFunc(PostParse post); void AddLongOption(const string &longopt, ArgRequirement re, int shortopt, const string &desc, const string &file); bool ParseShortOption(const int c, const char *optarg); bool ParseLongOption(const string &name, const char *optarg); void LoadOptionFile(); void LoadOptionProfile(const YAML::Node *p_node); vector<option> long_options; vector<string> option_file; vector<zuint> option_file_n; string short_options; vector<string> optstr,optdesc; map<int, string> short_long_; map<int, string> neg_short_long_; vector<PostParse> postparse_; template<typename T> friend class FlagsHelper; friend class FlagsSwitchHelper; friend class FlagsPostHelper; }; #define ZSHORTFLAGS(shortopt, arg, desc) \ zzz::Singleton<zzz::CmdParser>::Instance().AddShortOption(shortopt,arg,desc,__FILE__); #define ZCMDSEQ (zzz::Singleton<zzz::CmdParser>::Instance().sequential_) // Make it a better name, should always call it first. #define ZINIT(usage) \ ZGLOBAL_ADD(std::string(__DATE__) + ", " + __TIME__, "__MAIN_TIMESTAMP__");\ zzz::Singleton<zzz::CmdParser>::Instance().Parse(usage,argc,argv,__FILE__); #define ZCMDPARSE(usage) ZINIT(usage) template<typename T> class FlagsHelper { public: FlagsHelper(const string &name ,T *v, const string &desc, const string &file, const char x=0) { string strvar("ZFLAG_"); strvar += name; ZGLOBAL_ADD(v, strvar); Singleton<CmdParser>::Instance().AddAutoOption(name, desc, file, x); } }; class FlagsSwitchHelper { public: FlagsSwitchHelper(const string &name ,bool *v, const string &desc, const string &file, const char x=0) { string strvar("ZFLAG_"); strvar += name; ZGLOBAL_ADD(v, strvar); Singleton<CmdParser>::Instance().AddAutoOption(name, desc, file, x, true); } }; #define ZFLAGS_DOUBLE(longopt,default_value, desc) \ double ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<double> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_DOUBLE2(longopt,default_value, desc, x) \ double ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<double> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} #define ZFLAGS_INT(longopt,default_value, desc) \ int ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<int> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_INT2(longopt,default_value, desc, x) \ int ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<int> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} #define ZFLAGS_BOOL(longopt,default_value, desc) \ bool ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<bool> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_BOOL2(longopt,default_value, desc, x) \ bool ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<bool> __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} #define ZFLAGS_STRING(longopt,default_value, desc) \ std::string ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<std::string> __ZFLAGS_##longopt##_HELPER___(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_STRING2(longopt,default_value, desc, x) \ std::string ZFLAG_##longopt = default_value; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<std::string> __ZFLAG_##longopt##_HELPER___(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} #define ZFLAGS_SWITCH(longopt, desc) \ bool ZFLAG_##longopt = false; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsSwitchHelper __ZFLAG_##longopt##_HELPER___(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_SWITCH2(longopt, desc, x) \ bool ZFLAG_##longopt = false; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsSwitchHelper __ZFLAG_##longopt##_HELPER___(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} #define ZFLAGS_MULTIPLE(longopt, desc) \ std::vector<std::string> ZFLAG_##longopt; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<std::vector<std::string> > __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__);} #define ZFLAGS_MULTIPLE2(longopt, desc, x) \ std::vector<std::string> ZFLAG_##longopt; \ namespace ZFLAGS_NAMESPACE{zzz::FlagsHelper<std::vector<std::string> > __ZFLAG_##longopt##_HELPER__(#longopt, &ZFLAG_##longopt, desc,__FILE__, x);} class FlagsPostHelper { public: FlagsPostHelper(CmdParser::PostParse post) { Singleton<CmdParser>::Instance().AddPostParseFunc(post); } }; #define ZFLAGS_POST(post) \ namespace ZFLAGS_NAMESPACE{zzz::FlagsPostHelper __FLAGS_##post##_HELPER__(post);} #define ZFLAG_GET(type, name) (*ZGLOBAL_GET(type*, name)) }
zzz-engine
zzzEngine/zCore/zCore/Utility/CmdParser.hpp
C++
gpl3
5,761
#pragma once #include "../common.hpp" //wrap BraceItem namespace zzz{ class BraceItem; class BraceNode { public: BraceNode(const BraceNode &node); BraceNode(BraceItem *item,BraceItem *parent,int i); bool IsValid() const; BraceNode GetParent(); zuint NodeNumber() const; BraceNode GetNode(zuint i); BraceNode AppendNode(const string &str, const char h=0, const char t=0) const; bool HasNode(const string &str); bool RemoveNode(zuint i); //iteration BraceNode GetFirstNode(const string &str=string()); BraceNode GetFirstNodeInclude(const string &str); BraceNode GetNextSibling(const string &str=string()); BraceNode GetNextSiblingInclude(const string &str); void GotoNextSibling(const string &str=string()); void GotoNextSiblingInclude(const string &str); void operator++(); //head and tail brace char GetHeadBrace(); char GetTailBrace(); void SetHeadTail(char h, char t); const string& GetText() const; void SetText(const string &str); void GetChildrenText(string &str) const; private: BraceItem *item; BraceItem *parent; int idx; }; inline const BraceNode& operator<<(const BraceNode &node, const string &text) { node.AppendNode(text.c_str()); return node; } inline const BraceNode& operator<<(const BraceNode &node, const char *text) { node.AppendNode(text); return node; } }
zzz-engine
zzzEngine/zCore/zCore/Utility/BraceNode.hpp
C++
gpl3
1,409
#pragma once #include "../Math/Array.hpp" namespace zzz{ template<typename T> class SumTable { public: SumTable():ready_(false){} SumTable(const Array<2, T> &value) { Prepare(value); } void Prepare(const Array<2, T> &value) { table_.SetSize(value.Size()); for (int r=0; r<table_.Size(0); r++) for (int c=0; c<table_.Size(1); c++) { T previous=0; if (r!=0) previous+=table_[Vector2ui(r-1, c)]; if (c!=0) previous+=table_[Vector2ui(r, c-1)]; if (c!=0 && r!=0) previous-=table_[Vector2ui(r-1, c-1)]; table_[Vector2ui(r, c)]=previous+value[Vector2ui(r, c)]; } ready_=true; } //bottomdown included and leftup included T GetSum(const Vector2ui &leftup, const Vector2ui &bottomdown) { ZCHECK(ready_); ZCHECK(bottomdown>=leftup && bottomdown<table_.Size()); zuint beginr=leftup[0],beginc=leftup[1],endr=bottomdown[0],endc=bottomdown[1]; T ret=table_[Vector2ui(endr,endc)]; if (beginr>0) ret-=table_[Vector2ui(beginr-1,endc)]; if (beginc>0) ret-=table_[Vector2ui(endr,beginc-1)]; if (beginr>0 && beginc>0) ret+=table_[Vector2ui(beginr-1,beginc-1)]; return ret; } private: Array<2, T> table_; bool ready_; }; }
zzz-engine
zzzEngine/zCore/zCore/Algorithm/SumTable.hpp
C++
gpl3
1,262
#pragma once #include "../Math/Matrix.hpp" #include "../Math/Vector.hpp" //Gram-Schmidt process //to normalize and orthogonalize a set of vectors //based on http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process //QR based on http://en.wikipedia.org/wiki/Qr_decomposition namespace zzz{ template<typename T> class GramSchmidt { private: template<int N> static Vector<N, T> Proj(const Vector<N, T> &u, const Vector<N, T> &v) { return u*(FastDot(u, v)/FastDot(u, u)); } public: template<int N> static void Process(const MatrixBase<N, N, T> &input, MatrixBase<N, N, T> &output) { Matrix<N, N, T> u; for (int i=0; i<N; i++) { output.Row(i)=input.Row(i); for (int j=0; j<i; j++) output.Row(i)-=Proj(output.Row(j),input.Row(i)); } for (int i=0; i<N; i++) output.Row(i).Normalize(); } //basis is column in A and Q template<int N> static void QRDecomposition(const MatrixBase<N, N, T> &input, MatrixBase<N, N, T> &Q, MatrixBase<N, N, T> &R) { Matrix<N, N, T> A(input.Transposed()); Process(A, Q); R.Zero(); for (int i=0; i<N; i++) for (int j=i; j<N; j++) R(i, j)=FastDot(A.Row(j), Q.Row(i)); Q.Transpose(); } }; }
zzz-engine
zzzEngine/zCore/zCore/Algorithm/GramSchmidt.hpp
C++
gpl3
1,263
#pragma once #include "../common.hpp" namespace zzz{ //Fibonacci Heap is a fast heap that you can insert data and extract the minimal data sequentially //data in the heap can be decreased but never increased //Simple Usage: //heap.Insert(value) //while(!heap.IsEmpty()) value=heap.ExtractMin(); ////////////////////////////////////////////////////////////////////////// // Fibonacci Heap Node Class ////////////////////////////////////////////////////////////////////////// template<typename T> class FibonacciHeap; template<typename T> class FibonacciNode { friend class FibonacciHeap<T>; public: FibonacciNode() :parent(NULL),child(NULL),degree(0),mark(0),delete_flag(0) { left=this; right=this; } ~FibonacciNode(){} void operator=(const T &v) { key = v; //this need to be implemented if T is a class delete_flag = 0; } void operator=(FibonacciNode<T>& other) { key=other.key; delete_flag = other.delete_flag; } bool operator<(FibonacciNode<T>& other) { if (delete_flag==1 && other.delete_flag==0) return true; //-inf<any number if (other.delete_flag) return false; //nothing < -inf return key < other.key; //this need to be overload if T is a class } const T& GetKey(){return key;} protected: FibonacciNode *left, *right, *parent, *child; short degree; unsigned char mark, delete_flag; //link to the left of other //ATTENTION: not link this single node, but the whole chain //if you only want to link a single node, need to set the right and left of this node to itself void LinkToLeft(FibonacciNode<T> *other) { //right side right->left=other->left; other->left->right=right; //right side right=other; other->left=this; //parent parent=other->parent; } //get out of the loop and link left to right void Unlink() { left->right=right; right->left=left; left=NULL; right=NULL; } T key; }; ////////////////////////////////////////////////////////////////////////// // Fibonacci Heap Class ////////////////////////////////////////////////////////////////////////// template<typename T> class FibonacciHeap { private: FibonacciNode<T> *MinRoot; long NumNodes, NumTrees, NumMarkedNodes; public: typedef FibonacciNode<T> NodeType; FibonacciHeap():MinRoot(NULL),NumNodes(0),NumTrees(0),NumMarkedNodes(0) {} virtual ~FibonacciHeap() { Clear(); } void Clear() { while (MinRoot != NULL) { FibonacciNode<T>* Temp = ExtractMinNode(); delete Temp; } MinRoot=NULL; } // The Standard Heap Operations // simple interface bool IsEmpty(){return NumNodes==0;} FibonacciNode<T> *Insert(const T &v) { FibonacciNode<T> *NewNode=new FibonacciNode<T>; NewNode->key=v; InsertNode(NewNode); return NewNode; //return node address, so that DecreaseKey can be done } const T ExtractMin() { FibonacciNode<T>* m=ExtractMinNode(); T v=m->key; delete m; return v; } inline const T& Minimum() { return MinRoot->key; } // node manipulation interface void InsertNode(FibonacciNode<T> *NewNode) { if (NewNode == NULL) return; // If the heap is currently empty, then new node becomes singleton // circular root list if (MinRoot == NULL) MinRoot = NewNode->left = NewNode->right = NewNode; else { NewNode->LinkToLeft(MinRoot->right); // The new node becomes new MinRoot if it is less than current MinRoot if (*NewNode < *MinRoot) MinRoot = NewNode; } // We have one more node in the heap, and it is a tree on the root list NumNodes++; NumTrees++; NewNode->parent = NULL; } FibonacciNode<T>* ExtractMinNode() { FibonacciNode<T> *Result = MinRoot; // Remove minimum node and set MinRoot to next node if (Result == NULL) return NULL; MinRoot = Result->right; Result->Unlink(); if (Result->child == NULL && MinRoot == Result) //No child and this is the only root, tree goes empty MinRoot = NULL; else if (MinRoot == Result) //this is the only root, children became roots MinRoot = Result->child; else if (Result->child != NULL) //need to link children to root chain Result->child->LinkToLeft(MinRoot->right); //clear node NumNodes --; if (Result->mark) { NumMarkedNodes --; Result->mark = 0; } Result->degree = 0; Result->child = Result->parent = NULL; //consolidate tree if (MinRoot != NULL) Consolidate(); return Result; } //ATTENTION: This will delete OtherHeap void Union(FibonacciHeap<T> *OtherHeap) { if (OtherHeap == NULL || OtherHeap->MinRoot == NULL) return; OtherHeap->MinRoot->LinkToLeft(MinRoot->right); // Choose the new minimum for the heap if (*(OtherHeap->MinRoot) < *MinRoot) MinRoot = OtherHeap->MinRoot; // Set the amortized analysis statistics and size of the new heap NumNodes += OtherHeap->NumNodes; NumMarkedNodes += OtherHeap->NumMarkedNodes; NumTrees += OtherHeap->NumTrees; // Complete the union by setting the other heap to emptiness // then destroying it OtherHeap->MinRoot = NULL; OtherHeap->NumNodes = 0; OtherHeap->NumTrees = 0; OtherHeap->NumMarkedNodes = 0; delete OtherHeap; } bool DecreaseKey(FibonacciNode<T> *theNode, const T& NewKey) { FibonacciNode<T> Temp; Temp.key = NewKey; return DecreaseKey(theNode, &Temp); } bool DecreaseKey(FibonacciNode<T> *theNode, FibonacciNode<T> * NewNode) { //no increase is approved if (theNode==NULL || *theNode < *NewNode) return false; (*theNode) = (*NewNode); FibonacciNode<T> *theParent = theNode->parent; if (theParent != NULL && *theNode < *theParent) { Cut(theNode, theParent); CascadingCut(theParent); } if (*theNode < *MinRoot) MinRoot = theNode; return true; } bool Delete(FibonacciNode<T> *theNode) { if (theNode == NULL) return false; FibonacciNode<T> Temp; Temp.delete_flag = 1; bool Result = DecreaseKey(theNode, Temp); if (Result && ExtractMinNode() == NULL) Result = false; if (Result) { delete theNode; theNode->delete_flag = 0; } return Result; } // Extra utility functions long GetNumNodes() { return NumNodes; }; long GetNumTrees() { return NumTrees; }; long GetNumMarkedNodes() { return NumMarkedNodes; }; void GetAllNodes(vector<FibonacciNode<T>*> &nodes,FibonacciNode<T> *Tree = NULL, FibonacciNode<T> *theParent=NULL) { if (Tree == NULL) { Tree = MinRoot; nodes.clear(); } //siblings FibonacciNode<T>* Temp = Tree; do { nodes.push_back(Temp); Temp = Temp->right; } while (Temp != NULL && Temp != Tree); //children of all the siblings Temp = Tree; do { if (Temp->child != NULL) GetAllNodes(nodes, Temp->child, Temp); Temp = Temp->right; } while (Temp!=NULL && Temp != Tree); } void Print(FibonacciNode<T> *Tree = NULL, FibonacciNode<T> *theParent=NULL) { FibonacciNode<T>* Temp = NULL; if (Tree == NULL) Tree = MinRoot; Temp = Tree; do { if (Temp->left == NULL) zout << "(left is NULL)"; Temp->Print(); if (Temp->parent != theParent) zout << "(parent is incorrect)"; if (Temp->right == NULL) zout << "(right is NULL)"; else if (Temp->right->left != Temp) zout << "(Error in left link left) ->"; else zout << " <-> "; Temp = Temp->right; } while (Temp != NULL && Temp != Tree); zout << '\n'; Temp = Tree; do { zout << "Children of "; Temp->Print(); zout << ": "; if (Temp->child == NULL) zout << "NONE\n"; else Print(Temp->child, Temp); Temp = Temp->right; } while (Temp!=NULL && Temp != Tree); if (theParent == NULL) { char ch; zout << "Done Printing. Hit a key.\n"; cin >> ch; } } private: // Internal functions that help to implement the Standard Operations inline void Exchange(FibonacciNode<T>*& N1, FibonacciNode<T>*& N2) { FibonacciNode<T> *Temp; Temp = N1; N1 = N2; N2 = Temp; } void Consolidate() { FibonacciNode<T> *x, *y, *w; FibonacciNode<T> *A[1+8*sizeof(long)]; // 1+lg(n) int I=0, Dn = 1+8*sizeof(long); short d; // Initialize the consolidation detection array for (I=0; I < Dn; I++) A[I] = NULL; // We need to loop through all elements on root list. // When a collision of degree is found, the two trees // are consolidated in favor of the one with the lesser // element key value. We first need to break the circle // so that we can have a stopping condition (we can't go // around until we reach the tree we started with // because all root trees are subject to becoming a // child during the consolidation). MinRoot->left->right = NULL; MinRoot->left = NULL; w = MinRoot; do { //zout << "Top of Consolidate's loop\n"; //Print(w); x = w; d = x->degree; w = w->right; // We need another loop here because the consolidated result // may collide with another large tree on the root list. while (A[d] != NULL) { y = A[d]; if (*y < *x) Exchange(x, y); if (w == y) w = y->right; Link(y, x); A[d] = NULL; d++; //zout << "After a round of Linking\n"; //Print(x); } A[d] = x; } while (w != NULL); // Now we rebuild the root list, find the new minimum, // set all root list nodes' parent pointers to NULL and // count the number of subtrees. MinRoot = NULL; NumTrees = 0; for (I = 0; I < Dn; I++) if (A[I] != NULL) AddToRootList(A[I]); } void Link(FibonacciNode<T> *y, FibonacciNode<T> *x) { // Remove node y from root list if (y->right != NULL) y->right->left = y->left; if (y->left != NULL) y->left->right = y->right; NumTrees--; // Make node y a singleton circular list with a parent of x y->left = y->right = y; y->parent = x; if (x->child == NULL) // If node x has no children, then list y is its new child list x->child = y; else // Otherwise, node y must be added to node x's child list y->LinkToLeft(x->child->right); // Increase the degree of node x because it's now a bigger tree x->degree ++; // Node y has just been made a child, so clear its mark if (y->mark) NumMarkedNodes--; y->mark = 0; } void AddToRootList(FibonacciNode<T> *x) { if (x->mark) NumMarkedNodes --; x->mark = 0; NumNodes--; x->right=x->left=x; InsertNode(x); } // cut x from p void Cut(FibonacciNode<T> *x, FibonacciNode<T> *p) { if (p->child == x) p->child = x->right; if (x->right == x) p->child = NULL; p->degree --; x->Unlink(); AddToRootList(x); } void CascadingCut(FibonacciNode<T> *y) { FibonacciNode<T> *z = y->parent; while (z != NULL) { if (y->mark == 0) { y->mark = 1; NumMarkedNodes++; z = NULL; } else { Cut(y, z); y = z; z = y->parent; } } } }; } /* test code void main() { FibonacciHeap<double> heap; RandSeed(); for (int i=0; i<100000; i++) heap.Insert(UniformRand<double>(-100000.0,100000.0)); double x=-MAX_DOUBLE; int n=0; while(!heap.IsEmpty()) { n++; double m=heap.ExtractMin(); if (x<=m) x=m; else zout<<x<<' '<<m<<"error!\n"; } zout<<n<<endl; } */
zzz-engine
zzzEngine/zCore/zCore/Algorithm/FibonacciHeap.hpp
C++
gpl3
12,270
#pragma once //WARNINGs #pragma warning(disable:4244)//double to float #pragma warning(disable:4305)//double to float #pragma warning(disable:4267)//: 'initializing' : conversion from 'size_t' to 'uint', possible loss of data #pragma warning(disable:4522)//multiple assignment operators specified #pragma warning(disable:4503)//decorated name length exceeded, name was truncated #pragma warning(disable:4996)//'std::_Equal1': Function call with parameters that may be unsafe //zzz Defination #include "Define.hpp" //C++ and STL #include <cmath> #include <cstring> #include <cstdlib> #include <cstdio> #include <cstdarg> #include <ctime> #include <cassert> #include <vector> #include <deque> #include <stack> #include <queue> #include <map> #include <set> #include <list> //#include <hash_map> #include <functional> #include <numeric> #include <algorithm> #include <iostream> #include <fstream> #include <limits> #include <string> #include <sstream> #include <exception> #include <iterator> using namespace std; //nvwa #ifdef ENABLE_NVWA #include <nvwa/debug_new.h> #endif
zzz-engine
zzzEngine/zCore/zCore/common.hpp
C++
gpl3
1,120
#pragma once #include <EnvDetect.hpp> #include <stdint.h> namespace zzz { //common #undef min #undef max typedef uint8_t zuint8; typedef uint16_t zuint16; typedef uint32_t zuint32; typedef uint64_t zuint64; typedef int8_t zint8; typedef int16_t zint16; typedef int32_t zint32; typedef int64_t zint64; // zsize should only be used in IO. // size variable used inside memory should follow the system. #ifdef ZSIZE_32 typedef zuint32 zsize; #else typedef zuint64 zsize; #endif typedef unsigned char zuchar; typedef unsigned short zushort; typedef unsigned int zuint; typedef unsigned long zulong; typedef char zchar; typedef short zshort; typedef int zint; typedef long zlong; typedef zuint8 zbyte; typedef zuint8 zubyte; typedef float zfloat32; typedef double zfloat64; }
zzz-engine
zzzEngine/zCore/zCore/Define.hpp
C++
gpl3
818
#include <zCoreConfig.hpp> #ifdef ZZZ_DYNAMIC #include <zCoreAutoLink3rdParty.hpp> #endif
zzz-engine
zzzEngine/zCore/zCore/zCoreAutoLink.cpp
C++
gpl3
94
#pragma once // Separate link so when change a lib, only link needs redo. #include "zCoreConfig.hpp" #include "zCoreAutoLink3rdParty.hpp" #ifndef ZZZ_NO_PRAGMA_LIB #ifdef ZZZ_COMPILER_MSVC #ifdef ZZZ_DYNAMIC #ifdef ZZZ_DEBUG #ifndef ZZZ_OS_WIN64 #pragma comment(lib, "zCoredllD.lib") #else #pragma comment(lib, "zCoredllD_x64.lib") #endif // ZZZ_OS_WIN64 #else #ifndef ZZZ_OS_WIN64 #pragma comment(lib, "zCoredll.lib") #else #pragma comment(lib, "zCoredll_x64.lib") #endif // ZZZ_OS_WIN64 #endif #else #ifdef ZZZ_DEBUG #ifndef ZZZ_OS_WIN64 #pragma comment(lib, "zCoreD.lib") #else #pragma comment(lib, "zCoreD_x64.lib") #endif // ZZZ_OS_WIN64 #else #ifndef ZZZ_OS_WIN64 #pragma comment(lib, "zCore.lib") #else #pragma comment(lib, "zCore_x64.lib") #endif // ZZZ_OS_WIN64 #endif #endif #endif // ZZZ_COMPILER_MSVC #endif // ZZZ_NO_PRAGMA_LIB
zzz-engine
zzzEngine/zCore/zCore/zCoreAutoLink.hpp
C++
gpl3
996
#pragma once #include "../common.hpp" #include "Vector.hpp" #undef min #undef max namespace zzz{ template <typename T> class Vector<1, T> : public VectorBase<1, T> { protected: using VectorBase<1, T>::v; public: //constructor Vector(void){} Vector(const Vector<1, T>& a):VectorBase<2, T>(a){} explicit Vector(const T &a){v[0]=a;} Vector(const VectorBase<1, T>& a):VectorBase<1, T>(a){} template<typename T1> explicit Vector(const T1 *p):VectorBase<1, T>(p){} template<typename T1> explicit Vector(const Vector<1,T1>& a):VectorBase<1, T>(a){} template<typename T1> explicit Vector(const VectorBase<1,T1>& a):VectorBase<1, T>(a){} //assign inline const Vector<1, T> &operator=(const Vector<1, T>& a){VectorBase<1, T>::operator =(a); return *this;} inline void Set(const T &a){v[0]=a;} using VectorBase<1, T>::operator=; // alias inline T& x(){return v[0];} inline const T& x() const {return v[0];} }; typedef Vector<1,zint8> Vector1i8; typedef Vector<1,zuint8> Vector1ui8; typedef Vector<1,zint8> Vector1i16; typedef Vector<1,zuint8> Vector1ui16; typedef Vector<1,zint8> Vector1i32; typedef Vector<1,zuint8> Vector1ui32; typedef Vector<1,zint8> Vector1i64; typedef Vector<1,zuint8> Vector1ui64; typedef Vector<1,zfloat32> Vector1f32; typedef Vector<1,zfloat64> Vector1f64; typedef Vector<1,zuint> Vector1ui; typedef Vector<1,int> Vector1i; typedef Vector<1,float> Vector1f; typedef Vector<1,double> Vector1d; }
zzz-engine
zzzEngine/zCore/zCore/Math/Vector1.hpp
C++
gpl3
1,498
#pragma once #include "Vector.hpp" #include "Matrix.hpp" #include "../common.hpp" #include "Math.hpp" #include "SymEigenSystem.hpp" #include "SumCount.hpp" namespace zzz{ template<typename T> T Mean(const vector<T> &data) { SumCount<T> sc; sc += data; return sc.Mean(); } template<typename T> T Variance(const vector<T> &data) { T mean=Mean(data); T var(0); for (zuint i=0; i<data.size(); i++) { T diff=data[i]-mean; var+=diff*diff; } return var/(data.size()-1); } template<typename T> T StdDeviation(const vector<T> &data) { return Sqrt<T>(Variance(data)); } template<zuint N, typename T> Vector<N, T> Covariance(const vector<Vector<N, T> > &data, MatrixBase<N, N, T> &cov) { Vector<N, T> mean=Mean(data); vector<Vector<N, T> > diff; diff.reserve(data.size()); for (zuint i=0; i<data.size(); i++) diff.push_back(data[i]-mean); cov.Zero(); for (zuint i=0; i<diff.size(); i++) { for (zuint n=0; n<N; n++) for (zuint m=n; m<N; m++) cov(n, m)+=diff[i][n]*diff[i][m]; } cov/=(data.size()-1); for (zuint n=1; n<N; n++) for (zuint m=0; m<n; m++) cov(n, m)=cov(m, n); return mean; } template<zuint N, typename T> Vector<N, T> PCA(const vector<Vector<N, T> > &data, MatrixBase<N, N, T> &eigen_vector, Vector<N, T> &eigen_value) { Matrix<N, N, T> cov; Vector<N, T> mean = Covariance(data, cov); SymEigenSystem<T, N> ss; ss.Decompose(cov, eigen_vector, eigen_value); return mean; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Statistics.hpp
C++
gpl3
1,519
//modified from code by David Eberly[eberly@magic-software.com] //original code comes from C Recipe #pragma once #include "Math.hpp" #include "Vector.hpp" #include "Utility/Log.hpp" namespace zzz{ #define SIGN(a, b) ((b)<0 ? -fabs(a) : fabs(a)) template<typename T, int N> class SymEigenSystem { private: void tred2(T a[N+1][N+1], T d[N+1], T e[N+1]) { for (int i=N; i>=2; i--) { int l=i-1; T h=0; T scale=0; if (l > 1) { for (int k=1; k<=l; k++) scale += Abs<T>(a[i][k]); if (scale == 0.0) { e[i]=a[i][l]; } else { for (int k=1; k<=l; k++) { a[i][k] /= scale; h += a[i][k]*a[i][k]; } T f=a[i][l]; T g = f>0 ? -Sqrt<T>(h) : Sqrt<T>(h); e[i]=scale*g; h -= f*g; a[i][l]=f-g; f=0; for (int j=1; j<=l; j++) { // Next statement can be omitted if eigenvectors not wanted a[j][i]=a[i][j]/h; g=0; for (int k=1; k<=j; k++) g += a[j][k]*a[i][k]; for (int k=j+1; k<=l; k++) g += a[k][j]*a[i][k]; e[j]=g/h; f += e[j]*a[i][j]; } T hh=f/(h+h); for (int j=1; j<=l; j++) { f=a[i][j]; g=e[j]=e[j]-hh*f; for (int k=1; k<=j; k++) a[j][k] -= (f*e[k]+g*a[i][k]); } } } else { e[i]=a[i][l]; } d[i]=h; } // Next statement can be omitted if eigenvectors not wanted d[1]=0.0; e[1]=0.0; // Contents of this loop can be omitted if eigenvectors not // wanted except for statement d[i]=a[i][i]; for (int i=1; i<=N; i++) { int l=i-1; if (d[i]) { for (int j=1; j<=l; j++) { T g=0.0; for (int k=1; k<=l; k++) g += a[i][k]*a[k][j]; for (int k=1; k<=l; k++) a[k][j] -= g*a[k][i]; } } d[i]=a[i][i]; a[i][i]=1.0; for (int j=1; j<=l; j++) a[j][i]=a[i][j]=0.0; } } void tqli(T d[N+1], T e[N+1], T z[N+1][N+1]) { for (int i=2; i<=N; i++) e[i-1]=e[i]; e[N]=0.0; for (int l=1; l<=N; l++) { int iter=0; int Mat; do { for (Mat=l;Mat<=N-1;Mat++) { T dd=Abs<T>(d[Mat])+Abs<T>(d[Mat+1]); if (fabs(e[Mat])+dd == dd) break; } if (Mat != l) { if (iter++ == 30) { ZLOGI << "Too many iterations in TQLI" << endl; return; } T g=(d[l+1]-d[l])/(2.0*e[l]); T r=Sqrt<T>((g*g)+1.0); g=d[Mat]-d[l]+e[l]/(g + (g<0?-Abs<T>(r):Abs<T>(r))); T s=1; T c=1; T p=0; for (int i=Mat-1; i>=l; i--) { T f=s*e[i]; T b=c*e[i]; if (fabs(f) >= fabs(g)) { c=g/f; r=(float)(sqrt((c*c)+1.0)); e[i+1]=f*r; c *= (T)(s=(T)1.0/r); } else { s=f/g; r=(float)sqrt((s*s)+1.0); e[i+1]=g*r; s *= (T)(c=(T)1.0/r); } g=d[i+1]-p; r=(T)((d[i]-g)*s+2.0*c*b); p=s*r; d[i+1]=g+p; g=c*r-b; // Next loop can be omitted if eigenvectors not wanted for (int k=1; k<=N; k++) { f=z[k][i+1]; z[k][i+1]=s*z[k][i]+c*f; z[k][i]=c*z[k][i]-s*f; } } d[l]=d[l]-p; e[l]=g; e[Mat]=0.0; } } while (Mat != l); } T max_val; int max_index; for(int i=1; i<=N-1; i++) { max_val = d[i]; max_index = i; for(int k=i+1; k<=N; k++) { if (max_val < d[k]) { max_val = d[k]; max_index = k; } if (max_index != i) { e[1] = d[i]; d[i] = d[max_index]; d[max_index] = e[1]; for(int l=1; l<=N; l++) { e[1] = z[l][i]; z[l][i] = z[l][max_index]; z[l][max_index] = e[1]; } } } } } void Decompose(T **Mat, T **EigenVector, T *EigenValue) { T a[N+1][N+1]; T d[N+1], e[N+1]; // data structure for tred2 and tqli - don't ask for(int i=0; i<N; i++) for(int j=0; j<N; j++) a[i+1][j+1] = Mat[i][j]; tred2(a, d, e); tqli(d, e, a); for (int i=0; i<N; i++) { EigenValue[i] = d[i+1]; for (int j=0; j<N; j++) EigenVector[j][i] = a[i+1][j+1]; // order should be swapped } } public: void Decompose(const MatrixBase<N, N, T>& Mat, MatrixBase<N, N, T>& EigenVector, Vector<N, T>& EigenValue) { T a[N+1][N+1]; T d[N+1], e[N+1]; // data structure for tred2 and tqli - don't ask for(int i=0; i<N; i++) for(int j=0; j<N; j++) a[i+1][j+1] = Mat.At(i, j); tred2(a, d, e); tqli(d, e, a); Vector<N, T> eigenv; Vector<N, Vector<N, T> > eigenvec; for (int i=0; i<N; i++) { eigenv[i] = d[i+1]; for (int j=0; j<N; j++) eigenvec[j][i] = a[i+1][j+1]; // order should be swapped } vector<pair<T, zuint> > eigen_value_sort; eigen_value_sort.reserve(N); for (zuint i = 0; i < N; i++) eigen_value_sort.push_back(make_pair(eigenv[i], i)); sort(eigen_value_sort.rbegin(), eigen_value_sort.rend()); for (zuint i = 0; i < N; i++) { EigenValue[i] = eigen_value_sort[i].first; EigenVector.Row(i) = eigenvec[eigen_value_sort[i].second]; } } }; }
zzz-engine
zzzEngine/zCore/zCore/Math/SymEigenSystem.hpp
C++
gpl3
5,707
#pragma once #include "Matrix.hpp" namespace zzz{ template <typename T> class Matrix<2, 2, T> : public MatrixBase<2, 2, T> { public: Matrix(){} Matrix(const Matrix<2, 2, T> &mat):MatrixBase<2, 2, T>(mat){} Matrix(const MatrixBase<2, 2, T> &mat):MatrixBase<2, 2, T>(mat){} template<typename T1> explicit Matrix<2, 2, T>(const MatrixBase<2, 2,T1>& a):MatrixBase<2, 2, T>(a) {} template<typename T1> explicit Matrix<2, 2, T>(const Matrix<2, 2,T1>& a):MatrixBase<2, 2, T>(a) {} template<typename T1> explicit Matrix<2, 2, T>(const T1 *p):MatrixBase<2, 2, T>(p) {} Matrix(const T& a,const T& b,const T& c,const T& d) { T* v=Data(); v[0]=a; v[1]=b; v[2]=c; v[3]=d; } explicit Matrix(const T *p) { T* v=Data(); v[0]=p[0]; v[1]=p[1]; v[2]=p[2]; v[3]=p[3]; } Matrix(const Vector<2, T>& a,const Vector<2, T>& b) { T* v=Data(); v[0]=a[0]; v[1]=a[1]; v[2]=b[0]; v[3]=b[1]; } explicit Matrix(const Vector<2, T> *a) { T* v=Data(); v[0]=a[0][0]; v[1]=a[0][1]; v[2]=a[1][0]; v[3]=a[1][1]; } //assign inline const Matrix<2, 2, T> &operator=(const Matrix<2, 2, T>& a){MatrixBase<2, 2, T>::operator =(a); return *this;} using MatrixBase<2, 2, T>::operator=; using MatrixBase<2, 2, T>::Data; //alias const T& m00() const {return Data()[0];} const T& m01() const {return Data()[1];} const T& m10() const {return Data()[2];} const T& m11() const {return Data()[3];} const T& v0() const {return Data()[0];} const T& v1() const {return Data()[1];} const T& v2() const {return Data()[2];} const T& v3() const {return Data()[3];} T& m00() {return Data()[0];} T& m01() {return Data()[1];} T& m10() {return Data()[2];} T& m11() {return Data()[3];} T& v0() {return Data()[0];} T& v1() {return Data()[1];} T& v2() {return Data()[2];} T& v3() {return Data()[3];} //operator using MatrixBase<2, 2, T>::operator *; }; typedef Matrix<2, 2,zint8> Matrix2x2i8; typedef Matrix<2, 2,zuint8> Matrix2x2ui8; typedef Matrix<2, 2,zint16> Matrix2x2i16; typedef Matrix<2, 2,zuint16> Matrix2x2ui16; typedef Matrix<2, 2,zint32> Matrix2x2i32; typedef Matrix<2, 2,zuint32> Matrix2x2ui32; typedef Matrix<2, 2,zint64> Matrix2x2i64; typedef Matrix<2, 2,zuint64> Matrix2x2ui64; typedef Matrix<2, 2,zfloat32> Matrix2x2f32; typedef Matrix<2, 2,zfloat64> Matrix2x2f64; typedef Matrix<2, 2,zuint> Matrix2x2ui; typedef Matrix<2, 2,int> Matrix2x2i; typedef Matrix<2, 2,float> Matrix2x2f; typedef Matrix<2, 2,double> Matrix2x2d; }
zzz-engine
zzzEngine/zCore/zCore/Math/Matrix2x2.hpp
C++
gpl3
2,593
#pragma once #include <common.hpp> namespace zzz{ template<typename T> class SumCount { public: SumCount():all_(0), count_(0){} const T Sum() const {return all_;} const zuint Count() const {return count_;} const T Mean() const {return all_/count_;} void AddData(const T &p) { all_+=p; count_++; } template<typename T1> void AddData(const T1& _begin, const T1& _end) { for (T1 i=_begin; i!=_end; i++) AddData(*i); } void operator+=(const T &x) { AddData(x); } void operator+=(const vector<T> &x) { AddData(x.begin(), x.end()); } void operator+=(const SumCount<T> &x) { count_+=x.Count(); all_+=x.All(); } void Reset() { all_ = 0; count_ = 0; } private: T all_; zuint count_; }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/SumCount.hpp
C++
gpl3
832
#pragma once #include "Vector.hpp" //3-variables polynomial function namespace zzz{ typedef enum { POLY3_UNIT, POLY3_X, POLY3_Y, POLY3_Z, POLY3_XY, POLY3_XZ, POLY3_YZ, POLY3_X2, POLY3_Y2, POLY3_Z2, POLY3_X2Y, POLY3_X2Z, POLY3_XY2, POLY3_Y2Z, POLY3_XZ2, POLY3_YZ2, POLY3_XYZ, POLY3_X3, POLY3_Y3, POLY3_Z3, NUM_POLY3_COEFFS } POLY3COEFF; template<typename T> class Poly3 : public Vector<NUM_POLY3_COEFFS, T> { public: Poly3():Vector<NUM_POLY3_COEFFS, T>(0){} Poly3(const VectorBase<NUM_POLY3_COEFFS, T> &b):Vector<NUM_POLY3_COEFFS, T>(b){} Poly3(const Poly3<T> &b):Vector<NUM_POLY3_COEFFS, T>(b){} using Vector<NUM_POLY3_COEFFS, T>::operator+; using Vector<NUM_POLY3_COEFFS, T>::operator-; using Vector<NUM_POLY3_COEFFS, T>::operator+=; using Vector<NUM_POLY3_COEFFS, T>::operator-=; using Vector<NUM_POLY3_COEFFS, T>::Data; Poly3<T> Multiply(const Poly3<T> &b) const { Poly3<T> r; #if 0 if (!Poly3MultCheck((*this), b)) { zout<<"[poly3_mult] Polynomials cannot be multiplied!\n"; return r; } #endif const T *v=Data(); r[POLY3_UNIT] = v[POLY3_UNIT] * b[POLY3_UNIT]; r[POLY3_X] = v[POLY3_X] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X]; r[POLY3_Y] = v[POLY3_Y] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y]; r[POLY3_Z] = v[POLY3_Z] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Z]; r[POLY3_XY] = v[POLY3_XY] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_XY] + v[POLY3_X] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_X]; r[POLY3_XZ] = v[POLY3_XZ] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_XZ] + v[POLY3_X] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_X]; r[POLY3_YZ] = v[POLY3_YZ] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_YZ] + v[POLY3_Y] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_Y]; r[POLY3_X2] = v[POLY3_X2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X2] + v[POLY3_X] * b[POLY3_X]; r[POLY3_Y2] = v[POLY3_Y2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y2] + v[POLY3_Y] * b[POLY3_Y]; r[POLY3_Z2] = v[POLY3_Z2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Z2] + v[POLY3_Z] * b[POLY3_Z]; r[POLY3_X2Y] = v[POLY3_X2Y] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X2Y] + v[POLY3_X2] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_X2] + v[POLY3_XY] * b[POLY3_X] + v[POLY3_X] * b[POLY3_XY]; r[POLY3_X2Z] = v[POLY3_X2Z] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X2Z] + v[POLY3_X2] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_X2] + v[POLY3_XZ] * b[POLY3_X] + v[POLY3_X] * b[POLY3_XZ]; r[POLY3_XY2] = v[POLY3_XY2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_XY2] + v[POLY3_X] * b[POLY3_Y2] + v[POLY3_Y2] * b[POLY3_X] + v[POLY3_XY] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_XY]; r[POLY3_Y2Z] = v[POLY3_Y2Z] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y2Z] + v[POLY3_Y2] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_Y2] + v[POLY3_YZ] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_YZ]; r[POLY3_XZ2] = v[POLY3_XZ2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_XZ2] + v[POLY3_X] * b[POLY3_Z2] + v[POLY3_Z2] * b[POLY3_X] + v[POLY3_XZ] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_XZ]; r[POLY3_YZ2] = v[POLY3_YZ2] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_YZ2] + v[POLY3_Y] * b[POLY3_Z2] + v[POLY3_Z2] * b[POLY3_Y] + v[POLY3_YZ] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_YZ]; r[POLY3_XYZ] = v[POLY3_XYZ] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_XYZ] + v[POLY3_XY] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_XY] + v[POLY3_XZ] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_XZ] + v[POLY3_YZ] * b[POLY3_X] + v[POLY3_X] * b[POLY3_YZ]; r[POLY3_X3] = v[POLY3_X3] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X3] + v[POLY3_X2] * b[POLY3_X] + v[POLY3_X] * b[POLY3_X2]; r[POLY3_Y3] = v[POLY3_Y3] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y3] + v[POLY3_Y2] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_Y2]; r[POLY3_Z3] = v[POLY3_Z3] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Z3] + v[POLY3_Z2] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_Z2]; return r; } //multiply degree 0 1 of this to degree 0 1 of b Poly3<T> Multiply11(const Poly3<T> &b) { Poly3<T> r; T *v=Data(); r[POLY3_UNIT] = v[POLY3_UNIT] * b[POLY3_UNIT]; r[POLY3_X] = v[POLY3_X] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X]; r[POLY3_Y] = v[POLY3_Y] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y]; r[POLY3_Z] = v[POLY3_Z] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Z]; r[POLY3_XY] = v[POLY3_X] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_X]; r[POLY3_XZ] = v[POLY3_X] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_X]; r[POLY3_YZ] = v[POLY3_Y] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_Y]; r[POLY3_X2] = v[POLY3_X] * b[POLY3_X]; r[POLY3_Y2] = v[POLY3_Y] * b[POLY3_Y]; r[POLY3_Z2] = v[POLY3_Z] * b[POLY3_Z]; return r; } //multiply degree 0 1 2 of this to degree 0 1 of b Poly3<T> Multiply21(const Poly3<T> &b) { Poly3<T> r; T *v=Data(); r[POLY3_UNIT] = v[POLY3_UNIT] * b[POLY3_UNIT]; r[POLY3_X] = v[POLY3_X] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_X]; r[POLY3_Y] = v[POLY3_Y] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Y]; r[POLY3_Z] = v[POLY3_Z] * b[POLY3_UNIT] + v[POLY3_UNIT] * b[POLY3_Z]; r[POLY3_XY] = v[POLY3_XY] * b[POLY3_UNIT] + v[POLY3_X] * b[POLY3_Y] + v[POLY3_Y] * b[POLY3_X]; r[POLY3_XZ] = v[POLY3_XZ] * b[POLY3_UNIT] + v[POLY3_X] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_X]; r[POLY3_YZ] = v[POLY3_YZ] * b[POLY3_UNIT] + v[POLY3_Y] * b[POLY3_Z] + v[POLY3_Z] * b[POLY3_Y]; r[POLY3_X2] = v[POLY3_X2] * b[POLY3_UNIT] + v[POLY3_X] * b[POLY3_X]; r[POLY3_Y2] = v[POLY3_Y2] * b[POLY3_UNIT] + v[POLY3_Y] * b[POLY3_Y]; r[POLY3_Z2] = v[POLY3_Z2] * b[POLY3_UNIT] + v[POLY3_Z] * b[POLY3_Z]; r[POLY3_X2Y] = v[POLY3_X2] * b[POLY3_Y] + v[POLY3_XY] * b[POLY3_X]; r[POLY3_X2Z] = v[POLY3_X2] * b[POLY3_Z] + v[POLY3_XZ] * b[POLY3_X]; r[POLY3_XY2] = v[POLY3_Y2] * b[POLY3_X] + v[POLY3_XY] * b[POLY3_Y]; r[POLY3_Y2Z] = v[POLY3_Y2] * b[POLY3_Z] + v[POLY3_YZ] * b[POLY3_Y]; r[POLY3_XZ2] = v[POLY3_Z2] * b[POLY3_X] + v[POLY3_XZ] * b[POLY3_Z]; r[POLY3_YZ2] = v[POLY3_Z2] * b[POLY3_Y] + v[POLY3_YZ] * b[POLY3_Z]; r[POLY3_XYZ] = v[POLY3_XY] * b[POLY3_Z] + v[POLY3_XZ] * b[POLY3_Y] + v[POLY3_YZ] * b[POLY3_X]; r[POLY3_X3] = v[POLY3_X2] * b[POLY3_X]; r[POLY3_Y3] = v[POLY3_Y2] * b[POLY3_Y]; r[POLY3_Z3] = v[POLY3_Z2] * b[POLY3_Z]; return r; } T Eval(const T x, const T y, const T z) { T *v=Data(); double r = v[POLY3_UNIT]; r += v[POLY3_X] * x; r += v[POLY3_Y] * y; r += v[POLY3_Z] * z; r += v[POLY3_XY] * x * y; r += v[POLY3_XZ] * x * z; r += v[POLY3_YZ] * y * z; r += v[POLY3_X2] * x * x; r += v[POLY3_Y2] * y * y; r += v[POLY3_Z2] * z * z; r += v[POLY3_X2Y] * x * x * y; r += v[POLY3_X2Z] * x * x * z; r += v[POLY3_XY2] * x * y * y; r += v[POLY3_Y2Z] * y * y * z; r += v[POLY3_XZ2] * x * z * z; r += v[POLY3_YZ2] * y * z * z; r += v[POLY3_XYZ] * x * y * z; r += v[POLY3_X3] * x * x * x; r += v[POLY3_Y3] * y * y * y; r += v[POLY3_Z3] * z * z * z; return r; } //degree of highest non-zero coeff int Degree() const { T *v=Data(); if (v[POLY3_X3] != 0.0 || v[POLY3_Y3] != 0.0 || v[POLY3_Z3] != 0.0 || v[POLY3_X2Y] != 0.0 || v[POLY3_X2Z] != 0.0 || v[POLY3_XY2] != 0.0 || v[POLY3_XZ2] != 0.0 || v[POLY3_Y2Z] != 0.0 || v[POLY3_YZ2] != 0.0 || v[POLY3_XYZ] != 0.0) return 3; if (v[POLY3_X2] != 0.0 || v[POLY3_Y2] != 0.0 || v[POLY3_Z2] != 0.0 || v[POLY3_XY] != 0.0 || v[POLY3_XZ] != 0.0 || v[POLY3_YZ] != 0.0) return 2; if (v[POLY3_X] != 0.0 || v[POLY3_Y] != 0.0 || v[POLY3_Z] != 0.0) return 1; return 0; } }; template<typename T> int Poly3MultCheck(Poly3<T> a, Poly3<T> b) { int deg_a = a.Degree(); int deg_b = b.Degree(); if (deg_a + deg_b <= 3) return 1; else return 0; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Poly3.hpp
C++
gpl3
8,251
#pragma once #include <zCoreConfig.hpp> #include "../common.hpp" #include "Vector3.hpp" #include "Matrix4x4.hpp" namespace zzz{ #undef max #undef min inline zuint TimeSeed() { return time(NULL); } inline void RandSeed() { srand(TimeSeed()); } template<typename T> T UniformRand(const T &min, const T &max) { int r=rand(); double rr=(double)r/(double)RAND_MAX; return (max-min)*rr+min; } // The Park and Miller "Minimal Standard" LCG generator // X[n+1] = (X[n]*a)%m // Adapted from Numerical Recipies in C, 2nd Ed // Similar to FreeBSD random number generator class ZCORE_CLASS RandomLCG { public: RandomLCG(const zuint seed = 199125); ///< Construct with non-zero seed RandomLCG(const RandomLCG &rng); ///< Copy constructor zuint Rand(); ///< Random number in [0,max()] zuint Max() const; ///< Maximum random number void Seed(const zuint seed = 199125); ///< Seed the random number generator void SeedFromTime(); private: mutable zuint idum_; const static int a; const static int m; const static int q; const static int r; }; // Multiple LFSR (Linear Feedback Shift Register) generator // Larry Smith // Nigel Stewart, RMIT (nigels@nigels.com) // Original Pascal implementation from unknown source // This random number generator uses three LFSRs (Linear Feedback Shift Registers) // to create long sequences of random bits. Each bit is equally randomised. // The origins of this exact algorithm is unknown. This implementation is // based on the ctools module rndnums by Larry Smith, used with permission. // It is not really known how good this method is for random number generation - // but it has the advantage of generating 32 random bits. Probably not recommended // for crypto applications.... // Further information about LFSRs: // B. Schneier, Applied Cryptography, 2nd Ed, Johyn Wiley & Sons class ZCORE_CLASS RandomLFSRMix { public: /// Constructor RandomLFSRMix(const zuint seed1 = 199125,const zuint seed2 = 90618,const zuint seed3 = 189419); RandomLFSRMix(const RandomLFSRMix &rng); ///< Copy constructor zuint Rand(); ///< 32-bit random number zuint Max() const; ///< Maximum random number /// Seed the random number generator void Seed(const zuint seed1 = 199125,const zuint seed2 = 90618,const zuint seed3 = 189419); void SeedFromTime(); static RandomLFSRMix rng; ///< Global LFSRMix RNG for convenience private: mutable zuint regA_, regB_, regC_; }; // Adaptor for random numbers in integer domain template<typename T, class R = RandomLFSRMix> class RandomInteger { public: /// Constructor RandomInteger(R &random,const T min,const T max) :random_(random),min_(min),mod_(max-min+1) { ZCHECK_LE(min, max); } /// Constructor using default RNG RandomInteger(const T min,const T max) :random_(R::rng),min_(min),mod_(max-min+1) { ZCHECK_LE(min, max); } /// Copy constructor RandomInteger(const RandomInteger<T, R> &gen) : random_(gen.random_),min_(gen.min_),mod_(gen.mod_){} /// Random number in the range [min,max] zuint Rand() { return min_ + random_.Rand()%mod_; } void SeedFromTime(){random_.SeedFromTime();} private: R& random_; const T min_; const T mod_; }; // Adaptor for random float or double numbers template<typename T ,class R = RandomLFSRMix> class RandomReal { public: /// Constructor RandomReal(R &random,const T min = 0.0,const T max = 1.0) : random_(random),min_(min),max_(max),mult_(max-min){} /// Constructor using default RNG RandomReal(const T min = 0.0,const T max = 1.0) : random_(R::rng),min_(min),max_(max),mult_(max-min){} /// Copy constructor RandomReal(const RandomReal<T, R> &gen) : random_(gen._random),min_(gen.min_),max_(gen.max_),mult_(gen.mult_){} /// Random number in the range [min,max] T Rand() { return Lerp(min_,max_,float(random_.Rand())/numeric_limits<zuint>::max()); } void SeedFromTime(){random_.SeedFromTime();} private: R& random_; const T min_; const T max_; const T mult_; }; //normal distribution (0, 1) template<typename T, class R = RandomLFSRMix> class RandomNormal { public: /// Constructor RandomNormal(R &random,const T mean = 0, const T var = 1) : z_(random, 0.0, 1.0),mean_(mean),var_(var),takenX2_(true){} /// Constructor using default RNG RandomNormal(const T mean = 0, const T var = 1) : z_(R::rng, 0.0, 1.0),mean_(mean),var_(var),takenX2_(true){} /// Copy constructor RandomNormal(const RandomNormal<T, R> &gen) : z_(gen.z_.random_),mean_(gen.mean_),var_(gen.var_),takenX2_(true){} /// Random point on sphere surface T Rand() { //Box-Muller method if (takenX2_==false) { takenX2_=true; return lastX2_; } T R1=z_.Rand(),R2=z_.Rand(); lastX2_=Sqrt(-2*log(R1))*sin(C_2PI*R2)*var_+mean_; takenX2_=false; return Sqrt(-2*log(R1))*cos(C_2PI*R2)*var_+mean_; } void SeedFromTime(){z_.SeedFromTime();} private: RandomReal<T, R> z_; const T mean_, var_; bool takenX2_; T lastX2_; }; // Random points on the unit sphere // Nigel Stewart, RMIT (nigels@nigels.com) // http://www.math.niu.edu/~rusin/known-math/96/sph.rand // The trig method. This method works only in 3-space, but it is // very fast. It depends on the slightly counterintuitive fact // that each of the three coordinates of a uniformly // distributed point on S^2 is uniformly distributed on [-1, 1] (but // the three are not independent, obviously). Therefore, it // suffices to choose one axis (Z, say) and generate a uniformly // distributed value on that axis. This constrains the chosen point // to lie on a circle parallel to the X-Y plane, and the obvious // trig method may be used to obtain the remaining coordinates. // // Choose z uniformly distributed in [-1, 1]. // Choose t uniformly distributed on [0, 2*pi). // Let r = sqrt(1-z^2). // Let x = r * cos(t). // Let y = r * sin(t). template<typename T, class R = RandomLFSRMix> class RandomSphere { public: /// Constructor RandomSphere(R &random,const T radius = 1.0) : z_(random, -1.0, 1.0),t_(random, 0,C_2PI),radius_(radius){} /// Constructor using default RNG RandomSphere(const T radius = 1.0) : z_(R::rng, -1.0, 1.0),t_(R::rng, 0.0,C_2PI),radius_(radius){} /// Copy constructor RandomSphere(const RandomSphere<R> &gen) : z_(gen.z_.random_),t_(gen.t_.random_),radius_(gen.radius_){} /// Random point on sphere surface Vector<3, T> Rand() { const T z = z_.Rand(); const T t = t_.Rand(); const T r = radius_*Sqrt<T>(1.0-z*z); return Vector<3, T> (r*cos(t), r*sin(t),radius_*z); } void SeedFromTime(){z_.SeedFromTime();t_.SeedFromTime();} private: RandomReal<T, R> z_,t_; const T radius_; }; // Random orientation matricies in 3D template<typename T, class R = RandomLFSRMix> class RandomOrientation { public: /// Constructor RandomOrientation(R &random):s_(random),a_(random, 0.0,C_2PI){} /// Constructor using default RNG RandomOrientation():s_(R::rng),a_(R::rng, 0.0,C_2PI){} /// Copy constructor RandomOrientation(const RandomOrientation<R> &gen):s_(gen.s_),a_(gen.a_){} /// Random orientation matrix Matrix<4, 4, T> Rand() { // A is a vector distributed // randomly on the unit sphere const Vector<3, T> a(s_.Rand()); // B is orthogonal to A Vector<3, T> b; switch (a.MaxPos()) { case 0: b = a.Cross(Vector<3, T>(0, 0, 1)); break; // a in x direction case 1: b = a.Cross(Vector<3, T>(0, 0, 1)); break; // a in y direction case 2: b = a.Cross(Vector<3, T>(1, 0, 0)); break; // a in z direction } // C is orthogonal to both A and B Vector<3, T> c(b.Cross(a)); // TODO - Possible to avoid this step? b.Normalize(); c.Normalize(); // Choose an angle in the AB plane const T angle = a_.Rand(); const T sina = sin(angle); const T cosa = cos(angle); return Matrix<4, 4, T>(a, b*sina+c*cosa, b*cosa-c*sina); } void SeedFromTime(){s_.SeedFromTime();a_.SeedFromTime();} private: RandomSphere<T, R> s_; RandomReal<T, R> a_; }; //random sampling on unit hypersphere surface template<int N, typename T, class R = RandomLFSRMix> class RandomHyperSphere { public: /// Constructor RandomHyperSphere(R &random, const T radius = 1.0) : theta_(random, 0.0,C_2PI), radius_(radius){} /// Constructor using default RNG RandomHyperSphere(const T radius = 1.0) : theta_(RandomLFSRMix::rng, 0.0,C_2PI),radius_(radius){} /// Copy constructor RandomHyperSphere(const RandomHyperSphere<N, T, R> &gen) : theta_(gen.theta_),radius_(gen.radius_){} /// Random point on sphere surface Vector<N, T> Rand() { Vector<N-1, T> thetas; for (int i=0; i<N-1; i++) thetas[i]=theta_.Rand(); Vector<N, T> res; res[0]=1; for (int i=1; i<N-1; i++) res[i]=res[i-1]*sin(thetas[i-1]); res[N-1]=res[N-2]; for (int i=0; i<N-1; i++) res[i]*=cos(thetas[i]); res[N-1]*=sin(thetas[N-2]); if (radius_==1) return res; else return res*radius_; } Vector<N, T> RandOnDim(int n) { assert(n<=N); Vector<N-1, T> thetas; for (int i=0; i<n-1; i++) thetas[i]=theta_.Rand(); Vector<N, T> res; res[0]=1; for (int i=1; i<n-1; i++) res[i]=res[i-1]*sin(thetas[i-1]); res[n-1]=res[n-2]; for (int i=0; i<n-1; i++) res[i]*=cos(thetas[i]); res[n-1]*=sin(thetas[n-2]); for (int i=n; i<N; i++) res[i]=0; if (radius_==1) return res; else return res*radius_; } void SeedFromTime(){theta_.SeedFromTime();} private: RandomReal<T, R> theta_; const T radius_; }; //random sampling on unit hypersphere surface template<int N, typename T, class R = RandomLFSRMix> class RandomHyperSphere2 { public: /// Constructor RandomHyperSphere2(R &random, const T radius = 1.0) : z_(random, 0.0, 1.0), radius_(radius){} /// Constructor using default RNG RandomHyperSphere2(const T radius = 1.0) : z_(RandomLFSRMix::rng, 0.0, 1.0),radius_(radius){} /// Copy constructor RandomHyperSphere2(const RandomHyperSphere<N, T, R> &gen) : z_(gen.z_),radius_(gen.radius_){} /// Random point on sphere surface Vector<N, T> Rand() { Vector<N, T> z; for (int i=0; i<N; i++) z[i]=z_.Rand(); T r=FastDot(z, z); r=Sqrt(r); Vector<N, T> ret; for (int i=0; i<N; i++) ret[i]=z[i]/r; T len=ret.Len(); if (len==0) return Rand(); ret/=len; if (radius_==1) return ret; return ret*radius_; } Vector<N, T> RandOnDim(int n) { assert(n<=N); Vector<N, T> z; for (int i=0; i<n; i++) z[i]=z_.Rand(); T r=0; for (int i=0; i<n; i++) r+=z[i]*z[i]; r=Sqrt(r); Vector<N, T> ret; for (int i=0; i<n; i++) ret[i]=z[i]/r; for (int i=n; i<N; i++) ret[i]=0; T len=ret.Len(); if (len==0) return RandOnDim(n); ret/=len; if (radius_==1) return ret; else return ret*radius_; } void SeedFromTime(){z_.SeedFromTime();} private: RandomNormal<T, R> z_; const T radius_; }; }
zzz-engine
zzzEngine/zCore/zCore/Math/Random.hpp
C++
gpl3
11,332
#pragma once #include "../common.hpp" namespace zzz{ // Donald Knuth's 32 bit Mix Function // Discussed by Thomas Wang, HP // http://www.concentric.net/~Ttwang/tech/inthash.htm inline zuint HashKnuthUInt(zuint key) { // 2654435761 is the golden ratio of 2^32 return key*2654435761u; } // Robert Jenkin's 32 bit Mix Function // Better variation in low order bits than Knuth's method // Discussed by Thomas Wang, HP // http://www.concentric.net/~Ttwang/tech/inthash.htm inline zuint HashJenkinsUInt(zuint key) { key += (key << 12); key ^= (key >> 22); key += (key << 4); key ^= (key >> 9); key += (key << 10); key ^= (key >> 2); key += (key << 7); key ^= (key >> 12); return key; } // Thomas Wang's 32 bit Mix Function // Better variation in low order bits than Knuth's method // Discussed by Thomas Wang, HP // http://www.concentric.net/~Ttwang/tech/inthash.htm inline zuint HashWangUInt(zuint key) { key += ~(key << 15); key ^= (key >> 10); key += (key << 3); key ^= (key >> 6); key += ~(key << 11); key ^= (key >> 16); return key; } }
zzz-engine
zzzEngine/zCore/zCore/Math/HashFunction.hpp
C++
gpl3
1,124
#pragma once //a tensor-like data structure to store data #include "../common.hpp" #include "../Utility/Log.hpp" #include "../Utility/IOObject.hpp" #include "Vector2.hpp" #include "Vector3.hpp" #include "Vector4.hpp" #include "Vector.hpp" //low case function is STL competible, therefore at() takes int and size() return int; //Capital function takes VectorBase, At() takes VectorBase and Size() return VectorBase //[] take both namespace zzz { template<int N, typename T> class ArrayBase { public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef zuint size_type; typedef size_type difference_type; protected: T *v; VectorBase<N,size_type> sizes; VectorBase<N,size_type> subsizes; size_type size_all; public: //c'tor and d'tor ArrayBase():v(NULL),sizes(0),subsizes(0),size_all(0){} explicit ArrayBase(const VectorBase<N,size_type> &size):v(NULL),sizes(0),subsizes(0),size_all(0){SetSize(size);} ArrayBase(const T *data, const VectorBase<N,size_type> &size):v(NULL),sizes(0),subsizes(0),size_all(0){SetSize(size); SetData(data);} ArrayBase(const ArrayBase<N, T> &other):v(NULL),sizes(0),subsizes(0),size_all(0){SetSize(other.sizes); SetData(other.v);} virtual ~ArrayBase(){if (v) delete[] v; v=NULL;} //Direct pointer T* Data(){return v;} const T* Data() const {return v;} //mutator void SetData(const T *data){IOObject<T>::CopyData(v,data,size_all);} void SetSize(const VectorBase<N,size_type> &size) { if (sizes==size) return; if (v) { delete[] v; v = NULL; } sizes=size; subsizes[N-1]=1; for (int i=N-2; i>=0; i--) subsizes[i]=subsizes[i+1]*sizes[i+1]; size_all=subsizes[0]*sizes[0]; if (size_all != 0) { v=new T[size_all]; ZCHECK_NOT_NULL(v)<<"In ArrayBase, cannot allocate memory size of "<<sizeof(T)*size_all/1024.0/1024.0<<" MB"<<endl; } } void Set(const T *data, const VectorBase<N, size_type> &size){SetSize(size); SetData(data);} void Set(const ArrayBase<N, T> &other){SetSize(other.sizes); SetData(other.v);} const ArrayBase<N, T> &operator=(const ArrayBase<N, T> &other){Set(other); return *this;} const ArrayBase<N, T> &operator=(const T &other){for (size_type i=0; i<size_all; i++) v[i]=other; return *this;} void RawCopy(void *data, size_type length){ZRCHECK_LE(length, sizeof(T)*size_all); memcpy(v, data, length);} void RawCopy(const ArrayBase<N, T> &other){SetSize(other.sizes); memcpy(v,other.v,sizeof(T)*size_all);} //reference const T& At(const size_type pos) const{ ZRCHECK_LT(pos, size_all); return v[pos]; } T& At(const size_type pos) { ZRCHECK_LT(pos, size_all); return v[pos]; } const T& At(const VectorBase<N,size_type> &pos) const{return At(ToIndex(pos));} T& At(const VectorBase<N,size_type> &pos) {return At(ToIndex(pos));} const T& operator[](const size_type pos) const{return At(pos);} T& operator[](const size_type pos) {return At(pos);} const T& operator[](const VectorBase<N,size_type> &pos) const {return At(pos);} T& operator[](const VectorBase<N,size_type> &pos) {return At(pos);} const T& operator()(const VectorBase<N,size_type> &pos) const {return At(pos);} T& operator()(const VectorBase<N,size_type> &pos) {return At(pos);} //STL support // iterator support iterator begin() { return v; } const_iterator begin() const { return v; } iterator end() { return v+size_all; } const_iterator end() const { return v+size_all; } // reverse iterator support typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end());} reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const {return const_reverse_iterator(begin());} // at() with range check reference at(size_type i) { return At(i); } const_reference at(size_type i) const { return At(i); } // front() and back() reference front() { return v[0]; } const_reference front() const { return v[0];} reference back() { return v[size_all-1]; } const_reference back() const { return v[size_all-1]; } // size is constant size_type size() const { return size_all; } size_type Size(size_type i) const { return sizes[i]; } VectorBase<N,size_type> Size() const { return sizes; } bool empty() const { return v == NULL; } size_type max_size() const { return size_all; } void clear() { this->Clear(); } void Clear() { SetSize(VectorBase<N,size_type>(0)); } // index size_type ToIndex(const VectorBase<N,size_type> &pos) const {return pos.Dot(subsizes);} VectorBase<N,size_type> ToIndex(size_type idx) const { VectorBase<N,size_type> pos; for (size_type i=0; i<N; i++) { pos[i]=idx/subsizes[i]; idx-=pos[i]*subsizes[i]; } return pos; } bool CheckIndex(const VectorBase<N,size_type> &pos) const {for (size_type i=0; i<N; i++) if (pos[i]>=sizes[i]) return false; return true;} bool CheckIndex(const size_type &pos) const {return pos<size_all;} //addition inline const ArrayBase<N, T> operator+(const ArrayBase<N, T> &a) const { ZCHECK_EQ(sizes, a.sizes); ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]+a.v[i]; return ret; } inline const ArrayBase<N, T> operator+(const T &a) const { ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]+a; return ret; } inline void operator+=(const ArrayBase<N, T> &a) { ZCHECK_EQ(sizes, a.sizes); for (unsigned int i=0; i<size_all; i++) v[i]+=a.v[i]; } inline void operator+=(const T &a) { for (unsigned int i=0; i<size_all; i++) v[i]+=a; } //subtraction inline const ArrayBase<N, T> operator-(const ArrayBase<N, T> &a) const { ZCHECK_EQ(sizes, a.sizes); ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]-a.v[i]; return ret; } inline const ArrayBase<N, T> operator-(const T &a) const { ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]-a; return ret; } inline void operator-=(const ArrayBase<N, T> &a) { ZCHECK_EQ(sizes, a.sizes); for (unsigned int i=0; i<size_all; i++) v[i]-=a.v[i]; } inline void operator-=(const T &a) { for (unsigned int i=0; i<size_all; i++) v[i]-=a; } //multiplication inline const ArrayBase<N, T> operator*(const ArrayBase<N, T> &a) const { ZCHECK_EQ(sizes, a.sizes); ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]*a.v[i]; return ret; } inline const ArrayBase<N, T> operator*(const T &a) const { ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]*a; return ret; } inline void operator*=(const ArrayBase<N, T> &a) { ZCHECK_EQ(sizes, a.sizes); for (unsigned int i=0; i<size_all; i++) v[i]*=a.v[i]; } inline void operator*=(const T &a) { for (unsigned int i=0; i<size_all; i++) v[i]*=a; } //division inline const ArrayBase<N, T> operator/(const ArrayBase<N, T> &a) const { ZCHECK_EQ(sizes, a.sizes); ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]/a.v[i]; return ret; } inline const ArrayBase<N, T> operator/(const T &a) const { ArrayBase<N, T> ret; for (unsigned int i=0; i<size_all; i++) ret.v[i]=v[i]/a; return ret; } inline void operator/=(const ArrayBase<N, T> &a) { ZCHECK_EQ(sizes, a.sizes); for (unsigned int i=0; i<size_all; i++) v[i]/=a.v[i]; } inline void operator/=(const T &a) { for (unsigned int i=0; i<size_all; i++) v[i]/=a; } //Min and Max inline T Max() { T maxv=v[0]; for (unsigned int i=1; i<size_all; i++) if (maxv<v[i]) maxv=v[i]; return maxv; } inline int MaxPos() { T maxv=v[0]; int pos=0; for (unsigned int i=1; i<size_all; i++) if (maxv<v[i]) {maxv=v[i];pos=i;} return pos; } inline T Min() { T minv=v[0]; for (unsigned int i=1; i<size_all; i++) if (minv>v[i]) minv=v[i]; return minv; } inline int MinPos() { T minv=v[0]; int pos=0; for (unsigned int i=1; i<size_all; i++) if (minv>v[i]) {minv=v[i];pos=i;} return pos; } inline T AbsMax() { T maxv=v[0]; for (unsigned int i=1; i<size_all; i++) if (maxv<abs(v[i])) maxv=v[i]; return maxv; } inline int AbsMaxPos() { T maxv=v[0]; int pos=0; for (unsigned int i=1; i<size_all; i++) if (maxv<abs(v[i])) {maxv=v[i];pos=i;} return pos; } inline T AbsMin() { T minv=v[0]; for (unsigned int i=1; i<size_all; i++) if (minv>abs(v[i])) minv=v[i]; return minv; } inline int AbsMinPos() { T minv=v[0]; int pos=0; for (unsigned int i=1; i<size_all; i++) if (minv>abs(v[i])) {minv=v[i];pos=i;} return pos; } // math inline T Dot(const ArrayBase<N, T> &a) const { ZCHECK_EQ(sizes, a.sizes); T ret=0; for (unsigned int i=0; i<size_all; i++) ret+=v[i]*a.v[i]; return ret; } inline T Sum() const{T ret=0;for (unsigned int i=0; i<size_all; i++) ret+=v[i];return ret;} inline void Negative() {for (size_type i=0; i<size_all; i++) v[i]=-v[i];} inline T Len() const {return (T)sqrt((double)LenSqr());} inline T LenSqr() const {return Dot(*this);} inline T Normalize() {T norm=Len(); *this/=norm; return norm;} inline ArrayBase<N, T> Normalized() const {return *this/Len();} inline T DistTo(const ArrayBase<N, T> &a) const {return (T)sqrt((double)DistToSqr(a));} inline T DistToSqr(const ArrayBase<N, T> &a) const {ArrayBase<N, T> diff(*this-a); return diff.Dot(diff);} inline ArrayBase<N, T> Abs() { ArrayBase<N, T> ret; for (size_type i=0; i<N; i++) ret[i]=Abs(at(i)); return ret; } // comparisons bool operator== (const ArrayBase<N, T>& y) const {return std::equal(begin(), end(), y.begin());} bool operator< (const ArrayBase<N, T>& y) const {return std::lexicographical_compare(begin(),end(), y.begin(), y.end());} bool operator!= (const ArrayBase<N, T>& y) const {return !(*this==y);} bool operator> (const ArrayBase<N, T>& y) const {return y<*this;} bool operator<= (const ArrayBase<N, T>& y) const {return !(y<*this);} bool operator>= (const ArrayBase<N, T>& y) const {return !(*this<y);} void Zero(zuchar x=0){memset(v, x, sizeof(T)*size_all);} void Fill(const T &a) { for (size_type i=0; i<size_all; i++) v[i]=a; } void Fill(const VectorBase<N,size_type> &size, const T &a) { SetSize(size); Fill(a); } //IO friend inline ostream& operator<<(ostream& os,const ArrayBase<N, T> &me) { for (int i=0; i<me.size(); i++) os<<me.v[i]<<' '; return os; } friend inline istream& operator>>(istream& is,ArrayBase<N, T> &me) { for (int i=0; i<me.size(); i++) is>>me.v[i]; return is; } void SaveToFileA(ostream &fo) const { fo<<sizes; for (int i=0; i<size_all; i++) fo<<v[i]<<' '; } void LoadFromFileA(istream &fi) { VectorBase<N,size_type> s; fi>>s; SetSize(s); for (int i=0; i<size_all; i++) fi>>v[i]; } void WriteFileB(FILE *fp) const { sizes.WriteFileB(fp); fwrite(v,sizeof(T),size_all,fp); } void ReadFileB(FILE *fp) { VectorBase<N,size_type> s; s.ReadFileB(fp); SetSize(s); fread(v,sizeof(T),size_all,fp); } T Interpolate(const VectorBase<N,double> &coord) const { Vector<N,double> ratio; Vector<N, size_type> Min; Vector<N, size_type> Max; for (int i=0; i<N; i++) { if (coord[i]<0) return T(0); size_type tmp=floor(coord[i]); if (tmp>=Size(i)-1) return T(0); Min[i]=tmp; Max[i]=tmp+1; ratio[i]=1.0-coord[i]+tmp; } //rip out the cell ArrayBase<N, T> data(Vector<N,size_type>(2)); { VectorBase<N,size_type> thiscoord(0); bool good=true; while(good) { //interpolate if (thiscoord==Vector<N,size_type>(1)) int dummy=1; data(thiscoord)=At(thiscoord+Min); //next coord thiscoord[N-1]++; //normalize int curdim=N-1; while(true) { if (thiscoord[curdim]<2) break; //good if (curdim==0) //overflow { good=false; break; } thiscoord[curdim]=0; curdim--; thiscoord[curdim]++; } } } for (int i=0; i<N; i++) { VectorBase<N,size_type> thiscoord(0); bool good=true; while(good) { //interpolate VectorBase<N,size_type> another(thiscoord); another[i]=1; data(thiscoord)=data(thiscoord)*ratio[i]+data(another)*(1.0-ratio[i]); //next coord thiscoord[N-1]++; //normalize int curdim=N-1; while(true) { if (curdim==i) //overflow { good=false; break; } if (thiscoord[curdim]<2) break; //good thiscoord[curdim]=0; curdim--; thiscoord[curdim]++; } } } return data(VectorBase<N,size_type>(0)); } }; //write all these stuff just to avoid direct memory copy when construct and copy template <unsigned int N, typename T> class Array: public ArrayBase<N, T> { public: //constructor Array(void){} explicit Array(const VectorBase<N,size_type> &size):ArrayBase<N, T>(size){} Array(const T *data, const VectorBase<N,size_type> &size):ArrayBase<N, T>(data, size){} Array(const Array<N, T>& a):ArrayBase<N, T>(a) {} Array(const ArrayBase<N, T>& a):ArrayBase<N, T>(a) {} //assign inline const Array<N, T> &operator=(const Array<N, T>& a){ArrayBase<N, T>::operator =(a); return *this;} using ArrayBase<N, T>::operator=; }; // IOObject template<unsigned int N, typename T> class IOObject<ArrayBase<N, T> > { public: static void WriteFileB(FILE *fp, const ArrayBase<N, T> &src) { Vector<N, zuint64> size(src.Size()); IOObj::WriteFileB(fp, size); IOObj::WriteFileB(fp, src.Data(), src.size()); } static void ReadFileB(FILE *fp, ArrayBase<N, T>& dst) { Vector<N, zuint64> s; IOObj::ReadFileB(fp, s); dst.SetSize(Vector<N, zuint>(s)); IOObj::ReadFileB(fp, dst.Data(), dst.size()); } static void WriteFileR(RecordFile &fp, const zint32 label, const ArrayBase<N, T>& src) { Vector<N, zuint64> size(src.Size()); IOObj::WriteFileR(fp, label, size); IOObj::WriteFileR(fp, src.Data(), src.size()); } static void ReadFileR(RecordFile &fp, const zint32 label, ArrayBase<N, T>& dst) { Vector<N, zuint64> size; IOObj::ReadFileR(fp, label, size); dst.SetSize(Vector<N, zuint>(size)); IOObj::ReadFileR(fp, dst.Data(), dst.size()); } /// When the object inside Array is not SIMPLE_IOOBJECT, it must access 1 by 1, /// instead of access as a raw array. static const int RF_SIZE = 1; static const int RF_DATA = 2; static void WriteFileR1By1(RecordFile &rf, const zint32 label, const ArrayBase<N, T>& src) { VectorBase<N, zuint64> len = src.Size(); rf.WriteChildBegin(label); IOObj::WriteFileR(rf, RF_SIZE, len); rf.WriteRepeatBegin(RF_DATA); zuint sizeall = src.size(); for (zuint i = 0; i < sizeall; ++i) { rf.WriteRepeatChild(); IOObj::WriteFileR(rf, src[i]); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); } static void ReadFileR1By1(RecordFile &rf, const zint32 label, ArrayBase<N, T>& dst) { dst.clear(); if (!rf.LabelExist(label)) { return; } rf.ReadChildBegin(label); VectorBase<N, zuint64> len; IOObj::ReadFileR(rf, RF_SIZE, len); dst.SetSize(len); rf.ReadRepeatBegin(RF_DATA); zuint i = 0; while(rf.ReadRepeatChild()) { T v; IOObj::ReadFileR(rf, v); dst[i++] = v; } rf.ReadRepeatEnd(); ZCHECK_EQ(dst.size(), len) << "The length recorded is different from the actual length of data"; rf.ReadChildEnd(); } }; template<zuint N, typename T> class IOObject<Array<N, T> > { public: static void WriteFileB(FILE *fp, const Array<N, T> &src) { IOObject<ArrayBase<N, T> >::WriteFileB(fp, src); } static void ReadFileB(FILE *fp, Array<N, T>& dst) { IOObject<ArrayBase<N, T> >::ReadFileB(fp, dst); } static void WriteFileR(RecordFile &fp, const zint32 label, const Array<N, T>& src) { IOObject<ArrayBase<N, T> >::WriteFileR(fp, label, src); } static void ReadFileR(RecordFile &fp, const zint32 label, Array<N, T>& dst) { IOObject<ArrayBase<N, T> >::ReadFileR(fp, label, dst); } }; template <zuint N, typename T> inline ArrayBase<N, T> Abs(const ArrayBase<N, T> &x) { return x.Abs(); } }
zzz-engine
zzzEngine/zCore/zCore/Math/Array.hpp
C++
gpl3
17,416
#pragma once #include "Matrix.hpp" namespace zzz{ template <typename T> class Matrix<3, 3, T> : public MatrixBase<3, 3, T> { public: Matrix(){} Matrix(const Matrix<3, 3, T> &mat):MatrixBase<3, 3, T>(mat){} Matrix(const MatrixBase<3, 3, T> &mat):MatrixBase<3, 3, T>(mat){} template<typename T1> explicit Matrix<3, 3, T>(const MatrixBase<3, 3,T1>& a):MatrixBase<3, 3, T>(a) {} template<typename T1> explicit Matrix<3, 3, T>(const Matrix<3, 3,T1>& a):MatrixBase<3, 3, T>(a) {} template<typename T1> explicit Matrix<3, 3, T>(const T1 *p):MatrixBase<3, 3, T>(p) {} explicit Matrix<3, 3, T>(const T &a):MatrixBase<3, 3, T>(a){} Matrix(const T& a,const T& b,const T& c,const T& d,const T& e,const T& f,const T& g,const T& h,const T& i) { T* v=Data(); v[0]=a; v[1]=b; v[2]=c; v[3]=d; v[4]=e; v[5]=f; v[6]=g; v[7]=h; v[8]=i; } explicit Matrix(const T *p) { T* v=Data(); v[0]=p[0]; v[1]=p[1]; v[2]=p[2]; v[3]=p[3]; v[4]=p[4]; v[5]=p[5]; v[6]=p[6]; v[7]=p[7]; v[8]=p[8]; } Matrix(const Vector<3, T>& a,const Vector<3, T>& b,const Vector<3, T>& c) { T* v=Data(); v[0]=a[0]; v[1]=a[1]; v[2]=a[2]; v[3]=b[0]; v[4]=b[1]; v[5]=b[2]; v[6]=c[0]; v[7]=c[1]; v[8]=c[2]; } explicit Matrix(const Vector<3, T> *a) { T* v=Data(); v[0]=a[0][0]; v[1]=a[0][1]; v[2]=a[0][2]; v[3]=a[1][0]; v[4]=a[1][1]; v[5]=a[1][2]; v[6]=a[2][0]; v[7]=a[2][1]; v[8]=a[2][2]; } //assign inline const Matrix<3, 3, T> &operator=(const Matrix<3, 3, T>& a){MatrixBase<3, 3, T>::operator =(a); return *this;} using MatrixBase<3, 3, T>::operator=; using MatrixBase<3, 3, T>::Data; //alias const T& m00() const {return Data()[0];} const T& m01() const {return Data()[1];} const T& m02() const {return Data()[2];} const T& m10() const {return Data()[3];} const T& m11() const {return Data()[4];} const T& m12() const {return Data()[5];} const T& m20() const {return Data()[6];} const T& m21() const {return Data()[7];} const T& m22() const {return Data()[8];} const T& v0() const {return Data()[0];} const T& v1() const {return Data()[1];} const T& v2() const {return Data()[2];} const T& v3() const {return Data()[3];} const T& v4() const {return Data()[4];} const T& v5() const {return Data()[5];} const T& v6() const {return Data()[6];} const T& v7() const {return Data()[7];} const T& v8() const {return Data()[8];} T& m00() {return Data()[0];} T& m01() {return Data()[1];} T& m02() {return Data()[2];} T& m10() {return Data()[3];} T& m11() {return Data()[4];} T& m12() {return Data()[5];} T& m20() {return Data()[6];} T& m21() {return Data()[7];} T& m22() {return Data()[8];} T& v0() {return Data()[0];} T& v1() {return Data()[1];} T& v2() {return Data()[2];} T& v3() {return Data()[3];} T& v4() {return Data()[4];} T& v5() {return Data()[5];} T& v6() {return Data()[6];} T& v7() {return Data()[7];} T& v8() {return Data()[8];} }; typedef Matrix<3, 3,zint8> Matrix3x3i8; typedef Matrix<3, 3,zuint8> Matrix3x3ui8; typedef Matrix<3, 3,zint16> Matrix3x3i16; typedef Matrix<3, 3,zuint16> Matrix3x3ui16; typedef Matrix<3, 3,zint32> Matrix3x3i32; typedef Matrix<3, 3,zuint32> Matrix3x3ui32; typedef Matrix<3, 3,zint64> Matrix3x3i64; typedef Matrix<3, 3,zuint64> Matrix3x3ui64; typedef Matrix<3, 3,zfloat32> Matrix3x3f32; typedef Matrix<3, 3,zfloat64> Matrix3x3f64; typedef Matrix<3, 3,zuint> Matrix3x3ui; typedef Matrix<3, 3,int> Matrix3x3i; typedef Matrix<3, 3,float> Matrix3x3f; typedef Matrix<3, 3,double> Matrix3x3d; }
zzz-engine
zzzEngine/zCore/zCore/Math/Matrix3x3.hpp
C++
gpl3
3,671
#pragma once namespace zzz { // Column majored sparse matrix template<typename T> class SparseMatrix { SparseMatrix():row_(0), col_(0), sorted_(false){} SparseMatrix(zuint row, zuint col):row_(row), col_(col), sorted_(false){} void Create(zuint row, zuint col) { Clear(); if (row_==row && col_==col) return; row_=row; col_=col; } void ClearData() { for (zuint i=0; i<v_.size(); i++) v_[i].clear(); } void Clear() { v_.clear(); } const T& operator()(zuint row, zuint col) const { return Get(row, col); } const T& Get(zuint row, zuint col) const { vector<ColumnDataNode>::const_iterator vi; if (sorted_) vi = std::lower_bound(v_[col].begin(), v_[col].end(), row, RowEqual()); else vector<ColumnDataNode>::const_iterator vi = std::find(v_[col].begin(), v_[col].end(), row, RowEqual()); if (vi!=v_[col].end()) return vi->second; else return ZERO_VALUE; } T& MustGet(zuint row, zuint col) { vector<ColumnDataNode>::const_iterator vi; if (sorted_) vi = std::lower_bound(v_[col].begin(), v_[col].end(), row, RowEqual()); else vector<ColumnDataNode>::const_iterator vi = std::find(v_[col].begin(), v_[col].end(), row, RowEqual()); if (vi!=v_[col].end()) return vi->second; else { v_[col].push_back(make_pair(row, ZERO_VALUE)); sorted_=false; return v_[col].back(); } } void AddData(int row, int col, const T& number) { MustGet(row, col) = number; } void SortColumn() { for (zuint i=0; i<v_.size(); i++) sort(v_[i].begin(), v_[i].end()); sorted_=true; } private: typedef std::pair<int,double> ColumnDataNode; typedef std::vector<ColumnDataNode> ColumnData; static T ZERO_VALUE; class RowEqual { bool operator()(const int row, const ColumnDataNode &node) {return row == node.first;} }; bool sorted_; zuint row_, col_; vector<ColumnData> v_; }; template<typename T> T SparseMatrix::ZERO_VALUE=T(0); }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/SparseMatrix.hpp
C++
gpl3
2,128
#pragma once #include <common.hpp> #include "Vector.hpp" #undef min #undef max namespace zzz{ template <typename T> class Vector<3, T> : public VectorBase<3, T> { protected: using VectorBase<3, T>::v; public: //constructor Vector(void){} Vector(const Vector<3, T>& a):VectorBase<3, T>(a){} Vector(const T &a,const T &b,const T &c){v[0]=a; v[1]=b; v[2]=c;} Vector(const VectorBase<3, T>& a):VectorBase<3, T>(a){} explicit Vector(const T &a):VectorBase<3, T>(a){} explicit Vector(const VectorBase<2, T> &a, const T &b):VectorBase<3, T>(a, b){} explicit Vector(const VectorBase<4, T> &a):VectorBase<3, T>(a){} template<typename T1> explicit Vector(const T1 *p):VectorBase<3, T>(p){} template<typename T1> explicit Vector(const Vector<3,T1>& a):VectorBase<3, T>(a){} template<typename T1> explicit Vector(const VectorBase<3,T1>& a):VectorBase<3, T>(a){} inline const Vector<3, T> &operator=(const Vector<3, T>& a){VectorBase<3, T>::operator =(a); return *this;} inline void Set(const T &a, const T &b, const T &c){v[0]=a; v[1]=b; v[2]=c;} using VectorBase<3, T>::operator=; // Vector3 only cross inline Vector<3, T> Cross(const Vector<3, T> &a) const { return Vector<3, T>(v[1]*a.v[2]-v[2]*a.v[1], v[2]*a.v[0]-v[0]*a.v[2], v[0]*a.v[1]-v[1]*a.v[0]); } // alias inline T& x(){return v[0];} inline T& y(){return v[1];} inline T& z(){return v[2];} inline T& r(){return v[0];} inline T& g(){return v[1];} inline T& b(){return v[2];} inline T& i(){return v[0];} inline T& j(){return v[1];} inline T& k(){return v[2];} inline const T& x() const {return v[0];} inline const T& y() const {return v[1];} inline const T& z() const {return v[2];} inline const T& r() const {return v[0];} inline const T& g() const {return v[1];} inline const T& b() const {return v[2];} inline const T& i() const {return v[0];} inline const T& j() const {return v[1];} inline const T& k() const {return v[2];} }; typedef Vector<3,zint8> Vector3i8; typedef Vector<3,zuint8> Vector3ui8; typedef Vector<3,zint8> Vector3i16; typedef Vector<3,zuint8> Vector3ui16; typedef Vector<3,zint8> Vector3i32; typedef Vector<3,zuint8> Vector3ui32; typedef Vector<3,zint8> Vector3i64; typedef Vector<3,zuint8> Vector3ui64; typedef Vector<3,zfloat32> Vector3f32; typedef Vector<3,zfloat64> Vector3f64; typedef Vector<3,zuchar> Vector3uc; typedef Vector<3,zuint> Vector3ui; typedef Vector<3,int> Vector3i; typedef Vector<3,float> Vector3f; typedef Vector<3,double> Vector3d; template<typename T> inline Vector<3, T> Cross(const VectorBase<3, T> &a, const VectorBase<3, T> &b) { return Vector<3, T>(a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]); } template<typename T> inline void Cross(const VectorBase<3, T> &a, const VectorBase<3, T> &b, VectorBase<3, T> &res) { res[0]=a[1]*b[2]-a[2]*b[1]; res[1]=a[2]*b[0]-a[0]*b[2]; res[2]=a[0]*b[1]-a[1]*b[0]; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Vector3.hpp
C++
gpl3
3,011
#pragma once #include <common.hpp> namespace zzz{ template<typename T> class Average { public: Average():ave_(0), count_(0){} const T Sum() const {return ave_*count_;} const zuint Count() const {return count_;} const T Mean() const {return ave_;} void AddData(const T &p) { ave_ = ave_*(double(count_)/(count_+1)) + p / double(count_+1); count_++; } template<typename T1> void AddData(const T1& _begin, const T1& _end) { for (T1 i=_begin; i!=_end; i++) AddData(*i); } void operator+=(const T &x) { AddData(x); } void operator+=(const vector<T> &x) { AddData(x.begin(), x.end()); } void operator+=(const Average<T> &x) { ave_ = ave_*(double(count_)/(count_+x.count_)) + x.ave_*(double(x.count_)/(count_+x.count_)); count_ += x.Count(); } private: T ave_; zuint count_; }; } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/Average.hpp
C++
gpl3
925
#pragma once #include <common.hpp> #include "Vector2.hpp" namespace zzz{ template <typename T> class MinMax { public: #undef max #undef min MinMax():min_(numeric_limits<T>::max()),max_(numeric_limits<T>::is_signed ? -numeric_limits<T>::max() : 0){} MinMax(const T &min,const T &max):min_(min),max_(max){} MinMax(const T &p):min_(p),max_(p){} MinMax(const vector<T> &data):min_(numeric_limits<T>::max()),max_(-numeric_limits<T>::max()){ *this += data; } // create from list of vertex void Reset() { min_=T(numeric_limits<T>::max()); max_=T(-numeric_limits<T>::max()); } // min and max T &Min(){return min_;} const T &Min() const{return min_;} T &Max(){return max_;} const T &Max() const{return max_;} // Offset void SetOffset(const T &offset) { min_+=offset; max_+=offset; } // Center T Center() const{return (min_+max_)*0.5;} // Difference T Diff() const{return max_-min_;} Vector<2, T> Range() const {return Vector<2, T>(min_, max_);} bool IsLegal() const { if (min_>max_) return false; return true; } bool IsEmpty() const { return min_==max_; } void AddData(const T &p) { if (min_>p) min_=p; if (max_<p) max_=p; } template<typename T1> void AddData(const T1& _begin, const T1& _end) { for (T1 i = _begin; i != _end; i++) AddData(*i); } /// Boolean union void operator+=(const T &p) { AddData(p); } /// Boolean union void operator+=(const std::vector<T> &p) { AddData(p.begin(), p.end()); } /// Boolean union void operator+=(const MinMax<T> &box) { AddData(box.min_); AddData(box.max_); } const MinMax<T>& operator+(const MinMax<T> &box) const { MinMax<T> ret(*this); ret.AddData(box); return ret; } /// Boolean intersection void operator*=(const MinMax<T> &box) { if (min_<box.min_) min_=box.min_; if (max_>box.max_) max_=box.max_; } const MinMax<T>& operator*(const MinMax<T> &box) const { MinMax<T> ret(*this); ret*=box; return ret; } /// Box equality operator bool operator==(const MinMax<T> &box) const { return min_==box.min_ && max_==box.max_; } /// Volumetric classification bool IsInside(const T &pos) const { if (!Within<T>(min_,pos,max_)) return false; return true; } /// Intersection between boxes bool IsIntersect(const MinMax<T> &box) const { if (min_ > box.max_) return false; if (max_ < box.min_) return false; return true; } static MinMax<T> ZERO() { return MinMax(T(0), T(0)); } static MinMax<T> INFINITY() { return MinMax(); } T min_, max_; }; typedef MinMax<int> MinMaxi; typedef MinMax<float> MinMaxf; typedef MinMax<double> MinMaxd; SIMPLE_IOOBJECT(MinMaxi); SIMPLE_IOOBJECT(MinMaxf); SIMPLE_IOOBJECT(MinMaxd); }
zzz-engine
zzzEngine/zCore/zCore/Math/MinMax.hpp
C++
gpl3
2,965
#pragma once #include "DVector.hpp" // dynamic matrix, size is changable, and can own the data or not(different from Array<2, T>) namespace zzz{ template <typename T, bool OWN=true> class DMatrixBase { public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef zsize size_type; typedef size_type difference_type; protected: size_type nrow,ncol,size; size_type pit; T *v; public: inline DVector<T,false> Row(size_type a) { return DVector<T,false>(v+a*pit,ncol); } inline const DVector<T,false> Row(size_type a) const { return DVector<T,false>(v+a*pit,ncol); } template<bool OWN1> inline void operator=(const DMatrixBase<T,OWN1>& a); template<bool OWN1> inline DMatrixBase<T,true> operator*(const DMatrixBase<T,OWN1>& a) { DMatrixBase<T,true> temp(nrow, a.ncol); for (size_type i=0; i<nrow; i++) for (size_type j=0; j<a.ncol; j++) { temp[i][j]=0.0f; for (size_type k=0; k<ncol; k++) temp[i][j]+=At(i, k)*a[k][j]; } return temp; } template<bool OWN1> inline DVector<T,true> operator*(const DVector<T,OWN1>& a) { ZCHECK_EQ(ncol, a.size); DVector<T,true> ret(nrow); for (size_type i=0; i<nrow; i++) ret[i]=Row(i).Dot(a); return ret; } inline void operator=(const T& a) { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)=a; } inline void operator+=(const T a) { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)+=a; } inline void operator-=(const T a) { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)-=a; } inline void operator*=(const T a) { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)*=a; } inline void operator/=(const T a) { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)/=a; } public: friend inline ostream& operator<<(ostream& os,const DMatrixBase<T> &me) { for (size_type i=0; i<me.nrow; i++) { for (size_type j=0; j<me.ncol; j++) zout<<me.v[i*me.pit+j]<<' '; zout<<'\n'; } } inline T& At(size_type r,size_type c){return v[r*pit+c];} inline const T& At(size_type r,size_type c) const {return v[r*pit+c];} inline T& operator()(size_type r,size_type c){return v[r*pit+c];} inline const T& operator()(size_type r,size_type c) const {return v[r*pit+c];} void Negative() { for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) At(i, j)=-At(i, j); } void SetSize(size_type r,size_type c); void Transpose(); void Zero(); void Fill(const T &v); public: //math inline T Sum() { T ret=0; for (size_type i=0; i<nrow; i++) for (size_type j=0; j<ncol; j++) ret+=At(i, j); return ret; } DMatrixBase():v(NULL),nrow(0),ncol(0),pit(0),size(0){} }; ////////////////////////////////////////////////////////////////////////// template<typename T, bool OWN=true> class DMatrix : public DMatrixBase<T,OWN> { // Need to be partial specified. }; //specialize whole class for own template<typename T> class DMatrix<T,true> : public DMatrixBase<T,true> { public: using DMatrixBase<T,true>::size; using DMatrixBase<T,true>::v; using DMatrixBase<T,true>::nrow; using DMatrixBase<T,true>::ncol; using DMatrixBase<T,true>::pit; DMatrix(){} DMatrix(size_type row, size_type col){SetSize(row,col);} DMatrix(size_type row, size_type col, T f){ SetSize(row, col);for (size_type i=0; i<size; i++) v[i]=f;} DMatrix(T *a, size_type row, size_type col) { v=new T[row * col]; memcpy(v, a, sizeof(T) * row * col); nrow = row; ncol = col; pit = col; } DMatrix(const T *a,size_type row,size_type col) { v=new T[row*col]; memcpy(v, a,sizeof(T)*row*col); nrow=row;ncol=col;pit=col; } DMatrix(T *a,zuint row,zuint col,zuint apit) { v=new T[row*col]; for(zuint i=0; i<row; i++) memcpy(v+i*col, a+i*apit,sizeof(T)*col); pit=col; nrow=row;ncol=col; } //copy constructor DMatrix(const DMatrix<T,true> &other){*this=other;} template<bool OWN1> DMatrix(const DMatrixBase<T,OWN1>& a){*this=a;} //operator= const DMatrix<T,true> &operator=(const DMatrix<T,true> &a) { SetSize(a.nrow, a.ncol); for (zuint i=0; i<nrow*ncol; i++) v[i]=a.v[i]; return *this; } template<bool OWN1> const DMatrixBase<T,true> &operator=(const DMatrixBase<T,OWN1>& a) { SetSize(a.nrow, a.ncol); for (zuint i=0; i<nrow*ncol; i++) v[i]=a.v[i]; return *this; } ~DMatrix() { if (v) delete v; } void SetSize(zuint r,zuint c) { if (r==nrow && c==ncol) return; if (r*c!=size) { if (v) delete v; v=new T[r*c]; } nrow=r; ncol=c; size=r*c; pit=c; } using DMatrixBase<T,true>::At; void Transpose() { DMatrix<T,true> temp(*this); SetSize(ncol,nrow); for (zuint i=0; i<nrow; i++) for (zuint j=0; j<ncol; j++) At(i, j)=temp.At(j, i); } inline T* Data() {return v;} inline const T* Data() const {return v;} void Zero() { memset(v, 0,sizeof(T)*nrow*ncol); } void Fill(const T &a) { zuint s=nrow*ncol; for (zuint i=0; i<s; i++) v[i]=a; } }; //specialize whole class for not own template<typename T> class DMatrix<T,false> : public DMatrixBase<T,false> { public: using DMatrixBase<T,false>::size; using DMatrixBase<T,false>::v; using DMatrixBase<T,false>::nrow; using DMatrixBase<T,false>::ncol; using DMatrixBase<T,false>::pit; using DMatrixBase<T,false>::At; // DMatrix(){} DMatrix(T *a,zuint m,zuint n) { v=a; nrow=m;ncol=n;pit=n; } DMatrix(const T *a, zuint m, zuint n); DMatrix(T *a, zuint m, zuint n, zuint apit) { v=a; pit=apit; nrow=m;ncol=n; } DMatrix(const DMatrix<T,false>& a) { v=a.v; nrow=a.nrow;ncol=a.ncol;pit=a.pit; } template<bool OWN1> DMatrix(const DMatrixBase<T,OWN1>& a) { v=a.v; nrow=a.nrow;ncol=a.ncol;pit=a.pit; } ////////////////////////////////////////////////////////////////////////// const DMatrix<T,false>& operator=(const DMatrix<T,false>& a) { ZCHECK(nrow=a.nrow && ncol=a.ncol); for (zuint r=0; r<nrow; r++) for (zuint c=0; c<ncol; c++) At(r, c)=a.At(r, c); return *this; } template<bool OWN1> const DMatrixBase<T,false> & operator=(const DMatrixBase<T,OWN1>& a) { ZCHECK(nrow=a.nrow && ncol=a.ncol); for (zuint r=0; r<nrow; r++) for (zuint c=0; c<ncol; c++) At(r, c)=a.At(r, c); return *this; } template<bool OWN1> void SetSource(const DMatrixBase<T,OWN1>& a) { v=a.v; nrow=a.nrow;ncol=a.ncol;pit=a.pit; } template<bool OWN1> void SetSource(const T *a, const zuint rows, const zuint cols) { v=a; nrow=rows;ncol=cols;pit=ncol; } void Transpose() { DMatrix<T> temp(ncol,nrow); memcpy(temp.v, v,sizeof(T)*nrow*ncol); for (zuint i=0; i<nrow; i++) for (zuint j=0; j<ncol; j++) At(j, i)=temp.At(i, j); } void Zero() { T *c=v; for (zuint i=0; i<nrow; i++) { memset(c, 0,sizeof(T)*ncol); c+=pit; } } void Fill(const T &a) { zuint s=nrow*ncol; T *c=v; for (zuint i=0; i<nrow; i++) { for (zuint j=0; j<ncol; j++) c[j]=a; c+=pit; } } }; typedef DMatrix<zint8> DMatrixi8; typedef DMatrix<zuint8> DMatrixui8; typedef DMatrix<zint16> DMatrixi16; typedef DMatrix<zuint8> DMatrixui16; typedef DMatrix<zint32> DMatrixi32; typedef DMatrix<zuint32> DMatrixui32; typedef DMatrix<zint64> DMatrixi64; typedef DMatrix<zuint64> DMatrixui64; typedef DMatrix<zfloat32> DMatrixf32; typedef DMatrix<zfloat64> DMatrixf64; typedef DMatrix<float> DMatrixf; typedef DMatrix<double> DMatrixd; typedef DMatrix<int> DMatrixi; typedef DMatrix<zuint> DMatrixui; }
zzz-engine
zzzEngine/zCore/zCore/Math/DMatrix.hpp
C++
gpl3
8,251
#pragma once // dynamic vector, size is changable. can own the data or not(different form Array<1, T>) // when own, = set data, when not own = set reference #include "../common.hpp" namespace zzz{ template <typename T, bool OWN=true> class DVectorBase { public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef zsize size_type; typedef size_type difference_type; protected: T *v; zsize size; public: //STL support // iterator support iterator begin() { return v; } const_iterator begin() const { return v; } iterator end() { return v+size; } const_iterator end() const { return v+size; } // reverse iterator support typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end());} reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const {return const_reverse_iterator(begin());} // at() reference at(size_type i) {return v[i]; } const_reference at(size_type i) const {return v[i]; } // front() and back() reference front() { return v[0]; } const_reference front() const { return v[0];} reference back() { return v[size-1]; } const_reference back() const { return v[size-1]; } // size is constant bool empty() { return v==NULL; } // swap (note: linear complexity) template<bool OWN1> void swap (DVectorBase<T,OWN1>& y) { ZCHECK(size=y.size); std::swap_ranges(begin(),end(), y.begin());} ////////////////////////////////////////////////////////////////////////// // check range (may be private because it is static) bool IndexCheck (size_type i) { return (i>=0 && i<size());} //subscript inline T& operator [](int a) {return v[a];} inline const T& operator [](int a) const {return v[a];} //positive and negative inline const DVectorBase<T,OWN> operator+() const {return *this;} inline const DVectorBase<T,true> operator-() const {DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=-v[i]; return ret;} //addition template<bool OWN1> inline const DVectorBase<T,true> operator+(const DVectorBase<T,OWN1> &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]+a.v[i]; return ret; } inline const DVectorBase<T,true> operator+(const T &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]+a; return ret; } template<bool OWN1> inline void operator+=(const DVectorBase<T,OWN1> &a) { for (unsigned int i=0; i<size; i++) v[i]+=a.v[i]; } inline void operator+=(const T &a) { for (unsigned int i=0; i<size; i++) v[i]+=a; } //subtraction template<bool OWN1> inline const DVectorBase<T,true> operator-(const DVectorBase<T,OWN1> &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]-a.v[i]; return ret; } inline const DVectorBase<T,true> operator-(const T &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]-a; return ret; } template<bool OWN1> inline void operator-=(const DVectorBase<T,OWN1> &a) { for (unsigned int i=0; i<size; i++) v[i]-=a.v[i]; } inline void operator-=(const T &a) { for (unsigned int i=0; i<size; i++) v[i]-=a; } //multiplication template<bool OWN1> inline const DVectorBase<T,true> operator*(const DVectorBase<T,OWN1> &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]*a.v[i]; return ret; } inline const DVectorBase<T,true> operator*(const T &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]*a; return ret; } template<bool OWN1> inline void operator*=(const DVectorBase<T,OWN1> &a) { for (unsigned int i=0; i<size; i++) v[i]*=a.v[i]; } inline void operator*=(const T &a) { for (unsigned int i=0; i<size; i++) v[i]*=a; } //division template<bool OWN1> inline const DVectorBase<T,true> operator/(const DVectorBase<T,OWN1> &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]/a.v[i]; return ret; } inline const DVectorBase<T,true> operator/(const T &a) const { DVectorBase<T,true> ret; for (unsigned int i=0; i<size; i++) ret.v[i]=v[i]/a; return ret; } template<bool OWN1> inline void operator/=(const DVectorBase<T,OWN1> &a) { for (unsigned int i=0; i<size; i++) v[i]/=a.v[i]; } inline void operator/=(const T &a) { for (unsigned int i=0; i<size; i++) v[i]/=a; } //conversion inline T* Data() {return v;} inline const T* Data() const {return v;} inline void Zero() {memset(v, 0,sizeof(T)*size);} inline void Fill(const T &a){for (size_type i=0; i<size; i++) v[i]=a;} DVectorBase<T,false> SubVec(size_type start,size_type end){return DVectorBase<T,false>(v+start,end-start+1);} //math inline void Negative(){for (int i=0; i<size; i++) v[i]=-v[i];} inline T Len() const {return (T)sqrt((double)LenSqr());} inline T LenSqr() const { T ret=0; for (unsigned int i=0; i<size; i++) ret+=v[i]*v[i]; return (ret); } template<bool OWN1> inline T Dot(const DVectorBase<T,OWN1> &a) const { ZCHECK_EQ(size, a.size); T ret=0; for (unsigned int i=0; i<size; i++) ret+=v[i]*a.v[i]; return ret; } inline T Sum() const { T ret=0; for (size_type i=0; i<size; i++) ret+=v[i]; return ret; } inline T Normalize() {T norm=Len(); *this/=norm; return norm;} inline DVectorBase<T,true> Normalized() const {return *this/Len();} template<bool OWN1> inline T DistTo(const DVectorBase<T,OWN1> &a) const {return (T)sqrt((double)DistToSqr(a));} template<bool OWN1> inline T DistToSqr(const DVectorBase<T,OWN1> &a) const { T ret=0; for (unsigned int i=0; i<size; i++) ret+=(v[i]-a.v[i])*(v[i]-a.v[i]); return (ret); } DVectorBase<T,true> RandomPerpendicularUnitVec() const { DVectorBase<T,true> ret((T)0); ret[v[0]>(T)(1-EPS)?1:0]=(T)1; ret-=*this*ret.Dot(*this)/LenSqr(); ret.Normalize(); return ret; } //Min and Max inline T Max() { T maxv=v[0]; for (unsigned int i=1; i<size; i++) if (maxv<v[i]) maxv=v[i]; return maxv; } inline int MaxPos() { T maxv=v[0]; int pos=0; for (unsigned int i=1; i<size; i++) if (maxv<v[i]) {maxv=v[i];pos=i;} return pos; } inline T Min() { T minv=v[0]; for (unsigned int i=1; i<size; i++) if (minv>v[i]) minv=v[i]; return minv; } inline int MinPos() { T minv=v[0]; int pos=0; for (unsigned int i=1; i<size; i++) if (minv>v[i]) {minv=v[i];pos=i;} return pos; } inline T AbsMax() { T maxv=v[0]; for (unsigned int i=1; i<size; i++) if (maxv<abs(v[i])) maxv=v[i]; return maxv; } inline int AbsMaxPos() { T maxv=v[0]; int pos=0; for (unsigned int i=1; i<size; i++) if (maxv<abs(v[i])) {maxv=v[i];pos=i;} return pos; } inline T AbsMin() { T minv=v[0]; for (unsigned int i=1; i<size; i++) if (minv>abs(v[i])) minv=v[i]; return minv; } inline int AbsMinPos() { T minv=v[0]; int pos=0; for (unsigned int i=1; i<size; i++) if (minv>abs(v[i])) {minv=v[i];pos=i;} return pos; } // comparisons template<bool OWN1> bool operator== (const DVectorBase<T,OWN1>& y) const {return std::equal(begin(), end(), y.begin());} template<bool OWN1> bool operator< (const DVectorBase<T,OWN1>& y) const {return std::lexicographical_compare(begin(),end(), y.begin(), y.end());} template<bool OWN1> bool operator!= (const DVectorBase<T,OWN1>& y) const {return !(*this==y);} template<bool OWN1> bool operator> (const DVectorBase<T,OWN1>& y) const {return y<*this;} template<bool OWN1> bool operator<= (const DVectorBase<T,OWN1>& y) const {return !(y<*this);} template<bool OWN1> bool operator>= (const DVectorBase<T,OWN1>& y) const {return !(*this<y);} inline bool operator==(const T &c) const { for (int i=0; i<size; i++) if (v[i]!=c) return false; return true; } inline bool operator!=(const T &c) const {return !(*this==c);} //IO friend inline ostream& operator<<(ostream& os,const DVectorBase<T,OWN> &me) { for (int i=0; i<me.size; i++) os<<me.v[i]<<' '; return os; } friend inline istream& operator>>(istream& is,DVectorBase<T,OWN> &me) { for (int i=0; i<me.size; i++) is>>me.v[i]; return is; } void SaveToFileA(ostream &fo) { fo<<*this; } void LoadFromFileA(istream &fi) { fi>>*this; } void SaveToFileB(FILE *fp) { fwrite(v,sizeof(T),size,fp); } void LoadFromFileB(FILE *fp) { fread(v,sizeof(T),size,fp); } //dump inline void Print(ostream &os=zout) const { os<<"[ "; os<<*this; os<<"]\n"; } //constructor DVectorBase() {v=NULL;size=0;} ~DVectorBase(){} }; ////////////////////////////////////////////////////////////////////////// //define base template<typename T, bool OWN=true> struct DVector : public DVectorBase<T,OWN> { // Need partial specified. }; //specify whole class for own template<typename T> struct DVector<T,true> : public DVectorBase<T,true> { using DVectorBase<T,true>::v; using DVectorBase<T,true>::size; DVector(){} DVector(size_type n){v=new T[n]; size=n;} DVector(size_type n,const T& v); DVector(T *a, size_type n){v=new T[n]; size=n; for (size_type i=0; i<n; i++) v[i]=a[i];} DVector(const DVector<T,true>& a){*this=a;} template<bool OWN1> DVector(const DVectorBase<T,OWN1>& vec){v=new T[vec.size]; size=vec.size; for (zuint i=0; i<size; i++) v[i]=vec.v[i];} ~DVector(){if (v) delete[] v;} //copy const DVector<T,true> &operator=(const DVector<T,true>& a){SetSize(a.size); for (unsigned int i=0; i<size; i++) v[i]=(T)a[i]; return *this;} template <typename T1, bool OWN1> const DVector<T,true> &operator=(const DVectorBase<T1,OWN1>& a){SetSize(a.size); for (unsigned int i=0; i<size; i++) v[i]=(T)a[i]; return *this;} void SetSize(size_type n){if (n==size) return; if (v) delete v; v=new T[n]; size=n;} }; //specify whole class for not own template<typename T> struct DVector<T,false> : public DVectorBase<T,false> { using DVectorBase<T,false>::v; using DVectorBase<T,false>::size; DVector(size_type n,const T& v){v=new T[n]; size=n; for (size_type i=0; i<n; i++)v[i]=v;} DVector(T *a, size_type n){v=a; size=n;} DVector(const DVector<T,false>& a){v=a.v;size=a.size;} template<bool OWN1> DVector(const DVectorBase<T,OWN1>& vec){v=vec.v; size=vec.size;} ~DVector(){} //copy template <bool OWN1> inline const DVector<T,false> &operator=(const DVector<T,OWN1>& a){v=a.v; return *this;} template <bool OWN1> void SetHolder(const DVector<T,OWN1>& a){v=a.v; size=a.size; return *this;} void SetHolder(const T* a, const int n){v=a.v; size=n; return *this;} }; typedef DVector<zint8> DVectori8; typedef DVector<zuint8> DVectorui8; typedef DVector<zint16> DVectori16; typedef DVector<zuint8> DVectorui16; typedef DVector<zint32> DVectori32; typedef DVector<zuint32> DVectorui32; typedef DVector<zint64> DVectori64; typedef DVector<zuint64> DVectorui64; typedef DVector<zfloat32> DVectorf32; typedef DVector<zfloat64> DVectorf64; typedef DVector<float,true> DVectorf; typedef DVector<double,true> DVectord; typedef DVector<int,true> DVectori; typedef DVector<zuint,true> DVectorui; }
zzz-engine
zzzEngine/zCore/zCore/Math/DVector.hpp
C++
gpl3
12,113
#pragma once #include "../Utility/Tools.hpp" #include "../Utility/Timer.hpp" #include "../Utility/Log.hpp" #include "Math.hpp" //Iteration Exit Condition //Condition can be combination of abs(residue), iteration times more, abs(residue difference), or running time //If any condition satisfied, IsSatisfied will return true to indicate stop iteration namespace zzz{ template<typename T> class IterExitCond { public: //if true, exit bool IsSatisfied(T residue) { bool ret=false; ZLOG(ZDEBUG)<<"Iteration:"<<iterCount_; iterCount_++; if (CheckBit(exitCond_,ITERCOUNT)) if (iterCount_>=iterCountCond_) ret=true; ZLOG(ZDEBUG)<<" Residue:"<<residue; if (CheckBit(exitCond_,RESIDUE)) { if (Abs(residue)<=residueCond_) residueCount_++; else residueCount_=0; ZLOG(ZDEBUG)<<" ResidueCount:"<<residueCount_; if (residueCount_>=residueCountCond_) ret=true; } if (CheckBit(exitCond_,RESIDUEDIFF)) { if (iterCount_>1) { T diff=Abs(lastResidue_-residue); ZLOG(ZDEBUG)<<" Diff:"<<diff; if (diff<=residueDiffCond_) residueDiffCount_++; else residueDiffCount_=0; ZLOG(ZDEBUG)<<" DiffCount:"<<residueDiffCount_; if (residueDiffCount_>=residueDiffCountCond_) ret=true; } lastResidue_=residue; } if (CheckBit(exitCond_,TIME)) { double time=timer_.Elapsed(); if (time>=timeCond_) ret=true; ZLOG(ZDEBUG)<<" RunningTime:"<<time; } if (CheckBit(exitCond_, REPEAT)) { history_.push_front(residue); if (history_.size()>repeatLengthCond_*repeatTimesCond_) history_.pop_back(); for (zuint i=2; i<=repeatLengthCond_; i++) { if (history_.size()>=i*repeatTimesCond_) { bool all_equal=true; for (zuint k=1; k<i; k++) { if (history_[k]!=history_.front()) { all_equal=false; break; } } if (all_equal) continue; bool foundRepeat=true; for (zuint j=1; j<repeatTimesCond_; j++) { if (!equal(history_.begin(), history_.begin()+i, history_.begin()+j*i)) { foundRepeat=false; break; } } if (foundRepeat) { ret=true; ZLOGD<<" Repeat("<<i<<", "<<repeatTimesCond_<<")"; break; } } } } ZLOG(ZDEBUG)<<endl; //if (ret) Reset(); //if set maybe more convinient but difficult to debug return ret; } bool NeedLoop(T residue) { return !IsSatisfied(residue); } void Reset() { iterCount_=0; residueCount_=0; lastResidue_=0; residueDiffCount_=0; timer_.Restart(); } IterExitCond():exitCond_(0){Reset();} //set conditions void ClearAllCond() { exitCond_=0; } void SetCondResidue(T residue, zuint resicount=1) { residueCond_=residue; residueCountCond_=resicount; SetBit(exitCond_,RESIDUE); } void ClrCondResidue() { ClearBit(exitCond_,RESIDUE); } void SetCondIterCount(int i) { iterCountCond_=i; SetBit(exitCond_,ITERCOUNT); } void ClrCondIterCount() { ClearBit(exitCond_,ITERCOUNT); } void SetCondResidueDiff(T residiff, zuint residiffcount=1) { residueDiffCond_=residiff; residueDiffCountCond_=residiffcount; SetBit(exitCond_,RESIDUEDIFF); } void ClrCondResidueDiff() { ClearBit(exitCond_,RESIDUEDIFF); } void SetCondRunningTime(double seconds) { timeCond_=seconds; SetBit(exitCond_,TIME); } void ClrCondRunnintTIme() { ClearBit(exitCond_,TIME); } void SetCondRepeat(zuint repeat_length=10, zuint repeat_times=3) { repeatLengthCond_=repeat_length; repeatTimesCond_=repeat_times; history_.clear(); SetBit(exitCond_,REPEAT); } void ClrCondRepeat() { ClearBit(exitCond_,REPEAT); } private: //condition enum{RESIDUE=1,ITERCOUNT=2,RESIDUEDIFF=4,TIME=8,REPEAT=16}; int exitCond_; // iter count zuint iterCountCond_; // residue T residueCond_; zuint residueCountCond_; // residue diff T residueDiffCond_; zuint residueDiffCountCond_; // running time double timeCond_; // repeat zuint repeatLengthCond_; zuint repeatTimesCond_; deque<T> history_; //real data zuint iterCount_; zuint residueCount_; T lastResidue_; zuint residueDiffCount_; Timer timer_; }; }
zzz-engine
zzzEngine/zCore/zCore/Math/IterExitCond.hpp
C++
gpl3
4,604
#pragma once #include <zMat.hpp> namespace zzz{ class NonlinearSystem { public: NonlinearSystem(int n_var, int n_cons):nVar_(n_var),nConstraints_(n_cons){} int nVar_; int nConstraints_; virtual void Initialize(zVector<double> &init_x)=0; virtual void WriteBack(const zVector<double> &result_x)=0; virtual void CalculateResidue(double *residue, const double *x)=0; //jac is nConstraints*nVar virtual void CalculateJacobian(zMatrixBaseW<double,zColMajor> &jac, const double *x)=0; }; class NonlinearSystemSolver { public: virtual int Solve(NonlinearSystem &sys)=0; }; }
zzz-engine
zzzEngine/zCore/zCore/Math/NonlinearSystem/NonlinearSystem.hpp
C++
gpl3
611
#define ZCORE_SOURCE #include "MinpackSolver.hpp" #ifdef ZZZ_LIB_MINPACK #include <minpack.h> #include <zMat.hpp> #include "../../Utility/StringPrintf.hpp" namespace zzz{ NonlinearSystem *mysys=NULL; const string PrintResidue(const int *m, const double *fvec) { double v=0; for (int i=0; i<*m; i++) v+=fvec[i]*fvec[i]; return StringPrintf("Residue: %lf[%lf]", v, v/(*m)); } void lmder_helper(const int *m, const int *n, const double *x, double *fvec, double *fjac, const int *ldfjac, int *iflag) { if (*iflag==1) { mysys->CalculateResidue(fvec, x); ZLOG(ZDEBUG)<<PrintResidue(m,fvec); } else if (*iflag==2) { memset(fjac, 0,sizeof(double)*(*m)*(*n)); zMatrixRawArrayDressW<double,zColMajor> jac=Dress(fjac, mysys->nConstraints_, mysys->nVar_); mysys->CalculateJacobian(jac, x); } } void InterpretError(int err) { switch(err) { case 0: ZLOG(ZVERBOSE)<<"improper input parameters.\n"; break; case 1: ZLOG(ZVERBOSE)<<"algorithm estimates that the relative error in the sum of squares is at most tol.\n"; break; case 2: ZLOG(ZVERBOSE)<<"algorithm estimates that the relative error between x and the solution is at most tol.\n"; break; case 3: ZLOG(ZVERBOSE)<<"conditions for info = 1 and info = 2 both hold.\n"; break; case 4: ZLOG(ZVERBOSE)<<"fvec is orthogonal to the columns of the Jacobian to machine precision.\n"; break; case 5: ZLOG(ZVERBOSE)<<"number of calls to fcn has reached or exceeded 200*(n+1).\n"; break; case 6: ZLOG(ZVERBOSE)<<"tol is too small. no further reduction in the sum of squares is possible.\n"; break; case 7: ZLOG(ZVERBOSE)<<"tol is too small. no further improvement in the approximate solution x is possible.\n"; break; } } int MinpackSolver::Solve(NonlinearSystem &sys) { //ATTENTION: this is NOT thread-safe mysys=&sys; zVector<double> init_value; sys.Initialize(init_value); ZCHECK_EQ(init_value.Size(0), sys.nVar_) <<"The number of initial value is not enough! Need: " <<sys.nVar_<<", Provided:"<<init_value.Size(0); int m=sys.nConstraints_; int n=sys.nVar_; zVector<double> fvec(m); //output zMatrix<double> fjac(m, n); //output int ldfjac=m; double tol=EPSILON; int info; //output zVector<int> ipvt(n); //output int lwa=m*n+5*n+m; zVector<double> wa(lwa); lmder1_(lmder_helper, &m, &n,init_value.Data(),fvec.Data(),fjac.Data(), &ldfjac, &tol, &info,ipvt.Data(),wa.Data(), &lwa); sys.WriteBack(init_value); InterpretError(info); return info; } } #endif // ZZZ_LIB_MINPACK
zzz-engine
zzzEngine/zCore/zCore/Math/NonlinearSystem/MinpackSolver.cpp
C++
gpl3
2,628
#pragma once #include <LibraryConfig.hpp> #ifdef ZZZ_LIB_MINPACK #include "NonlinearSystem.hpp" namespace zzz{ class MinpackSolver : public NonlinearSystemSolver { public: int Solve(NonlinearSystem &sys); }; } #endif // ZZZ_LIB_MINPACK
zzz-engine
zzzEngine/zCore/zCore/Math/NonlinearSystem/MinpackSolver.hpp
C++
gpl3
254
#pragma once #include "Vector2.hpp" #include "Array.hpp" namespace zzz { template <typename T> struct Array<2, T> : public ArrayBase<2, T> { using ArrayBase<2, T>::v; using ArrayBase<2, T>::subsizes; public: //constructor Array(void){} Array(const zuint r, const zuint c):ArrayBase<2, T>(Vector2ui(r, c)){} explicit Array(const VectorBase<2,zuint> &size):ArrayBase<2, T>(size){} Array(const T *data, const zuint r, const zuint c):ArrayBase<2, T>(data, Vector2ui(r, c)){} Array(const T *data, const VectorBase<2,zuint> &size):ArrayBase<2, T>(data, size){} Array(const Array<2, T>& a):ArrayBase<2, T>(a) {} Array(const ArrayBase<2, T>& a):ArrayBase<2, T>(a) {} //assign inline const Array<2, T> &operator=(const Array<2, T>& a){ArrayBase<2, T>::operator =(a); return *this;} using ArrayBase<2, T>::operator=; //reference using ArrayBase<2, T>::operator(); using ArrayBase<2, T>::At; const T& At(const zuint r, const zuint c) const{ ZRCHECK_LT(r, Size(0)); ZRCHECK_LT(c, Size(1)); return At(ToIndex(r, c)); } T& At(const zuint r, const zuint c) { ZRCHECK_LT(r, Size(0)); ZRCHECK_LT(c, Size(1)); return At(ToIndex(r, c)); } const T& operator()(const zuint r, const zuint c) const{return At(r, c);} T& operator()(const zuint r, const zuint c) {return At(r, c);} T Interpolate(const double r, const double c) const {return ArrayBase<2, T>::Interpolate(Vector2d(r, c));} using ArrayBase<2, T>::Interpolate; zuint ToIndex(const zuint r, const zuint c) const {return r*subsizes[0] + c*subsizes[1];} using ArrayBase<2, T>::ToIndex; bool CheckIndex(const zuint r, const zuint c) const {return ArrayBase<2, T>::CheckIndex(Vector2ui(r, c));} using ArrayBase<2, T>::CheckIndex; void SetSize(const zuint r, const zuint c) {ArrayBase<2, T>::SetSize(Vector2ui(r, c));} using ArrayBase<2, T>::SetSize; void Fill(const zuint r, const zuint c, const T &a) { SetSize(r, c); Fill(a); } using ArrayBase<2, T>::Fill; }; typedef Array<2,zint8> Array2i8; typedef Array<2,zuint8> Array2ui8; typedef Array<2,zint16> Array2i16; typedef Array<2,zuint8> Array2ui16; typedef Array<2,zint32> Array2i32; typedef Array<2,zuint32> Array2ui32; typedef Array<2,zint64> Array2i64; typedef Array<2,zuint64> Array2ui64; typedef Array<2,zfloat32> Array2f32; typedef Array<2,zfloat64> Array2f64; typedef Array<2,char> Array2c; typedef Array<2,zuchar> Array2uc; typedef Array<2,short> Array2s; typedef Array<2,zushort> Array2us; typedef Array<2,int> Array2i; typedef Array<2,zuint> Array2ui; typedef Array<2,float> Array2f; typedef Array<2,double> Array2d; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/Array2.hpp
C++
gpl3
2,721
#pragma once #include "../common.hpp" #include "../Utility/Log.hpp" #include "../Utility/IOObject.hpp" #include "../Utility/Tools.hpp" #include "Math.hpp" #undef min #undef max namespace zzz{ template <unsigned int N, typename T> class VectorBase { protected: T v[N]; public: // STL support // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef zsize size_type; typedef size_type difference_type; // iterator support iterator begin() { return v; } const_iterator begin() const { return v; } iterator end() { return v+N; } const_iterator end() const { return v+N; } // reverse iterator support typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end());} reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const {return const_reverse_iterator(begin());} // at() reference at(size_type i) { ZRCHECK_LT(i, N); return v[i]; } const_reference at(size_type i) const { ZRCHECK_LT(i, N); return v[i]; } // front() and back() reference front() { return v[0]; } const_reference front() const { return v[0];} reference back() { return v[N-1]; } const_reference back() const { return v[N-1]; } // size is constant static size_type size() { return N; } static bool empty() { return false; } static size_type max_size() { return N; } enum { static_size = N }; // swap (note: linear complexity) void swap (VectorBase<N, T>& y) { std::swap_ranges(begin(),end(), y.begin());} // check range (may be private because it is static) bool CheckIndex (size_type i) { return (i>=0 && i<size());} //subscript inline T& operator [](int a) {return at(a);} inline const T& operator [](int a) const {return at(a);} //copy inline const VectorBase<N, T> &operator=(const T &a){for (unsigned int i=0; i<N; ++i) v[i]=a; return *this;} inline const VectorBase<N, T> &operator=(const VectorBase<N, T>& a){IOObject<T>::CopyData(v, a.v, N); return *this;} template <typename T1> inline const VectorBase<N, T> &operator=(const VectorBase<N,T1>& a){for (unsigned int i=0; i<N; ++i) v[i]=(T)a[i]; return *this;} //raw data access inline T* Data(){return v;} inline const T* Data() const {return v;} //rawcopy inline void RawCopy(const VectorBase<N, T>& a){memcpy(v, a.v,sizeof(T)*N);} inline void RawCopy(const T *a){memcpy(v, a.v,sizeof(T)*N);} inline void Zero(zuchar x=0){memset(v, x, sizeof(T)*N);} inline static VectorBase<N, T> GetZero(int x=0){VectorBase<N, T> v; v.Zero(x); return v;} inline void Fill(const T &a){for (size_type i=0; i<N; ++i) v[i]=a;} inline static VectorBase<N, T> GetFill(const T &x){VectorBase<N, T> v; v.Fill(x); return v;} //positive and negative inline const VectorBase<N, T> operator+() const {return *this;} inline const VectorBase<N, T> operator-() const {VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=-v[i]; return ret;} //addition inline const VectorBase<N, T> operator+(const VectorBase<N, T> &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]+a.v[i]; return ret; } inline const VectorBase<N, T> operator+(const T &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]+a; return ret; } inline void operator+=(const VectorBase<N, T> &a) { for (unsigned int i=0; i<N; ++i) v[i]+=a.v[i]; } inline void operator+=(const T &a) { for (unsigned int i=0; i<N; ++i) v[i]+=a; } //subtraction inline const VectorBase<N, T> operator-(const VectorBase<N, T> &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]-a.v[i]; return ret; } inline const VectorBase<N, T> operator-(const T &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]-a; return ret; } inline void operator-=(const VectorBase<N, T> &a) { for (unsigned int i=0; i<N; ++i) v[i]-=a.v[i]; } inline void operator-=(const T &a) { for (unsigned int i=0; i<N; ++i) v[i]-=a; } //multiplication inline const VectorBase<N, T> operator*(const VectorBase<N, T> &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]*a.v[i]; return ret; } inline const VectorBase<N, T> operator*(const T &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]*a; return ret; } inline void operator*=(const VectorBase<N, T> &a) { for (unsigned int i=0; i<N; ++i) v[i]*=a.v[i]; } inline void operator*=(const T &a) { for (unsigned int i=0; i<N; ++i) v[i]*=a; } //division inline const VectorBase<N, T> operator/(const VectorBase<N, T> &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]/a.v[i]; return ret; } inline const VectorBase<N, T> operator/(const T &a) const { VectorBase<N, T> ret; for (unsigned int i=0; i<N; ++i) ret.v[i]=v[i]/a; return ret; } inline void operator/=(const VectorBase<N, T> &a) { for (unsigned int i=0; i<N; ++i) v[i]/=a.v[i]; } inline void operator/=(const T &a) { for (unsigned int i=0; i<N; ++i) v[i]/=a; } //math inline T Dot(const VectorBase<N, T> &a) const {T ret=0;for (unsigned int i=0; i<N; ++i) ret+=v[i]*a.v[i]; return ret;} inline T Sum() const{T ret=0;for (unsigned int i=0; i<N; ++i) ret+=v[i];return ret;} inline void Negative() {for (size_type i=0; i<N; ++i) v[i]=-v[i];} inline T Len() const {return Sqrt<T>((double)LenSqr());} inline T LenSqr() const {return FastDot(*this, *this);} inline T SafeNormalize() {T norm=Len(); if (norm!=0) *this/=norm; return norm;} inline VectorBase<N, T> SafeNormalized() const {T norm=Len(); if (norm!=0) return *this/norm; return *this;} inline T Normalize() {T norm=Len(); ZCHECK_NE(norm, 0)<<"Vector Normalize Failed!"; *this/=norm; return norm;} inline VectorBase<N, T> Normalized() const {T norm=Len(); ZCHECK_NE(norm, 0)<<"Vector Normalized Failed!"; return *this/norm;} inline T DistTo(const VectorBase<N, T> &a) const {return (T)sqrt((double)DistToSqr(a));} inline T DistToSqr(const VectorBase<N, T> &a) const {VectorBase<N, T> diff(*this-a); return diff.Dot(diff);} VectorBase<N, T> RandomPerpendicularUnitVec() const { VectorBase<N, T> ret((T)0); ret[Abs(v[0])>(T)(1-EPSILON)?1:0]=(T)1; ret-=*this*ret.Dot(*this)/LenSqr(); ret.Normalize(); return ret; } //Min and Max inline T Max() const { T maxv=v[0]; for (unsigned int i=1; i<N; ++i) if (maxv<v[i]) maxv=v[i]; return maxv; } inline int MaxPos() const { T maxv=v[0]; int pos=0; for (unsigned int i=1; i<N; ++i) if (maxv<v[i]) {maxv=v[i];pos=i;} return pos; } inline T Min() const { T minv=v[0]; for (unsigned int i=1; i<N; ++i) if (minv>v[i]) minv=v[i]; return minv; } inline int MinPos() const { T minv=v[0]; int pos=0; for (unsigned int i=1; i<N; ++i) if (minv>v[i]) {minv=v[i];pos=i;} return pos; } inline T AbsMax() const { T maxv=Abs(v[0]); for (unsigned int i=1; i<N; ++i) if (maxv<Abs(v[i])) maxv=Abs(v[i]); return maxv; } inline int AbsMaxPos() const { T maxv=Abs(v[0]); int pos=0; for (unsigned int i=1; i<N; ++i) if (maxv<Abs(v[i])) {maxv=Abs(v[i]);pos=i;} return pos; } inline T AbsMin() const { T minv=Abs(v[0]); for (unsigned int i=1; i<N; ++i) if (minv>Abs(v[i])) minv=Abs(v[i]); return minv; } inline int AbsMinPos() const { T minv=Abs(v[0]); int pos=0; for (unsigned int i=1; i<N; ++i) if (minv>Abs(v[i])) {minv=Abs(v[i]);pos=i;} return pos; } inline VectorBase<N, T> RotateToLeft() const { VectorBase<N, T> ret; for (size_type i = 0; i < N-1; ++i) ret[i] = v[i+1]; ret[N-1] = v[0]; return ret; } inline VectorBase<N, T> RotateToRight() const { VectorBase<N, T> ret; T tmp = v[N - 1]; for (size_type i = N-1; i >= 1; --i) ret[i]=v[i-1]; ret[0] = v[N - 1]; return ret } inline VectorBase<N, T> Reverse() const { VectorBase<N, T> ret; for (size_type i = 0; i < N; ++i) ret[i] = v[N - 1 - i]; return ret; } inline void KeepMin(const VectorBase<N, T> &y) { for (size_type i=0; i<N; ++i) v[i]=min(v[i], y[i]); } inline void KeepMax(const VectorBase<N, T> &y) { for (size_type i=0; i<N; ++i) v[i]=max(v[i], y[i]); } // comparisons bool operator== (const VectorBase<N, T>& y) const {return SafeEqual(begin(), end(), y.begin(), y.end());} bool operator< (const VectorBase<N, T>& y) const {return std::lexicographical_compare(begin(),end(), y.begin(), y.end());} bool operator!= (const VectorBase<N, T>& y) const {return !(*this==y);} bool operator> (const VectorBase<N, T>& y) const {return y<*this;} bool operator<= (const VectorBase<N, T>& y) const {return !(y<*this);} bool operator>= (const VectorBase<N, T>& y) const {return !(*this<y);} //IO friend inline ostream& operator<<(ostream& os,const VectorBase<N, T> &me) { for (int i=0; i<N; ++i) os<<me.v[i]<<' '; return os; } friend inline istream& operator>>(istream& is,VectorBase<N, T> &me) { for (int i=0; i<N; ++i) is>>me.v[i]; return is; } //constructor VectorBase(void){} VectorBase(const VectorBase<N, T>& a) {*this=a;} explicit VectorBase(const T &a){*this=a;} template<typename T1> explicit VectorBase(const T1 *p) {for (size_type i=0; i<N; ++i) v[i]=p[i];} template<typename T1> explicit VectorBase(const VectorBase<N,T1>& a) {*this=a;} template<typename T1> explicit VectorBase(const VectorBase<N-1,T1>& a, const T1 &b) {for (size_type i=0; i<N-1; ++i) v[i]=a[i]; v[N-1]=b;} template<typename T1> explicit VectorBase(const VectorBase<N+1,T1>& a) {for (size_type i=0; i<N; ++i) v[i]=a[i];} }; //scale at front template <zuint N, typename T> inline const VectorBase<N, T> operator+(const T &v,const VectorBase<N, T> &vec) { return vec+v; } template <zuint N,typename T> inline const VectorBase<N, T> operator-(const T &v,const VectorBase<N, T> &vec) { return -vec+v; } template <zuint N,typename T> inline const VectorBase<N, T> operator*(const T &v,const VectorBase<N, T> &vec) { return vec*v; } template <zuint N,typename T> inline const VectorBase<N, T> operator/(const T &v,const VectorBase<N, T> &vec) { VectorBase<N, T> res; for (size_type i=0; i<N; ++i) res[i]=v/vec[i]; return res; } //write all these stuff just to avoid direct memory copy when construct and copy template <unsigned int N,typename T> class Vector : public VectorBase<N, T> { protected: using VectorBase<N, T>::v; public: //constructor Vector(void){} Vector(const Vector<N, T>& a):VectorBase<N, T>(a) {} Vector(const VectorBase<N, T>& a):VectorBase<N, T>(a) {} explicit Vector(const T &a):VectorBase<N, T>(a){} explicit Vector(const VectorBase<N-1, T> &a, const T &b):VectorBase<N, T>(a, b){} explicit Vector(const VectorBase<N+1, T> &a):VectorBase<N, T>(a){} template<typename T1> explicit Vector(const T1 *p):VectorBase<N, T>(p) {} template<typename T1> explicit Vector(const Vector<N,T1>& a):VectorBase<N, T>(a) {} template<typename T1> explicit Vector(const VectorBase<N,T1>& a):VectorBase<N, T>(a) {} //assign inline const Vector<N, T> &operator=(const Vector<N, T>& a){VectorBase<N, T>::operator =(a); return *this;} using VectorBase<N, T>::operator=; }; //meta-programming... // primary template template <unsigned int N, typename T> struct DotProductHelper { static T Result (const T* a, const T* b) { return *a * *b + DotProductHelper<N-1, T>::Result(a+1, b+1); } }; // partial specialization as end criteria template <typename T> struct DotProductHelper<1, T> { static T Result (const T* a, const T* b) {return *a * *b;} }; // convenience function template <unsigned int N, typename T> inline T FastDot(const VectorBase<N, T> &a, const VectorBase<N, T> &b) { return DotProductHelper<N, T>::Result(a.Data(), b.Data()); } // IOObject template<unsigned int N, typename T> class IOObject<VectorBase<N, T> > { public: static void WriteFileB(FILE *fp, const VectorBase<N, T>* src, zsize size) { IOObject<T>::WriteFileB(fp, src->Data(), size*N); } static void ReadFileB(FILE *fp, VectorBase<N, T>* dst, zsize size) { IOObject<T>::ReadFileB(fp, dst->Data(), size*N); } static void WriteFileB(FILE *fp, const VectorBase<N, T>& src) { IOObject<T>::WriteFileB(fp, src.Data(), N); } static void ReadFileB(FILE *fp, VectorBase<N, T>& dst) { IOObject<T>::ReadFileB(fp, dst.Data(), N); } static void WriteFileR(RecordFile &fp, const zint32 label, const VectorBase<N, T>& src) { IOObject<T>::WriteFileR(fp, label, src.Data(), N); } static void ReadFileR(RecordFile &fp, const zint32 label, VectorBase<N, T>& dst) { IOObject<T>::ReadFileR(fp, label, dst.Data(), N); } static void WriteFileR(RecordFile &fp, const VectorBase<N, T>& src) { IOObject<T>::WriteFileR(fp, src.Data(), N); } static void ReadFileR(RecordFile &fp, VectorBase<N, T>& dst) { IOObject<T>::ReadFileR(fp, dst.Data(), N); } static void WriteFileR(RecordFile &fp, const zint32 label, const VectorBase<N, T>* src, zsize size) { IOObject<T>::WriteFileR(fp, label, src->Data(), size*N); } static void ReadFileR(RecordFile &fp, const zint32 label, VectorBase<N, T>* dst, zsize size) { IOObject<T>::ReadFileR(fp, label, dst->Data(), size*N); } static void WriteFileR(RecordFile &fp, const VectorBase<N, T>* src, zsize size) { IOObject<T>::WriteFileR(fp, src->Data(), size*N); } static void ReadFileR(RecordFile &fp, VectorBase<N, T>* dst, zsize size) { IOObject<T>::ReadFileR(fp, dst->Data(), size*N); } static void CopyData(VectorBase<N, T>* dst, const VectorBase<N, T>* src, zsize size) { IOObject<T>::CopyData(static_cast<T*>(dst->Data()), static_cast<const T*>(src->Data()), size*N); } }; template<unsigned int N, typename T> class IOObject<Vector<N, T> > { public: static void WriteFileB(FILE *fp, const Vector<N, T>* src, zsize size) { IOObject<VectorBase<N, T> >::WriteFileB(fp, src, size); } static void ReadFileB(FILE *fp, Vector<N, T>* dst, zsize size) { IOObject<VectorBase<N, T> >::ReadFileB(fp, dst, size); } static void WriteFileB(FILE *fp, const Vector<N, T>& src) { IOObject<VectorBase<N, T> >::WriteFileB(fp, src); } static void ReadFileB(FILE *fp, Vector<N, T>& dst) { IOObject<VectorBase<N, T> >::ReadFileB(fp, dst); } static void WriteFileR(RecordFile &fp, const zint32 label, const Vector<N, T>& src) { IOObject<VectorBase<N, T> >::WriteFileR(fp, label, src); } static void ReadFileR(RecordFile &fp, const zint32 label, Vector<N, T>& dst) { IOObject<VectorBase<N, T> >::ReadFileR(fp, label, dst); } static void WriteFileR(RecordFile &fp, const Vector<N, T>& src) { IOObject<VectorBase<N, T> >::WriteFileR(fp, src); } static void ReadFileR(RecordFile &fp, Vector<N, T>& dst) { IOObject<VectorBase<N, T> >::ReadFileR(fp, dst); } static void WriteFileR(RecordFile &fp, const zint32 label, const Vector<N, T>* src, zsize size) { IOObject<VectorBase<N, T> >::WriteFileR(fp, label, src, size); } static void ReadFileR(RecordFile &fp, const zint32 label, Vector<N, T>* dst, zsize size) { IOObject<VectorBase<N, T> >::ReadFileR(fp, label, dst, size); } static void WriteFileR(RecordFile &fp, const Vector<N, T>* src, zsize size) { IOObject<VectorBase<N, T> >::WriteFileR(fp, src, size); } static void ReadFileR(RecordFile &fp, Vector<N, T>* dst, zsize size) { IOObject<VectorBase<N, T> >::ReadFileR(fp, dst, size); } static void CopyData(Vector<N, T>* dst, const Vector<N, T>* src, zsize size) { IOObject<VectorBase<N, T> >::CopyData(dst, src, size); } }; template <zuint N, typename T> inline Vector<N, T> Abs(const VectorBase<N, T> &x) { Vector<N, T> ret; for (size_type i=0; i<N; ++i) ret[i]=Abs(x[i]); return ret; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Vector.hpp
C++
gpl3
16,862
#pragma once #include <zMat.hpp> namespace zzz{ //AX=B class LinearSystem { public: LinearSystem(int n_var, int n_cons):nVar_(n_var),nConstraints_(n_cons){} const int nVar_; const int nConstraints_; virtual void Initialize(zMatrix<double> &A, zVector<double> &B)=0; virtual void WriteBack(zVector<double> &x)=0; }; class LinearSystemSolver { public: virtual int Solve(LinearSystem &sys)=0; }; }
zzz-engine
zzzEngine/zCore/zCore/Math/LinearSystem/LinearSystem.hpp
C++
gpl3
430
#include "LinearSystem.hpp" namespace zzz{ class DirectSolver : LinearSystemSolver { public: int Solve(LinearSystem &sys); }; }
zzz-engine
zzzEngine/zCore/zCore/Math/LinearSystem/DirectSolver.hpp
C++
gpl3
138
#define ZCORE_SOURCE #include "DirectSolver.hpp" namespace zzz{ int DirectSolver::Solve(LinearSystem &sys) { zMatrix<double> A; zVector<double> B; sys.Initialize(A, B); zMatrix<double> U, S,VT; bool res=SVD(A, U, S,VT); ZCHECK(res)<<"SVD Failed in DirectSolver"; for (zuint i=0; i<S.Size(0); i++) if (S(i, i)<EPSILON) S(i, i)=0; else S(i, i)=1.0/S(i, i); zMatrix<double> PSU(Trans(VT)*S*Trans(U)); zVector<double> X(PSU*B); sys.WriteBack(X); return 0; } }
zzz-engine
zzzEngine/zCore/zCore/Math/LinearSystem/DirectSolver.cpp
C++
gpl3
508
#pragma once #include <common.hpp> #include "Vector.hpp" #undef min #undef max namespace zzz{ template <typename T> class Vector<4, T> : public VectorBase<4, T> { protected: using VectorBase<4, T>::v; public: //constructor Vector(void){} Vector(const Vector<4, T>& a):VectorBase<4, T>(a){} Vector(const T &a1,const T &b,const T &c,const T &d){v[0]=a1; v[1]=b; v[2]=c; v[3]=d;} Vector(const VectorBase<4, T>& a):VectorBase<4, T>(a){} explicit Vector(const T &a1):VectorBase<4, T>(a1){} explicit Vector(const VectorBase<3, T> &a, const T &b):VectorBase<4, T>(a, b){} explicit Vector(const VectorBase<5, T> &a):VectorBase<4, T>(a){} template<typename T1> explicit Vector(const T1 *p):VectorBase<4, T>(p) {} template<typename T1> explicit Vector(const Vector<4,T1>& a1):VectorBase<4, T>(a1) {} template<typename T1> explicit Vector(const VectorBase<4,T1>& a1):VectorBase<4, T>(a1) {} //assign inline const Vector<4, T> &operator=(const Vector<4, T>& a){VectorBase<4, T>::operator =(a); return *this;} inline void Set(const T &a, const T &b, const T &c, const T &d){v[0]=a; v[1]=b; v[2]=c; v[3]=d;} using VectorBase<4, T>::operator=; // alias inline T& x(){return v[0];} inline T& y(){return v[1];} inline T& z(){return v[2];} inline T& w(){return v[3];} inline T& r(){return v[0];} inline T& g(){return v[1];} inline T& b(){return v[2];} inline T& a(){return v[3];} inline const T& x()const {return v[0];} inline const T& y()const {return v[1];} inline const T& z()const {return v[2];} inline const T& w()const {return v[3];} inline const T& r()const {return v[0];} inline const T& g()const {return v[1];} inline const T& b()const {return v[2];} inline const T& a()const {return v[3];} }; typedef Vector<4,zint8> Vector4i8; typedef Vector<4,zuint8> Vector4ui8; typedef Vector<4,zint8> Vector4i16; typedef Vector<4,zuint8> Vector4ui16; typedef Vector<4,zint8> Vector4i32; typedef Vector<4,zuint8> Vector4ui32; typedef Vector<4,zint8> Vector4i64; typedef Vector<4,zuint8> Vector4ui64; typedef Vector<4,zfloat32> Vector4f32; typedef Vector<4,zfloat64> Vector4f64; typedef Vector<4,zuchar> Vector4uc; typedef Vector<4,zuint> Vector4ui; typedef Vector<4,int> Vector4i; typedef Vector<4,float> Vector4f; typedef Vector<4,double> Vector4d; }
zzz-engine
zzzEngine/zCore/zCore/Math/Vector4.hpp
C++
gpl3
2,374
#define ZCORE_SOURCE #include "Random.hpp" #include "Math.hpp" namespace zzz{ //RandomLCG RandomLCG::rng; const int RandomLCG::a = 16807; const int RandomLCG::m = 2147483647; const int RandomLCG::q = 127773; const int RandomLCG::r = 2836; RandomLCG::RandomLCG(const zuint seed) : idum_(0) { RandomLCG::Seed(seed); ZCHECK(idum_!=0); } RandomLCG::RandomLCG(const RandomLCG &rng) { idum_ = rng.idum_; } zuint RandomLCG::Rand() { // Based on Numerical Recipes in C // and FreeBSD implementation of libkern/random.c // http://minnie.cs.adfa.edu.au/FreeBSD-srctree/newsrc/libkern/random.c.html // http://www.scd.ucar.edu/zine/96/spring/articles/3.random-6.html // http://www.mactech.com/articles/mactech/Vol.08/08.03/RandomNumbers/ // http://wad.www.media.mit.edu/people/wad/mas864/psrc/random.c.txt // http://prog.cz/swag/swag/numbers/0081.htm // http://www.dcs.gla.ac.uk/mail-www/glasgow-haskell-users/msg00158.html int t = a*(idum_%q) - r*(idum_/q); if (t <= 0) t += m; idum_ = t; return idum_; } void RandomLCG::Seed(const zuint seed) { if (seed) idum_ = seed; else idum_ = 25101974; ZCHECK(idum_!=0); } void RandomLCG::SeedFromTime() { Seed(TimeSeed()); } zuint RandomLCG::Max() const { return m-1; } ////////////////////////////////////////////////////////////////////// RandomLFSRMix RandomLFSRMix::rng; RandomLFSRMix::RandomLFSRMix(const zuint seed1,const zuint seed2,const zuint seed3) { Seed(seed1,seed2,seed3); } RandomLFSRMix::RandomLFSRMix(const RandomLFSRMix &rng) { Seed(rng.regA_,rng.regB_,rng.regC_); } zuint RandomLFSRMix::Rand() { zuint result = 0; for (int j=0; j<32; j++) { regA_ = ((((regA_ >> 31) ^ (regA_ >> 6) ^ (regA_ >> 4) ^ (regA_ >> 2) ^ (regA_ << 1) ^ regA_) & 0x00000001) << 31) | (regA_ >> 1); regB_ = ((((regB_ >> 30) ^ (regB_ >> 2)) & 0x00000001) << 30) | (regB_ >> 1); regC_ = ((((regC_ >> 28) ^ (regC_ >> 1)) & 0x00000001) << 28) | (regC_ >> 1); result = (result << 1) ^ (((regA_ & regB_) | (~regA_ & regC_)) & 0x00000001); } return result; } void RandomLFSRMix::Seed(const zuint seed1,const zuint seed2,const zuint seed3) { regA_ = seed1; regB_ = seed2; regC_ = seed3; } void RandomLFSRMix::SeedFromTime() { Seed(TimeSeed()+regA_,TimeSeed()+regB_,TimeSeed()+regC_); } zuint RandomLFSRMix::Max() const { return MAX_UINT; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Random.cpp
C++
gpl3
2,497
#pragma once #include "Matrix.hpp" namespace zzz{ template <typename T> class Matrix<4, 4, T> : public MatrixBase<4, 4, T> { public: Matrix(){} Matrix(const Matrix<4, 4, T> &mat):MatrixBase<4, 4, T>(mat){} Matrix(const MatrixBase<4, 4, T> &mat):MatrixBase<4, 4, T>(mat){} template<typename T1> explicit Matrix<4, 4, T>(const MatrixBase<4, 4,T1>& a):MatrixBase<4, 4, T>(a) {} template<typename T1> explicit Matrix<4, 4, T>(const Matrix<4, 4,T1>& a):MatrixBase<4, 4, T>(a) {} template<typename T1> explicit Matrix<4, 4, T>(const T1 *p):MatrixBase<4, 4, T>(p) {} Matrix(const T& a,const T& b,const T& c,const T& d,const T& e,const T& f,const T& g,const T& h,const T& i,const T& j,const T& k,const T& l,const T& m,const T& n,const T& o,const T& p) { T* v=Data(); v[0]=a; v[1]=b; v[2]=c; v[3]=d; v[4]=e; v[5]=f; v[6]=g; v[7]=h; v[8]=i; v[9]=j; v[10]=k; v[11]=l; v[12]=m; v[13]=n; v[14]=o; v[15]=p; } explicit Matrix(const T *p) { T* v=Data(); v[0]=p[0]; v[1]=p[1]; v[2]=p[2]; v[3]=p[3]; v[4]=p[4]; v[5]=p[5]; v[6]=p[6]; v[7]=p[7]; v[8]=p[8]; v[9]=p[9]; v[10]=p[10]; v[11]=p[11]; v[12]=p[12]; v[13]=p[13]; v[14]=p[14]; v[15]=p[15]; } Matrix(const Vector<3, T>& a,const Vector<3, T>& b,const Vector<3, T>& c) { T* v=Data(); v[0]=a[0]; v[1]=a[1]; v[2]=a[2]; v[3]=0; v[4]=b[0]; v[5]=b[1]; v[6]=b[2]; v[7]=0; v[8]=c[0]; v[9]=c[1]; v[10]=c[2]; v[11]=0; v[12]=0; v[13]=0; v[14]=0; v[15]=1; } Matrix(const Vector<4, T>& a,const Vector<4, T>& b,const Vector<4, T>& c, const Vector<4, T> &d) { T* v=Data(); v[0]=a[0]; v[1]=a[1]; v[2]=a[2]; v[3]=a[3]; v[4]=b[0]; v[5]=b[1]; v[6]=b[2]; v[7]=b[3]; v[8]=c[0]; v[9]=c[1]; v[10]=c[2]; v[11]=c[3]; v[12]=d[0]; v[13]=d[1]; v[14]=d[2]; v[15]=d[3]; } explicit Matrix(const Vector<4, T> *Data()) { T* v=Data(); v[0]=v[0][0]; v[1]=v[0][1]; v[2]=v[0][2]; v[3]=v[0][3]; v[4]=v[1][0]; v[5]=v[1][1]; v[6]=v[1][2]; v[7]=v[1][3]; v[8]=v[2][0]; v[9]=v[2][1]; v[10]=v[2][2]; v[11]=v[2][3]; v[12]=v[3][0]; v[13]=v[3][1]; v[14]=v[3][2]; v[15]=v[3][3]; } //assign inline const Matrix<4, 4, T> &operator=(const Matrix<4, 4, T>& a){MatrixBase<4, 4, T>::operator =(a); return *this;} using MatrixBase<4, 4, T>::operator=; using MatrixBase<4, 4, T>::Data; //alias const T& m00() const {return Data()[0];} const T& m01() const {return Data()[1];} const T& m02() const {return Data()[2];} const T& m03() const {return Data()[3];} const T& m10() const {return Data()[4];} const T& m11() const {return Data()[5];} const T& m12() const {return Data()[6];} const T& m13() const {return Data()[7];} const T& m20() const {return Data()[8];} const T& m21() const {return Data()[9];} const T& m22() const {return Data()[10];} const T& m23() const {return Data()[11];} const T& m30() const {return Data()[12];} const T& m31() const {return Data()[13];} const T& m32() const {return Data()[14];} const T& m33() const {return Data()[15];} const T& v0() const {return Data()[0];} const T& v1() const {return Data()[1];} const T& v2() const {return Data()[2];} const T& v3() const {return Data()[3];} const T& v4() const {return Data()[4];} const T& v5() const {return Data()[5];} const T& v6() const {return Data()[6];} const T& v7() const {return Data()[7];} const T& v8() const {return Data()[8];} const T& v9() const {return Data()[9];} const T& v10() const {return Data()[10];} const T& v11() const {return Data()[11];} const T& v12() const {return Data()[12];} const T& v13() const {return Data()[13];} const T& v14() const {return Data()[14];} const T& v15() const {return Data()[15];} T& m00() {return Data()[0];} T& m01() {return Data()[1];} T& m02() {return Data()[2];} T& m03() {return Data()[3];} T& m10() {return Data()[4];} T& m11() {return Data()[5];} T& m12() {return Data()[6];} T& m13() {return Data()[7];} T& m20() {return Data()[8];} T& m21() {return Data()[9];} T& m22() {return Data()[10];} T& m23() {return Data()[11];} T& m30() {return Data()[12];} T& m31() {return Data()[13];} T& m32() {return Data()[14];} T& m33() {return Data()[15];} T& v0() {return Data()[0];} T& v1() {return Data()[1];} T& v2() {return Data()[2];} T& v3() {return Data()[3];} T& v4() {return Data()[4];} T& v5() {return Data()[5];} T& v6() {return Data()[6];} T& v7() {return Data()[7];} T& v8() {return Data()[8];} T& v9() {return Data()[9];} T& v10() {return Data()[10];} T& v11() {return Data()[11];} T& v12() {return Data()[12];} T& v13() {return Data()[13];} T& v14() {return Data()[14];} T& v15() {return Data()[15];} }; typedef Matrix<4, 4,zint8> Matrix4x4i8; typedef Matrix<4, 4,zuint8> Matrix4x4ui8; typedef Matrix<4, 4,zint16> Matrix4x4i16; typedef Matrix<4, 4,zuint16> Matrix4x4ui16; typedef Matrix<4, 4,zint32> Matrix4x4i32; typedef Matrix<4, 4,zuint32> Matrix4x4ui32; typedef Matrix<4, 4,zint64> Matrix4x4i64; typedef Matrix<4, 4,zuint64> Matrix4x4ui64; typedef Matrix<4, 4,zfloat32> Matrix4x4f32; typedef Matrix<4, 4,zfloat64> Matrix4x4f64; typedef Matrix<4, 4,zuint> Matrix4x4ui; typedef Matrix<4, 4,int> Matrix4x4i; typedef Matrix<4, 4,float> Matrix4x4f; typedef Matrix<4, 4,double> Matrix4x4d; }
zzz-engine
zzzEngine/zCore/zCore/Math/Matrix4x4.hpp
C++
gpl3
5,451
#pragma once #include "../common.hpp" #include "Vector.hpp" #undef min #undef max namespace zzz{ template <typename T> class Vector<2, T> : public VectorBase<2, T> { protected: using VectorBase<2, T>::v; public: //constructor Vector(void){} Vector(const Vector<2, T>& a):VectorBase<2, T>(a){} Vector(const T &a, const T &b){v[0]=a; v[1]=b;} Vector(const VectorBase<2, T>& a):VectorBase<2, T>(a){} explicit Vector(const T &a):VectorBase<2, T>(a){} explicit Vector(const VectorBase<1, T> &a, const T &b):VectorBase<2, T>(a, b){} explicit Vector(const VectorBase<3, T> &a):VectorBase<2, T>(a){} template<typename T1> explicit Vector(const T1 *p):VectorBase<2, T>(p){} template<typename T1> explicit Vector(const Vector<2,T1>& a):VectorBase<2, T>(a){} template<typename T1> explicit Vector(const VectorBase<2,T1>& a):VectorBase<2, T>(a){} //assign inline const Vector<2, T> &operator=(const Vector<2, T>& a){VectorBase<2, T>::operator =(a); return *this;} inline void Set(const T &a, const T &b){v[0]=a; v[1]=b;} using VectorBase<2, T>::operator=; // alias inline T& x(){return v[0];} inline T& y(){return v[1];} inline const T& x() const {return v[0];} inline const T& y() const {return v[1];} }; typedef Vector<2,zint8> Vector2i8; typedef Vector<2,zuint8> Vector2ui8; typedef Vector<2,zint8> Vector2i16; typedef Vector<2,zuint8> Vector2ui16; typedef Vector<2,zint8> Vector2i32; typedef Vector<2,zuint8> Vector2ui32; typedef Vector<2,zint8> Vector2i64; typedef Vector<2,zuint8> Vector2ui64; typedef Vector<2,zfloat32> Vector2f32; typedef Vector<2,zfloat64> Vector2f64; typedef Vector<2,zuint> Vector2ui; typedef Vector<2,int> Vector2i; typedef Vector<2,float> Vector2f; typedef Vector<2,double> Vector2d; template<typename T> inline T Cross(const VectorBase<2, T> &a, const VectorBase<2, T> &b) { return a[0]*b[1]-a[1]*b[0]; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Vector2.hpp
C++
gpl3
1,939
#pragma once #include "Vector3.hpp" #include "Array.hpp" namespace zzz { template <typename T> struct Array<3, T> : public ArrayBase<3, T> { using ArrayBase<3, T>::v; using ArrayBase<3, T>::subsizes; public: //constructor Array(void){} Array(const zuint x, const zuint y, const zuint z):ArrayBase<3, T>(Vector3ui(x, y, z)){} explicit Array(const VectorBase<3,zuint> &size):ArrayBase<3, T>(size){} Array(const T *data, const zuint x, const zuint y, const zuint z):ArrayBase<3, T>(data, Vector3ui(x, y, z)){} Array(const T *data, const VectorBase<3, zuint> &size):ArrayBase<3, T>(data, size){} Array(const Array<3, T>& a):ArrayBase<3, T>(a) {} Array(const ArrayBase<3, T>& a):ArrayBase<3, T>(a) {} //assign inline const Array<3, T> &operator=(const Array<3, T>& a){ArrayBase<3, T>::operator =(a); return *this;} using ArrayBase<3, T>::operator=; //reference using ArrayBase<3, T>::operator(); using ArrayBase<3, T>::At; const T& At(const zuint x, const zuint y, const zuint z) const{ ZRCHECK_LT(x, Size(0)); ZRCHECK_LT(y, Size(1)); ZRCHECK_LT(z, Size(2)); return At(ToIndex(x, y, z)); } T& At(const zuint x, const zuint y, const zuint z) { ZRCHECK_LT(x, Size(0)); ZRCHECK_LT(y, Size(1)); ZRCHECK_LT(z, Size(2)); return At(ToIndex(x, y, z)); } const T& operator()(const zuint x, const zuint y, const zuint z) const{return At(x, y, z);} T& operator()(const zuint x, const zuint y, const zuint z) {return At(x, y, z);} T Interpolate(const double x, const double y, const double c) const {return ArrayBase<3, T>::Interpolate(Vector3d(x, y, z));} using ArrayBase<3, T>::Interpolate; zuint ToIndex(const zuint x, const zuint y, const zuint z) const {return x*subsizes[0] + y*subsizes[1] + z*subsizes[2];} using ArrayBase<3, T>::ToIndex; bool CheckIndex(const zuint x, const zuint y, const zuint z) const {return ArrayBase<3, T>::CheckIndex(Vector3ui(x, y, z));} using ArrayBase<3, T>::CheckIndex; void SetSize(const zuint x, const zuint y, const zuint z) {ArrayBase<3, T>::SetSize(Vector3ui(x, y, z));} using ArrayBase<3, T>::SetSize; void Fill(const zuint x, const zuint y, const zuint z, const T &a) { SetSize(x, y, z); Fill(a); } using ArrayBase<3, T>::Fill; }; typedef Array<3,zint8> Array3i8; typedef Array<3,zuint8> Array3ui8; typedef Array<3,zint16> Array3i16; typedef Array<3,zuint8> Array3ui16; typedef Array<3,zint32> Array3i32; typedef Array<3,zuint32> Array3ui32; typedef Array<3,zint64> Array3i64; typedef Array<3,zuint64> Array3ui64; typedef Array<3,zfloat32> Array3f32; typedef Array<3,zfloat64> Array3f64; typedef Array<3,char> Array3c; typedef Array<3,zuchar> Array3uc; typedef Array<3,short> Array3s; typedef Array<3,zushort> Array3us; typedef Array<3,int> Array3i; typedef Array<3,zuint> Array3ui; typedef Array<3,float> Array3f; typedef Array<3,double> Array3d; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/Array3.hpp
C++
gpl3
2,992
#pragma once #include "../Utility/Log.hpp" #include "Vector2.hpp" #include "Vector.hpp" #include "../common.hpp" namespace zzz{ template <unsigned int ROW, unsigned int COL, typename T> class MatrixBase { public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef zuint size_type; typedef size_type difference_type; protected: Vector<ROW,Vector<COL, T> > V; public: //STL support // iterator support iterator begin() { return (T*)&V; } const_iterator begin() const { return Data(); } iterator end() { return Data()+ROW*COL; } const_iterator end() const { return Data()+ROW*COL; } // reverse iterator support typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end());} reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const {return const_reverse_iterator(begin());} // at() with range check const T& at(const size_type pos) const { ZRCHECK_LT(pos, ROW*COL); return Data()[pos]; } T& at(const size_type pos) { ZRCHECK_LT(pos, ROW*COL); return Data()[pos]; } // front() and back() reference front() { return V[0][0]; } const_reference front() const { return V[0][0];} reference back() { return V[ROW][COL]; } const_reference back() const { return V[ROW][COL]; } // size is constant static size_type size() { return ROW*COL; } static bool empty() { return false; } static size_type max_size() { return ROW*COL; } enum { static_size=ROW*COL }; // swap (note: linear complexity) void swap (MatrixBase<ROW,COL, T>& y) { std::swap_ranges(begin(),end(), y.begin());} //subscript const T& operator[](const size_type pos) const {return at(pos);} T& operator[](const size_type pos) {return at(pos);} const T& At(const size_type x, const size_type y) const { ZRCHECK_LT(x, ROW); ZRCHECK_LT(y, COL); return V[x][y]; } T& At(const size_type x, const size_type y) { ZRCHECK_LT(x, ROW); ZRCHECK_LT(y, COL); return V[x][y]; } const T& At(const Vector<2,size_type> &pos) const {return At(pos[0],pos[1]);} T& At(const Vector<2,size_type> &pos) {return At(pos[0],pos[1]);} const T& operator()(const size_type x, const size_type y) const {return At(x, y);} T& operator()(const size_type x, const size_type y) {return At(x, y);} const T& operator()(const Vector<2,size_type> &pos) const {return At(pos[0],pos[1]);} T& operator()(const Vector<2,size_type> &pos) {return At(pos[0],pos[1]);} const Vector<COL, T>& Row(const size_type row) const{ ZRCHECK_LT(row, ROW); return V[row]; } Vector<COL, T>& Row(const size_type row) { ZRCHECK_LT(row, ROW); return V[row]; } //copy const MatrixBase<ROW,COL, T> &operator=(const T &a){for (size_type i=0; i<ROW*COL; i++) Data()[i]=a; return *this;} const MatrixBase<ROW,COL, T> &operator=(const MatrixBase<ROW,COL, T> &a){IOObject<T>::CopyData(Data(), a.Data(),ROW*COL); return *this;} template<typename T1> const MatrixBase<ROW,COL, T> &operator=(const MatrixBase<ROW,COL,T1> &a){for (zuint i=0; i<ROW*COL; i++) Data()[i]=a[i]; return *this;} //raw data access inline T* Data(){return reinterpret_cast<T*>(&V);} inline const T* Data() const {return reinterpret_cast<const T*>(&V);} //rawcopy void RawCopy(const MatrixBase<ROW,COL, T> &other){memcpy(Data(),other.Data(),sizeof(T)*ROW*COL);} void RawCopy(const T *data){memcpy(Data(),data,sizeof(T)*ROW*COL);} void Zero(zuchar x=0) {memset(Data(), x, sizeof(T)*ROW*COL);} static MatrixBase<ROW,COL, T> GetZero(int x=0) {MatrixBase<ROW,COL, T> mat; mat.Zero(x); return mat;} void Fill(const T &a){for (size_type i=0; i<ROW*COL; i++) Data()[i]=a;} static MatrixBase<ROW,COL, T> GetZero(const T x) {MatrixBase<ROW,COL, T> mat; mat.Fill(x); return mat;} ////////////////////////////////////////////////////////////////////////// // index size_type ToIndex(const Vector<2,size_type> &pos) const {return pos[0]*COL+pos[1];} Vector<2,size_type> ToIndex(size_type idx) const { Vector<2,size_type> pos; pos[0]=idx/COL;pos[1]=idx-pos[0]*COL; return pos; } bool CheckIndex(const Vector<2,size_type> &pos) const {return (pos[0]<ROW && pos[1]<COL);} bool CheckIndex(const size_type &pos) const {return pos<ROW*COL;} //Min and Max inline T Max() { T maxv=Data()[0]; for (unsigned int i=1; i<ROW*COL; i++) if (maxv<Data()[i]) maxv=Data()[i]; return maxv; } inline int MaxPos() { T maxv=Data()[0]; int pos=0; for (unsigned int i=1; i<ROW*COL; i++) if (maxv<Data()[i]) {maxv=Data()[i];pos=i;} return pos; } inline T Min() { T minv=Data()[0]; for (unsigned int i=1; i<ROW*COL; i++) if (minv>Data()[i]) minv=Data()[i]; return minv; } inline int MinPos() { T minv=Data()[0]; int pos=0; for (unsigned int i=1; i<ROW*COL; i++) if (minv>Data()[i]) {minv=Data()[i];pos=i;} return pos; } inline T AbsMax() { T maxv=Data()[0]; for (unsigned int i=1; i<ROW*COL; i++) if (maxv<abs(Data()[i])) maxv=Data()[i]; return maxv; } inline int AbsMaxPos() { T maxv=Data()[0]; int pos=0; for (unsigned int i=1; i<ROW*COL; i++) if (maxv<abs(Data()[i])) {maxv=Data()[i];pos=i;} return pos; } inline T AbsMin() { T minv=Data()[0]; for (unsigned int i=1; i<ROW*COL; i++) if (minv>abs(Data()[i])) minv=Data()[i]; return minv; } inline int AbsMinPos() { T minv=Data()[0]; int pos=0; for (unsigned int i=1; i<ROW*COL; i++) if (minv>abs(Data()[i])) {minv=Data()[i];pos=i;} return pos; } // array math inline T Dot(const MatrixBase<ROW,COL, T> &a) const {T ret=0;for (unsigned int i=0; i<ROW*COL; i++) ret+=Data()[i]*a.Data()[i]; return ret;} inline T Sum() const{T ret=0;for (unsigned int i=0; i<ROW*COL; i++) ret+=Data()[i];return ret;} inline void Negative() {for (size_type i=0; i<ROW*COL; i++) Data()[i]=-Data()[i];} inline T Len() const {return (T)sqrt((double)LenSqr());} inline T LenSqr() const {return Dot(*this);} inline T Normalize() {T norm=Len(); *this/=norm; return norm;} inline MatrixBase<ROW,COL, T> Normalized() const {return *this/Len();} inline T DistTo(const MatrixBase<ROW,COL, T> &a) const {return (T)sqrt((double)DistToSqr(a));} inline T DistToSqr(const MatrixBase<ROW,COL, T> &a) const {MatrixBase<ROW,COL, T> diff(*this-a); return diff.Dot(diff);} // comparisons bool operator== (const MatrixBase<ROW,COL, T>& y) const {return std::equal(begin(), end(), y.begin());} bool operator< (const MatrixBase<ROW,COL, T>& y) const {return std::lexicographical_compare(begin(),end(), y.begin(), y.end());} bool operator!= (const MatrixBase<ROW,COL, T>& y) const {return !(*this==y);} bool operator> (const MatrixBase<ROW,COL, T>& y) const {return y<*this;} bool operator<= (const MatrixBase<ROW,COL, T>& y) const {return !(y<*this);} bool operator>= (const MatrixBase<ROW,COL, T>& y) const {return !(*this<y);} inline bool operator==(const T &c) const { for (int i=0; i<ROW*COL; i++) if (Data()[i]!=c) return false; return true; } inline bool operator!=(const T &c) const {return !(*this==c);} //IO friend inline ostream& operator<<(ostream& os,const MatrixBase<ROW,COL, T> &me) { for (int i=0; i<ROW; i++) { for (int j=0; j<COL; j++) os<<me.V[i][j]<<' '; if (i!=ROW-1) os<<'\n'; } return os; } friend inline istream& operator>>(istream& is,MatrixBase<ROW,COL, T> &me) { for (int i=0; i<ROW*COL; i++) is>>me.Data()[i]; return is; } void SaveToFileA(ostream &fo) { for (int i=0; i<ROW*COL; i++) fo<<Data()[i]<<' '; } void LoadFromFileA(istream &fi) { for (int i=0; i<ROW*COL; i++) fi>>Data()[i]; } //positive and negative inline const MatrixBase<ROW,COL, T> operator+() const {return *this;} inline const MatrixBase<ROW,COL, T> operator-() const { MatrixBase<ROW,COL, T> ret; for (int i=0; i<ROW*COL; i++) ret.Data()[i]=-Data()[i]; return ret; } //addition inline MatrixBase<ROW,COL, T> operator+(const MatrixBase<ROW,COL, T> &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret[i]=Data()[i]+a.Data()[i]; return ret; } inline MatrixBase<ROW,COL, T> operator+(const T &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret[i]=Data()[i]+a; return ret; } inline void operator+=(const MatrixBase<ROW,COL, T> &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]+=a[i]; } inline void operator+=(const T &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]+=a; } //subtraction inline MatrixBase<ROW,COL, T> operator-(const MatrixBase<ROW,COL, T> &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]-a.Data()[i]; return ret; } inline MatrixBase<ROW,COL, T> operator-(const T &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]-a; return ret; } inline void operator-=(const MatrixBase<ROW,COL, T> &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]-=a.Data()[i]; } inline void operator-=(const T &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]-=a; } //matrix multiplication template<unsigned int COL2> inline MatrixBase<ROW,COL2, T> operator*(const MatrixBase<COL,COL2, T> &a) const { MatrixBase<ROW,COL2, T> ret; ret.Zero(); for (int i=0; i<ROW; i++) for (int j=0; j<COL2; j++) { for (int k=0; k<COL; k++) ret.At(i, j)+=At(i, k)*a.At(k, j); } return ret; } //multiply inline MatrixBase<ROW,COL, T> ScaleMultiply(const MatrixBase<ROW,COL, T> &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]*a.Data()[i]; return ret; } inline MatrixBase<ROW,COL, T> operator*(const T &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]*a; return ret; } inline void operator*=(const MatrixBase<ROW,COL, T> &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]*=a.Data()[i]; } inline void operator*=(const T &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]*=a; } //division inline MatrixBase<ROW,COL, T> operator/(const MatrixBase<ROW,COL, T> &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]/a.Data()[i]; return ret; } inline MatrixBase<ROW,COL, T> operator/(const T &a) const { MatrixBase<ROW,COL, T> ret; for (unsigned int i=0; i<ROW*COL; i++) ret.Data()[i]=Data()[i]/a; return ret; } inline void operator/=(const MatrixBase<ROW,COL, T> &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]/=a.Data()[i]; } inline void operator/=(const T &a) { for (unsigned int i=0; i<ROW*COL; i++) Data()[i]/=a; } // matrix math inline void Diagonal(const T x) { ZCHECK_EQ(ROW, COL); Zero(); for (int i=0; i<ROW; i++) At(i, i)=x; } inline void Diagonal(const Vector<ROW, T> &x) { ZCHECK_EQ(ROW, COL); Zero(); for (int i=0; i<ROW; i++) At(i, i)=x[i]; } inline static MatrixBase<ROW, COL, T> GetDiagonal(const T x) { MatrixBase<ROW, COL, T> mat; mat.Diagonal(x); return mat; } inline static MatrixBase<ROW, COL, T> GetDiagonal(const Vector<ROW, T> &x) { MatrixBase<ROW, COL, T> mat; mat.Diagonal(x); return mat; } inline void Identical() { Diagonal(1); } inline static MatrixBase<ROW, COL, T> GetIdentical() { MatrixBase<ROW, COL, T> mat; mat.Identical(); return mat; } inline void Transpose() { ZCHECK_EQ(ROW, COL); T t; for (int i=0; i<ROW; i++) for (int j=i; j<ROW; j++) if (i==j) continue; else { t=At(i, j); At(i, j)=At(j, i); At(j, i)=t; } } inline MatrixBase<COL,ROW, T> Transposed() const { MatrixBase<COL,ROW, T> ret; for (int i=0; i<ROW; i++) for (int j=0; j<COL; j++) ret.At(j, i)=At(i, j); return ret; } T Determinant() const { ZCHECK_EQ(ROW, COL); MatrixBase<ROW,COL, T> a = *this; int indx[ROW]; T d; a.luDecomposition(&indx[0], d); for(int i=0; i<ROW; i++) d *= a.V[i][i]; return d; } bool Invert() { ZCHECK_EQ(ROW, COL); MatrixBase<ROW,COL, T> a = *this; int indx[ROW]; Vector<ROW, T> col; T d; int i, j; if (!a.luDecomposition(&indx[0], d)) //Decompose the matrix just once. return false; //singular matrix for(j=0; j<ROW; j++) { //Find inverse by columns. for(i=0; i<ROW; i++) col[i]=0.0; col[j]=1.0; a.luBackSubstitution(&indx[0],col); for(i=0; i<ROW; i++) V[i][j]=col[i]; } return true; } MatrixBase<ROW,COL, T> Inverted() const { ZCHECK_EQ(ROW, COL); MatrixBase<ROW,COL, T> a = *this; MatrixBase<ROW,COL, T> y; int indx[ROW]; Vector<ROW, T> col; T d; int i, j; a.luDecomposition(&indx[0], d); //Decompose the matrix just once. for(j=0; j<ROW; j++) { //Find inverse by columns. for(i=0; i<ROW; i++) col[i]=0.0; col[j]=1.0; a.luBackSubstitution(&indx[0],col); for(i=0; i<ROW; i++) y.V[i][j]=col[i]; } return y; } bool IsSymmetric() const { if (ROW!=COL) return false; for (int i=0; i<ROW; ++i) { for (int j=0; j<ROW; ++j) { if (V[i][j] != V[j][i]) return false; } } return true; } T Trace() const { ZCHECK_EQ(ROW, COL); T t=0; for (int i=0; i<ROW; i++) t+=V[i][i]; return t; } // // Code borrowed from the Numerical Recipes in C++ // void luBackSubstitution(int indx[ROW], Vector<ROW, T>& b) { ZCHECK_EQ(ROW, COL); int i,ii=0,ip, j; T sum; for (i=0; i<ROW; i++) { ip=indx[i]; sum=b[ip]; b[ip]=b[i]; if (ii != 0) for (j=ii-1; j<i; j++) sum -= V[i][j]*b[j]; else if (sum != 0.0) ii=i+1; b[i]=sum; } for (i=ROW-1; i>=0; i--) { sum=b[i]; for (j=i+1; j<ROW; j++) sum -= V[i][j]*b[j]; b[i]=sum/V[i][i]; } } bool luDecomposition(int indx[ROW], T& d) { ZCHECK_EQ(ROW, COL); int i,imax, j, k; T big,dum,sum,temp; Vector<ROW, T> vv; d=1.0; for (i=0; i<ROW; i++) { big=0.0; for (j=0; j<ROW; j++) if ((temp=fabs(V[i][j])) > big) big=temp; if (big == 0.0) return false; //singular matrix vv[i]=1.0/big; } for (j=0; j<ROW; j++) { for (i=0; i<j; i++) { sum=V[i][j]; for (k=0; k<i; k++) sum -= V[i][k]*V[k][j]; V[i][j]=sum; } big=0.0; for (i=j; i<ROW; i++) { sum=V[i][j]; for (k=0; k<j; k++) sum -= V[i][k]*V[k][j]; V[i][j]=sum; if ((dum=vv[i]*fabs(sum)) >= big) { big=dum; imax=i; } } if (j != imax) { for (k=0; k<ROW; k++) { dum=V[imax][k]; V[imax][k]=V[j][k]; V[j][k]=dum; } d = -d; vv[imax]=vv[j]; } indx[j]=imax; if (V[j][j] == 0.0) V[j][j]=EPS; //_TINY; if (j != ROW-1) { dum=1.0/(V[j][j]); for (i=j+1; i<ROW; i++) V[i][j] *= dum; } } return true; } //c'tor and d'tor MatrixBase(){} explicit MatrixBase(const T &a){for (size_type i=0; i<ROW*COL; i++) Data()[i]=a;} template<typename T1> explicit MatrixBase(const T1 *data){for (size_type i=0; i<ROW*COL; i++) Data()[i]=data[i];} template<typename T1> explicit MatrixBase(const MatrixBase<ROW,COL,T1> &data){for (zuint i=0; i<ROW*COL; i++) Data()[i]=T(data[i]);} MatrixBase(const MatrixBase<ROW,COL, T> &other){*this=other;} }; //multiply vector template <zuint ROW,zuint COL,typename T> inline const Vector<ROW, T> operator*(const MatrixBase<ROW,COL, T> &mat, const VectorBase<COL, T> &vec) { Vector<ROW, T> ret; for (Vector<ROW, T>::size_type i=0; i<ROW; i++) { ret[i]=T(0); for (Vector<ROW, T>::size_type j=0; j<COL; j++) ret[i]+=mat(i, j)*vec[j]; } return ret; } template <zuint ROW,zuint COL,typename T> inline const Vector<COL, T> operator*(const VectorBase<ROW, T> &vec,const MatrixBase<ROW,COL, T> &mat) { Vector<COL, T> ret; for (Vector<COL, T>::size_type i=0; i<COL; i++) { ret[i]=T(0); for (Vector<COL, T>::size_type j=0; j<ROW; j++) ret[i]+=vec[j]*mat(j, i); } return ret; } //scale at front template <zuint ROW,zuint COL,typename T> inline const MatrixBase<ROW,COL, T> operator+(const T &v,const MatrixBase<ROW,COL, T> &mat) { return mat+v; } template <zuint ROW,zuint COL,typename T> inline const MatrixBase<ROW,COL, T> operator-(const T &v,const MatrixBase<ROW,COL, T> &mat) { return -mat+v; } template <zuint ROW,zuint COL,typename T> inline const MatrixBase<ROW,COL, T> operator*(const T &v,const MatrixBase<ROW,COL, T> &mat) { return mat*v; } template <zuint ROW,zuint COL,typename T> inline const MatrixBase<ROW,COL, T> operator/(const T &v,const MatrixBase<ROW,COL, T> &mat) { MatrixBase<ROW,COL, T> res; for (size_type i=0; i<ROW*COL; i++) res[i]=v/mat[i]; return res; } //write all these stuff just to avoid direct memory copy when construct and copy template<zuint ROW, zuint COL, typename T> class Matrix : public MatrixBase<ROW,COL, T> { public: //constructor Matrix(void){} Matrix(const Matrix<ROW,COL, T>& a):MatrixBase<ROW,COL, T>(a) {} Matrix(const MatrixBase<ROW,COL, T>& a):MatrixBase<ROW,COL, T>(a) {} template<typename T1> explicit Matrix(const MatrixBase<ROW,COL,T1>& a):MatrixBase<ROW,COL, T>(a) {} template<typename T1> explicit Matrix(const T1 *p):MatrixBase<ROW,COL, T>(p) {} explicit Matrix(const T &a):MatrixBase<ROW,COL, T>(a){} template<typename T1> explicit Matrix(const Matrix<ROW,COL,T1>& a):MatrixBase<ROW,COL, T>(a) {} //assign inline const Matrix<ROW,COL, T> &operator=(const Matrix<ROW,COL, T>& a){MatrixBase<ROW,COL, T>::operator =(a); return *this;} template <typename T1> inline const Matrix<ROW,COL, T> &operator=(const Matrix<ROW,COL,T1>& a){MatrixBase<ROW,COL, T>::operator =(a); return *this;} }; // IOObject template<unsigned int ROW, unsigned int COL, typename T> class IOObject<MatrixBase<ROW,COL, T> > { public: static void WriteFileB(FILE *fp, const MatrixBase<ROW,COL, T>* src, zsize size) { IOObject<T>::WriteFileB(fp, src->Data(), size * ROW * COL); } static void ReadFileB(FILE *fp, MatrixBase<ROW,COL, T>* dst, zsize size) { IOObject<T>::ReadFileB(fp, dst->Data(), size * ROW * COL); } static void WriteFileR(RecordFile &fp, const zint32 label, const MatrixBase<ROW,COL, T>* src, zsize size) { IOObject<T>::WriteFileR(fp, label, src->Data(), size * ROW * COL); } static void ReadFileR(RecordFile &fp, const zint32 label, MatrixBase<ROW,COL, T>* dst, zsize size) { IOObject<T>::ReadFileR(fp, label, dst->Data(), size * ROW * COL); } static void WriteFileR(RecordFile &fp, const zint32 label, const MatrixBase<ROW,COL, T>& src) { IOObject<MatrixBase<ROW,COL, T> >::WriteFileR(fp, label, &src, 1); } static void ReadFileR(RecordFile &fp, const zint32 label, MatrixBase<ROW,COL, T>& dst) { IOObject<MatrixBase<ROW,COL, T> >::ReadFileR(fp, label, &dst, 1); } static void CopyData(MatrixBase<ROW,COL, T>* dst, const MatrixBase<ROW,COL, T>* src, zsize size) { IOObject<T>::CopyData(static_cast<T*>(dst->Data()), static_cast<const T*>(src->Data()), size*ROW*COL); } }; template<unsigned int ROW, unsigned int COL, typename T> class IOObject<Matrix<ROW,COL, T> > { public: static void WriteFileB(FILE *fp, const Matrix<ROW,COL, T>* src, zsize size) { IOObject<MatrixBase<ROW,COL, T> >::WriteFileB(fp, src, size); } static void ReadFileB(FILE *fp, Matrix<ROW,COL, T>* dst, zsize size) { IOObject<MatrixBase<ROW,COL, T> >::ReadFileB(fp, dst, size); } static void WriteFileR(RecordFile &fp, const zint32 label, const Matrix<ROW,COL, T>* src, zsize size) { IOObject<MatrixBase<ROW,COL, T> >::WriteFileR(fp, label, src, size); } static void ReadFileR(RecordFile &fp, const zint32 label, Matrix<ROW,COL, T>* dst, zsize size) { IOObject<MatrixBase<ROW,COL, T> >::ReadFileR(fp, label, src, size); } static void WriteFileR(RecordFile &fp, const zint32 label, const Matrix<ROW,COL, T>& src) { IOObject<MatrixBase<ROW,COL, T> >::WriteFileR(fp, label, src); } static void ReadFileR(RecordFile &fp, const zint32 label, Matrix<ROW,COL, T>& dst) { IOObject<MatrixBase<ROW,COL, T> >::ReadFileR(fp, label, dst); } static void CopyData(Matrix<ROW,COL, T>* dst, const Matrix<ROW,COL, T>* src, zsize size) { IOObject<MatrixBase<ROW,COL, T> >::CopyData(dst, src, size); } }; template <zuint ROW, zuint COL, typename T> inline Matrix<ROW, COL, T> Abs(const MatrixBase<ROW, COL, T> &x) { Matrix<ROW, COL, N> ret; for (size_type i=0; i<ret.size(); i++) ret[i]=Abs(x[i]); return ret; } }
zzz-engine
zzzEngine/zCore/zCore/Math/Matrix.hpp
C++
gpl3
22,218
#pragma once #include "Vector1.hpp" #include "Array.hpp" namespace zzz { template <typename T> struct Array<1, T> : public ArrayBase<1, T> { protected: using ArrayBase<1, T>::v; public: //constructor Array(void){} explicit Array(const zuint size):ArrayBase<1, T>(Vector1ui(size)){} explicit Array(const VectorBase<1,size_type> &size):ArrayBase<1, T>(size){} Array(const T *data, const zuint size):ArrayBase<1, T>(data, Vector1ui(size)){} Array(const T *data, const VectorBase<1,size_type> &size):ArrayBase<1, T>(data, size){} Array(const Array<1, T>& a):ArrayBase<1, T>(a) {} Array(const ArrayBase<1, T>& a):ArrayBase<1, T>(a) {} //assign inline const Array<1, T> &operator=(const Array<1, T>& a){ArrayBase<1, T>::operator =(a); return *this;} using ArrayBase<1, T>::operator=; T Interpolate(const double coord) const {return ArrayBase<1, T>::Interpolate(Vector1d(coord));} using ArrayBase<1, T>::Interpolate; size_type ToIndex(const size_type pos) const {return pos;} using ArrayBase<1, T>::ToIndex; bool CheckIndex(const size_type pos) const {return ArrayBase<1, T>::CheckIndex(Vector1ui(pos));} using ArrayBase<1, T>::CheckIndex; void SetSize(const size_type size) {ArrayBase<1, T>::SetSize(Vector1ui(size));} using ArrayBase<1, T>::SetSize; void Fill(const size_type size, const T &a) { SetSize(size); Fill(a); } using ArrayBase<1, T>::Fill; void Set(const T* data, const size_type size) {ArrayBase<1, T>::Set(data, Vector1ui(size));} void Set(const vector<T>& data) {Set(data.data(), data.size());} using ArrayBase<1, T>::Set; }; typedef Array<1,zint8> Array1i8; typedef Array<1,zuint8> Array1ui8; typedef Array<1,zint16> Array1i16; typedef Array<1,zuint8> Array1ui16; typedef Array<1,zint32> Array1i32; typedef Array<1,zuint32> Array1ui32; typedef Array<1,zint64> Array1i64; typedef Array<1,zuint64> Array1ui64; typedef Array<1,zfloat32> Array1f32; typedef Array<1,zfloat64> Array1f64; typedef Array<1,char> Array1c; typedef Array<1,zuchar> Array1uc; typedef Array<1,short> Array1s; typedef Array<1,zushort> Array1us; typedef Array<1,int> Array1i; typedef Array<1,zuint> Array1ui; typedef Array<1,float> Array1f; typedef Array<1,double> Array1d; }; // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/Array1.hpp
C++
gpl3
2,312
#pragma once namespace zzz{ template<typename T> class Complex : public Vector<2, T> { using Vector<2, T>::v; public: Complex():Vector<2, T>(0, 0){} explicit Complex(const VectorBase<2, T> &v):Vector<2, T>(v){} explicit Complex(T r, T i):Vector<2, T>(r, i){} using Vector<2, T>::operator[]; T& Real(){return v[0];} const T& Real() const {return v[0];} T& Imag(){return v[1];} const T& Imag() const {return v[1];} using Vector<2, T>::operator+; using Vector<2, T>::operator-; void operator*=(const VectorBase<2, T>& other) { T r=Real()*other.Real()-Imag()*other.Imag(); T i=Real()*other.Imag()+Imag()*other.Real(); v[0]=r; v[1]=i; } const Complex<T>& operator*(const VectorBase<2, T>& other) { return Complex(Real()*other.Real()-Imag()*other.Imag(),Real()*other.Imag()+Imag()*other.Real()); } }; typedef Complex<double> Complexd; typedef Complex<float> Complexf; }
zzz-engine
zzzEngine/zCore/zCore/Math/Complex.hpp
C++
gpl3
955
#pragma once #include "../zCoreConfig.hpp" #include "Utility/Log.hpp" namespace zzz{ const double EPS=1e-7; const double EPSILON5=1e-5; const double EPSILON6=1e-6; const double EPSILON7=1e-7; const double EPSILON8=1e-8; const double EPSILON9=1e-9; const double EPSILON=EPSILON7; const double SMALL_EPSILON=EPSILON8; const double BIG_EPSILON=EPSILON6; const double TINY_EPSILON=EPSILON9; const double HUGE_EPSILON=EPSILON5; const double DOUBLE_EPSILON=numeric_limits<double>::epsilon(); const double FLOAT_EPSILON=numeric_limits<float>::epsilon(); const double C_EPS=1e-7; const double C_E=2.7182818284590452354; const double C_LOG2E=1.4426950408889634074; const double C_LOG10E=0.43429448190325182765; const double C_LN2=0.69314718055994530942; const double C_LN10=2.30258509299404568402; const double PI=3.1415926535897932384626433832795028841971693993751058209749445; const double C_PI=PI; const double C_2PI=PI*2.0; const double C_PI_2=C_PI/2.0; const double C_PI_4=C_PI/4.0; const double C_1_PI=1.0/C_PI; const double C_2_PI=2.0/C_PI; const double C_1_2PI=0.5/C_PI; const double C_PI_180=C_PI/180.0; const double C_180_PI=180.0/C_PI; const double C_D2R=C_PI_180; const double C_R2D=C_180_PI; const double C_SQRTPI=sqrt(C_PI); const double C_2_SQRTPI=2.0/C_SQRTPI; const double C_SQRT2=1.4142135623730950488016887242097; const double C_SQRT3=1.73205080756888; const double C_SQRT2_2=C_SQRT2/2.0; const double C_LNPI=1.14472988584940017414; const double C_EULER=0.57721566490153286061; #undef min #undef max #define DEFINE_MIN_MAX_VALUE(name, T) \ const T MIN_##name = numeric_limits<T>::min(); \ const T MAX_##name = numeric_limits<T>::max(); DEFINE_MIN_MAX_VALUE(CHAR, char); DEFINE_MIN_MAX_VALUE(SHORT, short); DEFINE_MIN_MAX_VALUE(USHORT, zushort); DEFINE_MIN_MAX_VALUE(INT, int); DEFINE_MIN_MAX_VALUE(UINT, zuint); DEFINE_MIN_MAX_VALUE(LONG, long); DEFINE_MIN_MAX_VALUE(FLOAT, float); DEFINE_MIN_MAX_VALUE(DOUBLE, double); DEFINE_MIN_MAX_VALUE(INT8, zint8); DEFINE_MIN_MAX_VALUE(UINT8, zuint8); DEFINE_MIN_MAX_VALUE(INT16, zint16); DEFINE_MIN_MAX_VALUE(UINT16, zuint16); DEFINE_MIN_MAX_VALUE(INT32, zint32); DEFINE_MIN_MAX_VALUE(UINT32, zuint32); DEFINE_MIN_MAX_VALUE(INT64, zint64); DEFINE_MIN_MAX_VALUE(UINT64, zuint64); DEFINE_MIN_MAX_VALUE(FLOAT16, zfloat32); DEFINE_MIN_MAX_VALUE(FLOAT32, zfloat64); #undef DEFINE_MIN_MAX_VALUE ////////////////////////////////////////////////////////////////////////// template <typename T> inline const T& Min(const T &a, const T &b) { if (a<b) return a; return b; } template <typename T> inline const T& Max(const T &a, const T &b) { if (a>b) return a; return b; } template <typename T> inline T& Min(T& a, T& b) { if (a<b) return a; return b; } template <typename T> inline T& Max(T& a, T& b) { if (a>b) return a; return b; } //ATTENTION TO PARAMETER ORDER: A X B template <typename T> inline const T& Clamp(const T &a, const T &x, const T &b) { if (x<a) return a; return (x>b)?b:x; } //ATTENTION TO PARAMETER ORDER: A X B template <typename T> inline bool Within(const T &a, const T &x, const T &b) { return (x>=a && x<=b); } template <typename T> inline T Sign(const T &x) { return (x>=T(0))?T(1):T(-1); } //ATTENTION TO PARAMETER ORDER: T0 T1 A template <typename T> inline T Lerp(const T &t0, const T &t1, const float a) { return t0*(1.0f-a)+t1*a; } template <typename T> inline T Lerp(const T &t0, const T &t1, const double a) { return t0*(1.0f-a)+t1*a; } template <typename T> inline int Round(const T &x) { if (x>=0) return (int)(x+T(0.5)); else return (int)(x-T(0.5)); } inline double Round(const double value, const int precision) { if (precision>=0) { const int p = Clamp(precision, -15,15); // Lookup table for pwr(10.0, i) const static double pwr[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14 }; // Table of inverses const static double invpwr[] = { 1e0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14 }; double val = value; if (value<0.0) val = ceil(val*pwr[p]-0.5); if (value>0.0) val = floor(val*pwr[p]+0.5); return val*invpwr[p]; } return value; } inline float Round(const float value, const int precision) { return (float) Round(double(value),precision); } template<int M,int N> struct StaticPow { enum{RESULT = M * StaticPow<M, N-1>::RESULT}; }; template<int M> struct StaticPow<M, 0> { enum{RESULT = 1}; }; inline int FlowToPower2(int w) { return 1 << (int)floor((log((double)w)/log(2.0f)) + 0.5f); } inline int Log2(int x) { int i = 0; while(x = x >> 1) ++i; return i; } inline float Log2(float x) { return static_cast<float>(::log(x)/C_LN2); } inline double Log2(double x) { return ::log(x)/C_LN2; } inline int Factorial(int n) { int ret=1; for (int i=2; i<=n; i++) ret*=i; return ret; } template<typename T1, typename T2> double Pow(const T1 x, const T2 y) { return pow(static_cast<double>(x),static_cast<double>(y)); } template<typename T> T Pow(const T &x, const int y) { T ret=1; for (int i=0; i<y; i++) ret*=x; return ret; } inline double WrapPI(double theta) { theta += PI; theta -= floor(theta * C_1_2PI) * C_2PI; ; theta -= PI; return theta; } inline double SafeACos(double x) { // Check limit conditions if (x <= -1.0f) return PI; if (x >= 1.0f) return 0.0; // Value is in the domain - use standard C function return acos(x); } template <typename T> inline T Sqr(const T &x) { return x*x; } template <typename T> inline T Cube(const T &x) { return x*x*x; } template <typename T> inline T Quart(const T &x) { return x*x*x*x; } template <typename T> inline T Quint(const T &x) { return x*x*x*x*x; } template <typename T> inline void Swap(T &x1, T &x2) { T tmp=x1; x1=x2; x2=tmp; } template <typename T> inline T Abs(const T x) { return std::abs(x); } template <typename T> inline void KeepAbs(T& x) { x=std::abs(x); } template <typename T> inline T Sqrt(const T x) { return static_cast<T>(std::sqrt(static_cast<double>(x))); } // Standard min and max functions #ifdef ZZZ_COMPILER_MSVC #undef min #undef max template <typename T> inline const T &min(const T &a, const T &b) { return (a < b) ? a : b; } template <typename T> inline const T &max(const T &a, const T &b) { return (a > b) ? a : b; } #endif inline zuchar FromHex(const char ch) { if (ch>='0' && ch<='9') return ch-'0'; if (ch>='a' && ch<='f') return ch-'a'+10; if (ch>='A' && ch<='F') return ch-'A'+10; ZCHECK((ch>='0' && ch<='9') || (ch>='a' && ch<='f') || (ch>='A' && ch<='F')); return 0; } inline int FromHex(const string &a) { int ret=0; for (size_t i=0; i<a.size(); i++) ret=(ret<<4)+FromHex(a[i]); return ret; } inline char ToHex(const zuchar val) { const char table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // Check sanity of input ZCHECK(/*val>=0 && */val<=15); return table[val&15]; } inline char ToHex(const char val) { return ToHex(zuchar(val)); } // Determine highest n, given 2^n <= x template<typename T> T LowerPowerOf2(const T x) { zuint tmp = 1<<(sizeof(T)*8-1); while ((tmp&x)==0 && tmp) tmp>>=1; return tmp; } //Determine lowest n, given 2^n >= x template<typename T>T UpperPowerOf2(const T x) { zuint tmp = 1<<(sizeof(T)*8-1); while ((tmp&x)==0 && tmp) tmp>>=1; return x==tmp ? tmp : tmp<<1; } //Test if two numbers have same sign template <typename T>bool IsSameSign(const T &a, const T &b) { return (a<0 && b<0) || (a>0 && b>0); } // Convert an integer to a float between 0 and 1 // IEEE 4 byte real // // 31 30 23 22 0 // |-------------------------------------. // |s | 8 bits |msb 23 bit mantissa lsb| // `-------------------------------------' // | | `---------------- mantissa // | `-------------------------------- biased exponent (7fh) // `------------------------------------- sign bit inline void Fraction(float &frac,const zuint bits) { ZCHECK(sizeof(float)==4 && sizeof(float)==sizeof(zuint)); union { float f; zuint i; } tmp; // Place fractional bits in mantissa tmp.i = (0x7f<<23) | (bits>>9); // Adjust to [0, 1) range frac = tmp.f-1.0f; } //Convert an integer to a double between 0 and 1 // IEEE 8 byte real // 63 62 52 51 0 // |-------------------------------------------------. // |s |11 bits| msb 52 bit mantissa lsb| // `-------------------------------------------------' // | | `---------------- mantissa // | `-------------------------------- biased exponent (3FFh) // `------------------------------------- sign bit inline void Fraction(double &frac,const zuint bits) { ZCHECK(sizeof(double)==8 && sizeof(double)==sizeof(zuint)*2); union { double f; zuint i[2]; } tmp; // Place fractional bits in mantissa tmp.i[1] = (0x3FF<<20) | (bits>>12); tmp.i[0] = (bits<<12); // Adjust to [0, 1) range frac = tmp.f-1.0; } //magic square root in Quake III // 1.0/sqrt(number) inline float MagicInvSqrt(float number) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * (long *) &y; // evil floating point bit level hacking i = 0x5f3759df - (i >> 1); // what the fuck? y = * (float *) &i; y = y * (threehalfs - (x2 * y * y)); // 1st iteration // y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed return y; } // Another implementation, better. inline float MagicInvSqrt2(float x) { float xhalf = 0.5f*x; int i = *(int*)&x; // get bits for floating value i = 0x5f375a86- (i>>1); // gives initial guess y0 x = *(float*)&i; // convert bits back to float x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy return x; } inline float MagicSqrt(float number) { long i; float x, y; const float f = 1.5F; x = number * 0.5F; y = number; i = * (long *) &y; i = 0x5f3759df - (i >> 1); y = * (float *) &i; y = y * (f - (x * y * y)); y = y * (f - (x * y * y)); return number * y; } inline bool IsInf(double x) { return x==numeric_limits<double>::infinity() || x==-numeric_limits<double>::infinity(); } inline bool IsInf(float x) { return x==numeric_limits<float>::infinity() || x==-numeric_limits<float>::infinity(); } template< typename T > inline bool IsNaN(const T &r) { return r != r; } inline bool IsBad(double x) { return IsInf(x) || IsNaN(x); } inline bool IsBad(float x) { return IsInf(x) || IsNaN(x); } #ifdef ZOPTIMIZE_ABS inline int Sign(const int x) { return 1|(x>>(sizeof(int)*8-1)); } inline short Sign(const short x) { return 1|(x>>(sizeof(short)*8-1)); } inline char Sign(const char x) { return 1|(x>>(sizeof(char)*8-1)); } #endif #ifdef ZOPTIMIZE_SIGN inline int Abs(const int x) { int mask=x>>(sizeof(int)*8-1); return (x + mask) ^ mask; } inline short Abs(const short x) { short mask=x>>(sizeof(short)*8-1); return (x + mask) ^ mask; } inline char Abs(const char x) { char mask=x>>(sizeof(char)*8-1); return (x + mask) ^ mask; } #endif #ifdef ZOPTIMIZE_MINMAX //UNSAFE MAX MIN //WILL FAIL IF THE MINUS OVERFLOW inline int Max(const int x, const int y) { return x-((x-y) & ((x-y)>>(sizeof(int)*8-1))); } inline int Min(const int x, const int y) { return y+((x-y) & ((x-y)>>(sizeof(int)*8-1))); } inline short Max(const short x, const short y) { return x-((x-y) & ((x-y)>>(sizeof(short)*8-1))); } inline short Min(const short x, const short y) { return y+((x-y) & ((x-y)>>(sizeof(short)*8-1))); } inline char Max(const char x, const char y) { return x-((x-y) & ((x-y)>>(sizeof(char)*8-1))); } inline char Min(const char x, const char y) { return y+((x-y) & ((x-y)>>(sizeof(char)*8-1))); } #endif } // namespace zzz
zzz-engine
zzzEngine/zCore/zCore/Math/Math.hpp
C++
gpl3
12,370
#pragma once #include "Function.hpp" namespace zzz{ //f(x)=1/(sigma^2*2pi)*exp(-((x-meanx)^2+(y-meany)^2)/(2*sigma^2)) class Gaussian2DFunction : public Function<Vector2d,double> { public: Gaussian2DFunction() :Function<Vector2d,double>(Vector2d(MAX_DOUBLE,MAX_DOUBLE), Vector2d(-MAX_DOUBLE, -MAX_DOUBLE)), mean_(0),sigma_(0){} Gaussian2DFunction(Vector2d mean, double sigma) :Function<Vector2d,double>(Vector2d(MAX_DOUBLE,MAX_DOUBLE), Vector2d(-MAX_DOUBLE, -MAX_DOUBLE)) { SetParameter(mean,sigma); } double Evaluate(const Vector2d& x) { return A_*exp(-(x-mean_).LenSqr()/(2*sigma_)); } void SetParameter(Vector2d mean, double sigma) { mean_=mean; sigma_=sigma; s2_=sigma_*sigma_; A_=1.0/(sigma*sigma*2*PI); } bool CheckInput(const Vector2d& x) { return true; } private: Vector2d mean_; double sigma_; double s2_; //sigma^2 double A_; //amplifier }; }
zzz-engine
zzzEngine/zCore/zCore/Function/Gaussian2DFunction.hpp
C++
gpl3
1,002
#pragma once #include "Function.hpp" namespace zzz{ //f(x)=1/(sigma*sqrt(2pi))*exp(-(x-mean)^2/(2*sigma^2)) class GaussianFunction : public Function<double,double> { public: GaussianFunction() :Function<double, double>(MAX_DOUBLE, -MAX_DOUBLE), mean_(0),sigma_(0){} GaussianFunction(double mean, double sigma) :Function<double, double>(MAX_DOUBLE, -MAX_DOUBLE) { SetParameter(mean,sigma); } double Evaluate(const double& x) { return A_*exp(-(x-mean_)*(x-mean_)/(2*sigma_)); } void SetParameter(double mean, double sigma) { mean_=mean; sigma_=sigma; s2_=sigma_*sigma_; A_=1.0/(sigma*sqrt(2*PI)); } bool CheckInput(const double& x) { return true; } private: double mean_; double sigma_; double s2_; //sigma^2 double A_; //amplifier }; }
zzz-engine
zzzEngine/zCore/zCore/Function/GaussianFunction.hpp
C++
gpl3
864
#pragma once namespace zzz{ template<typename TI, typename TO> //TI for input type, TO for output type class Function { public: typedef TI InputType; typedef TO OutputType; const TI InputMin; const TI InputMax; Function(const TI imin, const TI imax) :InputMin(imin),InputMax(imax) {} virtual bool CheckInput(const TI& x) //this function could be overload to check the input parameter { return Within<TI>(InputMin, x,InputMax); } TO operator()(const TI &x) { ZCHECK(CheckInput(x))<<"input out of range"; return Evaluate(x); } virtual TO Evaluate(const TI& x)=0; //every derived class need to implement this function }; }
zzz-engine
zzzEngine/zCore/zCore/Function/Function.hpp
C++
gpl3
698
#pragma once #include "EnvDetect.hpp" //#define ZZZ_LIB_MINIMAL #ifdef ZZZ_LIB_MINIMAL #include "LibraryConfig.hpp.minimal" #else #ifdef ZZZ_OS_WIN32 #include "LibraryConfig.hpp.win32" #endif #ifdef ZZZ_OS_WIN64 #include "LibraryConfig.hpp.win64" #endif #endif // ZZZ_LIB_MINIMAL
zzz-engine
zzzEngine/zCore/zCore/LibraryConfig.hpp
C++
gpl3
303
#pragma once // Compiler #ifdef _MSC_VER #define ZZZ_COMPILER_MSVC #endif #ifdef __MINGW32__ #define ZZZ_COMPILER_MINGW #endif #ifdef __CYGWIN__ #define ZZZ_COMPILER_CYGWIN #endif #ifdef __GNUC__ #define ZZZ_COMPILER_GCC #endif #ifdef __INTEL_COMPILER #define ZZZ_COMPILER_INTEL #endif // OS #ifdef _WIN32 #define ZZZ_OS_WIN #endif #if defined(_WIN64) #define ZZZ_OS_WIN64 #else #define ZZZ_OS_WIN32 #endif #ifdef __linux #define ZZZ_OS_LINUX #endif #ifdef Macintosh #define ZZZ_OS_MACOS #endif #if defined(ZZZ_COMPILER_GCC) || defined(ZZZ_COMPILER_INTEL) #ifdef __APPLE__ #define ZZZ_OS_MACOS #endif #endif // Architecture // By GNU C #ifdef __i386__ #define ZZZ_ARCH_I386 #elif defined(__ia64__) #define ZZZ_ARCH_I64 #endif // By MSVC, Intel #ifdef _M_IX86 #define ZZZ_ARCH_I386 #elif defined(_M_IA64) #define ZZZ_ARCH_I64 #endif // By MinGW32 #ifdef _X86_ #define ZZZ_ARCH_I386 #endif // Debug or Release #ifdef ZZZ_COMPILER_MSVC #ifdef _DEBUG #define ZZZ_DEBUG #else #define ZZZ_RELEASE #endif #endif #ifdef ZZZ_COMPILER_GCC #ifdef NDEBUG #define ZZZ_RELEASE #else #define ZZZ_DEBUG #endif #endif
zzz-engine
zzzEngine/zCore/zCore/EnvDetect.hpp
C++
gpl3
1,116
#pragma once #include <EnvDetect.hpp> #include <LibraryConfig.hpp> #ifdef ZZZ_OS_WIN32 #include "zCoreConfig.hpp.win32" #endif #ifdef ZZZ_OS_WIN64 #include "zCoreConfig.hpp.win64" #endif #ifdef ZZZ_DYNAMIC #pragma warning(disable:4251) // needs to have dll-interface #pragma warning(disable:4275) // non dll-interface class 'zzz::Uncopyable' used as base for dll-interface class 'zzz::RapidXML' #ifdef ZCORE_SOURCE #define ZCORE_FUNC __declspec(dllexport) #define ZCORE_CLASS __declspec(dllexport) #else #define ZCORE_FUNC __declspec(dllimport) #define ZCORE_CLASS __declspec(dllimport) #endif #else #define ZCORE_FUNC #define ZCORE_CLASS #endif
zzz-engine
zzzEngine/zCore/zCore/zCoreConfig.hpp
C++
gpl3
709
#pragma once #include "zCoreConfig.hpp" //math part should be the last #include "Math/Array1.hpp" #include "Math/Array2.hpp" #include "Math/Array3.hpp" #include "Math/Array.hpp" #include "Math/Average.hpp" #include "Math/Complex.hpp" #include "Math/DMatrix.hpp" #include "Math/DVector.hpp" #include "Math/IterExitCond.hpp" #include "Math/Math.hpp" #include "Math/Matrix2x2.hpp" #include "Math/Matrix3x3.hpp" #include "Math/Matrix4x4.hpp" #include "Math/Matrix.hpp" #include "Math/MinMax.hpp" #include "Math/Poly3.hpp" #include "Math/Random.hpp" #include "Math/Statistics.hpp" #include "Math/SymEigenSystem.hpp" #include "Math/Vector1.hpp" #include "Math/Vector2.hpp" #include "Math/Vector3.hpp" #include "Math/Vector4.hpp" #include "Math/Vector.hpp" #include "Math/NonlinearSystem/MinpackSolver.hpp" #include "Math/NonlinearSystem/NonlinearSystem.hpp" #include "Utility/Any.hpp" #include "Utility/AnyHolder.hpp" #include "Utility/AnyStack.hpp" #include "Utility/BraceFile.hpp" #include "Utility/CacheSet.hpp" #include "Utility/CheckPoint.hpp" #include "Utility/CmdParser.hpp" #include "Utility/FileTools.hpp" #include "Utility/Global.hpp" #include "Utility/IOFile.hpp" #include "Utility/IOInterface.hpp" #include "Utility/IOObject.hpp" #include "Utility/IndexSet.hpp" #include "Utility/Log.hpp" #include "Utility/ObjectCacheSet.hpp" #include "Utility/STLVector.hpp" #include "Utility/Singleton.hpp" #include "Utility/StaticTools.hpp" #include "Utility/StringGenerator.hpp" #include "Utility/StringPrintf.hpp" #include "Utility/StringTools.hpp" #include "Utility/TextProgress.hpp" #include "Utility/TextProgressBar.hpp" #include "Utility/Thread.hpp" #include "Utility/Timer.hpp" #include "Utility/Tools.hpp" #include "Utility/Uncopyable.hpp" #include "Algorithm/FibonacciHeap.hpp" #include "Algorithm/GramSchmidt.hpp" #include "Algorithm/SumTable.hpp" #include "Xml/RapidXML.hpp" #include "Xml/RapidXMLNode.hpp" #include "Xml/XML.hpp" #include "Xml/XMLNode.hpp" #include "common.hpp"
zzz-engine
zzzEngine/zCore/zCore/zCore.hpp
C++
gpl3
2,061
#define ZCORE_SOURCE #include "XML.hpp" #ifdef ZZZ_LIB_TINYXML #define TIXML_USE_STL #include <tinyxml/tinyxml.h> #include <tinyxml/tinystr.h> namespace zzz{ bool XML::LoadFile(const string &filename) { filename_=filename; bool res=doc_->LoadFile(filename); if (doc_->Error()) { printf("Error in %s: %s\n", doc_->Value(), doc_->ErrorDesc()); return false; } return res; } bool XML::SaveFile(const string &filename) { if (doc_->Error()) { printf("Error in %s: %s\n", doc_->Value(), doc_->ErrorDesc()); return false; } filename_=filename; return doc_->SaveFile(filename); } //children zuint XML::NodeNumber() const { zuint x=0; for (const TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) x++; return x; } XMLNode XML::GetNode(zuint i) { zuint x=-1; for (TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) x++; if (x==i) return XMLNode(pChild->ToElement(),this); } ZLOGF<<"Node "<<i<<" does not exist!"; return XMLNode(NULL,this); } XMLNode XML::GetNode(const string &name) { for (TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && name == pChild->Value()) return XMLNode(pChild->ToElement(),this); } ZLOGF<<"Node "<<name<<" does not exist!"; return XMLNode(NULL,this); } bool XML::HasNode(const string &name) { for (TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && name == pChild->Value()==0) return true; } return false; } XMLNode XML::AppendNode(const string &name) { if (NodeNumber()==0) doc_->LinkEndChild(new TiXmlDeclaration("1.0", "", "")); TiXmlElement *element=new TiXmlElement(name); doc_->LinkEndChild(element); return XMLNode(element,this); } bool XML::RemoveNode(const string &name) { for (TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (name == pChild->Value()) { doc_->RemoveChild(pChild); return true; } } return false; } bool XML::RemoveNode(zuint i) { zuint x=0; for (TiXmlNode *pChild=doc_->FirstChild();pChild!=0;pChild=pChild->NextSibling(), x++) { if (x==i) { doc_->RemoveChild(pChild); return true; } } return false; } const string& XML::GetFilename() const { return filename_; } XML::~XML() { delete doc_; } XML::XML() { doc_=new TiXmlDocument; } } #endif // ZZZ_LIB_TINYXML
zzz-engine
zzzEngine/zCore/zCore/Xml/XML.cpp
C++
gpl3
2,766
#define ZCORE_SOURCE #include "RapidXMLNode.hpp" #include "RapidXML.hpp" using namespace rapidxml; namespace zzz{ RapidXMLNode::RapidXMLNode(const RapidXMLNode &node):node_(node.node_),root_(node.root_) {} RapidXMLNode::RapidXMLNode(xml_node<> *node, const RapidXML *root):node_(node),root_(root) {} //self bool RapidXMLNode::IsValid() const { return node_!=NULL; } bool RapidXMLNode::SetName(const string &name) { node_->name(node_->document()->allocate_string(name.c_str())); return true; } //parent RapidXMLNode RapidXMLNode::GetParent() { ZRCHECK_NOT_NULL(node_->parent()); return RapidXMLNode(node_->parent(), root_); } //children zuint RapidXMLNode::NodeNumber() const { zuint x=0; for (const xml_node<> *pChild=node_->first_node(); pChild!=0; pChild=pChild->next_sibling()) if (pChild->type()==rapidxml::node_element) x++; return x; } RapidXMLNode RapidXMLNode::GetNode(zuint i) { zuint x=-1; for (xml_node<> *pChild=node_->first_node();pChild!=0;pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element) x++; if (x==i) return RapidXMLNode(pChild,root_); } ZLOGF<<"Node "<<i<<" does not exist!"; return RapidXMLNode(NULL,root_); } RapidXMLNode RapidXMLNode::GetNode(const string &name) { return GetFirstNode(name); } bool RapidXMLNode::HasNode(const string &name) { for (xml_node<> *pChild=node_->first_node(); pChild!=0; pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element && name == pChild->name()) return true; } return false; } RapidXMLNode RapidXMLNode::AppendNode(const string &name) { xml_node<> *element=node_->document()->allocate_node(rapidxml::node_element, node_->document()->allocate_string(name.c_str())); node_->append_node(element); return RapidXMLNode(element,root_); } bool RapidXMLNode::RemoveNode(const string &name) { xml_node<> *n=node_->first_node(name.c_str()); if (n==NULL) return false; node_->remove_node(n); return true; } bool RapidXMLNode::RemoveNode(zuint i) { zuint x=-1; for (xml_node<> *pChild=node_->first_node();pChild!=0;pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element) x++; if (x==i) { node_->remove_node(pChild); return true; } } return false; } //iteration RapidXMLNode RapidXMLNode::GetFirstNode(const string &name) { if (name.empty()) return RapidXMLNode(node_->first_node(NULL),root_); return RapidXMLNode(node_->first_node(name.c_str()),root_); } RapidXMLNode RapidXMLNode::GetNextSibling(const string &name) { if (name.empty()) return RapidXMLNode(node_->next_sibling(NULL),root_); return RapidXMLNode(node_->next_sibling(name.c_str()),root_); } void RapidXMLNode::GotoNextSibling(const string &name) { if (name.empty()) node_ = node_->next_sibling(NULL); node_=node_->next_sibling(name.c_str()); } void RapidXMLNode::operator++() { GotoNextSibling(); } //attribute bool RapidXMLNode::HasAttribute(const string &name) const { return node_->first_attribute(name.c_str())!=NULL; } const char *RapidXMLNode::GetAttribute(const string &name, const char *missing) const { const xml_attribute<>* res=node_->first_attribute(name.c_str()); return ((res!=NULL)?res->value():missing); } bool RapidXMLNode::SetAttribute(const string &name, const char *value) const { xml_attribute<>* res=node_->first_attribute(name.c_str()); if (res==NULL) node_->append_attribute( node_->document()->allocate_attribute( node_->document()->allocate_string(name.c_str()), node_->document()->allocate_string(value))); else res->value(node_->document()->allocate_string(value)); return true; } bool RapidXMLNode::SetAttribute(const string &name, const string &value) const { SetAttribute(name,value.c_str()); return true; } bool RapidXMLNode::RemoveAttribute(const string &name) { xml_attribute<>* res=node_->first_attribute(name.c_str()); if (res) { node_->remove_attribute(res); return true; } return false; } //Text const char *RapidXMLNode::GetText() const { return node_->value(); } bool RapidXMLNode::SetText(const char *v) const { node_->value(node_->document()->allocate_string(v)); return true; } bool RapidXMLNode::SetText(const string &v) const { return SetText(v.c_str()); } bool RapidXMLNode::RemoveText() { node_->value(NULL); return true; } const char *RapidXMLNode::GetName() const { return node_->name(); } }
zzz-engine
zzzEngine/zCore/zCore/Xml/RapidXMLNode.cpp
C++
gpl3
4,641
#pragma once #include <zCoreConfig.hpp> #include "../common.hpp" #include "../Utility/StringTools.hpp" #include <3rdparty/rapidxml/rapidxml.hpp> namespace zzz{ class RapidXML; class ZCORE_CLASS RapidXMLNode { public: RapidXMLNode(const RapidXMLNode &node); explicit RapidXMLNode(rapidxml::xml_node<> *node, const RapidXML *root); bool IsValid() const; bool SetName(const string &name); RapidXMLNode GetParent(); zuint NodeNumber() const; RapidXMLNode GetNode(zuint i); RapidXMLNode GetNode(const string &name); RapidXMLNode AppendNode(const string &name); bool HasNode(const string &name); bool RemoveNode(const string &name); bool RemoveNode(zuint i); //iteration RapidXMLNode GetFirstNode(const string &name=string()); RapidXMLNode GetNextSibling(const string &name=string()); void GotoNextSibling(const string &name=string()); void operator++(); bool HasAttribute(const string &name) const; const char *GetAttribute(const string &name, const char *missing=NULL) const; template<typename T>bool GetAttribute(const string &name, T& value) const { const string &str=GetAttribute(name); value = FromString<T>(str); return true; } bool SetAttribute(const string &name, const char *value) const; bool SetAttribute(const string &name, const string &value) const; template<typename T> bool SetAttribute(const string &name, const T &value) const { return SetAttribute(name,ToString(value)); } bool RemoveAttribute(const string &name); const char *GetText() const; bool SetText(const char *text) const; bool SetText(const string &text) const; bool RemoveText(); const char *GetName() const; const RapidXML *root_; protected: rapidxml::xml_node<>* node_; }; //input text inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const char *text) { node.SetText(text); return node; } inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const string &text) { node.SetText(text.c_str()); return node; } //input attribute template<typename T> inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const T &text) { node.SetText(ToString(text).c_str()); return node; } inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const char *, const char *> &attrib) { node.SetAttribute(attrib.first, attrib.second); return node; } inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const char *, const string> &attrib) { node.SetAttribute(attrib.first, attrib.second.c_str()); return node; } template<typename T> inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const char *, T> &attrib) { node.SetAttribute(attrib.first, ToString(attrib.second).c_str()); return node; } inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const string, const char *> &attrib) { node.SetAttribute(attrib.first, attrib.second); return node; } inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const string, const string> &attrib) { node.SetAttribute(attrib.first, attrib.second.c_str()); return node; } template<typename T> inline const RapidXMLNode& operator<<(const RapidXMLNode &node, const pair<const string, T> &attrib) { node.SetAttribute(attrib.first, ToString(attrib.second).c_str()); return node; } }
zzz-engine
zzzEngine/zCore/zCore/Xml/RapidXMLNode.hpp
C++
gpl3
3,481
#define ZCORE_SOURCE #include "RapidXML.hpp" #include <Utility\Log.hpp> #include <Utility\FileTools.hpp> #include <3rdparty/rapidxml/rapidxml_print.hpp> using namespace rapidxml; namespace zzz{ bool RapidXML::LoadFile(const string &filename) { filename_=filename; string text; ZCHECK(ReadFileToString(filename, text))<<"Cannot open file "<<filename; filetext_.SetSize(Vector<1,zuint>(text.size())+1); memcpy(filetext_.Data(), text.data(), text.size()); filetext_.back()=0; doc_.parse<0>(filetext_.Data()); return true; } bool RapidXML::SaveFile(const string &filename) { filename_=filename; ofstream fo(filename); ZCHECK(fo.good())<<"Cannot open file "<<filename; fo<<doc_; return true; } //children zuint RapidXML::NodeNumber() const { zuint x=0; for (const xml_node<> *pChild=doc_.first_node();pChild!=0;pChild=pChild->next_sibling()) if (pChild->type()==rapidxml::node_element) x++; return x; } RapidXMLNode RapidXML::GetNode(zuint i) { zuint x=-1; for (xml_node<> *pChild=doc_.first_node();pChild!=0;pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element) x++; if (x==i) return RapidXMLNode(pChild, this); } ZLOGF<<"Node "<<i<<" does not exist!"; return RapidXMLNode(NULL,this); } RapidXMLNode RapidXML::GetNode(const string &name) { for (xml_node<> *pChild=doc_.first_node();pChild!=0;pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element && name == pChild->name()) return RapidXMLNode(pChild,this); } ZLOGF<<"Node "<<name<<" does not exist!"; return RapidXMLNode(NULL,this); } bool RapidXML::HasNode(const string &name) { for (xml_node<> *pChild=doc_.first_node();pChild!=0;pChild=pChild->next_sibling()) { if (pChild->type()==rapidxml::node_element && name == pChild->name()) return true; } return false; } RapidXMLNode RapidXML::AppendNode(const string &name) { if (NodeNumber()==0) { xml_node<> *dec = doc_.allocate_node(node_declaration, NULL); dec->append_attribute(doc_.allocate_attribute( doc_.allocate_string("version"), doc_.allocate_string("1.0"))); doc_.append_node(dec); } xml_node<> *element=doc_.allocate_node(node_element,doc_.allocate_string(name.c_str())); doc_.append_node(element); return RapidXMLNode(element,this); } bool RapidXML::RemoveNode(const string &name) { xml_node<> *n = doc_.first_node(name.c_str()); if (n==NULL) return false; doc_.remove_node(n); return true; } bool RapidXML::RemoveNode(zuint i) { zuint x=0; for (xml_node<> *pChild=doc_.first_node();pChild!=0;pChild=pChild->next_sibling(), x++) { if (x==i) { doc_.remove_node(pChild); return true; } } return false; } const string& RapidXML::GetFilename() const { return filename_; } }
zzz-engine
zzzEngine/zCore/zCore/Xml/RapidXML.cpp
C++
gpl3
2,900
#pragma once #include "../Utility/IOInterface.hpp" #include "../Utility/Uncopyable.hpp" #include "XMLNode.hpp" #ifdef ZZZ_LIB_TINYXML class TiXmlDocument; namespace zzz{ class XML : public IOData, public Uncopyable { public: XML(); ~XML(); bool LoadFile(const string &); bool SaveFile(const string &); zuint NodeNumber() const; XMLNode GetNode(zuint i); XMLNode GetNode(const string &name); bool HasNode(const string &name); XMLNode AppendNode(const string &name); bool RemoveNode(const string &name); bool RemoveNode(zuint i); const string& GetFilename() const; private: TiXmlDocument *doc_; string filename_; }; } #endif // ZZZ_LIB_TINYXML
zzz-engine
zzzEngine/zCore/zCore/Xml/XML.hpp
C++
gpl3
704
#define ZCORE_SOURCE #include "XMLNode.hpp" #ifdef ZZZ_LIB_TINYXML #define TIXML_USE_STL #include <tinyxml/tinyxml.h> #include <tinyxml/tinystr.h> namespace zzz{ XMLNode::XMLNode(const XMLNode &node):node_(node.node_),root_(node.root_) {} XMLNode::XMLNode(TiXmlElement *node, const XML *root):node_(node),root_(root) {} //self bool XMLNode::IsValid() const { return node_!=NULL; } bool XMLNode::SetName(const string &name) { node_->SetValue(name); return true; } //parent XMLNode XMLNode::GetParent() { ZCHECK(node_->Parent()!=NULL); return XMLNode(node_->Parent()->ToElement(),root_); } //children zuint XMLNode::NodeNumber() const { zuint x=0; for (const TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) x++; return x; } XMLNode XMLNode::GetNode(zuint i) { zuint x=-1; for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) x++; if (x==i) return XMLNode(pChild->ToElement(),root_); } ZLOGF<<"Node "<<i<<" does not exist!"; return XMLNode(NULL,root_); } XMLNode XMLNode::GetNode(const string &name) { return GetFirstNode(name.c_str()); } bool XMLNode::HasNode(const string &name) { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && name == pChild->Value()) return true; } return false; } XMLNode XMLNode::AppendNode(const string &name) { TiXmlElement *element=new TiXmlElement(name); node_->LinkEndChild(element); return XMLNode(element,root_); } bool XMLNode::RemoveNode(const string &name) { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (name == pChild->Value()) { node_->RemoveChild(pChild); return true; } } return false; } bool XMLNode::RemoveNode(zuint i) { zuint x=-1; for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) x++; if (x==i) { node_->RemoveChild(pChild); return true; } } return false; } //iteration XMLNode XMLNode::GetFirstNode(const char *name) { if (name==NULL) { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) return XMLNode(pChild->ToElement(),root_); } } else { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && strcmp(name, pChild->Value())==0) return XMLNode(pChild->ToElement(),root_); } } return XMLNode(NULL,root_); } XMLNode XMLNode::GetNextSibling(const char *name) { if (name==NULL) { for (TiXmlNode *pChild=node_->NextSibling();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) return XMLNode(pChild->ToElement(),root_); } } else { for (TiXmlNode *pChild=node_->NextSibling();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && strcmp(name,pChild->Value())==0) return XMLNode(pChild->ToElement(),root_); } } return XMLNode(NULL,root_); } void XMLNode::GotoNextSibling(const char *name) { if (name==NULL) { for (TiXmlNode *pChild=node_->NextSibling();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT) { node_=pChild->ToElement(); return; } } } else { for (TiXmlNode *pChild=node_->NextSibling();pChild!=0;pChild=pChild->NextSibling()) { if (pChild->Type()==TiXmlNode::TINYXML_ELEMENT && strcmp(name, pChild->Value())==0) { node_=pChild->ToElement(); return; } } } node_=NULL; return; } void XMLNode::operator++() { GotoNextSibling(); } //attribute bool XMLNode::HasAttribute(const string &name) const { return node_->Attribute(name)!=NULL; } const char *XMLNode::GetAttribute(const string &name, const char *missing) const { const string *res=node_->Attribute(name); return ((res!=NULL)?res->c_str():missing); } bool XMLNode::SetAttribute(const string &name, const char *value) const { node_->SetAttribute(name,value); return true; } bool XMLNode::SetAttribute(const string &name, const string &value) const { node_->SetAttribute(name,value.c_str()); return true; } bool XMLNode::RemoveAttribute(const string &name) { node_->RemoveAttribute(name); return true; } //Text const char *XMLNode::GetText() const { return node_->GetText(); } bool XMLNode::SetText(const string &value) const { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (node_->Type()==TiXmlNode::TINYXML_TEXT) { pChild->SetValue(value); return true; } } node_->LinkEndChild(new TiXmlText(value)); return true; } bool XMLNode::RemoveText() { for (TiXmlNode *pChild=node_->FirstChild();pChild!=0;pChild=pChild->NextSibling()) { if (node_->Type()==TiXmlNode::TINYXML_COMMENT) { node_->RemoveChild(pChild); return true; } } return true; } const char *XMLNode::GetName() const { return node_->Value(); } } #endif // ZZZ_LIB_TINYXML
zzz-engine
zzzEngine/zCore/zCore/Xml/XMLNode.cpp
C++
gpl3
5,645
#pragma once #include <LibraryConfig.hpp> #ifdef ZZZ_LIB_TINYXML #include "../common.hpp" #include "../Utility/StringTools.hpp" class TiXmlElement; namespace zzz{ class XML; class XMLNode { public: XMLNode(const XMLNode &node); explicit XMLNode(TiXmlElement *node, const XML *root); bool IsValid() const; bool SetName(const string &name); XMLNode GetParent(); zuint NodeNumber() const; XMLNode GetNode(zuint i); XMLNode GetNode(const string &name); XMLNode AppendNode(const string &name); bool HasNode(const string &name); bool RemoveNode(const string &name); bool RemoveNode(zuint i); //iteration XMLNode GetFirstNode(const char *name=NULL); XMLNode GetNextSibling(const char *name=NULL); void GotoNextSibling(const char *name=NULL); void operator++(); bool HasAttribute(const string &name) const; const char *GetAttribute(const string &name, const char *missing=NULL) const; template<typename T>bool GetAttribute(const string &name, T& value) const { const char *str=GetAttribute(name); if (str==NULL) return false; value=FromString<T>(str); return true; } bool SetAttribute(const string &name, const string &value) const; bool SetAttribute(const string &name, const char *value) const; template<typename T> bool SetAttribute(const string &name, const T &value) const { return SetAttribute(name,ToString(value)); } bool RemoveAttribute(const string &name); const char *GetText() const; bool SetText(const string &text) const; bool RemoveText(); const char *GetName() const; const XML *root_; protected: TiXmlElement* node_; }; //input text inline const XMLNode& operator<<(const XMLNode &node, const char *text) { node.SetText(text); return node; } inline const XMLNode& operator<<(const XMLNode &node, const string &text) { node.SetText(text.c_str()); return node; } //input attribute template<typename T> inline const XMLNode& operator<<(const XMLNode &node, const T &text) { node.SetText(ToString(text).c_str()); return node; } inline const XMLNode& operator<<(const XMLNode &node, const pair<const string &, const char *> &attrib) { node.SetAttribute(attrib.first, attrib.second); return node; } inline const XMLNode& operator<<(const XMLNode &node, const pair<const string &, string> &attrib) { node.SetAttribute(attrib.first, attrib.second.c_str()); return node; } template<typename T> inline const XMLNode& operator<<(const XMLNode &node, const pair<const string &, T> &attrib) { node.SetAttribute(attrib.first, ToString(attrib.second).c_str()); return node; } } #endif // ZZZ_LIB_TINYXML
zzz-engine
zzzEngine/zCore/zCore/Xml/XMLNode.hpp
C++
gpl3
2,730
#pragma once #include "../Utility/IOInterface.hpp" #include "../Utility/Uncopyable.hpp" #include "RapidXMLNode.hpp" #include <Math/Array.hpp> namespace zzz{ class ZCORE_CLASS RapidXML : public IOData, public Uncopyable { public: bool LoadFile(const string &); bool SaveFile(const string &); zuint NodeNumber() const; RapidXMLNode GetNode(zuint i); RapidXMLNode GetNode(const string &name); bool HasNode(const string &name); RapidXMLNode AppendNode(const string &name); bool RemoveNode(const string &name); bool RemoveNode(zuint i); const string& GetFilename() const; private: rapidxml::xml_document<> doc_; string filename_; Array<1,char> filetext_; }; }
zzz-engine
zzzEngine/zCore/zCore/Xml/RapidXML.hpp
C++
gpl3
712
SET(THISLIB zVisualization) FILE(GLOB_RECURSE LibSrc *.cpp) #MESSAGE(STATUS "files ${LibSrc}") IF( "${DEBUG_MODE}" EQUAL "1") SET(THISLIB ${THISLIB}D) ENDIF() IF( "${BIT_MODE}" EQUAL "64" ) SET(THISLIB ${THISLIB}_X64) ENDIF() ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
zzz-engine
zzzEngine/zVisualization/CMakeLists.txt
CMake
gpl3
279
#pragma once #ifndef ZZZ_NO_PRAGMA_LIB #ifdef _DEBUG #ifndef ZZZ_OS_WIN64 #pragma comment(lib,"zVisualizationD.lib") #else #pragma comment(lib,"zVisualizationD_x64.lib") #endif // ZZZ_OS_WIN64 #else #ifndef ZZZ_OS_WIN64 #pragma comment(lib,"zVisualization.lib") #else #pragma comment(lib,"zVisualization_x64.lib") #endif // ZZZ_OS_WIN64 #endif #endif // ZZZ_NO_PRAGMA_LIB #include "Visualizer/TreeVisualizer2D.hpp" #include "Visualizer/SequenceVisualizer2D.hpp" #include "Visualizer/VisualizeNode2D.hpp" #include "Visualizer/VImage2D.hpp" #include "Visualizer/VText2D.hpp"
zzz-engine
zzzEngine/zVisualization/zVisualization/zVisualization.hpp
C++
gpl3
605
#pragma once #include "Visualizer2D.hpp" #include "VisualizeNode2D.hpp" namespace zzz{ class SequenceVisualizer2D:public Visualizer2D { public: SequenceVisualizer2D(Vis2DRenderer *renderer,int num):Visualizer2D(renderer),maxnum_(num),autofocus_(true){} ~SequenceVisualizer2D(void) { for (list<VisualizeNode2D*>::iterator lvi=nodes_.begin();lvi!=nodes_.end();lvi++) delete *lvi; nodes_.clear(); } void AddNode(VisualizeNode2D *node); void Draw(); list<VisualizeNode2D*> nodes_; int maxnum_; bool autofocus_; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/SequenceVisualizer2D.hpp
C++
gpl3
567
#pragma once #include "Visualizer2D.hpp" #include "VisualizeNode2D.hpp" namespace zzz{ class CombineVisualizer2D:public Visualizer2D { public: CombineVisualizer2D(Vis2DRenderer *renderer):Visualizer2D(renderer),autocenter_(true){} ~CombineVisualizer2D(void) { for (size_t i=0; i<visualizers_.size(); i++) delete visualizers_[i]; visualizers_.clear(); } void AddVisualizer(Visualizer2D *node) { node->SetRenderer(renderer_); visualizers_.push_back(node); } void Draw() { for (size_t i=0; i<visualizers_.size(); i++) visualizers_[i]->Draw(); } vector<Visualizer2D*> visualizers_; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/CombineVisualizer2D.hpp
C++
gpl3
664
#include <common.hpp> #include "TreeVisualizer2D.hpp" namespace zzz{ void zzz::TreeVisualizer2D::Rerange(int gap) { if (direction==0) { int treeheight=1; int centerx=tree_.GetHead()->v->posx_+(tree_.GetHead()->v->bbox_.Min(0)+tree_.GetHead()->v->bbox_.Max(0))/2; int lastheight=tree_.GetHead()->v->posy_+tree_.GetHead()->v->bbox_.Max(1); lastheight+=gap; while(true) { vector<TreeNode<VisualizeNode2D*> * > nodes=tree_.GetHead()->GetSameHeightSons(treeheight); if (nodes.empty()) break; int curwidth=(nodes.size()-1)*gap; int maxheight=0; for (size_t i=0; i<nodes.size(); i++) { curwidth+=nodes[i]->v->bbox_.Diff(0); maxheight=Max(maxheight,nodes[i]->v->bbox_.Diff(1)); } curwidth=centerx-curwidth/2; lastheight+=maxheight; for (size_t i=0; i<nodes.size(); i++) { nodes[i]->v->posx_=curwidth-nodes[i]->v->bbox_.Min(0); nodes[i]->v->posy_=lastheight-nodes[i]->v->bbox_.Max(1); curwidth+=nodes[i]->v->bbox_.Diff(0)+gap; } lastheight+=gap; treeheight++; } } if (direction==1) { int treeheight=1; int centery=tree_.GetHead()->v->posy_+(tree_.GetHead()->v->bbox_.Min(1)+tree_.GetHead()->v->bbox_.Max(1))/2; int lastwidth=tree_.GetHead()->v->posy_+tree_.GetHead()->v->bbox_.Max(0); lastwidth+=gap; while(true) { vector<TreeNode<VisualizeNode2D*> * > nodes=tree_.GetHead()->GetSameHeightSons(treeheight); if (nodes.empty()) break; int curheight=(nodes.size()-1)*gap; int maxwidth=0; for (size_t i=0; i<nodes.size(); i++) { curheight+=nodes[i]->v->bbox_.Diff(1); maxwidth=Max(maxwidth,nodes[i]->v->bbox_.Diff(0)); } curheight=centery-curheight/2; lastwidth+=maxwidth; for (size_t i=0; i<nodes.size(); i++) { nodes[i]->v->posy_=curheight-nodes[i]->v->bbox_.Min(1); nodes[i]->v->posx_=lastwidth-nodes[i]->v->bbox_.Max(0); curheight+=nodes[i]->v->bbox_.Diff(1)+gap; } lastwidth+=gap; treeheight++; } } } void zzz::TreeVisualizer2D::Draw() { deque<TreeNode<VisualizeNode2D*> *> q; q.push_back(tree_.GetHead()); while(!q.empty()) { TreeNode<VisualizeNode2D*>* cur=q.front(); cur->v->DrawPixels(renderer_); for (size_t i=0; i<cur->sons.size(); i++) { //TODO: draw line q.push_back(cur->sons[i]); } q.pop_front(); } } }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/TreeVisualizer2D.cpp
C++
gpl3
2,552
#include "VisualizeNode2D.hpp" #include <Renderer/Vis2DRenderer.hpp> #include <Resource/Shader/Shader.hpp> #include <Graphics/ColorDefine.hpp> namespace zzz{ VisualizeNode2D::~VisualizeNode2D() { Clear(); } void VisualizeNode2D::Clear() { for (size_t i=0; i<objs_.size(); i++) delete objs_[i]; objs_.clear(); } void VisualizeNode2D::DrawPixels(Vis2DRenderer *renderer) { CHECK_GL_ERROR(); for (size_t i=0; i<objs_.size(); i++) objs_[i]->DrawPixels(renderer, posx_, posy_); CHECK_GL_ERROR(); if (drawedge_) { Vector3d x1=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Min(1)+posy_); Vector3d y1=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Max(1)+posy_); Vector3d x2=renderer->UnProject(bbox_.Max(0)+posx_,bbox_.Max(1)+posy_); Vector3d y2=renderer->UnProject(bbox_.Max(0)+posx_,bbox_.Min(1)+posy_); Vector3d x3=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Min(1)+posy_); ColorDefine::white.ApplyGL(); ZRM->Get<Shader*>("ColorShader")->Begin(); glBegin(GL_LINES); glVertex3dv(x1.Data()); glVertex3dv(y1.Data()); glVertex3dv(x2.Data()); glVertex3dv(y1.Data()); glVertex3dv(x2.Data()); glVertex3dv(y2.Data()); glVertex3dv(x3.Data()); glVertex3dv(y2.Data()); glEnd(); Shader::End(); } } void VisualizeNode2D::AddObject(VisualizeObj2D* obj) { if (objs_.empty()) bbox_=obj->bbox_; else bbox_+=obj->bbox_; objs_.push_back(obj); } }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/VisualizeNode2D.cpp
C++
gpl3
1,496
#pragma once #include <common.hpp> #include "VisualizeObj2D.hpp" #include <Math\Vector2.hpp> namespace zzz{ class Vis2DRenderer; class VisualizeNode2D { public: VisualizeNode2D():drawedge_(true), bbox_(Vector2i(0)){} virtual ~VisualizeNode2D(); void AddObject(VisualizeObj2D* obj); void DrawPixels(Vis2DRenderer *renderer); void Clear(); vector<VisualizeObj2D*> objs_; double posx_,posy_; AABB<2,int> bbox_; bool drawedge_; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/VisualizeNode2D.hpp
C++
gpl3
467
#pragma once #include <Renderer/Vis2DRenderer.hpp> //use Vis2DRenderer to visualize 2D information namespace zzz{ class Visualizer2D { public: Visualizer2D(Vis2DRenderer *renderer):renderer_(renderer){} virtual void Draw()=0; Vis2DRenderer *renderer_; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/Visualizer2D.hpp
C++
gpl3
277
#include "SequenceVisualizer2D.hpp" namespace zzz{ void SequenceVisualizer2D::AddNode(VisualizeNode2D *node) { if ((int)nodes_.size()>=maxnum_) nodes_.pop_front(); double width=node->bbox_.Diff(0); for (list<VisualizeNode2D*>::iterator lvi=nodes_.begin();lvi!=nodes_.end();lvi++) { VisualizeNode2D *thisnode=*lvi; thisnode->posx_+=width; } node->posx_=0; node->posy_=0; nodes_.push_back(node); } void SequenceVisualizer2D::Draw() { if (autofocus_) { Vector2i size=nodes_.back()->bbox_.Diff(); int x=nodes_.back()->posx_+size[0]/2,y=nodes_.back()->posy_+size[1]/2; renderer_->SetCenter(x,y); CHECK_GL_ERROR(); } for (list<VisualizeNode2D*>::iterator lvi=nodes_.begin();lvi!=nodes_.end();lvi++) { VisualizeNode2D *node=*lvi; node->DrawPixels(renderer_); CHECK_GL_ERROR(); } } }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/SequenceVisualizer2D.cpp
C++
gpl3
874
#pragma once #include "VisualizeNode2D.hpp" #include "Visualizer2D.hpp" #include <Utility/Tree.hpp> namespace zzz{ class TreeVisualizer2D:public Visualizer2D { public: TreeVisualizer2D(Vis2DRenderer *renderer):Visualizer2D(renderer),direction(1) {} void Draw(); void Rerange(int gap=10); Tree<VisualizeNode2D*> tree_; int direction; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/TreeVisualizer2D.hpp
C++
gpl3
364
#pragma once #include <Image/Image.hpp> #include "VisualizeObj2D.hpp" namespace zzz{ template<typename T> class VImage2D : public VisualizeObj2D, public GraphicsHelper { public: VImage2D(const Image<T> &img, int x=0, int y=0):image(img) { bbox_.Min()=Vector2i(x,y); bbox_.Max()=Vector2i(x+image.Cols(), y+image.Rows()); } virtual void DrawPixels(Vis2DRenderer *renderer, double basex, double basey) { int x = basex + bbox_.Min(0); int y = basey + bbox_.Min(1); renderer->SetRasterPosRelative(x, y); DrawImage(image); } Image<T> image; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/VImage2D.hpp
C++
gpl3
599
#pragma once #include "Visualizer2D.hpp" #include "VisualizeNode2D.hpp" //has only one node to show one image namespace zzz{ class SingleVisualizer2D:public Visualizer2D { public: SingleVisualizer2D(Vis2DRenderer *renderer):Visualizer2D(renderer),autocenter_(true),node_(NULL){} ~SingleVisualizer2D(void) { if (node_) delete node_; node_=NULL; } void SetNode(VisualizeNode2D *node) { if (node_) delete node_; node_=node; } void Draw() { if (!node_) return; if (autocenter_) { Vector3d pos=renderer_->UnProject(renderer_->width_,renderer_->height_); node_->posx_=pos[0]-node_->bbox_.topleft[0]; node_->posy_=pos[1]-node_->bbox_.topleft[1]; } node_->DrawPixels(renderer_); } VisualizeNode2D* node_; bool autocenter_; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/SingleVisualizer2D.hpp
C++
gpl3
834
#pragma once #include <Graphics\AABB.hpp> namespace zzz{ class Vis2DRenderer; class VisualizeObj2D { public: AABB<2,int> bbox_; virtual void DrawPixels(Vis2DRenderer *renderer,double basex, double basey)=0; }; }
zzz-engine
zzzEngine/zVisualization/zVisualization/Visualizer/VisualizeObj2D.hpp
C++
gpl3
225