nux-4.0.8+16.04.20160209/0000755000015600001650000000000012656240224014704 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/0000755000015600001650000000000012656240224016267 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/OutputDevice.h0000644000015600001650000001041212656236757021076 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NOUTPUTDEVICE_H #define NOUTPUTDEVICE_H namespace nux { class NSerializer; class LogOutputDevice { public: LogOutputDevice (); virtual ~LogOutputDevice (); BOOL m_terminated; virtual void Serialize (const TCHAR *log_data, const TCHAR *log_prefix, int severity) = 0; virtual void Flush (); virtual void Shutdown (); VARARG_DECL (void/*FuncRet*/, void/*StaticFuncRet*/, {}/*Return*/, LogFunction/*FuncName*/, VARARG_NONE/*Pure*/, const TCHAR*/*FmtType*/, VARARG_EXTRA (int severity) /*ExtraDecl*/, VARARG_EXTRA (severity) /*ExtraParam*/ ); void Enable (); void Disable (); protected: bool _object_destroyed; bool _enabled; }; //! Output to null device. class NullOutput : public LogOutputDevice { NUX_DECLARE_GLOBAL_OBJECT (NullOutput, GlobalSingletonInitializer); public: void Serialize ( const TCHAR * /* V */, const TCHAR * /* LogPrefix */, int /* severity */) {} }; //! Output to log file. class LogFileOutput : public LogOutputDevice { NUX_DECLARE_GLOBAL_OBJECT (LogFileOutput, GlobalSingletonInitializer); //LogFileOutput( const TCHAR* InFilename); public: /*! Closes output device and cleans up. */ void Shutdown(); /*! Flush the write cache so the output to the file isn't truncated. */ void Flush(); /*! Write a stream to the log file. @param log_data Stream characters to write. @param LogPrefix A string to write before the input stream of characters. */ void Serialize (const TCHAR *log_data, const TCHAR *LogPrefix, int severity); private: NSerializer *m_LogSerializer; std::string m_Filename; bool m_Opened; bool m_Closed; /*! Serialize data directly to the log file without any type of conversion or preprocessing. @param log_data String of char to write to the output file. */ void SerializeRaw (const TCHAR *log_data); }; //! Output to microsoft visual console. class VisualOutputConsole : public LogOutputDevice { NUX_DECLARE_GLOBAL_OBJECT (VisualOutputConsole, GlobalSingletonInitializer); public: //! Write data to visual studio output debug console. /*! @param text Text to log. @param log_prefix Prefix for the text. @param severity Importance of the message. */ void Serialize (const TCHAR *text, const TCHAR *log_prefix, int severity); }; //! Standard printf output console. class PrintfOutputConsole : public LogOutputDevice { NUX_DECLARE_GLOBAL_OBJECT (PrintfOutputConsole, GlobalSingletonInitializer); public: //! Write text to the standard printf output debug console. /*! @param text Text to log. @param log_prefix Prefix for the text. @param severity Importance of the message. */ void Serialize (const TCHAR *text, const TCHAR *log_prefix, int severity); }; class LogOutputRedirector : public LogOutputDevice { NUX_DECLARE_GLOBAL_OBJECT (LogOutputRedirector, GlobalSingletonInitializer); public: virtual void AddOutputDevice (LogOutputDevice *OutputDevice); virtual void RemoveOutputDevice (LogOutputDevice *OutputDevice); virtual bool IsRedirectingTo (LogOutputDevice *OutputDevice); void Serialize (const TCHAR *log_data, const TCHAR *log_prefix, int severity); void Flush(); void Shutdown(); private: std::vector OutputDevices; }; } #endif // NOUTPUTDEVICE_H nux-4.0.8+16.04.20160209/NuxCore/SystemWindows.h0000644000015600001650000003023312656236757021320 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef SYSTEMWIN32_H #define SYSTEMWIN32_H #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include #include #include #include #include #include #include #include #include #include #include #include // If NUX_LOG_FILE_ANSI is set to 1, log files will be written in ASCII characters even when in UNICODE. #define NUX_LOG_FILE_ANSI 1 // // Undo any Windows defines. // #undef BYTE // #undef WORD // #undef DWORD // #undef INT // #undef FLOAT // #undef MAXBYTE // #undef MAXWORD // #undef MAXDWORD // #undef MAXINT // #undef CDECL // #undef BOOL // #undef TCHAR // // // Undef Windows min and max. Conflict with std::min, std::max. // #undef min // #undef max // #define NUX_VARARGS __cdecl // Functions with variable arguments // Calling Convention // This is the default calling convention for C and C++ programs. // Because the stack is cleaned up by the caller, it can do vararg functions. // Argument-passing order: Right to left #define NUX_CDECL __cdecl // The __stdcall calling convention is used to call Win32 API functions. // The callee cleans the stack, so the compiler makes vararg functions __cdecl. // Argument-passing order: Right to left #define NUX_STDCALL __stdcall // The __fastcall calling convention specifies that arguments to functions are to be passed in registers, when possible. #define NUX_FASTCALL __fastcall // This is the default calling convention used by C++ member functions that do not use variable arguments. // Under thiscall, the callee cleans the stack, which is impossible for vararg functions. #define NUX_THISCALL thiscall // #define NUX_INLINE inline // Force inline code #define NUX_FORCEINLINE __forceinline // Force inline code #define NUX_FORCENOINLINE __declspec(noinline) // Force code to NOT be inline // Unsigned base types. typedef unsigned char BYTE; // 8-bit unsigned. typedef unsigned short WORD; // 16-bit unsigned. typedef unsigned int UINT; // 32-bit unsigned. typedef unsigned long DWORD; // 32-bit unsigned. typedef unsigned __int64 QWORD; // 64-bit unsigned. // Signed base types. typedef signed char SBYTE; // 8-bit signed. typedef signed short SWORD; // 16-bit signed. typedef signed int INT; // 32-bit signed. typedef signed __int64 SQWORD; // 64-bit signed. // Character types. typedef char ANSICHAR; // An ANSI character. typedef unsigned char ANSIUCHAR; // An ANSI character. typedef wchar_t UNICHAR; // A unicode character. L"Hello" is of type wchar_t and should not be confuse with type unsigned short on windows. // Other base types. typedef float FLOAT; // 32-bit IEEE floating point. typedef double DOUBLE; // 64-bit IEEE double. /////////////////////////////////////////////// // UNICODE // /////////////////////////////////////////////// #ifdef _UNICODE #ifndef _TCHAR_DEFINED typedef wchar_t TCHAR; #endif #ifndef _TEXT_DEFINED #undef TEXT #define TEXT(s) L##s #endif #else #ifndef _TCHAR_DEFINED typedef ANSICHAR TCHAR; #endif #undef TEXT #define TEXT(s) s #endif // #ifdef WIN32_SECURE // #define STRNCPY_S(strDest, numberOfElements, strSource, count) strncpy_s(strDest, numberOfElements, strSource, count) // #define WCSNCPY_S(strDest, numberOfElements, strSource, count) wcsncpy_s(strDest, numberOfElements, strSource, count) // #define MBSNCPY_S(strDest, numberOfElements, strSource, count) _mbsncpy_s(strDest, numberOfElements, strSource, count) // #define _TCSNCPY_S(strDest, numberOfElements, strSource, count) _tcsncpy_s(strDest, numberOfElements, strSource, count) // // #define STRCPY_S(strDest, numberOfElements, strSource) strcpy_s(strDest, numberOfElements, strSource) // #define WCSCPY_S(strDest, numberOfElements, strSource) wcscpy_s(strDest, numberOfElements, strSource) // #define MBSCPY_S(strDest, numberOfElements, strSource) _mbscpy_s(strDest, numberOfElements, strSource) // #define _TCSCPY_S(strDest, numberOfElements, strSource) _tcscpy_s(strDest, numberOfElements, strSource) // // #define STRCAT_S(strDest, numberOfElements, strSource) strcat_s(strDest, numberOfElements, strSource) // #define WCSCAT_S(strDest, numberOfElements, strSource) wcscat_s(strDest, numberOfElements, strSource) // #define MBSCAT_S(strDest, numberOfElements, strSource) _mbscat_s(strDest, numberOfElements, strSource) // // #define _VSNPRINTF_S(strDest, numberOfElements, Count, Format, VA_Arg_List) _vsnprintf_s(strDest, numberOfElements, Count, Format, VA_Arg_List) // #define _VSNTPRINTF_S(strDest, numberOfElements, Count, Format, VA_Arg_List) _vsntprintf_s(strDest, numberOfElements, Count, Format, VA_Arg_List) // #define SPRINTF_S(strDest, numberOfElements, Format, ...) sprintf_s(strDest, numberOfElements, Format, ##__VA_ARGS__) // #define _SNPRINTF_S(strDest, numberOfElements, Count, Format, ...) _snprintf_s(strDest, numberOfElements, Count, Format, ##__VA_ARGS__) // // #define STRDATE_S(strDest, numberOfElements) _strdate_s(strDest, numberOfElements) // #define _TSTRDATE_S(strDest, numberOfElements) _tstrdate_s(strDest, numberOfElements) // #define _STRTIME_S(strDest, numberOfElements) _strtime_s(strDest, numberOfElements) // #define _TSTRTIME_S(strDest, numberOfElements) _tstrtime_s(strDest, numberOfElements) // // #define FOPEN_S(file, filename, mode) fopen_s(file, filename, mode) // // #define _TCSNLEN(str, numberOfElements) _tcsnlen(str) // // #define _TSPLITPATH(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) _tsplitpath_s(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) // #define _TMAKEPATH_S(path, numberOfElements, Drive, Dir, Filename, Extension) _tmakepath_s(path, numberOfElements, Drive, Dir, Filename, Extension) // // #define SSCANF_S(buffer, Format, ...) sscanf_s(buffer, Format, ##__VA_ARGS__) // #define SWSCANF_S(buffer, Format, ...) swscanf_s(buffer, Format, ##__VA_ARGS__) // // #else // #define STRNCPY_S(strDest, numberOfElements, strSource, count) strncpy(strDest, strSource, count) // #define WCSNCPY_S(strDest, numberOfElements, strSource, count) wcsncpy(strDest, strSource, count) // #define MBSNCPY_S(strDest, numberOfElements, strSource, count) _mbsncpy(strDest, strSource, count) // #define _TCSNCPY_S(strDest, numberOfElements, strSource, count) _tcsncpy(strDest, strSource, count) // // #define STRCPY_S(strDest, numberOfElements, strSource) strcpy(strDest, strSource) // #define WCSCPY_S(strDest, numberOfElements, strSource) wcscpy(strDest, strSource) // #define MBSCPY_S(strDest, numberOfElements, strSource) _mbscpy(strDest, strSource) // #define _TCSCPY_S(strDest, numberOfElements, strSource) _tcscpy(strDest, strSource) // // #define STRCAT_S(strDest, numberOfElements, strSource) strcat(strDest, strSource) // #define WCSCAT_S(strDest, numberOfElements, strSource) wcscat(strDest, strSource) // #define MBSCAT_S(strDest, numberOfElements, strSource) _mbscat(strDest, strSource) // // #define _VSNPRINTF_S(strDest, numberOfElements, Count, Format, VA_Arg_List) _vsnprintf(strDest, Count, Format, VA_Arg_List) // #define _VSNTPRINTF_S(strDest, numberOfElements, Count, Format, VA_Arg_List) _vsntprintf(strDest, Count, Format, VA_Arg_List) // #define SPRINTF_S(strDest, numberOfElements, Format, a,b,c,d,e,f,g,h,i,j,k,l) sprintf(strDest, Format, VARG(a),VARG(b),VARG(c),VARG(d),VARG(e),VARG(f),VARG(g),VARG(h),VARG(i),VARG(j),VARG(k),VARG(l)) // #define _SNPRINTF_S(strDest, numberOfElements, Count, Format, a,b,c,d,e,f,g,h,i,j,k,l) _snprintf(strDest, Count, Format, VARG(a),VARG(b),VARG(c),VARG(d),VARG(e),VARG(f),VARG(g),VARG(h),VARG(i),VARG(j),VARG(k),VARG(l)) // // #define STRDATE_S(strDest, numberOfElements) _strdate(strDest) // #define _TSTRDATE_S(strDest, numberOfElements) _tstrdate(strDest) // #define _STRTIME_S(strDest, numberOfElements) _strtime(strDest) // #define _TSTRTIME_S(strDest, numberOfElements) _tstrtime(strDest) // // #define FOPEN_S(file, filename, mode) (file=fopen(filename, mode)) // // #define _TCSNLEN(str, numberOfElements) _tcsclen(str) // // #define _TSPLITPATH(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) _tsplitpath(path, Drive, Dir, Filename, Extension) // #define _TMAKEPATH_S(path, numberOfElements, Drive, Dir, Filename, Extension) _makepath(path, Drive, Dir, Filename, Extension) // // #define SSCANF_S(buffer, Format, VA_Arg_List) sscanf(buffer, Format, VA_Arg_List) // #define SWSCANF_S(buffer, Format, VA_Arg_List) swscanf(buffer, Format, VA_Arg_List) // #endif /////////////////////////////////////////////// // Variable argument functions // /////////////////////////////////////////////// //@note: Currently xutility breaks with this enabled 2005 fixes it #pragma warning(disable : 4619) // #pragma warning : there is no warning number 'number' //#pragma warning(disable : 4267) // #pragma warning : conversion from 'size_t' to 'int', possible loss of data // Unwanted VC++ level 4 warnings to disable. #pragma warning(disable : 4100) // unreferenced formal parameter #pragma warning(disable : 4127) // Conditional expression is constant #pragma warning(disable : 4200) // Zero-length array item at end of structure, a VC-specific extension #pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union #pragma warning(disable : 4244) // conversion to float, possible loss of data #pragma warning(disable : 4245) // conversion from 'enum ' to 'unsigned long', signed/unsigned mismatch #pragma warning(disable : 4251) // needs to have dll-interface to be used by clients of class 'ULinker' #pragma warning(disable : 4275) // non dll-interface class used as base for dll-interface class #pragma warning(disable : 4291) // typedef-name '' used as synonym for class-name '' #pragma warning(disable : 4324) // structure was padded due to __declspec(align()) #pragma warning(disable : 4355) // this used in base initializer list #pragma warning(disable : 4389) // signed/unsigned mismatch #pragma warning(disable : 4511) // copy constructor could not be generated #pragma warning(disable : 4512) // assignment operator could not be generated #pragma warning(disable : 4514) // unreferenced inline function has been removed #pragma warning(disable : 4699) // creating precompiled header #pragma warning(disable : 4702) // unreachable code in inline expanded function #pragma warning(disable : 4710) // inline function not expanded #pragma warning(disable : 4711) // function selected for autmatic inlining #pragma warning(disable : 4714) // __forceinline function not expanded namespace nux { void *GetDllHandle ( const TCHAR *DllName ); void FreeDllHandle ( void *DllHandle ); void *GetDllExport ( void *DllHandle, const TCHAR *ExportName ); } #endif // SYSTEMWIN32_H nux-4.0.8+16.04.20160209/NuxCore/Colors.cpp0000644000015600001650000001754312656236757020266 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "Colors.h" namespace nux { namespace color { // Definition of Luma coefficients as per ITU-R Recommendation BT.601 // http://en.wikipedia.org/wiki/Rec._601 const float LumaRed = 0.299f; const float LumaGreen = 0.587f; const float LumaBlue = 0.114f; // // Definition of Luma coefficients as per ITU-R Recommendation BT.709 // // http://en.wikipedia.org/wiki/Rec._709 // float LumaRed = 0.2126f; // float LumaGreen = 0.7152f; // float LumaBlue = 0.0722f; const Color Transparent(0, 0, 0, 0); //Red colors const Color IndianRed(0xCD, 0x5C, 0x5C); const Color LightCoral(0xF0, 0x80, 0x80); const Color Salmon(0xFA, 0x80, 0x72); const Color DarkSalmon(0xE9, 0x96, 0x7A); const Color LightSalmon(0xFF, 0xA0, 0x7A); const Color Crimson(0xDC, 0x14, 0x3C); const Color Red(0xFF, 0x00, 0x00); const Color FireBrick(0xB2, 0x22, 0x22); const Color DarkRed(0x8B, 0x00, 0x00); //Pink colors const Color Pink(0xFF, 0xC0, 0xCB); const Color LightPink(0xFF, 0xB6, 0xC1); const Color HotPink(0xFF, 0x69, 0xB4); const Color DeepPink(0xFF, 0x14, 0x93); const Color MediumVioletRed(0xC7, 0x15, 0x85); const Color PaleVioletRed(0xDB, 0x70, 0x93); //Orange colors //const Color LightSalmon = Color (0xFF/255.0f, 0xA0/255.0f, 0x7A/255.0f);// 255 160 122 const Color Coral(0xFF, 0x7F, 0x50); const Color Tomato(0xFF, 0x63, 0x47); const Color OrangeRed(0xFF, 0x45, 0x00); const Color DarkOrange(0xFF, 0x8C, 0x00); const Color Orange(0xFF, 0xA5, 0x00); //Yellow colors const Color Gold(0xFF, 0xD7, 0x00); const Color Yellow(0xFF, 0xFF, 0x00); const Color LightYellow(0xFF, 0xFF, 0xE0); const Color LemonChiffon(0xFF, 0xFA, 0xCD); const Color LightGoldenrodYellow(0xFA, 0xFA, 0xD2); const Color PapayaWhip(0xFF, 0xEF, 0xD5); const Color Moccasin(0xFF, 0xE4, 0xB5); const Color PeachPuff(0xFF, 0xDA, 0xB9); const Color PaleGoldenrod(0xEE, 0xE8, 0xAA); const Color Khaki(0xF0, 0xE6, 0x8C); const Color DarkKhaki(0xBD, 0xB7, 0x6B); //Purple colors const Color Lavender(0xE6, 0xE6, 0xFA); const Color Thistle(0xD8, 0xBF, 0xD8); const Color Plum(0xDD, 0xA0, 0xDD); const Color Violet(0xEE, 0x82, 0xEE); const Color Orchid(0xDA, 0x70, 0xD6); const Color Fuchsia(0xFF, 0x00, 0xFF); const Color Magenta(0xFF, 0x00, 0xFF); const Color MediumOrchid(0xBA, 0x55, 0xD3); const Color MediumPurple(0x93, 0x70, 0xDB); const Color BlueViolet(0x8A, 0x2B, 0xE2); const Color DarkViolet(0x94, 0x00, 0xD3); const Color DarkOrchid(0x99, 0x32, 0xCC); const Color DarkMagenta(0x8B, 0x00, 0x8B); const Color Purple(0x80, 0x00, 0x80); const Color Indigo(0x4B, 0x00, 0x82); const Color SlateBlue(0x6A, 0x5A, 0xCD); const Color DarkSlateBlue(0x48, 0x3D, 0x8B); //Green colors const Color GreenYellow(0xAD, 0xFF, 0x2F); const Color Chartreuse(0x7F, 0xFF, 0x00); const Color LawnGreen(0x7C, 0xFC, 0x00); const Color Lime(0x00, 0xFF, 0x00); const Color LimeGreen(0x32, 0xCD, 0x32); const Color PaleGreen(0x98, 0xFB, 0x98); const Color LightGreen(0x90, 0xEE, 0x90); const Color MediumSpringGreen(0x00, 0xFA, 0x9A); const Color SpringGreen(0x00, 0xFF, 0x7F); const Color MediumSeaGreen(0x3C, 0xB3, 0x71); const Color SeaGreen(0x2E, 0x8B, 0x57); const Color ForestGreen(0x22, 0x8B, 0x22); const Color Green(0x00, 0x80, 0x00); const Color DarkGreen(0x00, 0x64, 0x00); const Color YellowGreen(0x9A, 0xCD, 0x32); const Color OliveDrab(0x6B, 0x8E, 0x23); const Color Olive(0x80, 0x80, 0x00); const Color DarkOliveGreen(0x55, 0x6B, 0x2F); const Color MediumAquamarine(0x66, 0xCD, 0xAA); const Color DarkSeaGreen(0x8F, 0xBC, 0x8F); const Color LightSeaGreen(0x20, 0xB2, 0xAA); const Color DarkCyan(0x00, 0x8B, 0x8B); const Color Teal(0x00, 0x80, 0x80); //Blue colors const Color Aqua(0x00, 0xFF, 0xFF); const Color Cyan(0x00, 0xFF, 0xFF); const Color LightCyan(0xE0, 0xFF, 0xFF); const Color PaleTurquoise(0xAF, 0xEE, 0xEE); const Color Aquamarine(0x7F, 0xFF, 0xD4); const Color Turquoise(0x40, 0xE0, 0xD0); const Color MediumTurquoise(0x48, 0xD1, 0xCC); const Color DarkTurquoise(0x00, 0xCE, 0xD1); const Color CadetBlue(0x5F, 0x9E, 0xA0); const Color SteelBlue(0x46, 0x82, 0xB4); const Color LightSteelBlue(0xB0, 0xC4, 0xDE); const Color PowderBlue(0xB0, 0xE0, 0xE6); const Color LightBlue(0xAD, 0xD8, 0xE6); const Color SkyBlue(0x87, 0xCE, 0xEB); const Color LightSkyBlue(0x87, 0xCE, 0xFA); const Color DeepSkyBlue(0x00, 0xBF, 0xFF); const Color DodgerBlue(0x1E, 0x90, 0xFF); const Color CornflowerBlue(0x64, 0x95, 0xED); const Color MediumSlateBlue(0x7B, 0x68, 0xEE); const Color RoyalBlue(0x41, 0x69, 0xE1); const Color Blue(0x00, 0x00, 0xFF); const Color MediumBlue(0x00, 0x00, 0xCD); const Color DarkBlue(0x00, 0x00, 0x8B); const Color Navy(0x00, 0x00, 0x80); const Color MidnightBlue(0x19, 0x19, 0x70); //Brown colors const Color Cornsilk(0xFF, 0xF8, 0xDC); const Color BlanchedAlmond(0xFF, 0xEB, 0xCD); const Color Bisque(0xFF, 0xE4, 0xC4); const Color NavajoWhite(0xFF, 0xDE, 0xAD); const Color Wheat(0xF5, 0xDE, 0xB3); const Color BurlyWood(0xDE, 0xB8, 0x87); const Color Tan(0xD2, 0xB4, 0x8C); const Color RosyBrown(0xBC, 0x8F, 0x8F); const Color SandyBrown(0xF4, 0xA4, 0x60); const Color Goldenrod(0xDA, 0xA5, 0x20); const Color DarkGoldenrod(0xB8, 0x86, 0x0B); const Color Peru(0xCD, 0x85, 0x3F); const Color Chocolate(0xD2, 0x69, 0x1E); const Color SaddleBrown(0x8B, 0x45, 0x13); const Color Sienna(0xA0, 0x52, 0x2D); const Color Brown(0xA5, 0x2A, 0x2A); const Color Maroon(0x80, 0x00, 0x00); //White colors const Color White(0xFF, 0xFF, 0xFF); const Color Snow(0xFF, 0xFA, 0xFA); const Color Honeydew(0xF0, 0xFF, 0xF0); const Color MintCream(0xF5, 0xFF, 0xFA); const Color Azure(0xF0, 0xFF, 0xFF); const Color AliceBlue(0xF0, 0xF8, 0xFF); const Color GhostWhite(0xF8, 0xF8, 0xFF); const Color WhiteSmoke(0xF5, 0xF5, 0xF5); const Color Seashell(0xFF, 0xF5, 0xEE); const Color Beige(0xF5, 0xF5, 0xDC); const Color OldLace(0xFD, 0xF5, 0xE6); const Color FloralWhite(0xFF, 0xFA, 0xF0); const Color Ivory(0xFF, 0xFF, 0xF0); const Color AntiqueWhite(0xFA, 0xEB, 0xD7); const Color Linen(0xFA, 0xF0, 0xE6); const Color LavenderBlush(0xFF, 0xF0, 0xF5); const Color MistyRose(0xFF, 0xE4, 0xE1); //Grey colors const Color Gainsboro(0xDC, 0xDC, 0xDC); const Color LightGrey(0xD3, 0xD3, 0xD3); const Color Silver(0xC0, 0xC0, 0xC0); const Color DarkGray(0xA9, 0xA9, 0xA9); const Color Gray(0x80, 0x80, 0x80); const Color DimGray(0x69, 0x69, 0x69); const Color LightSlateGray(0x77, 0x88, 0x99); const Color SlateGray(0x70, 0x80, 0x90); const Color DarkSlateGray(0x2F, 0x4F, 0x4F); const Color Black(0x00, 0x00, 0x00); // More Colors const Color Aubergine(0x2B, 0x0B, 0x30); } } nux-4.0.8+16.04.20160209/NuxCore/Animation.h0000644000015600001650000000510512656236757020400 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_ANIMATION_H #define NUX_CORE_ANIMATION_H #include #include #include "EasingCurve.h" namespace nux { namespace animation { class Animation : boost::noncopyable { public: enum State { Stopped, Paused, Running, }; Animation(); virtual ~Animation(); virtual int Duration() const = 0; virtual int CurrentTimePosition() const = 0; void Start(); void Stop(); void Pause(); void Resume(); State CurrentState() const; sigc::signal finished; // Move the animation on so many milliseconds. virtual void Advance(int msec) = 0; protected: virtual void Restart() = 0; private: State state_; }; template class AnimateValue : public Animation { public: AnimateValue(); AnimateValue(int msec_duration); AnimateValue(VALUE_TYPE const& start, VALUE_TYPE const& finish, int msec_duration); AnimateValue& SetStartValue(VALUE_TYPE const& start); AnimateValue& SetFinishValue(VALUE_TYPE const& finish); AnimateValue& SetDuration(int msecs); AnimateValue& SetEasingCurve(EasingCurve const& curve); void Reverse(); virtual int Duration() const; virtual int CurrentTimePosition() const; sigc::signal updated; VALUE_TYPE const& GetStartValue() const; VALUE_TYPE const& GetFinishValue() const; VALUE_TYPE const& GetCurrentValue() const; // Move the animation on so many milliseconds. virtual void Advance(int msec); protected: virtual void Restart(); private: int msec_current_; int msec_duration_; VALUE_TYPE start_value_; VALUE_TYPE finish_value_; VALUE_TYPE current_value_; EasingCurve easing_curve_; }; }} #include "Animation-inl.h" #endif nux-4.0.8+16.04.20160209/NuxCore/AnimationController.h0000644000015600001650000000470112656236757022445 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_ANIMATION_CONTROLLER_H #define NUX_CORE_ANIMATION_CONTROLLER_H #include namespace nux { namespace animation { class Animation; class TickSource { public: virtual ~TickSource(); // tick value is in microseconds sigc::signal tick; }; /** * The Animation Controller is responsible for updating running animations. * * The controller is constructed with a tick source, and operates as a * pseudo-singleton. A controller must be created somewhere, and once it is, * it set as the default controller. It is expected that there is only one * animation controller. */ class Controller { public: static Controller* Instance(); Controller(); virtual ~Controller(); virtual void AddAnimation(Animation* animation) = 0; virtual void RemoveAnimation(Animation* animation) = 0; virtual bool HasRunningAnimations() const = 0; private: #if defined(NUX_OS_WINDOWS) && !defined(NUX_VISUAL_STUDIO_VC11) Controller(Controller const&); Controller& operator = (Controller const&); #else Controller(Controller const&) = delete; Controller& operator = (Controller const&) = delete; #endif }; class AnimationController : public Controller, public sigc::trackable { public: AnimationController(TickSource& tick_source); virtual ~AnimationController(); // tick is expected to be ever increasing virtual void OnTick(long long tick); virtual void AddAnimation(Animation* animation); virtual void RemoveAnimation(Animation* animation); virtual bool HasRunningAnimations() const; private: struct Impl; Impl* pimpl; }; }} // close namespaces #endif nux-4.0.8+16.04.20160209/NuxCore/Character/0000755000015600001650000000000012656240224020163 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/Character/NAscii.cpp0000644000015600001650000000564512656236757022067 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NAscii.h" namespace nux { // Windows-1252 code page t_uchar GAscii[] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 0xFF, '', 0x81, '', '', '', '', '', '', '', '', '', '', '', 0x8d, '', 0x8f, 0x90, '', '', '', '', '', '', '', 0x98, '', '', '', '', 0x9d, '', '', 0xa0, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' }; } nux-4.0.8+16.04.20160209/NuxCore/Character/NUnicodeGNU.h0000644000015600001650000002445012656236757022437 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUNICODEGNU_H #define NUNICODEGNU_H namespace nux { // UTF-16 is the primary encoding mechanism used by Microsoft Windows 2000, Windows 2000 Server, Windows XP and Windows 2003 Server. // Unicode Byte Order Mark (BOM) enum {UNICODE_UTF32_BE = 0x0000FEFF }; enum {UNICODE_UTF32_LE = 0xFFFE0000 }; enum {UNICODE_UTF16_BE = 0xFEFF }; enum {UNICODE_UTF16_LE = 0xFFFE }; enum {UNICODE_UTF8 = 0xEFBBBF }; const BYTE UTF32_BE[] = {0x04 /*size*/, 0x00, 0x00, 0xFE, 0xFF }; const BYTE UTF32_LE[] = {0x04 /*size*/, 0xFF, 0xFE, 0x00, 0x00 }; const BYTE UTF16_BE[] = {0x02 /*size*/, 0xFE, 0xFF }; const BYTE UTF16_LE[] = {0x02 /*size*/, 0xFF, 0xFE }; const BYTE UTF8[] = {0x03 /*size*/, 0xEF, 0xBB, 0xBF }; enum {UNICODE_BOM = 0xfeff}; // UTF-16 is the default encoding form of the Unicode Standard // On Linux and Mac OS X, wchar_t is 4 bytes! // On windows wchar_t is 2 bytes! #ifdef UNICODE inline TCHAR ConvertAnsiCharToTCHAR (ANSICHAR In) { TCHAR output; const t_UTF8 *source_start = &In; const t_UTF8 *source_end = source_start + 1; t_UTF16 *target_start = reinterpret_cast (&output); t_UTF16 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline ANSICHAR ConvertTCHARToAnsiChar (TCHAR In) { ANSICHAR output; const t_UTF16 *source_start = &In; const t_UTF16 *source_end = source_start + 1; t_UTF8 *target_start = reinterpret_cast (&output); t_UTF8 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline TCHAR ConvertUnicodeCharToTCHAR (UNICHAR In) { return In; } inline UNICHAR ConvertTCHARToUnicodeChar (TCHAR In) { return In; } #else inline TCHAR ConvertUnicodeCharToTCHAR (UNICHAR In) { TCHAR output; const t_UTF16 *source_start = &In; const t_UTF16 *source_end = source_start + 1; t_UTF8 *target_start = reinterpret_cast (&output); t_UTF8 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline UNICHAR ConvertTCHARToUnicodeChar (TCHAR In) { UNICHAR output; const t_UTF8 *source_start = reinterpret_cast (&In); const t_UTF8 *source_end = source_start + 1; t_UTF16 *target_start = reinterpret_cast (&output); t_UTF16 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline TCHAR ConvertAnsiCharToTCHAR (ANSICHAR In) { return In; } inline ANSICHAR ConvertTCHARToAnsiChar (TCHAR In) { return In; } #endif /*! Convert a single UNICHAR to ANSICHAR. */ inline ANSICHAR ConvertUnicodeCharToAnsiChar (UNICHAR In) { TCHAR output; const t_UTF16 *source_start = &In; const t_UTF16 *source_end = source_start + 1; t_UTF8 *target_start = reinterpret_cast (&output); t_UTF8 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } /*! Convert a single ANSICHAR to UNICHAR. */ inline UNICHAR ConvertAnsiCharToUnicodeChar (ANSICHAR In) { TCHAR output; const t_UTF8 *source_start = reinterpret_cast (&In); const t_UTF8 *source_end = source_start + 1; t_UTF16 *target_start = reinterpret_cast (&output); t_UTF16 *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } class UnicharToAnsicharConvertion { public: // Default to ANSI code page UnicharToAnsicharConvertion() {} /*! Convert from UNICHAR to ANSICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ ANSICHAR *Convert (const UNICHAR *Source) { std::wstring utf16string (Source); size_t utf16size = utf16string.length(); size_t utf8size = 6 * utf16size + 1; ANSICHAR *utf8string = new ANSICHAR[utf8size]; const t_UTF16 *source_start = utf16string.c_str(); const t_UTF16 *source_end = source_start + utf16size; t_UTF8 *target_start = reinterpret_cast (&utf8string); t_UTF8 *target_end = target_start + utf8size; ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { delete [] utf8string; utf8string = 0; } // mark end of string *target_start = 0; return utf8string; } }; //! ANSICHAR to UNICHAR conversion class AnsicharToUnicharConvertion { public: NUX_INLINE AnsicharToUnicharConvertion() {} /*! Convert from ANSICHAR to UNICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE UNICHAR *Convert (const ANSICHAR *Source) { std::string utf8string (Source); size_t utf8size = utf8string.length(); size_t utf16size = utf8size + 1; UNICHAR *utf16string = new UNICHAR[utf16size]; const t_UTF8 *source_start = reinterpret_cast (utf8string.c_str() ); const t_UTF8 *source_end = source_start + utf8size; t_UTF16 *target_start = reinterpret_cast (&utf16string); t_UTF16 *target_end = target_start + utf16size; ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { delete [] utf16string; utf16string = 0; } // mark end of string *target_start = 0; return utf16string; } }; //! TCHAR to ANSI conversion // TCHAR can be ansi or unicode depending if UNICODE is defined or not. class TCharToAnsiConvertion { public: NUX_INLINE TCharToAnsiConvertion() {} /*! Convert from TCHAR to ANSICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE ANSICHAR *Convert (const TCHAR *Source) { // Determine whether we need to allocate memory or not #ifdef UNICODE UnicharToAnsicharConvertion convert; return convert.Convert (Source); #else int length = strlen (Source) + 1; int size = length * sizeof (ANSICHAR); ANSICHAR *Dest = new ANSICHAR[size]; STRNCPY_S (Dest, size, Source, length); return Dest; #endif } }; //! ANSI to TCHAR conversion // TCHAR can be ansi or unicode depending if UNICODE is defined or not. class AnsiToTCharConversion { public: NUX_INLINE AnsiToTCharConversion() {} /*! Convert from ANSICHAR to TCHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE TCHAR *Convert (const ANSICHAR *Source) { #ifdef UNICODE AnsicharToUnicharConvertion convert; return convert.Convert (Source); #else unsigned int length = strlen (Source) + 1; unsigned int size = length; TCHAR *Dest = new TCHAR[size]; STRNCPY_S (Dest, size, Source, length); return Dest; #endif } }; /*! Convert from one string format to another. */ template < typename CONVERT_TO, typename CONVERT_FROM, typename BASE_CONVERTER, DWORD DefaultConversionSize = 128 > class NCharacterConversion: public BASE_CONVERTER { CONVERT_TO *ConvertedString; // Hide the default constructor NCharacterConversion(); public: /*! Converts the data by using the Convert() method on the base class */ explicit inline NCharacterConversion (const CONVERT_FROM *Source) { if (Source != NULL) { // Use base class' convert method ConvertedString = BASE_CONVERTER::Convert (Source); } else { ConvertedString = NULL; } } /*! If memory was allocated, then it is freed below */ inline ~NCharacterConversion() { if (ConvertedString != NULL) { delete [] ConvertedString; } } // Operator to get access to the converted string inline operator CONVERT_TO* (void) const { return ConvertedString; } }; // Conversion typedefs typedef NCharacterConversion ANSI_To_TCHAR_Conversion; typedef NCharacterConversion TCHAR_To_ANSI_Conversion; typedef NCharacterConversion UNICHAR_To_ANSICHAR_Conversion; typedef NCharacterConversion ANSICHAR_To_UNICHAR_Conversion; } #endif // NUNICODEGNU_H nux-4.0.8+16.04.20160209/NuxCore/Character/NUnicodeGNU.cpp0000644000015600001650000000153712656236757022773 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NUnicodeGNU.h" namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Character/NTChar.h0000644000015600001650000000423712656236757021501 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NTCHAR_H #define NTCHAR_H namespace nux { inline TCHAR ToUpperCase ( TCHAR c ) { return (c < TEXT ('a') || c > TEXT ('z') ) ? (c) : (c + TEXT ('A') - TEXT ('a') ); } inline TCHAR ToLowerCase ( TCHAR c ) { return (c < TEXT ('A') || c > TEXT ('Z') ) ? (c) : (c + TEXT ('a') - TEXT ('A') ); } inline bool IsUpperCase ( TCHAR c ) { return (c >= TEXT ('A') && c <= TEXT ('Z') ); } inline bool IsLowerCase ( TCHAR c ) { return (c >= TEXT ('a') && c <= TEXT ('z') ); } inline bool IsAlphaChar ( TCHAR c ) { return (c >= TEXT ('a') && c <= TEXT ('z') ) || (c >= TEXT ('A') && c <= TEXT ('Z') ); } inline bool IsDigitChar ( TCHAR c ) { return c >= TEXT ('0') && c <= TEXT ('9'); } inline bool IsAlphanumericChar ( TCHAR c ) { return (c >= TEXT ('a') && c <= TEXT ('z') ) || (c >= TEXT ('A') && c <= TEXT ('Z') ) || (c >= TEXT ('0') && c <= TEXT ('9') ); } inline bool IsWhitespaceChar ( TCHAR c ) { return c == TEXT (' ') || c == TEXT ('\t'); } inline bool IsLinebreakChar ( TCHAR c ) { //@todo - support for language-specific line break characters return c == TEXT ('\n'); } /** Returns nonzero if character is a space character. */ inline bool IsSpaceChar ( TCHAR c ) { #ifdef NUX_UNICODE return ( std::iswspace (c) != 0 ); #else return ( std::isspace (c) != 0 ); #endif } } #endif // NTCHAR_H nux-4.0.8+16.04.20160209/NuxCore/Character/NUTF.h0000644000015600001650000000733212656236757021135 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUTF_H #define NUTF_H // http://en.wikipedia.org/wiki/UTF-16 // In computing, UTF-16 (16-bit Unicode Transformation Format) is a variable-length character encoding // for Unicode, capable of encoding the entire Unicode repertoire. The encoding form maps code points // (characters) into a sequence of 16-bit words, called code units. For characters in the Basic // Multilingual Plane (BMP) the resulting encoding is a single 16-bit word. For characters in the other // planes, the encoding will result in a pair of 16-bit words, together called a surrogate pair. All possible // code points from U+0000 through U+10FFFF, except for the surrogate code points U+D800U+DFFF // (which are not characters), are uniquely mapped by UTF-16 regardless of the code point's current or // future character assignment or use. // // As many uses in computing require units of bytes (octets) there are three related encoding schemes // which map to octet sequences instead of words: namely UTF-16, UTF-16BE, and UTF-16LE. They // differ only in the byte order chosen to represent each 16-bit unit and whether they make use of a // Byte Order Mark. All of the schemes will result in either a 2 or 4-byte sequence for any given character. // // UTF-16 is officially defined in Annex Q of the international standard ISO/IEC 10646-1. It is also // described in The Unicode Standard version 3.0 and higher, as well as in the IETF's RFC 2781. // // UCS-2 (2-byte Universal Character Set) is an obsolete character encoding which is a predecessor // to UTF-16. The UCS-2 encoding form is nearly identical to that of UTF-16, except that it does not // support surrogate pairs and therefore can only encode characters in the BMP range U+0000 through // U+FFFF. As a consequence it is a fixed-length encoding that always encodes characters into a // single 16-bit value. As with UTF-16, there are three related encoding schemes (UCS-2, UCS-2BE, UCS-2LE) // that map characters to a specific byte sequence. // // Because of the technical similarities and upwards compatibility from UCS-2 to UTF-16, the two // encodings are often erroneously conflated and used as if interchangeable, so that strings encoded // in UTF-16 are sometimes misidentified as being encoded in UCS-2. namespace nux { //! Convert UTF-16 to UTF-8 class NUTF8 { // UTF-8 encoded characters may theoretically be up to six bytes long, however 16-bit BMP characters are only up to three bytes long. public: explicit NUTF8 (const UNICHAR *Source); explicit NUTF8 (const std::wstring &Source); ~NUTF8(); operator const char* (); private: void Convert (const UNICHAR *); //void Convert(const t_UTF32*); char *utf8; }; //! Convert UTF-8 to UTF-16 class NUTF16 { public: explicit NUTF16 (const char *Source); explicit NUTF16 (const std::string &Source); ~NUTF16(); operator const UNICHAR* (); private: void Convert (const char *); UNICHAR *unicode; }; } #endif // NUTF_H nux-4.0.8+16.04.20160209/NuxCore/Character/NAscii.h0000644000015600001650000000164612656236757021531 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NTASCII_H #define NTASCII_H namespace nux { extern t_uchar GAscii[]; extern t_uchar GAsciiCP437[]; } #endif // NTASCII_H nux-4.0.8+16.04.20160209/NuxCore/Character/NUni.h0000644000015600001650000001602012656236757021224 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUNI_H #define NUNI_H /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Header file. Several funtions are included here, forming a complete set of conversions between the three formats. UTF-7 is not included here, but is handled in a separate source file. Each of these routines takes pointers to input buffers and output buffers. The input buffers are const. Each routine converts the text between *sourceStart and sourceEnd, putting the result into the buffer between *targetStart and targetEnd. Note: the end pointers are *after* the last item: e.g. *(sourceEnd - 1) is the last item. The return result indicates whether the conversion was successful, and if not, whether the problem was in the source or target buffers. (Only the first encountered problem is indicated.) After the conversion, *sourceStart and *targetStart are both updated to point to the end of last text successfully converted in the respective buffers. Input parameters: sourceStart - pointer to a pointer to the source buffer. The contents of this are modified on return so that it points at the next thing to be converted. targetStart - similarly, pointer to pointer to the target buffer. sourceEnd, targetEnd - respectively pointers to the ends of the two buffers, for overflow checking only. These conversion functions take a ConversionFlags argument. When this flag is set to strict, both irregular sequences and isolated surrogates will cause an error. When the flag is set to lenient, both irregular sequences and isolated surrogates are converted. Whether the flag is strict or lenient, all illegal sequences will cause an error return. This includes sequences such as: , , or in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code must check for illegal sequences. When the flag is set to lenient, characters over 0x10FFFF are converted to the replacement character; otherwise (when the flag is set to strict) they constitute an error. Output parameters: The value "sourceIllegal" is returned from some routines if the input sequence is malformed. When "sourceIllegal" is returned, the source value will point to the illegal value that caused the problem. E.g., in UTF-8 when a sequence is malformed, it points to the start of the malformed sequence. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Fixes & updates, Sept 2001. ------------------------------------------------------------------------ */ /* --------------------------------------------------------------------- The following 4 definitions are compiler-specific. The C standard does not guarantee that wchar_t has at least 16 bits, so wchar_t is no less portable than unsigned short! All should be unsigned values to avoid sign extension during bit mask & shift operations. ------------------------------------------------------------------------ */ //typedef unsigned long unsigned int; /* at least 32 bits */ //typedef unsigned short wchar_t; /* at least 16 bits */ //typedef unsigned char unsigned char; /* typically 8 bits */ //typedef unsigned char Boolean; /* 0 or 1 */ namespace nux { /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (unsigned int)0x0000FFFD #define UNI_MAX_BMP (unsigned int)0x0000FFFF #define UNI_MAX_UTF16 (unsigned int)0x0010FFFF #define UNI_MAX_UTF32 (unsigned int)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (unsigned int)0x0010FFFF typedef enum { conversionOK = 0, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; typedef enum { strictConversion = 0, lenientConversion } ConversionFlags; ConversionResult ConvertUTF8toUTF16 ( const unsigned char **sourceStart, const unsigned char *sourceEnd, wchar_t **targetStart, wchar_t *targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF8 ( const wchar_t **sourceStart, const wchar_t *sourceEnd, unsigned char **targetStart, unsigned char *targetEnd, ConversionFlags flags); ConversionResult ConvertUTF8toUTF32 ( const unsigned char **sourceStart, const unsigned char *sourceEnd, unsigned int **targetStart, unsigned int *targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF8 ( const unsigned int **sourceStart, const unsigned int *sourceEnd, unsigned char **targetStart, unsigned char *targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF32 ( const wchar_t **sourceStart, const wchar_t *sourceEnd, unsigned int **targetStart, unsigned int *targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF16 ( const unsigned int **sourceStart, const unsigned int *sourceEnd, wchar_t **targetStart, wchar_t *targetEnd, ConversionFlags flags); bool isLegalUTF8Sequence (const unsigned char *source, const unsigned char *sourceEnd); /* intended to work the same as g_utf8_validate */ bool tr_utf8_validate ( const char *str, int max_len, const char **end ); } #endif /* NUNI_H */ nux-4.0.8+16.04.20160209/NuxCore/Character/NUni.cpp0000644000015600001650000006116012656236757021564 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Source code file. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Sept 2001: fixed const & error conditions per mods suggested by S. Parent & A. Lillich. June 2002: Tim Dodd added detection and handling of incomplete source sequences, enhanced error detection, added casts to eliminate compiler warnings. July 2003: slight mods to back out aggressive FFFE detection. Jan 2004: updated switches in from-UTF8 conversions. Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions. May 2006: updated isLegalUTF8Sequence. See the header file "ConvertUTF.h" for complete documentation. ------------------------------------------------------------------------ */ #include "NuxCore.h" //#include "NUni.h" namespace nux { static const int halfShift = 10; /* used for shifting by 10 bits */ static const unsigned int halfBase = 0x0010000UL; static const unsigned int halfMask = 0x3FFUL; #define UNI_SUR_HIGH_START (unsigned int)0xD800 #define UNI_SUR_HIGH_END (unsigned int)0xDBFF #define UNI_SUR_LOW_START (unsigned int)0xDC00 #define UNI_SUR_LOW_END (unsigned int)0xDFFF ConversionResult ConvertUTF32toUTF16 (const unsigned int **sourceStart, const unsigned int *sourceEnd, wchar_t **targetStart, wchar_t *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const unsigned int *source = *sourceStart; wchar_t *target = *targetStart; while (source < sourceEnd) { unsigned int ch; if (target >= targetEnd) { result = targetExhausted; break; } ch = *source++; if (ch <= UNI_MAX_BMP) /* Target is a character <= 0xFFFF */ { /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = (wchar_t) ch; /* normal case */ } } else if (ch > UNI_MAX_LEGAL_UTF32) { if (flags == strictConversion) { result = sourceIllegal; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ if (target + 1 >= targetEnd) { --source; /* Back up source pointer! */ result = targetExhausted; break; } ch -= halfBase; *target++ = (wchar_t) ( (ch >> halfShift) + UNI_SUR_HIGH_START); *target++ = (wchar_t) ( (ch & halfMask) + UNI_SUR_LOW_START); } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF16toUTF32 (const wchar_t **sourceStart, const wchar_t *sourceEnd, unsigned int **targetStart, unsigned int *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const wchar_t *source = *sourceStart; unsigned int *target = *targetStart; unsigned int ch, ch2; while (source < sourceEnd) { const wchar_t *oldSource = source; /* In case we have to back up because of target overflow. */ ch = *source++; /* If we have a surrogate pair, convert to UTF32 first. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { /* If the 16 bits following the high surrogate are in the source buffer... */ if (source < sourceEnd) { ch2 = *source; /* If it's a low surrogate, convert to UTF32. */ if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { ch = ( (ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + halfBase; ++source; } else if (flags == strictConversion) /* it's an unpaired high surrogate */ { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } else /* We don't have the 16 bits following the high surrogate. */ { --source; /* return to the high surrogate */ result = sourceExhausted; break; } } else if (flags == strictConversion) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } if (target >= targetEnd) { source = oldSource; /* Back up source pointer! */ result = targetExhausted; break; } *target++ = ch; } *sourceStart = source; *targetStart = target; #ifdef CVTUTF_DEBUG if (result == sourceIllegal) { fprintf (stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2); fflush (stderr); } #endif return result; } /* --------------------------------------------------------------------- */ /* * Index into the table below with the first byte of a UTF-8 sequence to * get the number of trailing bytes that are supposed to follow it. * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is * left as-is for anyone who may want to do such conversion, which was * allowed in earlier algorithms. */ static const char trailingBytesForUTF8[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; /* * Magic values subtracted from a buffer value during UTF8 conversion. * This table contains as many values as there might be trailing bytes * in a UTF-8 sequence. */ static const unsigned int offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed * into the first byte, depending on how many bytes follow. There are * as many entries in this table as there are UTF-8 sequence types. * (I.e., one byte sequence, two byte... etc.). Remember that sequencs * for *legal* UTF-8 will be 4 or fewer bytes total. */ static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; /* --------------------------------------------------------------------- */ /* The interface converts a whole buffer to avoid function-call overhead. * Constants have been gathered. Loops & conditionals have been removed as * much as possible for efficiency, in favor of drop-through switches. * (See "Note A" at the bottom of the file for equivalent code.) * If your compiler supports it, the "isLegalUTF8" call can be turned * into an inline function. */ /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF16toUTF8 (const wchar_t **sourceStart, const wchar_t *sourceEnd, unsigned char **targetStart, unsigned char *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const wchar_t *source = *sourceStart; unsigned char *target = *targetStart; while (source < sourceEnd) { unsigned int ch; unsigned short bytesToWrite = 0; const unsigned int byteMask = 0xBF; const unsigned int byteMark = 0x80; const wchar_t *oldSource = source; /* In case we have to back up because of target overflow. */ ch = *source++; /* If we have a surrogate pair, convert to UTF32 first. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { /* If the 16 bits following the high surrogate are in the source buffer... */ if (source < sourceEnd) { unsigned int ch2 = *source; /* If it's a low surrogate, convert to UTF32. */ if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { ch = ( (ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + halfBase; ++source; } else if (flags == strictConversion) /* it's an unpaired high surrogate */ { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } else /* We don't have the 16 bits following the high surrogate. */ { --source; /* return to the high surrogate */ result = sourceExhausted; break; } } else if (flags == strictConversion) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } /* Figure out how many bytes the result will require */ if (ch < (unsigned int) 0x80) { bytesToWrite = 1; } else if (ch < (unsigned int) 0x800) { bytesToWrite = 2; } else if (ch < (unsigned int) 0x10000) { bytesToWrite = 3; } else if (ch < (unsigned int) 0x110000) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; } target += bytesToWrite; if (target > targetEnd) { source = oldSource; /* Back up source pointer! */ target -= bytesToWrite; result = targetExhausted; break; } switch (bytesToWrite) /* note: everything falls through. */ { case 4: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (unsigned char) (ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ /* * Utility routine to tell whether a sequence of bytes is legal UTF-8. * This must be called with the length pre-determined by the first byte. * If not calling this from ConvertUTF8to*, then the length can be set by: * length = trailingBytesForUTF8[*source]+1; * and the sequence is illegal right away if there aren't that many bytes * available. * If presented with a length > 4, this returns false. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static bool isLegalUTF8 (const unsigned char *source, int length) { unsigned char a; const unsigned char *srcptr = source + length; switch (length) { default: return false; /* Everything else falls through when "true"... */ case 4: if ( (a = (*--srcptr) ) < 0x80 || a > 0xBF) return false; case 3: if ( (a = (*--srcptr) ) < 0x80 || a > 0xBF) return false; case 2: if ( (a = (*--srcptr) ) > 0xBF) return false; switch (*source) { /* no fall-through in this inner switch */ case 0xE0: if (a < 0xA0) return false; break; case 0xED: if ( (a < 0x80) || (a > 0x9F) ) return false; break; case 0xF0: if (a < 0x90) return false; break; case 0xF4: if (a > 0x8F) return false; break; default: if (a < 0x80) return false; } case 1: if (*source >= 0x80 && *source < 0xC2) return false; } if (*source > 0xF4) return false; return true; } /* --------------------------------------------------------------------- */ /* * Exported function to return whether a UTF-8 sequence is legal or not. * This is not used here; it's just exported. */ bool isLegalUTF8Sequence (const unsigned char *source, const unsigned char *sourceEnd) { int length; if (source == sourceEnd) { return true; } while (true) { length = trailingBytesForUTF8[*source] + 1; if (source + length > sourceEnd) { return false; } if (!isLegalUTF8 (source, length) ) { return false; } source += length; if (source >= sourceEnd) { return true; } } return true; } /** * This is a variation of isLegalUTF8Sequence() that behaves like g_utf8_validate(). * In addition to knowing if the sequence is legal, it also tells you the last good character. */ bool tr_utf8_validate ( const char *str, int max_len, const char **end ) { const unsigned char *source = (const unsigned char *) str; const unsigned char *sourceEnd; if ( max_len == 0 ) return true; if ( str == NULL ) return false; sourceEnd = source + ( (max_len < 0) ? strlen (str) : (size_t) max_len); if ( source == sourceEnd ) { if ( end != NULL ) *end = (const char *) source; return true; } for ( ;; ) { const int length = trailingBytesForUTF8[*source] + 1; if (source + length > sourceEnd) { if ( end != NULL ) *end = (const char *) source; return false; } if (!isLegalUTF8 (source, length) ) { if ( end != NULL ) *end = (const char *) source; return false; } source += length; if (source >= sourceEnd) { if ( end != NULL ) *end = (const char *) source; return true; } } return true; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF16 (const unsigned char **sourceStart, const unsigned char *sourceEnd, wchar_t **targetStart, wchar_t *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const unsigned char *source = *sourceStart; wchar_t *target = *targetStart; while (source < sourceEnd) { unsigned int ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { result = sourceExhausted; break; } /* Do this check whether lenient or strict */ if (! isLegalUTF8 (source, extraBytesToRead + 1) ) { result = sourceIllegal; break; } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (target >= targetEnd) { source -= (extraBytesToRead + 1); /* Back up source pointer! */ result = targetExhausted; break; } if (ch <= UNI_MAX_BMP) /* Target is a character <= 0xFFFF */ { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { source -= (extraBytesToRead + 1); /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = (wchar_t) ch; /* normal case */ } } else if (ch > UNI_MAX_UTF16) { if (flags == strictConversion) { result = sourceIllegal; source -= (extraBytesToRead + 1); /* return to the start */ break; /* Bail out; shouldn't continue */ } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ if (target + 1 >= targetEnd) { source -= (extraBytesToRead + 1); /* Back up source pointer! */ result = targetExhausted; break; } ch -= halfBase; *target++ = (wchar_t) ( (ch >> halfShift) + UNI_SUR_HIGH_START); *target++ = (wchar_t) ( (ch & halfMask) + UNI_SUR_LOW_START); } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF32toUTF8 ( const unsigned int **sourceStart, const unsigned int *sourceEnd, unsigned char **targetStart, unsigned char *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const unsigned int *source = *sourceStart; unsigned char *target = *targetStart; while (source < sourceEnd) { unsigned int ch; unsigned short bytesToWrite = 0; const unsigned int byteMask = 0xBF; const unsigned int byteMark = 0x80; ch = *source++; if (flags == strictConversion ) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } /* * Figure out how many bytes the result will require. Turn any * illegally large UTF32 things (> Plane 17) into replacement chars. */ if (ch < (unsigned int) 0x80) { bytesToWrite = 1; } else if (ch < (unsigned int) 0x800) { bytesToWrite = 2; } else if (ch < (unsigned int) 0x10000) { bytesToWrite = 3; } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } target += bytesToWrite; if (target > targetEnd) { --source; /* Back up source pointer! */ target -= bytesToWrite; result = targetExhausted; break; } switch (bytesToWrite) /* note: everything falls through. */ { case 4: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (unsigned char) ( (ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (unsigned char) (ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF32 ( const unsigned char **sourceStart, const unsigned char *sourceEnd, unsigned int **targetStart, unsigned int *targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const unsigned char *source = *sourceStart; unsigned int *target = *targetStart; while (source < sourceEnd) { unsigned int ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { result = sourceExhausted; break; } /* Do this check whether lenient or strict */ if (! isLegalUTF8 (source, extraBytesToRead + 1) ) { result = sourceIllegal; break; } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; case 4: ch += *source++; ch <<= 6; case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (target >= targetEnd) { source -= (extraBytesToRead + 1); /* Back up the source pointer! */ result = targetExhausted; break; } if (ch <= UNI_MAX_LEGAL_UTF32) { /* * UTF-16 surrogate values are illegal in UTF-32, and anything * over Plane 17 (> 0x10FFFF) is illegal. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { source -= (extraBytesToRead + 1); /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = ch; } } else /* i.e., ch > UNI_MAX_LEGAL_UTF32 */ { result = sourceIllegal; *target++ = UNI_REPLACEMENT_CHAR; } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- Note A. The fall-through switches in UTF-8 reading code save a temp variable, some decrements & conditionals. The switches are equivalent to the following loop: { int tmpBytesToRead = extraBytesToRead+1; do { ch += *source++; --tmpBytesToRead; if (tmpBytesToRead) ch <<= 6; } while (tmpBytesToRead > 0); } In UTF-8 writing code, the switches on "bytesToWrite" are similarly unrolled loops. --------------------------------------------------------------------- */ } nux-4.0.8+16.04.20160209/NuxCore/Character/NUnicode.cpp0000644000015600001650000000466412656236757022425 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NUnicode.h" namespace nux { ANSICHAR *UnicharToAnsicharConvertion::Convert (const UNICHAR *Source) { std::wstring utf16string (Source); size_t utf16size = utf16string.length(); size_t utf8size = 6 * utf16size; ANSICHAR *utf8string = new ANSICHAR[utf8size+1]; const wchar_t *source_start = utf16string.c_str(); const wchar_t *source_end = source_start + utf16size; unsigned char *target_start = reinterpret_cast (utf8string); unsigned char *target_end = target_start + utf8size; ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { delete [] utf8string; utf8string = 0; } // mark end of string *target_start = 0; return utf8string; } UNICHAR *AnsicharToUnicharConvertion::Convert (const ANSICHAR *Source) { std::string utf8string (Source); size_t utf8size = utf8string.length(); size_t utf16size = utf8size; UNICHAR *utf16string = new UNICHAR[utf16size+1]; const unsigned char *source_start = reinterpret_cast (utf8string.c_str() ); const unsigned char *source_end = source_start + utf8size; wchar_t *target_start = reinterpret_cast (utf16string); wchar_t *target_end = target_start + utf16size; ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { delete[] utf16string; utf16string = 0; } // mark end of string *target_start = 0; return utf16string; } } nux-4.0.8+16.04.20160209/NuxCore/Character/NUnicode.h0000644000015600001650000002474612656236757022075 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUNICODE_H #define NUNICODE_H namespace nux { // UTF-16 is the primary encoding mechanism used by Microsoft Windows 2000, Windows 2000 Server, Windows XP and Windows 2003 Server. // Unicode Byte Order Mark (BOM) enum {UNICODE_UTF32_BE = 0x0000FEFF }; enum {UNICODE_UTF32_LE = 0xFFFE0000 }; enum {UNICODE_UTF16_BE = 0xFEFF }; enum {UNICODE_UTF16_LE = 0xFFFE }; enum {UNICODE_UTF8 = 0xEFBBBF }; const BYTE UTF32_BE[] = {0x04 /*size*/, 0x00, 0x00, 0xFE, 0xFF }; const BYTE UTF32_LE[] = {0x04 /*size*/, 0xFF, 0xFE, 0x00, 0x00 }; const BYTE UTF16_BE[] = {0x02 /*size*/, 0xFE, 0xFF }; const BYTE UTF16_LE[] = {0x02 /*size*/, 0xFF, 0xFE }; const BYTE UTF8[] = {0x03 /*size*/, 0xEF, 0xBB, 0xBF }; enum {UNICODE_BOM = 0xfeff}; // UTF-16 is the default encoding form of the Unicode Standard // On Linux and Mac OS X, wchar_t is 4 bytes! // On windows wchar_t is 2 bytes! #ifdef UNICODE inline TCHAR ConvertAnsiCharToTCHAR (ANSICHAR In) { TCHAR output; const unsigned char *source_start = &In; const unsigned char *source_end = source_start + 1; wchar_t *target_start = reinterpret_cast (&output); wchar_t *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline ANSICHAR ConvertTCHARToAnsiChar (TCHAR In) { ANSICHAR output; const wchar_t *source_start = &In; const wchar_t *source_end = source_start + 1; unsigned char *target_start = reinterpret_cast (&output); unsigned char *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline TCHAR ConvertUnicodeCharToTCHAR (UNICHAR In) { return In; } inline UNICHAR ConvertTCHARToUnicodeChar (TCHAR In) { return In; } #else inline TCHAR ConvertUnicodeCharToTCHAR (UNICHAR In) { TCHAR output; const wchar_t *source_start = &In; const wchar_t *source_end = source_start + 1; unsigned char *target_start = reinterpret_cast (&output); unsigned char *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline UNICHAR ConvertTCHARToUnicodeChar (TCHAR In) { UNICHAR output; const unsigned char *source_start = reinterpret_cast (&In); const unsigned char *source_end = source_start + 1; wchar_t *target_start = reinterpret_cast (&output); wchar_t *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } inline TCHAR ConvertAnsiCharToTCHAR (ANSICHAR In) { return In; } inline ANSICHAR ConvertTCHARToAnsiChar (TCHAR In) { return In; } #endif /*! Convert a single UNICHAR to ANSICHAR. */ inline ANSICHAR ConvertUnicodeCharToAnsiChar (UNICHAR In) { TCHAR output; const wchar_t *source_start = &In; const wchar_t *source_end = source_start + 1; unsigned char *target_start = reinterpret_cast (&output); unsigned char *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF16toUTF8 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } /*! Convert a single ANSICHAR to UNICHAR. */ inline UNICHAR ConvertAnsiCharToUnicodeChar (ANSICHAR In) { UNICHAR output; const unsigned char *source_start = reinterpret_cast (&In); const unsigned char *source_end = source_start + 1; wchar_t *target_start = reinterpret_cast (&output); wchar_t *target_end = target_start + sizeof (wchar_t); ConversionResult res = ConvertUTF8toUTF16 (&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { output = 0; } return output; } class UnicharToAnsicharConvertion { public: // Default to ANSI code page UnicharToAnsicharConvertion() {} /*! Convert from UNICHAR to ANSICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ ANSICHAR *Convert (const UNICHAR *Source); /*{ std::wstring utf16string(Source); size_t utf16size = utf16string.length(); size_t utf8size = 6 * utf16size; ANSICHAR *utf8string = new ANSICHAR[utf8size+1]; const wchar_t *source_start = utf16string.c_str(); const wchar_t *source_end = source_start + utf16size; unsigned char* target_start = reinterpret_cast(utf8string); unsigned char* target_end = target_start + utf8size; ConversionResult res = ConvertUTF16toUTF8(&source_start, source_end, &target_start, target_end, lenientConversion); if (res != conversionOK) { delete utf8string; utf8string = 0; } // mark end of string *target_start = 0; return utf8string; }*/ }; //! ANSICHAR to UNICHAR conversion class AnsicharToUnicharConvertion { public: AnsicharToUnicharConvertion() {} /*! Convert from ANSICHAR to UNICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ UNICHAR *Convert (const ANSICHAR *Source); }; //! TCHAR to ANSI conversion // TCHAR can be ansi or unicode depending if UNICODE is defined or not. class TCharToAnsiConvertion { public: NUX_INLINE TCharToAnsiConvertion() {} /*! Convert from TCHAR to ANSICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE ANSICHAR *Convert (const TCHAR *Source) { // Determine whether we need to allocate memory or not #ifdef UNICODE UnicharToAnsicharConvertion convert; return convert.Convert (Source); #else size_t length = strlen (Source) + 1; size_t size = length * sizeof (ANSICHAR); ANSICHAR *Dest = new ANSICHAR[size]; STRNCPY_S (Dest, size, Source, length); return Dest; #endif } }; //! TCHAR to Unichar conversion // TCHAR can be ansi or unicode depending if UNICODE is defined or not. class TCharToUnicharConvertion { public: NUX_INLINE TCharToUnicharConvertion() {} /*! Convert from TCHAR to ANSICHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE UNICHAR *Convert (const TCHAR *Source) { // Determine whether we need to allocate memory or not #ifdef UNICODE size_t length = strlen (Source) + 1; size_t size = length * sizeof (UNICHAR); UNICHAR *Dest = new UNICHAR[size]; STRNCPY_S (Dest, size, Source, length); return Dest; #else AnsicharToUnicharConvertion convert; return convert.Convert (Source); #endif } }; //! ANSI to TCHAR conversion // TCHAR can be ansi or unicode depending if UNICODE is defined or not. class AnsiToTCharConversion { public: NUX_INLINE AnsiToTCharConversion() {} /*! Convert from ANSICHAR to TCHAR @param Source String to convert. Null terminated. @return Return a pointer to the new string. Null terminated. */ NUX_INLINE TCHAR *Convert (const ANSICHAR *Source) { #ifdef UNICODE AnsicharToUnicharConvertion convert; return convert.Convert (Source); #else size_t length = strlen (Source) + 1; size_t size = length; TCHAR *Dest = new TCHAR[size]; STRNCPY_S (Dest, size, Source, length); return Dest; #endif } }; /*! Convert from one string format to another. */ template < typename CONVERT_TO, typename CONVERT_FROM, typename BASE_CONVERTER, DWORD DefaultConversionSize = 128 > class NCharacterConversion: public BASE_CONVERTER { CONVERT_TO *ConvertedString; // Hide the default constructor NCharacterConversion(); public: /*! Converts the data by using the Convert() method on the base class */ explicit inline NCharacterConversion (const CONVERT_FROM *Source) { if (Source != NULL) { // Use base class' convert method ConvertedString = BASE_CONVERTER::Convert (Source); } else { ConvertedString = NULL; } } /*! If memory was allocated, then it is freed below */ inline ~NCharacterConversion() { if (ConvertedString != NULL) { delete [] ConvertedString; } } // Operator to get access to the converted string inline operator CONVERT_TO* (void) const { return ConvertedString; } }; // Conversion typedefs // typedef NCharacterConversion ANSI_To_TCHAR_Conversion; // typedef NCharacterConversion TCHAR_To_ANSI_Conversion; // typedef NCharacterConversion UNICHAR_To_ANSICHAR_Conversion; // typedef NCharacterConversion ANSICHAR_To_UNICHAR_Conversion; } #endif // NUNICODE_H nux-4.0.8+16.04.20160209/NuxCore/Character/NUTF.cpp0000644000015600001650000002360312656236757021467 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NUTF.h" namespace nux { NUTF8::NUTF8 (const UNICHAR *Source) { Convert (Source); } NUTF8::NUTF8 (const std::wstring &Source) { Convert (NUX_REINTERPRET_CAST (UNICHAR *, NUX_CONST_CAST (wchar_t *, Source.c_str() ) ) ); } void NUTF8::Convert (const UNICHAR *Source) { int NumBytes = 0; // *6 each UTF16 char can translate to up to 6 bytes in UTF8 // +1 for NULL char size_t Size = wcslen ( (wchar_t *) Source) * 6 + 1; utf8 = new char[Size]; memset (utf8, 0, Size); unsigned char TwoBytes[2]; TwoBytes[0] = '\0'; TwoBytes[1] = '\0'; utf8[0] = '\0'; // U-00000000 U-0000007F: 0xxxxxxx // U-00000080 U-000007FF: 110xxxxx 10xxxxxx // U-00000800 U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx // U-00010000 U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // U-00200000 U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // U-04000000 U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // The original specification of UTF-8 allowed for sequences of up to six bytes covering numbers up to 31 bits // (the original limit of the universal character set). However, UTF-8 was restricted by RFC 3629 to use only // the area covered by the formal Unicode definition, U+0000 to U+10FFFF, in November 2003. So UTF-8 code point is at most 4 bytes. for (size_t n = 0; Source[n] != 0; n++) { if (Source[n] <= 0x7F) { TwoBytes[0] = (char) Source[n]; STRCAT_S (utf8, Size, (const char *) &TwoBytes[0]); } else { // 11 valid bits 2 bytes if (Source[n] <= 0x7FF) { // Extract the 5 highest bits TwoBytes[0] = (char) (0xC0 + (Source[n] >> 6) ); NumBytes = 2; } // 16 valid bits 3 bytes else if (Source[n] <= 0xFFFF) { // Extract the highest 4 bits TwoBytes[0] = (char) (0xE0 + (Source[n] >> 12) ); NumBytes = 3; } // Unichar is only 16 bits. Do no continue because (Source[n] >> 18) does not make sense. // 21 valid bits 4 bytes else if (Source[n] <= 0x1FFFFF) { // Extract the highest 3 bits TwoBytes[0] = (char) (0xF0 + (Source[n] >> 18) ); NumBytes = 4; } // Split a 26 bit character into 5 bytes else if (Source[n] <= 0x3FFFFFF) { // Extract the highest 2 bits TwoBytes[0] = (char) (0xF8 + (Source[n] >> 24) ); NumBytes = 5; } // Split a 31 bit character into 6 bytes else if (Source[n] <= 0x7FFFFFFF) { // Extract the highest bit TwoBytes[0] = (char) (0xFC + (Source[n] >> 30) ); NumBytes = 6; } STRCAT_S (utf8, Size, (const char *) &TwoBytes[0]); // Extract the remaining bits - 6 bits at a time for (int i = 1, shift = (NumBytes - 2) * 6; shift >= 0; i++, shift -= 6) { TwoBytes[0] = (char) (0x80 + ( (Source[n] >> shift) & 0x3F) ); STRCAT_S (utf8, Size, (const char *) &TwoBytes[0]); } } } } // void NUTF8::Convert(const t_UTF32* Source) // { // int NumBytes = 0; // // int Size = 0; // while(Source[Size] != 0) // { // ++Size; // } // // *6: each UTF16 char can translate to up to 6 bytes in UTF8 // // +1: for NULL char // Size = Size * 6 + 1; // utf8 = new char[Size*sizeof(t_UTF32)]; // memset(utf8, 0, Size*sizeof(t_UTF32)); // // unsigned char TwoBytes[2]; // TwoBytes[0] = '\0'; TwoBytes[1] = '\0'; // // utf8[0] = '\0'; // // // U-00000000 U-0000007F: 0xxxxxxx // // U-00000080 U-000007FF: 110xxxxx 10xxxxxx // // U-00000800 U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx // // U-00010000 U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // // U-00200000 U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // // U-04000000 U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // // The original specification of UTF-8 allowed for sequences of up to six bytes covering numbers up to 31 bits // // (the original limit of the universal character set). However, UTF-8 was restricted by RFC 3629 to use only // // the area covered by the formal Unicode definition, U+0000 to U+10FFFF, in November 2003. So UTF-8 code point is at most 4 bytes. // // for(size_t n = 0; Source[n] != 0; n++) // { // if (Source[n] <= 0x7F) // { // TwoBytes[0] = (char)Source[n]; // STRCAT_S(utf8, Size, (const char*)&TwoBytes[0]); // } // else // { // // 11 valid bits 2 bytes // if (Source[n] <= 0x7FF) // { // // Extract the 5 highest bits // TwoBytes[0] = (char)(0xC0 + (Source[n] >> 6)); // NumBytes = 2; // } // // 16 valid bits 3 bytes // else if (Source[n] <= 0xFFFF) // { // // Extract the highest 4 bits // TwoBytes[0] = (char)(0xE0 + (Source[n] >> 12)); // NumBytes = 3; // } // // 21 valid bits 4 bytes // else if (Source[n] <= 0x1FFFFF) // { // // Extract the highest 3 bits // TwoBytes[0] = (char)(0xF0 + (Source[n] >> 18)); // NumBytes = 4; // } // // Split a 26 bit character into 5 bytes // else if (Source[n] <= 0x3FFFFFF) // { // // Extract the highest 2 bits // TwoBytes[0] = (char)(0xF8 + (Source[n] >> 24)); // NumBytes = 5; // } // // Split a 31 bit character into 6 bytes // else if (Source[n] <= 0x7FFFFFFF) // { // // Extract the highest bit // TwoBytes[0] = (char)(0xFC + (Source[n] >> 30)); // NumBytes = 6; // } // // STRCAT_S(utf8, Size, (const char*)&TwoBytes[0]); // // // Extract the remaining bits - 6 bits at a time // for(int i = 1, shift = (NumBytes-2)*6; shift >= 0; i++, shift -= 6) // { // TwoBytes[0] = (char)(0x80 + ((Source[n] >> shift) & 0x3F)); // STRCAT_S(utf8, Size, (const char*)&TwoBytes[0]); // } // } // } // } NUTF8::~NUTF8() { delete [] utf8; } NUTF8::operator const char* () { return utf8; } /////////////////////////////////////////////////////////////////////////////// // Convert each unicode character in the source to UTF-8 NUTF16::NUTF16 (const char *Source) { Convert (Source); } NUTF16::NUTF16 (const std::string &Source) { Convert (Source.c_str() ); } void NUTF16::Convert (const char *Source) { // U-00000000 U-0000007F: 0xxxxxxx // U-00000080 U-000007FF: 110xxxxx 10xxxxxx // U-00000800 U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx // U-00010000 U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // U-00200000 U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // U-04000000 U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx unsigned char MSB; int temp = 0; int numbytes = 0; // Number of bytes used to represent the unicode char int pos = 0; size_t len = strlen (Source) + 1; // +1 for NULL char unicode = new UNICHAR[len*6]; // Loop through the characters in the string and decode them for (size_t n = 0; n < len; ++n) { // Find the hexadecimal number following the equals sign MSB = Source[n]; if (MSB <= 0x7F) { unicode[pos++] = (UNICHAR) MSB; } else { // 2 bytes if (MSB >= 0xC0 && MSB <= 0xDF) { temp = (MSB - 0xC0) << 6; numbytes = 2; } // 3 bytes else if (MSB >= 0xE0 && MSB <= 0xEF) { temp = (MSB - 0xE0) << 12; numbytes = 3; } // 4 bytes else if (MSB >= 0xF0 && MSB <= 0xF7) { temp = (MSB - 0xF0) << 18; numbytes = 4; } // 5 bytes else if (MSB >= 0xF8 && MSB <= 0xFB) { temp = (MSB - 0xF8) << 24; numbytes = 5; } // 6 bytes else if (MSB >= 0xFC && MSB <= 0xFD) { temp = (MSB - 0xFC) << 30; numbytes = 6; } // Loop through the remaining hexadecimal numbers representing the next unicode character for (int i = 0, shift = (numbytes - 2) * 6; shift >= 0; i++, shift -= 6) { int nVal = ( ( (unsigned char) Source[n+1+i]) - 0x80 ) << shift; temp += nVal; } // Add the unicode character to the final string unicode[pos++] = (UNICHAR) temp; // Move the character index in the source to the next unicode character n += (numbytes - 1); } } } NUTF16::~NUTF16() { delete [] unicode; } NUTF16::operator const UNICHAR* () { return unicode; } } nux-4.0.8+16.04.20160209/NuxCore/LoggingWriter.h0000644000015600001650000000363712656236757021254 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_LOGGING_WRITER_H #define NUX_CORE_LOGGING_WRITER_H #include #include #include #include "Logger.h" /** * The Writer singleton is responsible for controlling where the * logging message go. For testing purposes it is able to define the logging * stream, normally a std::stringstream. * * The default behaviour is to output to std::cout. * * As far as logging the timestamp goes, we only go to second precision in the * logging format itself. If a high performance timer is needed it should be * managed by the caller. */ namespace nux { namespace logging { class Writer : boost::noncopyable { public: static Writer& Instance(); ~Writer(); void WriteMessage(Level severity, std::string const& module, std::string const& filename, int line_number, std::time_t timestamp, std::string const& message); void SetOutputStream(std::ostream& out); private: Writer(); private: class Impl; Impl* pimpl; }; } } #endif nux-4.0.8+16.04.20160209/NuxCore/OutputDevice.cpp0000644000015600001650000003105312656236757021435 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Parsing.h" #include #include namespace nux { #if defined(NUX_DEBUG) //! Create a backup copy of a file if it exist. The copy feature a timestamp in the filename. /*! @param Filename The name of the file to check. */ static void CreateBackupCopy (const TCHAR *Filename) { if (GFileManager.FileSize (Filename) > 0) { // Create string with system time to create a unique filename. unsigned int Year, Month, Day, Hour, Min, Sec, MSec; GetLocalTime (Year, Month, Day, Hour, Min, Sec, MSec); std::string Name, Extension; std::string file = Filename; size_t pos = file.rfind('.'); if (pos != std::string::npos) { Name = file.substr(0, pos); Extension = file.substr(pos + 1); } else { Name = file; } std::ostringstream s; s << std::setfill('0') << Name << "-backup-" << Year << "." << std::setw(2) << Month << "." << std::setw(2) << Day << "." << std::setw(2) << Hour << "." << std::setw(2) << Min << "." << std::setw(2) << Sec; if (Extension.size() ) { s << "." << Extension; } std::string BackupFilename = s.str(); GFileManager.Copy (BackupFilename.c_str(), Filename, true, true, NULL); } } #endif NUX_IMPLEMENT_GLOBAL_OBJECT (NullOutput); NUX_IMPLEMENT_GLOBAL_OBJECT (LogOutputRedirector); NUX_IMPLEMENT_GLOBAL_OBJECT (LogFileOutput); NUX_IMPLEMENT_GLOBAL_OBJECT (VisualOutputConsole) NUX_IMPLEMENT_GLOBAL_OBJECT (PrintfOutputConsole) LogOutputDevice::LogOutputDevice() : _object_destroyed (false) { _enabled = true; } LogOutputDevice::~LogOutputDevice() { _object_destroyed = true; } void LogOutputDevice::Shutdown() { _object_destroyed = true; } void LogOutputDevice::Flush() { } void LogOutputDevice::Enable () { _enabled = true; } void LogOutputDevice::Disable () { _enabled = false; } VARARG_BODY ( void /*FuncRet*/, LogOutputDevice::LogFunction/*FuncName*/, const TCHAR* /*FmtType*/, VARARG_EXTRA (int severity) /*ExtraDecl*/) { if (_object_destroyed) return; int BufferSize = 1024; int NewBufferSize = 0; TCHAR *Buffer = NULL; int Result = -1; while (Result == -1) { if (NewBufferSize) { TCHAR *temp = new TCHAR[NewBufferSize]; Memcpy (temp, Buffer, BufferSize); NUX_SAFE_DELETE_ARRAY (Buffer); Buffer = temp; BufferSize = NewBufferSize; } else { Buffer = new TCHAR[BufferSize]; } GET_VARARGS_RESULT (Buffer, BufferSize, BufferSize - 1, Fmt, Result); if (Result == -1) NewBufferSize = 2 * BufferSize; }; Buffer[Result] = 0; Serialize (Buffer, TEXT ("Nux"), severity); NUX_SAFE_DELETE_ARRAY (Buffer); } void LogFileOutput::Constructor() { m_LogSerializer = NULL; m_Opened = false; m_Closed = false; #if defined(NUX_DEBUG) // The Editor requires a fully qualified directory to not end up putting the log in various directories. m_Filename = GetProgramDirectory(); if ( (m_Filename[m_Filename.size()-1] != NUX_SLASH_CHAR) || (m_Filename[m_Filename.size()-1] != NUX_BACKSLASH_CHAR) ) m_Filename += (const TCHAR *) NUX_PATH_SEPARATOR_STRING; m_Filename += GetLogDirectory(); // Create the directory tree where the Logs file will be stored. GFileManager.MakeDirectory (m_Filename.c_str(), 1); m_Filename += (const TCHAR *) NUX_PATH_SEPARATOR_STRING; m_Filename += TEXT ("nux"); m_Filename += TEXT (".log"); // if the file already exists, create a backup as we are going to overwrite it if (!m_Opened) { CreateBackupCopy (m_Filename.c_str() ); } // Open log file. m_LogSerializer = GFileManager.CreateFileWriter (m_Filename.c_str(), NSerializer::Read | NSerializer::Write | NSerializer::OverWriteReadOnly | (m_Opened ? NSerializer::Append : 0) ); if (m_LogSerializer) { m_Opened = true; #if UNICODE && !NUX_LOG_FILE_ANSI m_LogSerializer->Serialize ( (void *) &NUX_UTF16_BE[1], NUX_UTF16_BE[0] /*size*/ ); #endif LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("Log file open, %s"), GetFormattedLocalTime().c_str()); } else { m_Closed = true; } #endif } void LogFileOutput::Destructor() { Shutdown(); } /*! Closes output device and cleans up. This can't happen in the destructor as we have to call "delete" which cannot be done for static/ global objects. */ void LogFileOutput::Shutdown() { if (m_LogSerializer) { LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("Log file closed, %s"), GetFormattedLocalTime().c_str()); Flush(); delete m_LogSerializer; m_LogSerializer = NULL; } m_Closed = true; } void LogFileOutput::Flush() { if (m_LogSerializer) { m_LogSerializer->Flush(); } } //! Write data to the output log file. /*! @param log_data Text to log. @param log_prefix Prefix for the text */ void LogFileOutput::Serialize (const TCHAR *log_data, const TCHAR *log_prefix, int /* severity */) { if (!_enabled) return; if (_object_destroyed) return; if (m_LogSerializer) { #if UNICODE && NUX_LOG_FILE_ANSI ANSICHAR ACh[1024]; INT DataOffset = 0; INT i; while (log_data[DataOffset]) { for (i = 0; i < NUX_ARRAY_COUNT (ACh) && log_data[DataOffset]; i++, DataOffset++) { ACh[i] = ConvertTCHARToAnsiChar (log_data[DataOffset]); } // serialize chunks of 1024 characters m_LogSerializer->Serialize (ACh, i); }; for (i = 0; NUX_LINE_TERMINATOR[i]; i++) { ACh[i] = NUX_LINE_TERMINATOR[i]; } m_LogSerializer->Serialize (ACh, i); #else std::string Raw = std::string (log_prefix) + std::string (TEXT (": ") ) + std::string (log_data) + std::string (NUX_LINE_TERMINATOR); SerializeRaw (Raw.c_str() ); #endif } } void LogFileOutput::SerializeRaw (const TCHAR *log_data) { unsigned int s = (unsigned int) StringLength (log_data) * sizeof (TCHAR); m_LogSerializer->Serialize (NUX_CONST_CAST (TCHAR *, log_data), s); } void LogOutputRedirector::Constructor() { } void LogOutputRedirector::Destructor() { Shutdown(); } void LogOutputRedirector::AddOutputDevice (LogOutputDevice *OutputDevice) { if ( OutputDevice ) { if (std::find (OutputDevices.begin(), OutputDevices.end(), OutputDevice) != OutputDevices.end() ) return; OutputDevices.push_back (OutputDevice); } } void LogOutputRedirector::RemoveOutputDevice (LogOutputDevice *OutputDevice) { std::vector::iterator it = std::find (OutputDevices.begin(), OutputDevices.end(), OutputDevice); OutputDevices.erase (it); } bool LogOutputRedirector::IsRedirectingTo (LogOutputDevice *OutputDevice) { if (std::find (OutputDevices.begin(), OutputDevices.end(), OutputDevice) != OutputDevices.end() ) return true; return false; } void LogOutputRedirector::Serialize (const TCHAR *log_data, const TCHAR *log_prefix, int severity) { if (!_enabled) return; for (unsigned int OutputDeviceIndex = 0; OutputDeviceIndex < OutputDevices.size(); OutputDeviceIndex++) { OutputDevices[OutputDeviceIndex]->Serialize (log_data, log_prefix, severity); } } void LogOutputRedirector::Flush() { for (unsigned int OutputDeviceIndex = 0; OutputDeviceIndex < OutputDevices.size(); OutputDeviceIndex++) { OutputDevices[OutputDeviceIndex]->Flush(); } } void LogOutputRedirector::Shutdown() { for (unsigned int OutputDeviceIndex = 0; OutputDeviceIndex < OutputDevices.size(); OutputDeviceIndex++) { OutputDevices[OutputDeviceIndex]->Shutdown(); // do not delete the output device. This is the responsibility of the owwners. } OutputDevices.clear(); } void VisualOutputConsole::Constructor() {} void VisualOutputConsole::Destructor() {} //! Write data to visual studio output debug console. /*! @param log_data Text to log. @param log_prefix Prefix for the text */ #if defined(NUX_OS_WINDOWS) void VisualOutputConsole::Serialize(const TCHAR* text, const TCHAR* log_prefix, int severity) { if (!_enabled) return; TCHAR Temp[4096]; Snprintf (Temp, 4096, 4096 - 1, TEXT ("%s: %s%s"), log_prefix, text, NUX_LINE_TERMINATOR); OutputDebugString (Temp); } #else void VisualOutputConsole::Serialize(const TCHAR * /* text */, const TCHAR * /* log_prefix */, int /* severity */) { } #endif void PrintfOutputConsole::Constructor() {} void PrintfOutputConsole::Destructor() {} //! Write data to visual studio output debug console. /*! @param log_data Text to log. @param log_prefix Prefix for the text */ void PrintfOutputConsole::Serialize (const TCHAR *text, const TCHAR *log_prefix, int severity) { if (!_enabled) return; TCHAR Temp[4096]; #if defined (NUX_OS_WINDOWS) Snprintf (Temp, 4096, 4096 - 1, TEXT ("%s: %s%s"), log_prefix, text, NUX_LINE_TERMINATOR); HANDLE hConsole; hConsole = GetStdHandle(STD_OUTPUT_HANDLE); if (severity == NUX_MSG_SEVERITY_CRITICAL) { SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_INTENSITY|BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY); } else if (severity == NUX_MSG_SEVERITY_ALERT) { SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_INTENSITY); } else if (severity == NUX_MSG_SEVERITY_WARNING) { SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY); } else if (severity == NUX_MSG_SEVERITY_INFO) { SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN|FOREGROUND_INTENSITY); } else if (severity == NUX_MSG_SEVERITY_NONE) { SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY); } printf ("%s", &Temp[0]); SetConsoleTextAttribute(hConsole, FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE); #elif defined (NUX_OS_LINUX) // {attr} is one of following // // 0 Reset All Attributes (return to normal mode) // 1 Bright (Usually turns on BOLD) // 2 Dim // 3 Underline // 5 Blink // 7 Reverse // 8 Hidden // // {fg} is one of the following // // 30 Black // 31 Red // 32 Green // 33 Yellow // 34 Blue // 35 Magenta // 36 Cyan // 37 White (greyish) // 38 White // // {bg} is one of the following // // 40 Black // 41 Red // 42 Green // 43 Yellow // 44 Blue // 45 Magenta // 46 Cyan // 47 White (greyish) // 48 White int Foreground = 38; int Background = 48; int Bold = 0; if (severity == NUX_MSG_SEVERITY_CRITICAL) { Foreground = 31; Background = 44; Bold = 1; } else if (severity == NUX_MSG_SEVERITY_ALERT) { Foreground = 31; Bold = 1; } else if (severity == NUX_MSG_SEVERITY_WARNING) { Foreground = 33; Bold = 1; } else if (severity == NUX_MSG_SEVERITY_INFO) { Foreground = 32; Bold = 1; } else if (severity == NUX_MSG_SEVERITY_NONE) { Foreground = 38; Bold = 0; } Snprintf (Temp, 4096, 4096 - 1, TEXT ("%c[%d;%d;%dm%s: %s%c[%d;%d;%dm%s"), 0x1B, Bold, Foreground, Background, log_prefix, text, 0x1B, 0, 38, 48, NUX_LINE_TERMINATOR); printf ("%s", &Temp[0]); #else Snprintf (Temp, 4096, 4096 - 1, TEXT ("%s: %s%s"), log_prefix, text, NUX_LINE_TERMINATOR); printf ("%s", &Temp[0]); #endif } void NullOutput::Constructor() {} void NullOutput::Destructor() {} } nux-4.0.8+16.04.20160209/NuxCore/Object.h0000644000015600001650000002011212656236757017662 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2010-2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUXCORE_OBJECT_H #define NUXCORE_OBJECT_H #include #include #include #include #include "ObjectType.h" #include "Property.h" #include "PropertyTraits.h" #define NUX_FILE_LINE_PROTO const char* __Nux_FileName__=__FILE__, int __Nux_LineNumber__ = __LINE__ #define NUX_FILE_LINE_DECL const char* __Nux_FileName__, int __Nux_LineNumber__ #define NUX_FILE_LINE_PARAM __Nux_FileName__, __Nux_LineNumber__ #define NUX_TRACKER_LOCATION __FILE__, __LINE__ #define OnDestroyed object_destroyed namespace nux { template class ObjectPtr; template class ObjectWeakPtr; class ObjectStats { NUX_DECLARE_GLOBAL_OBJECT (ObjectStats, GlobalSingletonInitializer); public: typedef std::list AllocationList; AllocationList _allocation_list; int _total_allocated_size; //! Total allocated memory size in bytes. int _number_of_objects; //! Number of allocated objects; }; #define GObjectStats NUX_GLOBAL_OBJECT_INSTANCE(nux::ObjectStats) //! Base class of heap allocated objects. /*! Trackable does not implement reference counting. It only defines the API. It is up to the class that inherit from Trackable to implement the reference counting. */ class Trackable: public nux::Introspectable, public sigc::trackable, public boost::noncopyable { public: NUX_DECLARE_ROOT_OBJECT_TYPE (Trackable); //! Test if object reference is owned. /* @return True if the object reference is owned. */ bool OwnsTheReference(); //! Test if object was allocated dynamically. /* @return True if the object was allocated dynamically. */ bool IsHeapAllocated(); //! Test if object was allocated dynamically. /* @return True if the object was allocated dynamically. */ bool IsDynamic() const; //! Increase the reference count. /* Widget are typically created and added to containers. It is decided that when widgets are created, they should have a floating reference and their reference count is set to 1. { Button* button = new Button(); // button ref_cout = 1, floating = true; container->AddButton(button); // button has a floating reference; when container call button->ref() the ref count // of button remains at 1 but the floating reference is set to false. From now on, // calling button->ref will always increase the ref count (since button no longer has a floating reference). } It is best to pair calls to ref() with unref() when it comes to widgets. So if a widget was not added to a container and so it still has a floating reference, then call Dispose(). Dispose does some sanity check; it verifies that: ref_count == 1 floating == true If these conditions are verified, dispose will cause the object to be destroyed. Calling unref() on an object that has a floating reference will trigger a warning/error in order to invite the developer. The developer can either ref the object first before calling unref or simply not create the widget since it does not appear to have been used. During development it often happen that one forget to dispose an object with a floating reference. Assuming that all functions that receive a reference counted object properly call ref on the object and that the compiler can detect unused variables, then the developer should have a way to detect reference counted objects that are not owned. It is up to the developer to properly handle these objects. @return True if the object has been referenced. */ virtual bool Reference(); //! Decrease the reference count. /*! @return True if the object has been destroyed */ virtual bool UnReference(); //! Mark the object as owned. /*! If this object is not owned, calling SinkReference() as the same effect as calling Reference(). @return True if the object was not owned previously */ virtual bool SinkReference(); //! Destroy and object that has a floating reference. /*! @return True if the object has been destroyed */ virtual bool Dispose(); //! Return the size of allocated for this object. /*! @return The size allocated for this object. */ virtual int GetObjectSize (); static std::new_handler set_new_handler (std::new_handler handler); static void *operator new (size_t size); #if (__GNUC__ < 4 && __GNUC_MINOR__ < 4) static void *operator new (size_t size, void *ptr); #endif static void operator delete (void *ptr); protected: Trackable(); virtual ~Trackable() = 0; void SetOwnedReference (bool b); int _heap_allocated; private: static std::new_handler _new_current_handler; bool _owns_the_reference; int _size_of_this_object; }; //! The base class of Nux objects. class Object: public Trackable { public: NUX_DECLARE_OBJECT_TYPE (BaseObject, Trackable); //! Constructor Object (bool OwnTheReference = true, NUX_FILE_LINE_PROTO); //! Increase reference count. /*! @return True if the object has successfully referenced. */ bool Reference(); //! Decrease reference count. /*! @return True if the object reference count has reached 0 and the object has been destroyed. */ bool UnReference(); //! Mark the object as owned. /*! If this object is not owned, calling SinkReference() as the same effect as calling Reference(). @return True if the object was not owned previously */ virtual bool SinkReference(); //! Destroy and object that has a floating reference. /*! @return True is the object has been destroyed */ virtual bool Dispose(); //! Get the reference count of this object. /*! @return The reference count of this object. */ int GetReferenceCount() const; //! Get the number of ObjectPtr holding this object. /*! @return The number of ObjectPtr holding this object. */ int ObjectPtrCount() const; //! Signal emitted immediately before the object is destroyed. sigc::signal object_destroyed; std::string GetAllocationLocation() const; std::string GetTypeName() const; protected: //! Private destructor. /* Private destructor. Ensure that Object cannot be created on the stack (only on the heap), but objects that inherits from Object can stil be created on the stack or on the heap. (MEC++ item27) */ virtual ~Object(); private: //! Destroy the object. void Destroy(); Object (const Object &); Object &operator = (const Object &); NThreadSafeCounter* reference_count_; //!< Number of ObjectPtr hosting the object. NThreadSafeCounter* objectptr_count_; std::string allocation_location_; std::string allocation_stacktrace_; template friend class ObjectPtr; template friend class ObjectWeakPtr; friend class ObjectStats; }; } #endif // NUXOBJECT_H nux-4.0.8+16.04.20160209/NuxCore/FilePath.cpp0000644000015600001650000001026212656236757020510 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "FilePath.h" namespace nux { FilePath::FilePath() { if (std::find (m_SearchPath.begin(), m_SearchPath.end(), TEXT ("") ) != m_SearchPath.end() ) return; m_SearchPath.push_back (TEXT ("") ); // for fully qualified path } FilePath::~FilePath() { } void FilePath::AddSearchPath (const std::string &searchpath) { if (std::find (m_SearchPath.begin(), m_SearchPath.end(), searchpath) != m_SearchPath.end() ) return; m_SearchPath.push_back (searchpath); } void FilePath::AddSearchPath (const std::vector& searchpath) { for (unsigned int i = 0; i < searchpath.size(); i++) { if (std::find (m_SearchPath.begin(), m_SearchPath.end(), searchpath[i]) == m_SearchPath.end() ) m_SearchPath.push_back (searchpath[i]); } } std::string FilePath::GetPathToFile (const TCHAR *filename) const { std::string FileName = GetFile (filename); size_t loc = FileName.rfind(TEXT('\\'), 0); if (loc == std::string::npos) { loc = FileName.rfind(TEXT('/'), 0); } if (loc != std::string::npos) FileName = FileName.substr(0, loc); else FileName = std::string(TEXT (".")); return FileName; } std::string FilePath::GetFile (const TCHAR *filename) const { NUX_RETURN_VALUE_IF_NULL (filename, std::string (TEXT ("") ) ); if (std::string (filename) == std::string (TEXT ("") ) ) return std::string (TEXT ("") ); std::string FileName = filename; if (GFileManager.FileExist(FileName.c_str() ) ) return FileName; for (unsigned int i = 0; i < m_SearchPath.size(); i++) { if (m_SearchPath[i].size() == 0) continue; std::string FilePath; char last = m_SearchPath[i][m_SearchPath[i].size() - 1]; if (last == TEXT('/') || last == TEXT('\\')) FilePath = m_SearchPath[i] + filename; else FilePath = m_SearchPath[i] + NUX_PATH_SEPARATOR_STRING + filename; if (GFileManager.FileExist (FilePath.c_str() ) ) return FilePath; } // Still not found. Then peel off the root of the filename and append our custom search path. // filename = "MediaProg/UI3DGraphics/MyFile.txt" // search for: // CustomPath0/UI3DGraphics/MyFile.txt // CustomPath1/UI3DGraphics/MyFile.txt // CustomPath2/UI3DGraphics/MyFile.txt // CustomPath3/UI3DGraphics/MyFile.txt // CustomPath0/MyFile.txt // CustomPath1/MyFile.txt // CustomPath2/MyFile.txt // CustomPath3/MyFile.txt // FileName = filename; for (size_t i = 0; i < m_SearchPath.size(); i++) { size_t pos; std::string PathName; while (FileName.find_first_of(TEXT ("\\/")) != std::string::npos) { pos = FileName.find_first_of(TEXT ("\\/")) + 1; FileName = FileName.substr(pos, FileName.length() - pos); char last = m_SearchPath[i][m_SearchPath[i].size() - 1]; if (last == TEXT('/') || last == TEXT('\\')) PathName = m_SearchPath[i] + FileName; else PathName = m_SearchPath[i] + NUX_PATH_SEPARATOR_STRING + FileName; if (GFileManager.FileExist (PathName.c_str() ) ) return PathName; } } nuxDebugMsg (TEXT ("[FilePath::GetFile] Cannot find file: %s"), filename); return std::string (TEXT ("") ); } } nux-4.0.8+16.04.20160209/NuxCore/Size.h0000644000015600001650000000212312656236757017370 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUX_CORE_SIZE_H #define NUX_CORE_SIZE_H namespace nux { class Size { public: Size(); Size(int w, int h); int width; int height; }; bool operator == (const Size& lhs, const Size& rhs); bool operator != (const Size& lhs, const Size& rhs); } #include "Size-inl.h" #endif // SIZE_H nux-4.0.8+16.04.20160209/NuxCore/PropertyTraits.h0000644000015600001650000001426112656236757021477 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #if defined(NUX_OS_WINDOWS) #pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list #endif #ifndef NUXCORE_PROPERTY_TRAITS_H #define NUXCORE_PROPERTY_TRAITS_H #include #include #include #include "Color.h" namespace nux { namespace type { /** * Here we want to have only explict type support, to avoid someone using the * system with something we haven't though of and getting upset when if it * doesn't work properly. */ template ::value> struct PropertyTrait { /** * Expected content: * * typedef T ValueType; * - used to make sure that there is a definition of the PropertyTrait * for the particular value of T. * * static std::string to_string(T const& value) * - used to convert the type to a string * * static std::pair from_string(std::string const& serialized_form) * - If the serialized form is convertable to T, then we get: * (value, true) * - If it is not convertable we get: * (T(), false) */ }; /** * The serializable_impl template has different signatures than the standard * Serializable traits class to avoid the generalised template being used as a * traits type when we really don't want it being used in that way, but we do * want a generalized implementation for the types we do care about. */ template struct serializable_impl { typedef std::pair ResultType; static std::string to_string_impl(T const& value) { return boost::lexical_cast(value); } static ResultType from_string_impl(std::string const& serialized_form) { try { return ResultType(boost::lexical_cast(serialized_form), true); } catch (const boost::bad_lexical_cast& ) { return std::make_pair(T(), false); } } }; template struct PropertyTrait { typedef ENUM ValueType; typedef serializable_impl Serialiser; typedef std::pair ResultType; static std::string to_string(ENUM value) { return Serialiser::to_string_impl(value); } static std::pair from_string(std::string const& serialized_form) { Serialiser::ResultType result = Serialiser::from_string_impl(serialized_form); return ResultType(static_cast(result.first), result.second); } }; template <> struct PropertyTrait { typedef int ValueType; static std::string to_string(int value) { return serializable_impl::to_string_impl(value); } static std::pair from_string(std::string const& serialized_form) { return serializable_impl::from_string_impl(serialized_form); } }; template <> struct PropertyTrait { typedef unsigned ValueType; static std::string to_string(unsigned value) { return serializable_impl::to_string_impl(value); } static std::pair from_string(std::string const& serialized_form) { return serializable_impl::from_string_impl(serialized_form); } }; template <> struct PropertyTrait { typedef float ValueType; static std::string to_string(float value) { return serializable_impl::to_string_impl(value); } static std::pair from_string(std::string const& serialized_form) { return serializable_impl::from_string_impl(serialized_form); } }; template <> struct PropertyTrait { typedef double ValueType; static std::string to_string(double value) { return serializable_impl::to_string_impl(value); } static std::pair from_string(std::string const& serialized_form) { return serializable_impl::from_string_impl(serialized_form); } }; template <> struct PropertyTrait { typedef bool ValueType; static std::string to_string(bool value) { return value ? "true" : "false"; } static std::pair from_string(std::string const& serialized_form) { if (serialized_form == "true") { return std::make_pair(true, true); } else if (serialized_form == "false") { return std::make_pair(false, true); } else { return std::make_pair(false, false); } } }; template <> struct PropertyTrait { typedef std::string ValueType; static std::string to_string(std::string const& value) { return value; } static std::pair from_string(std::string const& serialized_form) { return std::make_pair(serialized_form, true); } }; // template <> // struct PropertyTrait // { // typedef Color ValueType; // static std::string to_string(Color value) // { // std::string str = std::string("[") + // serializable_impl::to_string_impl(value.red) + std::string(" ") + // serializable_impl::to_string_impl(value.green) + std::string(" ") + // serializable_impl::to_string_impl(value.blue) + std::string(" ") + // serializable_impl::to_string_impl(value.alpha) + std::string(" ") + // std::string("]"); // return str; // } // static std::pair from_string(std::string const& serialized_form) // { // // todo // return std::make_pair(color::Red, true); // } // }; } } #endif nux-4.0.8+16.04.20160209/NuxCore/EasingCurve.h0000644000015600001650000000333412656236757020676 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_EASING_CURVE_H #define NUX_CORE_EASING_CURVE_H namespace nux { namespace animation { class EasingCurve { public: #if defined(NUX_OS_WINDOWS) && !defined(NUX_VISUAL_STUDIO_VC11) enum Type #else enum class Type #endif { Linear, InQuad, OutQuad, InOutQuad, BackEaseIn, BackEaseOut, BackEaseInOut, BounceIn, BounceOut, BounceInOut, ExpoEaseIn, ExpoEaseOut }; typedef double (*EasingFunction)(double); explicit EasingCurve(Type type = Type::Linear); // progress is expected to be between zero and one inclusive. // // Values less than zero will return zero will return zero, and // greater than one will return one. // // The returned value may be greater than one, or less than zero for some // special curves. double ValueForProgress(double progress); private: EasingFunction func_; }; }} #endif nux-4.0.8+16.04.20160209/NuxCore/AsyncFileWriter.h0000644000015600001650000000322012656236757021527 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUXCORE_ASYNC_FILE_WRITER_H #define NUXCORE_ASYNC_FILE_WRITER_H #include #include namespace nux { /** * Write to a file asynchronously. * * This uses the GIO async functions, and as such depend on the gobject main * loop. */ class AsyncFileWriter { public: AsyncFileWriter(std::string const& filename); // Destructor kills any pending async requests, and close the file // synchronously if it is open. ~AsyncFileWriter(); // Queue the data for writing. It'll happen some time. void Write(std::string const& data); // Close the file asynchronously. When the file is closed, the closed // signal is emitted. void Close(); bool IsClosing() const; sigc::signal opened; sigc::signal closed; private: class Impl; Impl* pimpl; }; } #endif nux-4.0.8+16.04.20160209/NuxCore/ThreadWin.cpp0000644000015600001650000002653312656236757020711 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "TextString.h" #include "ThreadWin.h" namespace nux { #define NUX_ATOMOP_ITERLOCKED_INCREMENT InterlockedIncrement #define NUX_ATOMOP_ITERLOCKED_DECREMENT InterlockedDecrement #define NUX_ATOMOP_ITERLOCKED_EXCHANGED InterlockedExchange #define NUX_ATOMOP_ITERLOCKED_VALUE long NThreadSafeCounter::Increment() { return NUX_ATOMOP_ITERLOCKED_INCREMENT ( &m_Counter ); } long NThreadSafeCounter::Decrement() { return NUX_ATOMOP_ITERLOCKED_DECREMENT ( &m_Counter ); } long NThreadSafeCounter::Set (long i) { return NUX_ATOMOP_ITERLOCKED_EXCHANGED ( &m_Counter, i ); } long NThreadSafeCounter::GetValue() const { return m_Counter; } long NThreadSafeCounter::operator ++ () { return Increment(); } long NThreadSafeCounter::operator -- () { return Decrement(); } bool NThreadSafeCounter::operator == (long i) { return (m_Counter == i); } unsigned int NThreadLocalStorage::m_TLSIndex[NThreadLocalStorage::NbTLS]; BOOL NThreadLocalStorage::m_TLSUsed[NThreadLocalStorage::NbTLS]; NThreadLocalStorage::TLS_ShutdownCallback NThreadLocalStorage::m_TLSCallbacks[NThreadLocalStorage::NbTLS]; // http://msdn2.microsoft.com/en-us/library/xcb2z8hs(VS.80).aspx // // Usage: SetWin32ThreadName (-1, "MainThread"); // #define MS_VC_EXCEPTION 0x406D1388 typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; void SetWin32ThreadName (DWORD dwThreadID, LPCSTR szThreadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = szThreadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException ( MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (DWORD), (ULONG_PTR *) &info ); } __except (EXCEPTION_CONTINUE_EXECUTION) { } } BOOL NThreadLocalStorage::RegisterTLS(unsigned int index, NThreadLocalStorage::TLS_ShutdownCallback shutdownCallback) { if (m_TLSUsed[index]) { nuxDebugMsg("[NThreadLocalStorage::RegisterTLS] TLS has already been registered."); return TRUE; } if (!m_TLSUsed[index]) { m_TLSIndex[index] = TlsAlloc(); if (m_TLSIndex[index] == TLS_OUT_OF_INDEXES) { nuxAssertMsg (0, TEXT ("[NThreadLocalStorage::RegisterTLS] Out of TLS index.") ); } m_TLSUsed[index] = TRUE; m_TLSCallbacks[index] = shutdownCallback; return TRUE; } else { return FALSE; } } void NThreadLocalStorage::Initialize() { for (unsigned int i = 0; i < NThreadLocalStorage::NbTLS; i++) { m_TLSUsed[i] = FALSE; // Fill the array with invalid values m_TLSIndex[i] = NThreadLocalStorage::InvalidTLS; // invalid index } } void NThreadLocalStorage::Shutdown() { ThreadShutdown(); } void NThreadLocalStorage::ThreadInit() { } void NThreadLocalStorage::ThreadShutdown() { TLS_ShutdownCallback *callback = m_TLSCallbacks; for (unsigned int i = 0; i < NThreadLocalStorage::NbTLS; ++i, ++callback) { if (*callback) { (**callback) (); } } } NUX_IMPLEMENT_ROOT_OBJECT_TYPE (NThread); NThread::NThread() : m_ThreadState (THREADINIT) { m_pThreadFunc = NThread::EntryPoint; // Can call Detach() also. } NThread::NThread (LPTHREAD_START_ROUTINE lpExternalRoutine) { Attach (lpExternalRoutine); } NThread::~NThread() { CloseHandle (m_ThreadCtx.m_hThread); } ThreadState NThread::Start ( void *arg ) { if ( m_ThreadCtx.m_hThread == 0) { m_ThreadCtx.m_pUserData = arg; m_ThreadCtx.m_hThread = CreateThread (NULL, 0, m_pThreadFunc, this, 0 /*CREATE_SUSPENDED*/, (LPDWORD) &m_ThreadCtx.m_dwTID); if (m_ThreadCtx.m_hThread != 0) { //ResumeStart(); m_ThreadState = THREADINIT; m_ThreadCtx.m_dwExitCode = (unsigned int) - 1; return m_ThreadState; } else { nuxDebugMsg (TEXT ("[NThread::Start] Cannot start thread: %s"), inlGetSystemErrorMessage() ); m_ThreadState = THREAD_START_ERROR; return m_ThreadState; } } return m_ThreadState; } ThreadState NThread::Stop(bool bForceKill) { // From MSDN // TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code and its initial stack is not deallocated. DLLs attached to the thread are not notified that the thread is terminating. // TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems: // If the target thread owns a critical section, the critical section will not be released. // If the target thread is allocating memory from the heap, the heap lock will not be released. // If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent. // If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL. // Attention: Calling Stop from another thread is not going to free the stack of this thread. // the stack is freed only if the thread exits by itself. if (m_ThreadCtx.m_hThread) { BOOL success = GetExitCodeThread(m_ThreadCtx.m_hThread, (LPDWORD) &m_ThreadCtx.m_dwExitCode); if ((m_ThreadCtx.m_dwExitCode == STILL_ACTIVE) && bForceKill) { // This will forcibly kill the thread! Read the doc on TerminateThread to find out about the consequences. TerminateThread(m_ThreadCtx.m_hThread, unsigned int (-1)); CloseHandle(m_ThreadCtx.m_hThread); } m_ThreadCtx.m_hThread = NULL; } m_ThreadState = THREADSTOP; return m_ThreadState; } ThreadState NThread::Suspend() { unsigned int ret = SuspendThread(m_ThreadCtx.m_hThread); if (ret == 0xFFFFFFFF) { nuxDebugMsg(TEXT("[NThread::Suspend] Cannot suspend thread: %s"), inlGetSystemErrorMessage()); return THREAD_SUSPEND_ERROR; } m_ThreadState = THREADSUSPENDED; return m_ThreadState; } ThreadState NThread::Resume() { unsigned int ret = ResumeThread(m_ThreadCtx.m_hThread); if (ret == 0xFFFFFFFF) { nuxDebugMsg(TEXT("[NThread::Suspend] Cannot resume thread: %s"), inlGetSystemErrorMessage()); return THREAD_RESUME_ERROR; } if (ret == 1) { // If the return value is 1, the specified thread was suspended but was restarted. m_ThreadState = THREADRUNNING; } if (ret > 1) { // If the return value is greater than 1, the specified thread is still suspended. m_ThreadState = THREADSUSPENDED; } return m_ThreadState; } // go from suspended to thread start ThreadState NThread::ResumeStart() { m_ThreadState = THREADINIT; unsigned int ret = ResumeThread(m_ThreadCtx.m_hThread); if (ret == 0xFFFFFFFF) { nuxDebugMsg(TEXT("[NThread::ResumeExit] Cannot resume thread: %s"), inlGetSystemErrorMessage()); return THREAD_RESUME_ERROR; } if (ret == 1) { // If the return value is 1, the specified thread was suspended but was restarted. m_ThreadState = THREADINIT; } if (ret > 1) { nuxAssert(0); // should not happen // If the return value is greater than 1, the specified thread is still suspended. m_ThreadState = THREADINIT; } return m_ThreadState; } // go from suspended to thread exit ThreadState NThread::ResumeExit() { m_ThreadState = THREADSTOP; unsigned int ret = ResumeThread(m_ThreadCtx.m_hThread); if (ret == 0xFFFFFFFF) { nuxDebugMsg(TEXT("[NThread::ResumeExit] Cannot resume thread: %s"), inlGetSystemErrorMessage()); return THREAD_RESUME_ERROR; } if (ret == 1) { // If the return value is 1, the specified thread was suspended but was restarted. m_ThreadState = THREADSTOP; } if (ret > 1) { nuxAssert(0); // should not happen // If the return value is greater than 1, the specified thread is still suspended. m_ThreadState = THREADSTOP; } return m_ThreadState; } DWORD WINAPI NThread::EntryPoint(void *pArg) { NThread *pParent = reinterpret_cast (pArg); if (pParent == 0) { nuxDebugMsg(TEXT("[NThread::EntryPoint] Invalid pointer. The thread will exit.")); return 0; } if (!pParent->ThreadCtor()) { // return another message saying the thread could not execute due to error in ThreadCtor; return 0; } pParent->Run(pParent->m_ThreadCtx.m_pUserData); pParent->ThreadDtor(); return 0; } unsigned int NThread::GetExitCode() const { if ( m_ThreadCtx.m_hThread ) GetExitCodeThread (m_ThreadCtx.m_hThread, (LPDWORD) &m_ThreadCtx.m_dwExitCode); return m_ThreadCtx.m_dwExitCode; } HANDLE NThread::GetThreadHandle() { return m_ThreadCtx.m_hThread; } unsigned int NThread::GetThreadId() { return (unsigned int)m_ThreadCtx.m_dwTID; } ThreadState NThread::GetThreadState() const { return m_ThreadState; } void NThread::SetThreadState(ThreadState state) { m_ThreadState = state; } void NThread::SetThreadName(const TCHAR *ThreadName) { SetWin32ThreadName (GetThreadId(), TCHAR_TO_ANSI (ThreadName) ); m_ThreadName = ThreadName; } const std::string& NThread::GetThreadName() const { return m_ThreadName; } ThreadWaitResult NThread::JoinThread(NThread *thread, unsigned int milliseconds) { if (thread == NULL) { return THREAD_WAIT_RESULT_FAILED; } unsigned int result = WaitForSingleObject(thread->GetThreadHandle(), milliseconds); switch(result) { case WAIT_OBJECT_0: return THREAD_WAIT_RESULT_COMPLETED; case WAIT_ABANDONED: return THREAD_WAIT_RESULT_ABANDONED; case WAIT_TIMEOUT: return THREAD_WAIT_RESULT_TIMEOUT; case WAIT_FAILED: default: return THREAD_WAIT_RESULT_FAILED; } } } nux-4.0.8+16.04.20160209/NuxCore/Parsing.h0000644000015600001650000002164312656236757020071 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NPARSING_H #define NPARSING_H namespace nux { //! Parse a stream of characters and look for a string of TCHAR at the start of the stream. /*! If the string is found, Stream points to the next character after the string. Space and tab characters at the beginning of the stream are ignored. @param Stream Character stream to search. @param Match Token to match. @return TRUE if the character string is found at the start of the stream (excluding space and tab characters). */ bool ParseCommand (const TCHAR **Stream, const TCHAR *Match); //! Parse a stream of characters and look for a t_32 value after the token string. /*! Parse a unsigned int after the named token. @param stream Character stream to search. @param token Token to match. @return True if the character string is found at the start of the stream (excluding space and tab characters). */ bool Parse_u32 (const TCHAR *stream, const TCHAR *Match, DWORD &value); //! Parses a string of N character from a character stream after a named token. /*! Parses a string from a character stream. @param Stream Character stream to search. @param Match Token to match. @param Value Buffer containing the parsed value. @param Size The size of the Value buffer, in characters. @param MaxLen Max number of character to return. @return TRUE if the token is found inside the stream. */ bool Parse_tchar (const TCHAR *stream, const TCHAR *Match, TCHAR *value, int size, int MaxLen); //! Parse a BYTE after the named token. /*! Parse a BYTE after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value Buffer containing the parsed value. @return TRUE if the token is found inside the stream. */ bool Parse_u8 (const TCHAR *Stream, const TCHAR *Match, BYTE &Value); //! Parse a signed BYTE after the named token. /*! Parse a signed BYTE after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed signed BYTE @return TRUE if the token is found inside the stream. */ bool Parse_s8 (const TCHAR *Stream, const TCHAR *Match, SBYTE &Value); //! Parse a WORD after the named token. /*! Parse a WORD after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed WORD @return TRUE if the token is found inside the stream. */ bool Parse_u16 (const TCHAR *Stream, const TCHAR *Match, WORD &Value); //! Parse a signed WORD after the named token. /*! Parse a signed WORD after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed signed WORD @return TRUE if the token is found inside the stream. */ bool Parse_s16 (const TCHAR *Stream, const TCHAR *Match, SWORD &Value); //! Parse a floating point value after the named token. /*! Parse a floating point value after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed floating point value @return TRUE if the token is found inside the stream. */ bool Parse_float (const TCHAR *Stream, const TCHAR *Match, float &Value); //! Parse a double WORD after the named token. /*! Parse a double WORD after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed double WORD @return TRUE if the token is found inside the stream. */ bool Parse_int (const TCHAR *Stream, const TCHAR *Match, int &Value); //! Parse a std::string after the named token. /*! Parse a std::string after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed std::string @return TRUE if the token is found inside the stream. */ bool Parse_string (const TCHAR *Stream, const TCHAR *Match, std::string &Value); //! Parse a QUADWORD after the named token. /*! Parse a QUADWORD after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed QUADWORD @return TRUE if the token is found inside the stream. */ bool Parse_u64 (const TCHAR *Stream, const TCHAR *Match, QWORD &Value); //! Parse a SIGNED QUADWORD after the named token. /*! Parse a SIGNED QUADWORD after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed SIGNED QUADWORD @return TRUE if the token is found inside the stream. */ bool Parse_s64 (const TCHAR *Stream, const TCHAR *Match, SQWORD &Value); //! Parse a BOOLEAN after the named token. /*! Parse a BOOLEAN after the named token. @param Stream Character stream to search. @param Match Token to match. @param Value parsed BOOLEAN value @return TRUE if the token is found inside the stream. */ bool Parse_bool (const TCHAR *Stream, const TCHAR *Match, bool &OnOff); //! Extract a line of Stream (everything up to, but not including, CR/LF). /*! @param Stream Character stream to search. @param LineBuffer The first line in Stream. @param BufferSize Size of LineBuffer. @param GoToNextLine If true, advanced the pointer after the first CR/LF character at the end of the string. If FALSE advanced the pointer past all the CR/LF character at the end of the string. @return True i a line was copied to LineString; */ bool ParseLine (const TCHAR **Stream, TCHAR *LineBuffer, int BufferSize); //! Extract a line of Stream (everything up to, but not including, CR/LF). /*! @param Stream Character stream to search. @param LineString The first line in Stream. @param GoToNextLine If true, advanced the pointer after the first CR/LF character at the end of the string. If FALSE advanced the pointer past all the CR/LF character at the end of the string. @return True i a line was copied to LineString; */ bool ParseLine (const TCHAR **Stream, std::string &LineString); //! Parse the next space-delimited string from the input stream. If the next token starts with a quote, gets entire quoted string. /*! @param Str stream of characters to search. @param TokenBuffer The parsed token string. @param BufferSize Size of the TokenBuffer. @return True if a token was found. */ bool ParseToken (const TCHAR *Str, TCHAR *TokenBuffer, int BufferSize); //! Parse the next space-delimited string from the input stream. If the next token starts with a quote, gets entire quoted string. /*! @param Str stream of characters to search. @param TokenBuffer The parsed token string. @return True if a token was found. */ bool ParseToken (const TCHAR *Str, std::string &TokenString); //! Parse the next space-delimited string from the input stream. If the next token starts with a quote, gets entire quoted string. /*! @param Str stream of characters to parse. @return The next token in a std::string. */ std::string ParseToken (const TCHAR *Str); //! Go to the next token in the stream. /*! Skip tabs, and space at the beginning of each line. Skip everything on a line that follows the given comment char token If there is a valid token in the input, Stream will point to it. @param Stream stream of characters @param CommentChar Character representing the beginning of a comment on a line. ie ';' '#". */ void ParseToNextLine (const TCHAR **Stream, TCHAR CommentChar); //! Checks if a Token command-line parameter exists in the stream. /*! Checks if a Token command-line parameter exists in the stream @param Stream stream of characters to search @param token to match @return True if found. */ bool ParseParam (const TCHAR *Stream, const TCHAR *Param); } #endif // NPARSING_H nux-4.0.8+16.04.20160209/NuxCore/RollingFileAppender.h0000644000015600001650000000256112656236757022351 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_ROLLING_FILE_APPENDER_H #define NUX_CORE_ROLLING_FILE_APPENDER_H #include #include #include namespace nux { namespace logging { class RollingFileAppender : public std::ostream { public: RollingFileAppender(std::string const& filename); RollingFileAppender(std::string const& filename, unsigned number_of_backup_files, unsigned long long max_log_size); ~RollingFileAppender(); sigc::signal files_rolled; }; } } #endif nux-4.0.8+16.04.20160209/NuxCore/Process.cpp0000644000015600001650000000743712656236757020444 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { #ifdef _WIN32 // // Launch a uniform resource locator (i.e. http://www.yahoo.com/finance). // This is expected to return immediately as the URL is launched by another // task. // void inlLaunchURL(const TCHAR *URL, const TCHAR *Parms, std::string Error) { nuxDebugMsg ( TEXT ("LaunchURL %s %s"), URL, Parms ? Parms : TEXT ("") ); HINSTANCE Code = CALL_OS_TCHAR_FUNCTION (ShellExecuteW (NULL, TEXT ("open"), URL, Parms ? Parms : TEXT (""), TEXT (""), SW_SHOWNORMAL), ShellExecuteA (NULL, "open", TCHAR_TO_ANSI (URL), Parms ? TCHAR_TO_ANSI (Parms) : "", "", SW_SHOWNORMAL) ); Error = (int) Code <= 32 ? TEXT ("UrlFailed") : TEXT (""); } // // Creates a new process and its primary thread. The new process runs the // specified executable file in the security context of the calling process. // void *inlCreateProc ( const TCHAR *URL, const TCHAR *Parms ) { nuxDebugMsg ( TEXT ("CreateProc %s %s"), URL, Parms ); TCHAR CommandLine[1024]; Snprintf ( CommandLine, 1024, 1024 - 1, TEXT ("%s %s"), URL, Parms ); PROCESS_INFORMATION ProcInfo; SECURITY_ATTRIBUTES Attr; Attr.nLength = sizeof (SECURITY_ATTRIBUTES); Attr.lpSecurityDescriptor = NULL; Attr.bInheritHandle = TRUE; STARTUPINFO StartupInfo = { sizeof (STARTUPINFO), NULL, NULL, NULL, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL, SW_HIDE, NULL, NULL, NULL, NULL, NULL }; if ( !CreateProcess ( NULL, CommandLine, &Attr, &Attr, TRUE, DETACHED_PROCESS | REALTIME_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcInfo ) ) return NULL; return (void *) ProcInfo.hProcess; } // // Retrieves the termination status of the specified process. // BOOL inlGetProcReturnCode ( void *ProcHandle, INT *ReturnCode ) { return GetExitCodeProcess ( (HANDLE) ProcHandle, (DWORD *) ReturnCode ) && * ( (DWORD *) ReturnCode) != STILL_ACTIVE; } NUX_IMPLEMENT_GLOBAL_OBJECT (NProcess); void NProcess::Constructor() { m_ProcessID = GetCurrentProcessId(); m_ProcessHandle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, m_ProcessID); m_MainThreadID = GetCurrentThreadId(); m_MainThreadHandle = OpenThread (THREAD_ALL_ACCESS, FALSE, m_MainThreadID); } void NProcess::Destructor() { CloseHandle (m_MainThreadHandle); CloseHandle (m_ProcessHandle); } HANDLE NProcess::GetProcessHandle() { return m_ProcessHandle; } DWORD NProcess::GetProcessID() { return m_ProcessID; } HANDLE NProcess::GetMainThreadHandle() { return m_MainThreadHandle; } DWORD NProcess::GetMainThreadID() { return m_MainThreadID; } HANDLE NProcess::GetCurrentThreadHandle() { DWORD ThreadID = GetCurrentThreadId(); return OpenThread (THREAD_ALL_ACCESS, FALSE, ThreadID); } DWORD NProcess::GetCurrentThreadID() { return GetCurrentThreadId(); } #endif } nux-4.0.8+16.04.20160209/NuxCore/Property-inl.h0000644000015600001650000002131012656236757021061 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUXCORE_PROPERTY_INL_H #define NUXCORE_PROPERTY_INL_H namespace nux { template PropertyChangedSignal::PropertyChangedSignal() : notify_(true) {} template void PropertyChangedSignal::DisableNotifications() { notify_ = false; } template void PropertyChangedSignal::EnableNotifications() { notify_ = true; } template void PropertyChangedSignal::EmitChanged(VALUE_TYPE const& new_value) { if (notify_) changed.emit(new_value); } template Property::Property() : value_(VALUE_TYPE()) , setter_function_(std::bind(&Property::DefaultSetter, this, std::placeholders::_1, std::placeholders::_2)) {} template Property::Property(VALUE_TYPE const& initial) : value_(initial) , setter_function_(std::bind(&Property::DefaultSetter, this, std::placeholders::_1, std::placeholders::_2)) {} template Property::Property(VALUE_TYPE const& initial, SetterFunction setter_function) : value_(initial) , setter_function_(setter_function) {} template VALUE_TYPE Property::operator=(VALUE_TYPE const& value) { return Set(value); } template Property::operator VALUE_TYPE() const { return value_; } template VALUE_TYPE Property::operator()() const { return value_; } template VALUE_TYPE Property::operator()(VALUE_TYPE const& value) { return Set(value); } template VALUE_TYPE Property::Get() const { return value_; } template VALUE_TYPE Property::Set(VALUE_TYPE const& value) { if (setter_function_(value_, value)) SignalBase::EmitChanged(value_); return value_; } template bool Property::DefaultSetter(VALUE_TYPE& target, VALUE_TYPE const& value) { bool changed = false; if (target != value) { target = value; changed = true; } return changed; } template void Property::SetSetterFunction(SetterFunction setter_function) { setter_function_ = setter_function; } template ROProperty::ROProperty() : getter_function_(std::bind(&ROProperty::DefaultGetter, this)) {} template ROProperty::ROProperty(GetterFunction getter_function) : getter_function_(getter_function) {} template ROProperty::operator VALUE_TYPE() const { return getter_function_(); } template VALUE_TYPE ROProperty::operator()() const { return getter_function_(); } template VALUE_TYPE ROProperty::Get() const { return getter_function_(); } template VALUE_TYPE ROProperty::DefaultGetter() const { return VALUE_TYPE(); } template void ROProperty::SetGetterFunction(GetterFunction getter_function) { getter_function_ = getter_function; } template RWProperty::RWProperty() : getter_function_(std::bind(&RWProperty::DefaultGetter, this)) , setter_function_(std::bind(&RWProperty::DefaultSetter, this, std::placeholders::_1)) {} template RWProperty::RWProperty(GetterFunction getter_function, SetterFunction setter_function) : getter_function_(getter_function) , setter_function_(setter_function) {} template VALUE_TYPE RWProperty::operator=(VALUE_TYPE const& value) { return Set(value); } template RWProperty::operator VALUE_TYPE() const { return getter_function_(); } template VALUE_TYPE RWProperty::operator()() const { return getter_function_(); } template VALUE_TYPE RWProperty::operator()(VALUE_TYPE const& value) { return Set(value); } template VALUE_TYPE RWProperty::Get() const { return getter_function_(); } template VALUE_TYPE RWProperty::Set(VALUE_TYPE const& value) { if (setter_function_(value)) { VALUE_TYPE new_value = getter_function_(); SignalBase::EmitChanged(new_value); return new_value; } return getter_function_(); } template VALUE_TYPE RWProperty::DefaultGetter() const { return VALUE_TYPE(); } template bool RWProperty::DefaultSetter(VALUE_TYPE const& /* value */) { return false; } template void RWProperty::SetSetterFunction(SetterFunction setter_function) { setter_function_ = setter_function; } template void RWProperty::SetGetterFunction(GetterFunction getter_function) { getter_function_ = getter_function; } // We need to provide a default constructor since we hide the copy ctor. inline Introspectable::Introspectable() {} inline void Introspectable::AddProperty(std::string const& name, PropertyBase* property) { // check to see if it exists and if it does barf horribly as we can't // have two properties with the same name; properties_[name] = property; } inline bool Introspectable::SetProperty(std::string const& name, const char* value) { PropertyContainer::iterator i = properties_.find(name); if (i == properties_.end()) return false; else return i->second->SetValue(value); } template bool Introspectable::SetProperty(std::string const& name, T const& value) { PropertyContainer::iterator i = properties_.find(name); if (i == properties_.end()) return false; else { return i->second->SetValue(type::PropertyTrait::to_string(value)); } } template T Introspectable::GetProperty(std::string const& name, T* /* foo */) { PropertyContainer::iterator i = properties_.find(name); if (i == properties_.end()) return T(); std::string s = i->second->GetSerializedValue(); std::pair result = type::PropertyTrait::from_string(s); // If this is called with a template type that the property does not // support nice conversion to, you'll get no error, but will get // a default constructed T. We could use an exception here. return result.first; } template SerializableProperty::SerializableProperty(Introspectable* owner, std::string const& name) : Base() , name_(name) { owner->AddProperty(name, this); } template SerializableProperty::SerializableProperty(Introspectable* owner, std::string const& name, T const& initial) : Base(initial) , name_(name) { owner->AddProperty(name, this); } template bool SerializableProperty::SetValue(std::string const& serialized_form) { std::pair result = TraitType::from_string(serialized_form); if (result.second) { Base::Set(result.first); } return result.second; } template std::string SerializableProperty::GetSerializedValue() const { return TraitType::to_string(Base::Get()); } template T SerializableProperty::operator=(T const& value) { Base::Set(value); // There are no arguments to ‘get’ that depend on a template parameter, // so we explicitly specify Base. return Base::Get(); } } #endif nux-4.0.8+16.04.20160209/NuxCore/NumberConversion.h0000644000015600001650000000375512656236757021770 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUMBERCONVERSION_H #define NUMBERCONVERSION_H namespace nux { //! Convert a TCHAR string to a double value. /*! @param digit A TCHAR string. @return A double value translated from a TCHAR string. */ double CharToDouble (const TCHAR *digit); //! Convert a double to an std::string. /*! @param d A double value. @return An std::string. */ std::string DoubleToChar (double d); //! Convert a TCHAR string to a 32 bits long value. /*! @param digit A TCHAR string. @return A 32 bits long value translated from a TCHAR string. */ int CharToInteger (const TCHAR *digit); //! Convert an integer to a tstring. /*! @param value An integer value. @param base Base of the integer representation. @return A string. */ std::string IntegerToChar (int value, int base = 10); //! Convert an string to an integer. /*! @param digit A TCHAR string. @return An integer value. */ int IntegerToChar (const TCHAR *digit); //! Convert an Hex TCHAR string to an integer value. /*! @param value A TCHAR string. @return An integer value. */ unsigned int HexCharToInteger (const TCHAR *s); } #endif // NUMBERCONVERSION_H nux-4.0.8+16.04.20160209/NuxCore/Makefile.am0000644000015600001650000001123612656236757020346 0ustar pbuserpbgroup00000000000000CLEANFILES = DISTCLEANFILES = EXTRA_DIST = AM_CPPFLAGS = \ -I$(srcdir) \ -I$(top_srcdir) \ -DPREFIX=\""$(prefix)"\" \ -DLIBDIR=\""$(libdir)"\" \ -DDATADIR=\""$(datadir)"\" \ -DG_LOG_DOMAIN=\"NuxCore\" lib_LTLIBRARIES = \ libnux-core-@NUX_API_VERSION@.la libnux_core_@NUX_API_VERSION@_la_CPPFLAGS= \ $(GCC_FLAGS) \ $(NUX_CORE_CFLAGS) \ $(MAINTAINER_CFLAGS) \ $(COVERAGE_CFLAGS) libnux_core_@NUX_API_VERSION@_la_LIBADD = \ $(NUX_CORE_LIBS) -lpthread libnux_core_@NUX_API_VERSION@_la_LDFLAGS = \ $(NUX_LT_LDFLAGS) \ $(COVERAGE_LDFLAGS) source_cpp = \ Animation.cpp \ AnimationController.cpp \ AsyncFileWriter.cpp \ EasingCurve.cpp \ TextString.cpp \ TimeFunctions.cpp \ Template.cpp \ FilePath.cpp \ FileManager/NSerializer.cpp \ FileManager/NFileManagerGeneric.cpp \ FileManager/NFileManagerGNU.cpp \ SystemGNU.cpp \ OutputDevice.cpp \ Exception.cpp \ Memory.cpp \ Character/NUTF.cpp \ Character/NUni.cpp \ Character/NUnicode.cpp \ Color.cpp \ ColorPrivate.cpp \ Colors.cpp \ FileName.cpp \ ThreadGNU.cpp \ Parsing.cpp \ Logger.cpp \ LoggingWriter.cpp \ NUniqueIndex.cpp \ GlobalInitializer.cpp \ ObjectType.cpp \ Platform.cpp \ Rect.cpp \ FileIO.cpp \ Process.cpp \ NumberConversion.cpp \ NuxCore.cpp \ Object.cpp \ Math/Algo.cpp \ Math/Constants.cpp \ Math/MathFunctions.cpp \ Math/Line2D.cpp \ Math/Bezier.cpp \ Math/Spline.cpp \ Math/Quaternion.cpp \ Math/Matrix2.cpp \ Math/Trigonometry.cpp \ Math/Tweening.cpp \ Math/Complex.cpp \ Math/Point3D.cpp \ Math/Matrix4.cpp \ Math/Matrix3.cpp \ Math/Line3D.cpp \ RollingFileAppender.cpp \ InitiallyUnownedObject.cpp source_file_manager_h = \ FileManager/NFileManagerGNU.h \ FileManager/NFileManagerGeneric.h \ FileManager/NSerializer.h source_character_h = \ Character/NUTF.h \ Character/NUni.h \ Character/NUnicode.h \ Character/NTChar.h source_math_h = \ Math/Algo.h \ Math/Bezier.h \ Math/Constants.h \ Math/Point3D.h \ Math/Vector4.h \ Math/Matrix2.h \ Math/Spline.h \ Math/Vector3.h \ Math/MathFunctions.h \ Math/Quaternion.h \ Math/Trigonometry.h \ Math/Line3D.h \ Math/MathInc.h \ Math/Complex.h \ Math/Matrix3.h \ Math/Vector2.h \ Math/Line2D.h \ Math/Point2D.h \ Math/Point2D-inl.h \ Math/Tweening.h \ Math/Matrix4.h \ Math/MathUtility.h source_h = \ Animation.h \ Animation-inl.h \ AnimationController.h \ AsyncFileWriter.h \ EasingCurve.h \ Point.h \ FilePath.h \ System.h \ Parsing.h \ StringConversion.h \ GlobalInitializer.h \ Rect.h \ Platform.h \ Inalogic.h \ Color.h \ Colors.h \ Logger.h \ LoggerPrivate.h \ LoggingWriter.h \ RollingFileAppender.h \ Memory.h \ Error.h \ SystemGNU.h \ NuxCore.h \ FileName.h \ OutputDevice.h \ Process.h \ ObjectType.h \ ObjectPtr.h \ NumberConversion.h \ Object.h \ Size.h \ Size-inl.h \ Exception.h \ TimeFunctions.h \ Macros.h \ ThreadGNU.h \ TextString.h \ Template.h \ NUniqueIndex.h \ FileIO.h \ InitiallyUnownedObject.h \ Property.h \ Property-inl.h \ PropertyAnimation.h \ PropertyOperators.h \ PropertyTraits.h \ Win32Dialogs/NWin32Clipboard.h libnux_core_@NUX_API_VERSION@_la_SOURCES = \ $(source_cpp) \ $(source_h) \ $(source_character_h) \ $(source_file_manager_h) \ $(source_math_h) \ $(source_memory_h) nux_coredir = $(includedir)/Nux-@NUX_API_VERSION@/NuxCore nux_core_HEADERS = $(source_h) nux_chardir = $(nux_coredir)/Character nux_char_HEADERS = $(source_character_h) nux_file_managerdir = $(nux_coredir)/FileManager nux_file_manager_HEADERS = $(source_file_manager_h) nux_mathdir = $(nux_coredir)/Math nux_math_HEADERS = $(source_math_h) nux_memorydir = $(nux_coredir)/Memory nux_memory_HEADERS = $(source_memory_h) # pkg-config file nux-core-@NUX_API_VERSION@.pc: nux-core.pc $(AM_V_GEN) cp -f nux-core.pc nux-core-@NUX_API_VERSION@.pc pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = nux-core-@NUX_API_VERSION@.pc unused_src = \ Character/NAscii.cpp \ Character/NAscii.h \ Character/NUnicodeGNU.cpp \ Character/NUnicodeGNU.h \ CppReadme.txt \ FileManager/NFileManagerWindows.cpp \ FileManager/NFileManagerWindows.h \ Plugin/NPlugin.h \ Plugin/NPluginInterface.h \ Plugin/NPluginManager.cpp \ Plugin/NPluginManager.h \ Plugin/NPluging.cpp \ SystemWindows.cpp \ SystemWindows.h \ ThreadWin.cpp \ ThreadWin.h \ Win32Dialogs/NWin32Clipboard.cpp \ Win32Dialogs/NWin32CustomDialog.cpp \ Win32Dialogs/NWin32CustomDialog.h \ Win32Dialogs/NWin32MessageBox.cpp \ Win32Dialogs/NWin32MessageBox.h CLEANFILES += nux-core-@NUX_API_VERSION@.pc DISTCLEANFILES += nux-core.pc EXTRA_DIST += nux-core.pc.in ${unused_src} nux-4.0.8+16.04.20160209/NuxCore/GlobalInitializer.h0000644000015600001650000001020212656236757022057 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NGLOBALINITIALIZER_H #define NGLOBALINITIALIZER_H #include "Macros.h" #include "System.h" #ifdef _WIN32 #define NUX_GLOBAL_OBJECT_INIT_SEQUENCE() \ NUX_GLOBAL_OBJECT_VARIABLE(NGlobalData); \ NUX_GLOBAL_OBJECT_VARIABLE(NProcess); \ NUX_GLOBAL_OBJECT_VARIABLE(NullOutput); \ NUX_GLOBAL_OBJECT_VARIABLE(UniqueIndex); \ NUX_GLOBAL_OBJECT_VARIABLE(NFileManagerWindows); \ NUX_GLOBAL_OBJECT_VARIABLE(VisualOutputConsole); \ NUX_GLOBAL_OBJECT_VARIABLE(PrintfOutputConsole); \ NUX_GLOBAL_OBJECT_VARIABLE(LogFileOutput); \ NUX_GLOBAL_OBJECT_VARIABLE(LogOutputRedirector); \ NUX_GLOBAL_OBJECT_VARIABLE(ObjectStats); #elif (defined NUX_OS_LINUX) #define NUX_GLOBAL_OBJECT_INIT_SEQUENCE() \ NUX_GLOBAL_OBJECT_VARIABLE(NGlobalData); \ NUX_GLOBAL_OBJECT_VARIABLE(NullOutput); \ NUX_GLOBAL_OBJECT_VARIABLE(UniqueIndex); \ NUX_GLOBAL_OBJECT_VARIABLE(NFileManagerGNU); \ NUX_GLOBAL_OBJECT_VARIABLE(PrintfOutputConsole); \ NUX_GLOBAL_OBJECT_VARIABLE(LogFileOutput); \ NUX_GLOBAL_OBJECT_VARIABLE(LogOutputRedirector); \ NUX_GLOBAL_OBJECT_VARIABLE(ObjectStats); #endif namespace nux { // This class initialize all inalogic singleton (global objects) in order. It also initialize memory allocators. // Therefore, do not call new GlobalSingletonInitializer as it will try to call inalogic memory allocator and fail. // You may use the global placement new operator(it is not overwritten by inalogic) to create GlobalSingletonInitializer // inside the application data space by calling SystemInitializer(). At shutdown, call SystemShutdown() // // You may also create GlobalSingletonInitializer in this way: // main() // { // GlobalSingletonInitializer GlobalInitializer; // } // // class GlobalSingletonInitializer { NUX_DISABLE_OBJECT_COPY (GlobalSingletonInitializer); GlobalSingletonInitializer *operator & (); const GlobalSingletonInitializer *operator & () const; public: GlobalSingletonInitializer(); ~GlobalSingletonInitializer(); static bool Ready(); private: static bool m_bGlobalObjectsReady; NUX_GLOBAL_OBJECT_INIT_SEQUENCE(); }; // Nifty Counter idiom. See http://www-d0.fnal.gov/KAI/doc/tutorials/static_initialization.html class GlobalInitializer { public: GlobalInitializer(); ~GlobalInitializer(); static void ForceShutdown(); private: static int m_Count; }; // Every compilation unit that includes this file will have its own instance of sGlobalInitializer. sGlobalInitializer is initialized // before the main function of the program is called. The first time sGlobalInitializer is initialized, it calls SystemStart() to create // our global object singleton. In SystemStart() we have a change to create our singletons in any order we like. // When the program exits, every instance of sGlobalInitializer will be destroyed. The last instance destroyed will call SystemShutdown(). // In SystemShutdown() we can destroy our global objects in any order we like. static GlobalInitializer sGlobalInitializer; } #endif // NGLOBALINITIALIZER_H nux-4.0.8+16.04.20160209/NuxCore/FileIO.h0000644000015600001650000000315212656236757017570 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NFILE_H #define NFILE_H #include #include namespace nux { bool LoadFileToArray ( std::vector& Result, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); bool LoadTextFileToAnsiArray ( std::vector& Result, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); bool LoadTextFileToUnicodeArray ( std::vector& Result, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); bool LoadFileToString(std::string &Result, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); bool SaveArrayToFile(const std::vector& Array, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); bool SaveStringToFile(const std::string &String, const TCHAR *Filename, NFileManager &FileManager = GFileManager ); } #endif // NFILE_H nux-4.0.8+16.04.20160209/NuxCore/ThreadGNU.h0000644000015600001650000003332612656236757020250 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NTHREADGNU_H #define NTHREADGNU_H #include "ObjectType.h" /*#include #include #include #include #include */ namespace nux { class NThreadSafeCounter { public: NThreadSafeCounter() { m_Counter = 0; } NThreadSafeCounter (int i) { m_Counter = i; } int Increment(); int Decrement(); int Set (int i); int GetValue() const; int operator ++ (); int operator -- (); bool operator == (int i); private: int m_Counter; }; class NCriticalSection { public: //! Initialize critical section. /*! Initialize critical section. */ NCriticalSection() { pthread_mutex_init (&m_lock, 0); } //! Destroy critical section. /*! Destroy critical section. */ ~NCriticalSection() { pthread_mutex_destroy (&m_lock); } //! Enter critical section. /*! Enter critical section. This function is made const so it can be used without restriction. For that matter, m_lock is made mutable. */ void Lock() const { // NUXTODO: There are issues with locking on Linux when starting nux in embedded mode.,. #ifndef NUX_OS_LINUX pthread_mutex_lock (&m_lock); #endif } //! Leave critical section. /*! Leave critical section. This function is made const so it can be used without restriction. For that matter, m_lock is made mutable. */ void Unlock() const { // NUXTODO: There are issues with locking on Linux when starting nux in embedded mode.,. #ifndef NUX_OS_LINUX pthread_mutex_unlock (&m_lock); #endif } private: //! Prohibit copy constructor. /*! Prohibit copy constructor. */ NCriticalSection (const NCriticalSection &); //! Prohibit assignment operator. /*! Prohibit assignment operator. */ NCriticalSection &operator= (const NCriticalSection &); mutable pthread_mutex_t m_lock; }; //! Scope Lock class /*! Takes a critical section object as parameter of the constructor. The constructor locks the critical section. The destructor unlocks the critical section. */ class NScopeLock { public: //! The constructor locks the critical section object. /*! The constructor locks the critical section object. @param LockObject Critical section object. */ NScopeLock (NCriticalSection *CriticalSectionObject) : m_CriticalSectionObject (CriticalSectionObject) { nuxAssert (m_CriticalSectionObject); m_CriticalSectionObject->Lock(); } //! The destructor unlocks the critical section object. /*! The destructor unlocks the critical section object. */ ~NScopeLock (void) { nuxAssert (m_CriticalSectionObject); m_CriticalSectionObject->Unlock(); } private: //! Prohibit default constructor. /*! Prohibit default constructor. */ NScopeLock (void); //! Prohibit copy constructor. /*! Prohibit copy constructor. */ NScopeLock (const NScopeLock &ScopeLockObject); //! Prohibit assignment operator. /*! Prohibit assignment operator. */ NScopeLock &operator= (const NScopeLock & /* ScopeLockObject */) { return *this; } //! Critical section Object. /*! Critical section Object. */ NCriticalSection *m_CriticalSectionObject; }; class NThreadLocalStorage { public: enum { NbTLS = 128, InvalidTLS = 0xFFFFFFFF }; typedef void (*TLS_ShutdownCallback) (); static BOOL m_TLSUsed[NbTLS]; static __thread void *m_TLSIndex[NbTLS]; static TLS_ShutdownCallback m_TLSCallbacks[NbTLS]; static void Initialize(); static void Shutdown(); static BOOL RegisterTLS (unsigned int index, TLS_ShutdownCallback shutdownCallback); static BOOL UnRegisterTLS (unsigned int index); static void ThreadInit(); static void ThreadShutdown(); public: template static inline T GetData (unsigned int index) { nuxAssert (sizeof (T) <= sizeof (size_t) ); nuxAssert (index < NbTLS); nuxAssert (m_TLSUsed[index]); // T and (unsigned long) can be of different sizes // but this limits the use of GetData to classes without copy constructors union { T t; void *v; } temp; temp.v = m_TLSIndex[index]; return temp.t; } template static inline void SetData (unsigned int index, T value) { nuxAssert (sizeof (T) <= sizeof (size_t) ); nuxAssert (index < NbTLS); nuxAssert (m_TLSUsed[index]); // T and (unsigned long) can be of different sizes // but this limits the use of GetData to classes without copy constructors union { T t; void *v; } temp; temp.t = value; m_TLSIndex[index] = temp.v; } }; #define inlDeclareThreadLocalStorage(type, index, name) \ struct ThreadLocalStorageDef##name { enum Const { Index = index}; };\ inline type GetTLS_##name() { return nux::NThreadLocalStorage::GetData(ThreadLocalStorageDef##name::Index); }\ inline void SetTLS_##name(type value) { nux::NThreadLocalStorage::SetData(ThreadLocalStorageDef##name::Index, value); } #define inlRegisterThreadLocalIndex(index, name, shutdownCallback) \ nuxVerifyExpr(index == ThreadLocalStorageDef##name::Index); \ nuxVerifyExpr(nux::NThreadLocalStorage::RegisterTLS(index, shutdownCallback)) #define inlUnRegisterThreadLocalIndex(name) \ nuxVerifyExpr(nux::NThreadLocalStorage::UnRegisterTLS(ThreadLocalStorageDef##name::Index)) #define inlGetThreadLocalStorage(name) GetTLS_##name() #define inlSetThreadLocalStorage(name, value) SetTLS_##name(value) #ifdef POP_CHECK_THREADS #define nuxAssertInsideThread(threadtype) nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype) #define nuxAssertInsideThread2(threadtype1, threadtype2) nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype1 || popGetThreadLocalData(ThreadType) == threadtype2) #define nuxAssertNotInsideThread(threadtype) nuxAssert( inlGetThreadLocalStorage(ThreadType) != threadtype) #else #define nuxAssertInsideThread(threadtype) ((void) 0) #define nuxAssertInsideThread2(threadtype1, threadtype2) ((void) 0) #define nuxAssertNotInsideThread(threadtype) ((void) 0) #endif enum ThreadState { THREADINIT, THREADRUNNING, THREADSUSPENDED, THREADSTOP, THREAD_START_ERROR, THREAD_STOP_ERROR, THREAD_SUSPEND_ERROR, THREAD_RESUME_ERROR, }; enum ThreadWaitTimeout { THREAD_WAIT_TIMEOUT_NONE = 0, THREAD_WAIT_TIMEOUT_FOREVER = 0xFFFFFFFF, }; enum ThreadWaitResult { THREAD_WAIT_RESULT_COMPLETED = 0, THREAD_WAIT_RESULT_ABANDONED = 1, THREAD_WAIT_RESULT_TIMEOUT = 2, THREAD_WAIT_RESULT_FAILED = 3, }; // http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c3793/ typedef void* (*ThreadRoutineFunc) (void *); class NThread { NUX_DECLARE_ROOT_OBJECT_TYPE (NThread); public: /*! Info: Default Constructor */ NThread(); /*! Info: Plug Constructor Use this to migrate/port existing worker threads to objects immediately Although you lose the benefits of ThreadCTOR and ThreadDTOR. */ NThread (ThreadRoutineFunc lpExternalRoutine); /*! Info: Default Destructor I think it is wise to destroy the thread even if it is running, when the main thread reaches here. */ virtual ~NThread(); /*! Info: Starts the thread. This function starts the thread pointed by m_pThreadFunc with default attributes */ virtual ThreadState Start ( void *arg = NULL ); /*! Info: Stops the thread. This function stops the current thread. We can force kill a thread which results in a TerminateThread. */ virtual ThreadState Stop ( bool bForceKill = false ); ThreadState Suspend(); ThreadState Resume(); ThreadState ResumeStart(); ThreadState ResumeExit(); /*! Info: Starts the thread. This function starts the thread pointed by m_pThreadFunc with default attributes */ unsigned int GetExitCode() const; /*! Info: Attaches a Thread Function Used primarily for porting but can serve in developing generic thread objects */ void Attach ( ThreadRoutineFunc lpThreadFunc ) { m_pThreadFunc = lpThreadFunc; } /*! Info: Detaches the Attached Thread Function Detaches the Attached Thread Function, If any. by resetting the thread function pointer to EntryPoint1 */ void Detach ( void ) { m_pThreadFunc = NThread::EntryPoint; } pthread_t GetPThread(); ThreadState GetThreadState() const; void SetThreadState (ThreadState state); /*! Wait for a thread to complete. The second parameters to this call specifies a how long to wait for the thread to complete. The following options are available: ThreadWaitTimeout::THREAD_WAIT_TIMEOUT_NONE: The function returns immediately if the thread exits. ThreadWaitTimeout::THREAD_WAIT_TIMEOUT_FOREVER: The function waits until the thread exits. @param thread Pointer to a valid NThread. @param milliseconds Time to wait for the thread to complete. */ static ThreadWaitResult JoinThread(NThread *thread, unsigned int milliseconds); protected: volatile ThreadState m_ThreadState; /*! Info: DONT override this method. This function is like a standard template. Override if you are sure of what you are doing. In C++ the entry function of a thread cannot be a normal member function of a class. However, it can be a static member function of a class. This is what we will use as the entry point. There is a gotcha here though. Static member functions do not have access to the this pointer of a C++ object. They can only access static data. Fortunately, there is way to do it. Thread entry point functions take a void * as a parameter so that the caller can typecast any data and pass in to the thread. We will use this to pass this to the static function. The static function will then typecast the void * and use it to call a non static member function */ static void *EntryPoint (void *); /*! Info: Override this method. This function should contain the body/code of your thread. Notice the signature is similar to that of any worker thread function except for the calling convention. */ virtual int Run (void* /* arg */) { return m_ThreadCtx.m_dwExitCode; } /*! Info: Constructor-like function. Will be called by EntryPoint before executing the thread body. Override this function to provide your extra initialization. NOTE: do not confuse it with the classes constructor @return TRUE if the thread can continue running the program. If FALSE is returned, the thread won't execute the main body Run() and will exit without calling ThreadDtor. */ virtual bool ThreadCtor() { return true; } /*! Info: Destructor-like function. Will be called by EntryPoint after executing the thread body. Override this function to provide your extra destruction. NOTE: do not confuse it with the classes constructor @return TRUE if this function executed without problems. */ virtual bool ThreadDtor() { return true; } private: /*! Info: Thread Context Inner Class Every thread object needs to be associated with a set of values. like UserData Pointer, Handle, Thread ID etc. NOTE: This class can be enhanced to varying functionalities eg., * Members to hold StackSize * SECURITY_ATTRIBUTES member. */ class NThreadContext { public: NThreadContext () : m_pUserData (NULL) , m_pParent (NULL) , m_dwExitCode (0) { memset (&m_ThreadAttribute, 0, sizeof (m_ThreadAttribute)); memset (&m_dwTID, 0, sizeof (m_dwTID)); } /* * Attributes Section */ public: pthread_attr_t m_ThreadAttribute; pthread_t m_dwTID; // The Thread ID void *m_pUserData; // The user data pointer void *m_pParent; // The this pointer of the parent NThread object unsigned int m_dwExitCode; // The Exit Code of the thread }; /*! Attributes Section */ protected: /*! Info: Members of NThread */ NThreadContext m_ThreadCtx; // The Thread Context member ThreadRoutineFunc m_pThreadFunc; // The Worker Thread Function Pointer }; } #endif // NTHREADGNU_H nux-4.0.8+16.04.20160209/NuxCore/CppReadme.txt0000644000015600001650000002133112656236757020710 0ustar pbuserpbgroup00000000000000Storage types in C++ --------------------- *Constant Data Values are known at compile-time. This kind of data stored outside of the program read-write area. Therefore write attempt is undefined. const char *hello1 = "Hello world"; char *hello2 = "Other hello"; // hello1[1] = 'a'; // syntax error hello2[1] = 'a'; // could cause runtime error char *s = const_cast(hello1); // dangerous s[3] = 'x'; // could be runtime error ! There is difference between a string literal and an initialized character array. int main() { // declaration of three arrays in the user data area // read and write permissions for the elements: char t1[] = {'H','e','l','l','o','\0'}; char t2[] = "Hello"; char t3[] = "Hello"; // declaration of two pointers in the user data area // read and write permissions for the pointers // ...and... // allocation of the "Hello" literal (possibly) read-only char *s1 = "Hello"; // s1 points to 'H' char *s2 = "Hello"; // ... and s2 likely points to the same place void *v1 = t1, *v2 = t2, *v3 = t3, *v4 = s1, *v5 = s2; std::cout < * * Authored by: Jay Taoko * */ #ifndef SYSTEM_H #define SYSTEM_H #ifdef _DEBUG #define NUX_DEBUG #endif #ifdef _WIN32 #define NUX_OS_WINDOWS #elif __arm__ #define NUX_OS_LINUX #elif __linux__ #define NUX_OS_LINUX #elif __APPLE__ #define NUX_OS_MACOSX #endif #if __GNUC__ #define NUX_GNUC_COMPILER #if __GNUG__ #define NUX_GNUCPP_COMPILER #else #error Support only g++. #endif // Compiler string. #define NUX_COMPILER_STRING "GNU CPP Compiler" // Build string #ifdef NUX_DEBUG #define NUX_BUILD_STRING "Debug build compiled with " NUX_COMPILER_STRING #else #define NUX_BUILD_STRING "Compiled with " NUX_COMPILER_STRING #endif #endif #if __APPLE_CC__ #define NUX_APPLE_COMPILER #endif #if defined(_MSC_VER) #define NUX_MICROSOFT_COMPILER #endif #if defined(_M_X64) || defined(__amd64__) || defined(__ia64__) #define NUX_ARCH_x64 #elif defined(_M_IX86) || defined(__i386__) #define NUX_ARCH_i386 #elif defined(__arm__) #define NUX_ARCH_ARM #endif // If we are compiling for linux, and neither USE_X11 or NO_X11 are set, // then assume that we are compiling for X11 #if defined(NUX_OS_LINUX) # if defined(USE_X11) # if defined(NO_X11) # error Can not define both USE_X11 and NO_X11 # endif # elif !defined(NO_X11) # define USE_X11 # endif #elif defined(USE_X11) # error X11 not supported on non-linux systems #endif #if defined(USE_X11) # define DRAG_AND_DROP_SUPPORTED #endif // Right now, we only support minimal builds for ARM if no X. #if (defined(NUX_ARCH_ARM) && defined(NO_X11) && !defined(NUX_MINIMAL)) # define NUX_MINIMAL #endif // Compiler Macros: // NUX_GNUCPP_COMPILER // NUX_MICROSOFT_COMPILER // OS Macros: // NUX_OS_WINDOWS // NUX_OS_LINUX // NUX_OS_CELL // NUX_OS_MACOSX #ifdef _WIN32 // Add lib DbgHelp.lib for the following function // StackWalk64 // SymFunctionTableAccess64 // SymGetModuleBase64 // SymGetModuleInfo64 // SymGetLineFromAddr64 // SymGetSymFromAddr64 // SymInitialize // SymSetOptions // SymGetOptions // SymLoadModule64 #pragma comment(lib, "DbgHelp") // _MSC_VER: Defines the major and minor versions of the compiler. For example, 1300 for Microsoft Visual C++ .NET. 1300 represents version 13 // and no point release. This represents the fact that there have been a total of 13 releases of the compiler. // If you type cl /? at the command line, you will see the full version for the compiler you are using. #ifndef _MSC_VER #error Support only Visual Studio Compiler. #endif #define VISUAL_STUDIO_2010_COMPILER 1600 #define VISUAL_STUDIO_2008_COMPILER 1500 #define VISUAL_STUDIO_2005_COMPILER 1400 #define VISUAL_STUDIO_2003_COMPILER 1310 #if _MSC_VER >= 1600 #define NUX_VISUAL_STUDIO_2010 #elif _MSC_VER >= 1500 #define NUX_VISUAL_STUDIO_2008 #elif _MSC_VER >= 1400 #define NUX_VISUAL_STUDIO_2005 #elif _MSC_VER >= 1310 #define NUX_VISUAL_STUDIO_2003 #endif // Compiler string. #if (_MSC_VER >= VISUAL_STUDIO_2008_COMPILER) #define NUX_COMPILER_STRING "Visual Studio 2008" #elif (_MSC_VER >= VISUAL_STUDIO_2005_COMPILER) #define NUX_COMPILER_STRING "Visual Studio 2005" #elif (_MSC_VER >= VISUAL_STUDIO_2003_COMPILER) #define NUX_COMPILER_STRING "Visual Studio 2003" #endif // Build String #ifdef NUX_DEBUG #define NUX_BUILD_STRING "Debug build compiled with " NUX_COMPILER_STRING #else #define NUX_BUILD_STRING "Compiled with " NUX_COMPILER_STRING #endif // Define the proper values for _WIN32_WINNT and WINVER in the compiler response file "compiler_options.h" // Windows Vista _WIN32_WINNT>=0x0600 // WINVER>=0x0600 // Windows Server 2003 _WIN32_WINNT>=0x0502 // WINVER>=0x0502 // Windows XP _WIN32_WINNT>=0x0501 // WINVER>=0x0501 // Windows 2000 _WIN32_WINNT>=0x0500 // WINVER>=0x0500 // Windows NT 4.0 _WIN32_WINNT>=0x0400 // WINVER>=0x0400 // Windows Me _WIN32_WINDOWS=0x0500 // WINVER>=0x0500 // Windows 98 _WIN32_WINDOWS>=0x0410 // WINVER>=0x0410 // Windows 95 _WIN32_WINDOWS>=0x0400 // WINVER>=0x0400 // Minimum system required Macros to define // Windows Vista NTDDI_VERSION >=NTDDI_LONGHORN // Windows Server 2003 SP1 NTDDI_VERSION >=NTDDI_WS03SP1 // Windows Server 2003 NTDDI_VERSION >=NTDDI_WS03 // Windows XP SP2 NTDDI_VERSION >=NTDDI_WINXPSP2 // Windows XP SP1 NTDDI_VERSION >=NTDDI_WINXPSP1 // Windows XP NTDDI_VERSION >=NTDDI_WINXP // Windows 2000 SP4 NTDDI_VERSION >=NTDDI_WIN2KSP4 // Windows 2000 SP3 NTDDI_VERSION >=NTDDI_WIN2KSP3 // Windows 2000 SP2 NTDDI_VERSION >=NTDDI_WIN2KSP2 // Windows 2000 SP1 NTDDI_VERSION >=NTDDI_WIN2KSP1 // Windows 2000 NTDDI_VERSION >=NTDDI_WIN2K #define WIN32_LEAN_AND_MEAN 1 #endif // _WIN32 // Logging #if defined(NUX_OS_WINDOWS) && defined(NUX_DEBUG) #define NUX_ENABLE_ASSERT_MACROS #define NUX_ENABLE_LOGGING #elif defined(NUX_OS_LINUX) && defined(NUX_DEBUG) #define NUX_ENABLE_ASSERT_MACROS #define NUX_ENABLE_LOGGING #endif // NOP: no operation // Specifies that a function should be ignored and the argument list // be parsed but no code be generated for the arguments. It is intended for use in global // debug functions that take a variable number of arguments. #if defined(NUX_MICROSOFT_COMPILER) #define NUX_COMPILER_SUPPORTS_NOOP #define NUX_NOOP __noop #elif defined(NUX_GNUCPP_COMPILER) #define NUX_COMPILER_SUPPORTS_NOOP #define NUX_NOOP __asm__("nop") #endif // Pragma pack support #if defined(NUX_MICROSOFT_COMPILER) || defined(NUX_GNUCPP_COMPILER) #define NUX_SUPPORTS_PRAGMA_PACK #endif // Define variadic macro support #if defined(NUX_MICROSOFT_COMPILER) && (defined(NUX_VISUAL_STUDIO_2005) || defined(NUX_VISUAL_STUDIO_2008) || defined(NUX_VISUAL_STUDIO_2010)) #define NUX_VARIADIC_MACROS_SUPPORT #elif defined(NUX_GNUCPP_COMPILER) #define NUX_VARIADIC_MACROS_SUPPORT #endif /// DLL declaration macros #if defined(NUX_OS_WINDOWS) #ifdef NUX_DLL #if (!defined(_WIN32)) && (!defined(_WIN64)) #error("ERROR: Use NUX_DLL is permitted only on win32 & win64 platforms") #endif #define NUX_DECLSPEC_DLLIMPORT __declspec(dllimport) #define NUX_DECLSPEC_DLLEXPORT __declspec(dllexport) #else #define NUX_DECLSPEC_DLLIMPORT #define NUX_DECLSPEC_DLLEXPORT #endif #ifdef NUX_EXPORT_DLL #define NUX_DECLSPEC_DLL NUX_DECLSPEC_DLLEXPORT #else #define NUX_DECLSPEC_DLL NUX_DECLSPEC_DLLIMPORT #endif #elif defined(NUX_OS_LINUX) #if __GNUC__ >= 4 #define NUX_DECLSPEC_DLLIMPORT __attribute__ ((visibility("default"))) #define NUX_DECLSPEC_DLLEXPORT __attribute__ ((visibility("default"))) #else #define NUX_DECLSPEC_DLLIMPORT #define NUX_DECLSPEC_DLLEXPORT #endif #ifdef NUX_EXPORT_DLL #define NUX_DECLSPEC_DLL NUX_DECLSPEC_DLLEXPORT #else #define NUX_DECLSPEC_DLL NUX_DECLSPEC_DLLIMPORT #endif #endif #define NUX_CHECK_PUREVIRTUALS 1 // Throwing exceptions: // #ifdef NUX_DEBUG // // if we are in Debug disable exceptions. What we want is to break were and error happens: ie NUX_BREAK_ASM_INT3 // #define NUX_EXCEPTIONS_DISABLED 1 // #endif #define NUX_EXCEPTIONS_DISABLED 1 #define STL std #endif // SYSTEM_H nux-4.0.8+16.04.20160209/NuxCore/Object.cpp0000644000015600001650000002444112656236757020226 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2010-2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Object.h" #include "ObjectPtr.h" #include "Logger.h" namespace nux { DECLARE_LOGGER(logger, "nux.core.object"); NUX_IMPLEMENT_ROOT_OBJECT_TYPE (Trackable); NUX_IMPLEMENT_OBJECT_TYPE (Object); NUX_IMPLEMENT_GLOBAL_OBJECT (ObjectStats); void ObjectStats::Constructor() { _total_allocated_size= 0; _number_of_objects = 0; } void ObjectStats::Destructor() { #if defined(NUX_DEBUG) if (_number_of_objects) { std::cerr << "[ObjectStats::Destructor] " << _number_of_objects << " undeleted objects.\n\t" << _allocation_list.size() << " items in allocation list.\n"; } int index = 0; #if defined(NUX_OS_WINDOWS) // Visual Studio does not support range based for loops. for (AllocationList::iterator ptr = _allocation_list.begin(); ptr != _allocation_list.end(); ++ptr) { Object* obj = static_cast(*ptr); std::stringstream sout; sout << "\t" << ++index << " Undeleted object: Type " << obj->GetTypeName() << ", " << obj->GetAllocationLocation() << "\n"; OutputDebugString(sout.str().c_str()); std::cerr << sout.str().c_str(); } #else for (auto ptr : _allocation_list) { Object* obj = static_cast(ptr); std::cerr << "\t" << ++index << " Undeleted object: Type " << obj->GetTypeName() << ", " << obj->GetAllocationLocation() << "\n"; } #endif #endif } std::new_handler Trackable::_new_current_handler = 0; Trackable::Trackable() { _heap_allocated = -1; _owns_the_reference = false; } Trackable::~Trackable() { } bool Trackable::Reference() { return false; } bool Trackable::UnReference() { return false; } bool Trackable::SinkReference() { return false; } bool Trackable::Dispose() { return false; } bool Trackable::OwnsTheReference() { return _owns_the_reference; } void Trackable::SetOwnedReference (bool b) { if (_owns_the_reference == true) { LOG_DEBUG(logger) << "Do not change the ownership if is already set to true!" << "\n"; return; } _owns_the_reference = b; } std::new_handler Trackable::set_new_handler (std::new_handler handler) { std::new_handler old_handler = _new_current_handler; _new_current_handler = handler; return old_handler; } void* Trackable::operator new (size_t size) { // Set the new_handler for this call std::new_handler global_handler = std::set_new_handler (_new_current_handler); // If allocation fails _new_current_handler is called, if specified, // otherwise the global new_handler is called. void *ptr; try { ptr = ::operator new (size); GObjectStats._allocation_list.push_front (ptr); NUX_STATIC_CAST (Trackable *, ptr)->_size_of_this_object = size; GObjectStats._total_allocated_size += size; ++GObjectStats._number_of_objects; } catch (std::bad_alloc &) { std::set_new_handler (global_handler); throw; } // Reset gloabal new_handler std::set_new_handler (global_handler); return ptr; } #if (__GNUC__ < 4 && __GNUC_MINOR__ < 4) void *Trackable::operator new (size_t size, void *ptr) { return ::operator new (size, ptr); } #endif void Trackable::operator delete (void *ptr) { ObjectStats::AllocationList::iterator i = std::find (GObjectStats._allocation_list.begin(), GObjectStats._allocation_list.end(), ptr); if (i != GObjectStats._allocation_list.end() ) { GObjectStats._total_allocated_size -= NUX_STATIC_CAST (Trackable *, ptr)->_size_of_this_object; --GObjectStats._number_of_objects; GObjectStats._allocation_list.erase (i); ::operator delete (ptr); } #ifdef NUX_DEBUG else { // Complain quite loudly as this should never happen. LOG_ERROR(logger) << "Attempting to delete a pointer we can't find."; } #endif } bool Trackable::IsHeapAllocated() { if (_heap_allocated == -1) { _heap_allocated = IsDynamic(); } return _heap_allocated; } bool Trackable::IsDynamic() const { // Get pointer to beginning of the memory occupied by this. const void *ptr = dynamic_cast (this); // Search for ptr in allocation_list #if defined(NUX_OS_WINDOWS) && !defined(NUX_VISUAL_STUDIO_2010) std::list::iterator i = std::find(GObjectStats._allocation_list.begin(), GObjectStats._allocation_list.end(), ptr); #else auto i = std::find(GObjectStats._allocation_list.begin(), GObjectStats._allocation_list.end(), ptr); #endif return i != GObjectStats._allocation_list.end(); } int Trackable::GetObjectSize () { return _size_of_this_object; } ////////////////////////////////////////////////////////////////////// Object::Object(bool OwnTheReference, NUX_FILE_LINE_DECL) : reference_count_(new NThreadSafeCounter()) , objectptr_count_(new NThreadSafeCounter()) { reference_count_->Set(1); SetOwnedReference(OwnTheReference); #ifdef NUX_DEBUG std::ostringstream sout; if (__Nux_FileName__) sout << __Nux_FileName__; else sout << ""; sout << ":" << __Nux_LineNumber__; allocation_location_ = sout.str(); #endif } Object::~Object() { if (IsHeapAllocated()) { // If the object has properly been UnReference, it should have gone // through Destroy(). if that is the case then _reference_count should // be NULL or its value (returned by GetValue ()) should be equal to 0; // We can use this to detect when delete is called directly on an // object. if (reference_count_->GetValue() > 0) { LOG_WARN(logger) << "Invalid object destruction, still has " << reference_count_->GetValue() << " references." << "\nObject allocated at: " << GetAllocationLocation() << "\n"; } } delete reference_count_; delete objectptr_count_; } bool Object::Reference() { if (!IsHeapAllocated()) { LOG_WARN(logger) << "Trying to reference an object that was not heap allocated." << "\nObject allocated at: " << GetAllocationLocation() << "\n"; return false; } if (!OwnsTheReference()) { SetOwnedReference(true); // The ref count remains at 1. Exit the method. return true; } reference_count_->Increment(); return true; } bool Object::UnReference() { if (!IsHeapAllocated()) { LOG_WARN(logger) << "Trying to un-reference an object that was not heap allocated." << "\nObject allocated at: " << GetAllocationLocation() << "\n"; return false; } if (objectptr_count_->GetValue() == reference_count_->GetValue()) { // There are ObjectPtr's hosting this object. Release all of them to // destroy this object. This prevent from calling UnReference () many // times and destroying the object when there are ObjectPtr's hosting // it. This method should not be called directly in that case. LOG_WARN(logger) << "There are ObjectPtr hosting this object. " << "Release all of them to destroy this object. " << "\nObject allocated at: " << GetAllocationLocation() << "\n"; #if defined(NUX_OS_LINUX) LOG_WARN(logger) << "UnReference occuring here: \n" << logging::Backtrace(); #endif return false; } reference_count_->Decrement(); if (reference_count_->GetValue() == 0) { Destroy(); return true; } return false; } bool Object::SinkReference() { return Reference(); } bool Object::Dispose() { // The intent of the Dispose call is to destroy objects with a float // reference (reference count is equal to 1 and the '_owns_the_reference' // flag is set to false). In Nux, only widgets object can have a floating // reference. And widgets are only visible if added to the widget tree. // When an object with a floating reference is added to the widget tree, // it becomes "owned'. It looses it floating reference status but it still // has a reference count number of 1. In practice, since widgets must be // added to the widget tree, there should never be a need to call Dispose // (except in a few cases). // Dispose() was designed to only destroy objects with floating // references, while UnReference() destroys objects that are "owned". // That is now relaxed. Dispose() calls UnReference(). return UnReference(); } void Object::Destroy() { #ifdef NUX_DEBUG static int delete_depth = 0; ++delete_depth; std::string obj_type = GetTypeName(); LOG_TRACE(logger) << "Depth: " << delete_depth << ", about to delete " << obj_type << " allocated at " << GetAllocationLocation(); #endif // Weak smart pointers will clear their pointers when they get this signal. object_destroyed.emit(this); delete this; #ifdef NUX_DEBUG LOG_TRACE(logger) << "Depth: " << delete_depth << ", delete successful for " << obj_type; --delete_depth; #endif } int Object::GetReferenceCount() const { return reference_count_->GetValue(); } int Object::ObjectPtrCount() const { return objectptr_count_->GetValue(); } std::string Object::GetAllocationLocation() const { return allocation_location_; } std::string Object::GetTypeName() const { return Type().name; } } nux-4.0.8+16.04.20160209/NuxCore/Color.cpp0000644000015600001650000002627312656236757020103 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "Color.h" #include "ColorPrivate.h" #include #include #include #define NUX_RGBA_GET_ALPHA(rgba) ((rgba) >> 24) #define NUX_RGBA_GET_RED(rgba) (((rgba) >> 16) & 0xff) #define NUX_RGBA_GET_GREEN(rgba) (((rgba) >> 8) & 0xff) #define NUX_RGBA_GET_BLUE(rgba) ((rgba) & 0xff) namespace nux { namespace color { Color::Color() : red(0.0f) , green(0.0f) , blue(0.0f) , alpha(1.0f) , premultiplied_(false) {} Color::Color(RedGreenBlue const& rgb, float a) : red(rgb.red) , green(rgb.green) , blue(rgb.blue) , alpha(a) , premultiplied_(false) {} Color::Color (unsigned int c) : red(NUX_RGBA_GET_RED(c) / 255.0f) , green(NUX_RGBA_GET_GREEN(c) / 255.0f) , blue(NUX_RGBA_GET_BLUE(c) / 255.0f) , alpha(NUX_RGBA_GET_ALPHA(c) / 255.0f) , premultiplied_(false) {} Color::Color(int r, int g, int b) : red(r / 255.0f) , green(g / 255.0f) , blue(b / 255.0f) , alpha(1.0f) , premultiplied_(false) {} Color::Color(float r, float g, float b, float a) : red(r) , green(g) , blue(b) , alpha(a) , premultiplied_(false) {} Color::Color(std::string const& hex) : red(0.0f) , green(0.0f) , blue(0.0f) , alpha(1.0f) , premultiplied_(false) { HexToRGBA(hex, red, green, blue, alpha); } Color Color::GetPremultiplied() { if (premultiplied_) { // Already pre-multiplied. Return *this; return *this; } Color c; c.SetPremultiplied(red, green, blue, alpha); return c; } void Color::SetPremultiplied(float r, float g, float b, float a) { red = r * a; green = g * a; blue = b * a; alpha = a; premultiplied_ = true; } bool Color::IsPremultiplied() { return premultiplied_; } bool operator == (const Color& lhs, const Color& rhs) { return (lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue && lhs.alpha == rhs.alpha && lhs.premultiplied_ == rhs.premultiplied_); } bool operator != (const Color& lhs, const Color& rhs) { return !(lhs == rhs); } Color RandomColor() { return Color(RandomColorINT()); } unsigned int RandomColorINT() { // std::rand isn't defined to be more random than 2^15, so we need // to generate the full unsigned in chunks. // MSB is alpha, which is set to 255. The next three bytes are // red, green, blue. return (0xff << 24) | ((std::rand() & 0xff) << 16) | ((std::rand() & 0xff) << 8) | (std::rand() & 0xff); } Color operator + (Color const& lhs, Color const& rhs) { return Color(lhs.red + rhs.red, lhs.green + rhs.green, lhs.blue + rhs.blue, lhs.alpha + rhs.alpha); } Color operator - (Color const& lhs, Color const& rhs) { return Color(lhs.red - rhs.red, lhs.green - rhs.green, lhs.blue - rhs.blue, lhs.alpha - rhs.alpha); } Color operator + (float scalar, Color const& c) { return Color(c.red + scalar, c.green + scalar, c.blue + scalar, c.alpha + scalar); } Color operator + (Color const& c, float scalar) { return scalar + c; } Color operator - (float scalar, Color const& c) { return Color(scalar - c.red, scalar - c.green, scalar - c.blue, scalar - c.alpha); } Color operator - (Color const& c, float scalar) { return Color(c.red - scalar, c.green - scalar, c.blue - scalar, c.alpha - scalar); } Color operator * (float scalar, Color const& c) { return Color(c.red * scalar, c.green * scalar, c.blue * scalar, c.alpha * scalar); } Color operator * (Color const& c, float scalar) { return scalar * c; } // The Hue/Saturation/Value model was created by A. R. Smith in 1978. It is // based on such intuitive color characteristics as tint, shade and tone (or // family, purety and intensity). The coordinate system is cylindrical, and // the colors are defined inside a hexcone. The hue value H runs from 0 to // 360. The saturation S is the degree of strength or purity and is from 0 to // 1. Purity is how much white is added to the color, so S=1 makes the purest // color (no white). Brightness V also ranges from 0 to 1, where 0 is the // black. There is no transformation matrix for RGB/HSV conversion, but the // algorithm follows: // r,g,b values are from 0 to 1 // h = [0,360], s = [0,1], v = [0,1] // if s == 0, then h = -1 (undefined) void RGBtoHSV(float r, float g, float b, float& h, float& s, float& v) { float mini, maxi, delta; mini = std::min(std::min(r, g), b); maxi = std::max(std::max(r, g), b); v = maxi; delta = maxi - mini; if (maxi != 0) { s = delta / maxi; } else { // MAX = 0 (i.e. if v = 0), then s is undefined. r = g = b = 0 s = 0; h = -1; return; } if (delta == 0) // MAX = MIN (i.e. s = 0), then h is undefined. r = g = b { h = 0; s = 0; return; } if (r == maxi) h = (g - b) / delta; // between yellow & magenta else if (g == maxi) h = 2 + (b - r) / delta; // between cyan & yellow else h = 4 + (r - g) / delta; // between magenta & cyan h *= 60; // degrees if (h < 0) h += 360; // convert h from [0, 360] to [0, 1] h = h / 360.0f; } void HSVtoRGB(float& r, float& g, float& b, float h, float s, float v ) { int i; float f, p, q, t; // convert h from [0, 1] to [0, 360] h = h * 360.0f; if (s == 0) { // achromatic (grey) r = g = b = v; return; } h /= 60.0f; // sector 0 to 5 i = (int) std::floor(h); f = h - i; // factorial part of h p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch ( i ) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: // case 5: r = v; g = p; b = q; break; } } ///////////////////////// // HLS-RGB Conversions // ///////////////////////// // Static function. Auxiliary to HLS2RGB(). static float HLStoRGB_(float rn1, float rn2, float huei) { float hue = huei; if (hue > 360.0f) hue = hue - 360.0f; if (hue < 0.0f) hue = hue + 360.0f; if (hue < 60.0f ) return rn1 + (rn2 - rn1) * hue / 60.0f; if (hue < 180.0f) return rn2; if (hue < 240.0f) return rn1 + (rn2 - rn1) * (240.0f - hue) / 60.0f; return rn1; } void HLStoRGB(float& r, float& g, float& b, float hue, float light, float satur) { // Static method to compute RGB from HLS. The l and s are between [0,1] // and h is between [0, 1]. The returned r,g,b triplet is between [0,1]. hue *= 360.0f; float rh, rl, rs, rm1, rm2; rh = rl = rs = 0; if (hue > 0) rh = hue; if (rh > 360.0f) rh = 360.0f; if (light > 0) rl = light; if (rl > 1) rl = 1; if (satur > 0) rs = satur; if (rs > 1) rs = 1.0f; if (rl <= 0.5f) rm2 = rl * (1.0f + rs); else rm2 = rl + rs - rl * rs; rm1 = 2.0f * rl - rm2; if (!rs) { r = rl; g = rl; b = rl; return; } r = HLStoRGB_(rm1, rm2, rh + 120); g = HLStoRGB_(rm1, rm2, rh); b = HLStoRGB_(rm1, rm2, rh - 120); } void RGBtoHLS(float rr, float gg, float bb, float& hue, float& light, float& satur) { // Static method to compute HLS from RGB. The r,g,b triplet is between // [0,1], hue is between [0,1], light and satur are [0,1]. float rnorm, gnorm, bnorm, minval, maxval, msum, mdiff, r, g, b; r = g = b = 0; if (rr > 0) r = rr; if (r > 1) r = 1; if (gg > 0) g = gg; if (g > 1) g = 1; if (bb > 0) b = bb; if (b > 1) b = 1; minval = r; if (g < minval) minval = g; if (b < minval) minval = b; maxval = r; if (g > maxval) maxval = g; if (b > maxval) maxval = b; rnorm = gnorm = bnorm = 0; mdiff = maxval - minval; msum = maxval + minval; light = 0.5f * msum; if (maxval != minval) { rnorm = (maxval - r) / mdiff; gnorm = (maxval - g) / mdiff; bnorm = (maxval - b) / mdiff; } else { satur = hue = 0; return; } if (light < 0.5f) satur = mdiff / msum; else satur = mdiff / (2.0f - msum); if (r == maxval) hue = 60.0f * (6.0f + bnorm - gnorm); else if (g == maxval) hue = 60.0f * (2.0f + rnorm - bnorm); else hue = 60.0f * (4.0f + gnorm - rnorm); if (hue > 360) hue = hue - 360; hue = hue / 360.0f; } RedGreenBlue::RedGreenBlue(float r, float g, float b) : red(r) , green(g) , blue(b) {} RedGreenBlue::RedGreenBlue(Color const& color) : red(color.red) , green(color.green) , blue(color.blue) {} RedGreenBlue::RedGreenBlue(HueSaturationValue const& hsv) { HSVtoRGB(red, green, blue, hsv.hue, hsv.saturation, hsv.value); } RedGreenBlue::RedGreenBlue(HueLightnessSaturation const& hls) { HLStoRGB(red, green, blue, hls.hue, hls.lightness, hls.saturation); } HueSaturationValue::HueSaturationValue(float h, float s, float v) : hue(h) , saturation(s) , value(v) {} HueSaturationValue::HueSaturationValue(RedGreenBlue const& rgb) { RGBtoHSV(rgb.red, rgb.green, rgb.blue, hue, saturation, value); } HueSaturationValue::HueSaturationValue(Color const& c) { RGBtoHSV(c.red, c.green, c.blue, hue, saturation, value); } HueLightnessSaturation::HueLightnessSaturation(float h, float l, float s) : hue(h) , lightness(l) , saturation(s) {} HueLightnessSaturation::HueLightnessSaturation(RedGreenBlue const& rgb) { RGBtoHLS(rgb.red, rgb.green, rgb.blue, hue, lightness, saturation); } HueLightnessSaturation::HueLightnessSaturation(Color const& c) { RGBtoHLS(c.red, c.green, c.blue, hue, lightness, saturation); } } } nux-4.0.8+16.04.20160209/NuxCore/NuxCore.cpp0000644000015600001650000001046112656236757020400 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { // MessageBox resolves to: // MessageBoxA, if UNICODE is not defined // MessageBoxW, if UNICODE is defined // In all cases in the code, it is assumed that we have UNICODE and _UNICODE defined or not. // We have no support for cases of (UNICODE, !_UNICODE) or (!UNICODE, _UNICODE) // TCHAR resolves: // char, if _UNICODE is not defined // wchar_t, if _UNICODE is defined // Set to true to disable the popping of dialog box. The message will go to the log. const bool GNoDialog = false; /*----------------------------------------------------------------------------- Formatted printing and messages. -----------------------------------------------------------------------------*/ #if defined(NUX_OS_WINDOWS) unsigned int GetVariableArgs ( TCHAR *Dest, unsigned int Size, unsigned int Count, const TCHAR*& Fmt, va_list ArgPtr) #else unsigned int GetVariableArgs ( TCHAR *Dest, unsigned int /* Size */, unsigned int Count, const TCHAR*& Fmt, va_list ArgPtr) #endif { unsigned int Result = VSNTPRINTF_S (Dest, Size, Count, Fmt, ArgPtr); va_end (ArgPtr); return Result; } #if defined(NUX_OS_WINDOWS) unsigned int GetVariableArgsAnsi(ANSICHAR *Dest, unsigned int Size, unsigned int Count, const ANSICHAR*& Fmt, va_list ArgPtr) #else unsigned int GetVariableArgsAnsi ( ANSICHAR *Dest, unsigned int /* Size */, unsigned int Count, const ANSICHAR*& Fmt, va_list ArgPtr) #endif { unsigned int Result = VSNPRINTF_S (Dest, Size, Count, Fmt, ArgPtr); va_end (ArgPtr); return Result; } // This function can be used to print anything before the other output are initialized. void PrintOutputDebugString (const TCHAR *Format, ... ) { TCHAR TempStr[4096]; GET_VARARGS ( TempStr, 4096, NUX_ARRAY_COUNT (TempStr) - 1, Format ); #ifdef _WIN32 OutputDebugString ( TempStr ); #else printf ("%s\n", TCHAR_TO_ANSI (TempStr) ); #endif } void LogOutputAssertMessage (const ANSICHAR *File, int Line, const TCHAR *Format/*=TEXT("")*/, ... ) { TCHAR TempStr[4096]; GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Format ); // Logged to a file... Put "\r\n" at the end of each line. if (LogOutputRedirector::Ready() ) GLogDevice.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("Assertion failed: %s\r\n [File:%s]\r\n [Line: %i]\r\n"), (const TCHAR *) TempStr, ANSI_TO_TCHAR (File), Line); } void LogOutputErrorMessage (const ANSICHAR *File, int Line, const TCHAR *Format/*=TEXT("")*/, ... ) { TCHAR TempStr[4096]; GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Format ); if (LogOutputRedirector::Ready() ) GLogDevice.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("Error: %s\r\n [File:%s]\r\n [Line: %d]\r\n"), (const TCHAR *) TempStr, ANSI_TO_TCHAR (File), Line); } void LogOutputDebugMessage (const TCHAR *Format/*=TEXT("")*/, ... ) { TCHAR TempStr[4096]; GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Format ); if (LogOutputRedirector::Ready() ) GLogDevice.LogFunction (NUX_MSG_SEVERITY_NONE, TempStr); } void LogOutputSeverityMessage (int Severity, const TCHAR *Format/*=TEXT("")*/, ... ) { TCHAR TempStr[4096]; GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Format ); if (LogOutputRedirector::Ready() ) GLogDevice.LogFunction (Severity, TempStr); } bool OutputRedirectorReady() { return LogOutputRedirector::Ready(); } } nux-4.0.8+16.04.20160209/NuxCore/ObjectType.cpp0000644000015600001650000000162212656236757021064 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "ObjectType.h" namespace nux { const NObjectType NObjectType::Null_Type("NULL", 0); } nux-4.0.8+16.04.20160209/NuxCore/Plugin/0000755000015600001650000000000012656240224017525 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/Plugin/NPluginInterface.h0000644000015600001650000000214712656236757023117 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NPLUGININTERFACE_H #define NPLUGININTERFACE_H #include "NPlugin.h" namespace nux { class NPluginInterface { public: NPluginInterface() {} virtual ~NPluginInterface() {} virtual int Activate() = 0; virtual int Execute() = 0; virtual int Destroy() = 0; }; } #endif // NPLUGININTERFACE_H nux-4.0.8+16.04.20160209/NuxCore/Plugin/NPlugin.h0000644000015600001650000000364612656236757021303 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NPLUGIN_H #define NPLUGIN_H #define NUX_DECLARE_PLUGIN(x) extern "C"{__declspec(dllexport) NPluginInterface * MakePlugin(){ return new x;}} #define NUX_SET_PLUGIN_TYPE(x) extern "C"{__declspec(dllexport) TCHAR * GetPluginType(){ return x;}} #define NUX_SET_PLUGIN_NAME(x) extern "C"{__declspec(dllexport) TCHAR * GetPluginName(){ return x;}} namespace nux { class NPluginInterface; typedef NPluginInterface * (*PLUGIN_FACTORYFUNC) (); typedef TCHAR * (*PLUGIN_TEXTFUNC) (); class NPlugin { public: NPlugin() { ClearMembers(); } ~NPlugin(); NPluginInterface *MakeNewInstance(); void SetFileName (const TCHAR *nm); TCHAR *GetName() { return pluginName; } TCHAR *GetType() { return pluginType; } void SetName (const TCHAR *nm); void SetType (const TCHAR *nm); private: void ClearMembers() { pluginType = NULL; pluginName = NULL; filename = NULL; dllHandle = NULL; } TCHAR *filename; TCHAR *pluginType; TCHAR *pluginName; HINSTANCE dllHandle; PLUGIN_FACTORYFUNC funcHandle; }; } #endif // NPLUGIN_H nux-4.0.8+16.04.20160209/NuxCore/Plugin/NPluging.cpp0000644000015600001650000000345412656236757022002 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "NPlugin.h" namespace nux { NPlugin::~NPlugin() { delete[] filename; delete[] pluginType; delete[] pluginName; if (dllHandle) FreeLibrary (dllHandle); ClearMembers(); } void NPlugin::SetFileName (const TCHAR *nm) { size_t sz = _tcslen (nm) + 1; filename = new TCHAR[sz]; STRCPY_S (filename, sz, nm); } void NPlugin::SetName (const TCHAR *nm) { size_t sz = _tcslen (nm) + 1; pluginName = new TCHAR[sz]; STRCPY_S (pluginName, sz, nm); } void NPlugin::SetType (const TCHAR *nm) { size_t sz = _tcslen (nm) + 1; pluginType = new TCHAR[sz]; STRCPY_S (pluginType, sz, nm); } NPluginInterface *NPlugin::MakeNewInstance() { if (!dllHandle) dllHandle = LoadLibrary (filename); if (dllHandle != NULL) { funcHandle = reinterpret_cast (GetProcAddress (dllHandle, "MakePlugin") ); if (funcHandle != NULL) { return funcHandle(); } } return NULL; } } nux-4.0.8+16.04.20160209/NuxCore/Plugin/NPluginManager.cpp0000644000015600001650000000542512656236757023126 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "NPluginInterface.h" #include "NPluginManager.h" namespace nux { void NPluginManager::GetPluginList (TCHAR *dirPath, bool addToList) { if (!addToList) ClearPluginList(); WIN32_FIND_DATA fd; TCHAR fname[MAX_PATH]; STRCPY_S (fname, MAX_PATH, dirPath); size_t len = _tcslen (fname); if (fname[len-1] == TEXT ('/') || fname[len-1] == TEXT ('\\') ) STRCAT_S (fname, MAX_PATH, TEXT ("*.dll") ); else STRCAT_S (fname, MAX_PATH, TEXT ("\\*.dll") ); HANDLE hFind = FindFirstFile (fname, &fd); NFileName Path = dirPath; Path.RemoveBackSlashAtEnd(); Path.RemoveSlashAtEnd(); if (hFind == INVALID_HANDLE_VALUE) { FindClose (hFind); return; } do { HINSTANCE dllHandle = NULL; try { if (! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { NFileName FilePath = Path + NUX_PATH_SEPARATOR_STRING + fd.cFileName; dllHandle = LoadLibrary (FilePath.c_str() ); if (dllHandle != NULL) { PLUGIN_FACTORYFUNC funcHandle; funcHandle = reinterpret_cast (GetProcAddress (dllHandle, "makePlugin") ); if (funcHandle != NULL) { NPlugin *curPlugin = new NPlugin(); curPlugin->SetFileName (FilePath.c_str() ); PLUGIN_TEXTFUNC textFunc; textFunc = reinterpret_cast (GetProcAddress (dllHandle, "getPluginType") ); curPlugin->SetType (textFunc() ); textFunc = reinterpret_cast (GetProcAddress (dllHandle, "getPluginName") ); curPlugin->SetName (textFunc() ); pluginRegister.push_back (curPlugin); } FreeLibrary (dllHandle); } } } catch (...) { if (dllHandle != NULL) FreeLibrary (dllHandle); } } while (FindNextFile (hFind, &fd) ); FindClose (hFind); } } nux-4.0.8+16.04.20160209/NuxCore/Plugin/NPluginManager.h0000644000015600001650000000333712656236757022573 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NPLUGINMANAGER_H #define NPLUGINMANAGER_H #include "NPlugin.h" namespace nux { class NPluginManager { public: NPluginManager() {} ~NPluginManager() { ClearPluginList(); } void GetPluginList (TCHAR *dirPath, bool addToList = false); NPluginInterface *MakeNewPluginInstance (int index) { return pluginRegister.at (index)->MakeNewInstance(); } int GetNumPlugins() { return int (pluginRegister.size() ); } TCHAR *GetPluginName (int index) { return pluginRegister.at (index)->GetName(); } TCHAR *KetPluginType (int index) { return pluginRegister.at (index)->GetType(); } private: void ClearPluginList() { for (unsigned int i = 0; i < pluginRegister.size(); i++) { delete pluginRegister.at (i); } pluginRegister.clear(); } std::vector pluginRegister; }; } #endif // NPLUGINMANAGER_H nux-4.0.8+16.04.20160209/NuxCore/TimeFunctions.cpp0000644000015600001650000001362212656236757021606 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { TimeStamp::TimeStamp() { GetTime(); } TimeStamp::~TimeStamp() { m_Year = 1970; m_Month = 1; m_Day = 1; m_Hour = 0; m_Minute = 0; m_Second = 0; m_MicroSecond = 0; } long long TimeStamp::GetJulianDayNumber (void) const { long long JDN = m_Day - 32075L + 1461L * (m_Year + 4800L + (m_Month - 14L) / 12L) / 4L + 367L * (m_Month - 2L - ( (m_Month - 14L) / 12L) * 12L) / 12L - 3L * ( (m_Year + 4900L - (m_Month - 14L) / 12L) / 100L) / 4L; return JDN; } double TimeStamp::GetJulianDate() const { double JD = GetJulianDayNumber() + (m_Hour - 12) / 1440.0f + m_Minute / 1440.0f + m_Second / 86400.0f; return JD; } unsigned int TimeStamp::GetSecondOfDay (void) const { return m_Hour * 60 * 60 + m_Minute * 60 + m_Second; } bool TimeStamp::operator == (TimeStamp &Other) const { bool b = (m_Year == Other.m_Year) && (m_Day == Other.m_Day) && (m_Month == Other.m_Month) && (m_Hour == Other.m_Hour) && (m_Minute == Other.m_Minute) && (m_Second == Other.m_Second); return b; } bool TimeStamp::operator != (TimeStamp &Other) const { if (*this == Other) return false; return true; } bool TimeStamp::operator < (TimeStamp &Other) const { double JD = GetJulianDate(); if (JD < Other.GetJulianDate() ) return true; return false; } bool TimeStamp::operator > (TimeStamp &Other) const { double JD = GetJulianDate(); if (JD > Other.GetJulianDate() ) return true; return false; } bool TimeStamp::operator >= (TimeStamp &Other) const { double JD = GetJulianDate(); if (JD >= Other.GetJulianDate() ) return true; return false; } bool TimeStamp::operator <= (TimeStamp &Other) const { double JD = GetJulianDate(); if (JD <= Other.GetJulianDate() ) return true; return false; } void TimeStamp::GetTime() { GetLocalTime (m_Year, m_Month, m_Day, m_Hour, m_Minute, m_Second, m_MicroSecond); } std::string GetFormattedLocalTime() { TCHAR buffer[1024]; Memset(buffer, 0, 1024); unsigned int Year; unsigned int Month; unsigned int Day; unsigned int Hour; unsigned int Minute; unsigned int Second; unsigned int MicroSec; GetLocalTime (Year, Month, Day, Hour, Minute, Second, MicroSec); #ifdef _WIN32 _stprintf_s (buffer, 1024 - 1, TEXT ("%d:%d:%d: %d/%d/%d"), Hour, Minute, Second, Day, Month, Year); std::string result = buffer; #else _stprintf (buffer, TEXT ("%d:%d:%d: %d/%d/%d"), Hour, Minute, Second, Day, Month, Year); std::string result = buffer; #endif return result; } void GetLocalTime (unsigned int &Year, unsigned int &Month, unsigned int &Day, unsigned int &Hour, unsigned int &Min, unsigned int &Sec, unsigned int &MicroSec) { #ifdef NUX_OS_WINDOWS SYSTEMTIME st; ::GetLocalTime (&st); Year = st.wYear; Month = st.wMonth; Day = st.wDay; Hour = st.wHour; Min = st.wMinute; Sec = st.wSecond; MicroSec = st.wMilliseconds * 1000; #elif (defined NUX_OS_LINUX) || (defined NUX_OS_MACOSX) time_t dt; struct tm dc; time (&dt); localtime_r (&dt, &dc); Year = dc.tm_year - 100 + 2000; Month = dc.tm_mon + 1; Day = dc.tm_mday; Hour = dc.tm_hour; Min = dc.tm_min; Sec = dc.tm_sec; MicroSec = 0; #else nuxAssert (0); #endif } void GetUTCTime (unsigned int &Year, unsigned int &Month, unsigned int &Day, unsigned int &Hour, unsigned int &Min, unsigned int &Sec, unsigned int &MicroSec) { #if (defined _WIN32) SYSTEMTIME st; ::GetSystemTime (&st); Year = st.wYear; Month = st.wMonth; Day = st.wDay; Hour = st.wHour; Min = st.wMinute; Sec = st.wSecond; MicroSec = st.wMilliseconds * 1000; #elif (defined NUX_OS_LINUX) || (defined NUX_OS_MACOSX) time_t dt; struct tm dc; time (&dt); gmtime_r (&dt, &dc); Year = dc.tm_year - 100 + 2000; Month = dc.tm_mon + 1; Day = dc.tm_mday; Hour = dc.tm_hour; Min = dc.tm_min; Sec = dc.tm_sec; MicroSec = 0; #else nuxAssert (0); #endif } long GetTimeZone() { #if (defined _WIN32) long seconds = 0; _get_timezone (&seconds); long hour = seconds / 3600; return hour; #else return 0; #endif } void SleepForMilliseconds (unsigned int Milliseconds) { #if defined(NUX_OS_WINDOWS) Sleep (Milliseconds); #elif defined(NUX_OS_LINUX) int ret = usleep (Milliseconds * 1000); if (ret != 0) { nuxDebugMsg (TEXT ("[SleepForMilliseconds] usleep has failed.") ); } #else #error Sleep(milliseconds) is not implemented for this platform. #endif } } nux-4.0.8+16.04.20160209/NuxCore/nux-core.pc.in0000644000015600001650000000043712656236757021004 0ustar pbuserpbgroup00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: NuxCore Description: Core objects and utilities for Nux Version: @VERSION@ Libs: -L${libdir} -lnux-core-@NUX_API_VERSION@ Cflags: -I${includedir}/Nux-@NUX_API_VERSION@ Requires: glib-2.0 sigc++-2.0 nux-4.0.8+16.04.20160209/NuxCore/Error.h0000644000015600001650000000261712656236757017557 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NYERROR_H #define NYERROR_H //#include //#include //#include //#include //void ny_output_error(const char *error_msg); //void ny_output_system_error(const char *error_msg); // //void ny_output_error(const char *error_msg) //{ // cout << error_msg << endl; //} // //void ny_output_system_error(const char *error_msg) //{ // perror(error_msg); //} typedef enum { HR_SUCCESS, HR_FAIL, HR_INVALID_ARG, HR_INVALID_CALL, HR_NOT_ENOUGH_MEMORY, HR_FILE_NOT_FOUND, HR_FILE_IO_FAIL, HR_UNSUPPORTED_FORMAT, HR_UNKNOW_ERROR } HReport; #endif // NYERROR_H nux-4.0.8+16.04.20160209/NuxCore/Math/0000755000015600001650000000000012656240224017160 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/Math/Spline.cpp0000644000015600001650000001741312656236757021144 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Spline.h" #include "MathFunctions.h" namespace nux { double *CubicSpline::SolveTridiag ( int n, double a[], double b[] ) { int i; double *x; double xmult; // // Check. // for ( i = 0; i < n; i++ ) { if ( a[1+i*3] == 0.0 ) { return NULL; } } x = new double[n]; for ( i = 0; i < n; i++ ) { x[i] = b[i]; } for ( i = 1; i < n; i++ ) { xmult = a[2+ (i-1) *3] / a[1+ (i-1) *3]; a[1+i*3] = a[1+i*3] - xmult * a[0+i*3]; x[i] = x[i] - xmult * x[i-1]; } x[n-1] = x[n-1] / a[1+ (n-1) *3]; for ( i = n - 2; 0 <= i; i-- ) { x[i] = ( x[i] - a[0+ (i+1) *3] * x[i+1] ) / a[1+i*3]; } return x; } CubicSpline::CubicSpline (int numpoint, std::vector x_array, std::vector y_array, int ibcbeg, double ybcbeg, int ibcend, double ybcend ) { if ( ( (int) x_array.size() != numpoint) || ( (int) y_array.size() != numpoint) ) { NUX_BREAK_ASM_INT3; } np = numpoint; t = new double[np]; y = new double[np]; ddy = 0; //new double[np]; for (int i = 0; i < np; i++) { t[i] = x_array[i]; y[i] = y_array[i]; //ddy[i] = 0; } ibcbeg_ = ibcbeg; ybcbeg_ = ybcbeg; ibcend_ = ibcend; ybcend_ = ybcend; Compute (ibcbeg_, ybcbeg_, ibcend_, ybcend_ ); } CubicSpline::CubicSpline() { np = 2; t = new double[np]; y = new double[np]; ddy = 0; //new double[np]; t[0] = 0.0; t[1] = 1.0; y[0] = 0.0; y[1] = 1.0; ibcbeg_ = 0; ybcbeg_ = 0; ibcend_ = 0; ybcend_ = 0; Compute (ibcbeg_, ybcbeg_, ibcend_, ybcend_ ); } CubicSpline::CubicSpline (const CubicSpline &Other) { if (Other.np == 0) NUX_BREAK_ASM_INT3; np = Other.np; t = new double[np]; y = new double[np]; for (int i = 0; i < np; i++) { t[i] = Other.t[i]; y[i] = Other.y[i]; } ibcbeg_ = Other.ibcbeg_; ybcbeg_ = Other.ybcbeg_; ibcend_ = Other.ibcend_; ybcend_ = Other.ybcend_; Compute (ibcbeg_, ybcbeg_, ibcend_, ybcend_ ); } CubicSpline &CubicSpline::operator = (const CubicSpline &Other) { if (Other.np == 0) NUX_BREAK_ASM_INT3; np = Other.np; t = new double[np]; y = new double[np]; for (int i = 0; i < np; i++) { t[i] = Other.t[i]; y[i] = Other.y[i]; } ibcbeg_ = Other.ibcbeg_; ybcbeg_ = Other.ybcbeg_; ibcend_ = Other.ibcend_; ybcend_ = Other.ybcend_; Compute (ibcbeg_, ybcbeg_, ibcend_, ybcend_); return *this; } void CubicSpline::Set (int numpoint, std::vector x_array, std::vector y_array, int ibcbeg, double ybcbeg, int ibcend, double ybcend) { if (numpoint <= 1) { np = 0; return; } if ( ( (int) x_array.size() != numpoint) || ( (int) y_array.size() != numpoint) ) { NUX_BREAK_ASM_INT3; } np = numpoint; if (t) delete [] t; if (y) delete [] y; if (ddy) delete [] ddy; t = new double[np]; y = new double[np]; ddy = 0; for (int i = 0; i < np; i++) { t[i] = x_array[i]; y[i] = y_array[i]; } Compute (ibcbeg, ybcbeg, ibcend, ybcend ); } CubicSpline::~CubicSpline() { if (t) delete [] t; if (y) delete [] y; if (ddy) delete [] ddy; } double *CubicSpline::Compute (int ibcbeg, double ybcbeg, int ibcend, double ybcend ) { double *a; double *b; int i; // // Check. // if ( np <= 1 ) { //"Fatal error: The number of data points N must be at least 2.\n"; NUX_BREAK_ASM_INT3; return 0; } for ( i = 0; i < np - 1; i++ ) { if ( t[i+1] <= t[i] ) { //"Fatal error: The knots must be strictly increasing, but\n"; NUX_BREAK_ASM_INT3; return NULL; } } a = new double[3*np]; b = new double[np]; // // Set up the first equation. // if ( ibcbeg == 0 ) { b[0] = 0.0; a[1+0*3] = 1.0; a[0+1*3] = -1.0; } else if ( ibcbeg == 1 ) { b[0] = ( y[1] - y[0] ) / ( t[1] - t[0] ) - ybcbeg; a[1+0*3] = ( t[1] - t[0] ) / 3.0; a[0+1*3] = ( t[1] - t[0] ) / 6.0; } else if ( ibcbeg == 2 ) { b[0] = ybcbeg; a[1+0*3] = 1.0; a[0+1*3] = 0.0; } else { //"Fatal error: IBCBEG must be 0, 1 or 2.\n"; NUX_BREAK_ASM_INT3; delete [] a; delete [] b; return NULL; } // // Set up the intermediate equations. // for ( i = 1; i < np - 1; i++ ) { b[i] = ( y[i+1] - y[i] ) / ( t[i+1] - t[i] ) - ( y[i] - y[i-1] ) / ( t[i] - t[i-1] ); a[2+ (i-1) *3] = ( t[i] - t[i-1] ) / 6.0; a[1+ i *3] = ( t[i+1] - t[i-1] ) / 3.0; a[0+ (i+1) *3] = ( t[i+1] - t[i] ) / 6.0; } // // Set up the last equation. // if ( ibcend == 0 ) { b[np-1] = 0.0; a[2+ (np-2) *3] = -1.0; a[1+ (np-1) *3] = 1.0; } else if ( ibcend == 1 ) { b[np-1] = ybcend - ( y[np-1] - y[np-2] ) / ( t[np-1] - t[np-2] ); a[2+ (np-2) *3] = ( t[np-1] - t[np-2] ) / 6.0; a[1+ (np-1) *3] = ( t[np-1] - t[np-2] ) / 3.0; } else if ( ibcend == 2 ) { b[np-1] = ybcend; a[2+ (np-2) *3] = 0.0; a[1+ (np-1) *3] = 1.0; } else { //"Fatal error: IBCEND must be 0, 1 or 2.\n"; NUX_BREAK_ASM_INT3; delete [] a; delete [] b; return NULL; } // // Solve the linear system. // if ( np == 2 && ibcbeg == 0 && ibcend == 0 ) { ddy = new double[2]; ddy[0] = 0.0; ddy[1] = 0.0; } else { if (ddy) { delete [] ddy; } ddy = SolveTridiag ( np, a, b ); if ( !ddy ) { //"Fatal error: The linear system could not be solved.\n"; NUX_BREAK_ASM_INT3; delete [] a; delete [] b; return NULL; } } delete [] a; delete [] b; return ddy; } double CubicSpline::Eval (double tval) { double dt; double h; int i; int ival; double yval; // // Determine the interval [ T(I), T(I+1) ] that contains TVAL. // Values below T[0] or above T[N-1] use extrapolation. // if (np <= 1) return 0.0; ival = np - 2; if (tval > t[np-1]) { tval = t[np-1]; } if (tval < t[0]) { tval = t[0]; } for ( i = 0; i < np - 1; i++ ) { if ( tval < t[i+1] ) { ival = i; break; } } // // In the interval I, the polynomial is in terms of a normalized // coordinate between 0 and 1. // dt = tval - t[ival]; h = t[ival+1] - t[ival]; yval = y[ival] + dt * ( ( y[ival+1] - y[ival] ) / h - ( ddy[ival+1] / 6.0 + ddy[ival] / 3.0 ) * h + dt * ( 0.5 * ddy[ival] + dt * ( ( ddy[ival+1] - ddy[ival] ) / ( 6.0 * h ) ) ) ); return yval; } } nux-4.0.8+16.04.20160209/NuxCore/Math/MathFunctions.h0000644000015600001650000000302012656236757022126 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATHFUNCTIONS_H #define MATHFUNCTIONS_H #include "Constants.h" namespace nux { int Factorial (int n); double BinomialCoefficient (int n, int k); //! Template power function. The exponent is an integer. /*! Template power function. The exponent is an integer. */ template inline T PowerInt (T _X, int _Y) // taken from Microsoft { unsigned int _N; if (_Y >= 0) _N = _Y; else _N = -_Y; for (T _Z = T (1); ; _X *= _X) { if ( (_N & 1) != 0) _Z *= _X; if ( (_N >>= 1) == 0) return (_Y < 0 ? T (1) / _Z : _Z); } } double Power (double x, double y); double Log2 (double d); double Floor (double d); } #endif // MATHFUNCTIONS_H nux-4.0.8+16.04.20160209/NuxCore/Math/Trigonometry.h0000644000015600001650000000322212656236757022052 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef TRIGONOMETRY_H #define TRIGONOMETRY_H #include "Vector3.h" namespace nux { // Assume the spherical coordinate system relatively to a right handed xyz, // with Z pointing up. // 0 <= phi < 180 // 0 <= theta < 360 ->>> along X axis, theta = 0. Vector3 SphericalToCartesianXBaseDeg (float r, float theta, float phi); Vector3 SphericalToCartesianXBaseRad (float r, float theta, float phi); // Assume the spherical coordinate system relatively to a right handed xyz, // with Y pointing up. // 0 <= phi < 180 // 0 <= theta < 360 ->>> along Z axis, theta = 0. Vector3 SphericalToCartesianZBaseDeg (float r, float theta, float phi); Vector3 SphericalToCartesianZBaseRad (float r, float theta, float phi); Vector3 CartesianToSphericalXBaseRad (float x, float y, float z); Vector3 CartesianToSphericalZBaseDeg (float x, float y, float z); } #endif // TRIGONOMETRY_H nux-4.0.8+16.04.20160209/NuxCore/Math/Quaternion.cpp0000644000015600001650000003144612656236757022041 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Matrix4.h" #include "Vector3.h" #include "Quaternion.h" // When writing to a matrix at row r and column c use m[r][c]. // When reading from a matrix at row r and column c use m[c][r]. namespace nux { Quaternion::Quaternion() { x = y = z = w = 0.0f; } Quaternion::Quaternion (const Quaternion &quat) { x = quat.x; y = quat.y; z = quat.z; w = quat.w; } Quaternion::Quaternion (const Vector3 &vec, float angle) { FromAngleAxis (vec.x, vec.y, vec.z, angle); } Quaternion::Quaternion (const Vector4 &vec) { FromAngleAxis (vec.w, vec.x, vec.y, vec.z); } Quaternion::Quaternion (float axis_x, float axis_y, float axis_z, float angle_radian) { FromAngleAxis (axis_x, axis_y, axis_z, angle_radian); } Quaternion::Quaternion (float euler_x, float euler_y, float euler_z) { FromEulerZXY (euler_x, euler_y, euler_z); } Quaternion::~Quaternion() { } Quaternion &Quaternion::operator = (const Quaternion &quat) { x = quat.x; y = quat.y; z = quat.z; w = quat.w; return (*this); } Quaternion Quaternion::operator + (const Quaternion &quat) const { Quaternion qt; qt.x = x + quat.x; qt.y = y + quat.y; qt.z = z + quat.z; qt.w = w + quat.w; return qt; } Quaternion Quaternion::operator - (const Quaternion &quat) const { Quaternion qt; qt.x = x - quat.x; qt.y = y - quat.y; qt.z = z - quat.z; qt.w = w - quat.w; return qt; } Quaternion Quaternion::operator * (const Quaternion &quat) const { Quaternion qt; float x1, x2, y1, y2, z1, z2, w1, w2; x1 = x; y1 = y; z1 = z; w1 = w; x2 = quat.x; y2 = quat.y; z2 = quat.z; w2 = quat.w; qt.x = w1 * x2 + x1 * w2 - z1 * y2 + y1 * z2; qt.y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2; qt.z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2; qt.w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2; return qt; } Quaternion Quaternion::operator * (const float &f) const { Quaternion qt; qt.x = x * f; qt.y = y * f; qt.z = z * f; qt.w = w * f; return qt; } Quaternion Quaternion::operator / (const float &f) const { Quaternion qt; qt.x = x / f; qt.y = y / f; qt.z = z / f; qt.w = w / f; return qt; } ////////////////////////////////////////////////////////////////////////// Quaternion &Quaternion::operator += (const Quaternion &quat) { x = x + quat.x; y = y + quat.y; z = z + quat.z; w = w + quat.w; return *this; } Quaternion &Quaternion::operator -= (const Quaternion &quat) { x = x - quat.x; y = y - quat.y; z = z - quat.z; w = w - quat.w; return *this; } Quaternion &Quaternion::operator *= (const Quaternion &quat) { Quaternion qt; float x1, x2, y1, y2, z1, z2, w1, w2; x1 = x; y1 = y; z1 = z; w1 = w; x2 = quat.x; y2 = quat.y; z2 = quat.z; w2 = quat.w; qt.x = w1 * x2 + x1 * w2 - z1 * y2 + y1 * z2; qt.y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2; qt.z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2; qt.w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2; x = qt.x; y = qt.y; z = qt.z; w = qt.w; return *this; } Quaternion &Quaternion::operator *= (const float &f) { x = x * f; y = y * f; z = z * f; w = w * f; return *this; } Quaternion &Quaternion::operator /= (const float &f) { x = x / f; y = y / f; z = z / f; w = w / f; return *this; } Quaternion Quaternion::operator + () const { Quaternion qt; qt.x = x; qt.y = y; qt.z = z; qt.w = w; return qt; } Quaternion Quaternion::operator - () const { Quaternion qt; qt.x = -x; qt.y = -y; qt.z = -z; qt.w = -w; return qt; } bool Quaternion::operator == (const Quaternion &quat) const { if ( (x == quat.x) && (y == quat.y) && (z == quat.z) && (w == quat.w) ) { return true; } return true; } bool Quaternion::operator != ( const Quaternion &quat) const { return ! ( (*this) == quat); } void Quaternion::Conjugate() { x = -x; y = -y; z = -z; } void Quaternion::Inverse() { float len; len = (float) std::sqrt (x * x + y * y + z * z + w * w); Conjugate(); x = x / len; y = y / len; z = z / len; w = w / len; } void Quaternion::Normalize() { float len; len = (float) std::sqrt (x * x + y * y + z * z + w * w); x = x / len; y = y / len; z = z / len; w = w / len; } /***************************************************************************************\ Function: Quaternion::dot_product Description: Compute the dot product of *this and the input quaternion vector Parameters: - quat Return Value: float. Comments: None. \***************************************************************************************/ float Quaternion::DotProduct (const Quaternion &quat) const { float d_p; d_p = x * quat.x + y * quat.y + z * quat.z + w * quat.w; return d_p; } /***************************************************************************************\ Function: Quaternion::length Description: Compute the length of a quaternion vector Parameters: None. Return Value: float Comments: None. \***************************************************************************************/ float Quaternion::Length() const { float len; len = (float) std::sqrt (x * x + y * y + z * z + w * w); return len; } /***************************************************************************************\ Function: Quaternion::FromAngleAxis Description: Set the quaternion to define a rotation of angle_randian around the vector define by (axis_x, axis_y, axis_z) Parameters: - angle_radian: angle in radian - axis_x - axis_y - axis_z Return Value: None. Comments: None. \***************************************************************************************/ void Quaternion::FromAngleAxis (float axis_x, float axis_y, float axis_z, float angle_radian) { float ax = axis_x; float ay = axis_y; float az = axis_z; // required: Normalize the axis float len = 1.0f / (float) std::sqrt ( ax * ax + ay * ay + az * az ); ax = ax * len; ay = ay * len; az = az * len; float sin_theta_over_two = (float) std::sin ( angle_radian / 2.0); x = ax * sin_theta_over_two; y = ay * sin_theta_over_two; z = az * sin_theta_over_two; w = (float) std::cos (angle_radian / 2.0); } /***************************************************************************************\ Function: Quaternion::FromEulerZXY Description: Set the quaternion to define a Euler transform Parameters: - euler_x: rotation angle around X axis (in radian) - euler_y: rotation angle around Y axis (in radian) - euler_z: rotation angle around Z axis (in radian) Return Value: None. Comments: The rotation are applied in the following order: rotation around Y axis rotation around X axis rotation around Z axis \***************************************************************************************/ void Quaternion::FromEulerZXY (float euler_x, float euler_y, float euler_z) { float roll_axis[3] = {0.0f, 0.0f, 1.0f}; float pitch_axis[3] = {1.0f, 0.0f, 0.0f}; float yaw_axis[3] = {0.0f, 1.0f, 0.0f}; Quaternion roll (euler_z, roll_axis[0], roll_axis[1], roll_axis[2]); Quaternion pitch (euler_x, pitch_axis[0], pitch_axis[1], pitch_axis[2]); Quaternion yaw (euler_y, yaw_axis[0], yaw_axis[1], yaw_axis[2]); (*this) = roll * pitch * yaw; } void Quaternion::GetAngleAxis (Vector3 &axis, float &angle_radian) const { Quaternion qt; qt.x = x; qt.y = y; qt.z = z; qt.w = w; // make a unit quaternion qt.Normalize(); // qt = sin(angle/2)*Uq + cos(angle/2) angle_radian = 2.0f * (float) std::acos (qt.w); float one_over_sin = 1.0f / (float) std::sqrt (qt.x * qt.x + qt.y * qt.y + qt.z * qt.z); //float one_over_sin = 1.0f / (float) sin(angle_radian / 2.0f); axis.x = qt.x * one_over_sin; axis.y = qt.y * one_over_sin; axis.z = qt.z * one_over_sin; } /***************************************************************************************\ Function: Quaternion::get_matrix Description: Return a Matrix4 object containing the rotation defined by the quaternion. Parameters: None. Return Value: Matrix4. Comments: None. \***************************************************************************************/ Matrix4 Quaternion::GetMatrix() const { Matrix4 mat4; /*float x = x; float y = y; float z = z; float w = w;*/ float s; s = 2.0f / ( (float) std::sqrt (x * x + y * y + z * z + w * w) ); mat4.m[0][0] = 1.0f - s * (y * y + z * z); mat4.m[0][1] = s * (x * y - w * z); mat4.m[0][2] = s * (x * z + w * y); mat4.m[0][3] = 0.0f; mat4.m[1][0] = s * (x * y + w * z); mat4.m[1][1] = 1.0f - s * (x * x + z * z); mat4.m[1][2] = s * (y * z - w * x); mat4.m[1][3] = 0.0f; mat4.m[2][0] = s * (x * z - w * y); mat4.m[2][1] = s * (y * z + w * x); mat4.m[2][2] = 1.0f - s * (x * x + y * y); mat4.m[2][3] = 0.0f; mat4.m[3][0] = 0.0f; mat4.m[3][1] = 0.0f; mat4.m[3][2] = 0.0f; mat4.m[3][3] = 1.0f; return mat4; } /*const Quaternion operator * (const Quaternion& quat1, const Quaternion& quat2) { Quaternion qt; float x1, x2, y1, y2, z1, z2, w1, w2; x1 = quat1.x; y1 = quat1.y; z1 = quat1.z; w1 = quat1.w; x2 = quat2.x; y2 = quat2.y; z2 = quat2.z; w2 = quat2.w; qt.x = w1*x2 + x1*w2 - z1*y2 + y1*z2; qt.y = w1*y2 + y1*w2 + z1*x2 - x1*z2; qt.z = w1*z2 + z1*w2 + x1*y2 - y1*x2; qt.w = w1*w2 - x1*x2 - y1*y2 - z1*z2; return qt; }*/ Quaternion operator * (float f, const Quaternion &quat) { Quaternion qt; qt.x = quat.x * f; qt.y = quat.y * f; qt.z = quat.z * f; qt.w = quat.w * f; return qt; } Quaternion Slerp (const float t, const Quaternion &lhs, const Quaternion &rhs) { // the slerp of a pair of unit quaterions is the weighted // interpolation between them, where the interpolation weight is // given by t = [0, 1.0] // // the trick to slerping is that we find the angle between the two // quats by treating them as a pair of four vectors and getting the // cosine [as the dot product]. // // then the slerp between two quaternions A and B is: // // A * (upper_weight) + B * (lower_weight) // // where the weights are the sines of the t-weighted angle // divided by the sine of the angle. // // the resulting quaternion is also a unit quaternion. // find the angle between the two quats by treating // them as 4-length vectors -- V1.V2 = cos(theta) float cosine_angle, angle_over_two; float coef1, coef2; Quaternion qt; Quaternion lhs_n, rhs_n; lhs_n = lhs; rhs_n = rhs; lhs_n.Normalize(); rhs_n.Normalize(); cosine_angle = lhs_n.DotProduct (rhs_n); // = cos(angle_over_two) // adjust signs (if necessary) if ( cosine_angle < 0.0 ) { cosine_angle = -cosine_angle; rhs_n = - rhs_n; } angle_over_two = (float) std::acos (cosine_angle); if ( (1 - cosine_angle) > 0.000001) { coef1 = (float) std::sin (angle_over_two * (1 - t) ) / (float) std::sin (angle_over_two); coef2 = (float) std::sin (angle_over_two * t) / (float) std::sin (angle_over_two); } else { // lhs and rhs are very close ... so we can do a linear interpolation coef1 = 1 - t; coef2 = t; } qt = coef1 * lhs_n + coef2 * rhs_n; return qt; } } nux-4.0.8+16.04.20160209/NuxCore/Math/Point2D.h0000644000015600001650000000237312656236757020635 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef POINT2D_H #define POINT2D_H namespace nux { template class Point2D { public: Point2D(); Point2D(T const& x, T const& y); T x, y; }; template bool operator ==(const Point2D& lhs, const Point2D& rhs); template bool operator !=(const Point2D& lhs, const Point2D& rhs); // Do we want to keep this really? typedef Point2D Point2; } #include "Point2D-inl.h" #endif // POINT2D_H nux-4.0.8+16.04.20160209/NuxCore/Math/Vector4.h0000644000015600001650000001327212656236757020704 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef VECTOR4_H #define VECTOR4_H namespace nux { template class Vec4 { public: inline Vec4(); inline ~Vec4(); inline Vec4 (const T &, const T &, const T &, const T &); inline Vec4 (const Vec4&); inline Vec4& operator = (const Vec4&); inline bool operator == (const Vec4&) const; inline bool operator != (const Vec4&) const; inline Vec4 operator + (const Vec4&) const; inline Vec4 operator * (const Vec4&) const; inline Vec4 operator - (const Vec4&) const; inline Vec4 operator - () const; inline Vec4& operator *= (const Vec4&); inline Vec4& operator += (const Vec4&); inline Vec4& operator -= (const Vec4&); inline Vec4 operator / (const T &) const; inline Vec4 operator * (const T &) const; inline Vec4& operator /= (const T &); inline Vec4& operator *= (const T &); inline T &operator [] (int i); inline const T &operator [] (int i) const; void divide_xyz_by_w(); template friend Vec4 operator* (const U &, const Vec4&); T x, y, z, w; }; template inline Vec4::Vec4() { x = 0; y = 0; z = 0; w = 1; } template inline Vec4::~Vec4() { } template inline Vec4::Vec4 (const T &fx, const T &fy, const T &fz, const T &fw) { x = fx; y = fy; z = fz; w = fw; } //Vec4::Vec4(double fx, double fy, double fz, double fw) //{ // x = T(fx); // y = T(fy); // z = T(fz); // w = T(fw); //} // //Vec4::Vec4(int fx, int fy, int fz, int fw) //{ // x = T(fx); // y = T(fy); // z = T(fz); // w = T(fw); //} template inline Vec4::Vec4 (const Vec4& v) { x = v.x; y = v.y; z = v.z; w = v.w; } template inline Vec4& Vec4::operator= (const Vec4& v) { x = v.x; y = v.y; z = v.z; w = v.w; return (*this); } template inline bool Vec4::operator == (const Vec4& v) const { if ( (x == v.x) && (y == v.y) && (z == v.z) && (w == v.w) ) { return true; } return false; } template inline bool Vec4::operator != (const Vec4& v) const { return ! (*this == v); } template inline Vec4 Vec4::operator+ (const Vec4& v) const { return Vec4 (x + v.x, y + v.y, z + v.z, w + v.w); } template inline Vec4 Vec4::operator* (const Vec4& v) const { return Vec4 (x * v.x, y * v.y, z * v.z, w * v.w); } template inline Vec4 Vec4::operator- (const Vec4& v) const { return Vec4 (x - v.x, y - v.y, z - v.z, w - v.w); } template inline Vec4 Vec4::operator- () const { //Do that for Matices too return Vec4 (-x, -y, -z, -w); } template inline Vec4& Vec4::operator*= (const Vec4& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } template inline Vec4& Vec4::operator+= (const Vec4& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } template inline Vec4& Vec4::operator-= (const Vec4& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } template inline Vec4 Vec4::operator / (const T &f) const { if (f == 0) { throw DivisionByZeroException(); } return Vec4 (x / f, y / f, z / f, w / f); } template inline Vec4 Vec4::operator * (const T &f) const { return Vec4 (x * f, y * f, z * f, w * f); } template inline Vec4& Vec4::operator /= (const T &f) { if (f == 0) { throw DivisionByZeroException(); } x = x / f; y = y / f; z = z / f; w = w / f; return *this; } template inline Vec4& Vec4::operator *= (const T &f) { x = x * f; y = y * f; z = z * f; w = w * f; return *this; } template inline Vec4 operator* (T f , const Vec4& v) { return Vec4 (f * v.x, f * v.y, f * v.z, f * v.w); } /// element access template inline T &Vec4::operator [] (int i) { assert (i >= 0); assert (i <= 3); return * (&x + i); } /// element access (const) template inline const T &Vec4::operator [] (int i) const { assert (i >= 0); assert (i <= 3); return * (&x + i); } template void Vec4::divide_xyz_by_w() { if (w == 0) { throw DivisionByZeroException(); } x = x / w; y = y / w; z = z / w; } template Vec4 operator* (const U &f, const Vec4& v) { return v * f; } typedef Vec4 Vector4; } #endif // VECTOR4_H nux-4.0.8+16.04.20160209/NuxCore/Math/Tweening.cpp0000644000015600001650000001733612656236757021476 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "MathInc.h" #include "Tweening.h" namespace nux { // Back double BackEaseIn (double t, double b, double c, double d, double s) { //return c*(t/=d)*t*((s+1)*t - s) + b; t /= d; return c * t * t * ( (s + 1) * t - s) + b; } double BackEaseOut (double t, double b, double c, double d, double s) { //return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; t = t / d - 1; return c * (t * t * ( (s + 1) * t + s) + 1) + b; } double BackEaseInOut (double t, double b, double c, double d, double s) { // if ((t/=d/2) < 1) // return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; // return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; if ( (t /= d / 2) < 1) { s *= (1.525); return c / 2 * (t * t * ( (s + 1) * t - s) ) + b; } s *= 1.525; t -= 2.0; return c / 2 * (t * t * ( (s + 1) * t + s) + 2) + b; } // Bounce double BounceEaseOut (double t, double b, double c, double d) { if ( (t /= d) < (1 / 2.75) ) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75) ) { t -= (1.5 / 2.75); return c * (7.5625 * t * t + .75) + b; } else if (t < (2.5 / 2.75) ) { t -= (2.25 / 2.75); return c * (7.5625 * t * t + .9375) + b; } else { t -= (2.625 / 2.75); return c * (7.5625 * t * t + .984375) + b; } } double BounceEaseIn (double t, double b, double c, double d) { return c - BounceEaseOut (d - t, 0, c, d) + b; } double BounceEaseInOut (double t, double b, double c, double d) { if (t < d / 2.0) return BounceEaseIn (t * 2, 0, c, d) * .5 + b; else return BounceEaseOut (t * 2 - d, 0, c, d) * .5 + c * .5 + b; } // Circ double CircEaseIn (double t, double b, double c, double d) { t /= d; return -c * (std::sqrt (1 - t * t) - 1) + b; } double CircEaseOut (double t, double b, double c, double d) { t = t / d - 1.0; return c * std::sqrt (1.0 - t * t) + b; } double CircEaseInOut (double t, double b, double c, double d) { if ( (t /= d / 2) < 1) { return -c / 2 * (std::sqrt (1 - t * t) - 1) + b; } t -= 2.0; return c / 2 * (std::sqrt (1.0 - t * t) + 1) + b; } // Cubic double CubicEaseIn (double t, double b, double c, double d) { t /= d; return c * t * t * t + b; } double CubicEaseOut (double t, double b, double c, double d) { t = t / d - 1.0; return c * (t * t * t + 1.0) + b; } double CubicEaseInOut (double t, double b, double c, double d) { if ( (t /= d / 2) < 1) { return c / 2 * t * t * t + b; } t -= 2.0; return c / 2 * (t * t * t + 2) + b; } // Elastic double ElasticEaseIn (double t, double b, double c, double d, double a, double p) { double s = 0; if (t == 0) return b; if ( (t /= d) == 1) return b + c; if (!p) p = d * .3; if (!a || a < std::abs (c) ) { a = c; s = p / 4; } else s = p / (2 * constants::pi) * std::asin (c / a); t -= 1.0; return - (a * std::pow (2, 10 * t) * std::sin ( (t * d - s) * (2 * constants::pi) / p ) ) + b; } double ElasticEaseOut (double t, double b, double c, double d, double a, double p) { double s = 0; if (t == 0) return b; if ( (t /= d) == 1) return b + c; if (!p) p = d * .3; if (!a || a < std::abs (c) ) { a = c; s = p / 4; } else s = p / (2 * constants::pi) * std::asin (c / a); return (a * std::pow (2, -10 * t) * std::sin ( (t * d - s) * (2 * constants::pi) / p ) + c + b); } double ElasticEaseInOut (double t, double b, double c, double d, double a, double p) { double s = 0; if (t == 0) return b; if ( (t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5); if (!a || a < std::abs (c) ) { a = c; s = p / 4; } else { s = p / (2 * constants::pi) * std::asin (c / a); } if (t < 1.0) { t -= 1; return -0.5 * (a * std::pow (2, 10.0 * t) * std::sin ( (t * d - s) * (2 * constants::pi) / p ) ) + b; } t -= 1; return a * std::pow (2, -10 * t) * std::sin ( (t * d - s) * (2 * constants::pi) / p ) * .5 + c + b; } // Expo double ExpoEaseIn (double t, double b, double c, double d) { return (t == 0) ? b : c * std::pow (2, 10 * (t / d - 1) ) + b; } double ExpoEaseOut (double t, double b, double c, double d) { return (t == d) ? b + c : c * (-std::pow (2, -10 * t / d) + 1) + b; } double ExpoEaseInOut (double t, double b, double c, double d) { if (t == 0) return b; if (t == d) return b + c; if ( (t /= d / 2) < 1) return c / 2 * std::pow (2, 10 * (t - 1) ) + b; return c / 2 * (-std::pow (2, -10 * --t) + 2) + b; } // Linear double LinearEaseNone (double t, double b, double c, double d) { return c * t / d + b; } double LinearEaseIn (double t, double b, double c, double d) { return c * t / d + b; } double LinearEaseOut (double t, double b, double c, double d) { return c * t / d + b; } double LinearEaseInOut (double t, double b, double c, double d) { return c * t / d + b; } // Quad double QuadEaseIn (double t, double b, double c, double d) { t /= d; return c * t * t + b; } double QuadEaseOut (double t, double b, double c, double d) { t /= d; return -c * t * (t - 2) + b; } double QuadEaseInOut (double t, double b, double c, double d) { if ( (t /= d / 2) < 1) { return c / 2 * t * t + b; } --t; return -c / 2 * (t * (t - 2) - 1) + b; } // Quart double QuartEaseIn (double t, double b, double c, double d) { t /= d; return c * t * t * t * t + b; } double QuartEaseOut (double t, double b, double c, double d) { t = t / d - 1; return -c * (t * t * t * t - 1) + b; } double QuartEaseInOut (double t, double b, double c, double d) { if ( (t /= d / 2) < 1) { return c / 2 * t * t * t * t + b; } t -= 2.0; return -c / 2 * (t * t * t * t - 2) + b; } // Quint double QuintEaseIn (double t, double b, double c, double d) { t /= d; return c * t * t * t * t * t + b; } double QuintEaseOut (double t, double b, double c, double d) { t = t / d - 1; return c * (t * t * t * t * t + 1) + b; } double QuintEaseInOut (double t, double b, double c, double d) { if ( (t /= d / 2) < 1) { return c / 2 * t * t * t * t * t + b; } t -= 2; return c / 2 * (t * t * t * t * t + 2) + b; } // Sine double SineEaseIn (double t, double b, double c, double d) { return -c * std::cos (t / d * (constants::pi / 2) ) + c + b; } double SineEaseOut (double t, double b, double c, double d) { return c * std::sin (t / d * (constants::pi / 2) ) + b; } double SineEaseInOut (double t, double b, double c, double d) { return -c / 2 * (std::cos (constants::pi * t / d) - 1) + b; } } nux-4.0.8+16.04.20160209/NuxCore/Math/Line3D.h0000644000015600001650000000725712656236757020442 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef LINE3D_H #define LINE3D_H #include "Vector3.h" namespace nux { template class Line3D { public: Line3D(); ~Line3D(); Line3D (const Line3D &line); Line3D (T lx_start, T ly_start, T lz_start, T lx_end, T ly_end, T lz_end); Line3D (const Vector3 &pt, Vector3 v); const Line3D& operator = (const Line3D&); bool operator == (const Line3D& line) const; float Length() const; const Vec3 GetDirectionVector() const; const Vec3 GetStartPoint() const; const Vec3 GetEndPoint() const; private: T x_start, y_start, z_start; T x_end, y_end, z_end; }; template Line3D::Line3D() { x_start = y_start = z_start = x_end = y_end = z_end = 0; } template Line3D::~Line3D() { } template Line3D::Line3D (const Line3D &line) { x_start = line.x_start; x_end = line.x_end; y_start = line.y_start; y_end = line.y_end; z_start = line.z_start; z_end = line.z_end; } template Line3D::Line3D (T lx_start, T ly_start, T lz_start, T lx_end, T ly_end, T lz_end) { x_start = lx_start; x_end = lx_end; y_start = ly_start; y_end = ly_end; z_start = lz_start; z_end = lz_end; } template Line3D::Line3D (const Vector3 &pt, Vector3 v) { x_start = pt.x; y_start = pt.y; z_start = pt.z; x_end = x_start + v.x; y_end = y_start + v.y; z_end = y_start + v.z; } template const Line3D& Line3D::operator = (const Line3D& Line) { x_start = Line.x_start; y_start = Line.y_start; z_start = Line.z_start; x_end = Line.x_end; y_end = Line.y_end; z_end = Line.z_end; } template bool Line3D::operator == (const Line3D &line) const { if ( (x_start == line.x_start) && (y_start == line.y_start) && (z_start == line.z_start) && (x_end == line.x_end) && (y_end == line.y_end) && (z_end == line.z_end) ) { return true; } else { return false; } } template float Line3D::Length() const { float l; l = (float) std::sqrt ( (x_end - x_start) * (x_end - x_start) + (y_end - y_start) * (y_end - y_start) + (z_end - z_start) * (z_end - z_start) ); return l; } template const Vec3 Line3D::GetDirectionVector() const { return Vec3 (x_start - x_end, y_start - y_end, z_start - z_end); } template const Vec3 Line3D::GetStartPoint() const { Vec3 p (x_start, y_start, z_start); return p; } template const Vec3 Line3D::GetEndPoint() const { Vec3 p (x_end, y_end, z_end); return p; } } #endif // LINE3D_H nux-4.0.8+16.04.20160209/NuxCore/Math/Line3D.cpp0000644000015600001650000000156512656236757020771 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Vector3.h" #include "Line3D.h" namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix2.cpp0000644000015600001650000000174012656236757021234 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Matrix2.h" // When writing to a matrix at row r and colum c use m[r][c]. // When reading from a matrix at row r and colum c use m[c][r]. namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Math/Complex.h0000644000015600001650000000447712656236757020774 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef COMPLEX_H #define COMPLEX_H namespace nux { class ComplexNumber { public: ~ComplexNumber(); ComplexNumber (float re = 0.0f, float im = 0.0f); ComplexNumber (const ComplexNumber &); ComplexNumber &operator = (const ComplexNumber &); //const ComplexNumber operator + (const ComplexNumber&) const; //const ComplexNumber operator - (const ComplexNumber&) const; //const ComplexNumber operator * (const ComplexNumber&) const; //const ComplexNumber operator / (const ComplexNumber&) const; //const ComplexNumber operator * (const float& f) const; //const ComplexNumber operator / (const float& f) const; void operator += (const ComplexNumber &); void operator -= (const ComplexNumber &); void operator *= (const ComplexNumber &); void operator /= (const ComplexNumber &); //void operator *= (const float& f); //void operator /= (const float& f); void conjugue(); float absolute(); bool IsNull(); float real() const; float imaginary() const; void real (float r); void imaginary (float i); private: float real_; float imaginary_; }; // does that conflict with the operators above??? const ComplexNumber operator+ (const ComplexNumber &lhs, const ComplexNumber &rhs); const ComplexNumber operator- (const ComplexNumber &lhs, const ComplexNumber &rhs); const ComplexNumber operator* (const ComplexNumber &lhs, const ComplexNumber &rhs); const ComplexNumber operator/ (const ComplexNumber &lhs, const ComplexNumber &rhs); } #endif // COMPLEX_H nux-4.0.8+16.04.20160209/NuxCore/Math/Tweening.h0000644000015600001650000000632412656236757021136 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef TWEENING_H #define TWEENING_H namespace nux { // Back double BackEaseIn (double t, double b, double c, double d, double s = 1.70158); double BackEaseOut (double t, double b, double c, double d, double s = 1.70158); double BackEaseInOut (double t, double b, double c, double d, double s = 1.70158); // Bounce double BounceEaseOut (double t, double b, double c, double d); double BounceEaseIn (double t, double b, double c, double d); double BounceEaseInOut (double t, double b, double c, double d); // Circ double CircEaseIn (double t, double b, double c, double d); double CircEaseOut (double t, double b, double c, double d); double CircEaseInOut (double t, double b, double c, double d); // Cubic double CubicEaseIn (double t, double b, double c, double d); double CubicEaseOut (double t, double b, double c, double d); double CubicEaseInOut (double t, double b, double c, double d); // Elastic double ElasticEaseIn (double t, double b, double c, double d, double a, double p); double ElasticEaseOut (double t, double b, double c, double d, double a, double p); double ElasticEaseInOut (double t, double b, double c, double d, double a, double p); // Expo double ExpoEaseIn (double t, double b, double c, double d); double ExpoEaseOut (double t, double b, double c, double d); double ExpoEaseInOut (double t, double b, double c, double d); // Linear double LinearEaseNone (double t, double b, double c, double d); double LinearEaseIn (double t, double b, double c, double d); double LinearEaseOut (double t, double b, double c, double d); double LinearEaseInOut (double t, double b, double c, double d); // Quad double QuadEaseIn (double t, double b, double c, double d); double QuadEaseOut (double t, double b, double c, double d); double QuadEaseInOut (double t, double b, double c, double d); // Quart double QuartEaseIn (double t, double b, double c, double d); double QuartEaseOut (double t, double b, double c, double d); double QuartEaseInOut (double t, double b, double c, double d); // Quint double QuintEaseIn (double t, double b, double c, double d); double QuintEaseOut (double t, double b, double c, double d); double QuintEaseInOut (double t, double b, double c, double d); // Sine double SineEaseIn (double t, double b, double c, double d); double SineEaseOut (double t, double b, double c, double d); double SineEaseInOut (double t, double b, double c, double d); } #endif // TWEENING_H nux-4.0.8+16.04.20160209/NuxCore/Math/MathInc.h0000644000015600001650000000223012656236757020671 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATHINC_H #define MATHINC_H #include "Constants.h" #include "MathUtility.h" #include "Complex.h" #include "Line2D.h" #include "Line3D.h" #include "Matrix2.h" #include "Matrix3.h" #include "Matrix4.h" #include "Quaternion.h" #include "Vector2.h" #include "Vector3.h" #include "Vector4.h" #include "Point2D.h" #include "Point3D.h" #include "Algo.h" #endif // MATHINC_H nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix4.cpp0000644000015600001650000000211712656236757021235 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Vector3.h" #include "Vector4.h" #include "Matrix4.h" #include "Constants.h" // When writing to a matrix at row r and colum c use m[r][c]. // When reading from a matrix (that is the result of matrix op) at row r and colum c use m[c][r]. namespace nux { #if 0 #endif } nux-4.0.8+16.04.20160209/NuxCore/Math/Point3D.cpp0000644000015600001650000000154112656236757021165 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Point3D.h" namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Math/Point2D-inl.h0000644000015600001650000000214012656236757021405 0ustar pbuserpbgroup00000000000000#ifndef POINT2D_INL_H #define POINT2D_INL_H namespace nux { template Point2D::Point2D() : x(0), y(0) { } template Point2D::Point2D(T const& X, T const& Y) : x(X), y(Y) { } template bool operator ==(const Point2D& lhs, const Point2D& rhs) { return (lhs.x == rhs.x) && (lhs.y == rhs.y); } template bool operator !=(const Point2D& lhs, const Point2D& rhs) { return !(lhs == rhs); } template Point2D operator -(const Point2D& lhs, const Point2D& rhs) { return Point2D(lhs.x - rhs.x, lhs.y - rhs.y); } template Point2D operator +(const Point2D& lhs, const Point2D& rhs) { return Point2D(lhs.x + rhs.x, lhs.y + rhs.y); } template Point2D operator *(const Point2D& lhs, S rhs) { return Point2D(lhs.x * rhs, lhs.y * rhs); } template Point2D operator *(S lhs, const Point2D& rhs) { return Point2D(rhs.x * lhs, rhs.y * lhs); } } #endif nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix3.h0000644000015600001650000004703712656236757020713 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATRIX3_H #define MATRIX3_H #include "Vector3.h" namespace nux { template class Matrix3x3 { public: Matrix3x3(); ~Matrix3x3(); Matrix3x3 (const Matrix3x3&); Matrix3x3 ( T a00, T a01, T a02, T a10, T a11, T a12, T a20, T a21, T a22); Matrix3x3& operator = (const Matrix3x3&); bool operator == (const Matrix3x3&); Matrix3x3 operator * (const Matrix3x3&) const; Matrix3x3 operator + (const Matrix3x3&) const; Matrix3x3 operator - (const Matrix3x3&) const; Matrix3x3& operator *= (const Matrix3x3&) const; Matrix3x3& operator += (const Matrix3x3&) const; Matrix3x3& operator -= (const Matrix3x3&) const; Matrix3x3 operator * (const T &) const; Matrix3x3 operator / (const T &) const; Matrix3x3& operator *= (const T &) const; Matrix3x3& operator /= (const T &) const; Vec3 operator * (const Vec3&) const; Matrix3x3 operator - (); // Get the (i, j) element of the current matrix. T &operator() (unsigned int i, unsigned int j); T operator () (unsigned int i, unsigned int j) const; T Determinant() const ; void Inverse(); Matrix3x3 GetInverse() const; //Matrix2x2 GetUpper2x2() const; void Zero(); void Identity(); static Matrix3x3 IDENTITY(); static Matrix3x3 ZERO(); T m[3][3]; }; /***************************************************************************************\ Function: Matrix3x3::Matrix3x3 Description: Constructor. Initialize the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix3x3::Matrix3x3() { Identity(); } /***************************************************************************************\ Function: Matrix3x3::~Matrix3x3 Description: Destructor. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix3x3::~Matrix3x3() { } /***************************************************************************************\ Function: Matrix3x3::Matrix3x3 Description: None. Parameters: - M Return Value: None. Comments: None. \***************************************************************************************/ template Matrix3x3::Matrix3x3 (const Matrix3x3& M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[0][2] = M.m[0][2]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; m[1][2] = M.m[1][2]; m[2][0] = M.m[2][0]; m[2][1] = M.m[2][1]; m[2][2] = M.m[2][2]; } /***************************************************************************************\ Function: Matrix3x3::Matrix3x3 Description: None. Parameters: T a00, T a01, T a02, T a10, T a11, T a12, T a20, T a21, T a22 Return Value: None. Comments: None. \***************************************************************************************/ template Matrix3x3::Matrix3x3 ( T a00, T a01, T a02, T a10, T a11, T a12, T a20, T a21, T a22) { m[0][0] = a00; m[0][1] = a01; m[0][2] = a02; m[1][0] = a10; m[1][1] = a11; m[1][2] = a12; m[2][0] = a20; m[2][1] = a21; m[2][2] = a22; } /***************************************************************************************\ Function: Matrix3x3::operator = Description: None. Parameters: - M Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator = (const Matrix3x3& M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[0][2] = M.m[0][2]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; m[1][2] = M.m[1][2]; m[2][0] = M.m[2][0]; m[2][1] = M.m[2][1]; m[2][2] = M.m[2][2]; return (*this); } template bool Matrix3x3::operator == (const Matrix3x3& M) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { if (m[i][j] != M.m[i][j]) return false; } return true; } /***************************************************************************************\ Function: Matrix3x3::operator * Description: Multiply by matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator * (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0] + m[0][2] * iM.m[2][0]; oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0] + m[1][2] * iM.m[2][0]; oM.m[2][0] = m[2][0] * iM.m[0][0] + m[2][1] * iM.m[1][0] + m[2][2] * iM.m[2][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1] + m[0][2] * iM.m[2][1]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1] + m[1][2] * iM.m[2][1]; oM.m[2][1] = m[2][0] * iM.m[0][1] + m[2][1] * iM.m[1][1] + m[2][2] * iM.m[2][1]; oM.m[0][2] = m[0][0] * iM.m[0][2] + m[0][1] * iM.m[1][2] + m[0][2] * iM.m[2][2]; oM.m[1][2] = m[1][0] * iM.m[0][2] + m[1][1] * iM.m[1][2] + m[1][2] * iM.m[2][2]; oM.m[2][2] = m[2][0] * iM.m[0][2] + m[2][1] * iM.m[1][2] + m[2][2] * iM.m[2][2]; return oM; } /***************************************************************************************\ Function: Matrix3x3::operator + Description: Add matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator+ (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[0][2] = m[0][2] + iM.m[0][2]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; oM.m[1][2] = m[1][2] + iM.m[1][2]; oM.m[2][0] = m[2][0] + iM.m[2][0]; oM.m[2][1] = m[2][1] + iM.m[2][1]; oM.m[2][2] = m[2][2] + iM.m[2][2]; return oM; } /***************************************************************************************\ Function: Matrix3x3::operator - Description: Substract matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator- (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[0][2] = m[0][2] - iM.m[0][2]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; oM.m[1][2] = m[1][2] - iM.m[1][2]; oM.m[2][0] = m[2][0] - iM.m[2][0]; oM.m[2][1] = m[2][1] - iM.m[2][1]; oM.m[2][2] = m[2][2] - iM.m[2][2]; return oM; } /***************************************************************************************\ Function: Matrix3x3::operator *= Description: Multiply by matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator *= (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0] + m[0][2] * iM.m[2][0]; oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0] + m[1][2] * iM.m[2][0]; oM.m[2][0] = m[2][0] * iM.m[0][0] + m[2][1] * iM.m[1][0] + m[2][2] * iM.m[2][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1] + m[0][2] * iM.m[2][1]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1] + m[1][2] * iM.m[2][1]; oM.m[2][1] = m[2][0] * iM.m[0][1] + m[2][1] * iM.m[1][1] + m[2][2] * iM.m[2][1]; oM.m[0][2] = m[0][0] * iM.m[0][2] + m[0][1] * iM.m[1][2] + m[0][2] * iM.m[2][2]; oM.m[1][2] = m[1][0] * iM.m[0][2] + m[1][1] * iM.m[1][2] + m[1][2] * iM.m[2][2]; oM.m[2][2] = m[2][0] * iM.m[0][2] + m[2][1] * iM.m[1][2] + m[2][2] * iM.m[2][2]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix3x3::operator += Description: Add matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator += (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[0][2] = m[0][2] + iM.m[0][2]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; oM.m[1][2] = m[1][2] + iM.m[1][2]; oM.m[2][0] = m[2][0] + iM.m[2][0]; oM.m[2][1] = m[2][1] + iM.m[2][1]; oM.m[2][2] = m[2][2] + iM.m[2][2]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix3x3::operator -= Description: Substract matrix iM. Parameters: - iM Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator -= (const Matrix3x3& iM) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[0][2] = m[0][2] - iM.m[0][2]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; oM.m[1][2] = m[1][2] - iM.m[1][2]; oM.m[2][0] = m[2][0] - iM.m[2][0]; oM.m[2][1] = m[2][1] - iM.m[2][1]; oM.m[2][2] = m[2][2] - iM.m[2][2]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix3x3::operator * Description: Multiply all elements by f. Parameters: - f Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator * (const T &f) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] * f; oM.m[0][1] = m[0][1] * f; oM.m[0][2] = m[0][2] * f; oM.m[1][0] = m[1][0] * f; oM.m[1][1] = m[1][1] * f; oM.m[1][2] = m[1][2] * f; oM.m[2][0] = m[2][0] * f; oM.m[2][1] = m[2][1] * f; oM.m[2][2] = m[2][2] * f; return oM; } /***************************************************************************************\ Function: Matrix3x3::operator / Description: Divide all elements by f. Parameters: - f Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator/ (const T &f) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[0][2] = m[0][2] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; oM.m[1][2] = m[1][2] / f; oM.m[2][0] = m[2][0] / f; oM.m[2][1] = m[2][1] / f; oM.m[2][2] = m[2][2] / f; return oM; } /***************************************************************************************\ Function: Matrix3x3::operator *= Description: Multiply all elements by f. Parameters: - f Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator *= (const T &f) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] * f; oM.m[0][1] = m[0][1] * f; oM.m[0][2] = m[0][2] * f; oM.m[1][0] = m[1][0] * f; oM.m[1][1] = m[1][1] * f; oM.m[1][2] = m[1][2] * f; oM.m[2][0] = m[2][0] * f; oM.m[2][1] = m[2][1] * f; oM.m[2][2] = m[2][2] * f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix3x3::operator /= Description: Divide all elements by f. Parameters: - f Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3& Matrix3x3::operator /= (const T &f) const { Matrix3x3 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[0][2] = m[0][2] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; oM.m[1][2] = m[1][2] / f; oM.m[2][0] = m[2][0] / f; oM.m[2][1] = m[2][1] / f; oM.m[2][2] = m[2][2] / f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix3x3::operator * Description: Multiply a matrix by a vector. Parameters: - V Return Value: Vector4. Comments: None. \***************************************************************************************/ template Vec3 Matrix3x3::operator * (const Vec3& V) const { Vec3 oV; oV.x = V.x * m[0][0] + V.y * m[0][1] + V.z * m[0][2]; oV.y = V.x * m[1][0] + V.y * m[1][1] + V.z * m[1][2]; oV.z = V.x * m[2][0] + V.y * m[2][1] + V.z * m[2][2]; return oV; } /***************************************************************************************\ Function: Matrix3x3::operator - () Description: Negate all elements of the matrix. Parameters: None. Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 Matrix3x3::operator- () { Matrix3x3 oM; oM.m[0][0] = -m[0][0]; oM.m[0][1] = -m[0][1]; oM.m[0][2] = -m[0][2]; oM.m[1][0] = -m[1][0]; oM.m[1][1] = -m[1][1]; oM.m[1][2] = -m[1][2]; oM.m[2][0] = -m[2][0]; oM.m[2][1] = -m[2][1]; oM.m[2][2] = -m[2][2]; return oM; } template T &Matrix3x3::operator () (unsigned int i, unsigned int j) { return m[i][j]; } template T Matrix3x3::operator () (unsigned int i, unsigned int j) const { return m[i][j]; } /***************************************************************************************\ Function: Matrix3x3::zero Description: Set the matrix to zero. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix3x3::Zero() { m[0][0] = 0.0; m[0][1] = 0.0; m[0][2] = 0.0; m[1][0] = 0.0; m[1][1] = 0.0; m[1][2] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 0.0; //memset(m, 0, sizeof(m)); } /***************************************************************************************\ Function: Matrix3x3::identity Description: Set the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix3x3::Identity() { m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0; m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0; } template T Matrix3x3::Determinant() const { T det; det = m[0][0] * m[1][1] * m[2][2] + m[0][1] * m[1][2] * m[2][0] + m[0][2] * m[2][0] * m[2][1] - m[0][0] * m[1][2] * m[2][1] - m[0][1] * m[1][0] * m[2][2] - m[0][2] * m[1][1] * m[2][0]; return det; } template void Matrix3x3::Inverse() { T det = Determinant(); if (det == T (0) ) { // Determinant is null. Matrix cannot be inverted. #ifdef NUX_DEBUG NUX_HARDWARE_BREAK; #endif return; } Matrix3x3 Temp; Temp.m[0][0] = m[1][1] * m[2][2] - m[1][2] * m[2][1]; Temp.m[0][1] = m[0][2] * m[2][1] - m[0][1] * m[2][2]; Temp.m[0][2] = m[0][1] * m[1][2] - m[0][2] * m[1][1]; Temp.m[1][0] = m[1][2] * m[2][0] - m[1][0] * m[2][2]; Temp.m[1][1] = m[0][0] * m[2][2] - m[0][2] * m[2][0]; Temp.m[1][2] = m[0][2] * m[1][0] - m[0][0] * m[1][2]; Temp.m[2][0] = m[1][0] * m[2][1] - m[1][1] * m[2][0]; Temp.m[2][1] = m[0][1] * m[2][0] - m[0][0] * m[2][1]; Temp.m[2][2] = m[0][0] * m[1][1] - m[0][1] * m[1][0]; *this = (T (1) / det) * Temp; } template Matrix3x3 Matrix3x3::GetInverse() const { Matrix3x3 Temp = *this; Temp.Inverse(); return Temp; } // template // Matrix2x2 Matrix3x3::GetUpper2x2() const // { // Matrix2x2 Temp; // Temp.m[0][0] = m[0][0]; // Temp.m[0][1] = m[0][1]; // // Temp.m[1][0] = m[1][0]; // Temp.m[1][1] = m[1][1]; // // return Temp; // } template Matrix3x3 Matrix3x3::IDENTITY() { Matrix3x3 matrix; matrix.Identity(); return matrix; } template Matrix3x3 Matrix3x3::ZERO() { Matrix3x3 matrix; matrix.Zero(); return matrix; } /***************************************************************************************\ Function: Matrix3x3::operator * Description: Multiply matrix rhs by constant lhs. Allow "f * matrix" operation.. Parameters: None. Return Value: Matrix3x3. Comments: None. \***************************************************************************************/ template Matrix3x3 operator * (const T &lhs, const Matrix3x3& rhs) { Matrix3x3 oM; oM.m[0][0] = rhs.m[0][0] / lhs; oM.m[0][1] = rhs.m[0][1] / lhs; oM.m[0][2] = rhs.m[0][2] / lhs; oM.m[1][0] = rhs.m[1][0] / lhs; oM.m[1][1] = rhs.m[1][1] / lhs; oM.m[1][2] = rhs.m[1][2] / lhs; oM.m[2][0] = rhs.m[2][0] / lhs; oM.m[2][1] = rhs.m[2][1] / lhs; oM.m[2][2] = rhs.m[2][2] / lhs; return oM; } typedef Matrix3x3 Matrix3; } #endif // MATRIX3_H nux-4.0.8+16.04.20160209/NuxCore/Math/Quaternion.h0000644000015600001650000000661712656236757021510 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef QUATERNION_H #define QUATERNION_H #include "Vector3.h" #include "Vector4.h" namespace nux { /***************************************************************************************\ Class: Quaternion Description: Define basic quaternion initialization and function. Comments: Member functions uses input angles in radian. \***************************************************************************************/ class Quaternion { public: Quaternion(); Quaternion (const Quaternion &s); Quaternion (const Vector3 &vec, float angle); Quaternion (const Vector4 &vec); // creates a Quaternion from an angle axis -- note that if angle > 2*PI the resulting // rotation is angle mod 2*PI Quaternion (float axis_x, float axis_y, float axis_z, float angle_radian); // creates a Quaternion from an angle-around-XYZ euler triple using roll-pitch-yaw order Quaternion (float euler_x, float euler_y, float euler_z); ~Quaternion(); Quaternion &operator = (const Quaternion &quat); // binary operators Quaternion operator + (const Quaternion &quat) const; Quaternion operator - (const Quaternion &quat) const; Quaternion operator * (const Quaternion &quat) const; Quaternion operator * (const float &f) const; Quaternion operator / (const float &f) const; // assignment operators Quaternion &operator += (const Quaternion &quat); Quaternion &operator -= (const Quaternion &quat); Quaternion &operator *= (const Quaternion &quat); Quaternion &operator *= (const float &f); Quaternion &operator /= (const float &f); // unary operators Quaternion operator + () const; Quaternion operator - () const; //const Quaternion operator / (const Quaternion& quat); bool operator == ( const Quaternion & ) const; bool operator != ( const Quaternion & ) const; void Conjugate(); void Inverse(); void Normalize(); float DotProduct (const Quaternion &quat) const; float Length() const; void GetAngleAxis (Vector3 &axis, float &angle_radian) const; // fetches the angle/axis given by the quat // Fetches 4x4 homogeneous matrix given by the quat Matrix4 GetMatrix() const; float x, y, z, w; friend Quaternion operator * (float f, const Quaternion &quat); private: // set the quaternion by angle-axis (see AA constructor) void FromAngleAxis (float axis_x, float axis_y, float axis_z, float angle_radian); // set the quaternion by euler axis angles (see euler constructor) void FromEulerZXY (float euler_x, float euler_y, float euler_z); }; } #endif // QUATERNION_H nux-4.0.8+16.04.20160209/NuxCore/Math/Constants.h0000644000015600001650000000246012656236757021327 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef CONSTANTS_H #define CONSTANTS_H namespace nux { namespace constants { extern const float pi; extern const float e; extern const float sqrt2; extern const float sqrt3; extern const float golden; extern const double epsilon_milli; extern const double epsilon_micro; extern const double epsilon_nano; extern const double epsilon_pico; extern const double epsilon_femto; extern const float flt_epsilon; extern const double dbl_epsilon; }; } #endif // CONSTANTS_H nux-4.0.8+16.04.20160209/NuxCore/Math/Spline.h0000644000015600001650000002314212656236757020605 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef SPLINE_H #define SPLINE_H #include namespace nux { double *d3_np_fs ( int n, double a[], double b[] ); double *spline_cubic_set ( int n, double t[], double y[], int ibcbeg, double ybcbeg, int ibcend, double ybcend ); double spline_cubic_val ( int n, double t[], double tval, double y[], double ypp[], double *ypval, double *yppval ); class CubicSpline { public: CubicSpline(); CubicSpline (const CubicSpline &Other); CubicSpline &operator = (const CubicSpline &Other); CubicSpline (int numpoint, std::vector x_array, std::vector y_array, int ibcbeg = 0, double ybcbeg = 0, int ibcend = 0, double ybcend = 0); void Set (int numpoint, std::vector x_array, std::vector y_array, int ibcbeg = 0, double ybcbeg = 0, int ibcend = 0, double ybcend = 0); ~CubicSpline(); //********************************************************************** // double* CubicSpline::Compute ( int n, double t[], double y[], int ibcbeg, double ybcbeg, int ibcend, double ybcend ) // Purpose: // // SPLINE_CUBIC_SET computes the second derivatives of a piecewise cubic spline. // // Discussion: // // For data interpolation, the user must call SPLINE_SET to determine // the second derivative data, passing in the data to be interpolated, // and the desired boundary conditions. // // The data to be interpolated, plus the SPLINE_SET output, defines // the spline. The user may then call SPLINE_VAL to evaluate the // spline at any point. // // The cubic spline is a piecewise cubic polynomial. The intervals // are determined by the "knots" or abscissas of the data to be // interpolated. The cubic spline has continous first and second // derivatives over the entire interval of interpolation. // // For any point T in the interval T(IVAL), T(IVAL+1), the form of // the spline is // // SPL(T) = A(IVAL) // + B(IVAL) * ( T - T(IVAL) ) // + C(IVAL) * ( T - T(IVAL) )**2 // + D(IVAL) * ( T - T(IVAL) )**3 // // If we assume that we know the values Y(*) and DDY(*), which represent // the values and second derivatives of the spline at each knot, then // the coefficients can be computed as: // // A(IVAL) = Y(IVAL) // B(IVAL) = ( Y(IVAL+1) - Y(IVAL) ) / ( T(IVAL+1) - T(IVAL) ) // - ( DDY(IVAL+1) + 2 * DDY(IVAL) ) * ( T(IVAL+1) - T(IVAL) ) / 6 // C(IVAL) = DDY(IVAL) / 2 // D(IVAL) = ( DDY(IVAL+1) - DDY(IVAL) ) / ( 6 * ( T(IVAL+1) - T(IVAL) ) ) // // Since the first derivative of the spline is // // SPL'(T) = B(IVAL) // + 2 * C(IVAL) * ( T - T(IVAL) ) // + 3 * D(IVAL) * ( T - T(IVAL) )**2, // // the requirement that the first derivative be continuous at interior // knot I results in a total of N-2 equations, of the form: // // B(IVAL-1) + 2 C(IVAL-1) * (T(IVAL)-T(IVAL-1)) + 3 * D(IVAL-1) * (T(IVAL) - T(IVAL-1))^2 = B(IVAL) // // or, setting H(IVAL) = T(IVAL+1) - T(IVAL) // // ( Y(IVAL) - Y(IVAL-1) ) / H(IVAL-1) - ( DDY(IVAL) + 2 * DDY(IVAL-1) ) * H(IVAL-1) / 6 + DDY(IVAL-1) * H(IVAL-1) // + ( DDY(IVAL) - DDY(IVAL-1) ) * H(IVAL-1) / 2 // = ( Y(IVAL+1) - Y(IVAL) ) / H(IVAL) - ( DDY(IVAL+1) + 2 * DDY(IVAL) ) * H(IVAL) / 6 // // or // // DDY(IVAL-1) * H(IVAL-1) + 2 * DDY(IVAL) * ( H(IVAL-1) + H(IVAL) ) + DDY(IVAL) * H(IVAL) // = 6 * ( Y(IVAL+1) - Y(IVAL) ) / H(IVAL) - 6 * ( Y(IVAL) - Y(IVAL-1) ) / H(IVAL-1) // // Boundary conditions must be applied at the first and last knots. // The resulting tridiagonal system can be solved for the DDY values. // // // Parameters: // // Input, int N, the number of data points. N must be at least 2. // In the special case where N = 2 and IBCBEG = IBCEND = 0, the // spline will actually be linear. // // Input, double T[N], the knot values, that is, the points were data is // specified. The knot values should be distinct, and increasing. // // Input, double Y[N], the data values to be interpolated. // // Input, int IBCBEG, left boundary condition flag: // 0: the cubic spline should be a quadratic over the first interval; // 1: the first derivative at the left endpoint should be YBCBEG; // 2: the second derivative at the left endpoint should be YBCBEG. // // Input, double YBCBEG, the values to be used in the boundary // conditions if IBCBEG is equal to 1 or 2. // // Input, int IBCEND, right boundary condition flag: // 0: the cubic spline should be a quadratic over the last interval; // 1: the first derivative at the right endpoint should be YBCEND; // 2: the second derivative at the right endpoint should be YBCEND. // // Input, double YBCEND, the values to be used in the boundary // conditions if IBCEND is equal to 1 or 2. // // Output, double SPLINE_CUBIC_SET[N], the second derivatives of the cubic spline. // double *Compute (int ibcbeg, double ybcbeg, int ibcend, double ybcend); //********************************************************************** // double Eval ( int n, double t[], double tval, double y[], double ddy[], double *dyval, double *ddyval ) // Purpose: // // SPLINE_CUBIC_VAL evaluates a piecewise cubic spline at a point. // // Discussion: // // SPLINE_CUBIC_SET must have already been called to define the values of YPP. // // For any point T in the interval T(IVAL), T(IVAL+1), the form of // the spline is // // SPL(T) = A // + B * ( T - T(IVAL) ) // + C * ( T - T(IVAL) )**2 // + D * ( T - T(IVAL) )**3 // // Here: // A = Y(IVAL) // B = ( Y(IVAL+1) - Y(IVAL) ) / ( T(IVAL+1) - T(IVAL) ) // - ( YPP(IVAL+1) + 2 * YPP(IVAL) ) * ( T(IVAL+1) - T(IVAL) ) / 6 // C = YPP(IVAL) / 2 // D = ( YPP(IVAL+1) - YPP(IVAL) ) / ( 6 * ( T(IVAL+1) - T(IVAL) ) ) // // Modified: // // 04 February 1999 // // Author: // // John Burkardt // // Parameters: // // Input, int N, the number of knots. // // Input, double Y[N], the data values at the knots. // // Input, double T[N], the knot values. // // Input, double TVAL, a point, typically between T[0] and T[N-1], at // which the spline is to be evalulated. If TVAL lies outside // this range, extrapolation is used. // // Input, double Y[N], the data values at the knots. // // Input, double YPP[N], the second derivatives of the spline at // the knots. // // Output, double *YPVAL, the derivative of the spline at TVAL. // // Output, double *YPPVAL, the second derivative of the spline at TVAL. // // Output, double SPLINE_VAL, the value of the spline at TVAL. // double Eval (double tval); //********************************************************************** // double* SolveTridiag ( int n, double a[], double b[] ); // Purpose: // // D3_NP_FS factors and solves a D3 system. // // Discussion: // // The D3 storage format is used for a tridiagonal matrix. // The superdiagonal is stored in entries (1,2:N), the diagonal in // entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the // original matrix is "collapsed" vertically into the array. // // This algorithm requires that each diagonal entry be nonzero. // It does not use pivoting, and so can fail on systems that // are actually nonsingular. // // Example: // // Here is how a D3 matrix of order 5 would be stored: // // * A12 A23 A34 A45 // A11 A22 A33 A44 A55 // A21 A32 A43 A54 * // // Parameters: // // Input, int N, the order of the linear system. // // Input/output, double A[3*N]. // On input, the nonzero diagonals of the linear system. // On output, the data in these vectors has been overwritten // by factorization information. // // Input, double B[N], the right hand side. // // Output, double D3_NP_FS[N], the solution of the linear system. // This is NULL if there was an error because one of the diagonal // entries was zero. // double *SolveTridiag ( int n, double a[], double b[] ); public: double *t; double *y; double *ddy; int ibcbeg_; double ybcbeg_; int ibcend_; double ybcend_; int np; // number of points }; } #endif // SPLINE_H nux-4.0.8+16.04.20160209/NuxCore/Math/MathUtility.h0000644000015600001650000002673612656236757021644 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATHUTILITY_H #define MATHUTILITY_H #include #include #include #include #include #include #include "Constants.h" #define DEGTORAD(d) (d) * nux::constants::pi / 180.0f #define RADTODEG(d) (d) * 180.0f / nux::constants::pi namespace nux { template inline T Square (const T A) { return A * A; } template inline T Clamp (const T X, const T min_value, const T max_value) { return X < min_value ? min_value : X < max_value ? X : max_value; } template inline T ClampUp (const T X, const T min_value) { return X < min_value ? min_value : X; } template inline T ClampDown (const T X, const T max_value) { return X > max_value ? max_value : X; } template inline T Align (const T Ptr, int Alignment) { return (T) (((unsigned int) Ptr + Alignment - 1) & ~ (Alignment - 1)); } //Bitwise rotation on the left. template inline const T Rol (const T &a, const unsigned int n = 1) { return (a << n) | (a >> ((sizeof (T) << 3) - n)); } //Bitwise rotation on the right. template inline const T Ror (const T &a, const unsigned int n = 1) { return (a >> n) | (a << ((sizeof (T) << 3) - n)); } //! Return the absolute value of a. template inline const T Abs (const T &a) { return a >= 0 ? a : -a; } //! Return the minimum between a and b. template inline const T &Min (const T &a, const T &b) { return a <= b ? a : b; } //! Return the minimum between a, b and c. template inline const T &Min (const T &a, const T &b, const T &c) { return Min (Min (a, b), c); } //! Return the minimum between a, b, c and d. template inline const T &Min (const T &a, const T &b, const T &c, const T &d) { return Min (Min (Min (a, b), c), d); } //! Return the maximum between a and b. template inline const T &Max (const T &a, const T &b) { return a >= b ? a : b; } //! Return the maximum between a, b and c. template inline const T &Max (const T &a, const T &b, const T &c) { return Max (Max (a, b), c); } //! Return the maximum between a,b,c and d. template inline const T &Max (const T &a, const T &b, const T &c, const T &d) { return Max (Max (a, b, c), d); } template inline T Max3 (const T A, const T B, const T C) { return Max (Max (A, B), C); } template inline T Min3 (const T A, const T B, const T C) { return Min (Min (A, B), C); } //! Return the sign of x. template inline T Sign (const T &x) { return (x < 0) ? -1 : (x == 0 ? 0 : 1); } template inline T Modulo (const T &x, const T &m) { return x - m * (T) std::floor ((double) x / m); } inline int ModuloInt (const int x, const int m) { return x >= 0 ? x % m : (x % m ? m + x % m : 0); } template inline T MinMod (const T &a, const T &b) { return a * b <= 0 ? 0 : (a > 0 ? (a < b ? a : b) : (a < b ? b : a)); } //! Return a random variable between [0,1[ (uniform distribution). /*! @return a random double value in the range [0, 1[ */ inline double Random() { return (double) std::rand() / RAND_MAX; } //! Return a random variable between [-1,1[ (uniform distribution). /*! @return a random double value in the range [-1, 1[. */ inline double CRandom() { return 1 - 2 * (std::rand() / RAND_MAX); } //! Return a random variable using a gaussian distribution and a variance of 1. /*! @return a random double value in the range [-1, 1[. */ inline double RandomGaussian() { return std::sqrt (-2 * std::log ((double) (1e-10 + (1 - 2e-10) * std::rand()))) * std::cos ((double) (2 * constants::pi * std::rand())); } inline unsigned int RandomUInt() { return std::rand(); } inline unsigned int RandomUInt (unsigned int max_random) { return std::rand() % max_random; } inline size_t DiffPointer (void *Ptr0, void *Ptr1) { if ((size_t) Ptr0 >= (size_t) Ptr1) return (size_t) ((size_t) Ptr0 - (size_t) Ptr1); return (size_t) ((size_t) Ptr1 - (size_t) Ptr0); } // Dangerous to use! template inline T SubstractPointer (void *Ptr, size_t Value) { return (T) (((size_t) Ptr) - Value); } template inline T AddPointer (void *Ptr, size_t Value) { return (T) (((size_t) Ptr) + Value); } //! Round up to the nearest multiple of Alignment that is greater or equal to Value /*! @param Alignment Must be a power of 2 */ template inline T RoundUp (T Value, int Alignment) { return (Value + (Alignment - 1)) & ~ (Alignment - 1); } //! Round down to the nearest multiple of Alignment that is smaller or equal to Value /*! @param Alignment Must be a power of 2 */ template inline T RoundDown (T Value, int Alignment) { return ((Value) & ~ (Alignment - 1)); } //! Return true is Value is aligned on Alignment /*! @param Alignment Must be a power of 2 */ template inline bool IsAligned (T Value, int Alignment) { return (((Value) & ~ (Alignment - 1)) == 0); } /*! Revert Byte order 0x0011 -> 0x1100 */ inline unsigned short ReverseByteOrdering (unsigned short value) { unsigned short temp; unsigned char *src = (unsigned char *) &value; unsigned char *dest = (unsigned char *) &temp; dest[0] = src[1]; dest[1] = src[0]; return temp; } /*! Revert Byte order 0x00112233 -> 0x33221100 */ inline unsigned int ReverseByteOrdering (unsigned int value) { unsigned int temp; unsigned char *src = (unsigned char *) &value; unsigned char *dest = (unsigned char *) &temp; dest[0] = src[3]; dest[1] = src[2]; dest[2] = src[1]; dest[3] = src[0]; return temp; } /*! Revert Byte order 0x0011223344556677 -> 0x7766554433221100 */ inline unsigned long long ReverseByteOrdering (unsigned long long value) { unsigned long long temp; unsigned char *src = (unsigned char *) &value; unsigned char *dest = (unsigned char *) &temp; dest[0] = src[7]; dest[1] = src[6]; dest[2] = src[5]; dest[3] = src[4]; dest[4] = src[3]; dest[5] = src[2]; dest[6] = src[1]; dest[7] = src[0]; return temp; } // Bit Hack // Determining if an integer is a power of 2 // http://graphics.stanford.edu/~seander/bithacks.html inline bool IsPowerOf2 (unsigned int n) { // The algorithm does not 0 consider 0 a power of two. (this is right) return ! (n & (n - 1)) && n; } // Compute the next highest power of 2 of 32-bit v // http://graphics.stanford.edu/~seander/bithacks.html inline unsigned int NextPowerOfTwo (unsigned int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } inline unsigned int GetLowerPowerOfTwoExponent (unsigned int x) { int count = 0; while (x > 1) { x >>= 1; count++; } return count; } inline unsigned int PowerOfTwo (int i) { int e = 0; unsigned int power = 1; while (e < i) { power = power << 1; e++; } return power; } // ClearLSBBit(0x01001100) = 0x01001000 inline unsigned int Hak32_ClearLSBBit (unsigned int N) { return N & (N - 1); } // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan // Hak32_CountNumBits(0x01001100) = 3 inline unsigned int Hak32_CountNumBits (unsigned int N) { unsigned int v = N; // count the number of bits set in v unsigned int c; // c accumulates the total bits set in v for (c = 0; v; c++) { v &= v - 1; // clear the least significant bit set } return c; } // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan : Compute parity in parallel inline unsigned int Hak32_BitParity (unsigned int N) { unsigned int v = N; // word value to compute the parity of v ^= v >> 16; v ^= v >> 8; v ^= v >> 4; v &= 0xf; return (0x6996 >> v) & 1; } #define HAK32_SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) // Return true if the CPU is little endian inline bool Hak32_CPULittleEndian() { const int x = 1; return ((unsigned char *) &x) [0]; } // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious // Find the log base 10 of an N-bit integer in O(lg(N)) inline unsigned int Hak32_Log2 (unsigned int N) { unsigned int v = N; // find the log base 2 of 32-bit v int r; // result goes here static const int MultiplyDeBruijnBitPosition[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; v |= v >> 1; // first round down to power of 2 v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v = (v >> 1) + 1; r = MultiplyDeBruijnBitPosition[static_cast (v * 0x077CB531UL) >> 27]; return r; } // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious // Find the log base 2 of an N-bit integer in O(lg(N)) inline unsigned int Hak32_Log10 (unsigned int N) { unsigned int v = N; // non-zero 32-bit integer value to compute the log base 10 of int r; // result goes here int t; // temporary static unsigned int const PowersOf10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; t = (Hak32_Log2 (v) + 1) * 1233 >> 12; // (use a lg2 method from above) r = t - (v < PowersOf10[t]); return r; } // http://graphics.stanford.edu/~seander/bithacks.html // Count the consecutive zero bits (trailing) on the right by binary search inline unsigned int Hack32_TrailingZeroRight (unsigned int N) { unsigned int v = N; // 32-bit word input to count zero bits on right unsigned int c; // c will be the number of zero bits on the right, // so if v is 1101000 (base 2), then c will be 3 // NOTE: if 0 == v, then c = 31. if (v & 0x1) { // special case for odd v (assumed to happen half of the time) c = 0; } else { c = 1; if ((v & 0xffff) == 0) { v >>= 16; c += 16; } if ((v & 0xff) == 0) { v >>= 8; c += 8; } if ((v & 0xf) == 0) { v >>= 4; c += 4; } if ((v & 0x3) == 0) { v >>= 2; c += 2; } c -= v & 0x1; } return c; } } #endif // MATHUTILITY_H nux-4.0.8+16.04.20160209/NuxCore/Math/Algo.h0000644000015600001650000000274212656236757020240 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef ALGO_H #define ALGO_H #include "Constants.h" #include "Constants.h" namespace nux { //http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ //! Determine if a point lies inside a polygon. /*! If the point is on an edge or a point of the polygon, return the parameter "OnEdge" @polygon The polygon to test. @n Number of points in the polygon @n pt The point to test. @onedge Value to return if the point lies on an edge or a vertex of the polygon @return 1 if the point is inside, 0 if it is outside, onedge if it is on the edges of the polygon. */ int PointInside2DPolygon(Point2* polygon, int n, Point2 pt, const int onedge); } #endif // ALGO_H nux-4.0.8+16.04.20160209/NuxCore/Math/MathFunctions.cpp0000644000015600001650000000263612656236757022475 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "MathFunctions.h" namespace nux { int Factorial (int n) { int i = 1; while (0 < n) { i *= n; n--; } return i; } double BinomialCoefficient (int n, int k) { if (n < 0) NUX_BREAK_ASM_INT3; if (k < 0 || k > n) return 0.0; double d = (double) Factorial (n) / (double) (Factorial (n - k) * Factorial (k) ); return d; } double Power (double x, double y) { return std::pow (x, y); } double Log2 (double d) { return std::log (d) / std::log (2.0); } double Floor (double d) { return std::floor (d); } } nux-4.0.8+16.04.20160209/NuxCore/Math/Trigonometry.cpp0000644000015600001650000000554412656236757022416 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Trigonometry.h" #include "Constants.h" namespace nux { // Assume the spherical coordinate system relatively to a right handed xyz, // with Z pointing up. // 0 <= phi < 180 // 0 <= theta < 360 ->>> along X axis, theta = 0. Vector3 SphericalToCartesianXBaseDeg (float r, float theta, float phi) { Vector3 v; v.x = r * std::cos (theta * constants::pi / 180.0f) * std::sin (phi * constants::pi / 180.0f); v.y = r * std::sin (theta * constants::pi / 180.0f) * std::sin (phi * constants::pi / 180.0f); v.z = r * std::cos (phi * constants::pi / 180.0f); return v; } Vector3 SphericalToCartesianXBaseRad (float r, float theta, float phi) { Vector3 v; v.x = r * std::cos (theta) * std::sin (phi); v.y = r * std::sin (theta) * std::sin (phi); v.z = r * std::cos (phi); return v; } // Assume the spherical coordinate system relatively to a right handed xyz, // with Y pointing up. // 0 <= phi < 180 // 0 <= theta < 360 ->>> along Z axis, theta = 0. Vector3 SphericalToCartesianZBaseDeg (float r, float theta, float phi) { Vector3 v; v.z = r * std::cos (theta * constants::pi / 180.0f) * std::sin (phi * constants::pi / 180.0f); v.x = r * std::sin (theta * constants::pi / 180.0f) * std::sin (phi * constants::pi / 180.0f); v.y = r * std::cos (phi * constants::pi / 180.0f); return v; } Vector3 SphericalToCartesianZBaseRad (float r, float theta, float phi) { Vector3 v; v.z = r * std::cos (theta) * std::sin (phi); v.x = r * std::sin (theta) * std::sin (phi); v.y = r * std::cos (phi); return v; } Vector3 CartesianToSphericalXBaseRad (float x, float y, float z) { float r, theta, phi; r = std::sqrt (x * x + y * y + z * z); theta = std::atan (y / x); phi = std::acos (z / r); return Vector3 (r, theta, phi); } Vector3 CartesianToSphericalZBaseDeg (float x, float y, float z) { float r, theta, phi; r = std::sqrt (x * x + y * y + z * z); theta = std::atan (x / z); phi = std::acos (y / r); return Vector3 (r, theta, phi); } } nux-4.0.8+16.04.20160209/NuxCore/Math/Constants.cpp0000644000015600001650000000340212656236757021657 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Constants.h" #include namespace nux { namespace constants { const float pi = 3.1415926535f; const float e = 2.7182817f; const float sqrt2 = 1.414214f; const float sqrt3 = 1.732051f; const float golden = 1.618034f; const double epsilon_milli = 0.001; const double epsilon_micro = 0.000001; const double epsilon_nano = 0.000000001; const double epsilon_pico = 0.000000000001; const double epsilon_femto = 0.000000000000001; #if defined(NUX_OS_WINDOWS) const float flt_epsilon = FLT_EPSILON; const double dbl_epsilon = DBL_EPSILON; #elif defined(NUX_OS_LINUX) const float flt_epsilon = __FLT_EPSILON__; const double dbl_epsilon = __DBL_EPSILON__; #elif defined(NUX_OS_MACOSX) const float dbl_epsilon = _FLT_EPSILON_; const double dbl_epsilon = _DBL_EPSILON_; #else #error Undefined OS. #endif } // namespace constants } nux-4.0.8+16.04.20160209/NuxCore/Math/Vector2.h0000644000015600001650000001270712656236757020704 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef VECTOR2_H #define VECTOR2_H #include "../Exception.h" #include "Vector4.h" #include "Vector3.h" namespace nux { class Matrix2; template class Vec2; template class Vec2 { public: inline Vec2(); inline ~Vec2(); inline Vec2 (const T &, const T &); inline Vec2 (const Vec2 &); inline Vec2& operator = (const Vec2&); inline bool operator == (const Vec2&) const; inline bool operator != (const Vec2&) const; inline Vec2 operator+ (const Vec2&) const; inline Vec2 operator* (const Vec2&) const; inline Vec2 operator- (const Vec2&) const; inline Vec2 operator- () const; inline Vec2& operator*= (const Vec2&); inline Vec2& operator+= (const Vec2&); inline Vec2& operator-= (const Vec2&); inline Vec2 operator/ (const T &) const; inline Vec2 operator* (const T &) const; inline T &operator [] (int i); inline const T &operator [] (int i) const; inline T Length() const; inline T DotProduct (const Vec2 &) const; inline T CrossProduct (const Vec2 &) const; inline void Normalize(); template friend Vec2 operator* (const U &, const Vec2&); friend class Matrix2; T x, y; }; template Vec2::Vec2() { x = 0; y = 0; } template Vec2::~Vec2() { } //template //Vec2::Vec2(const T& fx) //{ // x = fx; // y = fx; //} template Vec2::Vec2 (const T &fx, const T &fy) { x = fx; y = fy; } //Vec2::Vec2(double fx, double fy) //{ // x = float(fx); // y = float(fy); //} // //Vec2::Vec2(int fx, int fy) //{ // x = float(fx); // y = float(fy); //} template Vec2::Vec2 (const Vec2& v) { x = v.x; y = v.y; } template Vec2& Vec2::operator = (const Vec2& v) { x = v.x; y = v.y; return *this; } template bool Vec2::operator == (const Vec2& v) const { if ( (x == v.x) && (y == v.y) ) { return true; } return false; } template bool Vec2::operator != (const Vec2& v) const { return ! (*this == v); } template Vec2 Vec2::operator+ (const Vec2& v) const { return Vec2 (x + v.x, y + v.y); } template Vec2 Vec2::operator* (const Vec2& v) const { return Vec2 (x * v.x, y * v.y); } template Vec2 Vec2::operator- (const Vec2& v) const { return Vec2 (x - v.x, y - v.y); } template Vec2 Vec2::operator- () const { return Vec2 (-x, -y); } template Vec2& Vec2::operator*= (const Vec2& v) { x *= v.x; y *= v.y; return *this; } template Vec2& Vec2::operator+= (const Vec2& v) { x += v.x; y += v.y; return *this; } template Vec2& Vec2::operator-= (const Vec2& v) { x -= v.x; y -= v.y; return *this; } template Vec2 Vec2::operator/ (const T &f) const { if (f == 0) { throw DivisionByZeroException(); } return Vec2 (x / f, y / f); } template Vec2 Vec2::operator* (const T &f) const { return Vec2 (x * f, y * f); } /// element access template T &Vec2::operator [] (int i) { assert (i >= 0); assert (i <= 1); return * (&x + i); } /// element access (const) template const T &Vec2::operator [] (int i) const { assert (i >= 0); assert (i <= 1); return * (&x + i); } template T Vec2::Length() const { return (T) sqrt (x * x + y * y); } template T Vec2::DotProduct (const Vec2& v) const { return x * v.x + y * v.y; } template T Vec2::CrossProduct (const Vec2& v) const { T val; val = x * v.y - y * v.x; return val; } template void Vec2::Normalize() { T l; l = Length(); if (l == 0) { throw DivisionByZeroException(); } x = x / l; y = y / l; } template T DotProduct (const Vec2& lhs, const Vec2& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; } template T CrossProduct (const Vec2& lhs, const Vec2& rhs) { return lhs.x * rhs.y - lhs.y * rhs.x; } template Vec2 operator* (const U &f, const Vec2& v) { return v * f; } typedef Vec2 Vector2; typedef Vec2 Vertex2; } #endif // VECTOR2_H nux-4.0.8+16.04.20160209/NuxCore/Math/Vector3.h0000644000015600001650000001454212656236757020704 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef VECTOR3_H #define VECTOR3_H #include "../Exception.h" #include "Vector4.h" namespace nux { template class Vec3 { public: inline Vec3(); inline Vec3 (const T &, const T &, const T &); inline ~Vec3(); inline Vec3 (const Vec3 &); inline Vec3& operator = (const Vec3&); inline bool operator == (const Vec3&) const; inline bool operator != (const Vec3&) const; inline Vec3 operator + (const Vec3&) const; inline Vec3 operator * (const Vec3&) const; inline Vec3 operator - (const Vec3&) const; inline Vec3 operator - () const; inline Vec3& operator *= (const Vec3&); inline Vec3& operator += (const Vec3&); inline Vec3& operator -= (const Vec3&); inline Vec3 operator / (const T &) const; inline Vec3 operator * (const T &) const; inline Vec3& operator /= (const T &); inline Vec3& operator *= (const T &); inline T &operator [] (int i); inline const T &operator [] (int i) const; inline T Length() const; inline T LengthSquared() const; inline T DotProduct (const Vec3&) const; inline Vec3 CrossProduct (const Vec3&) const; inline void Normalize(); template friend Vec3 operator* (const U &, const Vec3&); //friend Vec3 operator * (T, Vec3&); T x, y, z; }; template inline Vec3::Vec3() { x = 0; y = 0; z = 0; } template inline Vec3::~Vec3() { } template inline Vec3::Vec3 (const T &fx, const T &fy, const T &fz) { x = fx; y = fy; z = fz; } //Vec3::Vec3(double fx, double fy, double fz) //{ // x = T(fx); // y = T(fy); // z = T(fz); //} // //Vec3::Vec3(int fx, int fy, int fz) //{ // x = T(fx); // y = T(fy); // z = T(fz); //} template Vec3::Vec3 (const Vec3& v) { x = v.x; y = v.y; z = v.z; } template Vec3& Vec3::operator = (const Vec3& v) { x = v.x; y = v.y; z = v.z; return *this; } template bool Vec3::operator == (const Vec3& v) const { if ( (x == v.x) && (y == v.y) && (z == v.z) ) { return true; } return false; } template bool Vec3::operator != (const Vec3& v) const { return ! (*this == v); } template Vec3 Vec3::operator + (const Vec3& v) const { return Vec3 (x + v.x, y + v.y, z + v.z); } template Vec3 Vec3::operator * (const Vec3 &v) const { return Vec3 (x * v.x, y * v.y, z * v.z); } template Vec3 Vec3::operator - (const Vec3 &v) const { return Vec3 (x - v.x, y - v.y, z - v.z); } template Vec3 Vec3::operator - () const { return Vec3 (-x, -y, -z); } template Vec3& Vec3::operator *= (const Vec3 &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } template Vec3& Vec3::operator += (const Vec3 &v) { x += v.x; y += v.y; z += v.z; return *this; } template Vec3& Vec3::operator -= (const Vec3 &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } template Vec3 Vec3::operator / (const T &f) const { if (f == 0) { throw DivisionByZeroException(); } return Vec3 (x / f, y / f, z / f); } template Vec3 Vec3::operator * (const T &f) const { return Vec3 (x * f, y * f, z * f); } template Vec3& Vec3::operator /= (const T &f) { if (f == 0) { throw DivisionByZeroException(); } x = x / f; y = y / f; z = z / f; return *this; } template Vec3& Vec3::operator *= (const T &f) { x = x * f; y = y * f; z = z * f; return *this; } /// element access template T &Vec3::operator [] (int i) { assert (i >= 0); assert (i <= 2); return * (&x + i); } /// element access (const) template const T &Vec3::operator [] (int i) const { assert (i >= 0); assert (i <= 2); return * (&x + i); } template T Vec3::Length() const { return sqrt (x * x + y * y + z * z); } template T Vec3::LengthSquared() const { return (x * x + y * y + z * z); } template T Vec3::DotProduct (const Vec3& v) const { return x * v.x + y * v.y + z * v.z; } template Vec3 Vec3::CrossProduct (const Vec3& v) const { return Vec3 (y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); } template void Vec3::Normalize() { T l; l = Length(); if (l == 0) { throw DivisionByZeroException(); } x = x / l; y = y / l; z = z / l; } template T DotProduct (const Vec3& lhs, const Vec3& rhs) { T out; out = lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; return out; } template const Vec3 CrossProduct (const Vec3& lhs, const Vec3& rhs) { Vec3 out; out.x = lhs.y * rhs.z - lhs.z * rhs.y; out.y = lhs.z * rhs.x - lhs.x * rhs.z; out.z = lhs.x * rhs.y - lhs.y * rhs.x; return out; } template inline Vec3 operator * (const U &f, const Vec3& v) { return v * f; } typedef Vec3 Vector3; typedef Vec3 Vertex3; } #endif // VECTOR3_H nux-4.0.8+16.04.20160209/NuxCore/Math/Bezier.h0000644000015600001650000000502412656236757020572 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef BEZIER_H #define BEZIER_H #include "Constants.h" namespace nux { //! Evaluate the Bernstein polynomial of degree n, at parameter t. /*! Evaluate the Bernstein polynomial of degree n, at parameter t. @param n The degree of the Bernstein basis polynomials. @param t The evaluation point. @return the values of the n+1 Bernstein basis of degree n. */ NUX_DECLSPEC_DLL double *Bernstein (int n, double t); //! Evaluate 2D Bezier curve of degree n. /*! Evaluate 2D Bezier curve of degree n. @param n The degree of the Bezier curve. @param t Parameter. @param xcon Array of n+1 x coordinates of control points. @param ycon Array of n+1 y coordinates of control points. @param xval Return the x coordinates of the Bezier curve at parameter t. @param yval Return the y coordinates of the Bezier curve at parameter t. */ NUX_DECLSPEC_DLL void Bezier_XY (int n, double t, double xcon[], double ycon[], double *xval, double *yval); //! Evaluate 2D Bezier curve of degree n. /*! Evaluate 2D Bezier curve of degree n. @param n The degree of the Bezier curve. @param t Parameter. @param xcon Array of n+1 x coordinates of control points. @param ycon Array of n+1 y coordinates of control points. @param ycon Array of n+1 z coordinates of control points. @param xval Return the x coordinates of the Bezier curve at parameter t. @param yval Return the y coordinates of the Bezier curve at parameter t. @param yval Return the z coordinates of the Bezier curve at parameter t. */ NUX_DECLSPEC_DLL void Bezier_XYZ (int n, double t, double xcon[], double ycon[], double zcon[], double *xval, double *yval, double *zval); } #endif // BEZIER_H nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix3.cpp0000644000015600001650000000173512656236757021241 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Matrix3.h" // When writing to a matrix at row r and colum c use m[r][c]. // When reading from a matrix at row r and colum c use m[c][r]. namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix2.h0000644000015600001650000003405512656236757020706 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATRIX2_H #define MATRIX2_H #include "Vector2.h" namespace nux { template class Matrix2x2 { public: Matrix2x2(); ~Matrix2x2(); Matrix2x2 (const Matrix2x2&); Matrix2x2& operator = (const Matrix2x2&); bool operator == (const Matrix2x2&); Matrix2x2 operator * (const Matrix2x2&) const; Matrix2x2 operator + (const Matrix2x2&) const; Matrix2x2 operator - (const Matrix2x2&) const; Matrix2x2& operator *= (const Matrix2x2&) const; Matrix2x2& operator += (const Matrix2x2&) const; Matrix2x2& operator -= (const Matrix2x2&) const; Matrix2x2 operator * (const T &) const; Matrix2x2 operator / (const T &) const; Matrix2x2& operator *= (const T &) const; Matrix2x2& operator /= (const T &) const; Vec2 operator * (const Vec2&) const; Matrix2x2 operator - (); // Get the (i, j) element of the current matrix. T &operator() (unsigned int i, unsigned int j); T operator () (unsigned int i, unsigned int j) const; void Zero(); void Identity(); T Determinant() const ; void Inverse(); Matrix2x2 GetInverse() const; static Matrix2x2 IDENTITY(); static Matrix2x2 ZERO(); T m[2][2]; }; /***************************************************************************************\ Function: Matrix2::Matrix2 Description: Constructor. Initialize the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix2x2::Matrix2x2() { Identity(); } template T Matrix2x2::Determinant() const { T det; det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; return det; } template void Matrix2x2::Inverse() { T det = Determinant(); if (det == T (0) ) { // Determinant is null. Matrix cannot be inverted. #ifdef NUX_DEBUG NUX_HARDWARE_BREAK; #endif return; } Matrix2x2 Temp; Temp.m[0][0] = m[1][1]; Temp.m[0][1] = -m[0][1]; Temp.m[1][0] = -m[1][0]; Temp.m[1][1] = m[0][0]; *this = (T (1) / det) * Temp; } template Matrix2x2 Matrix2x2::GetInverse() const { Matrix2x2 Temp = *this; Temp.Inverse(); return Temp; } /***************************************************************************************\ Function: Matrix2x2::~Matrix2 Description: Destructor. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix2x2::~Matrix2x2() { } /***************************************************************************************\ Function: Matrix2x2::Matrix2 Description: Copy constructor. Parameters: - M Return Value: None. Comments: None. \***************************************************************************************/ template Matrix2x2::Matrix2x2 (const Matrix2x2& M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; } /***************************************************************************************\ Function: Matrix2x2::operator = Description: Assignment operator. Parameters: - M Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator = (const Matrix2x2& M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; return (*this); } template bool Matrix2x2::operator == (const Matrix2x2& M) { for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) { if (m[i][j] != M.m[i][j]) return false; } return true; } /***************************************************************************************\ Function: Matrix2x2::operator * Description: Multiply by matrix iM. Parameters: - iM. Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 Matrix2x2::operator * (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0]; oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1]; return oM; } /***************************************************************************************\ Function: Matrix2x2::operator + Description: Add matrix iM. Parameters: - iM Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 Matrix2x2::operator + (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; return oM; } /***************************************************************************************\ Function: Matrix2x2::operator - Description: Substract matrix iM. Parameters: -iM Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 Matrix2x2::operator - (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; return oM; } /***************************************************************************************\ Function: Matrix2x2::operator *= Description: Multiply by matrix iM. Parameters: - iM. Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator *= (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0]; oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix2x2::operator += Description: Add matrix iM. Parameters: - iM Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator += (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix2x2::operator -= Description: Substract matrix iM. Parameters: -iM Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator -= (const Matrix2x2& iM) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix2x2::operator *= Description: Multiply all elements by f. Parameters: - f. Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator *= (const T &f) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] * f; oM.m[0][1] = m[0][1] * f; oM.m[1][0] = m[1][0] * f; oM.m[1][1] = m[1][1] * f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix2x2::operator / Description: Divide all elements by f. Parameters: - f Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 Matrix2x2::operator / (const T &f) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; return oM; } /***************************************************************************************\ Function: Matrix2x2::operator /= Description: Divide all elements by f. Parameters: - f Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2& Matrix2x2::operator /= (const T &f) const { Matrix2x2 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix2x2::operator * Description: Multiply a matrix by a vector. Parameters: - V Return Value: Vector2. Comments: None. \***************************************************************************************/ template Vec2 Matrix2x2::operator * (const Vec2& V) const { Vec2 oV; oV.x = V.x * m[0][0] + V.y * m[0][1]; oV.y = V.x * m[1][0] + V.y * m[1][1]; return oV; } /***************************************************************************************\ Function: Matrix2x2::operator - Description: Negate all elements of the matrix. Parameters: None. Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 Matrix2x2::operator - () { Matrix2x2 oM; oM.m[0][0] = -m[0][0]; oM.m[0][1] = -m[0][1]; oM.m[1][0] = -m[1][0]; oM.m[1][1] = -m[1][1]; return oM; } template T &Matrix2x2::operator () (unsigned int i, unsigned int j) { return m[i][j]; } template T Matrix2x2::operator () (unsigned int i, unsigned int j) const { return m[i][j]; } /***************************************************************************************\ Function: Matrix2x2::zero Description: Set the matrix to zero. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix2x2::Zero() { m[0][0] = 0.0; m[0][1] = 0.0; m[1][0] = 0.0; m[1][1] = 0.0; //memset(m, 0, sizeof(m)); } /***************************************************************************************\ Function: Matrix2x2::identity Description: Set the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix2x2::Identity() { m[0][0] = 1.0; m[0][1] = 0.0; m[1][0] = 0.0; m[1][1] = 1.0; } template Matrix2x2 Matrix2x2::IDENTITY() { Matrix2x2 matrix; matrix.Identity(); return matrix; } template Matrix2x2 Matrix2x2::ZERO() { Matrix2x2 matrix; matrix.Zero(); return matrix; } /***************************************************************************************\ Function: Matrix2x2::operator * Description: Multiply matrix rhs by constant lhs. Allow "f * matrix" operation. Parameters: None. Return Value: Matrix2x2. Comments: None. \***************************************************************************************/ template Matrix2x2 operator * (const T &lhs, const Matrix2x2& rhs) { Matrix2x2 oM; oM.m[0][0] = rhs.m[0][0] / lhs; oM.m[0][1] = rhs.m[0][1] / lhs; oM.m[1][0] = rhs.m[1][0] / lhs; oM.m[1][1] = rhs.m[1][1] / lhs; return oM; } } #endif // MATRIX2_H nux-4.0.8+16.04.20160209/NuxCore/Math/Algo.cpp0000644000015600001650000000577712656236757020606 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "MathInc.h" namespace nux { int PointInside2DPolygon(Point2* polygon, int n, Point2 pt, const int onedge) { nuxAssert(n > 3); if(n < 3) return 0; //cross points count of x int __count = 0; //neighbor bound vertices Point2D p1, p2; //left vertex p1 = polygon[0]; //check all rays for(int i = 1; i <= n; ++i) { //point is an vertex if(pt == p1) return onedge; //right vertex p2 = polygon[i % n]; //ray is outside of our interests if(pt.y < Min(p1.y, p2.y) || pt.y > Max(p1.y, p2.y)) { //next ray left point p1 = p2; continue; } //ray is crossing over by the algorithm (common part of) if(pt.y > Min(p1.y, p2.y) && pt.y < Max(p1.y, p2.y)) { //x is before of ray if(pt.x <= Max(p1.x, p2.x)) { //overlies on a horizontal ray if(p1.y == p2.y && pt.x >= Min(p1.x, p2.x)) return onedge; //ray is vertical if(p1.x == p2.x) { //overlies on a ray if(p1.x == pt.x) return onedge; //before ray else ++__count; } //cross point on the left side else { //cross point of x double xinters = (pt.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; //overlies on a ray if(fabs(pt.x - xinters) < constants::dbl_epsilon) return onedge; //before ray if(pt.x < xinters) ++__count; } } } //special case when ray is crossing through the vertex else { //p crossing over p2 if(pt.y == p2.y && pt.x <= p2.x) { //next vertex const Point2& p3 = polygon[(i+1) % n]; //pt.y lies between p1.y & p3.y if(pt.y >= Min(p1.y, p3.y) && pt.y <= Max(p1.y, p3.y)) { ++__count; } else { __count += 2; } } } //next ray left point p1 = p2; } //EVEN if(__count % 2 == 0) return(0); //ODD else return(1); } } nux-4.0.8+16.04.20160209/NuxCore/Math/Matrix4.h0000644000015600001650000012045712656236764020710 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef MATRIX4_H #define MATRIX4_H #include "Constants.h" #include "Vector3.h" #include "Vector4.h" namespace nux { // Our matrices are Row major just like C/C++: // m[2][3] represent the element at row 2 and column 3. // When multiplying a vector by a matrix, the vector is a column at the right of the matrix // // |a00, a01, a02, a03| |v0| // |a10, a11, a12, a13| * |v1| // |a20, a21, a22, a23| |v2| // |a30, a31, a32, a33| |v3| // // Note: OpenGL is column major. Before passing it a Matrix4x4 through glLoadMatrix, transpose it. template class Matrix4x4 { public: Matrix4x4(); ~Matrix4x4(); Matrix4x4 (const Matrix4x4 &); Matrix4x4 ( T a00, T a01, T a02, T a03, T a10, T a11, T a12, T a13, T a20, T a21, T a22, T a23, T a30, T a31, T a32, T a33); Matrix4x4& operator = (const Matrix4x4&); bool operator == (const Matrix4x4&); Matrix4x4 operator * (const Matrix4x4&) const; Matrix4x4 operator + (const Matrix4x4&) const; Matrix4x4 operator - (const Matrix4x4&) const; Matrix4x4& operator *= (const Matrix4x4&) const; Matrix4x4& operator += (const Matrix4x4&) const; Matrix4x4& operator -= (const Matrix4x4&) const; Matrix4x4 operator * (const T &) const; Matrix4x4 operator / (const T &) const; Matrix4x4 operator *= (const T &) const; Matrix4x4 operator /= (const T &) const; Vector4 operator * (const Vector4 &) const; Matrix4x4 operator - (); // Get the (i, j) element of the current matrix. T &operator() (unsigned int i, unsigned int j); T operator () (unsigned int i, unsigned int j) const; // Get a pointer to the current matrix. operator T *(); operator const T *() const; // Utility for 3D void Translate (T x, T y, T z); void Translate (const Vector3 &); void Rotate_x (T angle); void Rotate_y (T angle); void Rotate_z (T angle); void Scale (T sx, T sy, T sz); // Matrix Math T Trace() const; T Determinant() const ; void Inverse(); Matrix4x4 GetInverse() const; void Transpose(); //Matrix3x3 GetUpper3x3() const; //Matrix2x2 GetUpper2x2() const; /////////////////////////////////////////////// void Scale (T s); void Diagonal (T x, T y, T z, T w = T (1) ); void Rotate (T angle, Vector3 axis); // OpenGL void LookAt (const Vector3 &eye, const Vector3 &at, const Vector3 &up); void Orthographic (T l, T r, T b, T t, T n, T f); void Perspective (T l, T r, T t, T b, T n, T f); void PerspectiveInverse (T l, T r, T t, T b, T n, T f); void Perspective (T FoV, T AspectRatio, T NearPlane, T FarPlane); void Zero(); void Identity(); static Matrix4x4 IDENTITY(); static Matrix4x4 ZERO(); static Matrix4x4 ROTATEX(T angle); static Matrix4x4 ROTATEY(T angle); static Matrix4x4 ROTATEZ(T angle); static Matrix4x4 TRANSLATE(T x, T y, T z); static Matrix4x4 SCALE(T x, T y, T z); T m[4][4]; }; /***************************************************************************************\ Function: Matrix4x4::Matrix4x4 Description: Constructor. Initialize the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix4x4::Matrix4x4() { Identity(); } /***************************************************************************************\ Function: Matrix4x4::~Matrix4x4 Description: Destructor. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template Matrix4x4::~Matrix4x4() { } /***************************************************************************************\ Function: Matrix4x4::Matrix4x4 Description: None. Parameters: - M Return Value: None. Comments: None. \***************************************************************************************/ template Matrix4x4::Matrix4x4 (const Matrix4x4 &M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[0][2] = M.m[0][2]; m[0][3] = M.m[0][3]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; m[1][2] = M.m[1][2]; m[1][3] = M.m[1][3]; m[2][0] = M.m[2][0]; m[2][1] = M.m[2][1]; m[2][2] = M.m[2][2]; m[2][3] = M.m[2][3]; m[3][0] = M.m[3][0]; m[3][1] = M.m[3][1]; m[3][2] = M.m[3][2]; m[3][3] = M.m[3][3]; } /***************************************************************************************\ Function: Matrix4x4::Matrix4x4 Description: None. Parameters: T a00, T a01, T a02, T a03, T a10, T a11, T a12, T a13, T a20, T a21, T a22, T a23, T a30, T a31, T a32, T a33 Return Value: None. Comments: None. \***************************************************************************************/ template Matrix4x4::Matrix4x4 ( T a00, T a01, T a02, T a03, T a10, T a11, T a12, T a13, T a20, T a21, T a22, T a23, T a30, T a31, T a32, T a33) { m[0][0] = a00; m[0][1] = a01; m[0][2] = a02; m[0][3] = a03; m[1][0] = a10; m[1][1] = a11; m[1][2] = a12; m[1][3] = a13; m[2][0] = a20; m[2][1] = a21; m[2][2] = a22; m[2][3] = a23; m[3][0] = a30; m[3][1] = a31; m[3][2] = a32; m[3][3] = a33; } /***************************************************************************************\ Function: Matrix4x4::Matrix4x4 Description: Assignment operator. Parameters: - M Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4& Matrix4x4::operator = (const Matrix4x4& M) { m[0][0] = M.m[0][0]; m[0][1] = M.m[0][1]; m[0][2] = M.m[0][2]; m[0][3] = M.m[0][3]; m[1][0] = M.m[1][0]; m[1][1] = M.m[1][1]; m[1][2] = M.m[1][2]; m[1][3] = M.m[1][3]; m[2][0] = M.m[2][0]; m[2][1] = M.m[2][1]; m[2][2] = M.m[2][2]; m[2][3] = M.m[2][3]; m[3][0] = M.m[3][0]; m[3][1] = M.m[3][1]; m[3][2] = M.m[3][2]; m[3][3] = M.m[3][3]; return (*this); } template bool Matrix4x4::operator == (const Matrix4x4& M) { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { if (m[i][j] != M.m[i][j]) return false; } return true; } /***************************************************************************************\ Function: Matrix4x4::operator * Description: Multiply by matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator * (const Matrix4x4& iM) const { Matrix4x4 oM; // Output matrix first row oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0] + m[0][2] * iM.m[2][0] + m[0][3] * iM.m[3][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1] + m[0][2] * iM.m[2][1] + m[0][3] * iM.m[3][1]; oM.m[0][2] = m[0][0] * iM.m[0][2] + m[0][1] * iM.m[1][2] + m[0][2] * iM.m[2][2] + m[0][3] * iM.m[3][2]; oM.m[0][3] = m[0][0] * iM.m[0][3] + m[0][1] * iM.m[1][3] + m[0][2] * iM.m[2][3] + m[0][3] * iM.m[3][3]; // Output matrix second row oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0] + m[1][2] * iM.m[2][0] + m[1][3] * iM.m[3][0]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1] + m[1][2] * iM.m[2][1] + m[1][3] * iM.m[3][1]; oM.m[1][2] = m[1][0] * iM.m[0][2] + m[1][1] * iM.m[1][2] + m[1][2] * iM.m[2][2] + m[1][3] * iM.m[3][2]; oM.m[1][3] = m[1][0] * iM.m[0][3] + m[1][1] * iM.m[1][3] + m[1][2] * iM.m[2][3] + m[1][3] * iM.m[3][3]; // Output matrix third row oM.m[2][0] = m[2][0] * iM.m[0][0] + m[2][1] * iM.m[1][0] + m[2][2] * iM.m[2][0] + m[2][3] * iM.m[3][0]; oM.m[2][1] = m[2][0] * iM.m[0][1] + m[2][1] * iM.m[1][1] + m[2][2] * iM.m[2][1] + m[2][3] * iM.m[3][1]; oM.m[2][2] = m[2][0] * iM.m[0][2] + m[2][1] * iM.m[1][2] + m[2][2] * iM.m[2][2] + m[2][3] * iM.m[3][2]; oM.m[2][3] = m[2][0] * iM.m[0][3] + m[2][1] * iM.m[1][3] + m[2][2] * iM.m[2][3] + m[2][3] * iM.m[3][3]; // Output matrix fourth row oM.m[3][0] = m[3][0] * iM.m[0][0] + m[3][1] * iM.m[1][0] + m[3][2] * iM.m[2][0] + m[3][3] * iM.m[3][0]; oM.m[3][1] = m[3][0] * iM.m[0][1] + m[3][1] * iM.m[1][1] + m[3][2] * iM.m[2][1] + m[3][3] * iM.m[3][1]; oM.m[3][2] = m[3][0] * iM.m[0][2] + m[3][1] * iM.m[1][2] + m[3][2] * iM.m[2][2] + m[3][3] * iM.m[3][2]; oM.m[3][3] = m[3][0] * iM.m[0][3] + m[3][1] * iM.m[1][3] + m[3][2] * iM.m[2][3] + m[3][3] * iM.m[3][3]; return oM; } /***************************************************************************************\ Function: Matrix4x4::operator + Description: Add matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator + (const Matrix4x4& iM) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[0][2] = m[0][2] + iM.m[0][2]; oM.m[0][3] = m[0][3] + iM.m[0][3]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; oM.m[1][2] = m[1][2] + iM.m[1][2]; oM.m[1][3] = m[1][3] + iM.m[1][3]; oM.m[2][0] = m[2][0] + iM.m[2][0]; oM.m[2][1] = m[2][1] + iM.m[2][1]; oM.m[2][2] = m[2][2] + iM.m[2][2]; oM.m[2][3] = m[2][3] + iM.m[2][3]; oM.m[3][0] = m[3][0] + iM.m[3][0]; oM.m[3][1] = m[3][1] + iM.m[3][1]; oM.m[3][2] = m[3][2] + iM.m[3][2]; oM.m[3][3] = m[3][3] + iM.m[3][3]; return oM; } /***************************************************************************************\ Function: Matrix4x4::operator - Description: Substract matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator - (const Matrix4x4& iM) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[0][2] = m[0][2] - iM.m[0][2]; oM.m[0][3] = m[0][3] - iM.m[0][3]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; oM.m[1][2] = m[1][2] - iM.m[1][2]; oM.m[1][3] = m[1][3] - iM.m[1][3]; oM.m[2][0] = m[2][0] - iM.m[2][0]; oM.m[2][1] = m[2][1] - iM.m[2][1]; oM.m[2][2] = m[2][2] - iM.m[2][2]; oM.m[2][3] = m[2][3] - iM.m[2][3]; oM.m[3][0] = m[3][0] - iM.m[3][0]; oM.m[3][1] = m[3][1] - iM.m[3][1]; oM.m[3][2] = m[3][2] - iM.m[3][2]; oM.m[3][3] = m[3][3] - iM.m[3][3]; return oM; } /***************************************************************************************\ Function: Matrix4x4::operator *= Description: Multiply by matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4& Matrix4x4::operator *= (const Matrix4x4& iM) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] * iM.m[0][0] + m[0][1] * iM.m[1][0] + m[0][2] * iM.m[2][0] + m[0][3] * iM.m[3][0]; oM.m[1][0] = m[1][0] * iM.m[0][0] + m[1][1] * iM.m[1][0] + m[1][2] * iM.m[2][0] + m[1][3] * iM.m[3][0]; oM.m[2][0] = m[2][0] * iM.m[0][0] + m[2][1] * iM.m[1][0] + m[2][2] * iM.m[2][0] + m[2][3] * iM.m[3][0]; oM.m[3][0] = m[3][0] * iM.m[0][0] + m[3][1] * iM.m[1][0] + m[3][2] * iM.m[2][0] + m[3][3] * iM.m[3][0]; oM.m[0][1] = m[0][0] * iM.m[0][1] + m[0][1] * iM.m[1][1] + m[0][2] * iM.m[2][1] + m[0][3] * iM.m[3][1]; oM.m[1][1] = m[1][0] * iM.m[0][1] + m[1][1] * iM.m[1][1] + m[1][2] * iM.m[2][1] + m[1][3] * iM.m[3][1]; oM.m[2][1] = m[2][0] * iM.m[0][1] + m[2][1] * iM.m[1][1] + m[2][2] * iM.m[2][1] + m[2][3] * iM.m[3][1]; oM.m[3][1] = m[3][0] * iM.m[0][1] + m[3][1] * iM.m[1][1] + m[3][2] * iM.m[2][1] + m[3][3] * iM.m[3][1]; oM.m[0][2] = m[0][0] * iM.m[0][2] + m[0][1] * iM.m[1][2] + m[0][2] * iM.m[2][2] + m[0][3] * iM.m[3][2]; oM.m[1][2] = m[1][0] * iM.m[0][2] + m[1][1] * iM.m[1][2] + m[1][2] * iM.m[2][2] + m[1][3] * iM.m[3][2]; oM.m[2][2] = m[2][0] * iM.m[0][2] + m[2][1] * iM.m[1][2] + m[2][2] * iM.m[2][2] + m[2][3] * iM.m[3][2]; oM.m[3][2] = m[3][0] * iM.m[0][2] + m[3][1] * iM.m[1][2] + m[3][2] * iM.m[2][2] + m[3][3] * iM.m[3][2]; oM.m[0][3] = m[0][0] * iM.m[0][3] + m[0][1] * iM.m[1][3] + m[0][2] * iM.m[2][3] + m[0][3] * iM.m[3][3]; oM.m[1][3] = m[1][0] * iM.m[0][3] + m[1][1] * iM.m[1][3] + m[1][2] * iM.m[2][3] + m[1][3] * iM.m[3][3]; oM.m[2][3] = m[2][0] * iM.m[0][3] + m[2][1] * iM.m[1][3] + m[2][2] * iM.m[2][3] + m[2][3] * iM.m[3][3]; oM.m[3][3] = m[3][0] * iM.m[0][3] + m[3][1] * iM.m[1][3] + m[3][2] * iM.m[2][3] + m[3][3] * iM.m[3][3]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix4x4::operator += Description: Add matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4& Matrix4x4::operator += (const Matrix4x4& iM) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] + iM.m[0][0]; oM.m[0][1] = m[0][1] + iM.m[0][1]; oM.m[0][2] = m[0][2] + iM.m[0][2]; oM.m[0][3] = m[0][3] + iM.m[0][3]; oM.m[1][0] = m[1][0] + iM.m[1][0]; oM.m[1][1] = m[1][1] + iM.m[1][1]; oM.m[1][2] = m[1][2] + iM.m[1][2]; oM.m[1][3] = m[1][3] + iM.m[1][3]; oM.m[2][0] = m[2][0] + iM.m[2][0]; oM.m[2][1] = m[2][1] + iM.m[2][1]; oM.m[2][2] = m[2][2] + iM.m[2][2]; oM.m[2][3] = m[2][3] + iM.m[2][3]; oM.m[3][0] = m[3][0] + iM.m[3][0]; oM.m[3][1] = m[3][1] + iM.m[3][1]; oM.m[3][2] = m[3][2] + iM.m[3][2]; oM.m[3][3] = m[3][3] + iM.m[3][3]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix4x4::operator -= Description: Substract matrix iM. Parameters: - iM Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4& Matrix4x4::operator -= (const Matrix4x4& iM) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] - iM.m[0][0]; oM.m[0][1] = m[0][1] - iM.m[0][1]; oM.m[0][2] = m[0][2] - iM.m[0][2]; oM.m[0][3] = m[0][3] - iM.m[0][3]; oM.m[1][0] = m[1][0] - iM.m[1][0]; oM.m[1][1] = m[1][1] - iM.m[1][1]; oM.m[1][2] = m[1][2] - iM.m[1][2]; oM.m[1][3] = m[1][3] - iM.m[1][3]; oM.m[2][0] = m[2][0] - iM.m[2][0]; oM.m[2][1] = m[2][1] - iM.m[2][1]; oM.m[2][2] = m[2][2] - iM.m[2][2]; oM.m[2][3] = m[2][3] - iM.m[2][3]; oM.m[3][0] = m[3][0] - iM.m[3][0]; oM.m[3][1] = m[3][1] - iM.m[3][1]; oM.m[3][2] = m[3][2] - iM.m[3][2]; oM.m[3][3] = m[3][3] - iM.m[3][3]; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix4x4::operator * Description: Multiply all elements by f. Parameters: - f Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator * (const T &f) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] * f; oM.m[0][1] = m[0][1] * f; oM.m[0][2] = m[0][2] * f; oM.m[0][3] = m[0][3] * f; oM.m[1][0] = m[1][0] * f; oM.m[1][1] = m[1][1] * f; oM.m[1][2] = m[1][2] * f; oM.m[1][3] = m[1][3] * f; oM.m[2][0] = m[2][0] * f; oM.m[2][1] = m[2][1] * f; oM.m[2][2] = m[2][2] * f; oM.m[2][3] = m[2][3] * f; oM.m[3][0] = m[3][0] * f; oM.m[3][1] = m[3][1] * f; oM.m[3][2] = m[3][2] * f; oM.m[3][3] = m[3][3] * f; return oM; } /***************************************************************************************\ Function: Matrix4x4::operator / Description: Divide all elements by f. Parameters: - f Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator / (const T &f) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[0][2] = m[0][2] / f; oM.m[0][3] = m[0][3] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; oM.m[1][2] = m[1][2] / f; oM.m[1][3] = m[1][3] / f; oM.m[2][0] = m[2][0] / f; oM.m[2][1] = m[2][1] / f; oM.m[2][2] = m[2][2] / f; oM.m[2][3] = m[2][3] / f; oM.m[3][0] = m[3][0] / f; oM.m[3][1] = m[3][1] / f; oM.m[3][2] = m[3][2] / f; oM.m[3][3] = m[3][3] / f; return oM; } /***************************************************************************************\ Function: Matrix4x4::operator *= Description: Multiply all elements by f. Parameters: - f Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator *= (const T &f) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] * f; oM.m[0][1] = m[0][1] * f; oM.m[0][2] = m[0][2] * f; oM.m[0][3] = m[0][3] * f; oM.m[1][0] = m[1][0] * f; oM.m[1][1] = m[1][1] * f; oM.m[1][2] = m[1][2] * f; oM.m[1][3] = m[1][3] * f; oM.m[2][0] = m[2][0] * f; oM.m[2][1] = m[2][1] * f; oM.m[2][2] = m[2][2] * f; oM.m[2][3] = m[2][3] * f; oM.m[3][0] = m[3][0] * f; oM.m[3][1] = m[3][1] * f; oM.m[3][2] = m[3][2] * f; oM.m[3][3] = m[3][3] * f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix4x4::operator /= Description: Divide all elements by f. Parameters: - f Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator /= (const T &f) const { Matrix4x4 oM; oM.m[0][0] = m[0][0] / f; oM.m[0][1] = m[0][1] / f; oM.m[0][2] = m[0][2] / f; oM.m[0][3] = m[0][3] / f; oM.m[1][0] = m[1][0] / f; oM.m[1][1] = m[1][1] / f; oM.m[1][2] = m[1][2] / f; oM.m[1][3] = m[1][3] / f; oM.m[2][0] = m[2][0] / f; oM.m[2][1] = m[2][1] / f; oM.m[2][2] = m[2][2] / f; oM.m[2][3] = m[2][3] / f; oM.m[3][0] = m[3][0] / f; oM.m[3][1] = m[3][1] / f; oM.m[3][2] = m[3][2] / f; oM.m[3][3] = m[3][3] / f; *this = oM; return *this; } /***************************************************************************************\ Function: Matrix4x4::operator * Description: Multiply a matrix by a vector. Parameters: - V Return Value: Vector4. Comments: None. \***************************************************************************************/ template Vector4 Matrix4x4::operator * (const Vector4 &V) const { Vector4 oV; oV.x = V.x * m[0][0] + V.y * m[0][1] + V.z * m[0][2] + V.w * m[0][3]; oV.y = V.x * m[1][0] + V.y * m[1][1] + V.z * m[1][2] + V.w * m[1][3]; oV.z = V.x * m[2][0] + V.y * m[2][1] + V.z * m[2][2] + V.w * m[2][3]; oV.w = V.x * m[3][0] + V.y * m[3][1] + V.z * m[3][2] + V.w * m[3][3]; return oV; } /***************************************************************************************\ Function: Matrix4x4::operator - () Description: Negate all elements of the matrix. Parameters: None. Return Value: Matrix4x4. Comments: None. \***************************************************************************************/ template Matrix4x4 Matrix4x4::operator - () { Matrix4x4 oM; oM.m[0][0] = -m[0][0]; oM.m[0][1] = -m[0][1]; oM.m[0][2] = -m[0][2]; oM.m[0][3] = -m[0][3]; oM.m[1][0] = -m[1][0]; oM.m[1][1] = -m[1][1]; oM.m[1][2] = -m[1][2]; oM.m[1][3] = -m[1][3]; oM.m[2][0] = -m[2][0]; oM.m[2][1] = -m[2][1]; oM.m[2][2] = -m[2][2]; oM.m[2][3] = -m[2][3]; oM.m[3][0] = -m[3][0]; oM.m[3][1] = -m[3][1]; oM.m[3][2] = -m[3][2]; oM.m[3][3] = -m[3][3]; return oM; } template T &Matrix4x4::operator () (unsigned int i, unsigned int j) { return m[i][j]; } template T Matrix4x4::operator () (unsigned int i, unsigned int j) const { return m[i][j]; } template Matrix4x4::operator T *() { return reinterpret_cast (&m); } template Matrix4x4::operator const T *() const { return reinterpret_cast (&m); } /***************************************************************************************\ Function: Matrix4x4::zero Description: Set the matrix to zero. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Zero() { m[0][0] = 0.0; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = 0.0; m[1][0] = 0.0; m[1][1] = 0.0; m[1][2] = 0.0; m[1][3] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 0.0; m[2][3] = 0.0; m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 0.0; //memset(m, 0, sizeof(m)); } /***************************************************************************************\ Function: Matrix4x4::identity Description: Set the matrix to identity. Parameters: None. Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Identity() { m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = 0.0; m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0; m[1][3] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0; m[2][3] = 0.0; m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1.0; } /***************************************************************************************\ Function: Matrix4x4::translate Description: Add a translation to the current matrix. Parameters: - x - y - z Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Translate (T x, T y, T z) { Identity(); m[0][3] = x; m[1][3] = y; m[2][3] = z; } /***************************************************************************************\ Function: Matrix4x4::Transpose Description: Transpose the current matrix. Parameters: None Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Transpose() { for (int i = 0; i < 4; i++) { for (int j = 0; j < i; j++) { T t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t; } } } /***************************************************************************************\ Function: Matrix4x4::Rotate_x Description: Add rotation matrix around axe X. Parameters: - angle Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Rotate_x (T angle) { Identity(); m[0][0] = 1.0f; m[1][0] = 0.0f; m[2][0] = 0.0f; m[3][0] = 0.0f; m[0][1] = 0.0f; m[1][1] = (T) cos (angle); m[2][1] = (T) sin (angle); m[3][1] = 0.0f; m[0][2] = 0.0f; m[1][2] = (T) - sin (angle); m[2][2] = (T) cos (angle); m[3][2] = 0.0f; m[0][3] = 0.0f; m[1][3] = 0.0f; m[2][3] = 0.0f; m[3][3] = 1.0f; } /***************************************************************************************\ Function: Matrix4x4::Rotate_y Description: Add rotation matrix around axe Y. Parameters: - angle Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Rotate_y (T angle) { Identity(); m[0][0] = (T) cos (angle); m[1][0] = 0.0f; m[2][0] = (T) - sin (angle); m[3][0] = 0.0f; m[0][1] = 0.0f; m[1][1] = 1.0f; m[2][1] = 0.0f; m[3][1] = 0.0f; m[0][2] = (T) sin (angle); m[1][2] = 0.0f; m[2][2] = (T) cos (angle); m[3][2] = 0.0f; m[0][3] = 0.0f; m[1][3] = 0.0f; m[2][3] = 0.0f; m[3][3] = 1.0f; } /***************************************************************************************\ Function: Matrix4x4::Rotate_z Description: Add rotation matrix around axe Z. Parameters: - angle Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Rotate_z (T angle) { Identity(); m[0][0] = (T) cos (angle); m[1][0] = (T) sin (angle); m[2][0] = 0.0f; m[3][0] = 0.0f; m[0][1] = (T) - sin (angle); m[1][1] = (T) cos (angle); m[2][1] = 0.0f; m[3][1] = 0.0f; m[0][2] = 0.0f; m[1][2] = 0.0f; m[2][2] = 1.0f; m[3][2] = 0.0f; m[0][3] = 0.0f; m[1][3] = 0.0f; m[2][3] = 0.0f; m[3][3] = 1.0f; } /***************************************************************************************\ Function: Matrix4x4::Scale Description: Add a scale matrix. Parameters: - sx, sy, sz Return Value: None. Comments: None. \***************************************************************************************/ template void Matrix4x4::Scale (T sx, T sy, T sz) { Identity(); m[0][0] = sx; m[1][0] = 0.0f; m[2][0] = 0.0f; m[3][0] = 0.0f; m[0][1] = 0.0f; m[1][1] = sy; m[2][1] = 0.0f; m[3][1] = 0.0f; m[0][2] = 0.0f; m[1][2] = 0.0f; m[2][2] = sz; m[3][2] = 0.0f; m[0][3] = 0.0f; m[1][3] = 0.0f; m[2][3] = 0.0f; m[3][3] = 1.0f; } template T Matrix4x4::Trace() const { return m[0][0] + m[1][1] + m[2][2] + m[3][3]; } template T Matrix4x4::Determinant() const { const T &m00 = m[0][0]; const T &m01 = m[0][1]; const T &m02 = m[0][2]; const T &m03 = m[0][3]; const T &m10 = m[1][0]; const T &m11 = m[1][1]; const T &m12 = m[1][2]; const T &m13 = m[1][3]; const T &m20 = m[2][0]; const T &m21 = m[2][1]; const T &m22 = m[2][2]; const T &m23 = m[2][3]; const T &m30 = m[3][0]; const T &m31 = m[3][1]; const T &m32 = m[3][2]; const T &m33 = m[3][3]; T det = m03 * m12 * m21 * m30 - m02 * m13 * m21 * m30 - m03 * m11 * m22 * m30 + m01 * m13 * m22 * m30 + m02 * m11 * m23 * m30 - m01 * m12 * m23 * m30 - m03 * m12 * m20 * m31 + m02 * m13 * m20 * m31 + m03 * m10 * m22 * m31 - m00 * m13 * m22 * m31 - m02 * m10 * m23 * m31 + m00 * m12 * m23 * m31 + m03 * m11 * m20 * m32 - m01 * m13 * m20 * m32 - m03 * m10 * m21 * m32 + m00 * m13 * m21 * m32 + m01 * m10 * m23 * m32 - m00 * m11 * m23 * m32 - m02 * m11 * m20 * m33 + m01 * m12 * m20 * m33 + m02 * m10 * m21 * m33 - m00 * m12 * m21 * m33 - m01 * m10 * m22 * m33 + m00 * m11 * m22 * m33; return det; } template void Matrix4x4::Inverse() { T det = Determinant(); if (det == T (0) ) { // Determinant is null. Matrix cannot be inverted. #ifdef NUX_DEBUG NUX_HARDWARE_BREAK; #endif return; } const T &m00 = m[0][0]; const T &m01 = m[0][1]; const T &m02 = m[0][2]; const T &m03 = m[0][3]; const T &m10 = m[1][0]; const T &m11 = m[1][1]; const T &m12 = m[1][2]; const T &m13 = m[1][3]; const T &m20 = m[2][0]; const T &m21 = m[2][1]; const T &m22 = m[2][2]; const T &m23 = m[2][3]; const T &m30 = m[3][0]; const T &m31 = m[3][1]; const T &m32 = m[3][2]; const T &m33 = m[3][3]; Matrix4x4 Temp; Temp.m[0][0] = m12 * m23 * m31 - m13 * m22 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 + m11 * m22 * m33; Temp.m[0][1] = m03 * m22 * m31 - m02 * m23 * m31 - m03 * m21 * m32 + m01 * m23 * m32 + m02 * m21 * m33 - m01 * m22 * m33; Temp.m[0][2] = m02 * m13 * m31 - m03 * m12 * m31 + m03 * m11 * m32 - m01 * m13 * m32 - m02 * m11 * m33 + m01 * m12 * m33; Temp.m[0][3] = m03 * m12 * m21 - m02 * m13 * m21 - m03 * m11 * m22 + m01 * m13 * m22 + m02 * m11 * m23 - m01 * m12 * m23; Temp.m[1][0] = m13 * m22 * m30 - m12 * m23 * m30 - m13 * m20 * m32 + m10 * m23 * m32 + m12 * m20 * m33 - m10 * m22 * m33; Temp.m[1][1] = m02 * m23 * m30 - m03 * m22 * m30 + m03 * m20 * m32 - m00 * m23 * m32 - m02 * m20 * m33 + m00 * m22 * m33; Temp.m[1][2] = m03 * m12 * m30 - m02 * m13 * m30 - m03 * m10 * m32 + m00 * m13 * m32 + m02 * m10 * m33 - m00 * m12 * m33; Temp.m[1][3] = m02 * m13 * m20 - m03 * m12 * m20 + m03 * m10 * m22 - m00 * m13 * m22 - m02 * m10 * m23 + m00 * m12 * m23; Temp.m[2][0] = m11 * m23 * m30 - m13 * m21 * m30 + m13 * m20 * m31 - m10 * m23 * m31 - m11 * m20 * m33 + m10 * m21 * m33; Temp.m[2][1] = m03 * m21 * m30 - m01 * m23 * m30 - m03 * m20 * m31 + m00 * m23 * m31 + m01 * m20 * m33 - m00 * m21 * m33; Temp.m[2][2] = m01 * m13 * m30 - m03 * m11 * m30 + m03 * m10 * m31 - m00 * m13 * m31 - m01 * m10 * m33 + m00 * m11 * m33; Temp.m[2][3] = m03 * m11 * m20 - m01 * m13 * m20 - m03 * m10 * m21 + m00 * m13 * m21 + m01 * m10 * m23 - m00 * m11 * m23; Temp.m[3][0] = m12 * m21 * m30 - m11 * m22 * m30 - m12 * m20 * m31 + m10 * m22 * m31 + m11 * m20 * m32 - m10 * m21 * m32; Temp.m[3][1] = m01 * m22 * m30 - m02 * m21 * m30 + m02 * m20 * m31 - m00 * m22 * m31 - m01 * m20 * m32 + m00 * m21 * m32; Temp.m[3][2] = m02 * m11 * m30 - m01 * m12 * m30 - m02 * m10 * m31 + m00 * m12 * m31 + m01 * m10 * m32 - m00 * m11 * m32; Temp.m[3][3] = m01 * m12 * m20 - m02 * m11 * m20 + m02 * m10 * m21 - m00 * m12 * m21 - m01 * m10 * m22 + m00 * m11 * m22; *this = (T (1) / det) * Temp; } template Matrix4x4 Matrix4x4::GetInverse() const { Matrix4x4 Temp = *this; Temp.Inverse(); return Temp; } // template // Matrix3x3 Matrix4x4::GetUpper3x3() const // { // Matrix3x3 Temp; // Temp.m[0][0] = m[0][0]; // Temp.m[0][1] = m[0][1]; // Temp.m[0][2] = m[0][2]; // // Temp.m[1][0] = m[1][0]; // Temp.m[1][1] = m[1][1]; // Temp.m[1][2] = m[1][2]; // // Temp.m[2][0] = m[2][0]; // Temp.m[2][1] = m[2][1]; // Temp.m[2][2] = m[2][2]; // // return Temp; // } // // template // Matrix2x2 Matrix4x4::GetUpper2x2() const // { // Matrix2x2 Temp; // Temp.m[0][0] = m[0][0]; // Temp.m[0][1] = m[0][1]; // // Temp.m[1][0] = m[1][0]; // Temp.m[1][1] = m[1][1]; // // return Temp; // } // s 0 0 0 // 0 s 0 0 // 0 0 s 0 // 0 0 0 1 template void Matrix4x4::Scale (T s) { m[0][0] = s; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = 0.0; m[1][0] = 0.0; m[1][1] = s; m[1][2] = 0.0; m[1][3] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = s; m[2][3] = 0.0; m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1; } // x 0 0 0 // 0 y 0 0 // 0 0 z 0 // 0 0 0 w template void Matrix4x4::Diagonal (T x, T y, T z, T w) { m[0][0] = x; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = 0.0; m[1][0] = 0.0; m[1][1] = y; m[1][2] = 0.0; m[1][3] = 0.0; m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = z; m[2][3] = 0.0; m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = w; } template void Matrix4x4::Rotate (T angle, Vector3 axis) { //See Quaternion::from_angle_axis() and Quaternion::get_matrix() // note: adapted from david eberly's code without permission //TODO: make sure it is correct if (axis.LengthSquared() < constants::epsilon_micro) { Identity(); } else { axis.Normalize(); T fCos = (T) cos(angle); T fSin = (T) sin(angle); T fOneMinusCos = 1.0f-fCos; T fX2 = axis.x*axis.x; T fY2 = axis.y*axis.y; T fZ2 = axis.z*axis.z; T fXYM = axis.x*axis.y*fOneMinusCos; T fXZM = axis.x*axis.z*fOneMinusCos; T fYZM = axis.y*axis.z*fOneMinusCos; T fXSin = axis.x*fSin; T fYSin = axis.y*fSin; T fZSin = axis.z*fSin; m[0][0] = fX2*fOneMinusCos+fCos; m[0][1] = fXYM-fZSin; m[0][2] = fXZM+fYSin; m[0][3] = 0; m[1][0] = fXYM+fZSin; m[1][1] = fY2*fOneMinusCos+fCos; m[1][2] = fYZM-fXSin; m[1][3] = 0; m[2][0] = fXZM-fYSin; m[2][1] = fYZM+fXSin; m[2][2] = fZ2*fOneMinusCos+fCos; m[2][3] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; } } template void Matrix4x4::LookAt (const Vector3 &eye, const Vector3 &at, const Vector3 &up) { // left handed Vector3 z_axis = at - eye; Vector3 x_axis = z_axis.CrossProduct (up); Vector3 y_axis = x_axis.CrossProduct (z_axis); x_axis.Normalize(); y_axis.Normalize(); z_axis.Normalize(); Matrix4x4 Rot; Rot.m[0][0] = x_axis.x; Rot.m[0][1] = x_axis.y; Rot.m[0][2] = x_axis.z; Rot.m[0][3] = 0; Rot.m[1][0] = y_axis.x; Rot.m[1][1] = y_axis.y; Rot.m[1][2] = y_axis.z; Rot.m[1][3] = 0; Rot.m[2][0] = -z_axis.x; Rot.m[2][1] = -z_axis.y; Rot.m[2][2] = -z_axis.z; Rot.m[2][3] = 0; Rot.m[3][0] = 0.0f; Rot.m[3][1] = 0.0f; Rot.m[3][2] = 0.0f; Rot.m[3][3] = 1.0f; Matrix4x4 Trans; Trans.Translate (-eye.x, -eye.y, -eye.z); *this = Rot * Trans; } /// set to an orthographic projection matrix. // 2/(r-l) 0 0 -(r+l)/(r-l) // 0 2/(t-b) 0 -(t+b)/(t-b) // 0 0 -2/(f-n) -(f+n)/(f-n) // 0 0 0 1 template void Matrix4x4::Orthographic (T l, T r, T b, T t, T n, T f) { T sx = 1 / (r - l); T sy = 1 / (t - b); T sz = 1 / (f - n); m[0][0] = 2.0f * sx; m[0][1] = 0.0f; m[0][2] = 0.0f; m[0][3] = - (r + l) * sx; m[1][0] = 0.0f; m[1][1] = 2.0f * sy; m[1][2] = 0.0f; m[1][3] = - (t + b) * sy; m[2][0] = 0.0f; m[2][1] = 0.0f; m[2][2] = -2.0f * sz; m[2][3] = - (f + n) * sz; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; } /// set to a perspective projection matrix. // 2*n/(r-l) 0 (r+l)/(r-l) 0 // 0 2*n/(t-b) (t+b)/(t-b) 0 // 0 0 -(f+n)/(f-n) -2*f*n/(f-n) // 0 0 -1 0 template void Matrix4x4::Perspective (T l, T r, T t, T b, T n, T f) { m[0][0] = 2.0f * n / (r - l); m[0][1] = 0.0f; m[0][2] = (r + l) / (r - l); m[0][3] = 0.0f; m[1][0] = 0.0f; m[1][1] = 2.0f * n / (t - b); m[1][2] = (t + b) / (t - b); m[1][3] = 0.0f; m[2][0] = 0.0f; m[2][1] = 0.0f; m[2][2] = - (f + n) / (f - n); m[2][3] = -2.0f * f * n / (f - n); m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = -1.0f; m[3][3] = 0.0f; } // (r-l)/2*n 0 0 (r+l)/(2*n) // 0 (t-b)/(2*n) 0 (t+b)/(2*n) // 0 0 0 -1 // 0 0 -(f-n)/(2*f*n) (f+n)/(2*f*n) template void Matrix4x4::PerspectiveInverse (T l, T r, T t, T b, T n, T f) { m[0][0] = (r - l) / (2.0f * n); m[0][1] = 0; m[0][2] = 0; m[0][3] = (r + l) / (2.0f * n); m[1][0] = 0; m[1][1] = (t - b) / (2.0f * n); m[1][2] = (t + b) / (2.0f * n); m[1][3] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = 0; m[2][3] = -1; m[3][0] = 0; m[3][1] = 0; m[3][2] = - (f - n) / (2.0f * f * n); m[3][3] = (f + n) / (2.0f * f * n); } /// set to a perspective projection matrix specified in terms of field of view and aspect ratio. template void Matrix4x4::Perspective (T FoV, T AspectRatio, T NearPlane, T FarPlane) { const T t = tan (FoV * 0.5f) * NearPlane; const T b = -t; const T l = AspectRatio * b; const T r = AspectRatio * t; Perspective (l, r, t, b, NearPlane, FarPlane); } template Matrix4x4 Matrix4x4::IDENTITY() { Matrix4x4 matrix; matrix.Identity(); return matrix; } template Matrix4x4 Matrix4x4::ZERO() { Matrix4x4 matrix; matrix.Zero(); return matrix; } template Matrix4x4 Matrix4x4::ROTATEX(T angle) { Matrix4x4 matrix; matrix.Rotate_x(angle); return matrix; } template Matrix4x4 Matrix4x4::ROTATEY(T angle) { Matrix4x4 matrix; matrix.Rotate_y(angle); return matrix; } template Matrix4x4 Matrix4x4::ROTATEZ(T angle) { Matrix4x4 matrix; matrix.Rotate_z(angle); return matrix; } template Matrix4x4 Matrix4x4::TRANSLATE(T x, T y, T z) { Matrix4x4 matrix; matrix.Translate(x, y, z); return matrix; } template Matrix4x4 Matrix4x4::SCALE(T x, T y, T z) { Matrix4x4 matrix; matrix.Scale(x, y, z); return matrix; } /***************************************************************************************\ Function: operator * Description: Multiply matrix rhs by constant lhs. Allow "f * matrix" operation. Parameters: None. Return Value: Matrix4. Comments: None. \***************************************************************************************/ template Matrix4x4 operator * (const T &lhs, const Matrix4x4& rhs) { Matrix4x4 oM; oM.m[0][0] = rhs.m[0][0] * lhs; oM.m[0][1] = rhs.m[0][1] * lhs; oM.m[0][2] = rhs.m[0][2] * lhs; oM.m[0][3] = rhs.m[0][3] * lhs; oM.m[1][0] = rhs.m[1][0] * lhs; oM.m[1][1] = rhs.m[1][1] * lhs; oM.m[1][2] = rhs.m[1][2] * lhs; oM.m[1][3] = rhs.m[1][3] * lhs; oM.m[2][0] = rhs.m[2][0] * lhs; oM.m[2][1] = rhs.m[2][1] * lhs; oM.m[2][2] = rhs.m[2][2] * lhs; oM.m[2][3] = rhs.m[2][3] * lhs; oM.m[3][0] = rhs.m[3][0] * lhs; oM.m[3][1] = rhs.m[3][1] * lhs; oM.m[3][2] = rhs.m[3][2] * lhs; oM.m[3][3] = rhs.m[3][3] * lhs; return oM; } typedef Matrix4x4 Matrix4; } #endif // MATRIX4_H nux-4.0.8+16.04.20160209/NuxCore/Math/Complex.cpp0000644000015600001650000001704512656236757021322 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Complex.h" namespace nux { ComplexNumber::ComplexNumber (float re, float im) { real_ = re; imaginary_ = im; } ComplexNumber::ComplexNumber (const ComplexNumber &complex) { real_ = complex.real_; imaginary_ = complex.imaginary_; } ComplexNumber::~ComplexNumber() { } ComplexNumber &ComplexNumber::operator= (const ComplexNumber &complex) { real_ = complex.real_; imaginary_ = complex.imaginary_; return *this; } /*const ComplexNumber ComplexNumber::operator + (const ComplexNumber& complex) const { ComplexNumber result; result.real_ = real_ + complex.real_; result.imaginary_ = imaginary_ + complex.imaginary_; return result; } const ComplexNumber ComplexNumber::operator - (const ComplexNumber& complex) const { ComplexNumber result; result.real_ = real_ - complex.real_; result.imaginary_ = imaginary_ - complex.imaginary_; return result; } const ComplexNumber ComplexNumber::operator*(const ComplexNumber& complex) const { ComplexNumber result; float a, b, c, d; a = real_; b = imaginary_; c = complex.real_; d = complex.imaginary_; result.real_ = (a*c - b*d); result.imaginary_ = (a*d + b*c); return result; } const ComplexNumber ComplexNumber::operator / (const ComplexNumber& complex) const { ComplexNumber result; float a, b, c, d; float inv_denominator; a = real_; b = imaginary_; c = complex.real_; d = complex.imaginary_; inv_denominator = (float) 1.0 / (c*c + d*d); result.real_ = (a*c + b*d) * inv_denominator; result.imaginary_ = (b*c - a*d) * inv_denominator; return result; } */ /*const ComplexNumber ComplexNumber::operator * (const float& f) const { ComplexNumber result; result.real_ = real_ * f; result.imaginary_ = imaginary_ * f; return result; }*/ /*const ComplexNumber ComplexNumber::operator / (const float& f) const { ComplexNumber result; //if(f == 0.0f) // trow(Exception); result.real_ = real_ / f ; result.imaginary_ = imaginary_ / f; return result; }*/ void ComplexNumber::operator+= (const ComplexNumber &complex) { real_ += complex.real_; imaginary_ += complex.imaginary_; } void ComplexNumber::operator-= (const ComplexNumber &complex) { real_ -= complex.real_; imaginary_ -= complex.imaginary_; } void ComplexNumber::operator*= (const ComplexNumber &complex) { ComplexNumber result; float a, b, c, d; a = real_; b = imaginary_; c = complex.real_; d = complex.imaginary_; real_ = (a * c - b * d); imaginary_ = (a * d + b * c); } void ComplexNumber::operator /= (const ComplexNumber &complex) { ComplexNumber result; float a, b, c, d; float inv_denominator; //if(complex.real_ == 0 && complex.imaginary_ == 0) // trow(Exeption); a = real_; b = imaginary_; c = complex.real_; d = complex.imaginary_; inv_denominator = (float) 1.0 / (c * c + d * d); real_ = (a * c + b * d) * inv_denominator; imaginary_ = (b * c - a * d) * inv_denominator; } /*void ComplexNumber::operator *= (const float& f) { real_ *= f; imaginary_ *= f; }*/ /*void ComplexNumber::operator/=(const float& f) { //if(f == 0.0f) // trow(Exception); real_ *= (float)1.0 / f; imaginary_ *= (float)1.0 / f; }*/ void ComplexNumber::conjugue() { imaginary_ = -imaginary_; } float ComplexNumber::absolute() { float x, y, result; x = (float) std::fabs (real_); y = (float) std::fabs (imaginary_); if (x == 0.0) result = y; else { if (y == 0.0) result = x; else { float temp; if (x > y) { temp = y / x; result = x * (float) std::sqrt (1.0 + temp * temp); } else { temp = x / y; result = y * (float) std::sqrt (1.0 + temp * temp); } } } return result; } bool ComplexNumber::IsNull() { if ( (real_ == 0) && (imaginary_ == 0) ) { return true; } return false; } float ComplexNumber::real() const { return real_; } float ComplexNumber::imaginary() const { return imaginary_; } void ComplexNumber::real (float r) { real_ = r; } void ComplexNumber::imaginary (float i) { imaginary_ = i; } const ComplexNumber operator + (const ComplexNumber &lhs, const ComplexNumber &rhs) { return ComplexNumber (lhs.real() + rhs.real(), lhs.imaginary() + rhs.imaginary() ); } const ComplexNumber operator - (const ComplexNumber &lhs, const ComplexNumber &rhs) { return ComplexNumber (lhs.real() - rhs.real(), lhs.imaginary() - rhs.imaginary() ); } const ComplexNumber operator* (const ComplexNumber &lhs, const ComplexNumber &rhs) { ComplexNumber result; float a, b, c, d; a = lhs.real(); b = lhs.imaginary(); c = rhs.real(); d = rhs.imaginary(); result.real (a * c - b * d); result.imaginary (a * d + b * c); return result; } const ComplexNumber operator/ (const ComplexNumber &lhs, const ComplexNumber &rhs) { ComplexNumber result; float a, b, c, d; float inv_denominator; a = lhs.real(); b = lhs.imaginary(); c = rhs.real(); d = rhs.imaginary(); inv_denominator = (float) 1.0 / (c * c + d * d); result.real ( (a * c + b * d) * inv_denominator); result.imaginary ( (b * c - a * d) * inv_denominator); return result; } /*fcomplex Cdiv(fcomplex a, fcomplex b) { fcomplex c; float den, r; if (fabs(b.r) >= fabs(b.i)) { r = b.i/b.r; den = b.r + r*b.i; c.r = (a.r+r*a.i) / den; c.i = (a.i-r*a.r) / den; } else { r = b.r/b.i; den = b.i + r*b.r; c.r = (a.r*r+a.i) / den; c.i = (a.i*r-a.r) / den; } return c; } */ /* fcomplex Csqrt(fcomplex z) { fcomplex c; float w; if ((z.r == 0.0) && (z.i == 0.0)) { c.r = 0.0; c.i = 0.0; } else { w = sqrt( (sqrt( z.r*z.r + z.i*z.i ) + fabs(z.r)) * 0.5); if (z.r >= 0.0) { c.r = w; c.i = z.i / (2.0*w); } else { c.i = (z.i >= 0) ? w : -w; c.r = z.i / (2.0*c.i); } } return c; } fcomplex RCmul(float x, fcomplex a) { fcomplex c; c.r = x*a.r; c.i = x*a.i; return c; } fcomplex Cinv( fcomplex z) { fcomplex c; float s = 1.0 / (z.r*z.r + z.i*z.i); c.r = z.r * s; c.i = -z.i * s; return c; } */ } nux-4.0.8+16.04.20160209/NuxCore/Math/Line2D.h0000644000015600001650000000637312656236757020437 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef LINE2D_H #define LINE2D_H #include "Vector2.h" namespace nux { template class Line2D { public: Line2D(); ~Line2D(); Line2D (const Line2D &line); Line2D (T lx_start, T ly_start, T lz_start, T lx_end, T ly_end, T lz_end); Line2D (const Vec2& pt, Vec2 v); const Line2D& operator = (const Line2D&); bool operator == (const Line2D& line) const; float Length() const; const Vec2 GetDirectionVector() const; const Vec2 GetStartPoint() const; const Vec2 GetEndPoint() const; private: T x_start, y_start; T x_end, y_end; }; template Line2D::Line2D() { x_start = y_start = x_end = y_end = 0; } template Line2D::~Line2D() { } template Line2D::Line2D (const Line2D &line) { x_start = line.x_start; x_end = line.x_end; y_start = line.y_start; y_end = line.y_end; } template Line2D::Line2D (T lx_start, T ly_start, T lz_start, T lx_end, T ly_end, T lz_end) { x_start = lx_start; x_end = lx_end; y_start = ly_start; y_end = ly_end; } template Line2D::Line2D (const Vec2& pt, Vec2 v) { x_start = pt.x; y_start = pt.y; x_end = x_start + v.x; y_end = y_start + v.y; } template const Line2D& Line2D::operator = (const Line2D& Line) { x_start = Line.x_start; x_end = Line.x_end; y_start = Line.y_start; y_end = Line.y_end; } template bool Line2D::operator == (const Line2D& line) const { if ( (x_start == line.x_start) && (y_start == line.y_start) && (x_end == line.x_end) && (y_end == line.y_end) ) { return true; } else { return false; } } template float Line2D::Length() const { float l; l = (float) std::sqrt ( (x_end - x_start) * (x_end - x_start) + (y_end - y_start) * (y_end - y_start) ); return l; } template const Vec2 Line2D::GetDirectionVector() const { return Vec2 (x_start - x_end, y_start - y_end); } template const Vec2 Line2D::GetStartPoint() const { Vec2 p (x_start, y_start); return p; } template const Vec2 Line2D::GetEndPoint() const { Vec2 p (x_end, y_end); return p; } }; #endif // LINE2D_H nux-4.0.8+16.04.20160209/NuxCore/Math/Line2D.cpp0000644000015600001650000000156312656236757020766 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "Vector2.h" #include "Line2D.h" namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/Math/Bezier.cpp0000644000015600001650000000427312656236757021132 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "../NuxCore.h" #include "MathFunctions.h" #include "Bezier.h" namespace nux { NUX_DECLSPEC_DLL double *Bernstein (int n, double t) { if (n < 0) { NUX_BREAK_ASM_INT3; } double *bernstein; int i; bernstein = new double[n+1]; for (i = 0; i <= n; i++ ) { bernstein[i] = BinomialCoefficient (n, i) * PowerInt (t, i) * PowerInt (1.0 - t, n - i); } return bernstein; } NUX_DECLSPEC_DLL void Bezier_XY (int n, double t, double xcon[], double ycon[], double *xval, double *yval) { if (n < 0) { NUX_BREAK_ASM_INT3; } double *bval; int i; bval = Bernstein ( n, t ); *xval = 0.0; for ( i = 0; i <= n; i++ ) *xval = *xval + xcon[i] * bval[i]; *yval = 0.0; for ( i = 0; i <= n; i++ ) *yval = *yval + ycon[i] * bval[i]; delete [] bval; } NUX_DECLSPEC_DLL void Bezier_XYZ (int n, double t, double xcon[], double ycon[], double zcon[], double *xval, double *yval, double *zval) { if (n < 0) NUX_BREAK_ASM_INT3; double *bval; int i; bval = Bernstein ( n, t ); *xval = 0.0; for ( i = 0; i <= n; i++ ) *xval = *xval + xcon[i] * bval[i]; *yval = 0.0; for ( i = 0; i <= n; i++ ) *yval = *yval + ycon[i] * bval[i]; *zval = 0.0; for ( i = 0; i <= n; i++ ) *zval = *zval + zcon[i] * bval[i]; delete [] bval; } } nux-4.0.8+16.04.20160209/NuxCore/Math/Point3D.h0000644000015600001650000000373712656236757020643 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef POINT3D_H #define POINT3D_H namespace nux { template class Point3D { public: Point3D(); ~Point3D(); Point3D (const Point3D &Pt); Point3D (T x, T y, T z); void Set (T X, T Y, T Z); bool operator == (const Point3D& Pt) const; bool operator != (const Point3D& Pt) const; T x, y, z; }; template Point3D::Point3D() { x = 0; y = 0; z = 0; } template Point3D::~Point3D() { } template Point3D::Point3D (const Point3D &Pt) { x = Pt.x; y = Pt.y; z = Pt.z; } template Point3D::Point3D (T X, T Y, T Z) { x = X; y = Y; z = Z; } template void Point3D::Set (T X, T Y, T Z) { x = X; y = Y; z = Z; } template bool Point3D::operator == (const Point3D& Pt) const { if ( (x == Pt.x) && (y == Pt.y) && (z == Pt.z) ) { return true; } return false; } template bool Point3D::operator != (const Point3D& Pt) const { return ! ( (*this) == Pt); } typedef Point3D Point3; } #endif // POINT3D_H nux-4.0.8+16.04.20160209/NuxCore/Platform.cpp0000644000015600001650000001220612656236757020600 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #if defined(NUX_OS_LINUX) #include #endif namespace nux { NUX_IMPLEMENT_GLOBAL_OBJECT (NGlobalData); void NuxCoreInitialize (const TCHAR *CommandLine) { static bool sInitialized = false; // Avoid initializing multiple times. if (sInitialized) return; sInitialized = true; NUX_GLOBAL_OBJECT_INSTANCE (NGlobalData).Initialize (CommandLine); NThreadLocalStorage::Initialize(); } void ExitSystem() { //SystemShutdown(); } void inlInitRandomGenerator() { #if _WIN32 std::srand ( time (NULL) ); #endif } static std::string _GetProgramDirectory() { #if defined(NUX_OS_WINDOWS) TCHAR RootDirectory[NUX_MAX_FILEPATH_SIZE] = TEXT (""); if (!RootDirectory[0]) { DWORD Result = ::GetModuleFileName (NULL, RootDirectory, NUX_MAX_FILEPATH_SIZE); nuxAssertMsg (Result, TEXT ("[GetProgramDirectory] Can't get program's directory path.") ); if (Result == 0) std::string (TEXT ("Unknown Program Directory") ); unsigned int i; // Skip the program name for (i = (unsigned int) StringLength (RootDirectory) - 1; i > 0; i--) { if ( (RootDirectory[i - 1] == NUX_BACKSLASH_CHAR) || (RootDirectory[i-1] == TEXT ('/') ) ) break; } RootDirectory[i] = 0; } return std::string (RootDirectory); #elif defined(NUX_OS_LINUX) TCHAR RootDirectory[NUX_MAX_FILEPATH_SIZE] = TEXT (""); if (!RootDirectory[0]) { char *Result = getcwd (RootDirectory, NUX_MAX_FILEPATH_SIZE); nuxAssertMsg (Result, TEXT ("[GetProgramDirectory] Can't get program's directory path.") ); if (Result == 0) std::string (TEXT ("Unknown Program Directory") ); } nuxDebugMsg (TEXT ("[GetProgramDirectory] Program directory path: %s"), RootDirectory); return std::string (RootDirectory); #else return std::string (TEXT ("Unknown Program Directory") ); #endif } static std::string _GetComputerName() { #if defined(NUX_OS_WINDOWS) TCHAR ComputerName[NUX_MAX_FILEPATH_SIZE] = TEXT (""); if (!ComputerName[0]) { DWORD Size = NUX_ARRAY_COUNT (ComputerName); ::GetComputerName (ComputerName, &Size); TCHAR *c, *d; for (c = ComputerName, d = ComputerName; *c != 0; c++) { if (IsAlphanumericChar (*c) ) *d++ = *c; } *d++ = 0; } return std::string (ComputerName); #elif defined(NUX_OS_LINUX) char Buffer[NUX_MAX_FILEPATH_SIZE]; size_t BufferSize = NUX_ARRAY_COUNT (Buffer); if (gethostname (Buffer, BufferSize) != -1) { return std::string (Buffer); } return std::string (TEXT ("Unknown Computer Name") ); #else return std::string (TEXT ("Unknown Computer Name") ); #endif } // Get user name. NOTE: Only one return value is valid at a time! static std::string _GetUserName() { #if defined(NUX_OS_WINDOWS) TCHAR UserName[256] = TEXT (""); if ( !UserName[0] ) { DWORD Size = NUX_ARRAY_COUNT (UserName); ::GetUserName (UserName, &Size); TCHAR *c, *d; for (c = UserName, d = UserName; *c != 0; c++) if (IsAlphanumericChar (*c) ) *d++ = *c; *d++ = 0; } return std::string (UserName); #elif defined(NUX_OS_LINUX) struct passwd *userinfo; userinfo = getpwuid (getuid() ); if (userinfo == 0) return std::string (TEXT ("Unknown User") ); return std::string (userinfo->pw_name); #else return return std::string (TEXT ("Unknown User") ); #endif } void NGlobalData::Initialize (const TCHAR * /* CommandLine */) { } void NGlobalData::Constructor() { m_ComputerName = _GetComputerName(); m_ProgramDirectory = _GetProgramDirectory(); m_UserName = _GetUserName(); m_RandomSeed = 0x5A7CF91E; // arbitrary std::srand (m_RandomSeed); } void NGlobalData::Destructor() { } std::string GetComputerName() { return NUX_GLOBAL_OBJECT_INSTANCE (NGlobalData).m_ComputerName; } std::string GetProgramDirectory() { return NUX_GLOBAL_OBJECT_INSTANCE (NGlobalData).m_ProgramDirectory; } std::string GetUserName() { return NUX_GLOBAL_OBJECT_INSTANCE (NGlobalData).m_UserName; } std::string GetCmdLine() { return NUX_GLOBAL_OBJECT_INSTANCE (NGlobalData).m_CommandLine; } std::string GetLogDirectory() { return TEXT ("Logs"); } } nux-4.0.8+16.04.20160209/NuxCore/Logger.h0000644000015600001650000001423212656236757017701 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUX_CORE_LOGGER_H #define NUX_CORE_LOGGER_H #include #include #include #if defined(NUX_OS_WINDOWS) #define __func__ __FUNCTION__ #endif #define LOG_TRACE(logger) \ if (!Unwrap(logger).IsTraceEnabled()) {} \ else ::nux::logging::LogStream(::nux::logging::Trace, Unwrap(logger).module(), __FILE__, __LINE__).stream() #define LOG_DEBUG(logger) \ if (!Unwrap(logger).IsDebugEnabled()) {} \ else ::nux::logging::LogStream(::nux::logging::Debug, Unwrap(logger).module(), __FILE__, __LINE__).stream() #define LOG_INFO(logger) \ if (!Unwrap(logger).IsInfoEnabled()) {} \ else ::nux::logging::LogStream(::nux::logging::Info, Unwrap(logger).module(), __FILE__, __LINE__).stream() #define LOG_WARN(logger) LOG_WARNING(logger) #define LOG_WARNING(logger) \ if (!Unwrap(logger).IsWarningEnabled()) {} \ else ::nux::logging::LogStream(::nux::logging::Warning, Unwrap(logger).module(), __FILE__, __LINE__).stream() #define LOG_ERROR(logger) \ if (!Unwrap(logger).IsErrorEnabled()) {} \ else ::nux::logging::LogStream(::nux::logging::Error, Unwrap(logger).module(), __FILE__, __LINE__).stream() // We shouldn't really be logging block level information at anything higher than debug. #if defined(NUX_OS_WINDOWS) #define LOG_TRACE_BLOCK(logger) #define LOG_DEBUG_BLOCK(logger) #else #define LOG_TRACE_BLOCK(logger) ::nux::logging::BlockTracer _block_tracer_ ## __LINE__ (Unwrap(logger), ::nux::logging::Trace, __PRETTY_FUNCTION__, __FILE__, __LINE__) #define LOG_DEBUG_BLOCK(logger) ::nux::logging::BlockTracer _block_tracer_ ## __LINE__ (Unwrap(logger), ::nux::logging::Debug, __PRETTY_FUNCTION__, __FILE__, __LINE__) #endif /* * This macro is used to declare a file scoped logger module function. The * purpose of this is to allow a file scoped logger that doesn't use static * initialisation, but instead is a method that creates the object the first * time it is used. * * Used like: * * DECLARE_LOGGER(logger, "test.module"); * * Then used like this in some function (just like a normal logger object): * * LOG_DEBUG(logger) << "foo"; */ #define DECLARE_LOGGER(logger, module) \ namespace { \ ::nux::logging::Logger& logger() \ { \ static ::nux::logging::Logger instance(module); \ return instance; \ } \ } namespace nux { namespace logging { enum Level { NotSpecified, Trace, Debug, Info, Warning, Error, Critical, }; // Convert a string representation of a logging level into the enum value. Level get_logging_level(std::string level); /** * Configure multiple logging modules. * * This function expects a string of the format: * module=info;sub.module=debug;other.module=warning * * * The root module can be specified by using the value "", eg: * =info;other.module=debug * * The specified modules will have their logging level set to the specified * level as defined by the get_logging_level function. * * It is expected that this method is called during application startup with * the content of some environment variable. * nux::logging::configure_logging(::getenv("MY_APP_LOGGING_CONFIG")); */ void configure_logging(const char* config_string); std::string Backtrace(int levels = -1); void reset_logging(); std::string dump_logging_levels(std::string const& prefix = ""); class LogStream : public std::ostream { public: LogStream(Level severity, std::string const& module, std::string const& filename, int line_number); ~LogStream(); std::ostream& stream() { return *this; } }; class LoggerModule; typedef boost::shared_ptr LoggerModulePtr; class Logger { public: explicit Logger(std::string const& module); std::string const& module() const; bool IsErrorEnabled() const; bool IsWarningEnabled() const; bool IsInfoEnabled() const; bool IsDebugEnabled() const; bool IsTraceEnabled() const; void SetLogLevel(Level level); Level GetLogLevel() const; Level GetEffectiveLogLevel() const; private: LoggerModulePtr pimpl; }; // The Unwrap function is used by the LOG_* macros above to accept either a // reference to a Logger object, or a function that when called returns a // reference to a Logger object. inline Logger const& Unwrap(Logger const& logger) { return logger; } typedef Logger& (*LoggerFunc)(); inline Logger const& Unwrap(LoggerFunc func) { return func(); } /** * This class is used to log the entry and exit of a block. * * Entry is defined as where the object is created. This is most likely going * to be defined using the macros defined above. Exit is defined as object * destruction, which is normally controlled through the end of scope killing * the stack object. * * int some_func(params...) * { * LOG_TRACE_BLOCK(logger); * ... * } */ class BlockTracer { public: BlockTracer(Logger const& logger, Level level, std::string const& function_name, std::string const& filename, int line_number); ~BlockTracer(); private: Logger const& logger_; Level level_; std::string function_name_; std::string filename_; int line_number_; }; } } #endif nux-4.0.8+16.04.20160209/NuxCore/SystemGNU.h0000644000015600001650000004031512656236757020321 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef SYSTEMGNU_H #define SYSTEMGNU_H #include #include #include #include #include #include #include #include #include #include #include #include // If NUX_LOG_FILE_ANSI is set to 1, log files will be written in ASCII characters even when in UNICODE. #define NUX_LOG_FILE_ANSI 1 #define NUX_VARARGS __cdecl // Functions with variable arguments // Calling Convention // This is the default calling convention for C and C++ programs. // Because the stack is cleaned up by the caller, it can do vararg functions. // Argument-passing order: Right to left #define NUX_CDECL __cdecl // The __stdcall calling convention is used to call Win32 API functions. // The callee cleans the stack, so the compiler makes vararg functions __cdecl. // Argument-passing order: Right to left #define NUX_STDCALL __stdcall // The __fastcall calling convention specifies that arguments to functions are to be passed in registers, when possible. #define NUX_FASTCALL __fastcall // This is the default calling convention used by C++ member functions that do not use variable arguments. // Under thiscall, the callee cleans the stack, which is impossible for vararg functions. #define NUX_THISCALL thiscall // #define NUX_INLINE inline // Force inline code #define NUX_FORCEINLINE inline //__attribute__ ((__always_inline)) // Force inline code #define NUX_FORCENOINLINE __attribute__ ((noinline)) // Force code to NOT be inline // Unsigned base types. typedef unsigned char BOOL; // 8-bit unsigned. typedef unsigned char BYTE; // 8-bit unsigned. typedef unsigned short WORD; // 16-bit unsigned. typedef unsigned int UINT; // 32-bit unsigned. typedef unsigned long DWORD; // 32-bit unsigned. typedef uint64_t QWORD; // 64-bit unsigned. // Signed base types. typedef signed char SBYTE; // 8-bit signed. typedef signed short SWORD; // 16-bit signed. typedef signed int INT; // 32-bit signed. typedef int64_t SQWORD; // 64-bit signed. // Character types. typedef char ANSICHAR; // An ANSI character. typedef unsigned char ANSIUCHAR; // An ANSI character. typedef wchar_t UNICHAR; // A unicode character. // Other base types. typedef float FLOAT; // 32-bit IEEE floating point. typedef double DOUBLE; // 64-bit IEEE double. typedef unsigned long SIZE_T; // Corresponds to C SIZE_T. /////////////////////////////////////////////// // UNICODE // /////////////////////////////////////////////// #ifdef NUX_UNICODE typedef UNICHAR TCHAR; #undef TEXT #define TEXT(s) L##s #else typedef ANSICHAR TCHAR; #undef TEXT #define TEXT(s) s #endif #ifdef NUX_UNICODE #define WINE_tchar_true(a) (1) #define WINE_tchar_false(a) (0) #define WINE_tchar_tclen(a) (1) #define WINE_tchar_tccpy(a,b) do { *(a)=*(b); } while (0) #else #define WINE_tchar_true(a) (1) #define WINE_tchar_false(a) (0) #define WINE_tchar_tclen(a) (1) #define WINE_tchar_tccpy(a,b) do { *(a)=*(b); } while (0) #endif #ifndef NUX_UNICODE #ifndef NUX_MBCS #define NUX_TCHAR_ROUTINE(ansi, mbcs, unicode) ansi #else #define NUX_TCHAR_ROUTINE(ansi, mbcs, unicode) mbcs #endif #else #define NUX_TCHAR_ROUTINE(ansi, mbcs, unicode) unicode #endif #define NUX_UNIX_SYS_HOST_ROOT TEXT("/") #define NUX_UNIX_SYS_HOME TEXT("/home") /////////////////////////////////////////////// #define __targv NUX_TCHAR_ROUTINE(__argv, __argv, __wargv) #define _fgettc NUX_TCHAR_ROUTINE(fgetc, fgetc, fgetwc) #define _fgettchar NUX_TCHAR_ROUTINE(fgetchar, fgetchar, _fgetwchar) #define _fgetts NUX_TCHAR_ROUTINE(fgets, fgets, fgetws) #define _fputtc NUX_TCHAR_ROUTINE(fputc, fputc, fputwc) #define _fputtchar NUX_TCHAR_ROUTINE(fputchar, fputchar, _fputwchar) #define _fputts NUX_TCHAR_ROUTINE(fputs, fputs, fputws) #define _ftprintf NUX_TCHAR_ROUTINE(fprintf, fprintf, fwprintf) #define _ftscanf NUX_TCHAR_ROUTINE(fscanf, fscanf, fwscanf) #define _gettc NUX_TCHAR_ROUTINE(getc, getc, getwc) #define _gettchar NUX_TCHAR_ROUTINE(getchar, getchar, getwchar) #define _getts NUX_TCHAR_ROUTINE(gets, gets, getws) #define _isalnum NUX_TCHAR_ROUTINE(isalnum, _ismbcalnum, iswalnum) #define _istalpha NUX_TCHAR_ROUTINE(isalpha, _ismbcalpha, iswalpha) #define _istascii NUX_TCHAR_ROUTINE(isascii, __isascii, iswascii) #define _istcntrl NUX_TCHAR_ROUTINE(iscntrl, iscntrl, iswcntrl) #define _istdigit NUX_TCHAR_ROUTINE(isdigit, _ismbcdigit, iswdigit) #define _istgraph NUX_TCHAR_ROUTINE(isgraph, _ismbcgraph, iswgraph) #define _istlead NUX_TCHAR_ROUTINE(WINE_tchar_false,_ismbblead, WINE_tchar_false) #define _istleadbyte NUX_TCHAR_ROUTINE(WINE_tchar_false,isleadbyte, WINE_tchar_false) #define _istlegal NUX_TCHAR_ROUTINE(WINE_tchar_true, _ismbclegal, WINE_tchar_true) #define _istlower NUX_TCHAR_ROUTINE(islower, _ismbcslower,iswlower) #define _istprint NUX_TCHAR_ROUTINE(isprint, _ismbcprint, iswprint) #define _istpunct NUX_TCHAR_ROUTINE(ispunct, _ismbcpunct, iswpunct) #define _istspace NUX_TCHAR_ROUTINE(isspace, _ismbcspace, iswspace) #define _istupper NUX_TCHAR_ROUTINE(isupper, _ismbcupper, iswupper) #define _istxdigit NUX_TCHAR_ROUTINE(isxdigit, isxdigit, iswxdigit) #define _itot NUX_TCHAR_ROUTINE(_itoa, _itoa, _itow) #define _ltot NUX_TCHAR_ROUTINE(_ltoa, _ltoa, _ltow) #define _puttc NUX_TCHAR_ROUTINE(putc, putc, putwc) #define _puttchar NUX_TCHAR_ROUTINE(putchar, putchar, putwchar) #define _putts NUX_TCHAR_ROUTINE(puts, puts, putws) #define _sntprintf NUX_TCHAR_ROUTINE(sprintf, sprintf, swprintf) #define _stprintf NUX_TCHAR_ROUTINE(sprintf, sprintf, swprintf) #define _stscanf NUX_TCHAR_ROUTINE(sscanf, sscanf, swscanf) #define _taccess NUX_TCHAR_ROUTINE(access, _access, _waccess) #define _tasctime NUX_TCHAR_ROUTINE(asctime, asctime, _wasctime) #define _tccpy NUX_TCHAR_ROUTINE(WINE_tchar_tccpy,_mbccpy, WINE_tchar_tccpy) #define _tchdir NUX_TCHAR_ROUTINE(chdir, _chdir, _wchdir) #define _tclen NUX_TCHAR_ROUTINE(WINE_tchar_tclen,_mbclen, WINE_tchar_tclen) #define _tchmod NUX_TCHAR_ROUTINE(chmod, _chmod, _wchmod) #define _tcreat NUX_TCHAR_ROUTINE(creat, _creat, _wcreat) #define _tcscat NUX_TCHAR_ROUTINE(strcat, _mbscat, wcscat) #define _tcschr NUX_TCHAR_ROUTINE(strchr, _mbschr, wcschr) #define _tcsclen NUX_TCHAR_ROUTINE(strlen, _mbslen, wcslen) #define _tcscmp NUX_TCHAR_ROUTINE(strcmp, _mbscmp, wcscmp) #define _tcscoll NUX_TCHAR_ROUTINE(strcoll, _mbscoll, wcscoll) #define _tcscpy NUX_TCHAR_ROUTINE(strcpy, _mbscpy, wcscpy) #define _tcscspn NUX_TCHAR_ROUTINE(strcspn, _mbscspn, wcscspn) #define _tcsdec NUX_TCHAR_ROUTINE(_strdec, _mbsdec, _wcsdec) #define _tcsdup NUX_TCHAR_ROUTINE(strdup, _mbsdup, _wcsdup) #define _tcsftime NUX_TCHAR_ROUTINE(strftime, strftime, wcsftime) #define _tcsicmp NUX_TCHAR_ROUTINE(strcasecmp, _mbsicmp, _wcsicmp) #define _tcsicoll NUX_TCHAR_ROUTINE(_stricoll, _stricoll, _wcsicoll) #define _tcsinc NUX_TCHAR_ROUTINE(_strinc, _mbsinc, _wcsinc) #define _tcslen NUX_TCHAR_ROUTINE(strlen, strlen, wcslen) #define _tcslwr NUX_TCHAR_ROUTINE(strlwr, _mbslwr, wcslwr) #define _tcsnbcnt NUX_TCHAR_ROUTINE(_strncnt, _mbsnbcnt, _wcnscnt) #define _tcsncat NUX_TCHAR_ROUTINE(strncat, _mbsnbcat, wcsncat) #define _tcsnccat NUX_TCHAR_ROUTINE(strncat, _mbsncat, wcsncat) #define _tcsncmp NUX_TCHAR_ROUTINE(strncmp, _mbsnbcmp, wcsncmp) #define _tcsnccmp NUX_TCHAR_ROUTINE(strncmp, _mbsncmp, wcsncmp) #define _tcsnccnt NUX_TCHAR_ROUTINE(_strncnt, _mbsnccnt, _wcsncnt) #define _tcsnccpy NUX_TCHAR_ROUTINE(strncpy, _mbsncpy, wcsncpy) #define _tcsncicmp NUX_TCHAR_ROUTINE(_strnicmp, _mbsnicmp, _wcsnicmp) #define _tcsncpy NUX_TCHAR_ROUTINE(strncpy, _mbsnbcpy, wcsncpy) #define _tcsncset NUX_TCHAR_ROUTINE(_strnset, _mbsnset, _wcsnset) #define _tcsnextc NUX_TCHAR_ROUTINE(_strnextc, _mbsnextc, _wcsnextc) #define _tcsnicmp NUX_TCHAR_ROUTINE(_strnicmp, _mbsnicmp, _wcsnicmp) #define _tcsnicoll NUX_TCHAR_ROUTINE(_strnicoll, _strnicoll _wcsnicoll) #define _tcsninc NUX_TCHAR_ROUTINE(_strninc, _mbsninc, _wcsninc) #define _tcsnccnt NUX_TCHAR_ROUTINE(_strncnt, _mbsnccnt, _wcsncnt) #define _tcsnset NUX_TCHAR_ROUTINE(_strnset, _mbsnbset, _wcsnset) #define _tcspbrk NUX_TCHAR_ROUTINE(strpbrk, _mbspbrk, wcspbrk) #define _tcsspnp NUX_TCHAR_ROUTINE(_strspnp, _mbsspnp, _wcsspnp) #define _tcsrchr NUX_TCHAR_ROUTINE(strrchr, _mbsrchr, wcsrchr) #define _tcsrev NUX_TCHAR_ROUTINE(_strrev, _mbsrev, _wcsrev) #define _tcsset NUX_TCHAR_ROUTINE(_strset, _mbsset, _wcsset) #define _tcsspn NUX_TCHAR_ROUTINE(strspn, _mbsspn, wcsspn) #define _tcsstr NUX_TCHAR_ROUTINE(strstr, _mbsstr, wcsstr) #define _tcstod NUX_TCHAR_ROUTINE(strtod, strtod, wcstod) #define _tcstok NUX_TCHAR_ROUTINE(strtok, _mbstok, wcstok) #define _tcstol NUX_TCHAR_ROUTINE(strtol, strtol, wcstol) #define _tcstoul NUX_TCHAR_ROUTINE(std::strtoul, strtoul, std::wcstoul) #define _tcsupr NUX_TCHAR_ROUTINE(strupr, _mbsupr, wcsupr) #define _tcsxfrm NUX_TCHAR_ROUTINE(strxfrm, strxfrm, wcsxfrm) #define _tctime NUX_TCHAR_ROUTINE(ctime, ctime, _wctime) #define _tenviron NUX_TCHAR_ROUTINE(_environ, _environ, _wenviron) #define _texecl NUX_TCHAR_ROUTINE(execl, _execl, _wexecl) #define _texecle NUX_TCHAR_ROUTINE(execle, _execle, _wexecle) #define _texeclp NUX_TCHAR_ROUTINE(execlp, _execlp, _wexeclp) #define _texeclpe NUX_TCHAR_ROUTINE(execlpe, _execlpe, _wexeclpe) #define _texecv NUX_TCHAR_ROUTINE(execv, _execv, _wexecv) #define _texecve NUX_TCHAR_ROUTINE(execve, _execve, _wexecve) #define _texecvp NUX_TCHAR_ROUTINE(execvp, _execvp, _wexecvp) #define _texecvpe NUX_TCHAR_ROUTINE(execvpe, _execvpe, _wexecvpe) #define _tfdopen NUX_TCHAR_ROUTINE(fdopen, _fdopen, _wfdopen) #define _tfinddata_t NUX_TCHAR_ROUTINE(_finddata_t, _finddata_t, _wfinddata_t) #define _tfinddatai64_t NUX_TCHAR_ROUTINE(_finddatai64_t,_finddatai64_t,_wfinddatai64_t) #define _tfindfirst NUX_TCHAR_ROUTINE(_findfirst, _findfirst, _wfindfirst) #define _tfindnext NUX_TCHAR_ROUTINE(_findnext, _findnext, _wfindnext) #define _tfopen NUX_TCHAR_ROUTINE(fopen, fopen, _wfopen) #define _tfreopen NUX_TCHAR_ROUTINE(freopen, freopen, _wfreopen) #define _tfsopen NUX_TCHAR_ROUTINE(_fsopen, _fsopen, _wfsopen) #define _tfullpath NUX_TCHAR_ROUTINE(_fullpath, _fullpath, _wfullpath) #define _tgetcwd NUX_TCHAR_ROUTINE(getcwd, _getcwd, _wgetcwd) #define _tgetenv NUX_TCHAR_ROUTINE(getenv, getenv, _wgetenv) #define _tmain NUX_TCHAR_ROUTINE(main, main, wmain) #define _tmakepath NUX_TCHAR_ROUTINE(_makepath, _makepath, _wmakepath) #define _tmkdir NUX_TCHAR_ROUTINE(mkdir, _mkdir, _wmkdir) #define _tmktemp NUX_TCHAR_ROUTINE(mktemp, _mktemp, _wmktemp) #define _tperror NUX_TCHAR_ROUTINE(perror, perror, _wperror) #define _topen NUX_TCHAR_ROUTINE(open, _open, _wopen) #define _totlower NUX_TCHAR_ROUTINE(std::tolower, _mbctolower, towlower) #define _totupper NUX_TCHAR_ROUTINE(std::toupper, _mbctoupper, towupper) #define _tpopen NUX_TCHAR_ROUTINE(popen, _popen, _wpopen) #define _tprintf NUX_TCHAR_ROUTINE(printf, printf, wprintf) #define _tremove NUX_TCHAR_ROUTINE(remove, remove, _wremove) #define _trename NUX_TCHAR_ROUTINE(rename, rename, _wrename) #define _trmdir NUX_TCHAR_ROUTINE(rmdir, _rmdir, _wrmdir) #define _tsearchenv NUX_TCHAR_ROUTINE(_searchenv, _searchenv, _wsearchenv) #define _tscanf NUX_TCHAR_ROUTINE(scanf, scanf, wscanf) #define _tsetlocale NUX_TCHAR_ROUTINE(setlocale, setlocale, _wsetlocale) #define _tsopen NUX_TCHAR_ROUTINE(_sopen, _sopen, _wsopen) #define _tspawnl NUX_TCHAR_ROUTINE(_spawnl, _spawnl, _wspawnl) #define _tspawnle NUX_TCHAR_ROUTINE(_spawnle, _spawnle, _wspawnle) #define _tspawnlp NUX_TCHAR_ROUTINE(_spawnlp, _spawnlp, _wspawnlp) #define _tspawnlpe NUX_TCHAR_ROUTINE(_spawnlpe, _spawnlpe, _wspawnlpe) #define _tspawnv NUX_TCHAR_ROUTINE(_spawnv, _spawnv, _wspawnv) #define _tspawnve NUX_TCHAR_ROUTINE(_spawnve, _spawnve, _wspawnve) #define _tspawnvp NUX_TCHAR_ROUTINE(_spawnvp, _spawnvp, _tspawnvp) #define _tspawnvpe NUX_TCHAR_ROUTINE(_spawnvpe, _spawnvpe, _tspawnvpe) #define _tsplitpath NUX_TCHAR_ROUTINE(_splitpath, _splitpath, _wsplitpath) #define _tstat NUX_TCHAR_ROUTINE(_stat, _stat, _wstat) #define _tstrdate NUX_TCHAR_ROUTINE(_strdate, _strdate, _wstrdate) #define _tstrtime NUX_TCHAR_ROUTINE(_strtime, _strtime, _wstrtime) #define _tsystem NUX_TCHAR_ROUTINE(system, system, _wsystem) #define _ttempnam NUX_TCHAR_ROUTINE(tempnam, _tempnam, _wtempnam) #define _ttmpnam NUX_TCHAR_ROUTINE(tmpnam, tmpnam, _wtmpnam) #define _ttoi NUX_TCHAR_ROUTINE(atoi, atoi, _wtoi) #define _ttol NUX_TCHAR_ROUTINE(atol, atol, _wtol) #define _tutime NUX_TCHAR_ROUTINE(utime, _utime, _wutime) #define _tWinMain NUX_TCHAR_ROUTINE(WinMain, WinMain, wWinMain) #define _ultot NUX_TCHAR_ROUTINE(_ultoa, _ultoa, _ultow) #define _ungettc NUX_TCHAR_ROUTINE(ungetc, ungetc, ungetwc) #define _vftprintf NUX_TCHAR_ROUTINE(vfprintf, vfprintf, vfwprintf) #define _vsntprintf NUX_TCHAR_ROUTINE(vsnprintf, _vsnprintf, _vsnwprintf) #define _vstprintf NUX_TCHAR_ROUTINE(vsprintf, vsprintf, vswprintf) #define _vtprintf NUX_TCHAR_ROUTINE(vprintf, vprintf, vwprintf) #define _TEOF NUX_TCHAR_ROUTINE(EOF, EOF, WEOF) #endif // SYSTEMGNU_H nux-4.0.8+16.04.20160209/NuxCore/InitiallyUnownedObject.h0000644000015600001650000000233512656236757023110 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Neil Jagdish Patel * */ #include "Object.h" #ifndef NUXINITIALLYUNOWNEDOBJECT_H #define NUXINITIALLYUNOWNEDOBJECT_H namespace nux { //! The base class of Nux initially unowned objects. class InitiallyUnownedObject: public Object { public: NUX_DECLARE_OBJECT_TYPE (InitiallyUnownedObject, Object); //! Constructor InitiallyUnownedObject (NUX_FILE_LINE_PROTO); ~InitiallyUnownedObject (); }; } #endif // NUXINITIALLYUNOWNEDOBJECT_H nux-4.0.8+16.04.20160209/NuxCore/EasingCurve.cpp0000644000015600001650000001011412656236757021223 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #include "NuxCore.h" #include "EasingCurve.h" namespace na = nux::animation; namespace { // These easing curves are an attempt to match the Qt curves // defined here: // http://doc.qt.nokia.com/4.7-snapshot/qeasingcurve.html double linear(double progress) { return progress; } double in_quad(double progress) { return progress * progress; } double reverse(double progress, na::EasingCurve::EasingFunction func) { // invert progress, and pass to ease_in progress = 1 - progress; return 1 - func(progress); } double in_out(double progress, na::EasingCurve::EasingFunction func) { if (progress > 0.5) { double out_progress = 1 - (progress - 0.5) * 2; return 1 - (func(out_progress) / 2); } else { double in_progress = progress * 2; return func(in_progress) / 2; } } double out_quad(double progress) { return reverse(progress, in_quad); } double in_out_quad(double progress) { return in_out(progress, in_quad); } double back_ease_in(double progress) { // (s+1)*t^3 - s*t^2 const double overshoot = 1.70158; return (((overshoot + 1) * progress * progress * progress) - (overshoot * progress * progress)); } double back_ease_out(double progress) { return reverse(progress, back_ease_in); } double back_ease_in_out(double progress) { return in_out(progress, back_ease_in); } double bounce_in(double progress) { if (progress < (1 / 2.75)) { return 7.5625 * progress * progress; } else if (progress < (2 / 2.75)) { progress -= (1.5 / 2.75); return 7.5625 * progress * progress + 0.75; } else if (progress < (2.5 / 2.75) ) { progress -= (2.25 / 2.75); return 7.5625 * progress * progress + 0.9375; } else { progress -= (2.625 / 2.75); return 7.5625 * progress * progress + 0.984375; } } double bounce_out(double progress) { return reverse(progress, bounce_in); } double bounce_in_out(double progress) { return in_out(progress, bounce_out); } double expo_ease_in(double progress) { return (progress == 0) ? 0.0 : 1.0 * std::pow (2, 10 * (progress / 1.0 - 1) ) + 0.0; } double expo_ease_out(double progress) { return reverse(progress, expo_ease_in); } na::EasingCurve::EasingFunction GetEasingFunction(na::EasingCurve::Type type) { switch (type) { case na::EasingCurve::Type::InQuad: return in_quad; case na::EasingCurve::Type::OutQuad: return out_quad; case na::EasingCurve::Type::InOutQuad: return in_out_quad; case na::EasingCurve::Type::BackEaseIn: return back_ease_in; case na::EasingCurve::Type::BackEaseOut: return back_ease_out; case na::EasingCurve::Type::BackEaseInOut: return back_ease_in_out; case na::EasingCurve::Type::BounceIn: return bounce_in; case na::EasingCurve::Type::BounceOut: return bounce_out; case na::EasingCurve::Type::BounceInOut: return bounce_in_out; case na::EasingCurve::Type::ExpoEaseIn: return expo_ease_in; case na::EasingCurve::Type::ExpoEaseOut: return expo_ease_out; case na::EasingCurve::Type::Linear: default: return linear; } } } na::EasingCurve::EasingCurve(Type type) : func_(GetEasingFunction(type)) {} double na::EasingCurve::ValueForProgress(double progress) { if (progress <= 0) return 0; if (progress >= 1) return 1; return func_(progress); } nux-4.0.8+16.04.20160209/NuxCore/Exception.h0000644000015600001650000000463612656236757020427 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef EXCEPTION_H #define EXCEPTION_H #include namespace nux { // ***************** // * * // * Exception * // * * // ***************** // // The exception handling classes from the STL do what we want, // so this is nothing more than a base class for any of our // derived exceptions. I have changed the constructor to take a // std::string object, but this gets converted before calling // std::exception. class Exception : public std::exception { public: Exception (std::string name) throw() : std::exception (), name_ (name) { } virtual ~Exception () throw () {} virtual const char *what () const throw() { return name_.c_str(); } protected: std::string name_; }; // ************************ // * * // * Derived Exceptions * // * * // ************************ class BoundsException : public Exception { public: BoundsException (std::string name = "") : Exception ("apBoundsException: " + name) { } }; class NotSupportedException : public Exception { public: NotSupportedException (std::string name = "") : Exception ("NotSupportedException: " + name) { } }; class DivisionByZeroException : public Exception { public: DivisionByZeroException (std::string name = "") : Exception ("DivisionByZeroException: " + name) { } }; class InvalidIndexException : public Exception { public: InvalidIndexException (std::string name = "") : Exception ("InvalidIndexException: " + name) { } }; } #endif // EXCEPTION_H nux-4.0.8+16.04.20160209/NuxCore/StringConversion.h0000644000015600001650000000156612656236757022004 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NSTRINGCONVERSION_H #define NSTRINGCONVERSION_H #endif // NSTRINGCONVERSION_H nux-4.0.8+16.04.20160209/NuxCore/FileName.cpp0000644000015600001650000001150512656236757020475 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "FileName.h" #include "Math/MathUtility.h" namespace nux { std::string NFileName::GetDrive() const { size_t Pos = find('\\', 0); return Pos != std::string::npos ? substr(0, Pos) : ""; } std::string NFileName::GetExtension() const { size_t Pos = rfind('.'); return Pos != std::string::npos ? substr(Pos + 1) : ""; } // Returns the base filename without the path std::string NFileName::GetCleanFilename() const { size_t bsPos = rfind('\\'); size_t sPos = rfind('/'); size_t Pos = std::string::npos; if (bsPos != std::string::npos && sPos != std::string::npos) { Pos = Max(bsPos, sPos); } else if (bsPos != std::string::npos) { Pos = bsPos; } else if (sPos != std::string::npos) { Pos = sPos; } return Pos != std::string::npos ? (const std::string)substr(Pos + 1) : *this; } std::string NFileName::GetFilenameNoExtension() const { size_t Pos = rfind('.'); if (Pos != std::string::npos && Pos != 0) { return substr(0, Pos); } return *this; } // Returns the base filename without the path and without the extension std::string NFileName::GetBaseFilename() const { std::string Wk = GetCleanFilename(); size_t Pos = Wk.rfind('.'); if (Pos != std::string::npos) { return Wk.substr(Pos); } return Wk; } // Returns the path in front of the filename std::string NFileName::GetDirectoryPath() const { size_t bsPos = rfind('\\'); size_t sPos = rfind('/'); size_t Pos = std::string::npos; if (bsPos != std::string::npos && sPos != std::string::npos) { Pos = Max(bsPos, sPos); } else if (bsPos != std::string::npos) { Pos = bsPos; } else if (sPos != std::string::npos) { Pos = sPos; } return Pos != std::string::npos ? substr(Pos) : "."; } void NFileName::ChangeFileExtension (const TCHAR *ext) { size_t Pos = rfind('.'); if (Pos != std::string::npos) { replace(begin() + Pos, end(), ext); } *this = *this + "." + ext; } void NFileName::ConvertSlashToBackslash() { size_t Pos = find('/'); while (Pos != std::string::npos) { replace(Pos, 1, 1, '\\'); } } void NFileName::ConvertBackslashToSlash() { size_t Pos = find('\\'); while (Pos != std::string::npos) { replace(Pos, 1, 1, '/'); } } void NFileName::AddSlashAtEnd() { if (!empty() && operator[](size() - 1) != '/') append("/"); } void NFileName::AddBackSlashAtEnd() { if (!empty() && operator[](size() - 1) != '\\') *this += '\\'; } void NFileName::AddSlashAtStart() { if (!empty() && operator[](0) != '/') insert(0, 1, '/'); } void NFileName::AddBackSlashAtStart() { if (!empty() && operator[](0) != '\\') insert(0, 1, '\\'); } void NFileName::RemoveSlashAtEnd() { if (!empty() && operator[](size() - 1) == '/') { erase(end() - 1); } } void NFileName::RemoveBackSlashAtEnd() { if (!empty() && operator[](size() - 1) == '\\') { erase(end() - 1); } } void NFileName::RemoveSlashAtStart() { if (!empty() && operator[](0) == '/') { erase(0, 1); } } void NFileName::RemoveBackSlashAtStart() { if (!empty() && operator[](0) == '\\') { erase(0, 1); } } void NFileName::ConvertToCleanSlash() { ConvertBackslashToSlash(); size_t count = size(); for (size_t i = 0; i < count; ) { if ( (i < count - 1) && (operator[] (i) == '/' ) && (operator[] (i + 1) == ('/') ) ) { erase (i + 1, 1); --count; } else { i++; } } } void NFileName::ConvertToCleanBackslash() { ConvertSlashToBackslash(); size_t count = size(); for (size_t i = 0; i < count; ) { if ( (i < count - 1) && (operator[] (i) == '\\' ) && (operator[] (i + 1) == '\\' ) ) { erase (i + 1, 1); } else { i++; } } } } nux-4.0.8+16.04.20160209/NuxCore/ThreadWin.h0000644000015600001650000003451212656236757020352 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef THREADWIN_H #define THREADWIN_H #include "ObjectType.h" namespace nux { class NThreadSafeCounter { public: NThreadSafeCounter() { m_Counter = 0; } NThreadSafeCounter (long i) { m_Counter = i; } long Increment(); long Decrement(); long Set (long i); long GetValue() const; long operator ++ (); long operator -- (); bool operator == (long i); private: long m_Counter; }; class NCriticalSection { public: //! Initialize critical section. /*! Initialize critical section. */ NCriticalSection() { InitializeCriticalSection (&m_lock); } //! Destroy critical section. /*! Destroy critical section. */ ~NCriticalSection() { DeleteCriticalSection (&m_lock); } //! Enter critical section. /*! Enter critical section. This function is made const so it can be used without restriction. For that matter, m_lock is made mutable. */ void Lock() const { EnterCriticalSection (&m_lock); } //! Leave critical section. /*! Leave critical section. This function is made const so it can be used without restriction. For that matter, m_lock is made mutable. */ void Unlock() const { LeaveCriticalSection (&m_lock); } private: //! Prohibit copy constructor. /*! Prohibit copy constructor. */ NCriticalSection (const NCriticalSection &); //! Prohibit assignment operator. /*! Prohibit assignment operator. */ NCriticalSection &operator= (const NCriticalSection &); mutable CRITICAL_SECTION m_lock; }; //! Scope Lock class /*! Takes a critical section object as parameter of the constructor. The constructor locks the critical section. The destructor unlocks the critical section. */ class NScopeLock { public: //! The constructor locks the critical section object. /*! The constructor locks the critical section object. @param LockObject Critical section object. */ NScopeLock (NCriticalSection *CriticalSectionObject) : m_CriticalSectionObject (CriticalSectionObject) { nuxAssert (m_CriticalSectionObject); m_CriticalSectionObject->Lock(); } //! The destructor unlocks the critical section object. /*! The destructor unlocks the critical section object. */ ~NScopeLock (void) { nuxAssert (m_CriticalSectionObject); m_CriticalSectionObject->Unlock(); } private: //! Prohibit default constructor. /*! Prohibit default constructor. */ NScopeLock (void); //! Prohibit copy constructor. /*! Prohibit copy constructor. */ NScopeLock (const NScopeLock &ScopeLockObject); //! Prohibit assignment operator. /*! Prohibit assignment operator. */ NScopeLock &operator= (const NScopeLock &ScopeLockObject) { return *this; } //! Critical section Object. /*! Critical section Object. */ NCriticalSection *m_CriticalSectionObject; }; class NThreadLocalStorage { public: enum { NbTLS = 128, InvalidTLS = 0xFFFFFFFF }; typedef void (*TLS_ShutdownCallback) (); static BOOL m_TLSUsed[NbTLS]; static unsigned int m_TLSIndex[NbTLS]; static TLS_ShutdownCallback m_TLSCallbacks[NbTLS]; static void Initialize(); static void Shutdown(); static BOOL RegisterTLS (unsigned int index, TLS_ShutdownCallback shutdownCallback); static void ThreadInit(); static void ThreadShutdown(); public: template static inline T GetData (unsigned int index) { nuxAssert (sizeof (T) <= sizeof (size_t) ); nuxAssert (index < NbTLS); nuxAssert (m_TLSUsed[index]); // T and (unsigned long) can be of different sizes // but this limits the use of GetData to classes without copy constructors union { T t; void *v; } temp; temp.v = TlsGetValue (m_TLSIndex[index]); return temp.t; } template static inline void SetData (unsigned int index, T value) { nuxAssert (sizeof (T) <= sizeof (size_t) ); nuxAssert (index < NbTLS); nuxAssert (m_TLSUsed[index]); // T and (unsigned long) can be of different sizes // but this limits the use of GetData to classes without copy constructors union { T t; void *v; } temp; temp.t = value; BOOL b = TlsSetValue (m_TLSIndex[index], temp.v); nuxAssertMsg (b, TEXT ("[NThreadLocalStorage::SetData] TlsSetValue returned FALSE.") ); } }; #define inlDeclareThreadLocalStorage(type, index, name) \ struct ThreadLocalStorageDef##name { enum Const { Index = index}; };\ inline type GetTLS_##name() { return nux::NThreadLocalStorage::GetData(ThreadLocalStorageDef##name::Index); }\ inline void SetTLS_##name(type value) { nux::NThreadLocalStorage::SetData(ThreadLocalStorageDef##name::Index, value); } #define inlRegisterThreadLocalIndex(index, name, shutdownCallback) \ nuxVerifyExpr(index == ThreadLocalStorageDef##name::Index); \ nuxVerifyExpr(nux::NThreadLocalStorage::RegisterTLS(index, shutdownCallback)) #define inlGetThreadLocalStorage(name) GetTLS_##name() #define inlSetThreadLocalStorage(name, value) SetTLS_##name(value) #ifdef POP_CHECK_THREADS #define nuxAssertInsideThread(threadtype) nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype) #define nuxAssertInsideThread2(threadtype1, threadtype2) nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype1 || popGetThreadLocalData(ThreadType) == threadtype2) #define nuxAssertNotInsideThread(threadtype) nuxAssert( inlGetThreadLocalStorage(ThreadType) != threadtype) #else #define nuxAssertInsideThread(threadtype) ((void) 0) #define nuxAssertInsideThread2(threadtype1, threadtype2) ((void) 0) #define nuxAssertNotInsideThread(threadtype) ((void) 0) #endif void SetWin32ThreadName (DWORD dwThreadID, LPCSTR szThreadName); enum ThreadState { THREADINIT, THREADRUNNING, THREADSUSPENDED, THREADSTOP, THREAD_START_ERROR, THREAD_STOP_ERROR, THREAD_SUSPEND_ERROR, THREAD_RESUME_ERROR, }; enum ThreadWaitTimeout { THREAD_WAIT_TIMEOUT_NONE = 0, THREAD_WAIT_TIMEOUT_FOREVER = INFINITE, }; enum ThreadWaitResult { THREAD_WAIT_RESULT_COMPLETED = 0, THREAD_WAIT_RESULT_ABANDONED = 1, THREAD_WAIT_RESULT_TIMEOUT = 2, THREAD_WAIT_RESULT_FAILED = 3, }; // http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c3793/ class NThread { NUX_DECLARE_ROOT_OBJECT_TYPE (NThread); public: /*! Info: Default Constructor */ NThread(); /*! Info: Plug Constructor Use this to migrate/port existing worker threads to objects immediately Although you lose the benefits of ThreadCTOR and ThreadDTOR. */ NThread (LPTHREAD_START_ROUTINE lpExternalRoutine); /*! Info: Default Destructor I think it is wise to destroy the thread even if it is running, when the main thread reaches here. */ virtual ~NThread(); /*! Info: Starts the thread. This function starts the thread pointed by m_pThreadFunc with default attributes */ virtual ThreadState Start ( void *arg = NULL ); /*! Info: Stops the thread. This function stops the current thread. We can force kill a thread which results in a TerminateThread. */ virtual ThreadState Stop ( bool bForceKill = false ); ThreadState Suspend(); ThreadState Resume(); ThreadState ResumeStart(); ThreadState ResumeExit(); /*! Info: Starts the thread. This function starts the thread pointed by m_pThreadFunc with default attributes */ unsigned int GetExitCode() const; /*! Info: Attaches a Thread Function Used primarily for porting but can serve in developing generic thread objects */ void Attach ( LPTHREAD_START_ROUTINE lpThreadFunc ) { m_pThreadFunc = lpThreadFunc; } /*! Info: Detaches the Attached Thread Function Detaches the Attached Thread Function, If any. by resetting the thread function pointer to EntryPoint1 */ void Detach ( void ) { m_pThreadFunc = NThread::EntryPoint; } HANDLE GetThreadHandle(); unsigned int GetThreadId(); ThreadState GetThreadState() const; void SetThreadState (ThreadState state); void SetThreadName (const TCHAR *ThreadName); const std::string& GetThreadName() const; /*! Wait for a thread to complete. The second parameters to this call specifies a how long to wait for the thread to complete. The following options are available: ThreadWaitTimeout::THREAD_WAIT_TIMEOUT_NONE: The function returns immediately if the thread exits. ThreadWaitTimeout::THREAD_WAIT_TIMEOUT_FOREVER: The function waits until the thread exits. @param thread Pointer to a valid NThread. @param milliseconds Time to wait for the thread to complete. */ static ThreadWaitResult JoinThread(NThread *thread, unsigned int milliseconds); protected: std::string m_ThreadName; volatile ThreadState m_ThreadState; /*! Info: DONT override this method. This function is like a standard template. Override if you are sure of what you are doing. In C++ the entry function of a thread cannot be a normal member function of a class. However, it can be a static member function of a class. This is what we will use as the entry point. There is a gotcha here though. Static member functions do not have access to the this pointer of a C++ object. They can only access static data. Fortunately, there is way to do it. Thread entry point functions take a void * as a parameter so that the caller can typecast any data and pass in to the thread. We will use this to pass this to the static function. The static function will then typecast the void * and use it to call a non static member function */ static DWORD WINAPI EntryPoint (void *pArg); /*! Info: Override this method. This function should contain the body/code of your thread. Notice the signature is similar to that of any worker thread function except for the calling convention. */ virtual int Run (void* /* arg */ ) { return m_ThreadCtx.m_dwExitCode; } /*! Info: Constructor-like function. Will be called by EntryPoint before executing the thread body. Override this function to provide your extra initialization. NOTE: do not confuse it with the classes constructor @return TRUE if the thread can continue running the program. If FALSE is returned, the thread won't execute the main body Run() and will exit without calling ThreadDtor. */ virtual bool ThreadCtor() { return true; } /*! Info: Destructor-like function. Will be called by EntryPoint after executing the thread body. Override this function to provide your extra destruction. NOTE: do not confuse it with the classes constructor @return TRUE if this function executed without problems. */ virtual bool ThreadDtor() { return true; } private: /*! Info: Thread Context Inner Class Every thread object needs to be associated with a set of values. like UserData Pointer, Handle, Thread ID etc. NOTE: This class can be enhanced to varying functionalities eg., * Members to hold StackSize * SECURITY_ATTRIBUTES member. */ class NThreadContext { public: NThreadContext() { memset (this, 0, sizeof (this) ); } /* * Attributes Section */ public: HANDLE m_hThread; //!< The Thread Handle. volatile unsigned int m_dwTID; //!< The Thread ID. void *m_pUserData; //!< The user data pointer. void *m_pParent; //!< The this pointer of the parent NThread object. unsigned int m_dwExitCode; //!< The Exit Code of the thread. }; /*! Attributes Section */ protected: /*! Info: Members of NThread */ NThreadContext m_ThreadCtx; // The Thread Context member LPTHREAD_START_ROUTINE m_pThreadFunc; // The Worker Thread Function Pointer }; // USAGE: // DWORD WINAPI Threaded(void* lpData); // // class CDemoThread : public CThread // { // virtual unsigned int Run( void* /* arg */ ) // { // for(;;) // { // printf("Threaded Object Code \n"); // Sleep(1000); // } // } // }; // // void main( void ) // { // CDemoThread dmt; // dmt.Start(NULL); // SleepEx(15 * 1000, FALSE); // dmt.Stop(true); // // // A Sample Code for porting existent code of Threaded function // CThread t1(Threaded), t2; // t2.Attach(Threaded); // t1.Start(); // t2.Start(); // SleepEx(15 * 1000, FALSE); // t2.Stop(); // t1.Stop(); // } // // DWORD WINAPI Threaded( void* /* lpData */ ) // { // for(;;) // { // printf("worker threaded code"); // Sleep(1000); // } // } } #endif // THREADWIN_H nux-4.0.8+16.04.20160209/NuxCore/Parsing.cpp0000644000015600001650000002315612656236757020425 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Parsing.h" #define CHAR_TAB TEXT('\t') #define CHAR_CR TEXT('\r') #define CHAR_FF TEXT('\f') #define CHAR_NEW_LINE TEXT('\n') #define CHAR_QUOTE TEXT('\"') namespace nux { bool ParseCommand (const TCHAR **Stream, const TCHAR *Match) { while ( (**Stream == TEXT (' ') ) || (**Stream == CHAR_TAB) ) (*Stream) ++; if (TCharStringNICompare (*Stream, Match, StringLength (Match) ) == 0) { *Stream += StringLength (Match); if (!IsAlphanumericChar (**Stream) ) { while ( (**Stream == TEXT (' ') ) || (**Stream == CHAR_TAB) ) (*Stream) ++; return true; // Success. } else { *Stream -= StringLength (Match); return false; // Only found partial match. } } else return false; // No match. } bool Parse_tchar (const TCHAR *Stream, const TCHAR *Match, TCHAR *Value, int Size, int MaxLen) { const TCHAR *Found = Strfind (Stream, Match); if (Found) { const TCHAR *Start; Start = Found + StringLength (Match); if (*Start == '\x22') // Character '"' { // The value begins with the quotation mark character: ". We skip it. Strncpy (Value, Size, Start + 1, MaxLen); Value[MaxLen - 1] = 0; TCHAR *Temp = Strstr (Value, TEXT ("\x22") ); if (Temp != NULL) { // We read in the termination quotation mark. Set it t0 0 to null terminate the Value buffer. *Temp = 0; } } else { // Non-quoted string without spaces. Strncpy (Value, Size, Start, MaxLen); Value[MaxLen - 1] = 0; TCHAR *Temp; Temp = Strstr (Value, TEXT (" ") ); if (Temp) *Temp = 0; Temp = Strstr (Value, TEXT ("\r") ); if (Temp) *Temp = 0; Temp = Strstr (Value, TEXT ("\n") ); if (Temp) *Temp = 0; Temp = Strstr (Value, TEXT ("\t") ); if (Temp) *Temp = 0; Temp = Strstr (Value, TEXT (",") ); if (Temp) *Temp = 0; } return true; } else return false; } bool ParseParam (const TCHAR *Stream, const TCHAR *Param) { const TCHAR *Start = Stream; if (*Stream) { while ( (Start = Strfind (Start + 1, Param) ) != NULL) { if (Start > Stream && ( (Start[-1] == TEXT ('-') ) || (Start[-1] == TEXT ('/') ) ) ) { const TCHAR *End = Start + StringLength (Param); if (End == NULL || *End == 0 || IsWhitespaceChar (*End) ) return true; } } } return false; } bool Parse_string (const TCHAR *Stream, const TCHAR *Match, std::string &Value) { TCHAR Temp[4096] = TEXT (""); if (Parse_tchar (Stream, Match, Temp, NUX_ARRAY_COUNT (Temp), NUX_ARRAY_COUNT (Temp) ) ) { Value = Temp; return true; } else return false; } bool Parse_u64 (const TCHAR *Stream, const TCHAR *Match, QWORD &Value) { return Parse_s64 (Stream, Match, * (SQWORD *) &Value); } bool Parse_s64 (const TCHAR *Stream, const TCHAR *Match, SQWORD &Value) { TCHAR Temp[4096] = TEXT (""), *Ptr = Temp; if (Parse_tchar (Stream, Match, Temp, NUX_ARRAY_COUNT (Temp), NUX_ARRAY_COUNT (Temp) ) ) { Value = 0; bool Negative = (*Ptr == TEXT ('-') ); Ptr += Negative; while ( (*Ptr >= TEXT ('0') ) && (*Ptr <= TEXT ('9') ) ) Value = Value * 10 + *Ptr++ - TEXT ('0'); if (Negative) Value = -Value; return true; } else return false; } bool Parse_u32 (const TCHAR *Stream, const TCHAR *Match, DWORD &Value) { const TCHAR *Temp = Strfind (Stream, Match); TCHAR *End; if (Temp == NULL) return false; Value = Strtoi (Temp + StringLength (Match), &End, 10); return true; } bool Parse_u8 (const TCHAR *Stream, const TCHAR *Match, BYTE &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Temp += StringLength (Match); Value = (BYTE) CharToInteger (Temp); return (Value != 0) || IsDigitChar (Temp[0]); } bool Parse_s8 (const TCHAR *Stream, const TCHAR *Match, SBYTE &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Temp += StringLength (Match); Value = CharToInteger (Temp); return Value != 0 || IsDigitChar (Temp[0]); } bool Parse_u16 (const TCHAR *Stream, const TCHAR *Match, WORD &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Temp += StringLength (Match); Value = (unsigned short) CharToInteger (Temp); return Value != 0 || IsDigitChar (Temp[0]); } bool Parse_s16 (const TCHAR *Stream, const TCHAR *Match, SWORD &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Temp += StringLength (Match); Value = (short) CharToInteger (Temp); return Value != 0 || IsDigitChar (Temp[0]); } bool Parse_float (const TCHAR *Stream, const TCHAR *Match, float &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Value = CharToDouble (Temp + StringLength (Match) ); return true; } bool Parse_int (const TCHAR *Stream, const TCHAR *Match, int &Value) { const TCHAR *Temp = Strfind (Stream, Match); if (Temp == NULL) return false; Value = CharToInteger (Temp + StringLength (Match) ); return true; } bool Parse_bool (const TCHAR *Stream, const TCHAR *Match, bool &OnOff) { TCHAR TempStr[16]; if (Parse_tchar (Stream, Match, TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1) ) { OnOff = !Stricmp (TempStr, TEXT ("On") ) || !Stricmp (TempStr, TEXT ("True") ) || !Stricmp (TempStr, TEXT ("1") ); return true; } else return false; } void ParseToNextLine (const TCHAR **Stream, TCHAR CommentChar) { // Skip over spaces, tabs, cr's, and linefeeds. while (1) { while ( (**Stream == TEXT (' ') ) || (**Stream == CHAR_TAB) || (**Stream == CHAR_CR) || (**Stream == CHAR_NEW_LINE) || (**Stream == CHAR_FF) ) { // Skip tabs, cr, new line, form feed ++*Stream; } if (**Stream == CommentChar) { // Start of a comment while ( (**Stream != 0) && (**Stream != CHAR_NEW_LINE) && (**Stream != CHAR_CR) ) { // Advance to a new line ++*Stream; } } else { break; } } } bool ParseToken (const TCHAR *Str, TCHAR *TokenBuffer, int BufferSize) { int sz = 0; while ( (*Str == TEXT (' ') ) || (*Str == CHAR_TAB) ) { // Skip spaces and tabs. Str++; } if (*Str == CHAR_QUOTE) { // Get quoted string. Str++; while (*Str && (*Str != CHAR_QUOTE) && (sz + 1 < BufferSize) ) { TCHAR c = *Str++; if (sz + 1 < BufferSize) TokenBuffer[sz++] = c; } if (*Str == CHAR_QUOTE) Str++; } else { // Get unquoted string. for (; *Str && (*Str != TEXT (' ') ) && (*Str != CHAR_TAB); Str++) { if (sz + 1 < BufferSize) TokenBuffer[sz++] = *Str; } } TokenBuffer[sz] = 0; return sz != 0; } bool ParseToken (const TCHAR *Str, std::string &TokenString) { TokenString.clear(); // Skip spaces and tabs. while (IsWhitespaceChar (*Str) ) Str++; if (*Str == CHAR_QUOTE) { // Get quoted string. Str++; while (*Str && *Str != CHAR_QUOTE) { TCHAR c = *Str++; TokenString += c; } if (*Str == CHAR_QUOTE) Str++; } else { // Get unquoted string. for (; *Str && !IsWhitespaceChar (*Str); Str++) { TokenString += *Str; } } return TokenString.length() > 0; } std::string ParseToken (const TCHAR *Str, bool /* UseEscape */) { TCHAR Buffer[1024]; if (ParseToken (Str, Buffer, NUX_ARRAY_COUNT (Buffer) ) ) return Buffer; else return TEXT (""); } // // Get a line of Stream (everything up to, but not including, CR/LF. // Returns 0 if ok, nonzero if at end of stream and returned 0-length string. // bool ParseLine (const TCHAR **Stream, TCHAR *LineBuffer, int BufferSize) { TCHAR *tmp = LineBuffer; *tmp = 0; while ( (**Stream != 0) && (**Stream != CHAR_NEW_LINE) && (**Stream != CHAR_CR) && (**Stream != CHAR_FF) && (--BufferSize > 0) ) { * (tmp++) = * ( (*Stream) ++); } *tmp = 0; return LineBuffer[0] != 0; } bool ParseLine (const TCHAR **Stream, std::string &LineString) { LineString.clear(); while ( (**Stream != 0) && (**Stream != CHAR_NEW_LINE) && (**Stream != CHAR_CR) && (**Stream != CHAR_FF) ) { LineString += **Stream++; } return LineString.size() > 0; } } nux-4.0.8+16.04.20160209/NuxCore/Size-inl.h0000644000015600001650000000063212656236757020153 0ustar pbuserpbgroup00000000000000#ifndef NUX_CORE_SIZE_INL_H #define NUX_CORE_SIZE_INL_H namespace nux { inline Size::Size() : width(0), height(0) {} inline Size::Size(int w, int h) : width(w), height(h) {} inline bool operator == (const Size& lhs, const Size& rhs) { return (lhs.width == rhs.width) && (lhs.height == rhs.height); } inline bool operator != (const Size& lhs, const Size& rhs) { return !(lhs == rhs); } } #endif nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/0000755000015600001650000000000012656240224020474 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32CustomDialog.cpp0000644000015600001650000001420512656236757024555 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { static enum eFileDialogType { FILE_OPEN_DIALOG, FILE_SAVE_DIALOG, }; ColorDialogOption::ColorDialogOption() : m_ReturnColor (0, 0, 0, 0) { for (unsigned int i = 0; i < NUX_COLOR_DIALOG_CUSTOM_COLOR; i++) { m_CustomColors[i] = (COLORREF) (0xFFFFFF); } } ColorDialogOption::~ColorDialogOption() { } void ColorDialogOption::SetCustomColor (unsigned int index, unsigned int RGBColor) { nuxAssert (index < NUX_COLOR_DIALOG_CUSTOM_COLOR); m_CustomColors[index] = (COLORREF) RGBColor; } void ColorDialogOption::SetCustomColor (unsigned int index, BYTE R, BYTE G, BYTE B) { nuxAssert (index < NUX_COLOR_DIALOG_CUSTOM_COLOR); m_CustomColors[index] = (COLORREF) ((R<<16)|(G<<8)|B); } #define MAX_FILE_CHARACTERS 2*260 FileDialogOption::FileDialogOption() : NumFilters (0) , FormattedFilter (0) { DialogTitle = TEXT ("\0"); InitialDirectory = TEXT ("\0"); } FileDialogOption::~FileDialogOption() { } void FileDialogOption::AddFilter (const TCHAR *Description, const TCHAR *Filter) { nuxAssert (Description); nuxAssert (Filter); FilterDesc.push_back(std::string(Description)); Filters.push_back(std::string(Filter)); NumFilters++; } void FileDialogOption::RemoveFilter() { FilterDesc.clear(); Filters.clear(); NumFilters = 0; if (FormattedFilter) { delete [] FormattedFilter; FormattedFilter = 0; } } TCHAR *FileDialogOption::GetFormatedFilter() { size_t size = 0; for (unsigned int i = 0; i < NumFilters; i++) { size += FilterDesc[i].length() + Filters[i].length() + 2; // + 2 for for the NULL char at the end of each string } size += 1; // + 1 for the final NULL char. The total string is terminated by two NULL char if (FormattedFilter) delete [] FormattedFilter; FormattedFilter = new TCHAR[size]; size_t l = 0; for (unsigned int i = 0; i < NumFilters; i++) { Memcpy((void *) (FormattedFilter + l), FilterDesc[i].c_str(), FilterDesc[i].length()); l += FilterDesc[i].length(); FormattedFilter[l] = 0; l++; Memcpy ( (void *) (FormattedFilter + l), Filters[i].c_str(), Filters[i].length() ); l += Filters[i].length(); FormattedFilter[l] = 0; l++; } FormattedFilter[l] = 0; l++; nuxAssert (size == l); return FormattedFilter; } void FileDialogOption::SetDialogTitle (const TCHAR *Title) { DialogTitle = Title; } void FileDialogOption::SetInitialDirectory (const TCHAR *Directory) { InitialDirectory = Directory; } bool Win32ColorDialog (HWND hWnd, ColorDialogOption &cdo) { CHOOSECOLOR ColorOptions; Memset (&ColorOptions, 0, sizeof (CHOOSECOLOR) ); ColorOptions.lStructSize = sizeof (CHOOSECOLOR); ColorOptions.hwndOwner = hWnd; ColorOptions.hInstance = 0; ColorOptions.lpCustColors = cdo.m_CustomColors; ColorOptions.Flags = CC_ANYCOLOR | CC_FULLOPEN; if ( ChooseColor (&ColorOptions) ) { cdo.m_ReturnColor = Color (GetRValue (ColorOptions.rgbResult), GetGValue (ColorOptions.rgbResult), GetBValue (ColorOptions.rgbResult) ); return TRUE; }; return FALSE; } static bool _Win32FileDialog (HWND hWnd, eFileDialogType DialogType, FileDialogOption &fdo) { nuxAssert ( (DialogType == FILE_OPEN_DIALOG) || (DialogType == FILE_SAVE_DIALOG) ); OPENFILENAME SaveFileOption; TCHAR DrivePathFileName[MAX_FILE_CHARACTERS]; // buffer for OpenFileName.lpstrFile TCHAR FileName[MAX_FILE_CHARACTERS]; // buffer for OpenFileName.lpstrFileTitle DrivePathFileName[0] = 0; Memset (&SaveFileOption, 0, sizeof (OPENFILENAME) ); SaveFileOption.lStructSize = sizeof (OPENFILENAME); // (See remark at the end of this file!) SaveFileOption.hwndOwner = hWnd; SaveFileOption.lpstrFilter = fdo.GetFormatedFilter(); SaveFileOption.nFilterIndex = 0; // On return, this buffer contains the drive designator, path, file name, and extension of the selected file. SaveFileOption.lpstrFile = DrivePathFileName; SaveFileOption.nMaxFile = MAX_FILE_CHARACTERS; // On return, this buffer receives the file name and extension (without path information) of the selected file. SaveFileOption.lpstrFileTitle = FileName; SaveFileOption.nMaxFileTitle = MAX_FILE_CHARACTERS; SaveFileOption.lpstrInitialDir = fdo.GetInitialDirectory(); SaveFileOption.lpstrTitle = fdo.GetDialogTitle(); SaveFileOption.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR; SaveFileOption.lpstrDefExt = TEXT (""); if (DialogType == FILE_OPEN_DIALOG) { if (::GetOpenFileName (&SaveFileOption) ) { fdo.ReturnFileName = NFileName (SaveFileOption.lpstrFile); return TRUE; } } if (DialogType == FILE_SAVE_DIALOG) { if (::GetSaveFileName (&SaveFileOption) ) { fdo.ReturnFileName = NFileName (SaveFileOption.lpstrFile); return TRUE; } } unsigned int error = ::CommDlgExtendedError(); return FALSE; } bool Win32SaveFileDialog (HWND hWnd, FileDialogOption &fdo) { return (bool) _Win32FileDialog (hWnd, FILE_SAVE_DIALOG, fdo); } bool Win32OpenFileDialog (HWND hWnd, FileDialogOption &fdo) { return (bool) _Win32FileDialog (hWnd, FILE_OPEN_DIALOG, fdo); } } nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32Clipboard.cpp0000644000015600001650000001170012656236757024057 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NWin32Clipboard.h" namespace nux { void inlCopyTextToClipboard (const TCHAR *text) { // test to see if we can open the clipboard first before // wasting any cycles with the memory allocation if (::OpenClipboard (::GetActiveWindow() ) ) { // Empty the Clipboard. This also has the effect // of allowing Windows to free the memory associated // with any data that is in the Clipboard ::EmptyClipboard(); // Ok. We have the Clipboard locked and it's empty. // Now let's allocate the global memory for our data. // Here I'm simply using the GlobalAlloc function to // allocate a block of data equal to the text in the // "to clipboard" edit control plus one character for the // terminating null character required when sending // ANSI text to the Clipboard. HGLOBAL hClipboardData; hClipboardData = ::GlobalAlloc (GMEM_MOVEABLE, StringLength (text) + 1); // The actual size of the memory allocated can be larger than the requested size. // To determine the actual number of bytes allocated, use the GlobalSize or LocalSize function. // If the amount allocated is greater than the amount requested, the process can use the entire amount. unsigned int Size = ::GlobalSize (hClipboardData); // Calling GlobalLock returns to me a pointer to the // data associated with the handle returned from // GlobalAlloc TCHAR *pData; pData = (TCHAR *) ::GlobalLock (hClipboardData); // At this point, all I need to do is use the standard // C/C++ strcpy function to copy the data from the local // variable to the global memory. inlTCharStringCopy (pData, Size, text); // Once done, I unlock the memory - remember you // don't call GlobalFree because Windows will free the // memory automatically when EmptyClipboard is next // called. ::GlobalUnlock (hClipboardData); // Now, set the Clipboard data by specifying that // ANSI text is being used and passing the handle to // the global memory. #if UNICODE if (::SetClipboardData (CF_UNICODETEXT, hClipboardData) == NULL) { nuxError (TEXT ("SetClipboardData failed with error code %i"), ::GetLastError() ); } #else if (::SetClipboardData (CF_TEXT, hClipboardData) == NULL) { nuxError (TEXT ("SetClipboardData failed with error code %i"), ::GetLastError() ); } #endif // Finally, when finished I simply close the Clipboard // which has the effect of unlocking it so that other // applications can examine or modify its contents. ::CloseClipboard(); } } std::string inlReadTextToClipboard() { std::string ResultString; if (::OpenClipboard (::GetActiveWindow() ) ) { HGLOBAL GlobalMem = NULL; BOOL IsUnicodeText = 0; if ( (GlobalMem = GetClipboardData ( CF_UNICODETEXT )) ) { IsUnicodeText = 1; } else if ( (GlobalMem = GetClipboardData ( CF_TEXT )) ) { IsUnicodeText = 0; } if ( GlobalMem == 0) ResultString = TEXT (""); else { void *Data = ::GlobalLock ( GlobalMem ); nuxAssert ( Data ); if ( IsUnicodeText ) #if UNICODE ResultString = (TCHAR *) Data; #else ResultString = (ANSICHAR *) UNICHAR_TO_ANSICHAR (Data); #endif else { #if UNICODE ResultString = (UNICHAR *) ANSICHAR_TO_UNICHAR (Data); #else ResultString = (TCHAR *) Data; #endif // ANSICHAR* AnsiChar = (ANSICHAR*) Data; // INT i; // // This for loop count the number of characters in ACh. // for( i=0; AnsiChar[i]; i++ ); // // INT n = i+1; // TCHAR* CharArray = new TCHAR[n]; // for( i=0; i < n; i++ ) // CharArray[i]=FromAnsi(AnsiChar[i]); // ResultString = CharArray; // delete [] CharArray; } ::GlobalUnlock ( GlobalMem ); } nuxAssert (::CloseClipboard() ); } else ResultString = TEXT (""); return ResultString; } } nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32MessageBox.cpp0000644000015600001650000001400712656236757024220 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NWin32MessageBox.h" namespace nux { // // Get system error. // const TCHAR *inlGetSystemErrorMessage ( unsigned int Error ) { static TCHAR Msg[1024]; *Msg = 0; if ( Error == 0 ) Error = GetLastError(); #if UNICODE ANSICHAR ACh[1024]; FormatMessageA ( FORMAT_MESSAGE_FROM_SYSTEM, NULL, Error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), ACh, 1024, NULL ); _TCSCPY_S ( Msg, 1024, ANSI_TO_TCHAR (ACh) ); #else FormatMessage ( FORMAT_MESSAGE_FROM_SYSTEM, NULL, Error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), Msg, 1024, NULL ); #endif if (Strchr (Msg, TEXT ('\r') ) ) *Strchr (Msg, TEXT ('\r') ) = 0; if (Strchr (Msg, TEXT ('\n') ) ) *Strchr (Msg, TEXT ('\n') ) = 0; return Msg; } void inlOKMessageBox ( const TCHAR *Title, const TCHAR *Fmt, ... ) { TCHAR TempStr[4096] = TEXT (""); GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Fmt ); if (GNoDialog == TRUE) { nuxDebugMsg (TempStr); } else { MessageBox (NULL, TempStr, Title, MB_OK | MB_SYSTEMMODAL); } } void inlGetLastErrorMessageBox() { TCHAR TempStr[4096] = TEXT (""); Snprintf ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, TEXT ("GetLastError : %d\n\n%s"), GetLastError(), inlGetSystemErrorMessage() ); if ( GNoDialog == TRUE ) { nuxError (TempStr); } else { MessageBox ( NULL, TempStr, TEXT ("System Error"), MB_OK | MB_SYSTEMMODAL ); } } //#define VARARG_BODY( FuncRet, FuncName, FmtType, ExtraParamDecl ) VARARG_BODY (unsigned int, inlWin32MessageBox, const TCHAR *, VARARG_EXTRA (HWND OwnerWindowHandle) VARARG_EXTRA (const TCHAR *Caption) VARARG_EXTRA (MessageBoxType Type) VARARG_EXTRA (MessageBoxIcon Icon) VARARG_EXTRA (MessageBoxModal Modal) ) //BOOL inlWin32MessageBox(HWND OwnerWindowHandle, const TCHAR* Caption, const TCHAR* Message, MessageBoxType Type, unsigned int Modal) { // TCHAR TempStr[4096]=TEXT(""); // GET_VARARGS( TempStr, NUX_ARRAY_COUNT(TempStr), Fmt, Fmt ); TCHAR TempStr[4096] = TEXT (""); GET_VARARGS ( TempStr, NUX_ARRAY_COUNT (TempStr), NUX_ARRAY_COUNT (TempStr) - 1, Fmt); if (GNoDialog == TRUE) { nuxDebugMsg (TempStr); return 0; } else { unsigned int Win32Modal = 0; switch (Modal) { case MBMODAL_ApplicationModal: Win32Modal = MB_APPLMODAL; break; case MBMODAL_SystemModal: Win32Modal = MBMODAL_SystemModal; break; case MBMODAL_TaskModal: Win32Modal = MBMODAL_TaskModal; break; default: Win32Modal = MB_APPLMODAL; break; } unsigned int Win32Icon = 0; switch (Icon) { case MBICON_Exclamation: Win32Icon = MB_ICONEXCLAMATION; break; case MBICON_Warning: Win32Icon = MB_ICONWARNING; break; case MBICON_Information: Win32Icon = MB_ICONINFORMATION; break; case MBICON_Asterix: Win32Icon = MB_ICONASTERISK; break; case MBICON_Question: Win32Icon = MB_ICONQUESTION; break; case MBICON_Stop: Win32Icon = MB_ICONSTOP; break; case MBICON_Error: Win32Icon = MB_ICONERROR; break; case MBICON_Hand: Win32Icon = MB_ICONHAND; break; default: Win32Icon = MB_ICONINFORMATION; break; } int Result = 0; switch (Type) { case MBTYPE_Ok: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_OK | Win32Modal | Win32Icon); return (Result == IDOK) ? MBRES_Ok : 0; break; case MBTYPE_YesNo: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_YESNO | Win32Modal | Win32Icon); return (Result == IDYES) ? MBRES_Yes : MBRES_No; break; case MBTYPE_OkCancel: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_OKCANCEL | Win32Modal | Win32Icon); return (Result == IDOK) ? MBRES_Ok : MBRES_Cancel; break; case MBTYPE_YesNoCancel: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_YESNOCANCEL | Win32Modal | Win32Icon); return (Result == IDYES) ? MBRES_Yes : (Result == IDNO ? MBRES_No : MBRES_Cancel); break; case MBTYPE_CancelTryContinue: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_CANCELTRYCONTINUE | Win32Modal | Win32Icon); return (Result == IDCANCEL) ? MBRES_Cancel : (Result == IDTRYAGAIN ? MBRES_TryAgain : MBRES_Continue); break; case MBTYPE_AbortRetryIgnore: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_ABORTRETRYIGNORE | Win32Modal | Win32Icon); return (Result == IDABORT) ? MBRES_Abort : (Result == IDRETRY ? MBRES_Retry : MBRES_Ignore); break; default: Result = MessageBox ( (HWND) OwnerWindowHandle, TempStr, Caption, MB_OK | Win32Modal | Win32Icon); return (Result == IDOK) ? MBRES_Ok : 0; break; } } return 0; } } nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32MessageBox.h0000644000015600001650000000470112656236757023665 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NWIN32MESSAGEBOX_H #define NWIN32MESSAGEBOX_H namespace nux { // Returns the last system error code in string form. NOTE: Only one return value is valid at a time! const TCHAR *inlGetSystemErrorMessage ( unsigned int Error = 0 ); void inlGetLastErrorMessageBox(); void inlOKMessageBox ( const TCHAR *Title, const TCHAR *Fmt, ... ); // Message Box dialog type enum MessageBoxType { MBTYPE_Ok, MBTYPE_YesNo, MBTYPE_OkCancel, MBTYPE_YesNoCancel, MBTYPE_CancelTryContinue, MBTYPE_AbortRetryIgnore, MBTYPE_FORCE_DWORD = 0x7fffffff }; enum MessageBoxIcon { MBICON_Exclamation, MBICON_Warning, MBICON_Information, MBICON_Asterix, MBICON_Question, MBICON_Stop, MBICON_Error, MBICON_Hand, MBICON_FORCE_DWORD = 0x7fffffff }; enum MessageBoxModal { MBMODAL_ApplicationModal, MBMODAL_SystemModal, MBMODAL_TaskModal, MBMODAL_FORCE_DWORD = 0x7fffffff }; enum MessageBoxResult { MBRES_Ok = 1, MBRES_Cancel, MBRES_Abort, MBRES_Retry, MBRES_Ignore, MBRES_Yes, MBRES_No, MBRES_Close, MBRES_Help, MBRES_TryAgain, MBRES_Continue, MBRES_FORCE_DWORD = 0x7fffffff }; VARARG_DECL (unsigned int, static BOOL, return, inlWin32MessageBox, VARARG_NONE, const TCHAR *, VARARG_EXTRA (HWND OwnerWindowHandle) VARARG_EXTRA (const TCHAR *Caption) VARARG_EXTRA (MessageBoxType Type) VARARG_EXTRA (MessageBoxIcon Icon) VARARG_EXTRA (MessageBoxModal Modal), VARARG_EXTRA (OwnerWindowHandle) VARARG_EXTRA (Caption) VARARG_EXTRA (Type) VARARG_EXTRA (Icon) VARARG_EXTRA (Modal) ); } #endif // NWIN32MESSAGEBOX_H nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32Clipboard.h0000644000015600001650000000173612656236757023534 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NWIN32CLIPBOARD_H #define NWIN32CLIPBOARD_H namespace nux { void inlCopyTextToClipboard (const TCHAR *text); std::string inlReadTextToClipboard(); } #endif // NWIN32CLIPBOARD_H nux-4.0.8+16.04.20160209/NuxCore/Win32Dialogs/NWin32CustomDialog.h0000644000015600001650000000511712656236757024224 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NWIN32CUSTOMDIALOG_H #define NWIN32CUSTOMDIALOG_H #define NUX_COLOR_DIALOG_CUSTOM_COLOR 16 namespace nux { class FileDialogOption { public: FileDialogOption(); ~FileDialogOption(); void AddFilter (const TCHAR *Description, const TCHAR *Filter); TCHAR *GetFormatedFilter(); void RemoveFilter(); void SetDialogTitle (const TCHAR *Title); const TCHAR *GetDialogTitle() { return DialogTitle.c_str(); } void SetInitialDirectory (const TCHAR *Directory); const TCHAR *GetInitialDirectory() { return InitialDirectory.c_str(); } public: NFileName ReturnFileName; std::vector FilterDesc; std::vector Filters; TCHAR *FormattedFilter; unsigned int FilterLength; unsigned int NumFilters; std::string DialogTitle; std::string InitialDirectory; }; class ColorDialogOption { public: ColorDialogOption(); ~ColorDialogOption(); void SetCustomColor (unsigned int index, unsigned int RGBColor); void SetCustomColor (unsigned int index, BYTE R, BYTE G, BYTE B); public: COLORREF m_CustomColors[NUX_COLOR_DIALOG_CUSTOM_COLOR]; Color m_ReturnColor; }; bool Win32ColorDialog (HWND hWnd, ColorDialogOption &cdo); //! Open Win32 file Dialog /*! Open Win32 file Dialog Adding filter options FileDialogOption fdo; fdo.AddFilter(TEXT("All Files (*.*)"), TEXT("*.*")); fdo.AddFilter(TEXT("All Text (*.txt)"), TEXT("*.txt")); fdo.AddFilter(TEXT("All Images (*.bmp, *.tga, *.jpeg, *.png)"), TEXT("*.bmp;*.tga;*.jpeg;*.png")); */ bool Win32SaveFileDialog (HWND hWnd, FileDialogOption &fdo); bool Win32OpenFileDialog (HWND hWnd, FileDialogOption &fdo); } #endif // NWIN32CUSTOMDIALOG_H nux-4.0.8+16.04.20160209/NuxCore/ObjectPtr.h0000644000015600001650000004575412656236757020373 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2010-2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUXCORE_OBJECTPTR_H #define NUXCORE_OBJECTPTR_H #include #include namespace nux { template class ObjectWeakPtr; template class ObjectPtr; //! A smart pointer class. Implemented as an intrusive smart pointer. template class ObjectPtr { public: //! Constructor ObjectPtr() : ptr_(NULL) { } //! Copy constructor ObjectPtr(ObjectPtr const& other) : ptr_(other.ptr_) { if (ptr_) { ptr_->objectptr_count_->Increment(); ptr_->Reference(); } } //! Copy constructor /*! This method takes advantage of the nux type information using the virtual Type function. @param other Parameter with a type derived from T. */ template ObjectPtr(ObjectPtr const& other) : ptr_(NULL) { if (other.ptr_ && other.ptr_->Type().IsDerivedFromType(T::StaticObjectType)) { ptr_ = static_cast(other.ptr_); ptr_->objectptr_count_->Increment(); ptr_->Reference(); } } //! Construction with a base pointer of type T. /*! @param ptr Start maintaining a reference count of the passed pointer. @param WarnMissuse If True, then ObjectPtr test is ptr is owned or not. If ptr is not owned and WarnMissuse is True, then Print a warning message. This is a debug feature to detect cases such as "ObjectPtr(ObjectA) myobject(ptr);", because the calling code will no longer have a reference on ptr. */ explicit ObjectPtr(T *ptr, bool WarnMissuse = false) : ptr_(NULL) { if (ptr) { if (WarnMissuse && (!ptr->OwnsTheReference())) { nuxDebugMsg (TEXT ("[ObjectPtr::ObjectPtr] Warning: Constructing a smart pointer from an object with a floating reference.") ); } ptr_ = ptr; ptr_->objectptr_count_->Increment(); ptr_->Reference(); } } //! Construction with a base pointer of type O that inherits from type T. /*! @param ptr Start maintaining a reference count of the passed pointer. @param WarnMissuse If True, then ObjectPtr test is ptr is owned or not. If ptr is not owned and WarnMissuse is True, then Print a warning message. This is a debug feature to detect cases such as "ObjectPtr(ObjectA) myobject(ptr);", because the calling code will no longer have a reference on ptr. */ template explicit ObjectPtr(O *ptr, bool WarnMissuse = false) : ptr_(NULL) { if (ptr && ptr->Type().IsDerivedFromType(T::StaticObjectType)) { if (WarnMissuse && (!ptr->OwnsTheReference())) { nuxDebugMsg (TEXT ("[ObjectPtr::ObjectPtr] Warning: Constructing a smart pointer from an object with a floating reference.") ); } ptr_ = static_cast(ptr); ptr_->objectptr_count_->Increment(); ptr_->Reference(); } } //! Take ownership of ptr. void Adopt(T* ptr) { bool was_owned = false; if (ptr) { // If 'was_owned' is false, then ptr has a floating reference status. The next line: // ObjectPtr temp(ptr); // will not increase its reference count. It will only make the object "Owned". was_owned = ptr->OwnsTheReference(); } // If 'was_owned' is true then the next line increases the reference count of ptr. // Otherwise, ptr just becomes "Owned" (it looses it floating reference status). ObjectPtr temp(ptr); Swap(temp); // Now we want to release the reference that was added on construction, // but keep the smart pointer count. if (ptr_ && was_owned) { // ptr was already owned. Reduce the reference count that was added by the call to // ObjectPtr temp(ptr); ptr_->UnReference(); } } //! Assignment of a smart pointer of type T. /*! @param other Smart pointer of type T. */ ObjectPtr& operator=(T* ptr) { ObjectPtr temp(ptr); Swap(temp); return *this; } //! Assignment of a smart pointer of type T. /*! @param other Smart pointer of type T. */ ObjectPtr& operator=(ObjectPtr const& other) { ObjectPtr temp(other); Swap(temp); return *this; } //! Assignment of a smart pointer of type O that inherits from type T. /*! @param other Smart pointer of type O. */ template ObjectPtr& operator=(ObjectPtr const& other) { ObjectPtr temp(other); Swap(temp); return *this; } ~ObjectPtr() { ReleaseReference(); } T& operator*() const { nuxAssert(ptr_ != 0); return *ptr_; } T* operator->() const { nuxAssert(ptr_ != 0); return ptr_; } //! Return the stored pointer. /*! Caller of this function should Reference the pointer if they intend to keep it. @param Return the stored pointer. */ T* GetPointer () const { return ptr_; } //! Swap the content of 2 smart pointers. /*! @param other Smart pointer to swap with. */ void Swap (ObjectPtr& other) { std::swap(ptr_, other.ptr_); } operator bool() const { return bool(ptr_); } //! Test validity of the smart pointer. /*! Return True if the internal pointer is not null. */ bool operator() () const { return bool(ptr_); } //! Test validity of the smart pointer. /*! Return True if the internal pointer is null. */ bool IsNull() const { return !IsValid(); } //! Test validity of the smart pointer. /*! Return True if the internal pointer is not null. */ bool IsValid() const { return (ptr_ != NULL); } bool operator < (T *ptr) const { return (ptr_ < ptr); } bool operator > (T *ptr) const { return (ptr_ > ptr); } bool operator < (ObjectPtr other) const { return (ptr_ < other.ptr_); } bool operator > (ObjectPtr other) const { return (ptr_ > other.ptr_); } bool operator == (T *ptr) const { return ptr_ == ptr; } template bool operator != (U other) const { return !(*this == other); } template bool operator == (U* ptr) const { if (ptr && (!ptr->Type().IsDerivedFromType(T::StaticObjectType))) return false; return ptr_ == static_cast(ptr); } template bool operator == (ObjectPtr const& other) const { if (other.ptr_ && (!other.ptr_->Type().IsDerivedFromType (T::StaticObjectType) ) ) return false; return ptr_ == static_cast(other.ptr_); } template bool operator == (ObjectWeakPtr const& other) const { if (other.ptr_ && (!other.ptr_->Type().IsDerivedFromType (T::StaticObjectType) ) ) return false; return ptr_ == static_cast(other.ptr_); } //! Release the hosted pointer from this object. /*! Release the hosted pointer from this object. After this call, all the members are null. @return True if the hosted object was destroyed. */ bool Release() { return ReleaseReference(); } private: bool ReleaseReference() { if (!ptr_) { return false; } // Decrease the number of strong reference on the hosted pointer. ptr_->objectptr_count_->Decrement(); bool destroyed = ptr_->UnReference(); ptr_ = NULL; return destroyed; } T* ptr_; template friend class ObjectPtr; template friend class ObjectWeakPtr; }; //! A weak smart pointer class. Implemented as an intrusive smart pointer. /*! A weak smart pointer is built from a smart pointer or another weak smart pointer. It increments and decrements the total reference count of an pointer. Even is the original pointer is destroyed, weak smart pointers still point to the RefCounts pointers of the original pointer and can use it to check if the pointer is still valid or not. */ template class ObjectWeakPtr { public: //! Constructor ObjectWeakPtr() : ptr_(NULL) { } //! Construction with a base pointer of type T. /*! @param ptr Start maintaining a reference count of the passed pointer. @param WarnMissuse If True, then ObjectPtr test is ptr is owned or not. If ptr is not owned and WarnMissuse is True, then Print a warning message. This is a debug feature to detect cases such as "ObjectPtr(ObjectA) myobject(ptr);", because the calling code will no longer have a reference on ptr. */ explicit ObjectWeakPtr(T* ptr) : ptr_(ptr) { ConnectListener(); } //! Construction with a base pointer of type O that inherits from type T. /*! @param ptr Start maintaining a reference count of the passed pointer. @param WarnMissuse If True, then ObjectPtr test is ptr is owned or not. If ptr is not owned and WarnMissuse is True, then Print a warning message. This is a debug feature to detect cases such as "ObjectPtr(ObjectA) myobject(ptr);", because the calling code will no longer have a reference on ptr. */ template explicit ObjectWeakPtr(O* ptr, bool /* WarnMissuse */ = false) : ptr_(NULL) { if (ptr && (ptr->Type().IsDerivedFromType(T::StaticObjectType))) { ptr_ = static_cast(ptr); ConnectListener(); } } //! Copy constructor /*! @param other Parameter with type T. */ ObjectWeakPtr(ObjectWeakPtr const& other) : ptr_(other.ptr_) { ConnectListener(); } //! Copy constructor /*! @param other Parameter with a type derived from T. */ template ObjectWeakPtr(const ObjectWeakPtr& other) : ptr_(NULL) { if (other.ptr_ && (other.ptr_->Type().IsDerivedFromType(T::StaticObjectType))) { ptr_ = static_cast(other.ptr_); ConnectListener(); } } //! Construction from a smart pointer of type O that inherits from type T. /*! @param other Maintains a weak smart pointer reference to this parameter. */ template ObjectWeakPtr(const ObjectPtr &other) : ptr_(NULL) { if (other.ptr_ && (other.ptr_->Type().IsDerivedFromType(T::StaticObjectType))) { ptr_ = static_cast(other.ptr_); ConnectListener(); } } //! Assignment of a weak smart pointer of type T. /*! @param other Weak smart pointer of type T. */ ObjectWeakPtr& operator = (ObjectWeakPtr const& other) { Disconnect(); ptr_ = other.ptr_; ConnectListener(); return *this; } // Warning: We are not sure that other.ptr_ is valid. // Warning: Cannot call other.ptr_->Type().IsDerivedFromType (T::StaticObjectType) //! Assignment of a weak smart pointer of Type O that inherits from type T. /*! @param other Weak smart pointer of type O. */ template ObjectWeakPtr &operator = (const ObjectWeakPtr& other) { Disconnect(); if (other.ptr_ && other.ptr_->Type().IsDerivedFromType(T::StaticObjectType)) { ptr_ = static_cast(other.ptr_); ConnectListener(); } return *this; } //! Assignment of a smart pointer of Type O that inherits from type T. /*! @param other Maintains a weak smart pointer reference to this parameter. */ template ObjectWeakPtr &operator = (const ObjectPtr& other) { Disconnect(); if (other.ptr_ && other.ptr_->Type().IsDerivedFromType(T::StaticObjectType)) { ptr_ = static_cast(other.ptr_); ConnectListener(); } return *this; } //! Construction with a base pointer of type T. /*! @param ptr Start maintaining a reference count of the passed pointer. @param WarnMissuse If True, then ObjectPtr test is ptr is owned or not. If ptr is not owned and WarnMissuse is True, then Print a warning message. This is a debug feature to detect cases such as "ObjectPtr(ObjectA) myobject(ptr);", because the calling code will no longer have a reference on ptr. */ ObjectWeakPtr& operator = (T* ptr) { Disconnect(); ptr_ = ptr; ConnectListener(); return *this; } template ObjectWeakPtr &operator = (O* ptr) { Disconnect(); if (ptr && ptr->Type().IsDerivedFromType(T::StaticObjectType)) { ptr_ = static_cast(ptr); ConnectListener(); } return *this; } ~ObjectWeakPtr() { Disconnect(); } T& operator* () const { nuxAssert (ptr_ != 0); return *(const_cast(ptr_)); } T* operator -> () const { nuxAssert (ptr_ != 0); return const_cast(ptr_); } bool operator < (T *ptr) const { return (ptr_ < ptr); } bool operator > (T *ptr) const { return (ptr_ > ptr); } bool operator < (ObjectWeakPtr other) const { return (ptr_ < other.ptr_); } bool operator > (ObjectWeakPtr other) const { return (ptr_ > other.ptr_); } template bool operator != (U other) const { return !(*this == other); } bool operator == (T *ptr) const { return ptr_ == ptr; } template bool operator == (U *ptr) const { if (ptr && (!ptr->Type().IsDerivedFromType (T::StaticObjectType) ) ) return false; return ptr_ == static_cast(ptr); } /*! @other A weak pointer @return True is this weak pointer host the same pointer as the weak pointer passed as parameter. */ template bool operator == (const ObjectWeakPtr& other) const { if (other.ptr_ && (!other.ptr_->Type().IsDerivedFromType (T::StaticObjectType) ) ) return false; return ptr_ == static_cast(other.ptr_); } /*! @other An object pointer @return True is this weak pointer host the same pointer as the object pointer passed as parameter. */ template bool operator == (const ObjectPtr& other) const { if (other.ptr_ && (!other.ptr_->Type().IsDerivedFromType (T::StaticObjectType) ) ) return false; return ptr_ == static_cast(other.ptr_); } //! Return true is the hosted pointer is not null or has not been destroyed. /*! @return True if the internal pointer is not null. */ bool operator() () const { return bool(ptr_); } //! Return true is the hosted pointer is not null or has not been destroyed. /*! @return True if the internal pointer is not null or has not been destroyed. */ bool IsValid() const { return (ptr_ != NULL); } //! Return true is the hosted pointer is null or has been destroyed. /*! @return True if the internal pointer is null or has been destroyed. */ bool IsNull() const { return !IsValid(); } //! Release the hosted pointer from this object. /*! Release the hosted pointer from this object. After this call, the following members are null: _reference_count _weak_reference_count ptr_ This call decreases the count of weak reference before setting _weak_reference_count to null. @return True this was the last weak reference on the hosted object. */ bool Release() { Disconnect(); ptr_ = NULL; return false; } //! Return the stored pointer. /*! Caller of this function should Reference the pointer if they intend to keep it. @param Return the stored pointer. */ T* GetPointer () const { return ptr_; } private: void Disconnect() { if (destroy_listener_.connected()) destroy_listener_.disconnect(); } void ConnectListener() { if (ptr_) { auto slot = sigc::mem_fun(this, &ObjectWeakPtr::TargetDestroyed); destroy_listener_ = ptr_->object_destroyed.connect(slot); } } void TargetDestroyed(Object* /* ptr */) { ptr_ = NULL; // rese the connetion too destroy_listener_ = sigc::connection(); } T* ptr_; sigc::connection destroy_listener_; template friend class ObjectWeakPtr; template friend bool operator == (U *, const ObjectWeakPtr& a); template friend bool operator != (U *, const ObjectWeakPtr& a); template friend ObjectWeakPtr staticCast (const ObjectWeakPtr& from); template friend ObjectWeakPtr constCast (const ObjectWeakPtr& from); template friend ObjectWeakPtr dynamicCast (const ObjectWeakPtr& from); template friend ObjectWeakPtr checkedCast (const ObjectWeakPtr& from); template friend ObjectWeakPtr queryCast (const ObjectWeakPtr& from); }; /////////////////////////////////////////////////////// // globals template inline bool operator == (T *ptr, const ObjectPtr& a) { return a.ptr_ == ptr; } template inline bool operator != (T *ptr, const ObjectPtr& a) { return a.ptr_ != ptr; } template inline bool operator == (T *ptr, const ObjectWeakPtr& a) { return a.ptr_ == ptr; } template inline bool operator != (T *ptr, const ObjectWeakPtr& a) { return a.ptr_ != ptr; } } #endif nux-4.0.8+16.04.20160209/NuxCore/NumberConversion.cpp0000644000015600001650000000760512656236757022321 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "NumberConversion.h" namespace nux { /** * From: http://www.strudel.org.uk/itoa/ * C++ version 0.4 char* style "itoa": * Written by Luks Chmela * Released under GPLv3. */ std::string IntegerToChar (int value, int base) { char result[65]; // check that the base if valid if (base < 2 || base > 36) { return std::string(); } char *ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base) ]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr-- = *ptr1; *ptr1++ = tmp_char; } std::string str = result; return str; } double CharToDouble (const TCHAR *digit) { char *endptr = NULL; std::string str = TCHAR_TO_ANSICHAR (digit); errno = 0; double ret = std::strtod (str.c_str(), &endptr); unsigned int error = errno; if (error == ERANGE) { nuxDebugMsg ("[CharToDouble] Out for range value"); } return ret; } std::string DoubleToChar (double d) { TCHAR *buffer = new TCHAR[64]; Memset (buffer, 0, 64); SPRINTF_S (buffer, 64, "%.39f", d); std::string str = buffer; while (!str.empty() && str[str.size() - 1] == '0') { str.erase(str.end() - 1); } delete[] buffer; return str; } int CharToInteger (const TCHAR *digit) { std::string str = TCHAR_TO_ANSICHAR (digit); long long ret = std::atoi (str.c_str() ); return ret; } // convert an hexadecimal string to unsigned int unsigned int HexCharToInteger (const TCHAR *s) { int n = 0; // position in string int m = 0; // position in digit[] to shift int count; // loop index unsigned long intValue = 0; // integer value of hex string int digit[16]; // hold values to convert const TCHAR *hexStg = s; if ( (s[0] == TEXT ('0') ) && ( (s[1] == TEXT ('X') ) || (s[1] == TEXT ('x') ) ) ) { hexStg = s + 2; } while (n < 16) { if (hexStg[n] == TEXT ('\0') ) break; if (hexStg[n] > 0x29 && hexStg[n] < 0x40 ) //if 0 to 9 digit[n] = hexStg[n] & 0x0f; //convert to int else if (hexStg[n] >= TEXT ('a') && hexStg[n] <= TEXT ('f') ) //if a to f digit[n] = (hexStg[n] & 0x0f) + 9; //convert to int else if (hexStg[n] >= TEXT ('A') && hexStg[n] <= TEXT ('F') ) //if A to F digit[n] = (hexStg[n] & 0x0f) + 9; //convert to int else break; n++; } count = n; m = n - 1; n = 0; while (n < count) { // digit[n] is value of hex digit at position n // (m << 2) is the number of positions to shift // OR the bits into return value intValue = intValue | (digit[n] << (m << 2) ); m--; // adjust the position to set n++; // next digit to process } return (intValue); } } nux-4.0.8+16.04.20160209/NuxCore/Colors.h0000644000015600001650000001415412656236757017726 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef COLORS_H #define COLORS_H #include "Color.h" namespace nux { namespace color { // Definition of Luma coefficients as per ITU-R Recommendation BT.709 // http://en.wikipedia.org/wiki/Rec._709 extern const float LumaRed; extern const float LumaGreen; extern const float LumaBlue; // X11 color names from:http://en.wikipedia.org/wiki/Web_colors extern const Color Transparent; // Red colors extern const Color IndianRed; extern const Color LightCoral; extern const Color Salmon; extern const Color DarkSalmon; extern const Color LightSalmon; extern const Color Crimson; extern const Color Red; extern const Color FireBrick; extern const Color DarkRed; // Pink colors extern const Color Pink; extern const Color LightPink; extern const Color HotPink; extern const Color DeepPink; extern const Color MediumVioletRed; extern const Color PaleVioletRed; // Orange colors extern const Color Coral; extern const Color Tomato; extern const Color OrangeRed; extern const Color DarkOrange; extern const Color Orange; // Yellow colors extern const Color Gold; extern const Color Yellow; extern const Color LightYellow; extern const Color LemonChiffon; extern const Color LightGoldenrodYellow; extern const Color PapayaWhip; extern const Color Moccasin; extern const Color PeachPuff; extern const Color PaleGoldenrod; extern const Color Khaki; extern const Color DarkKhaki; // Purple colors extern const Color Lavender; extern const Color Thistle; extern const Color Plum; extern const Color Violet; extern const Color Orchid; extern const Color Fuchsia; extern const Color Magenta; extern const Color MediumOrchid; extern const Color MediumPurple; extern const Color BlueViolet; extern const Color DarkViolet; extern const Color DarkOrchid; extern const Color DarkMagenta; extern const Color Purple; extern const Color Indigo; extern const Color SlateBlue; extern const Color DarkSlateBlue; // Green colors extern const Color GreenYellow; extern const Color Chartreuse; extern const Color LawnGreen; extern const Color Lime; extern const Color LimeGreen; extern const Color PaleGreen; extern const Color LightGreen; extern const Color MediumSpringGreen; extern const Color SpringGreen; extern const Color MediumSeaGreen; extern const Color SeaGreen; extern const Color ForestGreen; extern const Color Green; extern const Color DarkGreen; extern const Color YellowGreen; extern const Color OliveDrab; extern const Color Olive; extern const Color DarkOliveGreen; extern const Color MediumAquamarine; extern const Color DarkSeaGreen; extern const Color LightSeaGreen; extern const Color DarkCyan; extern const Color Teal; // Blue colors extern const Color Aqua; extern const Color Cyan; extern const Color LightCyan; extern const Color PaleTurquoise; extern const Color Aquamarine; extern const Color Turquoise; extern const Color MediumTurquoise; extern const Color DarkTurquoise; extern const Color CadetBlue; extern const Color SteelBlue; extern const Color LightSteelBlue; extern const Color PowderBlue; extern const Color LightBlue; extern const Color SkyBlue; extern const Color LightSkyBlue; extern const Color DeepSkyBlue; extern const Color DodgerBlue; extern const Color CornflowerBlue; extern const Color MediumSlateBlue; extern const Color RoyalBlue; extern const Color Blue; extern const Color MediumBlue; extern const Color DarkBlue; extern const Color Navy; extern const Color MidnightBlue; // Brown colors extern const Color Cornsilk; extern const Color BlanchedAlmond; extern const Color Bisque; extern const Color NavajoWhite; extern const Color Wheat; extern const Color BurlyWood; extern const Color Tan; extern const Color RosyBrown; extern const Color SandyBrown; extern const Color Goldenrod; extern const Color DarkGoldenrod; extern const Color Peru; extern const Color Chocolate; extern const Color SaddleBrown; extern const Color Sienna; extern const Color Brown; extern const Color Maroon; // White colors extern const Color White; extern const Color Snow; extern const Color Honeydew; extern const Color MintCream; extern const Color Azure; extern const Color AliceBlue; extern const Color GhostWhite; extern const Color WhiteSmoke; extern const Color Seashell; extern const Color Beige; extern const Color OldLace; extern const Color FloralWhite; extern const Color Ivory; extern const Color AntiqueWhite; extern const Color Linen; extern const Color LavenderBlush; extern const Color MistyRose; // Grey colors extern const Color Gainsboro; extern const Color LightGrey; extern const Color Silver; extern const Color DarkGray; extern const Color Gray; extern const Color DimGray; extern const Color LightSlateGray; extern const Color SlateGray; extern const Color DarkSlateGray; extern const Color Black; // More Colors extern const Color Aubergine; } } #endif // COLORS_H nux-4.0.8+16.04.20160209/NuxCore/Color.h0000644000015600001650000001552312656236757017544 0ustar pbuserpbgroup00000000000000/* * Copyright 2010-2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef COLOR_H #define COLOR_H #include namespace nux { namespace color { // DirectX D3DFormat // // All formats are listed from left to right, most significant bit (MSB) to // least significant bit (LSB). For example, D3DFORMAT_ARGB is ordered from // the MSB channel A (alpha), to the LSB channel B (blue). When traversing // surface data, the data is stored in memory from LSB to MSB, which means // that the channel order in memory is from LSB (blue) to MSB (alpha). // // The default value for formats that contain undefined channels (G16R16, // A8, and so on) is 1. The only exception is the A8 format, which is // initialized to 000 for the three color channels. // // The order of the bits is from the most significant byte first, so // D3DFMT_A8L8 indicates that the high byte of this 2-byte format is // alpha. D3DFMT_D16 indicates a 16-bit integer value and an // application-lockable surface. // // Pixel formats have been chosen to enable the expression of // hardware-vendor-defined extension formats, as well as to include the // well-established four-character code (FOURCC) method. The set of formats // understood by the Microsoft Direct3D runtime is defined by D3DFORMAT. //Format of RGBA colors is //7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //| alpha | red | green | blue | //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //MSB 31 0 LSB //Format of RGB colors is //7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //| ignored | red | green | blue | //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //Format of BGR colors is //7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //| ignored | blue | green | red | //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //Format of RGBA colors is //7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //| red | green | blue | alpha | //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //Format of BGRA colors is //7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //| blue | green | red | alpha | //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ enum Model { RGB, HSV, HLS, YUV }; enum Channel { RED, GREEN, BLUE, HUE, SATURATION, LIGHT, VALUE }; enum Format { FLOAT, HEX, INT }; class RedGreenBlue; class Color { public: Color(); explicit Color(unsigned int c); Color(int r, int g, int b); Color(float r, float g, float b, float a = 1.0f); Color(RedGreenBlue const& rgb, float a = 1.0f); //! Constructor - Initializes the color using an hex string /*! Initializes the color using an hex string, which may be in one of these formats: #RGB (each of R, G, B, A is a single hex digit) #RGBA #RRGGBB #RRGGBBAA The color is #ffffffff if hex cannot be parsed. */ Color(std::string const& hex); //! Returns the pre-multiplied version of this color. /*! Returns the pre-multiplied version of this color. If this color is already pre-multiplied then *this is returned.\n The premultiplied color is Color(red * alpha, green * alpha, blue * alpha, alpha). @return The pre-multiplied version of this color. */ Color GetPremultiplied(); //! Sets a pre-multiplied color /*! Sets a pre-multiplied color @param r Red value. @param g Green value. @param b Blue value. @param a Alpha value. */ void SetPremultiplied(float r, float g, float b, float a); //! Returns True if this color is pre-multiplied. /*! Returns True if this color is pre-multiplied. @return True is this color is pre-multiplied. */ bool IsPremultiplied(); float red; float green; float blue; float alpha; protected: bool premultiplied_; //!< True if the rgb components have been pre-multiplied with the alpha component. friend bool operator == (Color const& lhs, Color const& rhs); }; bool operator == (Color const& lhs, Color const& rhs); bool operator != (Color const& lhs, Color const& rhs); Color operator + (Color const&, Color const&); Color operator + (float, Color const&); Color operator + (Color const&, float); Color operator - (Color const&, Color const&); Color operator - (float, Color const&); Color operator - (Color const&, float); Color operator * (float, Color const&); Color operator * (Color const&, float); Color RandomColor(); unsigned int RandomColorINT(); class HueSaturationValue; class HueLightnessSaturation; class RedGreenBlue { public: RedGreenBlue(float r, float g, float b); RedGreenBlue(Color const& color); RedGreenBlue(HueSaturationValue const&); RedGreenBlue(HueLightnessSaturation const&); float red; float green; float blue; }; class HueSaturationValue { public: HueSaturationValue(float h, float s, float v); HueSaturationValue(Color const&); HueSaturationValue(RedGreenBlue const&); float hue; float saturation; float value; }; class HueLightnessSaturation { public: HueLightnessSaturation(float h, float l, float s); HueLightnessSaturation(Color const&); HueLightnessSaturation(RedGreenBlue const&); float hue; float lightness; float saturation; }; } using color::Color; } #endif // COLOR_H nux-4.0.8+16.04.20160209/NuxCore/FileManager/0000755000015600001650000000000012656240224020441 5ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerGeneric.h0000644000015600001650000001707412656236757024430 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NFILEMANAGERGENERIC_H #define NFILEMANAGERGENERIC_H namespace nux { class NFileManagerWindows; class NFileTransferMonitor { public: NFileTransferMonitor() { m_bCancel = false; } virtual ~NFileTransferMonitor() {} void Cancel() { m_bCancel = true; } virtual bool Progress (float Fraction) = 0; #ifdef _WIN32 static DWORD CALLBACK CopyProgressRoutine ( NUX_IN LARGE_INTEGER TotalFileSize, NUX_IN LARGE_INTEGER TotalBytesTransferred, NUX_IN LARGE_INTEGER StreamSize, NUX_IN LARGE_INTEGER StreamBytesTransferred, NUX_IN DWORD dwStreamNumber, NUX_IN DWORD dwCallbackReason, NUX_IN HANDLE hSourceFile, NUX_IN HANDLE hDestinationFile, NUX_IN LPVOID lpData ) { NFileTransferMonitor *filetransfer = NUX_STATIC_CAST (NFileTransferMonitor *, lpData); if (filetransfer) { if (filetransfer->Progress (100.0 * double (TotalBytesTransferred.QuadPart) / double (TotalFileSize.QuadPart) ) == false) { return PROGRESS_CANCEL; } } return PROGRESS_CONTINUE; } //private: #endif BOOL m_bCancel; friend class NFileManagerWindows; }; class NFileManager { public: NFileManager() {} virtual ~NFileManager() {} /** Timestamp structure */ struct FileTimeStamp { // Time is in UTC INT Year; /* year */ INT Month; /* months since January - [0,11] */ INT Day; /* day of the month - [1,31] */ INT Hour; /* hours since midnight - [0,23] */ INT Minute; /* minutes after the hour - [0,59] */ INT Second; /* seconds after the minute - [0,59]*/ INT DayOfWeek; /* days since Sunday - [0,6] */ INT DayOfYear; /* days since January 1 - [0,365] */ INT GetJulian ( void ) const; INT GetSecondOfDay ( void ) const; bool operator == ( FileTimeStamp &Other ) const; bool operator != ( FileTimeStamp &Other ) const; bool operator < ( FileTimeStamp &Other ) const; bool operator > ( FileTimeStamp &Other ) const; bool operator >= ( FileTimeStamp &Other ) const; bool operator <= ( FileTimeStamp &Other ) const; }; virtual void Init (bool /* Startup */) {} virtual NSerializer *CreateFileReader ( const TCHAR *Filename, DWORD ReadFlags = 0, LogOutputDevice &Error = GNullDevice ) = 0; virtual NSerializer *CreateFileWriter ( const TCHAR *Filename, DWORD WriteFlags = 0, LogOutputDevice &Error = GNullDevice ) = 0; //! Return TRUE if the file exist. /*! Return TRUE if the file exist. @param Filename the full path of the file to search. @return TRUE if the file exist. */ virtual long long FileSize (const TCHAR *Filename) = 0; // Max file size is 16 terabytes minus 64 KB on NTFS. 4 gigabytes on Fat32. virtual bool FileExist (const TCHAR *Filename) = 0; virtual int Copy (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting = true, bool OverWriteReadOnly = false, NFileTransferMonitor *Progress = NULL) = 0; virtual bool Move (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting = true, bool OverWriteReadOnly = false, NFileTransferMonitor *Monitor = NULL) = 0; virtual bool Delete (const TCHAR *Filename, bool OverWriteReadOnly = false) = 0; virtual bool IsReadOnly (const TCHAR *Filename) = 0; virtual bool IsDirectory (const TCHAR *DirectoryName) = 0; virtual bool IsHidden (const TCHAR *Filename) = 0; virtual bool GetFileAttribute (const TCHAR *Filename, bool &isDirectory, bool &IsReadOnly, bool &IsHidden, long long &Size) = 0; virtual bool MakeDirectory (const TCHAR *Path, bool CreateCompletePath = false) = 0; //! Delete directory /*! Delete a Directory. If DeleteContent is true, The content of the directory is deleted before the directory itself; @param Path Path of the directory @param DeleteContentFirst Delete the content of the directory before deleting the directory itself. @return TRUE if the directory was deleted. */ virtual bool DeleteDirectory (const TCHAR *Path, bool DeleteContentFirst = false) = 0; /*! Creates a unique file name. The format of the name is "DirectoryPath/BaseName####.Extension" where #### is a 4-digit number in [0, 9999]. The new name is unique and does not exist in the path directory. The function returns the value of the index created for the new file name or -1 if none could be found. The return value can be saved and passed the he next call to CreateUniqueFileName in order to speed up the search. Example usage: Create a new file name for of form DirectoryPath/Filename####.ext CreateUniqueFileName(TEXT("DirectoryPath/Filename"), TEXT("ext"), Output); @param Filename Filename with optional path. @param Extension Extension. @param OutputFilename New filename. @param BaseIndex Base for index search. @return Index of the new file. -1 if the file couldn't be created The index has to be in the range [0, 9999]. */ virtual int CreateUniqueFileName (const TCHAR *Filename, const TCHAR *Extension, std::string &OutputFilename, unsigned int BaseIndex = 0xffffffff) = 0; virtual void FindFiles ( std::vector& FileNames, const TCHAR *Filename, bool Files, bool Directories ) = 0; virtual void ListFilesInDirectory ( std::vector& Result, const TCHAR *DirName) = 0; virtual time_t GetFileLastModified (const TCHAR *Filename) = 0; virtual double GetFileAgeSeconds (const TCHAR *Filename) = 0; virtual bool SetDefaultDirectory() = 0; virtual std::string GetCurrentDirectory() = 0; virtual bool GetTimeStamp ( const TCHAR *Path, FileTimeStamp &Timestamp ) = 0; protected: }; class NFileManagerGeneric : public NFileManager { public: int Copy (const TCHAR *InDestFile, const TCHAR *InSrcFile, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor *Monitor); bool MakeDirectory (const TCHAR *Path, bool CreateCompletePath = false); bool DeleteDirectory (const TCHAR *Path, bool DeleteContentFirst = false); bool Move (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting = true, bool OverWriteReadOnly = false, NFileTransferMonitor *Monitor = NULL); int CreateUniqueFileName (const TCHAR *Filename, const TCHAR *Extension, std::string &OutputFilename, unsigned int BaseIndex = 0xffffffff); bool IsDrive (const TCHAR *Path); }; } #endif // NFILEMANAGERGENERIC_H nux-4.0.8+16.04.20160209/NuxCore/FileManager/NSerializer.cpp0000644000015600001650000001167012656236757023421 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { // template // void NSerializer::SerializeBuffer(T* buffer, unsigned long long Length, unsigned long long ElementSize) // { // for(unsigned long long i = 0; i < Length; i++) // { // unsigned char* bytebuffer = (unsigned char*)(&buffer[i]); // Serialize(bytebuffer, ElementSize); // } // } // NSerializer& operator << (NSerializer& Sr, std::string& s) // { // Sr.SerializeBuffer(NUX_CONST_CAST(TCHAR*, s.GetTCharPtr()), s.Size()+1, sizeof(TCHAR)); // return Sr; // } // // NSerializer& operator << (NSerializer& Sr, std::string& s) // { // Sr.SerializeBuffer(NUX_CONST_CAST(char*, s.c_str()), s.size()+1, sizeof(char)); // return Sr; // } void NSerializer::Serialize (char &data) { SerializeFinal (&data, sizeof (char) ); } void NSerializer::Serialize (wchar_t &data) { SerializeFinal (&data, sizeof (wchar_t) ); } void NSerializer::Serialize (bool &data) { SerializeFinal (&data, sizeof (bool) ); } void NSerializer::Serialize (unsigned char &data) { SerializeFinal (&data, sizeof (unsigned char) ); } void NSerializer::Serialize (unsigned short &data) { SerializeFinal (&data, sizeof (unsigned short) ); } void NSerializer::Serialize (short &data) { SerializeFinal (&data, sizeof (short) ); } void NSerializer::Serialize (unsigned int &data) { SerializeFinal (&data, sizeof (unsigned int) ); } void NSerializer::Serialize (int &data) { SerializeFinal (&data, sizeof (int) ); } void NSerializer::Serialize (long &data) { SerializeFinal (&data, sizeof (long) ); } void NSerializer::Serialize (unsigned long &data) { SerializeFinal (&data, sizeof (unsigned long) ); } void NSerializer::Serialize (float &data) { SerializeFinal (&data, sizeof (float) ); } void NSerializer::Serialize (double &data) { SerializeFinal (&data, sizeof (double) ); } void NSerializer::Serialize (unsigned long long &data) { SerializeFinal (&data, sizeof (unsigned long long) ); } void NSerializer::Serialize (long long &data) { SerializeFinal (&data, sizeof (long long) ); } void NSerializer::Serialize (wchar_t *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (bool *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (char *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (unsigned char *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (unsigned short *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (short *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (unsigned int *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (int *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (long *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (unsigned long *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (float *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (double *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (unsigned long long *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } void NSerializer::Serialize (long long *buffer, unsigned int len, unsigned int stride) { SerializeFinal (buffer, len * stride); } } nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerWindows.cpp0000644000015600001650000006257412656236757025046 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Math/MathUtility.h" namespace nux { // Choose the size so it is a power of 2. Example (size-1)= 11111111. const int NWindowsSerialFileReader::sBufferSize = 1024; NWindowsSerialFileReader::NWindowsSerialFileReader (HANDLE InHandle, LogOutputDevice &InError) : m_FileHandle (InHandle) , m_Error (InError) , m_FilePos (0) , m_BufferBase (0) , m_BufferCount (0) { m_Buffer = new BYTE[sBufferSize]; m_FileSize = GetFileSize(); } NWindowsSerialFileReader::~NWindowsSerialFileReader() { NUX_SAFE_DELETE_ARRAY (m_Buffer); if (m_FileHandle) { Close(); } } bool NWindowsSerialFileReader::Precache (int PrecacheOffset, int PrecacheSize) { // Only pre-cache at current position and avoid work if pre-caching same offset twice. if ( (m_FilePos == PrecacheOffset) && (!m_BufferBase || !m_BufferCount || m_BufferBase != m_FilePos) ) { m_BufferBase = m_FilePos; // (sBufferSize - 1) contains only '1', i.e 1111111111. // So (m_FilePos & (sBufferSize-1)) is equal to m_FilePos if m_FilePos <= (sBufferSize-1). m_BufferCount = Min (Min (PrecacheSize, (int) (sBufferSize - (m_FilePos & (sBufferSize - 1) ) ) ), m_FileSize - m_FilePos); unsigned int Count = 0; //GTotalBytesReadViaFileManager += m_BufferCount; ::ReadFile (m_FileHandle, m_Buffer, m_BufferCount, NUX_REINTERPRET_CAST (DWORD *, &Count), NULL); if (Count != m_BufferCount) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("ReadFile failed: Count=%i BufferCount=%i Error=%s"), Count, m_BufferCount, inlGetSystemErrorMessage() ); } } return TRUE; } long long NWindowsSerialFileReader::Seek (long long InPos, NSerializer::SeekPos seekpos) { nuxAssert (InPos >= 0); nuxAssert (InPos <= m_FileSize); Flush(); // Because we precache our reads, we must perform Seek accordingly. LARGE_INTEGER pos; pos.QuadPart = m_FilePos; LARGE_INTEGER filepos; filepos.QuadPart = 0; // Set the file pointer to m_FilePos. if (::SetFilePointerEx (m_FileHandle, pos, &filepos, FILE_BEGIN) == 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("SetFilePointer Failed %i/%i: %i %s"), InPos, m_FileSize, m_FilePos, inlGetSystemErrorMessage() ); } // Now the file pointer is current with what we have read so far. pos.QuadPart = InPos; filepos.QuadPart = 0; if (::SetFilePointerEx (m_FileHandle, pos, &filepos, (seekpos == SeekStart) ? FILE_BEGIN : (seekpos == SeekCurrent) ? FILE_CURRENT : FILE_END) == 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("SetFilePointer Failed %i/%i: %i %s"), InPos, m_FileSize, m_FilePos, inlGetSystemErrorMessage() ); } m_FilePos = filepos.QuadPart; m_BufferBase = 0; m_BufferCount = 0; Precache (m_FilePos, sBufferSize); return filepos.QuadPart; } long long NWindowsSerialFileReader::Tell() { // Flush(); // LARGE_INTEGER pos; // LARGE_INTEGER filepos; // pos.QuadPart = 0; // ::SetFilePointerEx(m_FileHandle, pos, &filepos, FILE_CURRENT); // return filepos.QuadPart; return m_FilePos; } long long NWindowsSerialFileReader::GetFileSize() { nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return -1; long long Size = 0; if (::GetFileSizeEx (m_FileHandle, NUX_REINTERPRET_CAST (PLARGE_INTEGER, &Size) ) == 0) { Size = -1; } m_FileSize = Size > 0 ? Size : 0; return Size; } bool NWindowsSerialFileReader::Close() { if (m_FileHandle) { CloseHandle (m_FileHandle); } m_FileHandle = NULL; return !m_ErrorCode; } void NWindowsSerialFileReader::SerializeFinal (void* Dest, long long Length) { nuxAssert (Dest); while (Length > 0) { int DataSize = Min (Length, m_BufferBase + m_BufferCount - m_FilePos); if (DataSize == 0) { if (Length >= sBufferSize) { int Count = 0; //GTotalBytesReadViaFileManager += Length; ReadFile (m_FileHandle, Dest, Length, (DWORD*) &Count, NULL); if (Count != Length) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("ReadFile failed: Count=%i Length=%i Error=%s"), Count, Length, inlGetSystemErrorMessage() ); } m_FilePos += Length; m_BufferBase += Length; return; } Precache (m_FilePos, 0x7FFFFFFF); DataSize = Min (Length, m_BufferBase + m_BufferCount - m_FilePos); if (DataSize <= 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("ReadFile beyond EOF %i+%i/%i"), m_FilePos, Length, m_FileSize); } if (m_ErrorCode) return; } Memcpy (Dest, m_Buffer + m_FilePos - m_BufferBase, DataSize); m_FilePos += DataSize; Length -= DataSize; Dest = (BYTE *) Dest + DataSize; } } ////////////////////////////////////////////////////////////////////////// // Choose the size so it is a power of 2. Example (size-1)= 11111111. const int NWindowsSerialFileWriter::sBufferSize = 32; //NCriticalSection NWindowsSerialFileWriter::m_CriticalSection; NWindowsSerialFileWriter::NWindowsSerialFileWriter (HANDLE InHandle, LogOutputDevice &InError) : m_FileHandle (InHandle) , m_Error (InError) , m_BufferCount (0) { m_Pos = Tell(); m_Buffer = new BYTE[sBufferSize]; } NWindowsSerialFileWriter::~NWindowsSerialFileWriter() { NUX_SAFE_DELETE_ARRAY (m_Buffer); if (m_FileHandle) Close(); m_FileHandle = NULL; } long long NWindowsSerialFileWriter::Seek (long long InPos, NSerializer::SeekPos seekpos) { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return -1; _Flush(); LARGE_INTEGER pos; pos.QuadPart = InPos; LARGE_INTEGER filepos; filepos.QuadPart = 0; if (::SetFilePointerEx (m_FileHandle, pos, &filepos, (seekpos == SeekStart) ? FILE_BEGIN : (seekpos == SeekCurrent) ? FILE_CURRENT : FILE_END) == 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("SeekFailed") ); } m_Pos = filepos.QuadPart; return filepos.QuadPart; } long long NWindowsSerialFileWriter::Tell() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return -1; _Flush(); LARGE_INTEGER pos; LARGE_INTEGER filepos; filepos.QuadPart = 0; pos.QuadPart = 0; ::SetFilePointerEx (m_FileHandle, pos, &filepos, FILE_CURRENT); return filepos.QuadPart; } bool NWindowsSerialFileWriter::Close() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return true; _Flush(); if (m_FileHandle && !CloseHandle (m_FileHandle) ) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("WriteFailed") ); } m_FileHandle = NULL; return !m_ErrorCode; } long long NWindowsSerialFileWriter::GetFileSize() { nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return -1; long long Size = 0; if (::GetFileSizeEx (m_FileHandle, NUX_REINTERPRET_CAST (PLARGE_INTEGER, &Size) ) == 0) { Size = -1; } return Size; } void NWindowsSerialFileWriter::SerializeFinal (void *V, long long Length) { // This method is not re-entrant by itself. It relies on m_Buffer and other variables // that belong to this object. Therefore, it is not thread safe. We add a critical section // to make it thread safe. NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileHandle); nuxAssert (V); NUX_RETURN_IF_NULL (m_FileHandle); m_Pos += Length; int FreeSpace; while (Length > (FreeSpace = sBufferSize - m_BufferCount) ) { // m_Buffer is Full. Write it to the file. Memcpy (m_Buffer + m_BufferCount, V, FreeSpace); m_BufferCount += FreeSpace; Length -= FreeSpace; V = (BYTE *) V + FreeSpace; _Flush(); } if (Length) { Memcpy (m_Buffer + m_BufferCount, V, Length); m_BufferCount += Length; // Count the number of Characters stored in m_Buffer. } } void NWindowsSerialFileWriter::Flush() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileHandle); if (m_FileHandle == NULL) return; _Flush(); } void NWindowsSerialFileWriter::_Flush() { //GTotalBytesWrittenViaFileManager += m_BufferCount; if (m_BufferCount) { int Result = 0; if (!WriteFile (m_FileHandle, m_Buffer, m_BufferCount, (DWORD *) &Result, NULL) ) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NWindowsSerialFileWriter::_Flush] Write failed") ); } } m_BufferCount = 0; } ////////////////////////////////////////////////////////////////////////// NUX_IMPLEMENT_GLOBAL_OBJECT (NFileManagerWindows); void NFileManagerWindows::Constructor() { } void NFileManagerWindows::Destructor() { } HANDLE NFileManagerWindows::CreateReadFileHandle (const TCHAR *Filename, DWORD Flags) { DWORD Access = GENERIC_READ; DWORD Create = OPEN_EXISTING; DWORD SharedModeFlags = 0; SharedModeFlags |= (Flags & NSerializer::Read) ? FILE_SHARE_READ : 0; SharedModeFlags |= (Flags & NSerializer::Write) ? FILE_SHARE_WRITE : 0; HANDLE Handle = ::CreateFile (Filename, Access, SharedModeFlags, NULL, Create, FILE_ATTRIBUTE_NORMAL, NULL); if (Handle == INVALID_HANDLE_VALUE) { if (Flags & NSerializer::OutputErrorIfFail) nuxError (TEXT ("Failed to read file: %s"), Filename); } return Handle; } NSerializer *NFileManagerWindows::CreateFileReader (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error) { HANDLE Handle = CreateReadFileHandle (Filename, Flags); if (Handle == INVALID_HANDLE_VALUE) { return 0; } return new NWindowsSerialFileReader (Handle, Error); } HANDLE NFileManagerWindows::CreateWriteFileHandle (const TCHAR *Filename, DWORD Flags) { if (Flags & NSerializer::OverWriteReadOnly) { ::SetFileAttributes (Filename, 0); } DWORD Access = GENERIC_WRITE; DWORD SharedModeFlags = 0; SharedModeFlags |= (Flags & NSerializer::Read) ? FILE_SHARE_READ : 0; SharedModeFlags |= (Flags & NSerializer::Write) ? FILE_SHARE_WRITE : 0; DWORD Create = 0; Create |= (Flags & NSerializer::Append) ? OPEN_ALWAYS : 0; Create |= (Flags & NSerializer::NoOverWrite) ? CREATE_NEW /*fail if the file already exist*/ : CREATE_ALWAYS /*create the file if it does not exist*/; HANDLE Handle = ::CreateFile (Filename, Access, SharedModeFlags, NULL, Create, FILE_ATTRIBUTE_NORMAL, NULL); if (Handle == INVALID_HANDLE_VALUE) { if (Flags & NSerializer::OutputErrorIfFail) { nuxError (TEXT ("[NFileManagerWindows::CreateFileWriter] Failed to create file %s (GetLastError: %d)"), Filename, ::GetLastError() ); } } if ( (Flags & NSerializer::Append) && (Handle != INVALID_HANDLE_VALUE) ) { int Pos = ::SetFilePointer (Handle, 0, 0, FILE_END); } return Handle; } NSerializer *NFileManagerWindows::CreateFileWriter (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error) { HANDLE Handle = CreateWriteFileHandle (Filename, Flags); if (Handle == INVALID_HANDLE_VALUE) { return 0; } return new NWindowsSerialFileWriter (Handle, Error); } /*! @return Size of the File. Return -1 if an error occurs. */ long long NFileManagerWindows::FileSize (const TCHAR *Filename) { HANDLE Handle = ::CreateFile (Filename, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (Handle == INVALID_HANDLE_VALUE) { LPVOID lpMsgBuf = 0; ::FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ::GetLastError(), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); nuxDebugMsg (TEXT ("[NFileManagerWindows::FileSize] Failed to open file %s for attribute read (GetLastError: %d - %s)"), Filename, ::GetLastError(), lpMsgBuf); ::LocalFree (lpMsgBuf); return -1; } long long Size = 0; if (::GetFileSizeEx (Handle, NUX_REINTERPRET_CAST (PLARGE_INTEGER, &Size) ) == 0) { Size = -1; } CloseHandle (Handle); return Size; } bool NFileManagerWindows::FileExist (const TCHAR *Filename) { WIN32_FILE_ATTRIBUTE_DATA FileAttrData; if (::GetFileAttributesEx (Filename, GetFileExInfoStandard, NUX_STATIC_CAST (void *, &FileAttrData) ) ) { return true; } return false; } int NFileManagerWindows::Copy (const TCHAR *DestFile, const TCHAR *SrcFile, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor *Monitor) { // In case file exist and OverWriteReadOnly is true, Remove the ReadOnly attribute from the file. if (OverWriteReadOnly) { ::SetFileAttributes (DestFile, FILE_ATTRIBUTE_NORMAL); } DWORD Flags = (OverWriteExisting ? 0 : COPY_FILE_FAIL_IF_EXISTS); BOOL *pCancel = NULL; if (Monitor) pCancel = & (Monitor->m_bCancel); if (::CopyFileEx (SrcFile, DestFile, NFileTransferMonitor::CopyProgressRoutine, NUX_REINTERPRET_CAST (void *, Monitor), pCancel, Flags) == 0) { LPVOID lpMsgBuf = 0; ::FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ::GetLastError(), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); nuxDebugMsg (TEXT ("[NFileManagerWindows::Copy] Error copying file from '%s' to '%s'(GetLastError: %d - %s)"), SrcFile, DestFile, ::GetLastError(), lpMsgBuf); ::LocalFree (lpMsgBuf); return false; } ::SetFileAttributes (DestFile, FILE_ATTRIBUTE_NORMAL); return true; } bool NFileManagerWindows::Delete (const TCHAR *Filename, bool OverWriteReadOnly) { if (OverWriteReadOnly) { ::SetFileAttributes (Filename, FILE_ATTRIBUTE_NORMAL); } if ( (::DeleteFile (Filename) == 0) && (GetLastError() != ERROR_FILE_NOT_FOUND) ) { LPVOID lpMsgBuf = 0; ::FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ::GetLastError(), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); nuxDebugMsg (TEXT ("[NFileManagerWindows::Delete] Error deleting file '%s' (GetLastError: %d - %s)"), Filename, ::GetLastError(), lpMsgBuf); ::LocalFree (lpMsgBuf); return false; } return true; } bool NFileManagerWindows::IsReadOnly (const TCHAR *Filename) { WIN32_FILE_ATTRIBUTE_DATA FileAttrData; if (::GetFileAttributesEx (Filename, GetFileExInfoStandard, NUX_STATIC_CAST (void *, &FileAttrData) ) ) { return ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0); } else { nuxDebugMsg (TEXT ("[NFileManagerWindows::IsReadOnly]: Error reading attributes for file '%s'"), Filename); } return false; } bool NFileManagerWindows::IsDirectory (const TCHAR *DirectoryName) { WIN32_FILE_ATTRIBUTE_DATA FileAttrData; if (::GetFileAttributesEx (DirectoryName, GetFileExInfoStandard, NUX_STATIC_CAST (void *, &FileAttrData) ) ) { return ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); } else { nuxDebugMsg (TEXT ("[NFileManagerWindows::IsDirectory]: Error reading attributes for directory '%s'"), DirectoryName); } return false; } bool NFileManagerWindows::IsHidden (const TCHAR *Filename) { WIN32_FILE_ATTRIBUTE_DATA FileAttrData; if (::GetFileAttributesEx (Filename, GetFileExInfoStandard, NUX_STATIC_CAST (void *, &FileAttrData) ) ) { return ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0); } else { nuxDebugMsg (TEXT ("[NFileManagerWindows::IsHidden]: Error reading attributes for file '%s'"), Filename); } return false; } /*! @return TRUE is the file exist. */ bool NFileManagerWindows::GetFileAttribute (const TCHAR *Filename, bool &isDirectory, bool &isReadOnly, bool &isHidden, long long &Size) { isDirectory = false; isReadOnly = false; isHidden = false; Size = 0; WIN32_FILE_ATTRIBUTE_DATA FileAttrData; if (::GetFileAttributesEx (Filename, GetFileExInfoStandard, (void *) &FileAttrData) ) { isDirectory = ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); isReadOnly = ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0); isHidden = ( (FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0); Size = FileAttrData.nFileSizeLow | ( (long long) (FileAttrData.nFileSizeHigh) << 32); } else { nuxDebugMsg (TEXT ("[NFileManagerWindows::GetFileAttribute]: Error reading attributes for file '%s'"), Filename); return (0); } return TRUE; } bool NFileManagerWindows::Move (const TCHAR *Dest, const TCHAR *Src, bool Replace, bool EvenIfReadOnly, NFileTransferMonitor *Monitor) { DWORD Flags = MOVEFILE_COPY_ALLOWED | MOVEFILE_FAIL_IF_NOT_TRACKABLE; Flags |= (EvenIfReadOnly ? MOVEFILE_REPLACE_EXISTING : 0); BOOL *pCancel = NULL; if (Monitor) pCancel = & (Monitor->m_bCancel); if (::MoveFileWithProgress (Src, Dest, NFileTransferMonitor::CopyProgressRoutine, NUX_REINTERPRET_CAST (void *, Monitor), Flags) != 0) { nuxDebugMsg (TEXT ("[NFileManagerWindows::Move] Error moving file '%s' to '%s' (GetLastError: %d)"), Src, Dest, ::GetLastError() ); return false; } return true; } bool NFileManagerWindows::MakeDirectory (const TCHAR *Path, bool CreateCompletePath) { if (CreateCompletePath) { return NFileManagerGeneric::MakeDirectory (Path, CreateCompletePath); } if ( (::CreateDirectory (Path, NULL) == 0) && (::GetLastError() != ERROR_ALREADY_EXISTS) ) { nuxDebugMsg (TEXT ("[NFileManagerWindows::MakeDirectory] Error creating directory '%s' (GetLastError: %d)"), Path, ::GetLastError() ); return NUX_ERROR; } return NUX_OK; } bool NFileManagerWindows::DeleteDirectory (const TCHAR *Path, bool DeleteContentFirst) { if (DeleteContentFirst) { return NFileManagerGeneric::DeleteDirectory (Path, DeleteContentFirst); } if ( (::RemoveDirectory (Path) == 0) && (::GetLastError() != ERROR_FILE_NOT_FOUND) ) { nuxDebugMsg (TEXT ("[NFileManagerWindows::DeleteDirectory] Error deleting directory '%s' (GetLastError: %d)"), Path, ::GetLastError() ); return false; } return true; } void NFileManagerWindows::FindFiles (std::vector& Result, const TCHAR *Filename, bool Files, bool Directories) { HANDLE Handle = INVALID_HANDLE_VALUE; WIN32_FIND_DATA SearchData; Handle = ::FindFirstFile (Filename, &SearchData); if (Handle != INVALID_HANDLE_VALUE) { do { if (Stricmp (SearchData.cFileName, TEXT (".") ) && Stricmp (SearchData.cFileName, TEXT ("..") ) && ! (SearchData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) && ! (SearchData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) { if ( (SearchData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? Directories : Files) Result.push_back (std::string(SearchData.cFileName) ); } } while (::FindNextFile (Handle, &SearchData) ); } if (Handle != INVALID_HANDLE_VALUE) ::FindClose (Handle); } void NFileManagerWindows::ListFilesInDirectory (std::vector& Result, const TCHAR *DirName) { WIN32_FIND_DATA SearchData; HANDLE Handle = INVALID_HANDLE_VALUE; std::string DirectoryName = DirName; DirectoryName += TEXT ("\\*"); Handle = ::FindFirstFile (DirectoryName.c_str(), &SearchData); if (Handle != INVALID_HANDLE_VALUE) { // List all the other files in the directory. do { if (Stricmp (SearchData.cFileName, TEXT (".") ) && Stricmp (SearchData.cFileName, TEXT ("..") ) && ! (SearchData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) && ! (SearchData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) { Result.push_back(std::string(SearchData.cFileName)); } } while (::FindNextFile (Handle, &SearchData) ); } if (Handle != INVALID_HANDLE_VALUE) ::FindClose (Handle); } double NFileManagerWindows::GetFileAgeSeconds (const TCHAR *Filename) { struct _stat FileInfo; if (_tstat (Filename, &FileInfo) == 0) { time_t CurrentTime, FileTime; FileTime = FileInfo.st_mtime; time (&CurrentTime); return difftime (CurrentTime, FileTime); } return -1.0; } time_t NFileManagerWindows::GetFileLastModified (const TCHAR *Filename) { struct _stat FileInfo; if (_tstat (Filename, &FileInfo) == 0) { time_t FileTime; FileTime = FileInfo.st_mtime; return FileTime; } return -1; } // bool GetFileLastModified(const TCHAR* Filename, SYSTEMTIME& sysTime, bool bLocalTime) // { // ZeroMemory(&sysTime, sizeof(SYSTEMTIME)); // // DWORD dwAttr = ::GetFileAttributes(Filename); // // // files only // if (dwAttr == 0xFFFFFFFF) // return false; // // WIN32_FIND_DATA findFileData; // HANDLE hFind = ::FindFirstFile((LPTSTR)Filename, &findFileData); // // if (hFind == INVALID_HANDLE_VALUE) // return FALSE; // // ::FindClose(hFind); // // FILETIME ft = findFileData.ftLastWriteTime; // // if (bLocalTime) // ::FileTimeToLocalFileTime(&findFileData.ftLastWriteTime, &ft); // // ::FileTimeToSystemTime(&ft, &sysTime); // return true; // } bool NFileManagerWindows::SetDefaultDirectory() { return CALL_OS_TCHAR_FUNCTION(SetCurrentDirectoryW(GetProgramDirectory()), SetCurrentDirectoryA(TCHAR_TO_ANSI(GetProgramDirectory().c_str()))) != 0; } std::string NFileManagerWindows::GetCurrentDirectory() { #if UNICODE TCHAR Buffer[1024] = TEXT (""); ::GetCurrentDirectoryW (NUX_ARRAY_COUNT (Buffer), Buffer); return std::string(Buffer); #else ANSICHAR Buffer[1024] = ""; ::GetCurrentDirectoryA (NUX_ARRAY_COUNT (Buffer), Buffer); return std::string(Buffer); #endif } bool NFileManagerWindows::GetTimeStamp (const TCHAR *Filename, FileTimeStamp &Timestamp) { Memzero (&Timestamp, sizeof (Timestamp) ); struct _stat FileInfo; if (_tstat (Filename, &FileInfo) == 0) { #ifdef WIN32_SECURE __time64_t FileTime; // FileTime represents seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC). FileTime = FileInfo.st_mtime; tm pTime; // _gmtime64_s can express time up to 23:59:59, December 31, 3000, UTC _gmtime64_s (&pTime, &FileTime); Timestamp.Day = pTime.tm_mday; Timestamp.DayOfWeek = pTime.tm_wday; Timestamp.DayOfYear = pTime.tm_yday; Timestamp.Hour = pTime.tm_hour; Timestamp.Minute = pTime.tm_min; Timestamp.Second = pTime.tm_sec; Timestamp.Year = pTime.tm_year + 1900; #else time_t FileTime; // FileTime represents seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC). FileTime = FileInfo.st_mtime; // gmtime can express time up to 03:14:07 January 19, 2038, UTC tm *pTime = gmtime (&FileTime); Timestamp.Day = pTime->tm_mday; Timestamp.DayOfWeek = pTime->tm_wday; Timestamp.DayOfYear = pTime->tm_yday; Timestamp.Hour = pTime->tm_hour; Timestamp.Minute = pTime->tm_min; Timestamp.Second = pTime->tm_sec; Timestamp.Year = pTime->tm_year + 1900; #endif return TRUE; } return FALSE; } } nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerGNU.cpp0000644000015600001650000004466712656236757024050 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { // Choose the size so it is a power of 2. Example (size-1)= 11111111. const int NGNUSerialFileReader::sBufferSize = 1024; NGNUSerialFileReader::NGNUSerialFileReader (int InFileDescriptor, LogOutputDevice &InError, int InSize) : m_FileDescriptor (InFileDescriptor) , m_Error (InError) , m_FileSize (InSize) , m_FilePos (0) , m_BufferBase (0) , m_BufferCount (0) { m_Buffer = new BYTE[sBufferSize]; } NGNUSerialFileReader::~NGNUSerialFileReader() { NUX_SAFE_DELETE_ARRAY (m_Buffer); if (m_FileDescriptor) { Close(); } } bool NGNUSerialFileReader::Precache (int PrecacheOffset, int PrecacheSize) { // Only pre-cache at current position and avoid work if pre-caching same offset twice. if ( (m_FilePos == PrecacheOffset) && (!m_BufferBase || !m_BufferCount || m_BufferBase != m_FilePos) ) { m_BufferBase = m_FilePos; // (sBufferSize - 1) contains only '1', i.e 1111111111. // So (m_FilePos & (sBufferSize-1)) is equal to m_FilePos if m_FilePos <= (sBufferSize-1). m_BufferCount = Min (Min (PrecacheSize, (int) (sBufferSize - (m_FilePos & (sBufferSize - 1) ) ) ), m_FileSize - m_FilePos); long long Count = 0; //GTotalBytesReadViaFileManager += m_BufferCount; Count = read (m_FileDescriptor, m_Buffer, m_BufferCount); if (Count == 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Precache] Reached end of file while attempting to read %i bytes"), m_BufferCount); } if (Count == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Precache] Read error while attempting to read file: ???") ); } } return TRUE; } long long NGNUSerialFileReader::Seek (long long InPos, NSerializer::SeekPos seekpos) { nuxAssert (InPos >= 0); nuxAssert (InPos <= m_FileSize); Flush(); // Because we precache our reads, we must perform Seek accordingly. long long pos = m_FilePos; long long filepos = 0; // Set the file pointer to m_FilePos. filepos = lseek (m_FileDescriptor, pos, SEEK_SET); if (filepos == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Seek] Seek to %i has failed."), InPos); } // Now the file pointer is current with what we have read so far. pos = InPos; filepos = lseek (m_FileDescriptor, pos, (seekpos == SeekStart) ? SEEK_SET : (seekpos == SeekCurrent) ? SEEK_CUR : SEEK_END); if ( filepos == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Seek] Seek to %i has failed."), InPos); } m_FilePos = filepos; m_BufferBase = 0; m_BufferCount = 0; Precache (m_FilePos, sBufferSize); return filepos; } long long NGNUSerialFileReader::Tell() { // Flush(); // LARGE_INTEGER pos; // LARGE_INTEGER filepos; // pos.QuadPart = 0; // ::SetFilePointerEx(m_FileDescriptor, pos, &filepos, FILE_CURRENT); // return filepos.QuadPart; return m_FilePos; } long long NGNUSerialFileReader::GetFileSize() { return m_FileSize; } bool NGNUSerialFileReader::Close() { if (m_FileDescriptor) { int ret = close (m_FileDescriptor); if (ret == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Close] Error while closing file") ); } } m_FileDescriptor = 0; return !m_ErrorCode; } void NGNUSerialFileReader::SerializeFinal (void *Dest, long long Length) { nuxAssert (Dest); while (Length > 0) { int DataSize = Min (Length, m_BufferBase + m_BufferCount - m_FilePos); if (DataSize == 0) { if (Length >= sBufferSize) { long long Count = 0; //GTotalBytesReadViaFileManager += Length; Count = read (m_FileDescriptor, Dest, Length); if (Count == 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Serialize] Reached end of file while attempting to read %i bytes"), Length); } if (Count == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Serialize] Read error while attempting to read file: ???") ); } m_FilePos += Length; m_BufferBase += Length; return; } Precache (m_FilePos, 0x7FFFFFFF); DataSize = Min (Length, m_BufferBase + m_BufferCount - m_FilePos); if (DataSize <= 0) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("ReadFile beyond EOF %i+%i/%i"), m_FilePos, Length, m_FileSize); } if (m_ErrorCode) return; } Memcpy (Dest, m_Buffer + m_FilePos - m_BufferBase, DataSize); m_FilePos += DataSize; Length -= DataSize; Dest = (BYTE *) Dest + DataSize; } } ////////////////////////////////////////////////////////////////////////// // Choose the size so it is a power of 2. Example (size-1)= 11111111. const int NGNUSerialFileWriter::sBufferSize = 32; NGNUSerialFileWriter::NGNUSerialFileWriter (int InFileDescriptor, LogOutputDevice &InError, int /* InPos */) : m_FileDescriptor (InFileDescriptor) , m_Error (InError) , m_BufferCount (0) { m_Pos = Tell(); m_Buffer = new BYTE[sBufferSize]; } NGNUSerialFileWriter::~NGNUSerialFileWriter() { NUX_SAFE_DELETE_ARRAY (m_Buffer); if (m_FileDescriptor) Close(); m_FileDescriptor = 0; } long long NGNUSerialFileWriter::Seek (long long InPos, NSerializer::SeekPos seekpos) { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); if (m_FileDescriptor == 0) return -1; _Flush(); long long pos = InPos; long long filepos = 0; filepos = lseek (m_FileDescriptor, pos, (seekpos == SeekStart) ? SEEK_SET : (seekpos == SeekCurrent) ? SEEK_CUR : SEEK_END); if (filepos == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileWriter::Seek] Seek to %i has failed."), InPos); } m_Pos = filepos; return filepos; } long long NGNUSerialFileWriter::Tell() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); if (m_FileDescriptor == 0) return -1; _Flush(); long long pos = 0; long long filepos = 0; filepos = lseek (m_FileDescriptor, pos, SEEK_CUR); if (filepos == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileWriter::Tell] Seek to %i has failed."), pos); } return filepos; } bool NGNUSerialFileWriter::Close() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); if (m_FileDescriptor == 0) return true; _Flush(); int ret = close (m_FileDescriptor); if (ret == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileWriter::Close] Error while closing file") ); } m_FileDescriptor = 0; return !m_ErrorCode; } long long NGNUSerialFileWriter::GetFileSize() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); if (m_FileDescriptor == 0) return -1; struct stat sb; if (fstat (m_FileDescriptor, &sb) != 0) { m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileWriter::GetFileSize] Can't get file size.") ); return -1; } return sb.st_size; } void NGNUSerialFileWriter::SerializeFinal (void *V, long long Length) { // This method is not re-entrant by itself. It relies on m_Buffer and other variables // that belong to this object. Therefore, it is not thread safe. We add a critical section // to make it thread safe. NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); nuxAssert (V); NUX_RETURN_IF_NULL (m_FileDescriptor); m_Pos += Length; int FreeSpace; while (Length > (FreeSpace = sBufferSize - m_BufferCount) ) { // m_Buffer is Full. Write it to the file. Memcpy (m_Buffer + m_BufferCount, V, FreeSpace); m_BufferCount += FreeSpace; Length -= FreeSpace; V = (BYTE *) V + FreeSpace; _Flush(); } if (Length) { Memcpy (m_Buffer + m_BufferCount, V, Length); m_BufferCount += Length; // Count the number of Characters stored in m_Buffer. } } void NGNUSerialFileWriter::Flush() { NScopeLock Scope (&m_CriticalSection); nuxAssert (m_FileDescriptor); if (m_FileDescriptor == 0) return; _Flush(); } void NGNUSerialFileWriter::_Flush() { //GTotalBytesWrittenViaFileManager += m_BufferCount; if (m_BufferCount) { long long Result = 0; Result = write (m_FileDescriptor, m_Buffer, m_BufferCount); if (Result == -1) { m_ErrorCode = 1; m_Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileWriter::Flush] Write error.") ); } } m_BufferCount = 0; } ////////////////////////////////////////////////////////////////////////// NUX_IMPLEMENT_GLOBAL_OBJECT (NFileManagerGNU); void NFileManagerGNU::Constructor() { } void NFileManagerGNU::Destructor() { } NSerializer *NFileManagerGNU::CreateFileReader (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error) { int FileDesc = open (TCHAR_TO_ANSI (Filename), O_RDONLY); if (FileDesc == -1) { nuxDebugMsg (TEXT ("[NFileManagerGNU::CreateFileReader] Can't create file reade for: %s"), Filename); if (Flags & NSerializer::OutputErrorIfFail) { nuxError (TEXT ("[NFileManagerGNU::CreateFileReader] Can't open file: %s"), Filename); } return NULL; } struct stat sb; if (fstat (FileDesc, &sb) != 0) { int ret = close (FileDesc); if (ret == -1) { Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NFileManagerGNU::CreateFileReader] Error while closing file descriptor: %s"), Filename); } nuxDebugMsg (TEXT ("[NFileManagerGNU::CreateFileReader] Can't get file descriptor: %s"), Filename); Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NFileManagerGNU::CreateFileReader] Can't get file descriptor: %s"), Filename); return NULL; } return new NGNUSerialFileReader (FileDesc, Error, sb.st_size); } NSerializer *NFileManagerGNU::CreateFileWriter (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error) { if (FileExist (Filename) && (Flags & NSerializer::OverWriteReadOnly) ) { int ret = chmod (TCHAR_TO_ANSI (Filename), S_IRUSR | S_IWUSR); if (ret == -1) { Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NFileManagerGNU::CreateFileWriter] Can't change file mode") ); } } DWORD ModeFlags = 0; if ( (Flags & NSerializer::Read) && (Flags & NSerializer::Write) ) { ModeFlags |= O_RDWR; } else if (Flags & NSerializer::Read) { ModeFlags |= O_RDONLY; } else if (Flags & NSerializer::Write) { ModeFlags |= O_WRONLY; } ModeFlags |= (Flags & NSerializer::Append) ? O_APPEND : O_TRUNC; ModeFlags |= (Flags & NSerializer::NoOverWrite) ? (O_CREAT | O_EXCL) /*fail if the file already exist*/ : O_CREAT /*create the file if it does not exist*/; int FileDesc = open (TCHAR_TO_ANSI (Filename), ModeFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (FileDesc == -1) { if (Flags & NSerializer::OutputErrorIfFail) { nuxError (TEXT ("[NFileManagerGNU::CreateFileWriter] Failed to create file %s."), Filename); } return NULL; } if (Flags & NSerializer::Append) { long long Pos = lseek (FileDesc, 0, SEEK_END); if (Pos == -1) { Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NGNUSerialFileReader::Seek] Seek to %i has failed."), Pos); } } struct stat sb; if (fstat (FileDesc, &sb) != 0) { int ret = close (FileDesc); if (ret == -1) { Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NFileManagerGNU::CreateFileWriter] Error while closing file") ); } Error.LogFunction (NUX_MSG_SEVERITY_NONE, TEXT ("[NFileManagerGNU::CreateFileWriter] Can't create file reader.") ); return NULL; } // The third param is never used. return new NGNUSerialFileWriter (FileDesc, Error, 0); } long long NFileManagerGNU::FileSize (const TCHAR *Filename) { struct stat sb; if (stat (TCHAR_TO_ANSI (Filename), &sb) != 0) { nuxDebugMsg (TEXT ("[NFileManagerGNU::FileSize] Can't get file size") ); return 0; } if (sb.st_mode & S_IFDIR) { // This is a directory return 0; } return sb.st_size; } bool NFileManagerGNU::FileExist (const TCHAR *Filename) { struct stat sb; if (stat (TCHAR_TO_ANSI (Filename), &sb) != 0) { return false; } return true; } int NFileManagerGNU::Copy (const TCHAR *DestFile, const TCHAR *SrcFile, bool OverWriteExisting, bool /* OverWriteReadOnly */, NFileTransferMonitor * /* Monitor */) { size_t nmemb; //int nmemb; FILE *ifp, *ofp; char buf[BUFSIZ]; if (OverWriteExisting) { if (access (DestFile, F_OK) == 0) { //OUTLOG((FUNC, TRWRN, "file %s already exists\n", DestFile)); return false; } else if (errno != ENOENT) { //OUTLOG((FUNC, TRERR, "access(%s, F_OK) failed\n", DestFile)); return false; } } if ( (ifp = fopen (SrcFile, "r") ) == NULL) { //OUTLOG((FUNC, TRERR, "%s doesn't exist\n", SrcFile)); return false; } if ( (ofp = fopen (DestFile, "w+") ) == NULL) { //OUTLOG((FUNC, TRERR, "can't create %s\n", DestFile)); fclose (ifp); return false; } while ( (nmemb = fread (buf, 1, sizeof (buf), ifp) ) > 0) { if (fwrite (buf, 1, nmemb, ofp) != nmemb) { //OUTLOG((FUNC, TRERR, "fwrite failed\n")); fclose (ifp); fclose (ofp); return false; } } fclose (ifp); fclose (ofp); return true; } bool NFileManagerGNU::Delete (const TCHAR *Filename, bool OverWriteReadOnly) { if (OverWriteReadOnly) { chmod (TCHAR_TO_ANSI (Filename), S_IRUSR | S_IWUSR); } if (unlink (TCHAR_TO_ANSI (Filename) ) != 0) { nuxDebugMsg (TEXT ("[NFileManagerGNU::Delete] Error deleting file '%s'."), Filename); return false; } return true; } bool NFileManagerGNU::IsReadOnly (const TCHAR *Filename) { struct stat sb; if (stat (TCHAR_TO_ANSI (Filename), &sb) != 0) { nuxDebugMsg (TEXT ("[NFileManagerGNU::IsReadOnly] Error reading file status '%s'."), Filename); return false; } if ( (sb.st_mode & S_IRUSR) && ! (sb.st_mode & S_IWUSR) ) { return true; } return false; } bool NFileManagerGNU::IsDirectory (const TCHAR *DirectoryName) { struct stat sb; if (stat (TCHAR_TO_ANSI (DirectoryName), &sb) != 0) { nuxDebugMsg (TEXT ("[NFileManagerGNU::IsDirectory] Error reading file status '%s'."), DirectoryName); return false; } if (sb.st_mode & S_IFDIR) { return true; } return false; } bool NFileManagerGNU::IsHidden (const TCHAR * /* Filename */) { return false; } /*! @return TRUE is the file exist. */ bool NFileManagerGNU::GetFileAttribute (const TCHAR *Filename, bool &isDirectory, bool &isReadOnly, bool &isHidden, long long &Size) { isDirectory = false; isReadOnly = false; isHidden = false; Size = 0; struct stat sb; if (stat (TCHAR_TO_ANSI (Filename), &sb) != 0) { return false; } if (sb.st_mode & S_IFDIR) { isDirectory = true; } if ( (sb.st_mode & S_IRUSR) && ! (sb.st_mode & S_IWUSR) ) { isReadOnly = true; } Size = sb.st_mode; return true; } bool NFileManagerGNU::Move (const TCHAR * /* Dest */, const TCHAR * /* Src */, bool /* OverWriteExisting */, bool /* OverWriteReadOnly */, NFileTransferMonitor * /* Monitor */) { nuxAssert (0); return false; } bool NFileManagerGNU::MakeDirectory (const TCHAR *Path, bool CreateCompletePath) { if (CreateCompletePath) { return NFileManagerGeneric::MakeDirectory (Path, CreateCompletePath); } mkdir (TCHAR_TO_ANSI (Path), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); // EEXIST = -2147418092 = 0x80010014 // if((errno != 0) && (errno != EEXIST)) // { // nuxDebugMsg(TEXT("[NFileManagerGNU::MakeDirectory] Error creating directory '%s'."), Path); // return NUX_ERROR; // } return NUX_OK; } bool NFileManagerGNU::DeleteDirectory (const TCHAR * /* Path */, bool /* DeleteContentFirst */) { // if(DeleteContentFirst) // { // return NFileManagerGeneric::DeleteDirectory(Path, DeleteContentFirst); // } // if((::RemoveDirectory(Path) == 0) && (::GetLastError() != ERROR_FILE_NOT_FOUND)) // { // nuxDebugMsg(TEXT("[NFileManagerWindows::DeleteDirectory] Error deleting directory '%s' (GetLastError: %d)"), Path, ::GetLastError()); // return false; // } return true; } } nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerGeneric.cpp0000644000015600001650000001636412656236757024764 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Math/MathUtility.h" namespace nux { #define COPYBLOCKSIZE 32768 int NFileManagerGeneric::Copy (const TCHAR *InDestFile, const TCHAR *InSrcFile, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor *Monitor) { // Direct file copier. if (Monitor && !Monitor->Progress (0.0) ) { return COPY_CANCELED; } int Result = COPY_OK; std::string SrcFile = InSrcFile; std::string DestFile = InDestFile; NSerializer *Src = CreateFileReader (SrcFile.c_str() ); if (!Src) { Result = COPY_READFAIL; } else { unsigned int Size = Src->GetFileSize(); NSerializer *Dest = CreateFileWriter (DestFile.c_str(), (OverWriteExisting ? 0 : FILEWRITE_NOREPLACEEXISTING) | (OverWriteReadOnly ? FILEWRITE_EVENIFREADONLY : 0) ); if (!Dest) { Result = COPY_WRITEFAIL; } else { unsigned int Percent = 0, NewPercent = 0; BYTE Buffer[COPYBLOCKSIZE]; for (unsigned int Total = 0; Total < Size; Total += sizeof (Buffer) ) { unsigned int Count = Min (Size - Total, (unsigned int) sizeof (Buffer) ); Src->Serialize (Buffer, Count); if (Src->IsError() ) { Result = COPY_READFAIL; break; } Dest->Serialize (Buffer, Count); if (Dest->IsError() ) { Result = COPY_WRITEFAIL; break; } NewPercent = Total * 100 / Size; if (Monitor && Percent != NewPercent && !Monitor->Progress ( (float) NewPercent / 100.f) ) { Result = COPY_CANCELED; break; } Percent = NewPercent; } if (Result == COPY_OK) { if (!Dest->Close() ) { Result = COPY_WRITEFAIL; } } delete Dest; if (Result != COPY_OK) { Delete (DestFile.c_str() ); } } if (Result == COPY_OK) { if (!Src->Close() ) { Result = COPY_READFAIL; } } delete Src; } if (Monitor && Result == COPY_OK && !Monitor->Progress (1.0) ) { Result = COPY_CANCELED; } return Result; } bool NFileManagerGeneric::IsDrive (const TCHAR *Path) { // Does Path refer to a drive letter or UNC path? // A UNC is a naming convention that permits you to use a network resource, // such as a network server, without formally connecting to the network resource // with a mapped drive. A UNC path uses the following syntax: // \\\ // The share is a drive: D:\Folder of ServerA = "\\ServerA\D\Folder" if (Stricmp (Path, TEXT ("") ) == 0) return 1; else if ( (ToUpperCase (Path[0]) != ToLowerCase (Path[0]) ) && (Path[1] == TEXT (':') ) && (Path[2] == 0) ) // look for "a:", "c:", "d:" ... return 1; else if (Stricmp (Path, TEXT ("\\") ) == 0) // look for "\" return 1; else if (Stricmp (Path, TEXT ("\\\\") ) == 0) // look for "\\" return 1; else if (Path[0] == TEXT ('\\') && Path[1] == TEXT ('\\') && !Strchr (Path + 2, TEXT ('\\') ) ) // look for "\\Server" return 1; else if (Path[0] == TEXT ('\\') && Path[1] == TEXT ('\\') && Strchr (Path + 2, TEXT ('\\') ) && !Strchr (Strchr (Path + 2, TEXT ('\\') ) + 1, TEXT ('\\') ) ) // look for "\\Server\share" return 1; else return 0; } bool NFileManagerGeneric::MakeDirectory (const TCHAR *Path, bool /* CreateCompletePath */) { // Support code for making a directory tree. unsigned int SlashCount = 0, CreateCount = 0; for (TCHAR Full[256] = TEXT (""), *Ptr = Full; ; *Ptr++ = *Path++) { if ( (*Path == NUX_BACKSLASH_CHAR) || (*Path == NUX_SLASH_CHAR) || (*Path == 0) ) { if ( (SlashCount++ > 0) && !IsDrive (Full) ) { *Ptr = 0; if (MakeDirectory (Full, 0) != NUX_OK) return 0; CreateCount++; } } if (*Path == 0) break; } return CreateCount != 0; } bool NFileManagerGeneric::DeleteDirectory (const TCHAR *Path, bool /* DeleteContentFirst */) { nuxAssert (Path != NULL); size_t PathLength = StringLength (Path); if (PathLength == 0) return false; std::string WildcardPath = std::string (Path); if ( (WildcardPath[PathLength - 1] != NUX_BACKSLASH_CHAR) && (WildcardPath[PathLength - 1] != NUX_SLASH_CHAR) ) WildcardPath += NUX_BACKSLASH_CHAR; WildcardPath += TEXT ("*"); std::vector List; FindFiles (List, WildcardPath.c_str(), 1, 0); for (unsigned int i = 0; i < List.size(); i++) { if (!Delete ((std::string (Path) + NUX_BACKSLASH_CHAR + List[i]).c_str(), 1) ) return 0; } List.clear(); FindFiles (List, WildcardPath.c_str(), 0, 1); for (unsigned int i = 0; i < List.size(); i++) { if (!DeleteDirectory ((std::string (Path) + NUX_BACKSLASH_CHAR + List[i]).c_str(), true) ) return 0; } List.clear(); return DeleteDirectory (Path, false); } bool NFileManagerGeneric::Move (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor * /* Monitor */) { // Move file manually. if (Copy (Dest, Src, OverWriteExisting, OverWriteReadOnly, NULL) != COPY_OK) return 0; Delete (Src, 1); return 1; } int NFileManagerGeneric::CreateUniqueFileName (const TCHAR *Filename, const TCHAR *Extension, std::string &OutputFilename, unsigned int BaseIndex) { nuxAssert (Filename); nuxAssert (Extension); std::string FullPath (Filename); const size_t IndexMarker = FullPath.length(); // Marks location of the four-digit index. FullPath += TEXT ("0000."); FullPath += Extension; // Iterate over indices, searching for a file that doesn't exist. for (DWORD i = BaseIndex + 1 ; i < 10000 ; ++i) { FullPath[IndexMarker ] = i / 1000 + TEXT ('0'); FullPath[IndexMarker+1] = (i / 100) % 10 + TEXT ('0'); FullPath[IndexMarker+2] = (i / 10) % 10 + TEXT ('0'); FullPath[IndexMarker+3] = i % 10 + TEXT ('0'); if (GFileManager.FileSize (FullPath.c_str() ) == -1) { // The file doesn't exist; output success. OutputFilename = FullPath; return static_cast (i); } } // Can't find an empty filename slot with index in (StartVal, 9999]. return -1; } } nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerWindows.h0000644000015600001650000001205512656236757024500 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NFILEMANAGERWINDOWS_H #define NFILEMANAGERWINDOWS_H /*----------------------------------------------------------------------------- File Manager. -----------------------------------------------------------------------------*/ // File manager. namespace nux { class NWindowsSerialFileReader: public NSerializer { public: NWindowsSerialFileReader (HANDLE InHandle, LogOutputDevice &InError); ~NWindowsSerialFileReader(); virtual bool Precache (int PrecacheOffset, int PrecacheSize); virtual long long Seek (long long InPos, NSerializer::SeekPos seekpos); virtual long long Tell(); virtual long long GetFileSize(); virtual bool Close(); virtual void SerializeFinal (void *V, long long Length); virtual bool isReader() { return true; } virtual bool isWriter() { return false; } protected: HANDLE m_FileHandle; LogOutputDevice &m_Error; long long m_FileSize; long long m_FilePos; long long m_BufferBase; int m_BufferCount; BYTE *m_Buffer; static const int sBufferSize; }; class NWindowsSerialFileWriter : public NSerializer { public: NWindowsSerialFileWriter (HANDLE InHandle, LogOutputDevice &InError); ~NWindowsSerialFileWriter(); virtual long long Seek (long long InPos, NSerializer::SeekPos seekpos); virtual long long Tell(); virtual bool Close(); virtual void SerializeFinal (void *V, long long Length); virtual void Flush(); virtual long long GetFileSize(); virtual bool isReader() { return false; } virtual bool isWriter() { return true; } protected: void _Flush(); HANDLE m_FileHandle; LogOutputDevice &m_Error; long long m_Pos; int m_BufferCount; BYTE *m_Buffer; static const int sBufferSize; NCriticalSection m_CriticalSection; }; class NFileManagerWindows : public NFileManagerGeneric { NUX_DECLARE_GLOBAL_OBJECT (NFileManagerWindows, GlobalSingletonInitializer); public: // Flags is a combination of // NSerializer::OutputErrorIfFail // NSerializer::NoOverWrite // NSerializer::OverWriteReadOnly // NSerializer::Unbuffered // NSerializer::Append // NSerializer::Read virtual NSerializer *CreateFileReader (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error = GNullDevice); virtual NSerializer *CreateFileWriter (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error = GNullDevice); HANDLE CreateReadFileHandle (const TCHAR *Filename, DWORD Flags); HANDLE CreateWriteFileHandle (const TCHAR *Filename, DWORD Flags); /*! @return Size of the File. Return -1 if an error occurs. */ long long FileSize (const TCHAR *Filename); bool FileExist (const TCHAR *Filename); int Copy (const TCHAR *DestFile, const TCHAR *SrcFile, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor *Monitor); bool Move (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting = true, bool OverWriteReadOnly = false, NFileTransferMonitor *Monitor = NULL); bool Delete (const TCHAR *Filename, bool OverWriteReadOnly = false); bool IsReadOnly (const TCHAR *Filename); bool IsDirectory (const TCHAR *DirectoryName); bool IsHidden (const TCHAR *Filename); /*! @return TRUE is the file exist. */ bool GetFileAttribute (const TCHAR *Filename, bool &isDirectory, bool &isReadOnly, bool &isHidden, long long &Size); bool MakeDirectory (const TCHAR *Path, bool CreateCompletePath = false); bool DeleteDirectory (const TCHAR *Path, bool DeleteContentFirst = false); void FindFiles (std::vector& Result, const TCHAR *Filename, bool Files, bool Directories); void ListFilesInDirectory (std::vector& Result, const TCHAR *DirName); double GetFileAgeSeconds (const TCHAR *Filename); time_t GetFileLastModified (const TCHAR *Filename); bool GetFileLastModified (const TCHAR *Filename, SYSTEMTIME &sysTime, bool bLocalTime); bool SetDefaultDirectory(); std::string GetCurrentDirectory(); bool GetTimeStamp (const TCHAR *Filename, FileTimeStamp &Timestamp); }; } #endif // NFILEMANAGERWINDOWS_H nux-4.0.8+16.04.20160209/NuxCore/FileManager/NSerializer.h0000644000015600001650000001536012656236757023066 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NSERIALIZER_H #define NSERIALIZER_H namespace nux { class NSerializer { public: enum { OutputErrorIfFail = 0x01, NoOverWrite = 0x02, OverWriteReadOnly = 0x04, Unbuffered = 0x08, Append = 0x10, Read = 0x20, Write = 0x40, }; typedef enum { SeekStart = 0x00, SeekCurrent = 0x01, SeekEnd = 0x02, } SeekPos; // NSerializer interface. virtual ~NSerializer() {} virtual void SerializeFinal (void *V, long long Length) = 0; // template // void SerializeBuffer( T* buffer, unsigned long long NumberOfElements, unsigned long long ElementSize = sizeof(T)) // { // for(unsigned long long i = 0; i < NumberOfElements; i++) // { // unsigned char* bytebuffer = (unsigned char*)(&buffer[i]); // Serialize(bytebuffer, ElementSize); // } // } virtual bool isReader() = 0; virtual bool isWriter() = 0; virtual long long Tell() = 0; virtual long long GetFileSize() { return -1; } virtual long long Seek (long long FilePos, NSerializer::SeekPos) = 0; virtual bool Precache (INT /* PrecacheOffset */, INT /* PrecacheSize */) { return TRUE; } virtual void Flush() {}; virtual bool Close() = 0; virtual bool GetError() { return m_ErrorCode; } NSerializer &ByteOrderSerialize (void *V, INT Length ) { BOOL SwapBytes = 0; if ( SwapBytes ) { // Transferring between memory and file, so flip the byte order. for ( INT i = Length - 1; i >= 0; i-- ) Serialize ( (unsigned char *) V + i, 1 ); } else { // Transferring around within memory, so keep the byte order. Serialize ( (unsigned char *) V, Length); } return *this; } // Constructor. NSerializer() { Reset(); } NUX_INLINE bool IsError() const { return m_ErrorCode; } virtual void Serialize (char &data); virtual void Serialize (wchar_t &data); virtual void Serialize (bool &data); virtual void Serialize (unsigned char &data); virtual void Serialize (unsigned short &data); virtual void Serialize (short &data); virtual void Serialize (unsigned int &data); virtual void Serialize (int &data); virtual void Serialize (long &data); virtual void Serialize (unsigned long &data); virtual void Serialize (float &data); virtual void Serialize (double &data); virtual void Serialize (unsigned long long &data); virtual void Serialize (long long &data); virtual void Serialize (wchar_t *buffer, unsigned int len, unsigned int stride = sizeof (wchar_t) ); virtual void Serialize (bool *buffer, unsigned int len, unsigned int stride = sizeof (bool) ); virtual void Serialize (char *buffer, unsigned int len, unsigned int stride = sizeof (char) ); virtual void Serialize (unsigned char *buffer, unsigned int len, unsigned int stride = sizeof (unsigned char) ); virtual void Serialize (unsigned short *buffer, unsigned int len, unsigned int stride = sizeof (unsigned short) ); virtual void Serialize (short *buffer, unsigned int len, unsigned int stride = sizeof (short) ); virtual void Serialize (unsigned int *buffer, unsigned int len, unsigned int stride = sizeof (unsigned int) ); virtual void Serialize (int *buffer, unsigned int len, unsigned int stride = sizeof (int) ); virtual void Serialize (long *buffer, unsigned int len, unsigned int stride = sizeof (long) ); virtual void Serialize (unsigned long *buffer, unsigned int len, unsigned int stride = sizeof (unsigned long) ); virtual void Serialize (float *buffer, unsigned int len, unsigned int stride = sizeof (float) ); virtual void Serialize (double *buffer, unsigned int len, unsigned int stride = sizeof (double) ); virtual void Serialize (unsigned long long *buffer, unsigned int len, unsigned int stride = sizeof (unsigned long long) ); virtual void Serialize (long long *buffer, unsigned int len, unsigned int stride = sizeof (long long) ); virtual void Identify (const char* /* name */) {}; virtual void Begin() {}; virtual void End() {}; protected: void Reset (void) { m_ErrorCode = FALSE; } bool m_ErrorCode; }; NUX_INLINE NSerializer &operator << (NSerializer &Sr, bool &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, char &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, unsigned char &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, unsigned short &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, short &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, unsigned int &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, int &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, long &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, unsigned long &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, float &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, double &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, unsigned long long &v) { Sr.Serialize (v); return Sr; } NUX_INLINE NSerializer &operator << (NSerializer &Sr, long long &v) { Sr.Serialize (v); return Sr; } } #endif // NSERIALIZER_H nux-4.0.8+16.04.20160209/NuxCore/FileManager/NFileManagerGNU.h0000644000015600001650000001205212656236757023474 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NFILEMANAGERGNU_H #define NFILEMANAGERGNU_H #include /*----------------------------------------------------------------------------- File Manager. -----------------------------------------------------------------------------*/ namespace nux { // File manager. class NGNUSerialFileReader : public NSerializer { public: NGNUSerialFileReader (int InFileDescriptor, LogOutputDevice &InError, int InSize); ~NGNUSerialFileReader(); virtual bool Precache (int PrecacheOffset, int PrecacheSize); virtual long long Seek (long long InPos, NSerializer::SeekPos seekpos); virtual long long Tell(); virtual long long GetFileSize(); virtual bool Close(); virtual void SerializeFinal (void *V, long long Length); virtual bool isReader() { return true; } virtual bool isWriter() { return false; } protected: int m_FileDescriptor; LogOutputDevice &m_Error; long long m_FileSize; long long m_FilePos; long long m_BufferBase; int m_BufferCount; BYTE *m_Buffer; static const int sBufferSize; }; class NGNUSerialFileWriter : public NSerializer { public: NGNUSerialFileWriter (int InFileDescriptor, LogOutputDevice &InError, int InPos); ~NGNUSerialFileWriter(); virtual long long Seek (long long InPos, NSerializer::SeekPos seekpos); virtual long long Tell(); virtual bool Close(); virtual void SerializeFinal (void *V, long long Length); virtual void Flush(); virtual long long GetFileSize(); virtual bool isReader() { return false; } virtual bool isWriter() { return true; } protected: void _Flush(); int m_FileDescriptor; LogOutputDevice &m_Error; long long m_Pos; int m_BufferCount; BYTE *m_Buffer; static const int sBufferSize; NCriticalSection m_CriticalSection; }; class NFileManagerGNU : public NFileManagerGeneric { NUX_DECLARE_GLOBAL_OBJECT (NFileManagerGNU, GlobalSingletonInitializer); public: // Flags is a combination of // NSerializer::OutputErrorIfFail // NSerializer::NoOverWrite // NSerializer::OverWriteReadOnly // NSerializer::Unbuffered // NSerializer::Append // NSerializer::Read virtual NSerializer *CreateFileReader (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error = GNullDevice); virtual NSerializer *CreateFileWriter (const TCHAR *Filename, DWORD Flags, LogOutputDevice &Error = GNullDevice); /*! @return Size of the File. Return -1 if an error occurs. */ long long FileSize (const TCHAR *Filename); bool FileExist (const TCHAR *Filename); int Copy (const TCHAR *DestFile, const TCHAR *SrcFile, bool OverWriteExisting, bool OverWriteReadOnly, NFileTransferMonitor *Monitor); bool Move (const TCHAR *Dest, const TCHAR *Src, bool OverWriteExisting = true, bool OverWriteReadOnly = false, NFileTransferMonitor *Monitor = NULL); bool Delete (const TCHAR *Filename, bool OverWriteReadOnly = false); bool IsReadOnly (const TCHAR *Filename); bool IsDirectory (const TCHAR *DirectoryName); bool IsHidden (const TCHAR *Filename); /*! @return TRUE is the file exist. */ bool GetFileAttribute (const TCHAR *Filename, bool &isDirectory, bool &isReadOnly, bool &isHidden, long long &Size); bool MakeDirectory (const TCHAR *Path, bool CreateCompletePath = false); bool DeleteDirectory (const TCHAR *Path, bool DeleteContentFirst = false); void FindFiles(std::vector& /* Result */, const TCHAR* /* Filename */, bool /* Files */, bool /* Directories */) {}; void ListFilesInDirectory (std::vector& /* Result */, const TCHAR* /* DirName */) {}; double GetFileAgeSeconds (const TCHAR* /* Filename */) { return 0; }; time_t GetFileLastModified (const TCHAR * /* Filename */) { return 0; }; bool SetDefaultDirectory() { return false; }; std::string GetCurrentDirectory() { return std::string(); }; bool GetTimeStamp (const TCHAR * /* Filename */, FileTimeStamp & /* Timestamp */) { return false; }; }; } #endif // NFILEMANAGERGNU_H nux-4.0.8+16.04.20160209/NuxCore/NuxCore.h0000644000015600001650000011173212656236757020050 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NUXCORE_H #define NUXCORE_H #include "System.h" #include // (assert.h) #include // (ctype.h) #include // (errno.h) #include // (float.h) #include // (iso646.h) #include // (limits.h) #include // (locale.h) #include // (math.h) //#include // (setjmp.h) conflict with libpng on GNU systems //#include // (signal.h) #include // (stdarg.h) #include // (stddef.h) #include // (stdio.h) #include // (stdlib.h) #include // (string.h) #include // (time.h) #include // (wchar.h) #include // (wctype.h) #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // WIN32_SECURE if define for the latest version of Visual Studio starting at VS 2005. We use it for security improvement. #if (defined NUX_VISUAL_STUDIO_2005) || (defined NUX_VISUAL_STUDIO_2008) || (defined NUX_VISUAL_STUDIO_2010) #define WIN32_SECURE #endif #define NUX_STATIC_CAST(a, b) static_cast(b) #define NUX_REINTERPRET_CAST(a, b) reinterpret_cast(b) #define NUX_CONST_CAST(a, b) const_cast(b) #define NUX_DYNAMIC_CAST(a, b) dynamic_cast(b) #define NUX_INVALID_INDEX -1 #define NUX_INVALID_HANDLE -1 #define NUX_IN #define NUX_OUT #define NUX_MAKEFOURCHARTAG(ch0, ch1, ch2, ch3) \ ((DWORD)(BYTE)(ch0) | \ ((DWORD)(BYTE)(ch1) << 8) | \ ((DWORD)(BYTE)(ch2) << 16) | \ ((DWORD)(BYTE)(ch3) << 24 )) #define INLNEW new #define INLDELETE delete #define INLDELETEARRAY delete [] #define NUX_RUNTIME_ERROR(str, ...) LogOutputErrorMessage(__FILE__, __LINE__, str, ##__VA_ARGS__); #define NUX_ERROR_IF_NULL(test, str, ...) if((test) == 0) LogOutputErrorMessage(__FILE__, __LINE__, str, ##__VA_ARGS__); #define NUX_ERROR_IF_TRUE(test, str, ...) if(test) LogOutputErrorMessage(__FILE__, __LINE__, str, ##__VA_ARGS__); #define NUX_ERROR_IF_FALSE(test, str, ...) if(!(test)) LogOutputErrorMessage(__FILE__, __LINE__, str, ##__VA_ARGS__); #define NUX_RETURN_IF_NULL(test) if((test) == 0) return; #define NUX_RETURN_IF_NOTNULL(test) if((test) != 0) return; #define NUX_RETURN_IF_TRUE(test) if(test) return; #define NUX_RETURN_IF_FALSE(test) if(!(test)) return; #define NUX_RETURN_IF_FAIL(test) if(!(test)) return; #define NUX_RETURN_VALUE_IF_NULL(test, value) if((test) == 0) return value; #define NUX_RETURN_VALUE_IF_NOTNULL(test, value) if((test) != 0) return value; #define NUX_RETURN_VALUE_IF_TRUE(test, value) if(test) return value; #define NUX_RETURN_VALUE_IF_FALSE(test, value) if(!(test)) return value; // Structure Alignment #if defined(NUX_MICROSOFT_COMPILER) #define NUX_DATA_ALIGN(declaration, alignment) __declspec(align(alignment)) declaration #elif defined (NUX_GNUCPP_COMPILER) #define NUX_DATA_ALIGN(declaration, alignment) declaration __attribute__ ((aligned (alignment))) #endif // Sizeof is a compile time function. So array must be totally defined if sizeof is used on it. // The number of elements in array must be a constant at compile time. // Example: int array[10] is valid. #define NUX_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0])) // Compiler specific include. #if defined(NUX_OS_WINDOWS) && defined (NUX_MICROSOFT_COMPILER) #include "SystemWindows.h" #elif defined (NUX_OS_LINUX) && defined (NUX_GNUCPP_COMPILER) #include "SystemGNU.h" #elif defined (NUX_OS_MACOSX) && defined (NUX_GNUCPP_COMPILER) #error Unknown Compiler #else #error Unknown Compiler #endif namespace nux { // Variable arguments. unsigned int GetVariableArgs (TCHAR *Dest, unsigned int Size, unsigned int Count, const TCHAR*& Fmt, va_list ArgPtr); unsigned int GetVariableArgsAnsi (ANSICHAR *Dest, unsigned int Size, unsigned int Count, const ANSICHAR*& Fmt, va_list ArgPtr); #define GET_VARARGS(msg, size, len, fmt) \ { \ va_list arg_list; \ va_start(arg_list,fmt); \ VSNTPRINTF_S( msg, size, len, fmt, arg_list ); \ va_end( arg_list ); \ } #define GET_VARARGS_ANSI(msg, size, len, fmt) \ { \ va_list arg_list; \ va_start(arg_list,fmt); \ VSNPRINTF_S( msg, size, len, fmt, arg_list ); \ va_end( arg_list ); \ } #define GET_VARARGS_RESULT(msg, size, len, fmt, result) \ { \ va_list arg_list; \ va_start(arg_list, fmt); \ result = GetVariableArgs(msg, size, len, fmt, arg_list); \ va_end(arg_list); \ } ////////////////////////////////////////////////////////////////////////// // Check macros for assertions. // ////////////////////////////////////////////////////////////////////////// typedef enum { NUX_MSG_SEVERITY_CRITICAL = 0, NUX_MSG_SEVERITY_ALERT = 1, NUX_MSG_SEVERITY_WARNING = 2, NUX_MSG_SEVERITY_INFO = 3, NUX_MSG_SEVERITY_NONE = 4, } MessageSeverity; #define nuxOkMsg(str, ...) { nux::LogOutputSeverityMessage(nux::NUX_MSG_SEVERITY_INFO, str, ##__VA_ARGS__);} #define nuxWarningMsg(str, ...) { nux::LogOutputSeverityMessage(nux::NUX_MSG_SEVERITY_WARNING, str, ##__VA_ARGS__);} #define nuxAlertMsg(str, ...) { nux::LogOutputSeverityMessage(nux::NUX_MSG_SEVERITY_ALERT, str, ##__VA_ARGS__);} #define nuxCriticalMsg(str, ...) { nux::LogOutputSeverityMessage(nux::NUX_MSG_SEVERITY_CRITICAL, str, ##__VA_ARGS__);} #ifdef NUX_ENABLE_ASSERT_MACROS #define nuxAssert(expr) { if(!(expr)) nuxFailAssert(TEXT(#expr)); } // Expression is always evaluated no matter if NUX_ENABLE_ASSERT_MACROS is enabled. nuxFailAssert is called if enabled. #define nuxVerifyExpr(expr) { if(!(expr)) nuxFailAssert(TEXT(#expr)); } #define DEBUGTRACE(str, ...) nuxDebugMsg(str, ##__VA_ARGS__) #ifdef NUX_VARIADIC_MACROS_SUPPORT #define nuxFailAssert(str, ...) { if(nuxIsDebuggerPresent()){nux::LogOutputAssertMessage(__FILE__, __LINE__, str, ##__VA_ARGS__);} inlDebugBreak();} #define nuxError(str, ...) { if(nuxIsDebuggerPresent()){nux::LogOutputErrorMessage(__FILE__, __LINE__, str, ##__VA_ARGS__);} inlDebugBreak();} #define nuxDebugMsg(str, ...) { if(nuxIsDebuggerPresent()) nux::LogOutputDebugMessage(str, ##__VA_ARGS__);} #define nuxAssertMsg(expr, a, ...) { if(!(expr)) nuxFailAssert( TEXT(#expr) TEXT(" : ") a, ##__VA_ARGS__); } #define nuxVerifyExprMsg(expr, a, ...) { if(!(expr)) nuxFailAssert( TEXT(#expr) TEXT(" : ") a, ##__VA_ARGS__); } // Expression is always evaluated. nuxFailAssert is called if enabled. #else #define nuxFailAssert(a,b,c,d,e,f,g,h,i,j,k,l) { if(nuxIsDebuggerPresent()){nux::LogOutputAssertMessage(__FILE__,__LINE__,VARG(a),VARG(b),VARG(c),VARG(d),VARG(e),VARG(f),VARG(g),VARG(h),VARG(i),VARG(j),VARG(k),VARG(l));} inlDebugBreak();} #define nuxError(a,b,c,d,e,f,g,h,i,j,k,l) { if(nuxIsDebuggerPresent()) {nux::LogOutputErrorMessage(__FILE__,__LINE__,VARG(a),VARG(b),VARG(c),VARG(d),VARG(e),VARG(f),VARG(g),VARG(h),VARG(i),VARG(j),VARG(k),VARG(l));} inlDebugBreak();} #define nuxAssertMsg(expr,a,b,c,d,e,f,g,h,i,j,k,l) { if(!(expr)) { nuxFailAssert( TEXT(#expr) TEXT(" : ") a,b,c,d,e,f,g,h,i,j,k,l); } } #define nuxVerifyExprMsg(expr,a,b,c,d,e,f,g,h,i,j,k,l) { if(!(expr)) { nuxFailAssert( TEXT(#expr) TEXT(" : ") a,b,c,d,e,f,g,h,i,j,k,l); } } // Expression is always evaluated. nuxFailAssert is called if enabled. #define nuxDebugMsg(a,b,c,d,e,f,g,h,i,j,k,l) { if(nuxIsDebuggerPresent() && LogOutputRedirector::Ready()) GLogDevice.LogFunction(a,b,c,d,e,f,g,h,i,j,k,l); } #endif // Break if codepaths should never be reached. #define nuxAssertNoEntry() { nuxFailAssert( TEXT("This section of code should not be executed.") ); } // Break if codepaths should not be executed more than once. #define nuxAssertNoReEntry() \ { \ static bool s_inlRuntimeHasBeenHere##__LINE__ = false; \ nuxAssertMsg( !s_inlRuntimeHasBeenHere##__LINE__, TEXT("This section of code has already been called.") ); \ s_inlRuntimeHasBeenHere##__LINE__ = true; \ } class NRecursionScopeCounter { public: NRecursionScopeCounter (WORD &InCounter) : Counter ( InCounter ) { ++Counter; } ~NRecursionScopeCounter() { --Counter; } private: WORD &Counter; }; // Break if codepaths should never be called recursively. #define nuxAssertNoRecursion() \ static WORD RecursionCounter##__LINE__ = 0; \ nuxAssertMsg( RecursionCounter##__LINE__ == 0, TEXT("This section of code was entered recursively.") ); \ const NRecursionScopeCounter ScopeMarker##__LINE__( RecursionCounter##__LINE__ ) // Compile time assertion. Break if the assertion fails. // @param expr Must be evaluated at compile time. #define nuxAssertAtCompileTime(expr) typedef BYTE CompileTimeCheckType##__LINE__[(expr) ? 1 : -1] #else #ifdef NUX_MICROSOFT_COMPILER #define nuxAssert(expr) NUX_NOOP #define nuxVerifyExpr(expr) { if(!(expr)) {} } #define nuxDebugMsg(a, ...) NUX_NOOP #ifdef NUX_VARIADIC_MACROS_SUPPORT #define nuxAssertMsg(expr, a, ...) NUX_NOOP #define nuxVerifyExprMsg(expr, a, ...) { if(!(expr)) {} } #define nuxError(a, ...) NUX_NOOP #else #define nuxAssertMsg(expr,a,b,c,d,e,f,g,h,i,j,k,l) NUX_NOOP #define nuxVerifyExprMsg(expr,a,b,c,d,e,f,g,h,i,j,k,l) { if(!(expr)) {} } #define nuxError(a,b,c,d,e,f,g,h,i,j,k,l) NUX_NOOP #endif #define nuxAssertNoEntry() NUX_NOOP #define nuxAssertNoReentry() NUX_NOOP #define nuxAssertNoRecursion() NUX_NOOP #define nuxAssertAtCompileTime(expr) NUX_NOOP #else #define nuxDebugMsg(a, ...) #define nuxError(a, ...) {} #define nuxAssert(expr) {} #define nuxVerifyExpr(expr) { if(!(expr)) {} } #define nuxAssertMsg(expr,msg, ...) {} #define nuxVerifyExprMsg(expr, a, ...) { if(!(expr)) {} } #define nuxAssertNoEntry() {} #define nuxAssertNoReentry() {} #define nuxAssertNoRecursion() {} #define nuxAssertAtCompileTime(expr) {} #endif #endif ////////////////////////////////////////////////////////////////////////// // String conversion classes // ////////////////////////////////////////////////////////////////////////// #ifndef _UNICODE #define CALL_OS_TCHAR_FUNCTION(funcW,funcA) funcA #define TCHAR_TO_ANSI(str) str #define ANSI_TO_TCHAR(str) (const TCHAR*)((const ANSICHAR*)str) #define UTF8ToTCHAR(str) str #define TCHARToUTF8(str) str #define UTF16ToTCHAR(str) (const char*)NUTF8(str) #define TCHARToUTF16(str) (const wchar_t*)NUTF16(str) #else #define CALL_OS_TCHAR_FUNCTION(funcW,funcA) funcW /*! NOTE: Theses macros creates objects with very short lifespan. They are meant to be used as parameters to functions. Do not assign a variable to the content of the converted string as the object will go out of scope and the string released. Usage: SomeApi(TCHAR_TO_ANSI(SomeUnicodeString)); const char* SomePointer = TCHAR_TO_ANSI(SomeUnicodeString); <--- Bad!!! */ #define TCHAR_TO_ANSI(str) (ANSICHAR*)typedef NCharacterConversion((const TCHAR*)str) #define ANSI_TO_TCHAR(str) (TCHAR*)NCharacterConversion((const ANSICHAR*)str) #define UTF8ToTCHAR(str) (const wchar_t*)NUTF16(str) #define TCHARToUTF8(str) (const char*)NUTF8(str) #define UTF16ToTCHAR(str) str #define TCHARToUTF16(str) str #endif #define inlUTF16ToUTF8(s) (const char*)nux::NUTF8(s) #define inlUTF8ToUTF16(s) (const wchar_t*)nux::NUTF16(s) #define ANSICHAR_TO_UNICHAR(str) (UNICHAR*) nux::NCharacterConversion ((const ANSICHAR*)str) #define UNICHAR_TO_ANSICHAR(str) (ANSICHAR*) nux::NCharacterConversion ((const UNICHAR*)str) #define ANSICHAR_TO_TCHAR(str) (UNICHAR*) nux::NCharacterConversion ((const ANSICHAR*)str) #define TCHAR_TO_ANSICHAR(str) (ANSICHAR*) nux::NCharacterConversion ((const TCHAR*)str) #define TCHAR_TO_UNICHAR(str) (UNICHAR*) nux::NCharacterConversion ((const TCHAR*)str) #define NUX_WIN32_LINE_TERMINATOR TEXT("\r\n") #define NUX_UNIX_LINE_TERMINATOR TEXT("\n") #define NUX_MACOSX_LINE_TERMINATOR TEXT("\n") #if defined(NUX_OS_WINDOWS) #define NUX_LINE_TERMINATOR NUX_WIN32_LINE_TERMINATOR #elif defined(NUX_OS_LINUX) || defined(NUX_OS_MACOSX) #define NUX_LINE_TERMINATOR NUX_UNIX_LINE_TERMINATOR #endif #if defined(NUX_OS_WINDOWS) #define NUX_PATH_SEPARATOR_STRING NUX_BACKSLASH_STRING #define NUX_PATH_SEPARATOR_CHAR NUX_BACKSLASH_CHAR #elif defined(NUX_OS_LINUX) || defined(NUX_OS_MACOSX) #define NUX_PATH_SEPARATOR_STRING NUX_SLASH_STRING #define NUX_PATH_SEPARATOR_CHAR NUX_SLASH_CHAR #endif #define NUX_BACKSLASH_CHAR TEXT('\\') #define NUX_BACKSLASH_STRING TEXT("\\") #define NUX_SLASH_CHAR TEXT('/') #define NUX_SLASH_STRING TEXT("/") #define NUX_MAX_FILEPATH_SIZE 1024 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if (defined _WIN32) && (defined WIN32_SECURE) #define WCSNCPY_S(strDest, numberOfElements, strSource, count) wcsncpy_s (strDest, numberOfElements, strSource, count) #define STRNCPY_S(strDest, numberOfElements, strSource, count) _tcsncpy_s(strDest, numberOfElements, strSource, count) #define STRCPY_S(strDest, numberOfElements, strSource) _tcscpy_s(strDest, numberOfElements, strSource) #define STRCAT_S(strDest, numberOfElements, strSource) _tcscat_s(strDest, numberOfElements, strSource) #define VSNPRINTF_S(strDest, numberOfElements, Count, format, VA_Arg_List) vsnprintf_s(strDest, numberOfElements, Count, format, VA_Arg_List) #define VSNTPRINTF_S(strDest, numberOfElements, Count, format, VA_Arg_List) _vsntprintf_s(strDest, numberOfElements, Count, format, VA_Arg_List) #define SPRINTF_S(strDest, numberOfElements, format, ...) _stprintf_s(strDest, numberOfElements, format, ##__VA_ARGS__) #define SNPRINTF_S(strDest, numberOfElements, Count, format, ...) _sntprintf_s(strDest, numberOfElements, Count, format, ##__VA_ARGS__) #define STRDATE_S(strDest, numberOfElements) _tstrdate_s(strDest, numberOfElements) #define STRTIME_S(strDest, numberOfElements) _tstrtime_s(strDest, numberOfElements) #define FOPEN_S(file, filename, mode) _tfopen_s(file, filename, mode) #define STRLEN_S(str, numberOfElements) _tcsnlen(str, numberOfElements) #define SPLITPATH_S(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) _tsplitpath_s(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) #define MAKEPATH_S(path, numberOfElements, Drive, Dir, Filename, Extension) _tmakepath_s(path, numberOfElements, Drive, Dir, Filename, Extension) #define SSCANF_S(buffer, format, ...) _stscanf_s(buffer, format, ##__VA_ARGS__) #define SNSCANF_S(input, length, format, ...) _sntscanf_s(input, length, format, ##__VA_ARGS__) #else #define WCSNCPY_S(strDest, numberOfElements, strSource, count) wcsncpy (strDest, strSource, count) // The weird numElmt - numElmt in the expansion is to stop the compiler from complaining about unused params. #define STRNCPY_S(strDest, numElmt, strSource, count) _tcsncpy(strDest, strSource, count + numElmt - numElmt) #define STRCPY_S(strDest, numberOfElements, strSource) _tcscpy(strDest, strSource) #define STRCAT_S(strDest, numberOfElements, strSource) _tcscat(strDest, strSource) #define VSNPRINTF_S(strDest, numberOfElements, Count, format, VA_Arg_List) vsnprintf(strDest, Count, format, VA_Arg_List) #define VSNTPRINTF_S(strDest, numberOfElements, Count, format, VA_Arg_List) _vsntprintf(strDest, Count, format, VA_Arg_List) #define SPRINTF_S(strDest, numberOfElements, format, ...) _stprintf(strDest, format, ##__VA_ARGS__) #define SNPRINTF_S(strDest, numberOfElements, Count, format, ...) _sntprintf(strDest, Count, format, ##__VA_ARGS__) #define STRDATE_S(strDest, numberOfElements) _tstrdate(strDest) #define STRTIME_S(strDest, numberOfElements) _tstrtime(strDest) #define FOPEN_S(file, filename, mode) (file = _tfopen(filename, mode)) #define STRLEN_S(str, numberOfElements) _tcslen(str) #define SPLITPATH_S(path, Drive, DriveNumElements, Dir, DirNumElements, Filename, FileNumElements, Extension, ExtNumElements) _tsplitpath(path, Drive, Dir, Filename, Extension) #define MAKEPATH_S(path, numberOfElements, Drive, Dir, Filename, Extension) _makepath(path, Drive, Dir, Filename, Extension) #define SSCANF_S(buffer, format, ...) _stscanf(buffer, format, ##__VA_ARGS__) #define SNSCANF_S(input, length, format, ...) _sntscanf(input, length, format, ##__VA_ARGS__) #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern const bool GNoDialog; // Set to true to disable the popping of dialog box. The message will go to the log. #ifdef NUX_VISUAL_STUDIO_2003 //Visual Studio C++ 2003 doesn't support it, but there is a workaround: #pragma warning(disable: 4002) // Warning: too many actual parameters for macro 'ident' #pragma warning(disable: 4003) // Warning: not enough actual parameters for macro 'ident' template inline const T &VARG ( const T &t ) { return t; } inline const TCHAR *VARG( ) { return TEXT (""); } #endif #ifdef _UNICODE #define tstring std::wstring #define tostream std::wostream #define tistream std::wistream #define tiostream std::wiostream #define tofstream std::wofstream #define tfstream std::wfstream #else #define tstring std::string #define tostream std::ostream #define tistream std::istream #define tiostream std::iostream #define tofstream std::ofstream #define tfstream std::fstream #endif // // UTF-16 is the primary encoding mechanism used by Microsoft Windows 2000, Windows 2000 Server, Windows XP and Windows 2003 Server. // // Unicode Byte Order Mark (BOM) // enum {UNICODE_UTF32_BE = 0x0000FEFF }; // enum {UNICODE_UTF32_LE = 0xFFFE0000 }; // enum {UNICODE_UTF16_BE = 0xFEFF }; // enum {UNICODE_UTF16_LE = 0xFFFE }; // enum {UNICODE_UTF8 = 0xEFBBBF }; const BYTE NUX_UTF32_BE[] = {0x04 /*size*/, 0x00, 0x00, 0xFE, 0xFF }; const BYTE NUX_UTF32_LE[] = {0x04 /*size*/, 0xFF, 0xFE, 0x00, 0x00 }; const BYTE NUX_UTF16_BE[] = {0x02 /*size*/, 0xFE, 0xFF }; const BYTE NUX_UTF16_LE[] = {0x02 /*size*/, 0xFF, 0xFE }; const BYTE NUX_UTF8[] = {0x03 /*size*/, 0xEF, 0xBB, 0xBF }; // enum {UNICODE_BOM = 0xfeff }; class LogOutputDevice; class NFileManager; #define GNullDevice NUX_GLOBAL_OBJECT_INSTANCE(nux::NullOutput) #define GLogDevice NUX_GLOBAL_OBJECT_INSTANCE(nux::LogOutputRedirector) #if (defined NUX_OS_WINDOWS) #define GFileManager NUX_GLOBAL_OBJECT_INSTANCE(nux::NFileManagerWindows) #elif (defined NUX_OS_LINUX) #define GFileManager NUX_GLOBAL_OBJECT_INSTANCE(nux::NFileManagerGNU) #endif // Define architecture specific asm statements for hardware breakpoint #if defined(NUX_GNUC_COMPILER) #if (defined __i386__) || (defined __x86_64__) #define ARCH_HARDWARE_BREAK std::abort () #elif defined (__arm__) || (defined __ppc__) #define ARCH_HARDWARE_BREAK do {} while(0) #else #define ARCH_HARDWARE_BREAK do {} while(0) #endif #endif // Breaks into the debugger. Forces a GPF in non-debug builds. #if (defined NUX_DEBUG) && (defined NUX_MICROSOFT_COMPILER) #define nuxIsDebuggerPresent() IsDebuggerPresent() #define inlDebugBreak() ( IsDebuggerPresent() ? (DebugBreak(),1) : 1 ) #elif (defined _WIN32) #define nuxIsDebuggerPresent() IsDebuggerPresent() #define inlDebugBreak() std::abort () #elif (defined NUX_DEBUG) && (defined NUX_GNUCPP_COMPILER) #define nuxIsDebuggerPresent() 1 #define inlDebugBreak() ARCH_HARDWARE_BREAK #else #define nuxIsDebuggerPresent() 0 #define inlDebugBreak() #endif #if defined(NUX_MICROSOFT_COMPILER) #define NUX_HARDWARE_BREAK {__debugbreak();} #define NUX_BREAK_ASM_INT3 {__debugbreak();} #elif defined(NUX_GNUC_COMPILER) #define NUX_HARDWARE_BREAK ARCH_HARDWARE_BREAK #define NUX_BREAK_ASM_INT3 ARCH_HARDWARE_BREAK #else #define NUX_HARDWARE_BREAK #define NUX_BREAK_ASM_INT3 #endif ////////////////////////////////////////////////////////////////////////// // Variadic function prototypes. ////////////////////////////////////////////////////////////////////////// #define VARARG_EXTRA(A) A, #define VARARG_NONE #define VARARG_PURE =0 #if _MSC_VER static inline DWORD VAType (DWORD dw) { return dw; } static inline unsigned char VAType (unsigned char b) { return b; } static inline unsigned int VAType (unsigned int ui) { return ui; } static inline int VAType (int i) { return i; } static inline unsigned long long VAType (unsigned long long qw) { return qw; // possible conflict with size_t when compiling in 64 bits } static inline long long VAType (long long sqw) { return sqw; } static inline double VAType (double d) { return d; } static inline TCHAR VAType (TCHAR c) { return c; } static inline ANSICHAR *VAType (ANSICHAR *s) { return s; } static inline UNICHAR *VAType (UNICHAR *s) { return s; } template T *VAType (T *p) { return p; } template const T *VAType (const T *p) { return p; } // Declaration of prototypes with lots of arguments // If(the function return nothing) // { // Return = {} // StaticFuncRet = void // } // else // { // Return = return // StaticFuncRet = type0 // FuncRet = type1 // } // // If this is a pure virtual function then PURE is equal to: ==0 // ExtraParamDecl is declaration for additional parameters: VARARG_EXTRA(TCHAR* Dest) VARARG_EXTRA(INT Size) VARARG_EXTRA(INT Count) // ExtraParam is the parameters presented in ExtraParamDecl: VARARG_EXTRA(Dest) VARARG_EXTRA(Size) VARARG_EXTRA(Count) #define VARARG_DECL( FuncRet, StaticFuncRet, Return, FuncName, Pure, FmtType, ExtraParamDecl, ExtraParam ) \ FuncRet FuncName##__VA(ExtraParamDecl FmtType Fmt, ... ) Pure; \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt) {Return FuncName##__VA(ExtraParam (Fmt));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1) {T1 v1=VAType(V1);Return FuncName##__VA(ExtraParam (Fmt),(v1));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2) {T1 v1=VAType(V1);T2 v2=VAType(V2);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14,T15 V15) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);T15 v15=VAType(V15);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14),(v15));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14,T15 V15,T16 V16) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);T15 v15=VAType(V15);T16 v16=VAType(V16);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14),(v15),(v16));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14,T15 V15,T16 V16,T17 V17) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);T15 v15=VAType(V15);T16 v16=VAType(V16);T17 v17=VAType(V17);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14),(v15),(v16),(v17));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14,T15 V15,T16 V16,T17 V17,T18 V18) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);T15 v15=VAType(V15);T16 v16=VAType(V16);T17 v17=VAType(V17);T18 v18=VAType(V18);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14),(v15),(v16),(v17),(v18));} \ template \ StaticFuncRet FuncName(ExtraParamDecl FmtType Fmt,T1 V1,T2 V2,T3 V3,T4 V4,T5 V5,T6 V6,T7 V7,T8 V8,T9 V9,T10 V10,T11 V11,T12 V12,T13 V13,T14 V14,T15 V15,T16 V16,T17 V17,T18 V18,T19 V19) {T1 v1=VAType(V1);T2 v2=VAType(V2);T3 v3=VAType(V3);T4 v4=VAType(V4);T5 v5=VAType(V5);T6 v6=VAType(V6);T7 v7=VAType(V7);T8 v8=VAType(V8);T9 v9=VAType(V9);T10 v10=VAType(V10);T11 v11=VAType(V11);T12 v12=VAType(V12);T13 v13=VAType(V13);T14 v14=VAType(V14);T15 v15=VAType(V15);T16 v16=VAType(V16);T17 v17=VAType(V17);T18 v18=VAType(V18);T19 v19=VAType(V19);Return FuncName##__VA(ExtraParam (Fmt),(v1),(v2),(v3),(v4),(v5),(v6),(v7),(v8),(v9),(v10),(v11),(v12),(v13),(v14),(v15),(v16),(v17),(v18),(v19));} #define VARARG_BODY( FuncRet, FuncName, FmtType, ExtraParamDecl ) \ FuncRet FuncName##__VA( ExtraParamDecl FmtType Fmt, ... ) #else // !_MSC_VER #define VARARG_DECL( FuncRet, StaticFuncRet, Return, FuncName, Pure, FmtType, ExtraParamDecl, ExtraParam ) \ FuncRet FuncName( ExtraParamDecl FmtType Fmt, ... ) Pure #define VARARG_BODY( FuncRet, FuncName, FmtType, ExtraParamDecl ) \ FuncRet FuncName( ExtraParamDecl FmtType Fmt, ... ) #endif // _MSC_VER //! Log an outpout message to console or visual studio output. To be used while the log redirector is not initialized. void PrintOutputDebugString (const TCHAR *Format, ...); //! Log an assertion failure to registered output. void LogOutputAssertMessage (const ANSICHAR *File, int Line, const TCHAR *Format = TEXT (""), ...); //! Log an error message to registered output. void LogOutputErrorMessage (const ANSICHAR *File, int Line, const TCHAR *Format = TEXT (""), ...); //! Log and output message with a severity factor to registered output. Print colored output in XTerm. void LogOutputDebugMessage (const TCHAR *Format, ...); //! Log and output message with a severity factor to registered output. Print colored output in XTerm. void LogOutputSeverityMessage (int Severity, const TCHAR *Format/*=TEXT("")*/, ...); // Returns true is the output redirector is ready bool OutputRedirectorReady(); enum EFileWrite { FILEWRITE_NOFAIL = 0x01, FILEWRITE_NOREPLACEEXISTING = 0x02, FILEWRITE_EVENIFREADONLY = 0x04, FILEWRITE_UNBUFFERED = 0x08, FILEWRITE_APPEND = 0x10, FILEWRITE_ALLOWREAD = 0x20, }; enum ECopyResult { COPY_OK = 0x00, COPY_MISCFAIL = 0x01, COPY_READFAIL = 0x02, COPY_WRITEFAIL = 0x03, COPY_CANCELED = 0x06, }; enum NUX_STATUS { NUX_OK, NUX_ERROR, NUX_FILENOTFOUND, NUX_COPYFILE_ERROR, NUX_DELETEFILE_ERROR, }; } #include "Macros.h" #include "Memory.h" #include "Character/NUni.h" #if defined(NUX_OS_WINDOWS) #include "Character/NUnicode.h" #elif defined(NUX_OS_LINUX) #include "Character/NUnicode.h" #endif #include "Template.h" #include "NumberConversion.h" #include "TextString.h" #if defined(NUX_OS_WINDOWS) #include "ThreadWin.h" #elif defined(NUX_OS_LINUX) #include "ThreadGNU.h" #endif /*#include "Memory/NMemoryAllocatorInterface.h" #include "Memory/NDefaultMemoryAllocator.h" #include "Memory/NMemoryHook.h" #include "Memory/NMemoryAllocator.h" */ #include "NUniqueIndex.h" //#include "GlobalInitializer.h" #ifdef NUX_OS_WINDOWS #include "Win32Dialogs/NWin32MessageBox.h" #endif #include "Character/NTChar.h" #include "TimeFunctions.h" #include "Platform.h" #include "FileManager/NSerializer.h" #include "Process.h" #include "OutputDevice.h" #include "FileManager/NFileManagerGeneric.h" #ifdef NUX_OS_WINDOWS #include "FileManager/NFileManagerWindows.h" #elif defined NUX_OS_LINUX #include "FileManager/NFileManagerGNU.h" #endif #include "FileIO.h" #include "ObjectType.h" #include "FileName.h" #include "Color.h" #include "Colors.h" #include "Object.h" #ifdef NUX_OS_WINDOWS #include "Win32Dialogs/NWin32CustomDialog.h" #include "Win32Dialogs/NWin32Clipboard.h" #endif #include "GlobalInitializer.h" #endif // NUXCORE_H nux-4.0.8+16.04.20160209/NuxCore/Memory.cpp0000644000015600001650000000465212656236757020272 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { unsigned int Memcmp ( const void *Buf1, const void *Buf2, unsigned int Count ) { return std::memcmp ( Buf1, Buf2, Count ); } bool MemIsZero ( const void *V, size_t Count ) { unsigned char *B = (unsigned char *) V; while ( Count-- > 0 ) if ( *B++ != 0 ) return false; return true; } void *Memmove ( void *Dest, const void *Src, size_t Count ) { if (Count == 0) return Dest; return std::memmove ( Dest, Src, Count ); } void Memset ( void *Dest, int C, size_t Count ) { std::memset ( Dest, C, Count ); } void Memzero ( void *Dest, size_t Count ) { std::memset ( Dest, 0, Count ); } void Memcpy ( void *Dest, const void *Src, size_t Count ) { std::memcpy ( Dest, Src, Count ); } void Memswap ( void *Ptr1, void *Ptr2, size_t Size ) { void *Temp = malloc (Size); Memcpy ( Temp, Ptr1, Size ); Memcpy ( Ptr1, Ptr2, Size ); Memcpy ( Ptr2, Temp, Size ); free (Temp); } bool IsMemoryAligned (void *data, unsigned int alignment) { nuxAssertMsg ( (alignment & (alignment - 1) ) == 0, TEXT ("[IsMemAligned] Argument for memory alignment test is not a power of two: %d"), alignment); return ( ( (uintptr_t) &data) & (alignment - 1) ) == 0; } void *Malloc (size_t Count, unsigned int /* Alignment */) { return std::malloc ( Count ); } void *Realloc (void *Original, size_t Count, unsigned int /* Alignment */) { void *mem = std::realloc ( Original, Count ); if (mem == 0) { nuxCriticalMsg (TEXT ("[Realloc] realloc failed.")); return NULL; } return mem; } } nux-4.0.8+16.04.20160209/NuxCore/SystemGNU.cpp0000644000015600001650000000000012656236757020637 0ustar pbuserpbgroup00000000000000nux-4.0.8+16.04.20160209/NuxCore/Rect.h0000644000015600001650000000612412656236757017360 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef RECT_H #define RECT_H #include "Point.h" #include "Size.h" namespace nux { class Rect { public: Rect(); Rect(int x_, int y_, int width_, int height_); Rect(const Rect &); Rect(Rect&&); Rect &operator = (Rect r); bool operator == (const Rect &p) const; bool operator != (const Rect &p) const; //! Return true is the area of this rectangle is Null. /*! Return true is the area of this rectangle is Null. */ bool IsNull() const; bool IsInside(const Point &p) const; bool IsInside(const Point2D &p) const; bool IsIntersecting(const Rect&) const; Rect Intersect(const Rect &) const; // expand the width by factor_x and the height by factor_y void Expand (int factor_x, int factor_y); int GetWidth() const { return width; } int GetHeight() const { return height; } //! Returns a Point at the center of the Rectangle. Point GetCenter() const { return Point (x + width / 2, y + height / 2); } //! Returns a Point at the center of the Rectangle. Point GetPosition() const { return Point (x, y); } void SetWidth (int w) { width = w; } void SetHeight (int h) { height = h; } void SetX (int px) { x = px; } void SetY (int py) { y = py; } void Set (int px, int py, int w, int h); void SetPosition (int px, int py); void SetSize (int px, int py); void OffsetSize (int dw, int dh) { width += dw; height += dh; if (width < 0) width = 0; if (height < 0) height = 0; } void OffsetPosition (int dx, int dy) { x += dx; y += dy; } bool IsPointInside (int dx, int dy) const; Rect GetExpand (int dx, int dy) const; friend void swap(Rect& lhs, Rect& rhs) { using std::swap; swap(lhs.x, rhs.x); swap(lhs.y, rhs.y); swap(lhs.width, rhs.width); swap(lhs.height, rhs.height); } int x, y; int width, height; }; Rect operator+(Rect const& lhs, Rect const& rhs); Rect operator-(Rect const& lhs, Rect const& rhs); Rect operator*(Rect const& lhs, float scalar); std::ostream& operator<<(std::ostream &os, Rect const&); typedef Rect Geometry; } #endif // RECT_H nux-4.0.8+16.04.20160209/NuxCore/Platform.h0000644000015600001650000000456712656236757020260 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NPLATFORM_H #define NPLATFORM_H namespace nux { void NuxCoreInitialize (const TCHAR *CommandLine); void inlPreInitializePlatform(); void inlInitializePlatform(); void inlPostInitializePlatform(); void inlExitSystem(); void inlInitRandomGenerator(); /*----------------------------------------------------------------------------- Command line. -----------------------------------------------------------------------------*/ //! Get the program command line /*! Get the program command line. @return The program command line. */ std::string GetCmdLine(); //! Get startup directory. /*! Get startup directory. @return The computer name. */ std::string GetProgramDirectory(); //! Get computer name. /*! Get computer name. @return The computer name. */ std::string GetComputerName(); //! Get user name. /*! Get the user name. @return The user name. */ std::string GetUserName(); //! Return the logs directory /*! Returns the directory where logs files are output. This cannot be in a .ini files as the system may start logging before the .ini files are read. @return The logs directory */ std::string GetLogDirectory(); class NGlobalData { NUX_DECLARE_GLOBAL_OBJECT (NGlobalData, GlobalSingletonInitializer); public: void Initialize (const TCHAR *CommandLine); unsigned int m_RandomSeed; std::string m_UserName; std::string m_ComputerName; std::string m_ProgramName; std::string m_ProgramDirectory; std::string m_CommandLine; }; } #endif // NPLATFORM_H nux-4.0.8+16.04.20160209/NuxCore/Property.h0000644000015600001650000001601212656236757020304 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #ifndef NUXCORE_PROPERTY_H #define NUXCORE_PROPERTY_H #include "PropertyTraits.h" #include #include #include #include /** * Much of this property work is based on the work by Lois Goldthwaite, * SC22/WG21/N1615=04-0055 - C++ Properties -- a Library Solution * * The basic ideas were extended to add update notifications, and * serialisation and introspection. */ namespace nux { template class PropertyChangedSignal { public: PropertyChangedSignal(); sigc::signal changed; void DisableNotifications(); void EnableNotifications(); void EmitChanged(VALUE_TYPE const& new_value); private: bool notify_; }; /** * A read/write property that stores the value type. * * The default setter emits the changed event if and only if the value * changes. A custom setter can be provided by passing in a setter function * using sigc::mem_fun or sigc::ptr_fun. */ template class Property : public PropertyChangedSignal { public: typedef VALUE_TYPE ValueType; typedef PropertyChangedSignal SignalBase; typedef std::function SetterFunction; Property(); explicit Property(VALUE_TYPE const& initial); Property(VALUE_TYPE const& initial, SetterFunction setter_function); VALUE_TYPE operator=(VALUE_TYPE const& value); operator VALUE_TYPE() const; // function call access VALUE_TYPE operator()() const; VALUE_TYPE operator()(VALUE_TYPE const& value); // get and set access VALUE_TYPE Get() const; VALUE_TYPE Set(VALUE_TYPE const& value); void SetSetterFunction(SetterFunction setter_function); private: // Properties themselves are not copyable. Property(Property const&); Property& operator=(Property const&); bool DefaultSetter(VALUE_TYPE& target, VALUE_TYPE const& value); private: VALUE_TYPE value_; SetterFunction setter_function_; }; // We could easily add a Write Only Property if and when we need one. /** * A read only property that uses a function to get the value. * * The default constructor creates a read only property that always returns * the default constructed VALUE_TYPE. */ template class ROProperty : public PropertyChangedSignal { public: typedef VALUE_TYPE ValueType; typedef std::function GetterFunction; ROProperty(); explicit ROProperty(GetterFunction getter_function); operator VALUE_TYPE() const; VALUE_TYPE operator()() const; VALUE_TYPE Get() const; void SetGetterFunction(GetterFunction getter_function); private: // ROProperties themselves are not copyable. ROProperty(ROProperty const&); ROProperty& operator=(ROProperty const&); VALUE_TYPE DefaultGetter() const; private: GetterFunction getter_function_; }; /** * A read/write property that uses a functions to get and set the value. * * The value type is not stored in the propery, but maintained by the setter * and getter functions. * * A changed signal is emitted if the setter function specifies that the value * has changed. * * The default setter does nothing and emits no signal, and the default getter * returns a default constructed VALUE_TYPE. The default getter and setter * should be overridden through either the constructor args or through the * SetGetterFunction / SetSetterFunction. */ template class RWProperty : public PropertyChangedSignal { public: typedef VALUE_TYPE ValueType; typedef PropertyChangedSignal SignalBase; typedef std::function SetterFunction; typedef std::function GetterFunction; RWProperty(); RWProperty(GetterFunction getter_function, SetterFunction setter_function); VALUE_TYPE operator=(VALUE_TYPE const& value); operator VALUE_TYPE() const; // function call access VALUE_TYPE operator()() const; VALUE_TYPE operator()(VALUE_TYPE const& value); // get and set access VALUE_TYPE Get() const; VALUE_TYPE Set(VALUE_TYPE const& value); void SetGetterFunction(GetterFunction getter_function); void SetSetterFunction(SetterFunction setter_function); private: // RWProperties themselves are not copyable. RWProperty(RWProperty const&); RWProperty& operator=(RWProperty const&); VALUE_TYPE DefaultGetter() const; bool DefaultSetter(VALUE_TYPE const& value); private: GetterFunction getter_function_; SetterFunction setter_function_; }; class PropertyBase { public: virtual ~PropertyBase() {} virtual bool SetValue(std::string const& serialized_form) = 0; virtual std::string GetSerializedValue() const = 0; }; class Introspectable { public: Introspectable(); // Needs to have a container of properties /// If the property was not able to be set with the value, the method /// returns false. bool SetProperty(std::string const& name, const char* value); template bool SetProperty(std::string const& name, T const& value); template T GetProperty(std::string const& name, T* foo = 0); void AddProperty(std::string const& name, PropertyBase* property); private: // Introspectable objects are not copyable. Introspectable(Introspectable const&); Introspectable& operator=(Introspectable const&); private: typedef std::map PropertyContainer; PropertyContainer properties_; }; template class SerializableProperty : public Property, public PropertyBase { public: typedef Property Base; typedef typename type::PropertyTrait TraitType; typedef typename TraitType::ValueType ValueType; SerializableProperty(Introspectable* owner, std::string const& name); SerializableProperty(Introspectable* owner, std::string const& name, VALUE_TYPE const& initial); virtual bool SetValue(std::string const& serialized_form); virtual std::string GetSerializedValue() const; // Operator assignment is not inherited nicely, so redeclare it here. VALUE_TYPE operator=(VALUE_TYPE const& value); private: std::string name_; }; } #include "Property-inl.h" #include "PropertyOperators.h" #endif nux-4.0.8+16.04.20160209/NuxCore/FilePath.h0000644000015600001650000000321012656236757020150 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ ////////////////////////////////////////////////////////////////////////// // This file comes from NVidia SDK 9.5 data_path.h // ////////////////////////////////////////////////////////////////////////// #ifndef FILEPATH_H #define FILEPATH_H #ifdef _WIN32 # pragma warning(disable:4786) // symbol size limitation ... STL #endif #include #include #include #include #include namespace nux { class FilePath { public: FilePath(); ~FilePath(); void AddSearchPath (const std::string &searchpath); void AddSearchPath (const std::vector& searchpath); std::string GetPathToFile (const TCHAR *filename) const; std::string GetFile (const TCHAR *filename) const; private: std::vector m_SearchPath; }; } #endif // FILEPATH_H nux-4.0.8+16.04.20160209/NuxCore/TextString.cpp0000644000015600001650000000452212656236757021131 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" namespace nux { // // Copy a string with length checking. //warning: Behavior differs from strncpy; last character is zeroed. // TCHAR *Strncpy (TCHAR *Dest, size_t Size, const TCHAR *Src, size_t MaxLen) { STRNCPY_S (Dest, Size, Src, MaxLen); Dest[MaxLen] = 0; return Dest; } // Search a string inside a string. Return a pointer to the beginning of the searched string if it is found. Else, return NULL; // The shearched string must be preceded by a non alpha numeric character in Str. const TCHAR *Strfind (const TCHAR *Str, const TCHAR *Find) { nuxAssert (Find != NULL); nuxAssert (Str != NULL); if (Find == NULL || Str == NULL) { return NULL; } bool AlphaNum = 0; TCHAR First = ( (*Find < TEXT ('a') ) || (*Find > TEXT ('z') ) ) ? (*Find) : (*Find + TEXT ('A') - TEXT ('a') ); size_t Len = StringLength (Find++) - 1; TCHAR chr = *Str++; while (chr) { if ( (chr >= TEXT ('a') ) && (chr <= TEXT ('z') ) ) { chr += TEXT ('A') - TEXT ('a'); } if (!AlphaNum && (chr == First) && !TCharStringNICompare (Str, Find, Len) ) { return Str - 1; } AlphaNum = ( (chr >= TEXT ('A') ) && (chr <= TEXT ('Z') ) ) || ( (chr >= TEXT ('0') ) && (chr <= TEXT ('9') ) ); chr = *Str++; } return NULL; } VARARG_BODY (int, Snprintf, const TCHAR *, VARARG_EXTRA (TCHAR *Dest) VARARG_EXTRA (int Size) VARARG_EXTRA (int Count) ) { int Result = -1; GET_VARARGS_RESULT (Dest, Size, Count, Fmt, Result); return Result; } } nux-4.0.8+16.04.20160209/NuxCore/Rect.cpp0000644000015600001650000001100112656236757017701 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Point.h" #include "Size.h" #include "Rect.h" namespace nux { Rect::Rect() : x(0) , y(0) , width(0) , height(0) {} Rect::Rect(int x_, int y_, int width_, int height_) : x(x_) , y(y_) , width(std::max(0, width_)) , height(std::max(0, height_)) {} Rect::Rect(const Rect &r) : x(r.x) , y(r.y) , width(r.width) , height(r.height) {} Rect::Rect(Rect &&r) : Rect() { swap(*this, r); } Rect &Rect::operator = (Rect r) { swap(*this, r); return *this; } bool Rect::operator == (const Rect &r) const { if ( (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height) ) { return true; } return false; } bool Rect::operator != (const Rect &r) const { if ( (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height) ) { return false; } return true; } bool Rect::IsNull() const { return ((width == 0) || (height == 0)); } void Rect::Set (int px, int py, int w, int h) { x = px; y = py; width = w; height = h; } void Rect::SetPosition (int px, int py) { x = px; y = py; } void Rect::SetSize (int w, int h) { width = w; height = h; } bool Rect::IsInside (const Point &p) const { return ( (x <= p.x) && (x + width > p.x) && (y <= p.y) && (y + height > p.y) ); } bool Rect::IsInside(const Point2D &p) const { return ( (x <= (int)p.x) && (x + width > (int)p.x) && (y <= (int)p.y) && (y + height > (int)p.y) ); } bool Rect::IsPointInside (int x_, int y_) const { return ( (x <= x_) && (x + width > x_) && (y <= y_) && (y + height > y_) ); } bool Rect::IsIntersecting(const Rect &r) const { return ! ((r.x > x + width) || (r.x + r.width < x) || (r.y > y + height) || (r.y + r.height < y)); } Rect Rect::Intersect (const Rect &r) const { // Get the corner points. if (IsIntersecting(r)) { const Point &ul1 = Point (x, y); const Point &ul2 = Point (r.x, r.y); int xx = std::max(ul1.x, ul2.x); int yy = std::max(ul1.y, ul2.y); int ww = std::min(ul1.x + width, ul2.x + r.width) - xx; int hh = std::min(ul1.y + height, ul2.y + r.height) - yy; return Rect (xx, yy, ww, hh); } else { // No intersection return Rect (); } } // expand the width by factor_x and the height by factor_y void Rect::Expand (int dx, int dy) { if (!IsNull() ) { x -= dx; y -= dy; width += 2 * dx; height += 2 * dy; } } // expand the width by factor_x and the height by factor_y Rect Rect::GetExpand (int dx, int dy) const { Rect r = Rect (x - dx, y - dy, width + 2 * dx, height + 2 * dy); if (r.IsNull() ) { return Rect (0, 0, 0, 0); } return r; } Rect operator+(Rect const& lhs, Rect const& rhs) { return Rect(lhs.x + rhs.x, lhs.y + rhs.y, lhs.width + rhs.width, lhs.height + rhs.height); } Rect operator-(Rect const& lhs, Rect const& rhs) { return Rect(lhs.x - rhs.x, lhs.y - rhs.y, lhs.width - rhs.width, lhs.height - rhs.height); } Rect operator*(Rect const& lhs, float scalar) { return Rect(lhs.x * scalar, lhs.y * scalar, lhs.width * scalar, lhs.height * scalar); } std::ostream& operator<<(std::ostream &os, Rect const& rect) { return os << "Rect, x: " << rect.x << " y: " << rect.y << " width: " << rect.width << " height: " << rect.height; } } nux-4.0.8+16.04.20160209/NuxCore/Template.cpp0000644000015600001650000000153412656236757020571 0ustar pbuserpbgroup00000000000000/* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #include "NuxCore.h" #include "Template.h" namespace nux { } nux-4.0.8+16.04.20160209/NuxCore/RollingFileAppender.cpp0000644000015600001650000001700112656236757022677 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #include "NuxCore.h" #include "RollingFileAppender.h" #include #include #include #include #include #include #include "AsyncFileWriter.h" namespace nux { namespace logging { namespace { std::string backup_path(std::string const& path, unsigned number) { if (number == 0) return path; std::ostringstream sout; sout << path << "." << number; return sout.str(); } // Change the implementation to string buf // Have a GFile representing the file on disk // g_file_append gives a GFileOutputStream (subclass of GOutputStream) // g_output_stream_write_async (only have one in progress at a time) // g_output_stream_flush_async (probably don't want a pending async) // keep our own count of the written bytes. // Tests don't have a g_object main loop, so we have another way... // while (g_main_context_pending(g_main_context_get_thread_default())) { // g_main_context_iteration(g_main_context_get_thread_default()); // } class RollingFileStreamBuffer : public std::stringbuf { public: RollingFileStreamBuffer(std::string const& filename, unsigned number_of_backup_files, unsigned long long max_log_size, sigc::signal& files_rolled); ~RollingFileStreamBuffer(); protected: virtual int sync(); private: void AsyncWriterClosed(); void RotateFiles(); #if defined(NUX_OS_WINDOWS) && (!defined(NUX_VISUAL_STUDIO_2010)) std::tr1::shared_ptr writer_; #else std::shared_ptr writer_; #endif GFile* log_file_; std::string filename_; unsigned number_of_backup_files_; unsigned long long max_log_size_; unsigned long long bytes_written_; sigc::connection writer_closed_; sigc::signal& files_rolled_; }; RollingFileStreamBuffer::RollingFileStreamBuffer(std::string const& filename, unsigned number_of_backup_files, unsigned long long max_log_size, sigc::signal& files_rolled) : filename_(filename) , number_of_backup_files_(number_of_backup_files) , max_log_size_(max_log_size) , bytes_written_(0) , files_rolled_(files_rolled) { // Make sure that the filename starts with a '/' for a full path. if (filename.empty() || filename[0] != '/') { std::string error_msg = "\"" + filename + "\" is not a full path"; throw std::runtime_error(error_msg.c_str()); } // Looks to see if our filename exists. if (g_file_test(filename.c_str(), G_FILE_TEST_EXISTS)) { // The filename needs to be a regular file. if (!g_file_test(filename.c_str(), G_FILE_TEST_IS_REGULAR)) { std::string error_msg = filename + " is not a regular file"; throw std::runtime_error(error_msg.c_str()); } // Rotate the files. RotateFiles(); } else { GFile* log_file = g_file_new_for_path(filename.c_str()); GFile* log_dir = g_file_get_parent(log_file); if (log_dir) { g_file_make_directory_with_parents(log_dir, NULL, NULL); g_object_unref(log_dir); g_object_unref(log_file); } else { g_object_unref(log_file); std::string error_msg = "Can't get parent for " + filename; throw std::runtime_error(error_msg.c_str()); } } // Now open the filename. writer_.reset(new AsyncFileWriter(filename)); log_file_ = g_file_new_for_path(filename_.c_str()); } RollingFileStreamBuffer::~RollingFileStreamBuffer() { // We don't want notification when the writer closes now. if (writer_closed_.connected()) writer_closed_.disconnect(); g_object_unref(log_file_); } void RollingFileStreamBuffer::RotateFiles() { // If we aren't keeping backups, no rolling needed. if (number_of_backup_files_ == 0) return; unsigned backup = number_of_backup_files_; std::string last_log(backup_path(filename_, backup)); if (g_file_test(last_log.c_str(), G_FILE_TEST_EXISTS)) { // Attempt to remove it. GFile* logfile = g_file_new_for_path(last_log.c_str()); g_file_delete(logfile, NULL, NULL); g_object_unref(logfile); } // Move the previous files out. while (backup > 0) { std::string prev_log(backup_path(filename_, --backup)); if (g_file_test(prev_log.c_str(), G_FILE_TEST_EXISTS)) { GFile* dest = g_file_new_for_path(last_log.c_str()); GFile* src = g_file_new_for_path(prev_log.c_str()); // We don't really care if there are errors for now. g_file_move(src, dest, G_FILE_COPY_NONE, NULL, NULL, NULL, NULL); g_object_unref(src); g_object_unref(dest); } last_log = prev_log; } } void RollingFileStreamBuffer::AsyncWriterClosed() { // Rotate the files and open a new file writer. RotateFiles(); writer_.reset(new AsyncFileWriter(filename_)); bytes_written_ = 0; // We emit the files_rolled_ here and not in the RotateFiles method as the // RotateFiles is called from the constructor, which has a reference to the // files_rolled signal from the parent stream. If this is emitted due // rotating the files in the contructor, we get a seg fault due to trying to // use the signal before it is constructed. files_rolled_.emit(); } int RollingFileStreamBuffer::sync() { // If the async file writer is in the middle of closing, there is nothing we can do. if (writer_->IsClosing()) return 0; std::string message = str(); // reset the stream str(""); std::size_t message_size = message.size(); if (message_size > 0) { bytes_written_ += message_size; writer_->Write(message); if (bytes_written_ > max_log_size_) { // Close the writer and once it is closed, rotate the files and open a new file. writer_closed_ = writer_->closed.connect( sigc::mem_fun(this, &RollingFileStreamBuffer::AsyncWriterClosed)); writer_->Close(); } } return 0; // success } } // anon namespace RollingFileAppender::RollingFileAppender(std::string const& filename) : std::ostream(new RollingFileStreamBuffer(filename, 5, 1e7, files_rolled)) { } RollingFileAppender::RollingFileAppender(std::string const& filename, unsigned number_of_backup_files, unsigned long long max_log_size) : std::ostream(new RollingFileStreamBuffer(filename, number_of_backup_files, max_log_size, files_rolled)) { } RollingFileAppender::~RollingFileAppender() { rdbuf()->pubsync(); std::streambuf* buff = rdbuf(0); delete buff; } } // namespace logging } // namespace nux nux-4.0.8+16.04.20160209/NuxCore/ObjectType.h0000644000015600001650000000755412656236757020543 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2010 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Jay Taoko * */ #ifndef NOBJECTTYPE_H #define NOBJECTTYPE_H #include namespace nux { // TODO: write a nice is_instance (and is_derived_instance) //template //bool is_instance(T const& struct NObjectType { const char* name; NObjectType* super; static const NObjectType Null_Type; NObjectType() : name("Null_Type") , super(NULL) { } NObjectType(const char* type_name, NObjectType* super_type) : name(type_name) , super(super_type) { } //! Return true is this has the same type as the argument type. inline bool operator == (const NObjectType &Type) const { return IsObjectType (Type); } //! Return true is this has is of a different type than the argument type. inline bool operator != (const NObjectType &Type) const { return !IsObjectType (Type); } //! Return true is this has the same type as the argument type. inline bool IsObjectType (const NObjectType &Type) const { return this == &Type; } //! Return true if this has the same type as the argument type or is derived from it. inline bool IsDerivedFromType (const NObjectType &Type) const { const NObjectType *current_type = this; while (current_type) { if (current_type == &Type) return true; current_type = current_type->super; } return false; } inline unsigned int SubClassDepth() const { const NObjectType* current_type = this; unsigned int depth = 0; while (current_type) { depth++; current_type = current_type->super; } return depth; } }; #define NUX_DECLARE_OBJECT_TYPE(TypeName, SuperType) \ public: \ typedef SuperType SuperObject; \ static ::nux::NObjectType StaticObjectType; \ public: \ virtual ::nux::NObjectType& Type() const { return StaticObjectType; } \ ::nux::NObjectType& GetTypeInfo() const { return StaticObjectType; } #define NUX_IMPLEMENT_OBJECT_TYPE(TypeName) \ ::nux::NObjectType TypeName::StaticObjectType(#TypeName, &TypeName::SuperObject::StaticObjectType); #define NUX_DECLARE_ROOT_OBJECT_TYPE(TypeName) \ public: \ typedef ::nux::NObjectType SuperObject; \ static ::nux::NObjectType StaticObjectType; \ public: \ virtual ::nux::NObjectType& Type() const { return StaticObjectType; } \ ::nux::NObjectType& GetTypeInfo() const { return StaticObjectType; } #define NUX_IMPLEMENT_ROOT_OBJECT_TYPE(TypeName) \ ::nux::NObjectType TypeName::StaticObjectType(#TypeName, 0); } // namespace nux #endif // NOBJECTTYPE_H nux-4.0.8+16.04.20160209/NuxCore/Animation.cpp0000644000015600001650000000352012656236757020732 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2012 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #include "NuxCore.h" #include "Animation.h" #include "AnimationController.h" namespace na = nux::animation; na::Animation::Animation() : state_(Stopped) {} na::Animation::~Animation() { if (state_ != Stopped) { if (Controller* controller = Controller::Instance()) controller->RemoveAnimation(this); } } void na::Animation::Pause() { if (state_ == Running) { state_ = Paused; } } void na::Animation::Resume() { if (state_ == Paused) { state_ = Running; } } void na::Animation::Start() { if (state_ == Stopped) { state_ = Running; Restart(); Controller* controller = Controller::Instance(); if (controller) controller->AddAnimation(this); } } void na::Animation::Stop() { if (state_ != Stopped) { state_ = Stopped; finished.emit(); Controller* controller = Controller::Instance(); if (controller) controller->RemoveAnimation(this); } } na::Animation::State na::Animation::CurrentState() const { return state_; } nux-4.0.8+16.04.20160209/NuxCore/PropertyOperators.h0000644000015600001650000001644312656236757022213 0ustar pbuserpbgroup00000000000000// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*- /* * Copyright 2011 Inalogic® Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License, as * published by the Free Software Foundation; either version 2.1 or 3.0 * of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR * PURPOSE. See the applicable version of the GNU Lesser General Public * License for more details. * * You should have received a copy of both the GNU Lesser General Public * License along with this program. If not, see * * Authored by: Tim Penhey * */ #if defined(NUX_OS_WINDOWS) #pragma warning(disable : 4519) // error C4519: default template arguments are only allowed on a class template #endif #ifndef NUXCORE_PROPERTY_OPERATORS_H #define NUXCORE_PROPERTY_OPERATORS_H namespace nux { /** * This is a very boring file. * * It adds boolean operators for properties. The challenge has been making * operators that work for properties and only properties. Since we don't * want to add explicit methods for each type of property we have, we have the * default template argument VT which gets the ValueType from the Property * definition. Since things like std::_list_iterator doesn't have a * ValueType typedef, these functions are discarded from the possible choices, * but since the Property templates do, they are valid, and get chosen. * * However as much as I'd like to have more generic operators for !=, <=, > * and >=, we can't really without making these functions choosable for types * that we don't want, so we have three functions defined for each operator. */ // operator == template